/
ShawCor.py
1906 lines (1114 loc) · 49.5 KB
/
ShawCor.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
from numpy.fft import *
from numpy import *
from numpy.linalg import *
from scipy.signal import *
from spr import *
from scipy.optimize import *
from matplotlib import *
import os, pickle
from Ultrasonic import GetSignal
from scipy.linalg import expm
from Elastodynamics.TMatrix import TMatrix1d
from matplotlib.pyplot import plot, show
def VelocityAttenuation(s,dt,d,c0,fbnd,df=0.1,db=-25):
from numpy import zeros
NFFT = FFTLengthPower2(round(1/(df*2*dt)))
s = s.copy()
s = s-mean(s)
sa = hilbert(s)
i0 = round((2*d/c0)/dt)
ix = abs(sa).argmax()
il,ir = PeakLimits(abs(sa),ix,db=db)
iw = max([ix-il,ir-ix])
iy = abs(sa[ix+i0-iw:ix+i0+iw]).argmax()+ix+i0-iw
w = tukeywin(2*iw,alpha=1.)
# print(shape(w))
# print(shape(s[ix-iw:ix+iw]))
x = w*s[ix-iw:ix+iw]
imx = abs(x).argmax()
y = w*s[iy-iw:iy+iw]
imy = abs(y).argmax()
x = hstack((x[imx::],zeros(NFFT-len(x)),x[0:imx]))
y = hstack((y[imy::],zeros(NFFT-len(y)),y[0:imy]))
f = linspace(0,1/(2*dt),NFFT/2+1)
ff = (f>=fbnd[0])&(f<=fbnd[1])
X = rfft(x)
Y = rfft(y)*exp(-1j*2*pi*f*(iy-ix)*dt)
H = -Y/X
phi = unwrap(angle(H))
H = H[ff]
f = f[ff]
# plot(f,log(abs(H)))
# plot(f,-4*pi*f*d/phi[ff])
# show()
c = -4*pi*f*d/phi[ff]
T = -phi[ff]/(2*pi*f)
A = log(abs(H))
p = polyfit(f,A,1)
x0 = [-p[0]/(2*d),2*d/(dt*(iy-ix))]
C = exp(p[1])
# func = lambda x: 0.5*real(dot(conj(H-exp(-2*d*x[0]*f)*exp(-1j*4*pi*f*d*(1/x[1] - (2/pi)*x[0]*log(f/f[0])))).transpose(),H-exp(-2*d*x[0]*f)*exp(-1j*4*pi*f*d*(1/x[1] - (2/pi)*x[0]*log(f/f[0])))))
func = lambda x: 0.5*real(dot(conj(H/C-exp(-2*d*x[0]*f)*exp(-1j*4*pi*f*d/x[1])).transpose(),H/C-exp(-2*d*x[0]*f)*exp(-1j*4*pi*f*d/x[1])))
xopt = optimize.fmin(func,x0,full_output=True)
# f = linspace(1e-6,1/(2*dt),len(X))
# Ym = -C*exp(-2*d*xopt[0]*f)*exp(-1j*4*pi*f*d/xopt[1])*exp(1j*4*xopt[0]*d*log(2*pi*f)/pi)*X
# ym = ifft(2*Ym,n=2*len(Ym)-2)
# y = ifft(2*Y,n=2*len(Y)-2)
# Hm = C*exp(-2*d*xopt[0][0]*f)*exp(-1j*4*pi*f*d*(1/xopt[0][1] - (2/pi)*xopt[0][0]*(log(2*pi*f) - log(2*pi*f[0]))))
Hm = C*exp(-2*d*xopt[0][0]*f)*exp(-1j*4*pi*f*d*(1/xopt[0][1]))
return xopt,f,Hm,H,c,x0
def getGroupVelocity(signal, dt, d, moving_average_n = 1, correlateSignal=True):
""" Calculate the speed of sound using time interval between signal peaks.
Correlates the signal with itself, plots it, and allows the user to select the bounds for two peaks.
The function then takes the index of the maximum inside the bounds as the time delay.
If correlate is false, the function simply plots the 'signal'
"""
# from numpy import correlate, argmax
# from matplotlib.pyplot import plot, ginput, figure
# from spr import moving_average
if correlateSignal:
corr = (correlate(abs(signal), abs(signal), 'full'))
corr = moving_average(corr, moving_average_n)
else:
corr = signal
figure()
plot(corr)
print("Please provide bounds")
bounds = ginput(4)
t1 = bounds[0][0] + argmax(corr[bounds[0][0]:bounds[1][0]])
t2 = bounds[2][0] + argmax(corr[bounds[2][0]:bounds[3][0]])
deltaT = abs(t2 - t1)*dt
return (2*d)/(deltaT)
def getGroupAttenuation(signal, dt, d, moving_average_n = 1, correlateSignal=True):
# from numpy import log, correlate
# from matplotlib.pyplot import plot, ginput, figure
# from spr import moving_average
if correlateSignal:
corr = (correlate(abs(signal), abs(signal), 'full'))
corr = moving_average(corr, moving_average_n)
else:
corr = signal
figure()
plot(corr)
print("Please provide bounds")
bounds = ginput(4)
a0 = max(corr[bounds[0][0]:bounds[1][0]])
a1 = max(corr[bounds[2][0]:bounds[3][0]])
return (1/(2*d))*log(a0/a1)
def getSpeedOfSoundAndThickness(signal_s, signal_w, dt, N, mindelay=100, c_w=1.487, c3=0, d3=0):
"""
Return specimen depth and speed of sound through specimen.
If d3=0 and c3=0, the assumption is that the specimen lies flat at some boundary.
If the specimen is not on some boundary, then either c3 or d3 must be specified.
If c3 is specified, it is necessary to select a third peak in the correlation.
"""
# from numpy import correlate, argmax
# from matplotlib.pyplot import plot, ginput, cla
# from spr import Delays
if(type(signal_s) == list):
tc = [getSpeedOfSoundAndThickness(s, signal_w, dt, N, mindelay, c_w, c3, d3) for s in signal_s]
thickness = [x[0] for x in tc]
waveSpeed = [x[1] for x in tc]
return thickness, waveSpeed
ind, A = Delays(2*signal_w+signal_s, N, mindelay=mindelay)
zero_point = len(signal_s) # len of cross-correlation is len of signal * 2
first_max = argmax(correlate(signal_s, signal_w, 'full'))
second_max = first_max + ind[1]
tc = abs(first_max - zero_point)*dt # in microseconds #tw-t1
tb = abs(second_max - zero_point)*dt # tw-t2
thickness = 0
speed = 0
if(c3==0 and d3==0):
thickness = 0.5*c_w*(tc)
speed = 2*thickness / (tc-tb)
if(c3 != 0):
print("Please provide bounds for the third max => tw - tm")
print("Note that this may not necessarily be the third furthest to the right")
corr_max_bounds[2] = ginput(2)
third_max = argmax(corr[corr_max_bounds[2][0][0]:corr_max_bounds[2][1][0]]) + corr_max_bounds[2][0][0]
ta = (third_max - zero_point)*dt # tw-tm
thickness = 0.5 * ( c_w*(tc) - c3*(tb-ta) )
speed = 2*thickness / (tc-tb)
print(c3*(tb-ta))
if(d3!=0):
thickness = 0.5 * ( c_w*(tc) - 2*d3 )
speed = 2*thickness / (tc-tb)
return ( thickness, speed )
def myEquation(H, d, w0, w, a0, n, c0):
# from numpy import exp
# this allocates more memory then it needs to...but it looks beautiful
sum = 0
for i in range(len(H)):
sum = sum + abs( H[i] * exp(1j*Tau(d, w0, a0, n, c0, w[i])) - 1)
return sum
def Tau(d, w0, a0, n, c0, w):
# from numpy import pi
return 2.*d *( 2*a0*(pow(w/w0, n-1) - 1)/(pi*(1-n)*w0) + 1/c0)
#def myEquation2(w, a0, n, c0):
# from numpy import exp
# return exp(1j*Tau2(w, a0, n, c0))
#
#def Tau2(w, a0, n, c0):
# from numpy import pi
# d = 1.12
# w0 = 5.5
# return 2.*d / ((2*a0*(pow(w/w0, n-1) - 1)/pi/(1-n)/w0) + c0)
def minimize(equation, setParameters, start, stop, step):
# from numpy import concatenate, arange
minParams = concatenate((setParameters, start))
minVal = equation(*minParams)
# all possible param values. Probably a bad idea.
params = [arange(start[i], stop[i]+step[i], step[i]) for i in range(0, len(start))]
start = [0 for i in range(0, len(params))]
start[-1] = -1 # trust me
end = [len(params[i]) for i in range(0, len(params))]
current = list(start)
clfi = len(current) - 1 # current for-loop index
counter = 0
while(current!=end):
current[clfi] = current[clfi] + 1
if (current[clfi] == end[clfi]):
clfi = clfi-1
else:
if ( clfi == (len(current) - 1) ): # inner-most for-loop
counter = counter + 1
testParams = concatenate((setParameters, [params[i][current[i]] for i in range(0, len(params))]))
testVal = equation(*testParams)
if (testVal < minVal):
minVal = testVal
minParams = list(testParams)[len(setParameters):]
else:
clfi = clfi + 1
current[clfi] = start[clfi]
return minVal, minParams
def exponential_fct(x, alpha, eta):
# from numpy import ndarray
if type(x) is list or type(x) is ndarray:
return [alpha*pow(x[i], eta) for i in range(0, len(x))]
return alpha*pow(x, eta)
def exponential_fit(xdata, ydata):
from scipy.optimize import curve_fit
return curve_fit(exponential_fct, xdata, ydata)
def getPhaseVelocityAndAttenuation(signal, dt, d2, frng, winsharp=0.1,df=0.1):
# from matplotlib.pyplot import close, plot, ginput, show, waitforbuttonpress
# from numpy import zeros, angle, conjugate, unwrap, pi, linspace, log, ndarray, argmax
# from numpy.fft import rfft
# from spr import tukeywin
# from spr import EchoSeparate
x = signal
if type(x) is list:
CA = [getPhaseVelocityAndAttenuation(signal[i], dt[i], d2[i], frng, winsharp, df) for i in range(0, len(signal))]
C = [c[0] for c in CA]
Alpha = [a[1] for a in CA]
elif type(x) is ndarray:
xe = EchoSeparate(signal, 2)
x=xe[0]
x=x*tukeywin(len(x),winsharp)
# removed negative sign for primer to steel
y=xe[1]
y=y*tukeywin(len(y),winsharp)
TT=1.
X = rfft(x,int(1/(df*dt)))
X_CONJ = conjugate(X)
Y = rfft(y,int(1/(df*dt)))
H = (Y*X_CONJ)/(X*X_CONJ)
w=2*pi*linspace(1.e-15,1./(2*dt),len(X))
phi=unwrap(angle(Y))-unwrap(angle(X))
Tau=dt*(argmax(abs(xe[1]))-argmax(abs(xe[0])))-phi/w
c=2*d2/Tau
H=H[(w>=2*pi*frng[0])&(w<=2*pi*frng[1])]
C=c[(w>=2*pi*frng[0])&(w<=2*pi*frng[1])]
Alpha=-log(abs(H)/TT)/(2*d2)
return C, Alpha
def getSpeedOfSoundInWater(T, S=0, D=0):
# from math import pow
"""
Return speed of sound in water. Accurate for 0<T<35, 0<D<1000.
Ref: Speed of sound in water: A simple equation for realistic parameters. Herman Medwin
:Arguments
- T - Temperature (C)
- S - Salinity (ppt)
- D - Depth (m)
"""
return (1449.2 + 4.6*T - 0.055*pow(T,2) + 0.00029*pow(T,3) + (1.34 - 0.010*T)*(S-35) + 0.016*D) * 0.001 # mm/us
def Save(data,filename,writemode='new'):
# import pickle,os
# data is a dictionary containing waveforms
if os.path.isdir('/Users/jlesage/Dropbox/ShawCor/'):
pth='/Users/jlesage/Dropbox/ShawCor/'
elif os.path.isdir('c:/Users/undel3/Dropbox/ShawCor'):
pth='c:/Users/undel3/Dropbox/ShawCor/'
elif os.path.isdir('c:/Users/utex3/Dropbox/ShawCor'):
pth = 'c:/Users/utex3/Dropbox/ShawCor/'
else:
pth=input('Input Valid Path to Store '+filename+':' )
fl=pth+filename+'.p'
print(fl)
# if (os.path.isfile(fl))&(writemode is 'append'):
if writemode[0] is 'replace':
old=pickle.load(open(fl,'rb'))
pickle.dump(data,open(fl,'wb'))
return old
elif writemode is 'new':
pickle.dump(data,open(fl,'wb'))
def Load(filename):
# import pickle,os
if os.path.isdir('/Users/jlesage/Dropbox/ShawCor/'):
pth='/Users/jlesage/Dropbox/ShawCor/'
elif os.path.isdir('c:/Users/undel3/Dropbox/ShawCor'):
pth='c:/Users/undel3/Dropbox/ShawCor/'
elif os.path.isdir('c:/Users/utex3/Dropbox/ShawCor'):
pth = 'c:/Users/utex3/Dropbox/ShawCor/'
else:
pth=input('Input Valid Path to Store '+filename+':' )
fl=pth+filename+'.p'
s=pickle.load(open(fl,'rb'), encoding='latin1')
return s
def LoadMultiple(files,key,ind):
# import pickle
x=[]
for f in files:
xx=pickle.load(open('/Users/jlesage/Dropbox/ShawCor/PipeSample'+f+'.p','rb'))
xx=xx[ind][key]
for j in range(len(xx)-1):
x.append(xx[j])
return x
def PipeGrid(angular, axial):
#import itertools
wSteps = round((angular[1]-angular[0])/angular[2]) # number of w steps
hSteps = round((axial[1]-axial[0])/axial[2]) # number of h steps
locations = [i for i in range(0, (wSteps+1)*(hSteps+1))]
for i in range(0, wSteps+1):
for j in range(0, hSteps+1):
if i%2==0:
locations[i*(hSteps+1) + j] = (angular[0]+angular[2]*i, axial[0]+axial[2]*j)
else:
locations[i*(hSteps+1) + j] = (angular[0]+angular[2]*i, axial[0]+axial[2]*(hSteps-j))
return locations
#return list(itertools.product(*([range(angular[0],angular[1]+angular[2],angular[2]), range(axial[0],axial[1]+axial[2],axial[2])])))
def GetSignals(nlocs,Keys,Vals,navg=512, sF = 50):
from Ultrasonic import GetSignal
signals = []
data = {}
for i in range(0, nlocs):
t0,dt,x=GetSignal(navg, sF)
signals.append(x)
data = {'TimeOrigin':t0,'SamplingPeriod':dt}
data['signals'] = signals
for i in range(len(Keys)):
data[Keys[i]]=Vals[i]
return data
def ComputeResponse(sc,T,rho,c,alpha,d):
# from numpy import tan,pi,linspace,exp,zeros,hstack,vstack,array
# from scipy.signal import gausspulse
# from numpy.fft import rfft,ifft
dt=1/(10*sc)
t=linspace(0,T,round(T/dt))
X=rfft(gausspulse((t-0.25*T),sc))
Z=[]
for i in range(len(rho)):
Z.append(rho[i]*c[i])
w=2*pi*linspace(0,1/(2*dt),len(X))
R01=(Z[1]-Z[0])/(Z[1]+Z[0])
T01=R01+1
T10=1-R01
R12=(Z[2]-Z[1])/(Z[1]+Z[2])
T12=R12+1
T21=1-R12
Z234=Z[3]*(Z[4]-1j*Z[3]*tan(w*d[3]/c[3]))/(Z[3]-1j*Z[4]*tan(w*d[3]/c[3]))
R234=(Z234-Z[2])/(Z234+Z[2])
T234=R234+1
R45=(Z[5]-Z[4])/(Z[5]+Z[4])
T45=R45+1
Z432=Z[3]*(Z[2]-1j*Z[3]*tan(w*d[3]/c[3]))/(Z[3]-1j*Z[2]*tan(w*d[3]/c[3]))
R432=(Z432-Z[4])/(Z432+Z[4])
T432=R432+1
Y0=exp(-2*d[0]*alpha[0])*exp(-1j*w*2*d[0]/c[0])*R01*X
Y1=exp(-2*d[1]*alpha[1])*exp(-1j*w*2*d[1]/c[1])*T01*T10*R12*Y0/R01
Y2=exp(-2*d[2]*alpha[2])*exp(-1j*w*2*d[2]/c[2])*T12*T21*R234*Y1/R12
Y3=exp(-2*d[4]*alpha[4])*exp(-1j*w*2*d[4]/c[4])*T234*T432*R45*Y2/R234
Y4=exp(-2*d[4]*alpha[4])*exp(-1j*w*2*d[4]/c[4])*R432*R45*Y3
Y5=exp(-2*d[4]*alpha[4])*exp(-1j*w*2*d[4]/c[4])*R432*R45*Y4
y=2*ifft(vstack((Y0,Y1,Y2,Y3,Y4,Y5)),n=2*len(X)-1).transpose()
x=2*ifft(X,n=2*len(X)-1)
t=linspace(0,T,len(x))
return t,x,y
def TransmissionReflection(s,rho,c,L,NpWl=10):
# from numpy import array,identity,pi,linspace,dot,arange,hstack,vstack,zeros,exp,ceil,sqrt
# from scipy.linalg import expm
# from numpy.linalg import solve
# from Elastodynamics.TMatrix import TMatrix1d
Ndiv=ceil(NpWl*L[0]*s[-1]/min(c))
l=L[0]/Ndiv
# print(Ndiv)
# print(l)
Y=linspace(l/2,L[0]-l/2,Ndiv)/L[0]
RT=zeros((4,1))
M0=rho[0]*c[0]**2
M1=rho[1]*c[1]**2
W=2*pi*s
Rho = lambda y: rho[1]*y+rho[0]*(1-y)
C = lambda y: sqrt((M1*y+M0*(1-y))/Rho(y))
P = lambda x,y,z: TMatrix1d(z,Rho(y),C(y),x)
for w in W:
P2=P(L[1],1,w)
P02=identity(2)
P30=P2
for y in Y:
P02=dot(P(l,y,w),P02)
P30=dot(P(l,1-y,w),P30)
P03=dot(P2,P02)
Z0=rho[0]*c[0]
Z3=rho[2]*c[2]
k0=w/c[0]
k3=w/c[2]
h=L[0]+L[1]
RT03=solve(array([[1j*w*Z0*P03[0,1]+P03[0,0],exp(-1j*k3*h)],[1j*w*Z0*P03[1,1]+P03[1,0],-1j*w*Z3*exp(-1j*k3*h)]]),dot(P03,array([[1],[-1j*w*Z0]])))
RT30=solve(array([[1j*w*Z3*P30[0,1]+P30[0,0],exp(-1j*k0*h)],[1j*w*Z3*P30[1,1]+P30[1,0],-1j*w*Z0*exp(-1j*k0*h)]]),dot(P30,array([[1],[-1j*w*Z3]])))
RT=hstack((RT,vstack((RT03,RT30))))
return RT[:,1::]
def DiffusiveFilter(sc,T,rho,c,L,dt=0.001,BW=0.7):
# from numpy import linspace,zeros,vstack,array,dot,conj,pi
# from scipy.signal import gausspulse
# from numpy.fft import rfft,ifft
t=linspace(0,T,round(T/dt))
X=rfft(gausspulse((t-0.25*T),sc,bw=BW))
s=linspace(0.,1/(2*dt),len(X))
s[0]=1e-6
RT=TransmissionReflection(s,rho,c,L)
Y=X*RT
s[0]=0.
Y[:,0] = Y[:,1]
y=ifft(2*Y,axis=1,n=2*Y.shape[1]-1)
x=ifft(2*X,n=2*len(X)-1)
t=linspace(0,T,y.shape[1])
return t,vstack((x,y)),s,vstack((X,Y)),RT
def PrimerH(s,R,T,c,alpha,d):
# from numpy import exp, linspace, pi
s = linspace(s[0],s[1],s[2])
HH = exp(-1j*2*d*2*pi*s/c)*exp(-2*alpha*d*s**2)
H = (R[0]+(T[0]*T[1]-R[0]*R[1])*R[2]*HH)/(1-R[1]*R[2]*HH)
return s,H
def ReflectionSequence(rho,c,alpha,d,dt,eps=1e-6):
# from numpy import exp, hstack, zeros, array
Z = [rho[i]*c[i] for i in range(len(rho))]
R = [(Z[i+1]-Z[i])/(Z[i+1]+Z[i]) for i in range(len(Z)-1)]
T = [4*Z[i]*Z[i+1]/((Z[i]+Z[i+1])**2) for i in range(len(Z)-2)]
Nt = [round(2*d[i]/(dt*c[i])) for i in range(len(d))]
A = T[0]*exp(-2*(d[0]*alpha[0]+d[1]*alpha[1]))
h=hstack((zeros(Nt[0]-1),R[0]*exp(-2*d[0]*alpha[0])))
h=hstack((h,zeros(Nt[1]-1),A*R[1]))
e = 1.
n = 1
BB = 0.
while e>eps:
B = T[1]*R[2]*exp(-2*n*d[2]*alpha[2])*(R[2]**(n-1))*((-R[1])**(n-1))
h=hstack((h,zeros(Nt[2]-1),A*B))
e = abs(B-BB)
BB = B
n+=1
return h
def PulseDistortionFeatures(x,dt):
# from spr import ACorrelate, EchoSeparate,moments
# from numpy import linspace
# from numpy.linalg import norm
# from matplotlib.pylab import plot,show
F=[]
for xx in x:
xe=EchoSeparate(xx,2,db=-20,ws=0.01)
# xc1=ACorrelate(xe[:,0]/norm(xe[:,0]),xe[:,1]/norm(xe[:,1]))
#
xc2=ACorrelate(xe[:,0],xe[:,0])
xc3=ACorrelate(xe[:,0],xe[:,1])
# t=linspace(-dt*len(xc1)/2,dt*len(xc1)/2,len(xc1))
t=linspace(0,dt*len(xc2),len(xc2))
# plot(xe[:,0])
# plot(xe[:,1])
#
# show()
m0=moments(abs(xc2),t)
# print(m0)
m1=moments(abs(xc3),t)
# print(m1)
F.append([m1[0]-m0[0],m1[1]-m0[1],m1[2]-m0[2],m1[3]-m0[3],m1[4]-m0[4]])
return F
def LayerH(x,dt,N=5,Nfreqs=11,asteel=0.01,csteel=5.9):
# from spr import EchoSeparate,PeakLimits
# from numpy import linspace,angle,unwrap,exp,pi,polyfit,hstack,array
# from numpy.fft import rfft
F=[]
failind=[]
for i in range(len(x)):
try:
xe=EchoSeparate(x[i]-mean(x[i]),N,db=-14)
print(len(xe))
except:
failind.append(i)
continue
Xe=rfft(xe,axis=0)
H=Xe[:,1::]/Xe[:,0:-1]
imax=abs(Xe[:,0]).argmax()
il,ir=PeakLimits(abs(Xe[:,0]),imax,db=-6)
s=linspace(0,1/(2*dt),Xe.shape[0])
phi=unwrap(angle(H),axis=0)
phi=phi[il:ir,:]
s=s[il:ir]
p=[polyfit(2*pi*s,phi[:,i],1,full=True) for i in range(phi.shape[1])]
H=abs(H[il:ir+1:int((ir-il)/Nfreqs),:])
T1=-p[0][0][0]
T2=-p[1][0][0]
T3=-p[2][0][0]
T4=-p[3][0][0]
Phi1=p[0][0][1]
Phi2=p[1][0][1]
Phi3=p[2][0][1]
Phi4=p[3][0][1]
R1=1-p[0][1][0]/(len(s)*phi[:,0].var())
R2=1-p[1][1][0]/(len(s)*phi[:,1].var())
R3=1-p[2][1][0]/(len(s)*phi[:,2].var())
R4=1-p[3][1][0]/(len(s)*phi[:,3].var())
H[:,2]=exp(asteel*csteel*T4)*H[:,2]
H[:,3]=exp(asteel*csteel*T4)*H[:,3]
H=H.flatten()
F.append(hstack((array([T1,T2,T4-T3,Phi1,Phi2,Phi3,Phi4]),H)))
return array(F),failind
def AmpDelay(x,dt,N=4,asteel=0.042,csteel=6.):
# from spr import AmplitudeDelayPhase
# from numpy import array,mean,exp
from sklearn.preprocessing import scale
F=[]
for xx in x:
A,T,phi=AmplitudeDelayPhase(xx-mean(xx),N,dt,db=-30)
# F.append([A[0],T[0],phi[0],A[1],T[1],phi[1],A[2],T[2],phi[2],A[3],T[3],phi[3]])
try:
F.append([A[0],T[0],phi[0],A[1],T[1],phi[1],A[2]*exp(asteel*csteel*(T[-1]-T[-2]))*(T[-1]-T[-2]),T[-1]-2*T[-2]+T[-3],phi[2],A[3]*exp(2*asteel*csteel*(T[-1]-T[-2]))*2*(T[-1]-T[-2]),phi[3]])
# F.append([A[1],T[1]-T[0],phi[1],(A[3]/A[2])*exp(asteel*csteel*(T[-1]-T[-2]))*(T[-1]-T[-2]),T[-1]-2*T[-2]+T[-3]])
# F.append([A[1],T[1]-T[0],phi[1]])
except:
pass
return F
def SpectralFeatures(x,dt,srng=[0.5,12.]):
# from spr import EchoSeparate, moments
# from numpy.fft import rfft
# from numpy import linspace,array
# from matplotlib.pyplot import
F=[]
for xx in x:
xe=EchoSeparate(xx,2,db=-30)
# plot(xe)
Xe=rfft(xe,axis=0)
Nf=Xe.shape[0]
Xe=abs(Xe)/Nf
s=linspace(0.,1/(2*dt),Nf)
# print(len(s))
# sind=array([(s>=srng[0])&(s<=srng[1])]).flatten()
# print(sind.shape)
#
# print(len(sind))
# s=s[sind]
#
# Xe=Xe[sind,:]
m0=moments(Xe[:,0],s)
m1=moments(Xe[:,1],s)
FF = [m1[i]-m0[i] for i in range(len(m0))]
F.append(FF)
return F
def CorrelationFeatures(x,Npts):
# from spr import EchoSeparate
# from numpy import correlate,zeros,hstack
# from numpy.linalg import norm
F=[]
for xx in x:
xe=EchoSeparate(xx,1,db=-30)
xe=xe.flatten()
A=norm(xe)
xc=correlate(xx/A,xe/A,'full')
xc=xc[abs(xc).argmax()::]
if len(xc)>=Npts:
xc=xc[0:Npts]/abs(xc[0:Npts]).max()
else:
xc=hstack((xc/abs(xc).max(),zeros(Npts-len(xc))))
F.append(xc)
return F
def AdhesiveFilter(x,dt,d,c,alpha):
from numpy import zeros
from numpy.fft import fft, ifft
im = abs(x).argmax()
x = hstack((x[im::],x[0:im]))
X = rfft(x)
f = linspace(0.0001,1/(2*dt),floor(len(x)/2)+1)
# H = exp(-2*d*alpha*f)*exp(-1j*4*pi*f*d*(1/c-20*alpha/pi**2))*exp(1j*4*f*alpha*d*log(2*pi*f)/pi)
H = exp(-2*d*alpha*f)*exp(-1j*4*pi*f*d*(1/c-20*alpha/pi**2))*exp(1j*4*f*alpha*d*log(2*pi*f)/pi)
Y = X*H
y = ifft(2*Y,n=2*len(Y)-1)
return f,x,y,X,Y
# def PrimerReflectionFit(H,f,d1,d2,c1,c2,alpha1,alpha2):
def PrimerReflectionFit(H,f,d2,c2,alpha2):
# Z0 = 0.943*2.05
# Z1 = 0.94*1.97
# H1 = exp(-2*d1*alpha1*f)*exp(-1j*4*pi*f*d1/c1) #*exp(1j*4*alpha1*d1*log(2*pi*f)/pi)
# H2 = exp(-2*d2*alpha2*f)*exp(-1j*4*pi*f*d2/c2) #*exp(1j*4*alpha2*d2*log(2*pi*f)/pi)
H2 = exp(-2*d2*alpha2*f)
HH2 = exp(1j*4*pi*f*d2/c2)
HHH2 = exp(-1j*4*pi*f*d2/c2)*H2
# H1 = exp(-2*d1*alpha1*f)*exp(-1j*4*pi*f*d1*(1/c1-20*alpha1/pi**2))*exp(1j*4*f*alpha1*d1*log(2*pi*f)/pi)
# H2 = exp(-2*d2*alpha2*f)*exp(-1j*4*pi*f*d2*(1/c2-20*alpha2/pi**2))*exp(1j*4*f*alpha2*d2*log(2*pi*f)/pi)
# H2 = exp(-1j*4*pi*f*d2*(1/c2))
# A = 4*Z0*Z1/(Z1+Z0)**2
# H1 = exp(1j*4*pi*c*f/d)
# H2 = exp(-2*alpha*f*d)
# H3 = exp()
# A = 4*Z0*Z1/((Z1+Z0)*(Z1-Z0))
# B = hstack((H1,H1*H2,H*H2))
# B = hstack((ones((shape(H2))),H2,H*H2))
B = hstack((HH2,H2,H*HHH2))
# B = hstack(())
Bt = conj(B.transpose())
# Bt = B.transpose()
# v = []
# r = []
# fbands = linspace(f[0],f[-1],Nfbands)
# print(fbands)
# print(shape(B))
# print(shape(Bt))
# for i in range(len(fbands)-1):
# ff = (f>=fbands[i])&(f<=fbands[i+1])
# vv = solve(dot(Bt[:,ff],B[ff,:]),dot(Bt[:,ff],Y[ff]))
# E = Y[ff]-dot(B[ff,:],vv)
# rr = 0.5*dot(conj(E.transpose()),E)
# v.append(vv)
# r.append(rr)
# print(c2)
# print(alpha2)
print(d2)
print(cond(dot(Bt,B)))
v = solve(dot(Bt,B),dot(Bt,H))
# v = dot(inv(dot(Bt,B)),dot(Bt,H))
# print(v)
E = H-dot(B,v)
# r = real(0.5*dot(conj(E.transpose()),E)[0][0])
r = 0.5*dot(conj(E.transpose()),E)
# r = 0.5*dot(conj(E.transpose()),E)
r = real(r[0,0])
print(r)
print(v[1]/v[0])
# print(shape(r))
return v,r
def PrimerFitResidual(x,*params):
# v,r = PrimerReflectionFit(params[0],params[1],x[0],x[1],x[2],x[3],x[4],x[5])
v,r = PrimerReflectionFit(params[0],params[1],x[0],x[1],x[2])
# v,r = PrimerReflectionFit(params[],params[3],x[0],x[1],params[0],params[1],x[2],x[3])
return r
def AdhesivePrimerH(f,v,p):
d1 = p[0]
d2 = p[1]
c1 = p[2]
c2 = p[3]
alpha1 = p[4]
alpha2 = p[5]
H1 = exp(-2*d1*alpha1*f)*exp(-1j*4*pi*f*d1/c1)
H2 = exp(-2*d2*alpha2*f)*exp(-1j*4*pi*f*d2/c2)