-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathASDFDBase.py
3360 lines (3266 loc) · 192 KB
/
ASDFDBase.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 for seismic data analysis based on ASDF database
:Methods:
aftan analysis (use pyaftan or aftanf77)
C3(Correlation of coda of Cross-Correlation) computation
python wrapper for Barmin's surface wave tomography Code
Automatic Receiver Function Analysis( Iterative Deconvolution and Harmonic Stripping )
Eikonal Tomography
Helmholtz Tomography
Stacking/Rotation for Cross-Correlation Results from SEED2CORpp
Bayesian Monte Carlo Inversion of Surface Wave and Receiver Function datasets (To be added soon)
:Dependencies:
numpy >=1.9.1
scipy >=0.18.0
matplotlib >=1.4.3
ObsPy >=1.0.1
pyfftw 0.10.3 (optional)
:Copyright:
Author: Lili Feng
Graduate Research Assistant
CIEI, Department of Physics, University of Colorado Boulder
email: lili.feng@colorado.edu
"""
import pyasdf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as plb
import matplotlib.dates as mdates
from matplotlib.colors import LightSource
import obspy
import warnings
import copy
import os, shutil
import numba
from functools import partial
import multiprocessing
import pyaftan
from subprocess import call
from obspy.clients.fdsn.client import Client
from mpl_toolkits.basemap import Basemap, shiftgrid, cm
import obspy.signal.array_analysis
from obspy.imaging.cm import obspy_sequential
from pyproj import Geod
from obspy.taup import TauPyModel
import CURefPy
import glob
import pycpt
from netCDF4 import Dataset
# from obspy.signal.invsim import corn_freq_2_paz
sta_info_default={'rec_func': 0, 'xcorr': 1, 'isnet': 0}
xcorr_header_default={'netcode1': '', 'stacode1': '', 'netcode2': '', 'stacode2': '', 'chan1': '', 'chan2': '',
'npts': 12345, 'b': 12345, 'e': 12345, 'delta': 12345, 'dist': 12345, 'az': 12345, 'baz': 12345, 'stackday': 0}
xcorr_sacheader_default = {'knetwk': '', 'kstnm': '', 'kcmpnm': '', 'stla': 12345, 'stlo': 12345,
'kuser0': '', 'kevnm': '', 'evla': 12345, 'evlo': 12345, 'evdp': 0., 'dist': 0., 'az': 12345, 'baz': 12345,
'delta': 12345, 'npts': 12345, 'user0': 0, 'b': 12345, 'e': 12345}
ref_header_default = {'otime': '', 'network': '', 'station': '', 'stla': 12345, 'stlo': 12345, 'evla': 12345, 'evlo': 12345, 'evdp': 0.,
'dist': 0., 'az': 12345, 'baz': 12345, 'delta': 12345, 'npts': 12345, 'b': 12345, 'e': 12345, 'arrival': 12345, 'phase': '',
'tbeg': 12345, 'tend': 12345, 'hslowness': 12345, 'ghw': 12345, 'VR': 12345, 'moveout': -1}
monthdict={1: 'JAN', 2: 'FEB', 3: 'MAR', 4: 'APR', 5: 'MAY', 6: 'JUN', 7: 'JUL', 8: 'AUG', 9: 'SEP', 10: 'OCT', 11: 'NOV', 12: 'DEC'}
geodist = Geod(ellps='WGS84')
taupmodel = TauPyModel(model="iasp91")
class noiseASDF(pyasdf.ASDFDataSet):
""" An object to for ambient noise cross-correlation analysis based on ASDF database
"""
# def init_working_env(self, datadir, workingdir):
# self.datadir = datadir
# self.workingdir = workingdir
def write_stationxml(self, staxml, source='CIEI'):
inv=obspy.core.inventory.inventory.Inventory(networks=[], source=source)
for staid in self.waveforms.list():
inv+=self.waveforms[staid].StationXML
inv.write(staxml, format='stationxml')
return
def write_stationtxt(self, stafile):
"""Write obspy inventory to txt station list(format used in SEED2COR)
"""
try:
auxiliary_info=self.auxiliary_data.StaInfo
isStaInfo=True
except:
isStaInfo=False
with open(stafile, 'w') as f:
for staid in self.waveforms.list():
stainv=self.waveforms[staid].StationXML
netcode=stainv.networks[0].code
stacode=stainv.networks[0].stations[0].code
lon=stainv.networks[0].stations[0].longitude
lat=stainv.networks[0].stations[0].latitude
if isStaInfo:
staid_aux=netcode+'/'+stacode
ccflag=auxiliary_info[staid_aux].parameters['xcorr']
f.writelines('%s %3.4f %3.4f %d %s\n' %(stacode, lon, lat, ccflag, netcode) )
else:
f.writelines('%s %3.4f %3.4f %s\n' %(stacode, lon, lat, netcode) )
return
def read_stationtxt(self, stafile, source='CIEI', chans=['BHZ', 'BHE', 'BHN'], dnetcode='TA'):
"""Read txt station list
"""
sta_info=sta_info_default.copy()
with open(stafile, 'r') as f:
Sta=[]
site=obspy.core.inventory.util.Site(name='01')
creation_date=obspy.core.utcdatetime.UTCDateTime(0)
inv=obspy.core.inventory.inventory.Inventory(networks=[], source=source)
total_number_of_channels=len(chans)
for lines in f.readlines():
lines=lines.split()
stacode=lines[0]
lon=float(lines[1])
lat=float(lines[2])
netcode=dnetcode
ccflag=None
if len(lines)==5:
try:
ccflag=int(lines[3])
netcode=lines[4]
except ValueError:
ccflag=int(lines[4])
netcode=lines[3]
if len(lines)==4:
try:
ccflag=int(lines[3])
except ValueError:
netcode=lines[3]
netsta=netcode+'.'+stacode
if Sta.__contains__(netsta):
index=Sta.index(netsta)
if abs(self[index].lon-lon) >0.01 and abs(self[index].lat-lat) >0.01:
raise ValueError('Incompatible Station Location:' + netsta+' in Station List!')
else:
print 'Warning: Repeated Station:' +netsta+' in Station List!'
continue
channels=[]
if lon>180.:
lon-=360.
for chan in chans:
channel=obspy.core.inventory.channel.Channel(code=chan, location_code='01', latitude=lat, longitude=lon,
elevation=0.0, depth=0.0)
channels.append(channel)
station=obspy.core.inventory.station.Station(code=stacode, latitude=lat, longitude=lon, elevation=0.0,
site=site, channels=channels, total_number_of_channels = total_number_of_channels, creation_date = creation_date)
network=obspy.core.inventory.network.Network(code=netcode, stations=[station])
networks=[network]
inv+=obspy.core.inventory.inventory.Inventory(networks=networks, source=source)
staid_aux=netcode+'/'+stacode
if ccflag!=None:
sta_info['xcorr']=ccflag
self.add_auxiliary_data(data=np.array([]), data_type='StaInfo', path=staid_aux, parameters=sta_info)
print 'Writing obspy inventory to ASDF dataset'
self.add_stationxml(inv)
print 'End writing obspy inventory to ASDF dataset'
return
def read_stationtxt_ind(self, stafile, source='CIEI', chans=['BHZ', 'BHE', 'BHN'], s_ind=1, lon_ind=2, lat_ind=3, n_ind=0):
"""Read txt station list, column index can be changed
"""
sta_info=sta_info_default.copy()
with open(stafile, 'r') as f:
Sta=[]
site=obspy.core.inventory.util.Site(name='01')
creation_date=obspy.core.utcdatetime.UTCDateTime(0)
inv=obspy.core.inventory.inventory.Inventory(networks=[], source=source)
total_number_of_channels=len(chans)
for lines in f.readlines():
lines=lines.split()
stacode=lines[s_ind]
lon=float(lines[lon_ind])
lat=float(lines[lat_ind])
netcode=lines[n_ind]
netsta=netcode+'.'+stacode
if Sta.__contains__(netsta):
index=Sta.index(netsta)
if abs(self[index].lon-lon) >0.01 and abs(self[index].lat-lat) >0.01:
raise ValueError('Incompatible Station Location:' + netsta+' in Station List!')
else:
print 'Warning: Repeated Station:' +netsta+' in Station List!'
continue
channels=[]
if lon>180.:
lon-=360.
for chan in chans:
channel=obspy.core.inventory.channel.Channel(code=chan, location_code='01', latitude=lat, longitude=lon,
elevation=0.0, depth=0.0)
channels.append(channel)
station=obspy.core.inventory.station.Station(code=stacode, latitude=lat, longitude=lon, elevation=0.0,
site=site, channels=channels, total_number_of_channels = total_number_of_channels, creation_date = creation_date)
network=obspy.core.inventory.network.Network(code=netcode, stations=[station])
networks=[network]
inv+=obspy.core.inventory.inventory.Inventory(networks=networks, source=source)
staid_aux=netcode+'/'+stacode
self.add_auxiliary_data(data=np.array([]), data_type='StaInfo', path=staid_aux, parameters=sta_info)
print 'Writing obspy inventory to ASDF dataset'
self.add_stationxml(inv)
print 'End writing obspy inventory to ASDF dataset'
return
def get_limits_lonlat(self):
"""Get the geographical limits of the stations
"""
staLst=self.waveforms.list()
minlat=90.
maxlat=-90.
minlon=360.
maxlon=0.
for staid in staLst:
lat, elv, lon=self.waveforms[staid].coordinates.values()
if lon<0: lon+=360.
minlat=min(lat, minlat)
maxlat=max(lat, maxlat)
minlon=min(lon, minlon)
maxlon=max(lon, maxlon)
print 'latitude range: ', minlat, '-', maxlat, 'longitude range:', minlon, '-', maxlon
self.minlat=minlat; self.maxlat=maxlat; self.minlon=minlon; self.maxlon=maxlon
return
def _get_basemap(self, projection='lambert', geopolygons=None, resolution='i'):
"""Get basemap for plotting results
"""
# fig=plt.figure(num=None, figsize=(12, 12), dpi=80, facecolor='w', edgecolor='k')
try:
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
except AttributeError:
self.get_limits_lonlat()
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
lat_centre = (maxlat+minlat)/2.0
lon_centre = (maxlon+minlon)/2.0
if projection=='merc':
m=Basemap(projection='merc', llcrnrlat=minlat-5., urcrnrlat=maxlat+5., llcrnrlon=minlon-5.,
urcrnrlon=maxlon+5., lat_ts=20, resolution=resolution)
m.drawparallels(np.arange(-80.0,80.0,5.0), labels=[1,0,0,1])
m.drawmeridians(np.arange(-170.0,170.0,5.0), labels=[1,0,0,1])
m.drawstates(color='g', linewidth=2.)
elif projection=='global':
m=Basemap(projection='ortho',lon_0=lon_centre, lat_0=lat_centre, resolution=resolution)
elif projection=='regional_ortho':
m1 = Basemap(projection='ortho', lon_0=minlon, lat_0=minlat, resolution='l')
m = Basemap(projection='ortho', lon_0=minlon, lat_0=minlat, resolution=resolution,\
llcrnrx=0., llcrnry=0., urcrnrx=m1.urcrnrx/mapfactor, urcrnry=m1.urcrnry/3.5)
m.drawparallels(np.arange(-80.0,80.0,10.0), labels=[1,0,0,0], linewidth=2, fontsize=20)
m.drawmeridians(np.arange(-170.0,170.0,10.0), linewidth=2)
elif projection=='lambert':
distEW, az, baz=obspy.geodetics.gps2dist_azimuth(minlat, minlon, minlat, maxlon) # distance is in m
distNS, az, baz=obspy.geodetics.gps2dist_azimuth(minlat, minlon, maxlat+2., minlon) # distance is in m
m = Basemap(width=distEW, height=distNS, rsphere=(6378137.00,6356752.3142), resolution='l', projection='lcc',\
lat_1=minlat-2, lat_2=maxlat, lon_0=lon_centre, lat_0=lat_centre+1)
m.drawparallels(np.arange(-80.0,80.0,5.0), linewidth=1, dashes=[2,2], labels=[1,1,0,0], fontsize=15)
m.drawmeridians(np.arange(-170.0,170.0,5.0), linewidth=1, dashes=[2,2], labels=[0,0,1,0], fontsize=15)
m.drawcoastlines(linewidth=1.0)
m.drawcountries(linewidth=1.)
# m.fillcontinents(lake_color='#99ffff',zorder=0.2)
m.drawmapboundary(fill_color="white")
try:
geopolygons.PlotPolygon(inbasemap=m)
except:
pass
return m
def _my_get_basemap(self, geopolygons=None, epsg=4269, xpixels=20000): #epsg code for America is 4269
"""Get basemap for plotting results. Use arcgisimage() to get high resolution background.
Revised by Hongda, NOV 2016
"""
try:
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
except AttributeError:
self.get_limits_lonlat()
minlon=self.minlon-2.; maxlon=self.maxlon+2.; minlat=self.minlat-2.; maxlat=self.maxlat+2.
m = Basemap(llcrnrlon=minlon,llcrnrlat=minlat,urcrnrlon=maxlon,urcrnrlat=maxlat, epsg=epsg)
m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = xpixels, verbose=False)
m.drawcoastlines(linewidth=1.0)
m.drawcountries(linewidth=1.0)
# m.fillcontinents(lake_color='#99ffff',zorder=0.2)
m.drawmapboundary(fill_color="white")
try:
geopolygons.PlotPolygon(inbasemap=m)
except:
pass
return m
def _my_2nd_get_basemap(self, projection='lambert', geopolygons=None, resolution='i'):
"""Get basemap for plotting results. Use the etopo1 file to generate colored mesh as the basemap for high resolution background.
Revised by Hongda, NOV 2016
"""
try:
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
except AttributeError:
self.get_limits_lonlat()
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
lat_centre = (maxlat+minlat)/2.0
lon_centre = (maxlon+minlon)/2.0
if projection=='merc':
m=Basemap(projection='merc', llcrnrlat=minlat-5., urcrnrlat=maxlat+5., llcrnrlon=minlon-5.,
urcrnrlon=maxlon+5., lat_ts=20, resolution=resolution)
m.drawparallels(np.arange(-80.0,80.0,5.0), labels=[1,0,0,1])
m.drawmeridians(np.arange(-170.0,170.0,5.0), labels=[1,0,0,1])
m.drawstates(color='g', linewidth=2.)
elif projection=='global':
m=Basemap(projection='ortho',lon_0=lon_centre, lat_0=lat_centre, resolution=resolution)
elif projection=='regional_ortho':
m1 = Basemap(projection='ortho', lon_0=minlon, lat_0=minlat, resolution='l')
m = Basemap(projection='ortho', lon_0=minlon, lat_0=minlat, resolution=resolution,\
llcrnrx=0., llcrnry=0., urcrnrx=m1.urcrnrx/mapfactor, urcrnry=m1.urcrnry/3.5)
m.drawparallels(np.arange(-80.0,80.0,10.0), labels=[1,0,0,0], linewidth=2, fontsize=20)
m.drawmeridians(np.arange(-170.0,170.0,10.0), linewidth=2)
elif projection=='lambert':
distEW, az, baz=obspy.geodetics.gps2dist_azimuth(minlat, minlon, minlat, maxlon) # distance is in m
distNS, az, baz=obspy.geodetics.gps2dist_azimuth(minlat, minlon, maxlat+2., minlon) # distance is in m
m = Basemap(width=distEW, height=distNS, rsphere=(6378137.00,6356752.3142), resolution=resolution, projection='lcc',\
lat_1=minlat-1, lat_2=maxlat+1, lon_0=lon_centre, lat_0=lat_centre)
m.drawparallels(np.arange(-80.0,80.0,5.0), linewidth=1, dashes=[2,2], labels=[1,1,0,0], fontsize=15)
m.drawmeridians(np.arange(-170.0,170.0,5.0), linewidth=1, dashes=[2,2], labels=[0,0,1,0], fontsize=15)
m.drawcoastlines(linewidth=1.0)
m.drawcountries(linewidth=1.0)
"""
Use the etopo1 file to draw a colored mesh as the basemap. Hongda, Nov 2016
"""
mycm=pycpt.load.gmtColormap('/projects/howa1663/Code/ToolKit/Models/ETOPO1/ETOPO1.cpt')
etopo1 = Dataset('/projects/howa1663/Code/ToolKit/Models/ETOPO1/ETOPO1_Ice_g_gmt4.grd', 'r') # read in the etopo1 file which was used as the basemap
lons = etopo1.variables["x"][:]
west = lons<0 # mask array with negetive longitudes
west = 360.*west*np.ones(len(lons))
lons = lons+west
lats = etopo1.variables["y"][:]
z = etopo1.variables["z"][:]
etopoz=z[(lats>(minlat-2))*(lats<(maxlat+2)), :]
etopoz=etopoz[:, (lons>(minlon-2))*(lons<(maxlon+2))]
lats=lats[(lats>(minlat-2))*(lats<(maxlat+2))]
lons=lons[(lons>(minlon-2))*(lons<(maxlon+2))]
x, y = m(*np.meshgrid(lons,lats))
m.pcolormesh(x, y, etopoz, shading='gouraud', cmap=mycm, vmin=etopoz.min(), vmax=(etopoz.max()+400))
m.drawmapboundary(fill_color="white")
try:
geopolygons.PlotPolygon(inbasemap=m)
except:
pass
return m
def _my_3rd_get_basemap(self, projection='lambert', geopolygons=None, resolution='i', azdeg=315, altdeg=45, blend_mode='soft', bound=True):
"""Get basemap for plotting results. Use the etopo1 file to generate colored mesh as the basemap for high resolution background.
Add shading to impove basemap detail, enable showing gradient.
-- Hongda, Jan 2017
--------------------------------------------------------------------------------------------------------------------------------
Parameters:
projection: choose different projection types
geoploygons:
resolution:
zadeg: azimuth in degree(from the North) of the light source
altdeg: altitude in degree(from the horizontal) of the light source
blend_mode: blend_mode of the shading, i.e.: overlay, hsv, soft...
bound: draw plate boundaries. True or False
"""
try:
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
except AttributeError:
self.get_limits_lonlat()
minlon=self.minlon; maxlon=self.maxlon; minlat=self.minlat; maxlat=self.maxlat
lat_centre = (maxlat+minlat)/2.0
lon_centre = (maxlon+minlon)/2.0
if projection=='merc':
m=Basemap(projection='merc', llcrnrlat=minlat-5., urcrnrlat=maxlat+5., llcrnrlon=minlon-5.,
urcrnrlon=maxlon+5., lat_ts=20, resolution=resolution)
m.drawparallels(np.arange(-80.0,80.0,5.0), labels=[1,0,0,1])
m.drawmeridians(np.arange(-170.0,170.0,5.0), labels=[1,0,0,1])
m.drawstates(color='g', linewidth=2.)
elif projection=='global':
m=Basemap(projection='ortho',lon_0=lon_centre, lat_0=lat_centre, resolution=resolution)
elif projection=='regional_ortho':
m1 = Basemap(projection='ortho', lon_0=minlon, lat_0=minlat, resolution='l')
m = Basemap(projection='ortho', lon_0=minlon, lat_0=minlat, resolution=resolution,\
llcrnrx=0., llcrnry=0., urcrnrx=m1.urcrnrx/mapfactor, urcrnry=m1.urcrnry/3.5)
m.drawparallels(np.arange(-80.0,80.0,10.0), labels=[1,0,0,0], linewidth=2, fontsize=20)
m.drawmeridians(np.arange(-170.0,170.0,10.0), linewidth=2)
elif projection=='lambert':
distEW, az, baz=obspy.geodetics.gps2dist_azimuth(minlat, minlon, minlat, maxlon) # distance is in m
distNS, az, baz=obspy.geodetics.gps2dist_azimuth(minlat, minlon, maxlat+2., minlon) # distance is in m
m = Basemap(width=distEW, height=distNS, rsphere=(6378137.00,6356752.3142), resolution=resolution, projection='lcc',\
lat_1=minlat-1, lat_2=maxlat+1, lon_0=lon_centre, lat_0=lat_centre)
m.drawparallels(np.arange(-80.0,80.0,5.0), linewidth=1, dashes=[2,2], labels=[1,1,0,0], fontsize=15)
m.drawmeridians(np.arange(-170.0,170.0,5.0), linewidth=1, dashes=[2,2], labels=[0,0,0,1], fontsize=15)
m.drawcoastlines(linewidth=1.0)
m.drawcountries(linewidth=1.0)
m.drawstates(linewidth=1.0)
if bound:
try:
m.readshapefile('/projects/howa1663/Code/ToolKit/Models/Plates/PB2002_plates', name='PB2002_plates', drawbounds=True, linewidth=1, color='orange') # draw plate boundary on basemap
except IOError:
print("Couldn't read shape file! Continue without drawing plateboundaries")
try:
mycm=pycpt.load.gmtColormap('/projects/howa1663/Code/ToolKit/Models/ETOPO1/ETOPO1.cpt')
etopo1 = Dataset('/projects/howa1663/Code/ToolKit/Models/ETOPO1/ETOPO1_Ice_g_gmt4.grd', 'r') # read in the etopo1 file which was used as the basemap
except IOError:
print("Couldn't read etopo data or color map file! Check file directory!")
lons = etopo1.variables["x"][:]
west = lons<0 # mask array with negetive longitudes
west = 360.*west*np.ones(len(lons))
lons = lons+west
lats = etopo1.variables["y"][:]
z = etopo1.variables["z"][:]
etopoz=z[(lats>(minlat-2))*(lats<(maxlat+2)), :]
etopoz=etopoz[:, (lons>(minlon-2))*(lons<(maxlon+2))]
lats=lats[(lats>(minlat-2))*(lats<(maxlat+2))]
lons=lons[(lons>(minlon-2))*(lons<(maxlon+2))]
etopoZ = m.transform_scalar(etopoz, lons-360*(lons>180)*np.ones(len(lons)), lats, etopoz.shape[0], etopoz.shape[1]) # tranform the altitude grid into the projected coordinate
ls = LightSource(azdeg=azdeg, altdeg=altdeg)
rgb = ls.shade(etopoZ, cmap=mycm, vert_exag=0.05, blend_mode=blend_mode)
m.imshow(rgb)
m.drawmapboundary(fill_color="white")
try:
geopolygons.PlotPolygon(inbasemap=m)
except:
pass
return m
def plot_stations(self, projection='lambert', geopolygons=None, showfig=True):
# self.minlon=85; self.maxlon=125; self.minlat=25; self.maxlat=45
staLst=self.waveforms.list()
stalons=np.array([]); stalats=np.array([])
for staid in staLst:
stla, evz, stlo=self.waveforms[staid].coordinates.values()
stalons=np.append(stalons, stlo); stalats=np.append(stalats, stla)
m=self._get_basemap(projection=projection, geopolygons=geopolygons)
m.etopo()
# m.shadedrelief()
stax, stay=m(stalons, stalats)
m.plot(stax, stay, 'ko', markersize=8)
# plt.title(str(self.period)+' sec', fontsize=20)
if showfig: plt.show()
def my_plot_stations(self, projection='lambert', geopolygons=None, resolution='i', title='', showfig=True, bound=True): #(self, geopolygons=None, epsg=4269, xpixels=20000, showfig=True):
# Hongda's plot_stations. Add flag to use different markers for different "networks".
staLst=self.waveforms.list()
stalons=np.array([]); stalats=np.array([]); staflags=np.array([]);netcodes=np.array([]);stacodes=np.array([])
for staid in staLst:
stla, evz, stlo=self.waveforms[staid].coordinates.values()
stalons = np.append(stalons, stlo); stalats=np.append(stalats, stla)
netcode = self.waveforms[staid].StationXML.networks[0].code
netcodes = np.append(netcodes, netcode)
stacode = self.waveforms[staid].StationXML.networks[0].stations[0].code
stacodes = np.append(stacodes, stacode)
stafl = self.auxiliary_data.StaInfo[netcode][stacode].parameters['xcorr']
staflags = np.append(staflags, stafl) # the type of maker used for the station depends on staflags%10, if staflags>10, tag the station name
m = self._my_3rd_get_basemap(projection=projection, geopolygons=geopolygons, resolution=resolution, bound=bound)
# m.shadedrelief()
stax, stay = m(stalons, stalats)
for i in range(len(stalons)):
if staflags[i]%10 == 0:
m.plot(stax[i], stay[i], 'gs', markersize=10)
elif staflags[i]%10 == 1:
m.plot(stax[i], stay[i], 'b^', markersize=10)
elif staflags[i]%10 == 2:
m.plot(stax[i], stay[i], 'ro', markersize=10)
elif staflags[i]% 10 == 3:
m.plot(stax[i], stay[i], 'cp', markersize=10)
elif staflags[i]% 10 == 4:
m.plot(stax[i], stay[i], 'yp', markersize=10)
elif staflags[i]%10 == 5:
m.plot(stax[i], stay[i], 'go', markersize=10, mec="black")
elif staflags[i]%10 == 6:
m.plot(stax[i], stay[i], 'cp', markersize=10)
elif staflags[i]%10 == 7:
m.plot(stax[i], stay[i], 'rp', markersize=10)
elif staflags[i]%10 == 8:
m.plot(stax[i], stay[i], 'wo', markersize=10, mec="black")
elif staflags[i]%10 == 9:
m.plot(stax[i], stay[i], 'ws', markersize=10, mec="black")
else:
print "The flag for marking " + stacodes[i] + " is wrong(not an integer)"
if staflags[i] >= 10:
plt.text(stax[i]-5000, stay[i]-5000, '%s' % (stacodes[i]), color='w')
# for j in range(int(len(stalons)/5)): # decide which stations that you want to add station name besides them
# plt.text(stax[5*j]-5000, stay[5*j]-5000, '%s' % (stacodes[5*j]))
# plt.title(str(self.period)+' sec', fontsize=20)
plt.title(title, fontsize=15)
if showfig: plt.show()
def my_plot_sta_with_path(self, projection='lambert', geopolygons=None, resolution='i', tag_name=np.array([]), used_staLst=np.array([]), pathLst=np.array([]), bound=True):
"""
Plot stations used for tomography and those paths which was removed
tag_name: the stations that you want to mark their names, you have to the where these stations are in the staLst which is hard, modification needed!
used_staLst: The station list that was used, used_staLst[0,:]: latitude, used_staLst[1,:]: longitude. Each station will appear multiple times
"""
m = self._my_3rd_get_basemap(projection=projection, geopolygons=geopolygons, resolution=resolution, bound=bound)
staLat = np.array([]); staLon = np.array([]); staN = np.array([])# Full station list, each station only appear once [0]lat, [1]lon, [2] path number this station has
for i in range(used_staLst.shape[1]):
if not used_staLst[0,i] in staLat:
staLat = np.append(staLat, used_staLst[0,i])
staLon = np.append(staLon, used_staLst[1,i])
staN = np.append(staN,1)
elif not used_staLst[1,i] in staLon[np.where(staLat==used_staLst[0,i])]:
staLat = np.append(staLat, used_staLst[0,i])
staLon = np.append(staLon, used_staLst[1,i])
staN = np.append(staN,1)
else:
ind1 = np.in1d(staLat,used_staLst[0,i]) & np.in1d(staLon,used_staLst[1,i])
ind1 = np.where(ind1==True)
if ind1[0].size != 1:
print "Find " + str(ind1[0].size) + " stations with the same latitude and longitude"
staN[ind1] += 1 # increase the count of this station's appearence
stax, stay = m(staLon, staLat)
evx, evy = m(pathLst[1], pathLst[0])
stx, sty = m(pathLst[3], pathLst[2])
for j in range(pathLst.shape[1]):
m.plot([evx[j], stx[j]],[evy[j],sty[j]], c='grey', zorder=1)
plt.scatter(stax, stay, c=staN, cmap='rainbow', vmin=staN.min(), vmax=staN.max(), zorder=2, s=150)
plt.colorbar()
for k in tag_name: # Tag the station name
plt.text(stax[k]-5000, stay[k]-5000, '%s' % (stacodes[k]))
# plt.title(str(self.period)+' sec', fontsize=20)
plt.show()
def wsac_xcorr(self, netcode1, stacode1, netcode2, stacode2, chan1, chan2, outdir='.', pfx='COR'):
"""Write cross-correlation data from ASDF to sac file
==============================================================================
Input Parameters:
netcode1, stacode1, chan1 - network/station/channel name for station 1
netcode2, stacode2, chan2 - network/station/channel name for station 2
outdir - output directory
pfx - prefix
Output:
e.g. outdir/COR/TA.G12A/COR_TA.G12A_BHT_TA.R21A_BHT.SAC
==============================================================================
"""
subdset=self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2][chan1][chan2]
sta1=self.waveforms[netcode1+'.'+stacode1].StationXML.networks[0].stations[0]
sta2=self.waveforms[netcode2+'.'+stacode2].StationXML.networks[0].stations[0]
xcorr_sacheader=xcorr_sacheader_default.copy()
xcorr_sacheader['kuser0']=netcode1
xcorr_sacheader['kevnm']=stacode1
xcorr_sacheader['knetwk']=netcode2
xcorr_sacheader['kstnm']=stacode2
xcorr_sacheader['kcmpnm']=chan1+chan2
xcorr_sacheader['evla']=sta1.latitude
xcorr_sacheader['evlo']=sta1.longitude
xcorr_sacheader['stla']=sta2.latitude
xcorr_sacheader['stlo']=sta2.longitude
xcorr_sacheader['dist']=subdset.parameters['dist']
xcorr_sacheader['az']=subdset.parameters['az']
xcorr_sacheader['baz']=subdset.parameters['baz']
xcorr_sacheader['b']=subdset.parameters['b']
xcorr_sacheader['e']=subdset.parameters['e']
xcorr_sacheader['delta']=subdset.parameters['delta']
xcorr_sacheader['npts']=subdset.parameters['npts']
xcorr_sacheader['user0']=subdset.parameters['stackday']
sacTr=obspy.io.sac.sactrace.SACTrace(data=subdset.data.value, **xcorr_sacheader)
if not os.path.isdir(outdir+'/'+pfx+'/'+netcode1+'.'+stacode1):
os.makedirs(outdir+'/'+pfx+'/'+netcode1+'.'+stacode1)
sacfname=outdir+'/'+pfx+'/'+netcode1+'.'+stacode1+'/'+ \
pfx+'_'+netcode1+'.'+stacode1+'_'+chan1+'_'+netcode2+'.'+stacode2+'_'+chan2+'.SAC'
sacTr.write(sacfname)
return
def wsac_xcorr_all(self, netcode1, stacode1, netcode2, stacode2, outdir='.', pfx='COR'):
"""Write all components of cross-correlation data from ASDF to sac file
==============================================================================
Input Parameters:
netcode1, stacode1 - network/station name for station 1
netcode2, stacode2 - network/station name for station 2
outdir - output directory
pfx - prefix
Output:
e.g. outdir/COR/TA.G12A/COR_TA.G12A_BHT_TA.R21A_BHT.SAC
==============================================================================
"""
subdset=self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2]
channels1=subdset.list()
channels2=subdset[channels1[0]].list()
for chan1 in channels1:
for chan2 in channels2:
self.wsac_xcorr(netcode1=netcode1, stacode1=stacode1, netcode2=netcode2,
stacode2=stacode2, chan1=chan1, chan2=chan2, outdir=outdir, pfx=pfx)
return
def get_xcorr_trace(self, netcode1, stacode1, netcode2, stacode2, chan1, chan2):
"""Get one single cross-correlation trace
"""
subdset=self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2][chan1][chan2]
evla, evz, evlo=self.waveforms[netcode1+'.'+stacode1].coordinates.values()
stla, stz, stlo=self.waveforms[netcode2+'.'+stacode2].coordinates.values()
tr=obspy.core.Trace()
tr.data=subdset.data.value
tr.stats.sac={}
tr.stats.sac.evla=evla
tr.stats.sac.evlo=evlo
tr.stats.sac.stla=stla
tr.stats.sac.stlo=stlo
tr.stats.sac.kuser0=netcode1
tr.stats.sac.kevnm=stacode1
tr.stats.network=netcode2
tr.stats.station=stacode2
tr.stats.sac.kcmpnm=chan1+chan2
tr.stats.sac.dist=subdset.parameters['dist']
tr.stats.sac.az=subdset.parameters['az']
tr.stats.sac.baz=subdset.parameters['baz']
tr.stats.sac.b=subdset.parameters['b']
tr.stats.sac.e=subdset.parameters['e']
tr.stats.sac.user0=subdset.parameters['stackday']
tr.stats.delta=subdset.parameters['delta']
return tr
def read_xcorr(self, datadir, pfx='COR', fnametype=2, inchannels=None, verbose=True):
"""Read cross-correlation data in ASDF database
===========================================================================================================
Input Parameters:
datadir - data directory
pfx - prefix
inchannels - input channels, if None, will read channel information from obspy inventory
fnametype - input sac file name type
=1: datadir/COR/G12A/COR_G12A_BHZ_R21A_BHZ.SAC # with netcodes
=2: datadir/COR/G12A/COR_G12A_R21A.SAC # with netcodes
=3: datadir/G12A/COR_G12A_R21A.SAC
-----------------------------------------------------------------------------------------------------------
Output:
ASDF path : self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2][chan1][chan2]
===========================================================================================================
"""
staLst=self.waveforms.list()
# main loop for station pairs
if inchannels!=None:
try:
if not isinstance(inchannels[0], obspy.core.inventory.channel.Channel):
channels=[]
for inchan in inchannels:
channels.append(obspy.core.inventory.channel.Channel(code=inchan, location_code='01',
latitude=0, longitude=0, elevation=0, depth=0) )
else:
channels=inchannels
except:
inchannels=None
for staid1 in staLst:
for staid2 in staLst:
netcode1, stacode1=staid1.split('.')
netcode2, stacode2=staid2.split('.')
if staid1 >= staid2:
continue
if fnametype==2 and not os.path.isfile(datadir+'/'+pfx+'/'+staid1+'/'+pfx+'_'+staid1+'_'+staid2+'.SAC'):
continue
if inchannels==None:
channels1=self.waveforms[staid1].StationXML.networks[0].stations[0].channels
channels2=self.waveforms[staid2].StationXML.networks[0].stations[0].channels
else:
channels1=channels
channels2=channels
skipflag=False
for chan1 in channels1:
if skipflag:
break
for chan2 in channels2:
if fnametype==1:
fname=datadir+'/'+pfx+'/'+staid1+'/'+pfx+'_'+staid1+'_'+chan1.code+'_'+staid2+'_'+chan2.code+'.SAC'
elif fnametype==2:
fname=datadir+'/'+pfx+'/'+staid1+'/'+pfx+'_'+staid1+'_'+staid2+'.SAC'
elif fnametype==3:
fname=datadir+'/'+stacode1+'/'+pfx+'_'+stacode1+'_'+stacode2+'.SAC'
try:
tr=obspy.core.read(fname)[0]
print "Done reading file: "+datadir+'/'+stacode1+'/'+pfx+'_'+stacode1+'_'+stacode2+'.SAC'
except IOError:
skipflag=True
print "Couldn't read file: "+datadir+'/'+stacode1+'/'+pfx+'_'+stacode1+'_'+stacode2+'.SAC'
break
# write cross-correlation header information
xcorr_header=xcorr_header_default.copy()
xcorr_header['b']=tr.stats.sac.b
xcorr_header['e']=tr.stats.sac.e
xcorr_header['netcode1']=netcode1
xcorr_header['netcode2']=netcode2
xcorr_header['stacode1']=stacode1
xcorr_header['stacode2']=stacode2
xcorr_header['npts']=tr.stats.npts
xcorr_header['delta']=tr.stats.delta
xcorr_header['stackday']=tr.stats.sac.user0
try:
xcorr_header['dist']=tr.stats.sac.dist
xcorr_header['az']=tr.stats.sac.az
xcorr_header['baz']=tr.stats.sac.baz
except AttributeError:
lon1=self.waveforms[staid1].StationXML.networks[0].stations[0].longitude
lat1=self.waveforms[staid1].StationXML.networks[0].stations[0].latitude
lon2=self.waveforms[staid2].StationXML.networks[0].stations[0].longitude
lat2=self.waveforms[staid2].StationXML.networks[0].stations[0].latitude
dist, az, baz=obspy.geodetics.gps2dist_azimuth(lat1, lon1, lat2, lon2)
dist=dist/1000.
xcorr_header['dist']=dist
xcorr_header['az']=az
xcorr_header['baz']=baz
staid_aux=netcode1+'/'+stacode1+'/'+netcode2+'/'+stacode2
xcorr_header['chan1']=chan1.code
xcorr_header['chan2']=chan2.code
self.add_auxiliary_data(data=tr.data, data_type='NoiseXcorr', path=staid_aux+'/'+chan1.code+'/'+chan2.code, parameters=xcorr_header)
if verbose and not skipflag:
print 'reading xcorr data: '+netcode1+'.'+stacode1+'_'+netcode2+'.'+stacode2
return
def xcorr_stack(self, datadir, startyear, startmonth, endyear, endmonth, pfx='COR', outdir=None, inchannels=None, fnametype=1):
"""Stack cross-correlation data from monthly-stacked sac files
===========================================================================================================
Input Parameters:
datadir - data directory
startyear, startmonth - start date for stacking
endyear, endmonth - end date for stacking
pfx - prefix
outdir - output directory (None is not to save sac files)
inchannels - input channels, if None, will read channel information from obspy inventory
fnametype - input sac file name type
=1: datadir/COR/G12A/COR_G12A_BHZ_R21A_BHZ.SAC
=2: datadir/COR/G12A/COR_G12A_R21A.SAC
-----------------------------------------------------------------------------------------------------------
Output:
ASDF path : self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2][chan1][chan2]
sac file(optional) : outdir/COR/TA.G12A/COR_TA.G12A_BHT_TA.R21A_BHT.SAC
===========================================================================================================
"""
# prepare year/month list for stacking
utcdate=obspy.core.utcdatetime.UTCDateTime(startyear, startmonth, 1)
ylst=np.array([], dtype=int)
mlst=np.array([], dtype=int)
while (utcdate.year<endyear or (utcdate.year<=endyear and utcdate.month<=endmonth) ):
ylst=np.append(ylst, utcdate.year)
mlst=np.append(mlst, utcdate.month)
try:
utcdate.month+=1
except ValueError:
utcdate.year+=1
utcdate.month=1
mnumb=mlst.size
# determine channels if inchannels is specified
if inchannels!=None:
try:
if not isinstance(inchannels[0], obspy.core.inventory.channel.Channel):
channels=[]
for inchan in inchannels:
channels.append(obspy.core.inventory.channel.Channel(code=inchan, location_code='01',
latitude=0, longitude=0, elevation=0, depth=0) )
else:
channels=inchannels
except:
inchannels=None
if inchannels==None:
fnametype==1
else:
if len(channels)!=1:
fnametype==1
staLst=self.waveforms.list()
# main loop for station pairs
for staid1 in staLst:
for staid2 in staLst:
netcode1, stacode1=staid1.split('.')
netcode2, stacode2=staid2.split('.')
if stacode1 >= stacode2:
continue
stackedST=[]
cST=[]
initflag=True
if inchannels==None:
channels1=self.waveforms[staid1].StationXML.networks[0].stations[0].channels
channels2=self.waveforms[staid2].StationXML.networks[0].stations[0].channels
else:
channels1=channels
channels2=channels
for im in xrange(mnumb):
skipflag=False
for chan1 in channels1:
if skipflag:
break
for chan2 in channels2:
month=monthdict[mlst[im]]
yrmonth=str(ylst[im])+'.'+month
if fnametype==1:
fname=datadir+'/'+yrmonth+'/'+pfx+'/'+stacode1+'/'+pfx+'_'+stacode1+'_'+chan1.code+'_'+stacode2+'_'+chan2.code+'.SAC'
elif fnametype==2:
fname=datadir+'/'+yrmonth+'/'+pfx+'/'+stacode1+'/'+pfx+'_'+stacode1+'_'+stacode2+'.SAC'
if not os.path.isfile(fname):
skipflag=True
break
try:
tr=obspy.core.read(fname)[0]
except TypeError:
warnings.warn('Unable to read SAC for: ' + stacode1 +'_'+stacode2 +' Month: '+yrmonth, UserWarning, stacklevel=1)
skipflag=True
if np.isnan(tr.data).any() or abs(tr.data.max())>1e20:
warnings.warn('NaN monthly SAC for: ' + stacode1 +'_'+stacode2 +' Month: '+yrmonth, UserWarning, stacklevel=1)
skipflag=True
break
cST.append(tr)
if len(cST)!=len(channels1)*len(channels2) or skipflag:
cST=[]
continue
if initflag:
stackedST=copy.deepcopy(cST)
initflag=False
else:
for itr in xrange(len(cST)):
mtr=cST[itr]
stackedST[itr].data+=mtr.data
stackedST[itr].stats.sac.user0+=mtr.stats.sac.user0
cST=[]
if len(stackedST)==len(channels1)*len(channels2):
print 'Finished Stacking for:'+netcode1+'.'+stacode1+'_'+netcode2+'.'+stacode2
# create sac output directory
if outdir!=None:
if not os.path.isdir(outdir+'/'+pfx+'/'+netcode1+'.'+stacode1):
os.makedirs(outdir+'/'+pfx+'/'+netcode1+'.'+stacode1)
# write cross-correlation header information
xcorr_header=xcorr_header_default.copy()
xcorr_header['b']=stackedST[0].stats.sac.b
xcorr_header['e']=stackedST[0].stats.sac.e
xcorr_header['netcode1']=netcode1
xcorr_header['netcode2']=netcode2
xcorr_header['stacode1']=stacode1
xcorr_header['stacode2']=stacode2
xcorr_header['npts']=stackedST[0].stats.npts
xcorr_header['delta']=stackedST[0].stats.delta
xcorr_header['stackday']=stackedST[0].stats.sac.user0
try:
xcorr_header['dist']=stackedST[0].stats.sac.dist
xcorr_header['az']=stackedST[0].stats.sac.az
xcorr_header['baz']=stackedST[0].stats.sac.baz
except AttributeError:
lon1=self.waveforms[staid1].StationXML.networks[0].stations[0].longitude
lat1=self.waveforms[staid1].StationXML.networks[0].stations[0].latitude
lon2=self.waveforms[staid2].StationXML.networks[0].stations[0].longitude
lat2=self.waveforms[staid2].StationXML.networks[0].stations[0].latitude
dist, az, baz=obspy.geodetics.gps2dist_azimuth(lat1, lon1, lat2, lon2)
dist=dist/1000.
xcorr_header['dist']=dist
xcorr_header['az']=az
xcorr_header['baz']=baz
staid_aux=netcode1+'/'+stacode1+'/'+netcode2+'/'+stacode2
i=0
for chan1 in channels1:
for chan2 in channels2:
stackedTr=stackedST[i]
if outdir!=None:
outfname=outdir+'/'+pfx+'/'+netcode1+'.'+stacode1+'/'+ \
pfx+'_'+netcode1+'.'+stacode1+'_'+chan1.code+'_'+netcode2+'.'+stacode2+'_'+chan2.code+'.SAC'
stackedTr.write(outfname,format='SAC')
xcorr_header['chan1']=chan1.code
xcorr_header['chan2']=chan2.code
self.add_auxiliary_data(data=stackedTr.data, data_type='NoiseXcorr', path=staid_aux+'/'+chan1.code+'/'+chan2.code, parameters=xcorr_header)
i+=1
return
def xcorr_stack_mp(self, datadir, outdir, startyear, startmonth, endyear, endmonth,
pfx='COR', inchannels=None, fnametype=1, subsize=1000, deletesac=True, nprocess=4):
"""Stack cross-correlation data from monthly-stacked sac files with multiprocessing
===========================================================================================================
Input Parameters:
datadir - data directory
outdir - output directory
startyear, startmonth - start date for stacking
endyear, endmonth - end date for stacking
pfx - prefix
inchannels - input channels, if None, will read channel information from obspy inventory
fnametype - input sac file name type
=1: datadir/COR/G12A/COR_G12A_BHZ_R21A_BHZ.SAC
=2: datadir/COR/G12A/COR_G12A_R21A.SAC
subsize - subsize of processing list, use to prevent lock in multiprocessing process
deletesac - delete output sac files
nprocess - number of processes
-----------------------------------------------------------------------------------------------------------
Output:
ASDF path : self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2][chan1][chan2]
sac file(optional) : outdir/COR/TA.G12A/COR_TA.G12A_BHT_TA.R21A_BHT.SAC
===========================================================================================================
"""
utcdate=obspy.core.utcdatetime.UTCDateTime(startyear, startmonth, 1)
ylst=np.array([], dtype=int)
mlst=np.array([], dtype=int)
print 'Preparing data for stacking'
while (utcdate.year<endyear or (utcdate.year<=endyear and utcdate.month<=endmonth) ):
ylst=np.append(ylst, utcdate.year)
mlst=np.append(mlst, utcdate.month)
try:
utcdate.month+=1
except ValueError:
utcdate.year+=1
utcdate.month=1
mnumb=mlst.size
staLst=self.waveforms.list()
if inchannels!=None:
try:
if not isinstance(inchannels[0], obspy.core.inventory.channel.Channel):
channels=[]
for inchan in inchannels:
channels.append(obspy.core.inventory.channel.Channel(code=inchan, location_code='01',
latitude=0, longitude=0, elevation=0, depth=0) )
else:
channels=inchannels
except:
inchannels=None
if inchannels==None:
fnametype==1
else:
if len(channels)!=1:
fnametype==1
stapairInvLst=[]
for staid1 in staLst:
if not os.path.isdir(outdir+'/'+pfx+'/'+staid1):
os.makedirs(outdir+'/'+pfx+'/'+staid1)
for staid2 in staLst:
netcode1, stacode1=staid1.split('.')
netcode2, stacode2=staid2.split('.')
if stacode1 >= stacode2:
continue
inv = self.waveforms[staid1].StationXML + self.waveforms[staid2].StationXML
if inchannels!=None:
inv.networks[0].stations[0].channels=channels
inv.networks[1].stations[0].channels=channels
stapairInvLst.append(inv)
print 'Start multiprocessing stacking !'
if len(stapairInvLst) > subsize:
Nsub = int(len(stapairInvLst)/subsize)
for isub in xrange(Nsub):
print isub,'in',Nsub
cstapairs=stapairInvLst[isub*subsize:(isub+1)*subsize]
STACKING = partial(stack4mp, datadir=datadir, outdir=outdir, ylst=ylst, mlst=mlst, pfx=pfx, fnametype=fnametype)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(STACKING, cstapairs) #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
cstapairs=stapairInvLst[(isub+1)*subsize:]
STACKING = partial(stack4mp, datadir=datadir, outdir=outdir, ylst=ylst, mlst=mlst, pfx=pfx, fnametype=fnametype)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(STACKING, cstapairs)
pool.close()
pool.join()
else:
STACKING = partial(stack4mp, datadir=datadir, outdir=outdir, ylst=ylst, mlst=mlst, pfx=pfx, fnametype=fnametype)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(STACKING, stapairInvLst)
pool.close()
pool.join()
print 'End of multiprocessing stacking !'
print 'Reading data into ASDF database'
for inv in stapairInvLst:
channels1=inv.networks[0].stations[0].channels
netcode1=inv.networks[0].code
stacode1=inv.networks[0].stations[0].code
channels2=inv.networks[1].stations[0].channels
netcode2=inv.networks[1].code
stacode2=inv.networks[1].stations[0].code
skipflag=False
xcorr_header=xcorr_header_default.copy()
xcorr_header['netcode1']=netcode1
xcorr_header['netcode2']=netcode2
xcorr_header['stacode1']=stacode1
xcorr_header['stacode2']=stacode2
staid_aux=netcode1+'/'+stacode1+'/'+netcode2+'/'+stacode2
for chan1 in channels1:
if skipflag:
break
for chan2 in channels2:
sacfname=outdir+'/'+pfx+'/'+netcode1+'.'+stacode1+'/'+ \
pfx+'_'+netcode1+'.'+stacode1+'_'+chan1.code+'_'+netcode2+'.'+stacode2+'_'+chan2.code+'.SAC'
try:
tr=obspy.read(sacfname)[0]
# cross-correlation header
xcorr_header['b']=tr.stats.sac.b
xcorr_header['e']=tr.stats.sac.e
xcorr_header['npts']=tr.stats.npts
xcorr_header['delta']=tr.stats.delta
xcorr_header['stackday']=tr.stats.sac.user0
try:
xcorr_header['dist']=tr.stats.sac.dist
xcorr_header['az']=tr.stats.sac.az
xcorr_header['baz']=tr.stats.sac.baz
except AttributeError:
lon1=inv.networks[0].stations[0].longitude
lat1=inv.networks[0].stations[0].latitude
lon2=inv.networks[1].stations[0].longitude
lat2=inv.networks[1].stations[0].latitude
dist, az, baz=obspy.geodetics.gps2dist_azimuth(lat1, lon1, lat2, lon2)
dist=dist/1000.
xcorr_header['dist']=dist
xcorr_header['az']=az
xcorr_header['baz']=baz
xcorr_header['chan1']=chan1.code
xcorr_header['chan2']=chan2.code
self.add_auxiliary_data(data=tr.data, data_type='NoiseXcorr', path=staid_aux+'/'+chan1.code+'/'+chan2.code, parameters=xcorr_header)
except IOError:
skipflag=True
break
if deletesac:
shutil.rmtree(outdir+'/'+pfx)
print 'End read data into ASDF database'
return