forked from NoisyLeon/NoisePy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquakedbase.py
3141 lines (3081 loc) · 173 KB
/
quakedbase.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 earthquake data analysis based on ASDF database
:Methods:
aftan analysis (use pyaftan or aftanf77)
Automatic Receiver Function Analysis( Iterative Deconvolution and Harmonic Stripping )
Preparing data for surface wave tomography (Barmin's method, Eikonal/Helmholtz tomography)
:Dependencies:
pyasdf and its dependencies
ObsPy and its dependencies
pyproj
Basemap
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.dates as mdates
import obspy
import warnings
import copy
import os, shutil
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 timeit
sta_info_default = {'xcorr': 1, 'isnet': 0}
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 requestInfo(object):
def __init__(self, evnumb, network, station, location, channel, starttime, endtime, quality=None,
minimumlength=None, longestonly=None, filename=None, attach_response=False, baz=0):
self.evnumb = evnumb
self.network = network
self.station = station
self.location = location
self.channel = channel
self.starttime = starttime
self.endtime = endtime
self.quality = quality
self.minimumlength = minimumlength
self.longestonly = longestonly
self.filename = filename
self.attach_response= attach_response
self.baz = baz
class quakeASDF(pyasdf.ASDFDataSet):
""" An object to for earthquake data analysis based on ASDF database
=================================================================================================================
version history:
Dec 8th, 2016 - first version
Jan 12th, 2018 - second version
changes:
1. correct the bug in _stretch function, improve the speed
2. no longer do stretch_back, directly stretch the function to reference slowness
3. using IASP91 model instead of a two layer model for moveout
4. changed output part for harmonic stripping
5. added more comments, changed the name of variables to improve readability
=================================================================================================================
"""
def print_info(self):
"""
Print information of the dataset.
"""
outstr = '============================================================ Earthquake Database ===========================================================\n'
outstr += self.__str__()+'\n'
outstr += '--------------------------------------------------------- Surface wave auxiliary Data ------------------------------------------------------\n'
if 'DISPbasic1' in self.auxiliary_data.list():
outstr += 'DISPbasic1 - Basic dispersion curve, no jump correction\n'
if 'DISPbasic2' in self.auxiliary_data.list():
outstr += 'DISPbasic2 - Basic dispersion curve, with jump correction\n'
if 'DISPpmf1' in self.auxiliary_data.list():
outstr += 'DISPpmf1 - PMF dispersion curve, no jump correction\n'
if 'DISPpmf2' in self.auxiliary_data.list():
outstr += 'DISPpmf2 - PMF dispersion curve, with jump correction\n'
if 'DISPbasic1interp' in self.auxiliary_data.list():
outstr += 'DISPbasic1interp - Interpolated DISPbasic1\n'
if 'DISPbasic2interp' in self.auxiliary_data.list():
outstr += 'DISPbasic2interp - Interpolated DISPbasic2\n'
if 'DISPpmf1interp' in self.auxiliary_data.list():
outstr += 'DISPpmf1interp - Interpolated DISPpmf1\n'
if 'DISPpmf2interp' in self.auxiliary_data.list():
outstr += 'DISPpmf2interp - Interpolated DISPpmf2\n'
if 'FieldDISPbasic1interp' in self.auxiliary_data.list():
outstr += 'FieldDISPbasic1interp - Field data of DISPbasic1\n'
if 'FieldDISPbasic2interp' in self.auxiliary_data.list():
outstr += 'FieldDISPbasic2interp - Field data of DISPbasic2\n'
if 'FieldDISPpmf1interp' in self.auxiliary_data.list():
outstr += 'FieldDISPpmf1interp - Field data of DISPpmf1\n'
if 'FieldDISPpmf2interp' in self.auxiliary_data.list():
outstr += 'FieldDISPpmf2interp - Field data of DISPpmf2\n'
outstr += '------------------------------------------------------ Receiver function auxiliary Data ----------------------------------------------------\n'
if 'RefR' in self.auxiliary_data.list():
outstr += 'RefR - Radial receiver function\n'
if 'RefRHS' in self.auxiliary_data.list():
outstr += 'RefRHS - Harmonic stripping results of radial receiver function\n'
if 'RefRmoveout' in self.auxiliary_data.list():
outstr += 'RefRmoveout - Move out of radial receiver function\n'
if 'RefRampc' in self.auxiliary_data.list():
outstr += 'RefRampc - Scaled radial receiver function\n'
if 'RefRstreback' in self.auxiliary_data.list():
outstr += 'RefRstreback - Stretch back of radial receiver function\n'
outstr += '============================================================================================================================================\n'
print outstr
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')
lat_centre = (self.maxlat+self.minlat)/2.0
lon_centre = (self.maxlon+self.minlon)/2.0
if projection=='merc':
m = Basemap(projection='merc', llcrnrlat=self.minlat-5., urcrnrlat=self.maxlat+5., llcrnrlon=self.minlon-5.,
urcrnrlon=self.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)
m.drawparallels(np.arange(-80.0,80.0,10.0), labels=[1,0,0,1])
m.drawmeridians(np.arange(-170.0,170.0,10.0), labels=[1,0,0,1])
elif projection=='regional_ortho':
m1 = Basemap(projection='ortho', lon_0=self.minlon, lat_0=self.minlat, resolution='l')
m = Basemap(projection='ortho', lon_0=self.minlon, lat_0=self.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(self.minlat, self.minlon, self.minlat, self.maxlon) # distance is in m
distNS, az, baz = obspy.geodetics.gps2dist_azimuth(self.minlat, self.minlon, self.maxlat+2., self.minlon) # distance is in m
m = Basemap(width=distEW, height=distNS, rsphere=(6378137.00,6356752.3142), resolution='l', projection='lcc',\
lat_1=self.minlat, lat_2=self.maxlat, lon_0=lon_centre, lat_0=lat_centre+1)
m.drawparallels(np.arange(-80.0,80.0,10.0), linewidth=1, dashes=[2,2], labels=[1,1,0,0], fontsize=15)
m.drawmeridians(np.arange(-170.0,170.0,10.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")
m.drawstates()
try:
geopolygons.PlotPolygon(inbasemap=m)
except:
pass
return m
#==================================================================
# functions for manipulating earthquake catalog
#==================================================================
def get_events(self, startdate, enddate, add2dbase=True, gcmt=False, Mmin=5.5, Mmax=None, minlatitude=None, maxlatitude=None, minlongitude=None, maxlongitude=None,
latitude=None, longitude=None, minradius=None, maxradius=None, mindepth=None, maxdepth=None, magnitudetype=None,
outquakeml=None):
"""Get earthquake catalog from IRIS server
=======================================================================================================
::: input parameters :::
startdate, enddata - start/end date for searching
Mmin, Mmax - minimum/maximum magnitude for searching
minlatitude - Limit to events with a latitude larger than the specified minimum.
maxlatitude - Limit to events with a latitude smaller than the specified maximum.
minlongitude - Limit to events with a longitude larger than the specified minimum.
maxlongitude - Limit to events with a longitude smaller than the specified maximum.
latitude - Specify the latitude to be used for a radius search.
longitude - Specify the longitude to the used for a radius search.
minradius - Limit to events within the specified minimum number of degrees from the
geographic point defined by the latitude and longitude parameters.
maxradius - Limit to events within the specified maximum number of degrees from the
geographic point defined by the latitude and longitude parameters.
mindepth - Limit to events with depth, in kilometers, larger than the specified minimum.
maxdepth - Limit to events with depth, in kilometers, smaller than the specified maximum.
magnitudetype - Specify a magnitude type to use for testing the minimum and maximum limits.
=======================================================================================================
"""
starttime = obspy.core.utcdatetime.UTCDateTime(startdate)
endtime = obspy.core.utcdatetime.UTCDateTime(enddate)
if not gcmt:
client = Client('IRIS')
try:
catISC = client.get_events(starttime=starttime, endtime=endtime, minmagnitude=Mmin, maxmagnitude=Mmax, catalog='ISC',
minlatitude=minlatitude, maxlatitude=maxlatitude, minlongitude=minlongitude, maxlongitude=maxlongitude,
latitude=latitude, longitude=longitude, minradius=minradius, maxradius=maxradius, mindepth=mindepth,
maxdepth=maxdepth, magnitudetype=magnitudetype)
endtimeISC = catISC[0].origins[0].time
except:
catISC = obspy.core.event.Catalog()
endtimeISC = starttime
if endtime.julday-endtimeISC.julday >1:
try:
catPDE = client.get_events(starttime=endtimeISC, endtime=endtime, minmagnitude=Mmin, maxmagnitude=Mmax, catalog='NEIC PDE',
minlatitude=minlatitude, maxlatitude=maxlatitude, minlongitude=minlongitude, maxlongitude=maxlongitude,
latitude=latitude, longitude=longitude, minradius=minradius, maxradius=maxradius, mindepth=mindepth,
maxdepth=maxdepth, magnitudetype=magnitudetype)
catalog = catISC+catPDE
except:
catalog = catISC
else:
catalog = catISC
outcatalog = obspy.core.event.Catalog()
# check magnitude
for event in catalog:
if event.magnitudes[0].mag < Mmin:
continue
outcatalog.append(event)
else:
# Updated the URL on Aug 31st, 2018
gcmt_url_old = 'http://www.ldeo.columbia.edu/~gcmt/projects/CMT/catalog/jan76_dec17.ndk'
gcmt_new = 'http://www.ldeo.columbia.edu/~gcmt/projects/CMT/catalog/NEW_MONTHLY'
if starttime.year < 2005:
print('Loading catalog: '+gcmt_url_old)
cat_old = obspy.read_events(gcmt_url_old)
if Mmax != None:
cat_old = cat_old.filter("magnitude <= %g" %Mmax)
if maxlongitude != None:
cat_old = cat_old.filter("longitude <= %g" %maxlongitude)
if minlongitude != None:
cat_old = cat_old.filter("longitude >= %g" %minlongitude)
if maxlatitude != None:
cat_old = cat_old.filter("latitude <= %g" %maxlatitude)
if minlatitude != None:
cat_old = cat_old.filter("latitude >= %g" %minlatitude)
if maxdepth != None:
cat_old = cat_old.filter("depth <= %g" %(maxdepth*1000.))
if mindepth != None:
cat_old = cat_old.filter("depth >= %g" %(mindepth*1000.))
temp_stime = obspy.core.utcdatetime.UTCDateTime('2018-01-01')
outcatalog = cat_old.filter("magnitude >= %g" %Mmin, "time >= %s" %str(starttime), "time <= %s" %str(endtime) )
else:
outcatalog = obspy.core.event.Catalog()
temp_stime = copy.deepcopy(starttime)
temp_stime.day = 1
while (temp_stime < endtime):
year = temp_stime.year
month = temp_stime.month
yearstr = str(int(year))[2:]
monstr = monthdict[month]
monstr = monstr.lower()
if year==2005 and month==6:
monstr = 'june'
if year==2005 and month==7:
monstr = 'july'
if year==2005 and month==9:
monstr = 'sept'
gcmt_url_new = gcmt_new+'/'+str(int(year))+'/'+monstr+yearstr+'.ndk'
# cat_new = obspy.core.event.read_events(gcmt_url_new)
try:
cat_new = obspy.read_events(gcmt_url_new, format='ndk')
print('Loading catalog: '+gcmt_url_new)
except:
print('Link not found: '+gcmt_url_new)
break
cat_new = cat_new.filter("magnitude >= %g" %Mmin, "time >= %s" %str(starttime), "time <= %s" %str(endtime) )
if Mmax != None:
cat_new = cat_new.filter("magnitude <= %g" %Mmax)
if maxlongitude != None:
cat_new = cat_new.filter("longitude <= %g" %maxlongitude)
if minlongitude!=None:
cat_new = cat_new.filter("longitude >= %g" %minlongitude)
if maxlatitude!=None:
cat_new = cat_new.filter("latitude <= %g" %maxlatitude)
if minlatitude!=None:
cat_new = cat_new.filter("latitude >= %g" %minlatitude)
if maxdepth != None:
cat_new = cat_new.filter("depth <= %g" %(maxdepth*1000.))
if mindepth != None:
cat_new = cat_new.filter("depth >= %g" %(mindepth*1000.))
outcatalog += cat_new
try:
temp_stime.month +=1
except:
temp_stime.year +=1
temp_stime.month = 1
try:
self.cat += outcatalog
except:
self.cat = outcatalog
if add2dbase:
self.add_quakeml(outcatalog)
if outquakeml != None:
self.cat.write(outquakeml, format='quakeml')
return
def read_quakeml(self, inquakeml, add2dbase=False):
self.cat = obspy.read_events(inquakeml)
if add2dbase:
self.add_quakeml(self.cat)
return
def copy_catalog(self):
print('Copying catalog from ASDF to memory')
self.cat = self.events
return
def copy_catalog_fromasdf(self, inasdffname):
print('Copying catalog from ASDF file')
indset = pyasdf.ASDFDataSet(inasdffname)
cat = indset.events
self.add_quakeml(cat)
return
def plot_events(self, gcmt=False, projection='lambert', valuetype='depth', geopolygons=None, showfig=True, vmin=None, vmax=None):
if gcmt:
from obspy.imaging.beachball import beach
ax = plt.gca()
evlons = np.array([])
evlats = np.array([])
values = np.array([])
focmecs = []
for event in self.events:
event_id = event.resource_id.id.split('=')[-1]
magnitude = event.magnitudes[0].mag
Mtype = event.magnitudes[0].magnitude_type
otime = event.origins[0].time
evlo = event.origins[0].longitude
evla = event.origins[0].latitude
evdp = event.origins[0].depth/1000.
if evlo > -80.:
continue
evlons = np.append(evlons, evlo)
evlats = np.append(evlats, evla);
if valuetype=='depth':
values = np.append(values, evdp)
elif valuetype=='mag':
values = np.append(values, magnitude)
if gcmt:
mtensor = event.focal_mechanisms[0].moment_tensor.tensor
mt = [mtensor.m_rr, mtensor.m_tt, mtensor.m_pp, mtensor.m_rt, mtensor.m_rp, mtensor.m_tp]
# nodalP=event.focal_mechanisms[0].nodal_planes.values()[1]
# mt=[nodalP.strike, nodalP.dip, nodalP.rake]
focmecs.append(mt)
self.minlat = evlats.min()-1.; self.maxlat=evlats.max()+1.
self.minlon = evlons.min()-1.; self.maxlon=evlons.max()+1.
# self.minlat=15; self.maxlat=50
# self.minlon=95; self.maxlon=128
m = self._get_basemap(projection=projection, geopolygons=geopolygons)
import pycpt
cmap = pycpt.load.gmtColormap('./GMT_panoply.cpt')
# cmap =discrete_cmap(int((vmax-vmin)/0.1)+1, cmap)
x, y = m(evlons, evlats)
if vmax==None and vmin==None:
vmax = values.max()
vmin = values.min()
if gcmt:
for i in xrange(len(focmecs)):
value = values[i]
rgbcolor= cmap( (value-vmin)/(vmax-vmin) )
b = beach(focmecs[i], xy=(x[i], y[i]), width=100000, linewidth=1, facecolor=rgbcolor)
b.set_zorder(10)
ax.add_collection(b)
# ax.annotate(str(i), (x[i]+50000, y[i]+50000))
im = m.scatter(x, y, marker='o', s=1, c=values, cmap=cmap, vmin=vmin, vmax=vmax)
cb = m.colorbar(im, "bottom", size="3%", pad='2%')
cb.set_label(valuetype, fontsize=20)
else:
if values.size!=0:
im = m.scatter(x, y, marker='o', s=300, c=values, cmap=cmap, vmin=vmin, vmax=vmax)
cb = m.colorbar(im, "bottom", size="3%", pad='2%')
else:
m.plot(x,y,'o')
if gcmt:
stime = self.events[0].origins[0].time
etime = self.events[-1].origins[0].time
else:
etime = self.events[0].origins[0].time
stime = self.events[-1].origins[0].time
plt.suptitle('Number of event: '+str(len(self.events))+' time range: '+str(stime)+' - '+str(etime), fontsize=20 )
if showfig:
plt.show()
return
#==================================================================
# functions for manipulating station inventory
#==================================================================
def read_stationtxt(self, stafile, source='CIEI', chans=['BHZ', 'BHE', 'BHN']):
"""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()
netsta = lines[0]
netcode = netsta[:2]
stacode = netsta[2:]
if stacode[-1]=='/':
stacode = stacode[:-1]
print netcode, stacode
lon = float(lines[1])
lat = float(lines[2])
if lat>90.:
lon = float(lines[2])
lat = float(lines[1])
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)
print 'Writing obspy inventory to ASDF dataset'
self.add_stationxml(inv)
print 'End writing obspy inventory to ASDF dataset'
return
def get_stations(self, startdate=None, enddate=None, network=None, station=None, location=None, channel=None, includerestricted=False,
minlatitude=None, maxlatitude=None, minlongitude=None, maxlongitude=None, latitude=None, longitude=None, minradius=None, maxradius=None):
"""Get station inventory from IRIS server
=======================================================================================================
::: input parameters :::
startdate, enddata - start/end date for searching
network - Select one or more network codes.
Can be SEED network codes or data center defined codes.
Multiple codes are comma-separated (e.g. "IU,TA").
station - Select one or more SEED station codes.
Multiple codes are comma-separated (e.g. "ANMO,PFO").
location - Select one or more SEED location identifiers.
Multiple identifiers are comma-separated (e.g. "00,01").
As a special case “--“ (two dashes) will be translated to a string of two space
characters to match blank location IDs.
channel - Select one or more SEED channel codes.
Multiple codes are comma-separated (e.g. "BHZ,HHZ").
minlatitude - Limit to events with a latitude larger than the specified minimum.
maxlatitude - Limit to events with a latitude smaller than the specified maximum.
minlongitude - Limit to events with a longitude larger than the specified minimum.
maxlongitude - Limit to events with a longitude smaller than the specified maximum.
latitude - Specify the latitude to be used for a radius search.
longitude - Specify the longitude to the used for a radius search.
minradius - Limit to events within the specified minimum number of degrees from the
geographic point defined by the latitude and longitude parameters.
maxradius - Limit to events within the specified maximum number of degrees from the
geographic point defined by the latitude and longitude parameters.
=======================================================================================================
"""
try:
starttime = obspy.core.utcdatetime.UTCDateTime(startdate)
except:
starttime = None
try:
endtime = obspy.core.utcdatetime.UTCDateTime(enddate)
except:
endtime = None
client = Client('IRIS')
inv = client.get_stations(network=network, station=station, starttime=starttime, endtime=endtime, channel=channel,
minlatitude=minlatitude, maxlatitude=maxlatitude, minlongitude=minlongitude, maxlongitude=maxlongitude,
latitude=latitude, longitude=longitude, minradius=minradius, maxradius=maxradius, level='channel',
includerestricted=includerestricted)
self.add_stationxml(inv)
try:
self.inv +=inv
except:
self.inv = inv
return
def copy_stations(self, inasdffname, startdate=None, enddate=None, location=None, channel=None, includerestricted=False,
minlatitude=None, maxlatitude=None, minlongitude=None, maxlongitude=None, latitude=None, longitude=None, minradius=None, maxradius=None):
"""copy and renew station inventory given an input ASDF file
the function will copy the network and station names while renew other informations given new limitations
=======================================================================================================
::: input parameters :::
inasdffname - input ASDF file name
startdate, enddata - start/end date for searching
network - Select one or more network codes.
Can be SEED network codes or data center defined codes.
Multiple codes are comma-separated (e.g. "IU,TA").
station - Select one or more SEED station codes.
Multiple codes are comma-separated (e.g. "ANMO,PFO").
location - Select one or more SEED location identifiers.
Multiple identifiers are comma-separated (e.g. "00,01").
As a special case “--“ (two dashes) will be translated to a string of two space
characters to match blank location IDs.
channel - Select one or more SEED channel codes.
Multiple codes are comma-separated (e.g. "BHZ,HHZ").
minlatitude - Limit to events with a latitude larger than the specified minimum.
maxlatitude - Limit to events with a latitude smaller than the specified maximum.
minlongitude - Limit to events with a longitude larger than the specified minimum.
maxlongitude - Limit to events with a longitude smaller than the specified maximum.
latitude - Specify the latitude to be used for a radius search.
longitude - Specify the longitude to the used for a radius search.
minradius - Limit to events within the specified minimum number of degrees from the
geographic point defined by the latitude and longitude parameters.
maxradius - Limit to events within the specified maximum number of degrees from the
geographic point defined by the latitude and longitude parameters.
=======================================================================================================
"""
try:
starttime = obspy.core.utcdatetime.UTCDateTime(startdate)
except:
starttime = None
try:
endtime = obspy.core.utcdatetime.UTCDateTime(enddate)
except:
endtime = None
client = Client('IRIS')
init_flag = False
indset = pyasdf.ASDFDataSet(inasdffname)
for staid in indset.waveforms.list():
network = staid.split('.')[0]
station = staid.split('.')[1]
print 'Copying/renewing station inventory: '+ staid
if init_flag:
inv += client.get_stations(network=network, station=station, starttime=starttime, endtime=endtime, channel=channel,
minlatitude=minlatitude, maxlatitude=maxlatitude, minlongitude=minlongitude, maxlongitude=maxlongitude,
latitude=latitude, longitude=longitude, minradius=minradius, maxradius=maxradius, level='channel',
includerestricted=includerestricted)
else:
inv = client.get_stations(network=network, station=station, starttime=starttime, endtime=endtime, channel=channel,
minlatitude=minlatitude, maxlatitude=maxlatitude, minlongitude=minlongitude, maxlongitude=maxlongitude,
latitude=latitude, longitude=longitude, minradius=minradius, maxradius=maxradius, level='channel',
includerestricted=includerestricted)
init_flag= True
self.add_stationxml(inv)
try:
self.inv +=inv
except:
self.inv = inv
return
#==================================================================
# functions for reading/downloading/writing waveforms
#==================================================================
def read_sac(self, datadir):
"""This function is a scratch for reading a specific datasets, DO NOT use this function!
"""
L = len(self.events)
evnumb = 0
import glob
for event in self.events:
event_id = event.resource_id.id.split('=')[-1]
magnitude = event.magnitudes[0].mag; Mtype=event.magnitudes[0].magnitude_type
event_descrip = event.event_descriptions[0].text+', '+event.event_descriptions[0].type
evnumb +=1
print '================================= Getting surface wave data ==================================='
print 'Event ' + str(evnumb)+' : '+event_descrip+', '+Mtype+' = '+str(magnitude)
st = obspy.Stream()
otime = event.origins[0].time
evlo = event.origins[0].longitude; evla=event.origins[0].latitude
tag = 'surf_ev_%05d' %evnumb
# if lon0!=None and lat0!=None:
# dist, az, baz=obspy.geodetics.gps2dist_azimuth(evla, evlo, lat0, lon0) # distance is in m
# dist=dist/1000.
# starttime=otime+dist/vmax; endtime=otime+dist/vmin
# commontime=True
# else:
# commontime=False
odate = str(otime.year)+'%02d' %otime.month +'%02d' %otime.day
for staid in self.waveforms.list():
netcode, stacode=staid.split('.')
print staid
stla, elev, stlo=self.waveforms[staid].coordinates.values()
# sta_datadir=datadir+'/'+netcode+'/'+stacode
sta_datadir=datadir+'/'+netcode+'/'+stacode
sacpfx=sta_datadir+'/'+stacode+'.'+odate
pzpfx='/home/lili/code/china_data/response_files/SAC_*'+netcode+'_'+stacode
respfx='/home/lili/code/china_data/RESP4WeisenCUB/dbRESPCNV20131007/'+netcode+'/'+staid+'/RESP.'+staid
st=obspy.Stream()
for chan in ['*Z', '*E', '*N']:
sacfname = sacpfx+chan
pzfpattern = pzpfx+'_'+chan
respfpattern= respfx+'*BH'+chan[-1]+'*'
#################
try: respfname=glob.glob(respfpattern)[0]
except: break
seedresp = {'filename': respfname, # RESP filename
# when using Trace/Stream.simulate() the "date" parameter can
# also be omitted, and the starttime of the trace is then used.
# Units to return response in ('DIS', 'VEL' or ACC)
'units': 'VEL'
}
try: tr=obspy.read(sacfname)[0]
except: break
tr.detrend()
tr.stats.channel='BH'+chan[-1]
tr.simulate(paz_remove=None, pre_filt=(0.001, 0.005, 1, 100.0), seedresp=seedresp)
################
# try: pzfname = glob.glob(pzfpattern)[0]
# except: break
# try: tr=obspy.read(sacfname)[0]
# except: break
# obspy.io.sac.sacpz.attach_paz(tr, pzfname)
# tr.decimate(10)
# tr.detrend()
# tr.simulate(paz_remove=tr.stats.paz, pre_filt=(0.001, 0.005, 1, 100.0))
st.append(tr)
self.add_waveforms(st, event_id=event_id, tag=tag)
def get_ray_waveforms(self, lon0=None, lat0=None, minDelta=-1, maxDelta=181, channel='LHZ', vmax=6.0, vmin=1.0, verbose=False,
startdate=None, enddate=None ):
"""Get Rayleigh wave data from IRIS server
====================================================================================================================
::: input parameters :::
lon0, lat0 - center of array. If specified, all waveform will have the same starttime and endtime
min/maxDelta - minimum/maximum epicentral distance, in degree
channel - Channel code, e.g. 'BHZ'.
Last character (i.e. component) can be a wildcard (‘?’ or ‘*’) to fetch Z, N and E component.
vmin, vmax - minimum/maximum velocity for surface wave window
=====================================================================================================================
"""
try:
print self.cat
except AttributeError:
self.copy_catalog()
client = Client('IRIS')
evnumb = 0
L = len(self.cat)
try:
stime4down = obspy.core.utcdatetime.UTCDateTime(startdate)
except:
stime4down = obspy.UTCDateTime(0)
try:
etime4down = obspy.core.utcdatetime.UTCDateTime(enddate)
except:
etime4down = obspy.UTCDateTime()
pre_filt = (0.001, 0.005, 1, 100.0)
for event in self.cat:
event_id = event.resource_id.id.split('=')[-1]
magnitude = event.magnitudes[0].mag
Mtype = event.magnitudes[0].magnitude_type
event_descrip = event.event_descriptions[0].text+', '+event.event_descriptions[0].type
otime = event.origins[0].time
evlo = event.origins[0].longitude
evla = event.origins[0].latitude
evnumb +=1
if otime < stime4down or otime > etime4down:
continue
print('================================= Getting surface wave data ===================================')
print('Event ' + str(evnumb)+' : '+event_descrip+', '+Mtype+' = '+str(magnitude))
st = obspy.Stream()
if lon0!=None and lat0!=None:
dist, az, baz = obspy.geodetics.gps2dist_azimuth(evla, evlo, lat0, lon0) # distance is in m
dist = dist/1000.
starttime = otime+dist/vmax
endtime = otime+dist/vmin
commontime = True
else:
commontime = False
Ntraces = 0
for staid in self.waveforms.list():
netcode, stacode= staid.split('.')
stla, elev, stlo= self.waveforms[staid].coordinates.values()
if not commontime:
dist, az, baz = obspy.geodetics.gps2dist_azimuth(evla, evlo, stla, stlo) # distance is in m
dist = dist/1000.
Delta = obspy.geodetics.kilometer2degrees(dist)
if Delta<minDelta:
continue
if Delta>maxDelta:
continue
starttime = otime+dist/vmax
endtime = otime+dist/vmin
# skip to next station if deployment date out of the range
st_date = self.waveforms[staid].StationXML.networks[0].stations[0].start_date
ed_date = self.waveforms[staid].StationXML.networks[0].stations[0].end_date
if starttime > ed_date or endtime < st_date:
continue
try:
tr = client.get_waveforms(network=netcode, station=stacode, location='*', channel=channel,
starttime=starttime, endtime=endtime, attach_response=True)[0]
try:
temp_resp = tr.stats.response
except AttributeError:
N = 10
i = 0
get_resp= False
while (i < N) and (not get_resp):
tr = client.get_waveforms(network=netcode, station=stacode, location='*', channel=channel,
starttime=starttime, endtime=endtime, attach_response=True)[0]
try:
resp = tr.stats.response
get_resp = True
except AttributeError:
i += 1
if not get_resp:
if verbose:
print 'No data for:', staid
continue
Ntraces += 1
except:
if verbose:
print 'No data for:', staid
continue
tr.detrend()
try:
tr.remove_response(pre_filt=pre_filt, taper_fraction=0.1)
except:
if verbose:
print 'No data for:', staid
continue
if verbose:
print 'Getting data for:', staid
st += tr
print('====================== Downloaded : '+str(Ntraces)+' traces =============================')
tag = 'surf_ev_%05d' %evnumb
# adding waveforms
self.add_waveforms(st, event_id=event_id, tag=tag)
return
def get_love_waveforms(self, lon0=None, lat0=None, minDelta=-1, maxDelta=181, channel='LHE,LHN,LHZ', vmax=6.0, vmin=1.0, verbose=False,
startdate=None, enddate=None, do_rotation=True ):
"""Get Love wave data from IRIS server
====================================================================================================================
::: input parameters :::
lon0, lat0 - center of array. If specified, all waveform will have the same starttime and endtime
min/maxDelta - minimum/maximum epicentral distance, in degree
channel - Channel code, e.g. 'BHZ'.
Last character (i.e. component) can be a wildcard (‘?’ or ‘*’) to fetch Z, N and E component.
vmin, vmax - minimum/maximum velocity for surface wave window
=====================================================================================================================
"""
try:
print self.cat
except AttributeError:
self.copy_catalog()
client = Client('IRIS')
evnumb = 0
L = len(self.cat)
try:
stime4down = obspy.core.utcdatetime.UTCDateTime(startdate)
except:
stime4down = obspy.UTCDateTime(0)
try:
etime4down = obspy.core.utcdatetime.UTCDateTime(enddate)
except:
etime4down = obspy.UTCDateTime()
pre_filt = (0.001, 0.005, 1, 100.0)
for event in self.cat:
evnumb +=1
event_id = event.resource_id.id.split('=')[-1]
magnitude = event.magnitudes[0].mag
Mtype = event.magnitudes[0].magnitude_type
event_descrip = event.event_descriptions[0].text+', '+event.event_descriptions[0].type
otime = event.origins[0].time
evlo = event.origins[0].longitude
evla = event.origins[0].latitude
if otime < stime4down or otime > etime4down:
continue
print('================================= Getting surface wave data ===================================')
print('Event ' + str(evnumb)+' : '+str(otime)+' '+event_descrip+', '+Mtype+' = '+str(magnitude))
st = obspy.Stream()
if lon0!=None and lat0!=None:
dist, az, baz = obspy.geodetics.gps2dist_azimuth(evla, evlo, lat0, lon0) # distance is in m
dist = dist/1000.
starttime = otime+dist/vmax
endtime = otime+dist/vmin
commontime = True
else:
commontime = False
Nstreams = 0
for staid in self.waveforms.list():
netcode, stacode= staid.split('.')
stla, elev, stlo= self.waveforms[staid].coordinates.values()
location = self.waveforms[staid].StationXML[0].stations[0].channels[0].location_code
dist, az, baz = obspy.geodetics.gps2dist_azimuth(evla, evlo, stla, stlo) # distance is in m
# # # az, baz, dist = geodist.inv(evlo, evla, stlo, stla)
dist = dist/1000.
Delta = obspy.geodetics.kilometer2degrees(dist)
if Delta < minDelta:
continue
if Delta > maxDelta:
continue
if not commontime:
starttime = otime + dist/vmax
endtime = otime + dist/vmin
# skip to next station if deployment date out of the range
st_date = self.waveforms[staid].StationXML.networks[0].stations[0].start_date
ed_date = self.waveforms[staid].StationXML.networks[0].stations[0].end_date
if starttime > ed_date or endtime < st_date:
continue
try:
temp_st = client.get_waveforms(network=netcode, station=stacode, location=location, channel=channel,
starttime=starttime, endtime=endtime, attach_response=True)
if len(temp_st) < 3:
if verbose:
print 'No data for:', staid
continue
if len(temp_st.select(channel='*E')) == 0 or len(temp_st.select(channel='*N')) == 0:
if verbose:
print 'No data for:', staid
continue
# # #
# # # #----------------------------------------------
# # # # determine which location has three component
# # # #----------------------------------------------
# # # for tr0 in temp_st:
# # # loc0 = tr0.stats.location
# # # t1 = tr0.stats.starttime
# # # t2 = tr0.stats.endtime
# # # isE = False
# # # isN = False
# # # isZ = False
# # # out_st = obspy.Stream()
# # # for tr in temp_st:
# # # if tr.stats.location != loc0:
# # # continue
# # # if tr.stats.starttime != t1:
# # # continue
# # # if tr.stats.endtime != t2:
# # # continue
# # # if tr.stats.channel[-1] == 'E':
# # # isE = True
# # # trE = tr.copy()
# # # out_st.append(trE)
# # # if tr.stats.channel[-1] == 'N':
# # # isN = True
# # # trN = tr.copy()
# # # out_st.append(trN)
# # # if tr.stats.channel[-1] == 'Z':
# # # isZ = True
# # # trZ = tr.copy()
# # # out_st.append(trZ)
# # # if isE and isN and isZ:
# # # break
# # # # now, out_st has three traces with the same location code
# # # if len(out_st) != 3:
# # # if verbose:
# # # print 'No data for:', staid
# # # continue
# # # #----------------------------------------------
# # # # check response
# # # #----------------------------------------------
# # # final_st = obspy.Stream()
# # # for tr in out_st:
# # # try:
# # # temp_resp = tr.stats.response
# # # final_st.append(tr)
# # # except AttributeError:
# # # N = 10
# # # i = 0
# # # while (i < N):
# # # temp_tr = client.get_waveforms(network = tr.stats.network, station=tr.stats.station,\
# # # location = tr.stats.location, channel = tr.stats.channel, \
# # # starttime=starttime, endtime=endtime, attach_response=True)[0]
# # # try:
# # # resp = temp_tr.stats.response
# # # final_st.append(temp_tr)
# # # except AttributeError:
# # # i += 1
# # # if len(final_st) != 3:
# # # if verbose:
# # # print 'No data for:', staid
# # # continue
except:
if verbose:
print 'No data for:', staid
continue
temp_st.detrend()
try:
temp_st.remove_response(pre_filt=pre_filt, taper_fraction=0.1)
except:
if verbose:
print 'No data for:', staid
continue
#-----------
# rotation
#-----------
if do_rotation:
try:
temp_st.rotate('NE->RT', back_azimuth=baz)
except:
if verbose:
print 'No data for:', staid
continue
if verbose:
print 'Getting data for:', staid
st += temp_st
Nstreams+= 1
print('====================== Downloaded : '+str(Nstreams)+' streams =============================')
tag = 'surf_ev_%05d' %evnumb
# adding waveforms
self.add_waveforms(st, event_id=event_id, tag=tag)
return
def get_surf_waveforms_mp(self, outdir, lon0=None, lat0=None, minDelta=-1, maxDelta=181, channel='LHZ', vmax=6.0, vmin=1.0, verbose=False,
subsize=1000, deletemseed=False, nprocess=None, snumb=0, enumb=None, startdate=None, enddate=None):
"""Get surface wave data from IRIS server with multiprocessing
====================================================================================================================
::: input parameters :::
lon0, lat0 - center of array. If specified, all wave form will have the same starttime and endtime
min/maxDelta - minimum/maximum epicentral distance, in degree
channel - Channel code, e.g. 'BHZ'.
Last character (i.e. component) can be a wildcard (‘?’ or ‘*’) to fetch Z, N and E component.
vmin, vmax - minimum/maximum velocity for surface wave window
subsize - subsize of processing list, use to prevent lock in multiprocessing process
deletemseed - delete output MiniSeed files
nprocess - number of processes
snumb, enumb - start/end number of processing block
=====================================================================================================================
"""
client = Client('IRIS')
evnumb = 0
L = len(self.events)
if not os.path.isdir(outdir):
os.makedirs(outdir)
reqwaveLst = []
swave = snumb*subsize
iwave = 0
try:
stime4down = obspy.core.utcdatetime.UTCDateTime(startdate)
except:
stime4down = obspy.UTCDateTime(0)
try:
etime4down = obspy.core.utcdatetime.UTCDateTime(enddate)
except:
etime4down = obspy.UTCDateTime()
print('================================= Preparing for surface wave data download ===================================')
try:
print self.cat
except AttributeError:
self.copy_catalog()
for event in self.cat:
eventid = event.resource_id.id.split('=')[-1]
magnitude = event.magnitudes[0].mag
Mtype = event.magnitudes[0].magnitude_type
event_descrip = event.event_descriptions[0].text+', '+event.event_descriptions[0].type
evnumb +=1
otime = event.origins[0].time
evlo = event.origins[0].longitude
evla = event.origins[0].latitude
if otime < stime4down or otime > etime4down:
continue
if lon0!=None and lat0!=None:
dist, az, baz = obspy.geodetics.gps2dist_azimuth(evla, evlo, lat0, lon0) # distance is in m
dist = dist/1000.
starttime = otime+dist/vmax
endtime = otime+dist/vmin
commontime = True
else:
commontime = False
for staid in self.waveforms.list():
netcode, stacode= staid.split('.')
iwave += 1
if iwave < swave:
continue
stla, elev, stlo = self.waveforms[staid].coordinates.values()
if not commontime:
dist, az, baz = obspy.geodetics.gps2dist_azimuth(evla, evlo, stla, stlo) # distance is in m
dist = dist/1000.
Delta = obspy.geodetics.kilometer2degrees(dist)
if Delta<minDelta:
continue
if Delta>maxDelta:
continue
starttime = otime+dist/vmax
endtime = otime+dist/vmin
location = self.waveforms[staid].StationXML[0].stations[0].channels[0].location_code
reqwaveLst.append( requestInfo(evnumb=evnumb, network=netcode, station=stacode, location=location, channel=channel,
starttime=starttime, endtime=endtime, attach_response=True) )
print('============================= Start multiprocessing download surface wave data ===============================')
if len(reqwaveLst) > subsize:
Nsub = int(len(reqwaveLst)/subsize)
# if enumb==None: enumb=Nsub
for isub in range(Nsub):
# if isub < snumb: continue
# if isub > enumb: continue
print 'Subset:', isub+1,'in',Nsub,'sets'
creqlst = reqwaveLst[isub*subsize:(isub+1)*subsize]
GETDATA = partial(get_waveforms4mp, outdir=outdir, client=client, pre_filt = (0.001, 0.005, 1, 100.0), verbose=verbose, rotation=False)
pool = multiprocessing.Pool(processes=nprocess)
pool.map(GETDATA, creqlst) #make our results with a map call