-
Notifications
You must be signed in to change notification settings - Fork 0
/
ForceMetric.py
1955 lines (1679 loc) · 62.2 KB
/
ForceMetric.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""
Module for AFM data analysis aquired with Asylum Research software. This
means reading .ibw data and bring them in an appropriate python format for AFM
analysis
"""
import os
import glob
import itertools
import numpy as np
import multiprocessing
import h5py as h5
import pandas as pd
from tqdm import tqdm
from igor import binarywave as ibw
from scipy import optimize as opt
from scipy.stats import chisquare
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter1d, gaussian_filter, map_coordinates
from scipy.special import ellipe, ellipk
from scipy.signal import argrelextrema
from joblib import Parallel, delayed
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.cbook import get_sample_data
#from matplotlib._png import read_png
from ContactPointDetermination import GradientCP, MultiplyCP, RovCP, FitCP, GofCP
# from mpl_toolkits.mplot3d import axes3d
# from mayavi import mlab
# from mayavi.api import Engine
# from mayavi.sources.api import ArraySource
# from mayavi.filters.api import WarpScalar, PolyDataNormals
# from mayavi.modules.api import Surface
def GetLine(data, p0, p1, num=1000):
"""
Extracts an interpolated line from a dataset.
Parameters
----------
data: ndarray of dim 2
image data from which the profile should be extracted
p0: tuple
x, y coordinates where the line should start
p1: tuple
x, y coordinates where the line should end
num: int
number of points for interpolation
Returns
-------
line: ndarray of dim 1
extracted line
"""
x0, y0 = p0
x1, y1 = p1
x, y = np.linspace(x0, x1, num), np.linspace(y0, y1, num)
line = map_coordinates(data, np.vstack((x, y)))
return line
def DynamicCoefficients(A1, phi1, omega, A1_norm, phi1_norm, k, Q):
"""
Returns elastic and viscose parameter k_s and c_s, respectivly.
Parameters
----------
A1_norm : list with free and damped amplitude [m]
phi1_norm : list with free and damped phase [rad]
k : spring constant of cantilever [N/m]
Returns
-------
k_s : ndarray or float
The spring constant for dynamic indentation experiments
c_s : ndarray or float
The viscosity for dynamic indentation experiments
"""
A1_free = A1_norm[0]
A1_near = A1_norm[1]
phi1_near = phi1_norm[1]
C1 = A1_free * k/Q * np.sqrt(1-1. / (2*Q)**2)
k_s = C1 * (np.cos(phi1)/A1 - np.cos(phi1_near)/A1_near)
c_s = C1 / omega * (np.sin(phi1)/A1 - np.sin(phi1_near)/A1_near)
return k_s, c_s
def IndentationFit(p, delta, gamma=2):
"""
General Form for elastic indentation models, e.g. Hertz contact
Parameters
----------
p : list of floats
This is related to the stiffness by a geometric factor which depends on
the contact model.
delta : ndarray of floats
These are the indentation values to fit
gamma : geometric exponent according to the contact model, e.g. for Hertz
gamma = 1.5
Returns
-------
res : ndarray of floats
"""
return p[0] * delta**gamma + p[1]
def errfunc(p, data, delta, gamma=2):
"""
Error function for fitting Young's modulus of force-distance data using
scipy.optimize.leastsq minimization.
Parameters
----------
p : list of floats
This is related to the stiffness by a geometric factor which depends on
the contact model.
delta : ndarray of floats
These are the indentation values to fit
gamma : geometric exponent according to the contact model, e.g. for Hertz
gamma = 1.5
data : ndarray of floats
force data to fit. This is usually from an indentation experiment but
it can also be simulated
Returns
-------
IndentationFit(p, delta, gamma)-data : ndarray of floats
difference between fit and data
"""
return IndentationFit(p, delta, gamma)-data
def NeoHookeanBead(delta, p, R=10e-9):
"""
This function represents the relationship between the force and the
indentation delta for a neo-hookean material in contact with a spherical
bead. If adhesion should be considered an additional term has to be
considered.
Parameters
----------
p : list of floats
This is related to the stiffness by a geometric factor which depends on
the contact model.
delta : ndarray of floats
These are the indentation values to fit
R : radius of the bead [m]
Returns
-------
force : ndarray with floats
The response force for a neo-Hookean material.
"""
C = p * np.pi * np.sqrt(R)
num = delta**(5./2) - 3 * np.sqrt(R) * delta**2 + 3 * R * delta**(3./2)
den = delta - 2 * np.sqrt(R * delta) + R
force = C * num / den
return force
def eccentricity(alpha, beta):
"""
Calculates eccentricity of an ellipse
Parameters
----------
alpha : float
Half-opening angle of the cone [rad]
beta : float
Inclination angle of the section plane [rad]
Returns
-------
ecc : float
Eccentricity of a cone section.
"""
ecc = np.sqrt(1-(np.cos(beta)*(1-np.tan(beta)**2*np.tan(alpha)**2))**2)
return ecc
def SlopeCorrection(alpha, beta):
"""
Calculates correction for conical indentations on an inclined half-space
Parameters
----------
alpha : float
Half-opening angle of the cone [rad]
beta : float
Inclination angle of the section plane [rad]
Returns
-------
f : float
correction parameter for mesured force F, i.e.
:math:`F_{new} = F \cdot f`.
"""
e = eccentricity(alpha, beta)
c1 = 1./(1 - (np.tan(beta)**2*np.tan(alpha)**2))
f = c1/np.cos(beta)/ellipk(e)*(np.pi - c1*ellipe(e)/np.cos(beta))
return f
def RealSlopeCorrection(alpha, beta):
"""
Calculates correction for conical indentations on an inclined half-space
Parameters
----------
alpha : float
Half-opening angle of the cone [rad]
beta : float
Inclination angle of the section plane [rad]
Returns
-------
f : float
correction parameter for mesured force F, i.e.
:math:`F_{new} = F \cdot f`.
"""
e = eccentricity(alpha, beta)
f = np.pi**2/4/ellipk(e)/ellipe(e)
return f
def MaximumSlope(height, dimx=20):
"""Caculates maximum slope of a surface"""
dx = dimx/height.shape[0]
gx, gy = np.gradient(height, dx)
m = gx + gy
theta = np.arcsin(m/(np.sqrt(2+m**2)))
return theta
def div0(a, b):
"""returns zeros for division by zero"""
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a, b)
c[~ np.isfinite(c)] = 0 # -inf inf NaN
return c
def ROV(x, I, smooth=True):
"""
Determines a significant point using the ratio of variances of 1D data with
an interval I.
Parameters
----------
x : 1d array
data with noisy data to determin characteristic point
I : int
Interval length for which the ratio of variances should be determined.
Returns
-------
r : float
ratio of variances
"""
if smooth:
x = gaussian_filter1d(x, 0.1*I)
N = len(x)
low = np.array([x[i:i+I].std() for i in range(I, N-I)])
high = np.array([x[i-I:i].std() for i in range(I, N-I)])
r = div0(low, high)
return r
def process1(point, trace=False, method='fiv',
model='s', fmin=None, fmax=None):
"""Subprocess for Young's map multiprocessing"""
try:
fc = ForceCurve(point)
fc.trace = trace
fc.correct(4, method=method)
return fc
except:
return np.nan
def process3(point, trace=False):
"""Subprocess for Young's map multiprocessing"""
if point:
fc = ForceCurve(point)
fc.trace = trace
fc.correct(2)
mini = fc.indentation.Trace().min()
maxi = fc.indentation.Trace().max()
newind = np.linspace(mini-maxi,
0,
2000)
f = interp1d(fc.indentation.Trace()-maxi, fc.force.Trace(), 'linear')
newf = f(newind)
return [newind, newf]
else:
return np.nan
def nearestPoint(x, x0):
"""
Determines index of x which is closest to x0. This is necessary if the
value one is interested is not in the array.
Parameters
----------
x : ndarray with floats
x0 : float
value of interest
Returns
-------
idx : int
largest index for value which is closest to x0
"""
check = np.abs(x-x0)
idx = int(np.amax(np.where(check == np.amin(check))))
return idx
def IdentifyScanMode(path):
wave = Wave(path)
if 'ForceDisplay0' in wave.keys():
mode = 'ForceCurve'
else:
mode = 'Imaging'
return mode
class Header(dict):
"""
Class which accociates the header as a dictionary of itself
"""
def __init__(self, header):
for key in header:
self[key] = header[key]
def AddHeaderEntries(self, entries):
for key in entries:
self[key] = entries[key]
def SearchHeader(self, string):
Hits = []
for key, value in self.items():
if string in key:
Hits.append(key)
if len(Hits):
return Hits
else:
print("%s is not a parameter in this header" % string)
class Wave(Header):
"""
Class for igor binary wave files for better access to data than with the
igor module. If igor file was converted to HDF5 this can be read as well
and will be in the same structure accessible for easy programming.
The header information is saved as a dictionary of self, i.e. if you want
to read the spring constant you can do this by self["SpringConstant"]
Parameters
----------
path : str
path of wave file
basefile: hdf5 type
required if data is part from an hdf5 file
Note
----
Only ibw and hdf5 is supported.
"""
def __init__(self, path, basefile=None, verbose=0):
self.path = path
ext = path.split('.')[-1]
N = len(path.split('.'))
if basefile:
f = basefile
if ext == 'ibw':
file_type = 'ibw'
elif ext == 'hdf5':
file_type = 'hdf5'
if N == 1:
file_type = 'hdf5_subgroup'
if file_type == 'ibw':
f = ibw.load(path)
self.wave = f.get('wave')
H = self.wave.get('note').splitlines()
header = dict()
for h in H:
try:
dec = h.decode("utf-8").split(":")
header[dec[0]] = float(dec[1])
except:
try:
dec = h.decode("utf-8").split(":")
header[dec[0]] = dec[1]
except:
if verbose:
print("Can't decode ", h)
self.data = 1*np.rollaxis(self.wave.get('wData'), -1)
label = self.wave.get('labels')
tmp = []
while not tmp:
tmp = label.pop(0)
tmp.pop(0)
self.labels = [t.decode("utf-8") for t in tmp]
elif file_type == 'hdf5':
f = h5.File(path, 'a')
data = f['data']
header = dict(data.attrs)
self.labels = list(np.array(list(data.get('label')), dtype='U20'))
if 'scan' in data:
self.data = np.rollaxis(np.array(data.get('scan')), -1, 0)
elif 'curve' in data:
self.data = np.rollaxis(np.array(data.get('curve')), -1, 0)
elif file_type == 'hdf5_subgroup':
data = f[path]
header = dict(data.attrs)
if 'scan' in path:
lbl_path = path.replace('scan', 'label')
elif 'curve' in path:
lbl_path = path.replace('curve', 'label')
self.data = np.rollaxis(np.array(data), -1, 0)
self.labels = list(np.array(list(f[lbl_path]), dtype='U20'))
Header.__init__(self, header)
def getParam(self, key):
"""
This function gives a parameter from the header. This is only for
readibility since the parameters can be accessed from the dictionary
"""
return self.header[key]
def getData(self, key):
"""
Returns data from the wave. self.labels shows available data.
"""
idx = self.labels.index(key)
return self.data[idx]
def WriteHDF5(self, path):
h5file = h5.File(path, 'a', driver='core')
data_grp = h5file.create_group('data')
for key in self.keys():
data_grp.attrs[key] = self[key]
if IdentifyScanMode(self.path) == 'Imaging':
dat = np.rollaxis(self.data, 0, 3)
stype = 'scan'
elif IdentifyScanMode(self.path) == 'ForceCurve':
dat = np.rollaxis(self.data, 0, 2)
stype = 'curve'
data_grp.create_dataset(stype, data=dat)
data_grp.create_dataset('label', data=np.array(self.labels,
dtype='S20'))
h5file.flush()
h5file.close()
class FDIndices(object):
"""
Class for indices of force-distance data,
i.e. approach, retract, dwelltime
Parameters
----------
indices : list of int
the indices are 3 for only aproach and retract and 4 for a dwell time.
The first index represents the first value of the approach curve
(usually 0), the last value of the approach curve (is also the first
value of the retract curve or if exist dwell time), and so on.
"""
def __init__(self, indices):
self.indices = indices
self.traceidx = [indices[0], indices[1]]
self.dwell = False
if len(indices) > 3:
self.dwell = True
if self.dwell:
self.retraceidx = [indices[2], indices[3]]
self.dwellidx = [indices[1], indices[2]]
else:
self.retraceidx = [indices[1], indices[2]]
class FDData(FDIndices):
"""
Class to describe qantity-distance data, i.e. the data has an approach part
and a retract part and it could also have a dwell part.
Parameters
----------
data : ndarray of floats
force distance data, such as indentation data, or force data
indices : list of int
indices for trace, retrace, and dwell. see also FDIndices
Examples
--------
>>> from ForceMetric import FDData
>>> import numpy as np
>>> force = np.linspace(0, 2, 1000)**2
"""
def __init__(self, data, indices):
FDIndices.__init__(self, indices)
self.data = data
self.trace = True
def Trace(self):
"""
The approach data of a force-indentation curve
Returns
-------
trace : ndarray of floats
"""
return self.data[self.traceidx[0]:self.traceidx[1]]
def Retrace(self):
"""
The retract data of a force-indentation curve
Returns
-------
retrace : ndarray of floats
"""
return self.data[self.retraceidx[0]:self.retraceidx[1]]
def Dwell(self):
"""
The dwell data of a force-indentation curve
Returns
-------
dwell : ndarray of floats
"""
if self.dwell:
return self.data[self.dwellidx[0]:self.dwellidx[1]]
else:
print("No dwell time")
def Data(self):
"""
The whole data of a force-indentation curve
Returns
-------
data : ndarray of floats
"""
if self.trace:
return self.Trace()
elif self.trace == 'dwell':
return self.Dwell()
else:
return self.Retrace()
class ParameterDict(object):
"""
A parameter dictionary class for Reading and writing information about a
file into a dictionary with the extension .npy
Parameters
----------
path : str
Path from which to load a parameter dictionary/header or where to save
it if it does not exist.
Note
----
At the moment only .npy and .ibw can be added.
"""
def __init__(self, path):
ext = path.split('.')[-1]
if ext == "ibw":
directory = os.path.dirname(path)
basename = os.path.basename(path).split('.')[0]
parapath = directory + os.sep + 'Parameters.npy'
elif ext == "npy":
parapath = path
self.path = parapath
check = os.path.isfile(self.path)
if check:
print("Load existing File")
self.parameters = np.load(self.path).item()
else:
print("New instance created")
self.parameters = dict()
# self.parameters = para[basename]
def AddFileInfo(self, fnb, dictionary):
""" This adds another dictionary to the parameter list. In the case fnb
already exists, the dictionary gets changed"""
self.parameters[fnb] = dictionary
def Write(self, path=None):
if path:
self.path = path
np.save(self.path, self.parameters, allow_pickle=True)
class AFMScan(Wave):
"""
A class for 2D AFM Scans including all parameters saved by the
Asylum Research Software. It also has a display function and a plane
subtraction. If wanted any observable can be projected on the height.
Parameters
----------
path : str
path of AFM file
Note
----
Only ibw and hdf5 is supported.
"""
def __init__(self, path, basefile=None):
Wave.__init__(self, path, basefile)
self.scan = [self['FastScanSize'],
self['SlowScanSize']]
self.dimensions = self.data.shape[1:]
def PlaneSubtraction(self, data, direction='xy', xdim=20e-6, ydim=20e-6):
"""
Does plane fit to AFM data and subtracts it in either x, y or x-y
direction
Parameters
----------
data: 2d array
data array which should be plane subtracted. It is also possible to
choose a label from the Wave class to perform this subtraction.
direction: str
the direction in which the plane fit should be performed, i.e. x,
y, or xy.
"""
if data in self.labels:
img = self.getData(data)
else:
img = 1*data
dx, dy = img.shape
print(img.shape)
print(dx, dy)
x = np.linspace(0, xdim, dx)
y = np.linspace(0, ydim, dy)
DX, DY = np.meshgrid(y, x)
px = np.array([np.polyfit(y, img[i], 1)
for i in np.arange(dx)]).mean(axis=0)
py = np.array([np.polyfit(x, img[:,i], 1)
for i in np.arange(dy)]).mean(axis=0)
print("calculate planes")
xplane = np.polyval(px, DX)
yplane = np.polyval(py, DY)
if direction == 'x':
print('x plane subtraction')
correction = xplane
elif direction == 'y':
print('y plane subtraction')
correction = yplane
else:
print('x-y plane subtraction')
correction = xplane + yplane
corrected = data - correction
corrected -= corrected.min()
return corrected
def Display(self, data,
title='Height',
zlabel=r'$z$ in um',
cmap = cm.gray,
save=False):
"""Displays AFM Data in an appropriate way"""
if data in self.labels:
img = self.getData(data)
else:
img = 1*data
area = [0, self.scan[0]*1e6, 0, self.scan[1]*1e6]
vmin = np.nanmedian(img) - 2 * np.nanstd(img)
vmin = max(0, vmin)
vmax = np.nanmedian(img) + 2 * np.nanstd(img)
fig, ax = plt.subplots(1, 1)
cax = ax.imshow(img,
extent=area,
origin='lower',
interpolation='nearest',
vmin=vmin, vmax=vmax,
cmap=cmap)
ax.set_xlabel(r'$x$ in um')
ax.set_ylabel(r'$x$ in um')
ax.set_title(title)
plt.colorbar(cax, ax=ax, label=zlabel)
if save:
plt.savefig(save)
def ProjectOnHeight(self, data,
cmap='gnuplot',
zlabel='E in MPa',
theta=50, phi=70,
sub_plane=True,
trace=True,
save=False):
"""Projects any quantity (data) with a color coding onto the height
profile of the AFM scan"""
area = [0, self.scan[0]*1e6, 0, self.scan[1]*1e6]
print ("Initialize projection map")
if trace:
z = self.getData("HeightTrace")
else:
z = self.getData("HeightRetrace")
print ("Initialize plot")
z -= z.min()
z *= 1e6
if sub_plane:
z = self.PlaneSubtraction(z)
dimx, dimy = z.shape
x = np.linspace(area[0], area[1], dimx)
y = np.linspace(area[0], area[1], dimy)
X, Y = np.meshgrid(x, y)
Z = 1*z
fig = mlab.figure(figure='Projection on height',
bgcolor=(1,1,1),
fgcolor=(0,0,0),
)
obj = mlab.mesh(X, Y, Z, scalars=data, colormap=cmap, figure=fig)
mlab.scalarbar(title=zlabel)
mlab.orientation_axes()
mlab.outline()
# fig.axes()
if save:
mlab.savefig(save)
else:
mlab.show()
class DynamicViscoelastic(object):
"""
Wrapper for dynamic viscoelastic properties for AFM tapping mode data.
Parameters
----------
amplitude : float
measured cantilever amplitude
phase : float
measured cantilever phase
free_amplitude : float
free cantilever amplitude
free_phase : float
free cantilever phase. This should be about :math:`\pi/2`
near_amplitude : float
cantilever amplitude about 10 nm above the surface for hydrodynamic
correction
near_phase : float
cantilever phase about 10 nm above the surface for hydrodynamic
correction. This should be :math:`< \pi/2`. If this is not the case
you are not in the repulsiv mode
Q : float
cantilever quality factor
k : float
cantiliver spring constant
omega0 : float
resonance/drive frequency of the cantilever :math:`2 \pi f_0 = \omega_0`
"""
def __init__(self, amplitude=False, phase=False,
free_amplitude=1.e-9, free_phase=np.pi/2.,
near_amplitude=1.e-9, near_phase=np.pi/2.,
Q=1., k=1., omega0=1.):
self.amplitude = amplitude
self.free_amplitude = free_amplitude
self.near_amplitude = near_amplitude
self.phase = phase
self.free_phase = free_phase
self.near_phase = near_phase
self.Q = Q
self.k = k
self.omega0 = omega0
def conservative(self):
"""
This gives the conservative part of the dynamic modulus, i.e. it is
related to a spring constant. In fact only for the Kelvin-Voigt model
this is really a spring constant.
Returns
-------
cons : ndarray of floats
conservative part of the dynamic modulus
Note
----
This is not a Young's shear modulus, which need an underlying
indentation model.
see DynamicYoung
"""
Q = self.Q
C1 = self.k * self.free_amplitude / Q * np.sqrt(1 - 1./ 4 / Q**2)
C2 = 1./self.near_amplitude
phi = self.phase
phi_n = self.near_phase
A = self.amplitude
A_n = self.near_amplitude
cons = C1 * (np.cos(phi) / A - C2 * np.cos(phi_n))
cons[cons<0] = np.nan
return cons
def dissipative(self):
"""
This gives the dissipative part of the dynamic modulus, i.e. it is
related to a viscosity. In fact only for the Kelvin-Voigt model
this is really a vicosity.
Returns
-------
diss : ndarray of floats
dissipative part of the dynamic modulus
Note
----
This is not a Young's shear modulus, which need an underlying
indentation model.
see DynamicYoung
"""
Q = self.Q
C1 = self.k * self.free_amplitude / Q * np.sqrt(1 - 1. / 4 / Q**2)
C2 = 1./self.near_amplitude
phi = self.phase
phi_n = self.near_phase
A = self.amplitude
omega0 = self.omega0
diss = C1 * (np.sin(phi) / A - C2 * np.sin(phi_n)) / omega0
diss[diss < 0] = np.nan
return diss
class DynamicYoung(DynamicViscoelastic):
"""
Calculates Dynamic Young's modulus from dynamic viscoelastic data
measurements using known contact models from continuum mechanics.
Hertz and Sneddon Model are given.
Wrapper for dynamic viscoelastic properties for AFM tapping mode data.
Parameters
----------
amplitude : float
measured cantilever amplitude
phase : float
measured cantilever phase
free_amplitude : float
free cantilever amplitude
free_phase : float
free cantilever phase. This should be about :math:`\pi/2`
near_amplitude : float
cantilever amplitude about 10 nm above the surface for hydrodynamic
correction
near_phase : float
cantilever phase about 10 nm above the surface for hydrodynamic
correction. This should be :math:`< \pi/2`. If this is not the case
you are not in the repulsiv mode
Q : float
cantilever quality factor
k : float
cantiliver spring constant
omega0 : float
resonance/drive frequency of the cantilever :math:`2 \pi f_0 = \omega_0`
"""
def __init__(self, amplitude=False, phase=False,
free_amplitude=1.e-9, free_phase=np.pi/2.,
near_amplitude=1.e-9, near_phase=np.pi/2.,
Q=1., k=1., omega0=1., E0=3e7):
DynamicViscoelastic.__init__(self, amplitude=amplitude, phase=phase,
free_amplitude=free_amplitude,
free_phase=free_phase,
near_amplitude=near_amplitude,
near_phase=near_phase, Q=Q, k=k,
omega0=omega0)
self.E0 = E0
def Storage(self, model='Sneddon',
F0=None, alpha=15*np.pi/180, nu=.5, R=10e-9):
"""
Calculates storage modulus from dynamic AFM experiments according to
the theory of Raman et al (2011)
"""
Sneddon = ['Sneddon', 'sneddon', 'S', 's']
Hertz = ['Hertz', 'hertz', 'H', 'h']
if not F0:
F0 = self.F0
if model in Sneddon:
SneddonFactor = np.tan(alpha)*8/np.pi*(1 - nu**2)
E = (self.conservative()/np.sqrt(F0))**2/SneddonFactor
elif model in Hertz:
E = (np.sqrt(0.5 * self.conservative() * (4./(3*F0))**(1./3))**3 /
np.sqrt(R))
return E
def MyStorage(self, model='Sneddon', F0=None, alpha=15*np.pi/180, nu=.5,
R=10e-9, E0=None):
Sneddon = ['Sneddon', 'sneddon', 'S', 's']
Hertz = ['Hertz', 'hertz', 'H', 'h']
if not F0:
F0 = self.F0
if not E0:
E0 = self.E0
if model in Sneddon:
SneddonFactor = np.tan(alpha)*2/np.pi*(1 - nu**2)
E = (self.conservative() * np.sqrt(E0 / F0)
/ (2 * np.sqrt(SneddonFactor)))
elif model in Hertz:
HertzFactor = 3./4 * R / (1 - nu**2)**2
E = (self.conservative() * (E0 / F0)**(1/3.)
/ (2 * np.sqrt(HertzFactor)))
return E
def Loss(self, model='Hertz',
F0=None, alpha=15*np.pi/180, nu=.5, R=10e-9, omega0=1.):
Sneddon = ['Sneddon', 'sneddon', 'S', 's']
Hertz = ['Hertz', 'hertz', 'H', 'h']
omega0 = self.omega0
if not F0:
F0 = self.F0
if model in Sneddon:
SneddonFactor = np.tan(alpha)*8/np.pi*(1 - nu**2)
E = (self.dissipative() * omega0/np.sqrt(F0))**2/SneddonFactor
elif model in Hertz:
E = (np.sqrt(0.5 * self.dissipative() * omega0 *
(4./(3*F0))**(1./3))**3 / np.sqrt(R))
return E
def MyLoss(self, model='Sneddon',
F0=None, alpha=15*np.pi/180, nu=.5, R=10e-9, E0=None,
omega0=1.):
Sneddon = ['Sneddon', 'sneddon', 'S', 's']
Hertz = ['Hertz', 'hertz', 'H', 'h']
omega0 = self.omega0
if not F0:
F0 = self.F0
if not E0:
E0 = self.E0
if model in Sneddon:
SneddonFactor = np.tan(alpha)*2/np.pi*(1 - nu**2)
E = (self.dissipative() * omega0 * np.sqrt(E0 / F0)
/ (2 * np.sqrt(SneddonFactor)))
elif model in Hertz:
HertzFactor = 3./4 * R / (1 - nu**2)**2
E = (self.dissipative() * omega0 * (E0 / F0)**(1/3.)
/ (2 * np.sqrt(HertzFactor)))
return E
def Delta(self, model='Sneddon',
F0=None, alpha=15*np.pi/180, nu=.5, R=10e-9, E0=None):
"""
Calculates indentation depth assuming an indentation behaviour
accourding to Hertz or Sneddon model, with E' beein Youngs' modulus
"""
Sneddon = ['Sneddon', 'sneddon', 'S', 's']
Hertz = ['Hertz', 'hertz', 'H', 'h']
if not E0:
E0 = self.E0