-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdata.py
978 lines (930 loc) · 38.7 KB
/
data.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
# -*- coding: utf-8 -*-
# distutils: language=c++
"""
Module for handling input data for Bayesian Monte Carlo inversion.
:Copyright:
Author: Lili Feng
Graduate Research Assistant
CIEI, Department of Physics, University of Colorado Boulder
email: [email protected]
"""
import numpy as np
import matplotlib.pyplot as plt
import numba
@numba.jit(numba.float64(numba.float64[:], numba.int64))
def _fast_compute_expect_misfit(stdarr, N):
temp = 0
Ndata = stdarr.size
for i in range(N):
temp_misfit = np.sqrt(((np.random.normal(scale=stdarr))**2/stdarr**2).sum()/Ndata)
temp +=temp_misfit
expected_misfit = temp/N
return expected_misfit
class rf(object):
"""
An object for handling receiver function data and computing misfit
==========================================================================
::: parameters :::
fs - sampling rate
npts - number of data points
rfo - observed receiver function array
to - time array of observed receiver function
stdrfo - uncerntainties in observed receiver function
rfp - predicted receiver function array
tp - time array of predicted receiver function
misfit - misfit value
L - likelihood value
==========================================================================
"""
def __init__(self):
self.npts = 0
self.fs = 0.
return
def readrftxt(self, infname):
"""
Read input txt file of receiver function
==========================================================================
::: input :::
infname - input file name
::: output :::
receiver function data is stored in self
==========================================================================
"""
if self.npts > 0:
print 'receiver function data is already stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
self.npts = inArr.shape[0]
self.to = inArr[:,0]
self.rfo = inArr[:,1]
try:
self.stdrfo = inArr[:,2]
except IndexError:
self.stdrfo = np.ones(self.npts, dtype=np.float64)*0.1
self.fs = 1./(self.to[1] - self.to[0])
return True
def get_rf(self, indata):
"""
get input receiver function data
==========================================================================
::: input :::
indata - input data array (3, N)
::: output :::
receiver function data is stored in self
==========================================================================
"""
if self.npts > 0:
print 'receiver function data is already stored!'
return False
self.npts = indata.shape[1]
self.to = indata[0, :]
self.rfo = indata[1, :]
try:
self.stdrfo = indata[2, :]
except IndexError:
self.stdrfo = np.ones(self.npts, dtype=np.float64)*0.1
self.fs = 1./(self.to[1] - self.to[0])
return True
def writerftxt(self, outfname, tf=10., prerf=True, obsrf=True):
"""
Write receiver function data to a txt file
==========================================================================
::: input :::
outfname - output file name
tf - end time point for trim
::: output :::
a txt file contains predicted and observed receiver function data
==========================================================================
"""
if self.npts == 0:
print 'receiver function data is not stored!'
return False
nout = int(self.fs*tf)+1
nout = min(nout, self.npts)
if prerf:
outArr = np.append(self.tp[:nout], self.rfp[:nout])
else:
outArr = np.array([])
if obsrf:
outArr = np.append(outArr, self.to[:nout])
outArr = np.append(outArr, self.rfo[:nout])
outArr = np.append(outArr, self.stdrfo[:nout])
Ncolumn = 0
if prerf:
Ncolumn += 2
if obsrf:
Ncolumn += 3
outArr = outArr.reshape((Ncolumn, nout))
outArr = outArr.T
if Ncolumn == 5:
header = 'tp rfp to rfo stdrfo'
elif Ncolumn == 2:
header = 'tp rfp'
elif Ncolumn == 3:
header = 'to rfo stdrfo'
np.savetxt(outfname, outArr, fmt='%g', header = header)
return True
# def get_misfit_incompatible(self, rffactor=40.):
# """
# compute misfit when the time array of predicted and observed data is incompatible, quite slow!
# ==============================================================================
# ::: input :::
# rffactor - factor for downweighting the misfit for likelihood computation
# ==============================================================================
# """
# if self.npts == 0:
# self.misfit = 0.
# self.L = 1.
# return 0
# j = 0
# for i in range(self.npts):
# while (self.tp[j] < self.to[i]):
# if self.to[i] == self.tp[j] and self.to[i] <= 10 and self.to[i] >= 0 :
# temp += ( (self.rfo[i] - self.rfp[j])**2 / (self.stdrfo[i]**2) )
# k += 1
# break
# j += 1
# self.misfit = sqrt(temp/k)
# tS = temp/rffactor
# if tS > 50.:
# tS = sqrt(tS*50.)
# self.L = exp(-0.5 * tS)
# return 1
def get_misfit(self, rffactor=40.):
"""
Compute misfit for receiver function
==============================================================================
::: input :::
rffactor - factor for downweighting the misfit for likelihood computation
==============================================================================
"""
if self.npts == 0:
self.misfit = 0.
self.L = 1.
return False
if not np.allclose(self.to, self.tp):
raise ValueError('Incompatable time arrays for predicted and observed rf!')
ind = (self.to<10.)*(self.to>=0.)
temp = ((self.rfo[ind] - self.rfp[ind])**2 / (self.stdrfo[ind]**2)).sum()
k = (self.rfo[ind]).size
self.misfit = np.sqrt(temp/k)
tS = temp/rffactor
if tS > 50.:
tS = np.sqrt(tS*50.)
self.L = np.exp(-0.5 * tS)
return True
def plot(self, showfig=True, prediction=False):
if self.npts == 0:
print 'No data for plotting!'
return
plt.figure()
ax = plt.subplot()
plt.errorbar(self.to, self.rfo, yerr=self.stdrfo, lw=1)
if prediction:
plt.plot(self.tp, self.rfp, 'r-', lw=3)
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
plt.xlabel('time (sec)', fontsize=30)
plt.ylabel('amplitude', fontsize=30)
plt.title('receiver function', fontsize=30)
if showfig:
plt.show()
class disp(object):
"""
An object for handling dispersion data and computing misfit
==========================================================================
::: parameters :::
--------------------------------------------------------------------------
:: phase ::
: isotropic :
npper - number of phase period
pper - phase period array
pvelo - observed phase velocities
stdpvelo- uncertainties for observed phase velocities
pvelp - predicted phase velocities
: anisotropic :
pphio - observed phase velocity fast direction angle
pampo - observed phase velocity azimuthal anisotropic amplitude
stdpphio- uncertainties for fast direction angle
stdpampo- uncertainties for azimuthal anisotropic amplitude
pphip - predicted phase velocity fast direction angle
pampp - predicted phase velocity azimuthal anisotropic amplitude
: others :
isphase - phase dispersion data is stored or not
pmisfit - phase dispersion misfit
pL - phase dispersion likelihood
pS - S function, L = exp(-0.5*S)
--------------------------------------------------------------------------
:: group ::
ngper - number of group period
gper - group period array
gvelo - observed group velocities
stdgvelo- uncertainties for observed group velocities
gvelp - predicted group velocities
: others :
isgroup - group dispersion data is stored or not
gmisfit - group dispersion misfit
gL - group dispersion likelihood
--------------------------------------------------------------------------
:: others ::
misfit - total misfit
L - total likelihood
period - common period array
nper - common number of periods
==========================================================================
"""
def __init__(self):
self.npper = 0
self.ngper = 0
self.nper = 0
self.isphase= False
self.isgroup= False
return
#----------------------------------------------------
# I/O functions
#----------------------------------------------------
def readdisptxt(self, infname, dtype='ph'):
"""
Read input txt file of dispersion curve
==========================================================================
::: input :::
infname - input file name
dtype - data type (phase/group)
::: output :::
dispersion curve is stored
==========================================================================
"""
dtype = dtype.lower()
if dtype == 'ph' or dtype == 'phase':
if self.isphase:
print 'phase velocity data is already stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
self.pper = inArr[:,0]
self.pvelo = inArr[:,1]
self.npper = self.pper.size
try:
self.stdpvelo = inArr[:,2]
except IndexError:
self.stdpvelo = np.ones(self.npper, dtype=np.float64)
self.isphase = True
elif dtype == 'gr' or dtype == 'group':
if self.isgroup:
print 'group velocity data is already stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
self.gper = inArr[:,0]
self.gvelo = inArr[:,1]
self.ngper = self.gper.size
try:
self.stdgvelo = inArr[:,2]
except IndexError:
self.stdgvelo = np.ones(self.ngper, dtype=np.float64)
self.isgroup = True
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def readdisptxt_predict(self, infname, dtype='ph'):
"""
Read input txt file of dispersion curve, include predicted curve
==========================================================================
::: input :::
infname - input file name
dtype - data type (phase/group)
::: output :::
dispersion curve is stored
==========================================================================
"""
dtype = dtype.lower()
if dtype == 'ph' or dtype == 'phase':
if self.isphase:
print 'phase velocity data is already stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
self.pper = inArr[:,0]
self.pvelp = inArr[:,1]
self.pvelo = inArr[:,2]
self.npper = self.pper.size
self.stdpvelo = inArr[:,3]
self.isphase = True
elif dtype == 'gr' or dtype == 'group':
if self.isgroup:
print 'group velocity data is already stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
self.gper = inArr[:,0]
self.gvelp = inArr[:,1]
self.gvelo = inArr[:,2]
self.ngper = self.gper.size
self.stdgvelo = inArr[:,3]
self.isgroup = True
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def get_disp(self, indata, dtype='ph'):
"""
get dispersion curve data from a input numpy array
==========================================================================
::: input :::
indata - input array (3, N)
dtype - data type (phase/group)
::: output :::
dispersion curve is stored
==========================================================================
"""
dtype = dtype.lower()
if dtype == 'ph' or dtype == 'phase':
if self.isphase:
print 'phase velocity data is already stored!'
return False
self.pper = indata[0, :]
self.pvelo = indata[1, :]
self.npper = self.pper.size
try:
self.stdpvelo = indata[2, :]
except IndexError:
self.stdpvelo = np.ones(self.npper, dtype=np.float64)
self.isphase = True
elif dtype == 'gr' or dtype == 'group':
if self.isgroup:
print 'group velocity data is already stored!'
return False
self.gper = indata[0, :]
self.gvelo = indata[1, :]
self.ngper = self.gper.size
try:
self.stdgvelo = indata[2, :]
except IndexError:
self.stdgvelo = np.ones(self.ngper, dtype=np.float64)
self.isgroup = True
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def get_azi_disp(self, indata):
"""
get dispersion curve data from a input numpy array
==========================================================================
::: input :::
indata - input array (3, N)
dtype - data type (phase/group)
::: output :::
dispersion curve is stored
==========================================================================
"""
self.isphase = True
# isotropic phase vel
self.pper = indata[0, :]
self.pvelo = indata[1, :]
self.npper = self.pper.size
self.stdpvelo = indata[2, :]
# azimuthal terms
self.psi2 = indata[3, :]
self.unpsi2 = indata[4, :]
self.amp = indata[5, :]
self.unamp = indata[6, :]
return True
def writedisptxt(self, outfname, dtype='ph', predisp=True, obsdisp=True):
"""
Write dispersion curve to a txt file
==========================================================================
::: input :::
outfname - output file name
dtype - data type (phase/group)
::: output :::
a txt file contains predicted and observed dispersion data
==========================================================================
"""
if dtype == 'ph' or dtype == 'phase':
if not self.isphase:
print 'phase velocity data is not stored!'
return False
if predisp:
outArr = np.append(self.pper, self.pvelp)
else:
outArr = self.pper.copy()
if obsdisp:
outArr = np.append(outArr, self.pvelo)
outArr = np.append(outArr, self.stdpvelo)
if predisp and not obsdisp:
Ncolumn = 2
elif not predisp and obsdisp:
Ncolumn = 3
elif predisp and obsdisp:
Ncolumn = 4
else:
raise ValueError('At least one of predisp/obsdisp must be True!')
outArr = outArr.reshape((Ncolumn, self.npper))
outArr = outArr.T
if Ncolumn == 4:
header = 'pper pvelp pvelo stdpvelo'
elif Ncolumn == 3:
header = 'pper pvelo stdpvelo'
elif Ncolumn == 2:
header = 'pper pvelp'
np.savetxt(outfname, outArr, fmt='%g', header=header)
elif dtype == 'gr' or dtype == 'group':
if not self.isgroup:
print 'group velocity data is not stored!'
return False
outArr = np.append(self.gper, self.gvelp)
outArr = np.append(outArr, self.gvelo)
outArr = np.append(outArr, self.stdgvelo)
outArr = outArr.reshape((4, self.ngper))
outArr = outArr.T
header = 'gper gvelp gvelo stdgvelo'
np.savetxt(outfname, outArr, fmt='%g', header=header)
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def readaziamptxt(self, infname, dtype='ph'):
"""
Read input txt file of azimuthal amplitude
==========================================================================
::: input :::
infname - input file name
dtype - data type (phase/group)
::: output :::
azimuthal amplitude is stored
==========================================================================
"""
dtype = dtype.lower()
if dtype == 'ph' or dtype == 'phase':
if not self.isphase:
print 'phase velocity data is not stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
if not np.allclose(self.pper , inArr[:,0]):
print 'inconsistent period array !'
return False
self.pampo = inArr[:,1]
self.npper = self.pper.size
try:
self.stdpampo = inArr[:,2]
except IndexError:
self.stdpampo = np.ones(self.npper, dtype=np.float64)
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def writeaziamptxt(self, outfname, dtype='ph'):
"""
Write azimuthal amplitude to a txt file
==========================================================================
::: input :::
outfname - output file name
dtype - data type (phase/group)
::: output :::
a txt file contains predicted and observed dispersion data
==========================================================================
"""
if dtype == 'ph' or dtype == 'phase':
if not self.isphase:
print 'phase velocity data is not stored!'
return False
outArr = np.append(self.pper, self.pampp)
outArr = np.append(outArr, self.pampo)
outArr = np.append(outArr, self.stdpampo)
outArr = outArr.reshape((4, self.npper))
outArr = outArr.T
header = 'pper pampp pampo stdpampo'
np.savetxt(outfname, outArr, fmt='%g')
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def readaziphitxt(self, infname, dtype='ph'):
"""
Read input txt file of fast direction azimuth
==========================================================================
::: input :::
infname - input file name
dtype - data type (phase/group)
::: output :::
fast direction azimuth is stored
==========================================================================
"""
dtype = dtype.lower()
if dtype == 'ph' or dtype == 'phase':
if not self.isphase:
print 'phase velocity data is not stored!'
return False
inArr = np.loadtxt(infname, dtype=np.float64)
if not np.allclose(self.pper , inArr[:, 0]):
print 'inconsistent period array !'
return False
self.pphio = inArr[:,1]
self.npper = self.pper.size
try:
self.stdpphio = inArr[:,2]
except IndexError:
self.stdpphio = np.ones(self.npper, dtype=np.float64)
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def writeaziphitxt(self, outfname, dtype='ph'):
"""
Write fast direction azimuth to a txt file
==========================================================================
::: input :::
outfname - output file name
dtype - data type (phase/group)
::: output :::
a txt file contains predicted and observed dispersion data
==========================================================================
"""
if dtype == 'ph' or dtype == 'phase':
if not self.isphase:
print 'phase velocity data is not stored!'
return False
outArr = np.append(self.pper, self.pphip)
outArr = np.append(outArr, self.pphio)
outArr = np.append(outArr, self.stdpphio)
outArr = outArr.reshape((4, self.npper))
outArr = outArr.T
header = 'pper pphip pphio stdpphio'
np.savetxt(outfname, outArr, fmt='%g', header=header)
else:
raise ValueError('Unexpected dtype: '+dtype)
return True
def writedispttitxt(self, outfname, dtype='ph'):
"""
Write dispersion curve to a txt file
==========================================================================
::: input :::
outfname - output file name
dtype - data type (phase/group)
::: output :::
a txt file contains predicted and observed dispersion data
==========================================================================
"""
if dtype == 'ph' or dtype == 'phase':
if not self.isphase:
print 'phase velocity data is not stored!'
return False
outArr = np.append(self.pper, self.pvelp)
outArr = np.append(outArr, self.pvelo)
outArr = np.append(outArr, self.stdpvelo)
# azimuthal amplitude
outArr = np.append(outArr, self.pampp)
outArr = np.append(outArr, self.pampo)
outArr = np.append(outArr, self.stdpampo)
# fast-direction azimuth
outArr = np.append(outArr, self.pphip)
outArr = np.append(outArr, self.pphio)
outArr = np.append(outArr, self.stdpphio)
outArr = outArr.reshape((10, self.npper))
outArr = outArr.T
header = 'pper pvelp pvelo stdpvelo pampp pampo stdpampo pphip pphio stdpphio'
np.savetxt(outfname, outArr, fmt='%g', header=header)
return True
#----------------------------------------------------
# functions computing misfit
#----------------------------------------------------
def get_pmisfit(self):
"""
Compute the misfit for phase velocities
"""
if not self.isphase :
print('No phase velocity data stored')
return False
temp = ((self.pvelo - self.pvelp)**2/self.stdpvelo**2).sum()
self.pmisfit = np.sqrt(temp/self.npper)
self.pS = temp
if temp > 50.:
temp = np.sqrt(temp*50.)
self.pL = np.exp(-0.5 * temp)
return True
def get_gmisfit(self):
"""
Compute the misfit for group velocities
"""
if not self.isgroup:
print('No group velocity data stored')
return False
temp = ((self.gvelo - self.gvelp)**2/self.stdgvelo**2).sum()
self.gmisfit = np.sqrt(temp/self.ngper)
self.gS = temp
if temp > 50.:
temp = np.sqrt(temp*50.)
self.gL = np.exp(-0.5 * temp)
return True
def get_misfit(self):
"""
Compute combined misfit of both phase and group dispersion
"""
# misfit for phase velocities
temp1 = 0.
temp2 = 0.
if self.isphase: # isphase is determined when reading phase velocity data
temp1 += ((self.pvelo - self.pvelp)**2/self.stdpvelo**2).sum()
tS = temp1
self.pS = tS
misfit = np.sqrt(temp1/self.npper)
if tS > 50.:
tS = np.sqrt(tS*50.)
L = np.exp(-0.5 * tS)
self.pmisfit= misfit
self.pL = L
# misfit for group velocities
if self.isgroup: # isgroup is determined when reading group velocity data
temp2 += ((self.gvelo - self.gvelp)**2/self.stdgvelo**2).sum()
tS = temp2
self.gS = tS
misfit = np.sqrt(temp2/self.ngper)
if tS > 50.:
tS = np.sqrt(tS*50.)
L = np.exp(-0.5 * tS)
self.gmisfit= misfit
self.gL = L
if (not self.isphase) and (not self.isgroup):
print('No dispersion data stored!')
self.misfit = 0.
self.L = 1.
return False
# misfit for both
temp = temp1 + temp2
self.S = temp
self.misfit = np.sqrt(temp/(self.npper+self.ngper))
if temp > 50.:
temp = np.sqrt(temp*50.)
if temp > 50.:
temp = np.sqrt(temp*50.)
self.L = np.exp(-0.5 * temp)
return True
def get_misfit_tti(self):
"""
compute misfit for inversion of tilted TI models, only applies to phase velocity dispersion
"""
temp1 = ((self.pvelo - self.pvelp)**2/self.stdpvelo**2).sum()
temp2 = ((self.pampo - self.pampp)**2/self.stdpampo**2).sum()
phidiff = abs(self.pphio - self.pphip)
phidiff[phidiff>90.] = 180. - phidiff[phidiff>90.]
temp3 = (phidiff**2/self.stdpphio**2).sum()
self.pS = temp1+temp2+temp3
tS = temp1+temp2+temp3
self.pmisfit = np.sqrt(tS/3./self.npper)
if tS > 50.:
tS = np.sqrt(tS*50.)
self.pL = np.exp(-0.5 * tS)
return
def expected_misfit(self):
# misfit for phase velocities
stdarr = np.array([], dtype=np.float64)
if self.isphase: # isphase is determined when reading phase velocity data
stdarr = np.append(stdarr, self.stdpvelo)
if self.isgroup: # isgroup is determined when reading group velocity data
stdarr = np.append(stdarr, self.stdgvelo)
# self.exp_misfit\
# = _fast_compute_expect_misfit(stdarr, 1000000)
# temp1 = 0.
# temp2 = 0.
# if self.isphase: # isphase is determined when reading phase velocity data
# temp1 += ((np.random.normal(scale=self.stdpvelo))**2/self.stdpvelo**2).sum()
# # misfit for group velocities
# if self.isgroup: # isgroup is determined when reading group velocity data
# temp2 += ((np.random.normal(scale=self.stdgvelo))**2/self.stdgvelo**2).sum()
# # misfit for both
# temp = temp1 + temp2
# self.exp_misfit = np.sqrt(temp/(self.npper+self.ngper))
return
def check_pdisp(self, dtype='ph', Tthresh = 50., mono_tol = 0.001, dv_tol=0.2):
""" check the predicted phase velocity
"""
if dtype == 'ph':
pvel = self.pvelp
periods = self.pper
elif dtype == 'gr':
pvel = self.gvelp
periods = self.gper
else:
raise ValueError('Unexpected input dtype = '+dtype)
# monotonical increase check
ind = periods > Tthresh
if (periods[ind]).size >= 2:
temp_pers = periods[ind]
temp_vel = pvel[ind]
vel_left = temp_vel[:-1]
vel_right = temp_vel[1:]
if np.any( (vel_left - vel_right) >= mono_tol ):
return False
# check the discontinuity in dispersion curves
vel_left = pvel[:-1]
vel_right = pvel[1:]
if np.any( abs(vel_left - vel_right) >= dv_tol ):
return False
return True
def check_large_perturb(self, thresh=10.):
"""check the differences between reference dispersion curve and predicted dispersion curve
"""
return (abs(self.pvelref - self.pvelp)/self.pvelref).max()*100. > thresh
def plot_azi_fit_old(self, inpsi=[], inamp=[]):
plt.figure(figsize=[18, 9.6])
ax = plt.subplot()
#self.psi2[self.psi2 - self.ppsi2 > 90.] -= 180.
#self.psi2[self.psi2 - self.ppsi2 < -90.] += 180.
self.ppsi2[self.ppsi2 - self.psi2 > 90.] -= 180.
self.ppsi2[self.ppsi2 - self.psi2 < -90.] += 180.
if len(inpsi) > 0:
inpsi[inpsi - self.psi2 > 90.] -= 180.
inpsi[inpsi - self.psi2 < -90.] += 180.
plt.errorbar(self.pper, self.psi2, yerr=self.unpsi2, fmt='ko')
plt.plot(self.pper, self.ppsi2, 'b-', lw=3, label='two-layer model')
if len(inpsi) == self.npper:
plt.plot(self.pper, inpsi, 'r--', lw=3, label='three-layer model')
plt.ylabel('Fast azimuth (deg)', fontsize=50)
plt.xlabel('Period (sec)', fontsize=50)
ax.tick_params(axis='x', labelsize=30)
ax.tick_params(axis='y', labelsize=30)
if len(inamp) == self.npper:
plt.legend(fontsize=30)
#
plt.figure(figsize=[18, 9.6])
ax = plt.subplot()
plt.errorbar(self.pper, self.amp, yerr=self.unamp, fmt='ko')
plt.plot(self.pper, self.pamp, 'b-', lw=3, label='two-layer model')
if len(inamp) == self.npper:
plt.plot(self.pper, inamp, 'r--', lw=3, label='three-layer model')
plt.ylabel('Anisotropy amplitude (%)', fontsize=50)
plt.xlabel('Period (sec)', fontsize=50)
ax.tick_params(axis='x', labelsize=30)
ax.tick_params(axis='y', labelsize=30)
if len(inamp) == self.npper:
plt.legend(fontsize=30)
ymax = (self.amp+self.unamp).max()
plt.ylim([0., ymax])
plt.show()
def plot_azi_fit(self, psitype=0, title=''):
# plt.figure(figsize=[18, 9.6])
fig, axs = plt.subplots(2, 1)
if psitype == 0:
self.psi2[self.psi2 - self.ppsi2 > 90.] -= 180.
self.psi2[self.psi2 - self.ppsi2 < -90.] += 180.
elif psitype == 1:
self.psi2[self.psi2<0.] += 180.
self.ppsi2[self.ppsi2<0.] += 180.
elif psitype == 2:
self.psi2[self.psi2>90.] -= 180.
self.ppsi2[self.ppsi2>90.] -= 180.
elif psitype == 3:
self.psi2[self.psi2>90.] -= 180.
self.ppsi2[self.ppsi2>90.] -= 180.
axs[0].errorbar(self.pper, self.psi2, yerr=self.unpsi2, fmt='ko')
axs[0].plot(self.pper, self.ppsi2, 'b-', lw=3 )
axs[0].set_ylabel('Fast azimuth (deg)', fontsize=20)
# axs[0].set_xlabel('Period (sec)', fontsize=30)
axs[0].tick_params(axis='x', labelsize=30)
axs[0].tick_params(axis='y', labelsize=15)
#
# plt.figure(figsize=[18, 9.6])
# ax = plt.subplot()
axs[1].errorbar(self.pper, self.amp, yerr=self.unamp, fmt='ko')
axs[1].plot(self.pper, self.pamp, 'b-', lw=3 )
axs[1].set_ylabel('Anisotropy amplitude (%)', fontsize=20)
axs[1].set_xlabel('Period (sec)', fontsize=30)
axs[1].tick_params(axis='x', labelsize=30)
axs[1].tick_params(axis='y', labelsize=15)
ymax = (self.amp+self.unamp).max()
axs[1].set_ylim([0., ymax])
plt.suptitle('Misfit = %g' %self.pmisfit+title, fontsize=30)
plt.show()
def plot_azi_fit_2(self, psitype=0, title=''):
# plt.figure(figsize=[18, 9.6])
fig, axs = plt.subplots(2, 1)
if psitype == 0:
self.psi2[self.psi2 - self.ppsi2 > 90.] -= 180.
self.psi2[self.psi2 - self.ppsi2 < -90.] += 180.
elif psitype == 1:
self.psi2[self.psi2<0.] += 180.
self.ppsi2[self.ppsi2<0.] += 180.
elif psitype == 2:
self.psi2[self.psi2>90.] -= 180.
self.ppsi2[self.ppsi2>90.] -= 180.
elif psitype == 3:
self.psi2[self.psi2>90.] -= 180.
self.ppsi2[self.ppsi2>90.] -= 180.
#
min_psi2 = self.psi2 - self.unpsi2
max_psi2 = self.psi2 + self.unpsi2
if np.any(self.ppsi2 > max_psi2):
self.unpsi2[self.ppsi2 > max_psi2] *= 1.5
if np.any(self.ppsi2 < min_psi2):
self.unpsi2[self.ppsi2 > min_psi2] *= 1.5
#
axs[0].errorbar(self.pper, self.psi2, yerr=self.unpsi2, fmt='ko')
axs[0].plot(self.pper, self.ppsi2, 'b-', lw=3 )
axs[0].set_ylabel('Fast azimuth (deg)', fontsize=20)
# axs[0].set_xlabel('Period (sec)', fontsize=30)
axs[0].tick_params(axis='x', labelsize=30)
axs[0].tick_params(axis='y', labelsize=15)
#
# plt.figure(figsize=[18, 9.6])
# ax = plt.subplot()
axs[1].errorbar(self.pper, self.amp, yerr=self.unamp, fmt='ko')
axs[1].plot(self.pper, self.pamp, 'b-', lw=3 )
axs[1].set_ylabel('Anisotropy amplitude (%)', fontsize=20)
axs[1].set_xlabel('Period (sec)', fontsize=30)
axs[1].tick_params(axis='x', labelsize=30)
axs[1].tick_params(axis='y', labelsize=15)
ymax = (self.amp+self.unamp).max()
axs[1].set_ylim([0., ymax])
plt.suptitle('Misfit = %g' %self.pmisfit+title, fontsize=30)
plt.show()
def get_misfit_hti(self):
temp1 = ((self.amp - self.pamp)**2/self.unamp**2).sum()
psidiff = abs(self.psi2 - self.ppsi2)
psidiff[psidiff>90.] = 180. - psidiff[psidiff>90.]
temp2 = (psidiff**2/self.unpsi2**2).sum()
#
self.pS = temp1+temp2
tS = temp1+temp2
self.pmisfit = np.sqrt(tS/2./self.npper)
#
self.pS_amp = temp1
self.pmisfit_amp = np.sqrt(temp1/self.npper)
#
self.pS_psi = temp2
self.pmisfit_psi = np.sqrt(temp2/self.npper)
if tS > 50.:
tS = np.sqrt(tS*50.)
self.pL = np.exp(-0.5 * tS)
def check_disp(self, thresh=0.4):
diff_vel = abs(self.pvelo - self.pvelp)
return np.any(diff_vel>thresh)
class data1d(object):
"""
An object for handling input data for inversion
==========================================================================
::: parameters :::
dispR - Rayleigh wave dispersion data
dispL - Love wave dispersion data
rfr - radial receiver function data
rft - transverse receiver function data
misfit - misfit value
L - likelihood value
==========================================================================
"""
def __init__(self):
self.dispR = disp()
self.dispL = disp()
self.rfr = rf()
self.rft = rf()
return
def get_misfit(self, wdisp=0.2, rffactor=40.):
"""
Compute combined misfit
==========================================================================================
::: input :::
wdisp - relative weigh for dispersion data ( 0.~1. )
wdisp == 0.: misfit of dispersion data is 0., likelihood is 1
wdisp == 1.: misfit of receiver function data is 0., likelihood is 1
rffactor - factor for downweighting the misfit for likelihood computation of rf
==========================================================================================
"""
if wdisp > 0.:
self.dispR.get_misfit()
else:
self.dispR.misfit = 0.
self.dispR.L = 1.
if wdisp < 1.:
self.rfr.get_misfit(rffactor = rffactor)
else:
self.rfr.misfit = 0.
self.rfr.L = 1.
# compute combined misfit and likelihood
self.misfit = wdisp*self.dispR.misfit + (1.-wdisp)*self.rfr.misfit
self.L = ((self.dispR.L)**wdisp)*((self.rfr.L)**(1.-wdisp))
return
def get_misfit_vti(self):
"""
compute misfit for inversion of Vertical TI models, only applies to phase velocity dispersion
"""
self.dispR.get_misfit()
self.dispL.get_misfit()
self.misfit = np.sqrt((self.dispR.pS + self.dispL.pS)/(self.dispR.npper + self.dispL.npper) )
tS = (self.dispR.pS + self.dispL.pS)
if tS > 50.:
tS = np.sqrt(tS*50.)
if tS > 50.:
tS = np.sqrt(tS*50.)
self.L = np.exp(-0.5 * tS)
return
def get_misfit_vti_2(self):
"""
compute misfit for inversion of Vertical TI models, only applies to phase velocity dispersion
"""
self.dispR.get_misfit()
self.dispL.get_misfit()
self.misfit = np.sqrt((self.dispR.pS + self.dispR.gS + self.dispL.pS)/(self.dispR.npper +self.dispR.ngper + self.dispL.npper) )
tS = (self.dispR.pS + self.dispR.gS + self.dispL.pS)
if tS > 50.:
tS = np.sqrt(tS*50.)
if tS > 50.:
tS = np.sqrt(tS*50.)
self.L = np.exp(-0.5 * tS)
return
def get_misfit_hti(self):
"""
compute misfit for inversion of Vertical TI models, only applies to phase velocity dispersion
"""
self.dispR.get_misfit_hti()
self.misfit = self.dispR.pmisfit
self.L = self.dispR.pL
return