forked from NoisyLeon/NoisePy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheikonaltomo.py
5883 lines (5715 loc) · 313 KB
/
eikonaltomo.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
# -*- coding: utf-8 -*-
"""
A python module to run surface wave eikonal/Helmholtz tomography
The code creates a datadbase based on hdf5 data format
:Dependencies:
pyasdf and its dependencies
GMT 5.x.x (for interpolation on Earth surface)
numba
numexpr
:Copyright:
Author: Lili Feng
Graduate Research Assistant
CIEI, Department of Physics, University of Colorado Boulder
email: lili.feng@colorado.edu
:References:
Lin, Fan-Chi, Michael H. Ritzwoller, and Roel Snieder. "Eikonal tomography: surface wave tomography by phase front tracking across a regional broad-band seismic array."
Geophysical Journal International 177.3 (2009): 1091-1110.
Lin, Fan-Chi, and Michael H. Ritzwoller. "Helmholtz surface wave tomography for isotropic and azimuthally anisotropic structure."
Geophysical Journal International 186.3 (2011): 1104-1120.
"""
import numpy as np
import numpy.ma as ma
import scipy.stats
import h5py, pyasdf
import os, shutil
from subprocess import call
from mpl_toolkits.basemap import Basemap, shiftgrid, cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import matplotlib
import colormaps
import obspy
import field2d_earth
import numexpr
import warnings
from functools import partial
import multiprocessing
from numba import jit, float32, int32, boolean, float64, int64
import numba
from numba import njit, prange
import time
from scipy import optimize
from uncertainties import ufloat
import uncertainties.umath
# compiled function to get weight for each event and each grid point
@jit(float32[:,:,:](float32[:,:,:], float32[:,:,:]))
def _get_azi_weight(aziALL, validALL):
Nevent, Nlon, Nlat = aziALL.shape
weightALL = np.zeros((Nevent, Nlon, Nlat), dtype=np.float32)
for ilon in xrange(Nlon):
for ilat in xrange(Nlat):
for i in xrange(Nevent):
for j in xrange(Nevent):
delAzi = abs(aziALL[i, ilon, ilat] - aziALL[j, ilon, ilat])
if delAzi < 20. or delAzi > 340.:
weightALL[i, ilon, ilat]+= validALL[i, ilon, ilat]
return weightALL
@jit(boolean[:](boolean[:], float64[:], float64[:], float64[:], float64[:]))
def _get_mask_interp(mask_in, lons_in, lats_in, lons, lats):
Nlat = lats.size
Nlon = lons.size
mask_out = np.ones((Nlat, Nlon), dtype=np.bool)
for i in range(Nlat):
for j in range(Nlon):
clat = lats[i]
clon = lons[j]
ind_lon = np.where(clon<=lons_in)[0][0]
ind_lat = np.where(clat<=lats_in)[0][0]
if (clon - lons_in[ind_lon])< 0.001 and (clat - lats_in[ind_lat]) < 0.001:
mask_out[i, j] = mask_in[ind_lat, ind_lon]
continue
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat, ind_lon]
if ind_lat > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat-1, ind_lon]
if ind_lon > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat-1, ind_lon-1]
if ind_lon > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat, ind_lon-1]
if ind_lat > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat-1, ind_lon-1]
return mask_out
# compiled function to evaluate station distribution
@jit(boolean(float64[:], float64[:], int32))
def _check_station_distribution_old(lons, lats, Nvalid_min):
N = lons.size
Nvalid = 0
for i in range(N):
lon1 = lons[i]
lat1 = lats[i]
NnearE = 0
NnearW = 0
NnearN = 0
NnearS = 0
for j in range(N):
lon2 = lons[j]
lat2 = lats[j]
if i == j:
continue
if abs(lat1 - lat2) < 1.5:
colat = 90. - (lat1+lat2)/2.
temp_R = 6371. * np.sin(np.pi * colat/180.)
dlon = abs(lon1 - lon2)
dist_lon = temp_R * np.sin(dlon*np.pi/180.)
if dist_lon < 150.:
if lon2 >= lon1:
NnearW += 1
else:
NnearE += 1
if lat2 >= lat1:
NnearN += 1
else:
NnearS += 1
if NnearE > 0 and NnearW > 0 and NnearN > 0 and NnearS > 0:
Nvalid += 1
if Nvalid >= Nvalid_min:
return True
else:
return False
@jit(boolean(float64[:], float64[:], int32))
def _check_station_distribution(lons, lats, Nvalid_min):
"""check the station distribution
Step 1. a station is counted as valid if there are at least four stations nearby
Step 2. check if the number of valid stations is larger than Nvalid_min
"""
N = lons.size
Nvalid = 0
for i in range(N):
lon1 = lons[i]
lat1 = lats[i]
Nnear = 0
for j in range(N):
lon2 = lons[j]
lat2 = lats[j]
if i == j:
continue
if abs(lat1 - lat2) < 1.5:
colat = 90. - (lat1+lat2)/2.
temp_R = 6371. * np.sin(np.pi * colat/180.)
dlon = abs(lon1 - lon2)
dist_lon = temp_R * np.sin(dlon*np.pi/180.)
if dist_lon < 150.:
Nnear += 1
if Nnear >= 4:
Nvalid += 1
if Nvalid >= Nvalid_min:
return True
else:
return False
def to_percent(y, position):
# Ignore the passed in position. This has the effect of scaling the default
# tick locations.
s = '%.0f' %(100. * y)
# The percent symbol needs escaping in latex
if matplotlib.rcParams['text.usetex'] is True:
return s + r'$\%$'
else:
return s + '%'
@jit(boolean[:](boolean[:], float64[:], float64[:], float64[:], float64[:]))
def _get_mask_interp(mask_in, lons_in, lats_in, lons, lats):
Nlat = lats.size
Nlon = lons.size
mask_out = np.ones((Nlat, Nlon), dtype=np.bool)
for i in range(Nlat):
for j in range(Nlon):
clat = lats[i]
clon = lons[j]
ind_lon = np.where(clon<=lons_in)[0][0]
ind_lat = np.where(clat<=lats_in)[0][0]
if (clon - lons_in[ind_lon])< 0.001 and (clat - lats_in[ind_lat]) < 0.001:
mask_out[i, j] = mask_in[ind_lat, ind_lon]
continue
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat, ind_lon]
if ind_lat > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat-1, ind_lon]
if ind_lon > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat-1, ind_lon-1]
if ind_lon > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat, ind_lon-1]
if ind_lat > 0:
mask_out[i, j] = mask_out[i, j]*mask_in[ind_lat-1, ind_lon-1]
return mask_out
def plot_fault_lines(mapobj, infname, lw=2, color='red'):
with open(infname, 'rb') as fio:
is_new = False
lonlst = []
latlst = []
for line in fio.readlines():
if line.split()[0] == '>':
x, y = mapobj(lonlst, latlst)
mapobj.plot(x, y, lw = lw, color=color)
# # # m.plot(xslb, yslb, lw = 3, color='white')
lonlst = []
latlst = []
continue
lonlst.append(float(line.split()[0]))
latlst.append(float(line.split()[1]))
x, y = mapobj(lonlst, latlst)
mapobj.plot(x, y, lw = lw, color=color)
@njit(numba.types.Tuple((float64[:, :, :], float64[:, :, :], float64[:, :, :], int64[:, :, :], int64[:, :]))\
(int64, int64, float32, float32, int64, float64[:, :], float64[:, :, :], float64[:, :], float64[:, :, :], numba.boolean[:, :, :]))
def _anisotropic_stacking(gridx, gridy, maxazi, minazi, N_bin, Nmeasure, aziALL,\
slowness_sumQC, slownessALL, index_outlier):
Nevent, Nx, Ny = aziALL.shape
Nx_trim = Nx - (gridx - 1)
Ny_trim = Ny - (gridy - 1)
NmeasureAni = np.zeros((Nx_trim, Ny_trim), dtype=np.int64) # for quality control
# initialization of anisotropic parameters
d_bin = float((maxazi-minazi)/N_bin)
# number of measurements in each bin
histArr = np.zeros((N_bin, Nx_trim, Ny_trim), dtype=np.int64)
# slowness in each bin
dslow_sum_ani = np.zeros((N_bin, Nx_trim, Ny_trim))
# slowness uncertainties for each bin
dslow_un = np.zeros((N_bin, Nx_trim, Ny_trim))
# velocity uncertainties for each bin
vel_un = np.zeros((N_bin, Nx_trim, Ny_trim))
#----------------------------------------------------------------------------------
# Loop over azimuth bins to get slowness, velocity and number of measurements
#----------------------------------------------------------------------------------
for ibin in range(N_bin):
sumNbin = np.zeros((Nx_trim, Ny_trim))
# slowness arrays
dslowbin = np.zeros((Nx_trim, Ny_trim))
dslow_un_ibin = np.zeros((Nx_trim, Ny_trim))
dslow_mean = np.zeros((Nx_trim, Ny_trim))
# velocity arrays
velbin = np.zeros((Nx_trim, Ny_trim))
vel_un_ibin = np.zeros((Nx_trim, Ny_trim))
vel_mean = np.zeros((Nx_trim, Ny_trim))
for ix in range(Nx_trim):
for iy in range(Ny_trim):
for ishift_x in range(gridx):
for ishift_y in range(gridy):
for iev in range(Nevent):
azi = aziALL[iev, ix + ishift_x, iy + ishift_y]
ibin_temp = np.floor((azi - minazi)/d_bin)
if ibin_temp != ibin:
continue
is_outlier = index_outlier[iev, ix + ishift_x, iy + ishift_y]
if is_outlier:
continue
temp_dslow = slownessALL[iev, ix + ishift_x, iy + ishift_y] - slowness_sumQC[ix + ishift_x, iy + ishift_y]
if slownessALL[iev, ix + ishift_x, iy + ishift_y] != 0.:
temp_vel= 1./slownessALL[iev, ix + ishift_x, iy + ishift_y]
else:
temp_vel= 0.
sumNbin[ix, iy] += 1
dslowbin[ix, iy] += temp_dslow
velbin[ix, iy] += temp_vel
NmeasureAni[ix, iy] += 1 # 2019-06-06
# end nested loop of grid shifting
if sumNbin[ix, iy] >= 2:
vel_mean[ix, iy] = velbin[ix, iy] / sumNbin[ix, iy]
dslow_mean[ix, iy] = dslowbin[ix, iy] / sumNbin[ix, iy]
else:
sumNbin[ix, iy] = 0
# compute uncertainties
for ix in range(Nx_trim):
for iy in range(Ny_trim):
for ishift_x in range(gridx):
for ishift_y in range(gridy):
for iev in range(Nevent):
azi = aziALL[iev, ix + ishift_x, iy + ishift_y]
ibin_temp = np.floor((azi - minazi)/d_bin)
if ibin_temp != ibin:
continue
is_outlier = index_outlier[iev, ix + ishift_x, iy + ishift_y]
if is_outlier:
continue
if slownessALL[iev, ix + ishift_x, iy + ishift_y] != 0.:
temp_vel = 1./slownessALL[iev, ix + ishift_x, iy + ishift_y]
else:
temp_vel = 0.
temp_vel_mean = vel_mean[ix, iy]
vel_un_ibin[ix, iy] += (temp_vel - temp_vel_mean)**2
temp_dslow = slownessALL[iev, ix + ishift_x, iy + ishift_y] - slowness_sumQC[ix + ishift_x, iy + ishift_y]
temp_dslow_mean = dslow_mean[ix, iy]
dslow_un_ibin[ix, iy] += (temp_dslow - temp_dslow_mean)**2
for ix in range(Nx_trim):
for iy in range(Ny_trim):
if sumNbin[ix, iy] < 2:
continue
vel_un_ibin[ix, iy] = np.sqrt(vel_un_ibin[ix, iy]/(sumNbin[ix, iy] - 1)/sumNbin[ix, iy])
vel_un[ibin, ix, iy] = vel_un_ibin[ix, iy]
dslow_un_ibin[ix, iy] = np.sqrt(dslow_un_ibin[ix, iy]/(sumNbin[ix, iy] - 1)/sumNbin[ix, iy])
dslow_un[ibin, ix, iy] = dslow_un_ibin[ix, iy]
histArr[ibin, ix, iy] = sumNbin[ix, iy]
dslow_sum_ani[ibin, ix, iy] = dslow_mean[ix, iy]
return dslow_sum_ani, dslow_un, vel_un, histArr, NmeasureAni
@njit(numba.types.Tuple((float64[:, :, :], float64[:, :, :], float64[:, :, :], int64[:, :, :], int64[:, :]))\
(int64, int64, float32, float32, int64, float64[:, :], float64[:, :, :], float64[:, :], float64[:, :, :], numba.boolean[:, :, :]), parallel=True)
def _anisotropic_stacking_parallel(gridx, gridy, maxazi, minazi, N_bin, Nmeasure, aziALL,\
slowness_sumQC, slownessALL, index_outlier):
Nevent, Nx, Ny = aziALL.shape
Nx_trim = Nx - (gridx - 1)
Ny_trim = Ny - (gridy - 1)
NmeasureAni = np.zeros((Nx_trim, Ny_trim), dtype=np.int64) # for quality control
# initialization of anisotropic parameters
d_bin = float((maxazi-minazi)/N_bin)
# number of measurements in each bin
histArr = np.zeros((N_bin, Nx_trim, Ny_trim), dtype=np.int64)
# slowness in each bin
dslow_sum_ani = np.zeros((N_bin, Nx_trim, Ny_trim))
# slowness uncertainties for each bin
dslow_un = np.zeros((N_bin, Nx_trim, Ny_trim))
# velocity uncertainties for each bin
vel_un = np.zeros((N_bin, Nx_trim, Ny_trim))
#----------------------------------------------------------------------------------
# Loop over azimuth bins to get slowness, velocity and number of measurements
#----------------------------------------------------------------------------------
for ibin in range(N_bin):
sumNbin = np.zeros((Nx_trim, Ny_trim))
# slowness arrays
dslowbin = np.zeros((Nx_trim, Ny_trim))
dslow_un_ibin = np.zeros((Nx_trim, Ny_trim))
dslow_mean = np.zeros((Nx_trim, Ny_trim))
# velocity arrays
velbin = np.zeros((Nx_trim, Ny_trim))
vel_un_ibin = np.zeros((Nx_trim, Ny_trim))
vel_mean = np.zeros((Nx_trim, Ny_trim))
for ix in prange(Nx_trim):
for iy in prange(Ny_trim):
for ishift_x in range(gridx):
for ishift_y in range(gridy):
for iev in range(Nevent):
azi = aziALL[iev, ix + ishift_x, iy + ishift_y]
ibin_temp = np.floor((azi - minazi)/d_bin)
if ibin_temp != ibin:
continue
is_outlier = index_outlier[iev, ix + ishift_x, iy + ishift_y]
if is_outlier:
continue
temp_dslow = slownessALL[iev, ix + ishift_x, iy + ishift_y] - slowness_sumQC[ix + ishift_x, iy + ishift_y]
if slownessALL[iev, ix + ishift_x, iy + ishift_y] != 0.:
temp_vel= 1./slownessALL[iev, ix + ishift_x, iy + ishift_y]
else:
temp_vel= 0.
# changing values
sumNbin[ix, iy] += 1
dslowbin[ix, iy] += temp_dslow
velbin[ix, iy] += temp_vel
NmeasureAni[ix, iy] += 1 # 2019-06-06
# end nested loop of grid shifting
if sumNbin[ix, iy] >= 2:
vel_mean[ix, iy] = velbin[ix, iy] / sumNbin[ix, iy]
dslow_mean[ix, iy] = dslowbin[ix, iy] / sumNbin[ix, iy]
else:
sumNbin[ix, iy] = 0
# compute uncertainties
for ix in prange(Nx_trim):
for iy in prange(Ny_trim):
for ishift_x in range(gridx):
for ishift_y in range(gridy):
for iev in range(Nevent):
azi = aziALL[iev, ix + ishift_x, iy + ishift_y]
ibin_temp = np.floor((azi - minazi)/d_bin)
if ibin_temp != ibin:
continue
is_outlier = index_outlier[iev, ix + ishift_x, iy + ishift_y]
if is_outlier:
continue
if slownessALL[iev, ix + ishift_x, iy + ishift_y] != 0.:
temp_vel = 1./slownessALL[iev, ix + ishift_x, iy + ishift_y]
else:
temp_vel = 0.
# changing values
temp_vel_mean = vel_mean[ix, iy]
vel_un_ibin[ix, iy] += (temp_vel - temp_vel_mean)**2
temp_dslow = slownessALL[iev, ix + ishift_x, iy + ishift_y] - slowness_sumQC[ix + ishift_x, iy + ishift_y]
temp_dslow_mean = dslow_mean[ix, iy]
dslow_un_ibin[ix, iy] += (temp_dslow - temp_dslow_mean)**2
for ix in prange(Nx_trim):
for iy in prange(Ny_trim):
if sumNbin[ix, iy] < 2:
continue
vel_un_ibin[ix, iy] = np.sqrt(vel_un_ibin[ix, iy]/(sumNbin[ix, iy] - 1)/sumNbin[ix, iy])
vel_un[ibin, ix, iy] = vel_un_ibin[ix, iy]
dslow_un_ibin[ix, iy] = np.sqrt(dslow_un_ibin[ix, iy]/(sumNbin[ix, iy] - 1)/sumNbin[ix, iy])
dslow_un[ibin, ix, iy] = dslow_un_ibin[ix, iy]
histArr[ibin, ix, iy] = sumNbin[ix, iy]
dslow_sum_ani[ibin, ix, iy] = dslow_mean[ix, iy]
return dslow_sum_ani, dslow_un, vel_un, histArr, NmeasureAni
# @jit(numba.types.Tuple((float32[:, :], float32[:, :]))(numba.boolean[:, :]), parallel=True)
def _get_gaps(indarr):
Nbin, Nlat, Nlon = indarr.shape
gap1 = np.zeros((Nlat, Nlon), dtype=np.float32)
gap2 = np.zeros((Nlat, Nlon), dtype=np.float32)
for ilat in range(Nlat):
for ilon in range(Nlon):
index = indarr[:, ilat, ilon]
isfirst = True
isnew = True
temp_Ngap = 0
gaparr = np.array([], dtype=np.float32)
for i in range(Nbin):
if index[i]:
if temp_Ngap> 0:
gaparr = np.append(gaparr, temp_Ngap)
temp_Ngap = 0
continue
if isfirst:
firstind = i
isfirst = False
temp_Ngap += 1
if temp_Ngap>0:
gaparr = np.append(gaparr, temp_Ngap)
if gaparr.size == 0:
gap1[ilat, ilon] \
= 0
gap2[ilat, ilon] \
= 0
continue
if firstind == 0 and gaparr.size>1:
outgap = gaparr[1:-1]
outgap = np.append(outgap, gaparr[0]+gaparr[-1])
else:
outgap = gaparr.copy()
if outgap.size>=2:
outgap = np.sort(outgap)
gap1[ilat, ilon] \
= outgap[-1]
gap2[ilat, ilon] \
= outgap[-2]
else:
gap1[ilat, ilon] \
= outgap[0]
gap2[ilat, ilon]\
= 0
return gap1, gap2
Npsi_glb = 360
dpsi_glb = 180./np.float64(Npsi_glb)
Namp_glb = 500
ampmax_glb = 5.
damp_glb = ampmax_glb/np.float64(Namp_glb)
@njit(float64[:, :](float64[:], float64[:], float64[:], float64), parallel=True)
def _get_azi_misfit(obsdat, obssem, az_grd, A0):
psiarr = np.arange(Npsi_glb)*dpsi_glb
amparr = np.arange(Namp_glb)*damp_glb
misfitarr = np.zeros((Npsi_glb, Namp_glb), dtype=np.float64)
Naz = np.float64(az_grd.size)
for ipsi in prange(Npsi_glb):
for iamp in prange(Namp_glb):
psi = psiarr[ipsi]*np.pi/180.
amp = amparr[iamp]
A2 = A0*amp/100.
predat = A0 + A2*np.cos(2.*(np.pi/180.*(az_grd+180.)-psi) )
misfitarr[ipsi, iamp]\
= np.sqrt( ((predat - obsdat)**2 / obssem**2).sum()/ Naz )
return misfitarr
def _get_azi_sem(obsdat, obssem, az_grd, A0):
misfitarr = _get_azi_misfit(obsdat, obssem, az_grd, A0)
minmisfit = misfitarr.min()
thresh = minmisfit + 0.5
index = misfitarr <= thresh
psiarr = np.arange(Npsi_glb)*dpsi_glb
amparr = np.arange(Namp_glb)*damp_glb
psi2d, amp2d= np.meshgrid(psiarr, amparr, indexing='ij')
psi_acc = psi2d[index]
amp_acc = amp2d[index]
unpsi = scipy.stats.circstd(psi_acc, high=180., low=0.)
unamp = amp_acc.std()
return unpsi, unamp
def _get_azi_sem_2(obsdat, obssem, az_grd, A0):
misfitarr = _get_azi_misfit(obsdat, obssem, az_grd, A0)
minmisfit = misfitarr.min()
thresh = minmisfit + 0.5
index = misfitarr <= thresh
psiarr = np.arange(Npsi_glb)*dpsi_glb
amparr = np.arange(Namp_glb)*damp_glb
psi2d, amp2d= np.meshgrid(psiarr, amparr, indexing='ij')
psi_acc = psi2d[index]
amp_acc = amp2d[index]
unpsi = scipy.stats.circstd(psi_acc, high=180.01, low=0.)
unamp = amp_acc.std()
return unpsi, unamp
def pre_azi_aniso(m, theta):
return m[0] + m[1]*np.sin(2.*theta/180.*np.pi) + m[2]*np.cos(2.*theta/180.*np.pi)
def azi_errfunc(m, azarr, tvel, tsem):
return (pre_azi_aniso(m, azarr) - tvel) / tsem
class data4stack(object):
"""data object storing array for eikonal stacking
"""
def __init__(self, slownessALL, reason_nALL, aziALL, Nmeasure, Nevent, period, Nlon, Nlat, nlon_grad, nlat_grad):
self.slownessALL = slownessALL
self.reason_nALL = reason_nALL
self.aziALL = aziALL
self.Nmeasure = Nmeasure
self.Nevent = Nevent
self.period = period
self.Nlon = Nlon
self.Nlat = Nlat
self.nlat_grad = nlat_grad
self.nlon_grad = nlon_grad
class EikonalTomoDataSet(h5py.File):
"""
Object for eikonal/Helmholtz tomography, builded upon hdf5 data file.
"""
#==================================================
# functions print the information of database
#==================================================
def print_attrs(self, print_to_screen=True):
"""
Print the attrsbute information of the dataset.
"""
outstr = '================================= Surface wave eikonal/Helmholtz tomography database ==================================\n'
try:
outstr += 'period(s): - '+str(self.attrs['period_array'])+'\n'
outstr += 'longitude range - '+str(self.attrs['minlon'])+' ~ '+str(self.attrs['maxlon'])+'\n'
outstr += 'longitude spacing/npts - '+str(self.attrs['dlon'])+'/'+str(self.attrs['Nlon'])+'\n'
outstr += 'nlon_grad/nlon_lplc - '+str(self.attrs['nlon_grad'])+'/'+str(self.attrs['nlon_lplc'])+'\n'
outstr += 'latitude range - '+str(self.attrs['minlat'])+' ~ '+str(self.attrs['maxlat'])+'\n'
outstr += 'latitude spacing/npts - '+str(self.attrs['dlat'])+'/'+str(self.attrs['Nlat'])+'\n'
outstr += 'nlat_grad/nlat_lplc - '+str(self.attrs['nlat_grad'])+'/'+str(self.attrs['nlat_lplc'])+'\n'
per_arr = self.attrs['period_array']
except:
print 'Empty Database!'
return None
if print_to_screen:
print outstr
else:
return outstr
return
def print_info(self, runid=0):
"""print the information of given eikonal/Helmholz run
"""
outstr = self.print_attrs(print_to_screen=False)
if outstr is None:
return
outstr += '========================================== Eikonal_run_%d' %runid +' ====================================================\n'
subgroup = self['Eikonal_run_%d' %runid]
pers = self.attrs['period_array']
perid = '%d_sec' %pers[0]
Nevent = len(subgroup[perid].keys())
outstr += '--- number of (virtual) events - '+str(Nevent)+'\n'
evid = subgroup[perid].keys()[0]
evgrp = subgroup[perid][evid]
outstr += '--- attributes for each event - evlo, evla, Nvalid_grd, Ntotal_grd \n'
outstr += '--- appV (apparent velocity) - '+str(evgrp['appV'].shape)+'\n'
try:
outstr += '--- corV (corrected velocity) - '+str(evgrp['corV'].shape)+'\n'
except KeyError:
outstr += '*** NO corrected velocity \n'
try:
outstr += '--- lplc_amp (amplitude Laplacian) - '+str(evgrp['lplc_amp'].shape)+'\n'
except KeyError:
outstr += '*** NO corrected lplc_amp \n'
outstr += '--- az (azimuth) - '+str(evgrp['az'].shape)+'\n'
outstr += '--- baz (back-azimuth) - '+str(evgrp['baz'].shape)+'\n'
outstr += '--- proAngle (propagation angle) - '+str(evgrp['proAngle'].shape)+'\n'
outstr += '--- travelT (travel time) - '+str(evgrp['travelT'].shape)+'\n'
outstr += '--- reason_n (index array) - '+str(evgrp['reason_n'].shape)+'\n'
outstr += ' 0: accepted point \n' + \
' 1: data point the has large difference between v1HD and v1HD02 \n' + \
' 2: data point that does not have near neighbor points at all E/W/N/S directions\n' + \
' 3: slowness is too large/small \n' + \
' 4: near a zero field data point \n' + \
' 5: epicentral distance is too small \n' + \
' 6: large curvature \n'
try:
outstr += '--- reason_n_helm (index array for Helmoltz) - '+str(evgrp['reason_n_helm'].shape)+'\n'
outstr += ' 0 ~ 6: same as above \n' + \
' 7: reason_n of amplitude field is non-zero (invalid) \n' + \
' 8: negative phase slowness after correction \n'
except KeyError:
outstr += '*** NO reason_n_helm \n'
try:
subgroup= self['Eikonal_stack_%d' %runid]
outstr += '=============================================================================================================\n'
except KeyError:
outstr += '========================================== NO corresponding stacked results =================================\n'
return
if subgroup.attrs['anisotropic']:
tempstr = 'anisotropic'
outstr += '--- isotropic/anisotropic - '+tempstr+'\n'
outstr += '--- N_bin (number of bins, for ani run) - '+str(subgroup.attrs['N_bin'])+'\n'
outstr += '--- minazi/maxazi (min/max azi, for ani run) - '+str(subgroup.attrs['minazi'])+'/'+str(subgroup.attrs['maxazi'])+'\n'
else:
tempstr = 'isotropic'
pergrp = subgroup[perid]
outstr += '--- Nmeasure (number of raw measurements) - '+str(pergrp['Nmeasure'].shape)+'\n'
outstr += '--- NmeasureQC (number of qc measurements) - '+str(pergrp['NmeasureQC'].shape)+'\n'
outstr += '--- slowness - '+str(pergrp['slowness'].shape)+'\n'
outstr += '--- slowness_std - '+str(pergrp['slowness_std'].shape)+'\n'
outstr += '--- mask - '+str(pergrp['mask'].shape)+'\n'
outstr += '--- vel_iso (isotropic velocity) - '+str(pergrp['vel_iso'].shape)+'\n'
outstr += '--- vel_sem (uncertainties for velocity) - '+str(pergrp['vel_sem'].shape)+'\n'
if subgroup.attrs['anisotropic']:
outstr += '--- NmeasureAni (number of aniso measurements) - '+str(pergrp['NmeasureAni'].shape)+'\n'
outstr += '--- histArr (number of binned measurements) - '+str(pergrp['histArr'].shape)+'\n'
outstr += '--- slownessAni (aniso perturbation in slowness) - '+str(pergrp['slownessAni'].shape)+'\n'
outstr += '--- slownessAni_sem (uncertainties in slownessAni) - '+str(pergrp['slownessAni_sem'].shape)+'\n'
outstr += '--- velAni_sem (uncertainties in binned velocity) - '+str(pergrp['velAni_sem'].shape)+'\n'
print outstr
return
def set_input_parameters(self, minlon, maxlon, minlat, maxlat, pers=np.array([]), dlon=0.2, dlat=0.2, \
nlat_grad=1, nlon_grad=1, nlat_lplc=2, nlon_lplc=2, optimize_spacing=True):
"""
Set input parameters for tomographic inversion.
=================================================================================================================
::: input parameters :::
minlon, maxlon - minimum/maximum longitude
minlat, maxlat - minimum/maximum latitude
pers - period array, default = np.append( np.arange(18.)*2.+6., np.arange(4.)*5.+45.)
dlon, dlat - longitude/latitude interval
optimize_spacing- optimize the grid spacing or not
if True, the distance for input dlat/dlon will be calculated and dlat may be changed to
make the distance of dlat as close to the distance of dlon as possible
=================================================================================================================
"""
if pers.size==0:
pers = np.append( np.arange(18.)*2.+6., np.arange(4.)*5.+45.)
self.attrs.create(name = 'period_array', data=pers, dtype='f')
self.attrs.create(name = 'minlon', data=minlon, dtype='f')
self.attrs.create(name = 'maxlon', data=maxlon, dtype='f')
self.attrs.create(name = 'minlat', data=minlat, dtype='f')
self.attrs.create(name = 'maxlat', data=maxlat, dtype='f')
if optimize_spacing:
ratio = field2d_earth.determine_interval(minlat=minlat, maxlat=maxlat, dlon=dlon, dlat = dlat)
print '----------------------------------------------------------'
print 'Changed dlat from dlat =',dlat,'to dlat =',dlat/ratio
print '----------------------------------------------------------'
dlat = dlat/ratio
self.attrs.create(name = 'dlon', data=dlon)
self.attrs.create(name = 'dlat', data=dlat)
Nlon = int((maxlon-minlon)/dlon+1)
Nlat = int((maxlat-minlat)/dlat+1)
self.attrs.create(name = 'Nlon', data=Nlon)
self.attrs.create(name = 'Nlat', data=Nlat)
self.attrs.create(name = 'nlat_grad', data=nlat_grad)
self.attrs.create(name = 'nlon_grad', data=nlon_grad)
self.attrs.create(name = 'nlat_lplc', data=nlat_lplc)
self.attrs.create(name = 'nlon_lplc', data=nlon_lplc)
return
def xcorr_eikonal(self, inasdffname, workingdir, fieldtype='Tph', channel='ZZ', data_type='FieldDISPpmf2interp', runid=0,\
deletetxt=True, verbose=False, cdist=150., mindp=10):
"""
Compute gradient of travel time for cross-correlation data
=================================================================================================================
::: input parameters :::
inasdffname - input ASDF data file
workingdir - working directory
fieldtype - fieldtype (Tph or Tgr)
channel - channel for analysis (default = ZZ )
data_type - data type
(default='FieldDISPpmf2interp', aftan measurements with phase-matched filtering and jump correction)
runid - run id
deletetxt - delete output txt files in working directory
cdist - distance for nearneighbor station criteria
mindp - minnimum required number of data points for eikonal operator
=================================================================================================================
"""
if fieldtype!='Tph' and fieldtype!='Tgr':
raise ValueError('Wrong field type: '+fieldtype+' !')
# create new eikonal group
create_group = False
while (not create_group):
try:
group = self.create_group( name = 'Eikonal_run_'+str(runid) )
create_group= True
except:
runid += 1
continue
group.attrs.create(name = 'fieldtype', data=fieldtype[1:])
# input xcorr database
inDbase = pyasdf.ASDFDataSet(inasdffname)
# get header
pers = self.attrs['period_array']
minlon = self.attrs['minlon']
maxlon = self.attrs['maxlon']
minlat = self.attrs['minlat']
maxlat = self.attrs['maxlat']
dlon = self.attrs['dlon']
dlat = self.attrs['dlat']
nlat_grad = self.attrs['nlat_grad']
nlon_grad = self.attrs['nlon_grad']
nlat_lplc = self.attrs['nlat_lplc']
nlon_lplc = self.attrs['nlon_lplc']
fdict = { 'Tph': 2, 'Tgr': 3}
evLst = inDbase.waveforms.list()
for per in pers:
print '--- computing gradient for: '+str(per)+' sec'
del_per = per-int(per)
if del_per==0.:
persfx = str(int(per))+'sec'
else:
dper = str(del_per)
persfx = str(int(per))+'sec'+dper.split('.')[1]
working_per = workingdir+'/'+str(per)+'sec'
per_group = group.create_group( name='%g_sec'%( per ) )
for evid in evLst:
netcode1, stacode1 = evid.split('.')
try:
subdset = inDbase.auxiliary_data[data_type][netcode1][stacode1][channel][persfx]
except KeyError:
print ('No travel time field for: '+evid)
continue
if verbose:
print ('Event: '+evid)
lat1, elv1, lon1 = inDbase.waveforms[evid].coordinates.values()
if lon1<0.:
lon1 += 360.
dataArr = subdset.data.value
field2d = field2d_earth.Field2d(minlon=minlon, maxlon=maxlon, dlon=dlon,
minlat=minlat, maxlat=maxlat, dlat=dlat, period=per, evlo=lon1, evla=lat1, fieldtype=fieldtype, \
nlat_grad=nlat_grad, nlon_grad=nlon_grad, nlat_lplc=nlat_lplc, nlon_lplc=nlon_lplc)
Zarr = dataArr[:, fdict[fieldtype]]
# skip if not enough data points
if Zarr.size <= mindp:
continue
distArr = dataArr[:, 5]
field2d.read_array(lonArr=np.append(lon1, dataArr[:,0]), latArr=np.append(lat1, dataArr[:,1]), ZarrIn=np.append(0., distArr/Zarr) )
outfname = evid+'_'+fieldtype+'_'+channel+'.lst'
field2d.interp_surface(workingdir=working_per, outfname=outfname)
field2d.check_curvature(workingdir=working_per, outpfx=evid+'_'+channel+'_')
field2d.eikonal_operator(workingdir=working_per, inpfx=evid+'_'+channel+'_', nearneighbor=True, cdist=cdist)
# save data to hdf5 dataset
event_group = per_group.create_group(name=evid)
event_group.attrs.create(name = 'evlo', data=lon1)
event_group.attrs.create(name = 'evla', data=lat1)
# added 04/05/2018
event_group.attrs.create(name = 'Ntotal_grd', data=field2d.Ntotal_grd)
event_group.attrs.create(name = 'Nvalid_grd', data=field2d.Nvalid_grd)
#
appVdset = event_group.create_dataset(name='appV', data=field2d.appV)
reason_ndset = event_group.create_dataset(name='reason_n', data=field2d.reason_n)
proAngledset = event_group.create_dataset(name='proAngle', data=field2d.proAngle)
azdset = event_group.create_dataset(name='az', data=field2d.az)
bazdset = event_group.create_dataset(name='baz', data=field2d.baz)
Tdset = event_group.create_dataset(name='travelT', data=field2d.Zarr)
if deletetxt:
shutil.rmtree(workingdir)
return
def xcorr_eikonal_raydbase(self, inh5fname, workingdir, rayruntype=0, rayrunid=0, period=None, crifactor=0.5, crilimit=10.,\
fieldtype='Tph', channel='ZZ', data_type='FieldDISPpmf2interp', runid=0, deletetxt=True, verbose=False, cdist=150., mindp=10):
"""
Compute gradient of travel time for cross-correlation data according to ray tomography database
=================================================================================================================
::: input parameters :::
inasdffname - input ASDF data file
workingdir - working directory
fieldtype - fieldtype (Tph or Tgr)
channel - channel for analysis
data_type - data type
(default='FieldDISPpmf2interp', aftan measurements with phase-matched filtering and jump correction)
runid - run id
deletetxt - delete output txt files in working directory
cdist - distance for nearneighbor station criteria
mindp - minnimum required number of data points for eikonal operator
=================================================================================================================
"""
if fieldtype!='Tph' and fieldtype!='Tgr':
raise ValueError('Wrong field type: '+fieldtype+' !')
create_group = False
while (not create_group):
try:
group = self.create_group( name = 'Eikonal_run_'+str(runid) )
create_group= True
except:
runid += 1
continue
group.attrs.create(name = 'fieldtype', data=fieldtype[1:])
pers = self.attrs['period_array']
minlon = self.attrs['minlon']
maxlon = self.attrs['maxlon']
minlat = self.attrs['minlat']
maxlat = self.attrs['maxlat']
dlon = self.attrs['dlon']
dlat = self.attrs['dlat']
nlat_grad = self.attrs['nlat_grad']
nlon_grad = self.attrs['nlon_grad']
nlat_lplc = self.attrs['nlat_lplc']
nlon_lplc = self.attrs['nlon_lplc']
fdict = { 'Tph': 2, 'Tgr': 3}
if period is not None:
pers = np.array([period])
inDbase = h5py.File(inh5fname)
rundict = {0: 'smooth_run', 1: 'qc_run'}
data_id = rundict[rayruntype]+'_'+str(rayrunid)
ingroup = inDbase[data_id]
ind_flag = 1
if rayruntype == 0:
ind_flag = 0
else:
if ingroup.attrs['isotropic']:
ind_flag = 0
for per in pers:
print 'Computing gradient for: '+str(per)+' sec'
del_per = per-int(per)
if del_per==0.:
persfx = str(int(per))+'sec'
else:
dper = str(del_per)
persfx = str(int(per))+'sec'+dper.split('.')[1]
working_per = workingdir+'/'+str(per)+'sec'
per_group = group.create_group( name='%g_sec'%( per ) )
# get data array from ray tomography database
ray_per_id = '%g_sec'%( per )
data = ingroup[ray_per_id+'/residual'].value
res_tomo = data[:,7+ind_flag]
cri_res = min(crifactor*per, crilimit)
data = data[ np.abs(res_tomo)<cri_res , :]
evlo = 0.
evla = 0.
Ndata = data.shape[0]
i_event = 0
for i in range(Ndata):
if evla != data[i, 1] or evlo != data[i, 2]:
# compute
if i != 0:
field2d.read_array(lonArr = np.append(evlo, stlos), latArr=np.append(evla, stlas), ZarrIn=np.append(0., Zarr) )
outfname = evid+'_'+fieldtype+'_'+channel+'.lst'
print outfname, Zarr.size, stlos.size, stlas.size
field2d.interp_surface(workingdir=working_per, outfname=outfname)
field2d.check_curvature(workingdir=working_per, outpfx=evid+'_'+channel+'_')
field2d.eikonal_operator(workingdir=working_per, inpfx=evid+'_'+channel+'_', nearneighbor=True, cdist=cdist)
# save data to hdf5 dataset
event_group = per_group.create_group(name=evid)
event_group.attrs.create(name = 'evlo', data=evlo)
event_group.attrs.create(name = 'evla', data=evla)
# added 04/05/2018
event_group.attrs.create(name = 'Ntotal_grd', data=field2d.Ntotal_grd)
event_group.attrs.create(name = 'Nvalid_grd', data=field2d.Nvalid_grd)
#
appVdset = event_group.create_dataset(name='appV', data=field2d.appV)
reason_ndset = event_group.create_dataset(name='reason_n', data=field2d.reason_n)
proAngledset = event_group.create_dataset(name='proAngle', data=field2d.proAngle)
azdset = event_group.create_dataset(name='az', data=field2d.az)
bazdset = event_group.create_dataset(name='baz', data=field2d.baz)
Tdset = event_group.create_dataset(name='travelT', data=field2d.Zarr)
evla = data[i, 1]
evlo = data[i, 2]
field2d = field2d_earth.Field2d(minlon=minlon, maxlon=maxlon, dlon=dlon,
minlat=minlat, maxlat=maxlat, dlat=dlat, period=per, evlo=evlo, evla=evla, fieldtype=fieldtype, \
nlat_grad=nlat_grad, nlon_grad=nlon_grad, nlat_lplc=nlat_lplc, nlon_lplc=nlon_lplc)
stlas = np.array([])
stlos = np.array([])
Zarr = np.array([])
i_event += 1
evid = 'ALK'+str(i_event)
stla = data[i, 3]
stlo = data[i, 4]
stlas = np.append(stlas, stla)
stlos = np.append(stlos, stlo)
dist, az, baz \
= obspy.geodetics.gps2dist_azimuth(evla, evlo, stla, stlo)
travelT = dist/data[i, 5]/1000.
Zarr = np.append(Zarr, travelT)
if deletetxt:
shutil.rmtree(workingdir)
return
def xcorr_eikonal_mp(self, inasdffname, workingdir, fieldtype='Tph', channel='ZZ', data_type='FieldDISPpmf2interp',\
runid=0, new_group=True, deletetxt=True, verbose=False, subsize=1000, nprocess=None, cdist=150., mindp=10, pers=None):
"""
Compute gradient of travel time for cross-correlation data with multiprocessing
=================================================================================================================
::: input parameters :::
inh5fname - input hdf5 data file
workingdir - working directory
fieldtype - fieldtype (Tph or Tgr)
channel - channel for analysis (default = ZZ )
data_type - data type
(default='FieldDISPpmf2interp', aftan measurements with phase-matched filtering and jump correction)
runid - run id
deletetxt - delete output txt files in working directory
subsize - subsize of processing list, use to prevent lock in multiprocessing process
nprocess - number of processes
cdist - distance for nearneighbor station criteria
mindp - minnimum required number of data points for eikonal operator
=================================================================================================================
"""
if fieldtype!='Tph' and fieldtype!='Tgr':
raise ValueError('Wrong field type: '+fieldtype+' !')
if new_group:
create_group = False
while (not create_group):
try:
group = self.create_group( name = 'Eikonal_run_'+str(runid) )
create_group= True
except:
runid += 1
continue
else:
group = self.require_group( name = 'Eikonal_run_'+str(runid) )
group.attrs.create(name = 'fieldtype', data=fieldtype[1:])
# input xcorr database
inDbase = pyasdf.ASDFDataSet(inasdffname)
# header information
if isinstance(pers, np.ndarray):
pers_dbase = self.attrs['period_array']
for per in pers:
if not (per in pers_dbase):
raise KeyError('Period '+str(per)+' s in the database attributes')
else:
pers = self.attrs['period_array']
minlon = self.attrs['minlon']
maxlon = self.attrs['maxlon']
minlat = self.attrs['minlat']
maxlat = self.attrs['maxlat']
dlon = self.attrs['dlon']
dlat = self.attrs['dlat']
nlat_grad = self.attrs['nlat_grad']
nlon_grad = self.attrs['nlon_grad']
nlat_lplc = self.attrs['nlat_lplc']
nlon_lplc = self.attrs['nlon_lplc']
fdict = { 'Tph': 2, 'Tgr': 3}
evLst = inDbase.waveforms.list()
fieldLst = []
#------------------------
# prepare data
#------------------------
for per in pers:
print '--- preparing data for gradient computation of '+str(per)+' sec'
del_per = per-int(per)
if del_per==0.:
persfx = str(int(per))+'sec'
else:
dper = str(del_per)
persfx = str(int(per))+'sec'+dper.split('.')[1]
working_per = workingdir+'/'+str(per)+'sec'
if not os.path.isdir(working_per):
os.makedirs(working_per)
for evid in evLst:
netcode1, stacode1 = evid.split('.')
try:
subdset = inDbase.auxiliary_data[data_type][netcode1][stacode1][channel][persfx]
except KeyError:
if verbose:
print 'No travel time field for: '+evid
continue
lat1, elv1, lon1 = inDbase.waveforms[evid].coordinates.values()
if lon1<0.:
lon1 += 360.
dataArr = subdset.data.value
field2d = field2d_earth.Field2d(minlon=minlon, maxlon=maxlon, dlon=dlon, minlat=minlat, maxlat=maxlat, dlat=dlat,
period=per, evlo=lon1, evla=lat1, fieldtype=fieldtype, evid=evid, \
nlat_grad=nlat_grad, nlon_grad=nlon_grad, nlat_lplc=nlat_lplc, nlon_lplc=nlon_lplc)
Zarr = dataArr[:, fdict[fieldtype]]
if Zarr.size <= mindp:
continue
distArr = dataArr[:, 5]
field2d.read_array(lonArr=np.append(lon1, dataArr[:,0]), latArr=np.append(lat1, dataArr[:,1]), ZarrIn=np.append(0., distArr/Zarr) )
fieldLst.append(field2d)
#-----------------------------------------
# Computing gradient with multiprocessing
#-----------------------------------------
if len(fieldLst) > subsize:
Nsub = int(len(fieldLst)/subsize)
for isub in range(Nsub):
print '--- eikonal computation subset:', isub,'in',Nsub,'sets'
cfieldLst = fieldLst[isub*subsize:(isub+1)*subsize]
EIKONAL = partial(eikonal4mp, workingdir=workingdir, channel=channel, cdist=cdist)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(EIKONAL, cfieldLst) #make our results with a map call
pool.close() #we are not adding any more processes
pool.join() #tell it to wait until all threads are done before going on
cfieldLst = fieldLst[(isub+1)*subsize:]
EIKONAL = partial(eikonal4mp, workingdir=workingdir, channel=channel, cdist=cdist)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(EIKONAL, cfieldLst) #make our results with a map call
pool.close() #we are not adding any more processes
pool.join() #tell it to wait until all threads are done before going on
else:
print '--- eikonal computation, one set'
EIKONAL = partial(eikonal4mp, workingdir=workingdir, channel=channel, cdist=cdist)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(EIKONAL, fieldLst) #make our results with a map call
pool.close() #we are not adding any more processes
pool.join() #tell it to wait until all threads are done before going on