-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathatacr_download_data.py
674 lines (595 loc) · 24.2 KB
/
atacr_download_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
#!/usr/bin/env python
# Copyright 2019 Pascal Audet & Helen Janiszewski
#
# This file is part of OBStools.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Import modules and functions
import numpy as np
import os.path
import pickle
import stdb
from obspy.clients.fdsn import Client
from obspy import Stream, UTCDateTime
from obstools.atacr import utils
from pathlib import Path
from argparse import ArgumentParser
from os.path import exists as exist
from numpy import nan
def get_daylong_arguments(argv=None):
"""
Get Options from :class:`~optparse.OptionParser` objects.
Calling options for the script `obs_download_data.py` that accompany this
package.
"""
parser = ArgumentParser(
usage="%(prog)s [options] <indb>",
description="Script used " +
"to download and pre-process up to four-component " +
"(H1, H2, Z and P), day-long seismograms to use in " +
"noise corrections of vertical component of OBS data. " +
"Data are requested from the internet using the client " +
"services framework for a given date range. The stations " +
"are processed one by one and the data are stored to disk.")
parser.add_argument(
"indb",
help="Station Database to process from.",
type=str)
# General Settings
parser.add_argument(
"--keys",
action="store",
type=str,
dest="stkeys",
default="",
help="Specify a comma-separated list of station keys " +
"for which to perform the analysis. These must be " +
"contained within the station database. Partial keys " +
"will be used to match against those in the dictionary. " +
"For instance, providing IU will match with all stations " +
"in the IU network. " +
"[Default processes all stations in the database]")
parser.add_argument(
"-C", "--channels",
action="store",
type=str,
dest="channels",
default="",
help="Specify a comma-separated list of channels for " +
"which to perform the transfer function analysis. " +
"Possible options are '12' (for horizontal channels 1 and 2) " +
"and/or 'P' (for pressure channel). Specifying '12' allows " +
"for tilt correction. Specifying 'P' allows for compliance " +
"correction. [Default '12,P' looks for both horizontal and " +
"pressure and allows for both tilt AND compliance corrections]")
parser.add_argument(
"--zcomp",
dest="zcomp",
type=str,
default="Z",
help="Specify the Vertical Component Channel Identifier. " +
"[Default Z].")
parser.add_argument(
"-O", "--overwrite",
action="store_true",
dest="ovr",
default=False,
help="Force the overwriting of pre-existing data. " +
"[Default False]")
# Server Settings
ServerGroup = parser.add_argument_group(
title="Server Settings",
description="Settings associated with which "
"datacenter to log into.")
ServerGroup.add_argument(
"--server",
action="store",
type=str,
dest="server",
default="IRIS",
help="Base URL of FDSN web service compatible "
"server (e.g. “http://service.iris.edu”) or key string for recognized "
"server (one of 'AUSPASS', 'BGR', 'EARTHSCOPE', 'EIDA', 'EMSC', 'ETH', "
"'GEOFON', 'GEONET', 'GFZ', 'ICGC', 'IESDMC', 'INGV', 'IPGP', 'IRIS', "
"'IRISPH5', 'ISC', 'KNMI', 'KOERI', 'LMU', 'NCEDC', 'NIEP', 'NOA', "
"'NRCAN', 'ODC', 'ORFEUS', 'RASPISHAKE', 'RESIF', 'RESIFPH5', 'SCEDC', "
"'TEXNET', 'UIB-NORSAR', 'USGS', 'USP'). [Default 'IRIS']")
ServerGroup.add_argument(
"--user-auth",
action="store",
type=str,
dest="userauth",
default=None,
help="Authentification Username and Password for the " +
"waveform server (--user-auth='username:authpassword') to access " +
"and download restricted data. [Default no user and password]")
ServerGroup.add_argument(
"--eida-token",
action="store",
type=str,
dest="tokenfile",
default=None,
help="Token for EIDA authentication mechanism, see " +
"http://geofon.gfz-potsdam.de/waveform/archive/auth/index.php. "
"If a token is provided, argument --user-auth will be ignored. "
"This mechanism is only available on select EIDA nodes. The token can "
"be provided in form of the PGP message as a string, or the filename "
"of a local file with the PGP message in it. [Default None]")
"""
# Database Settings
DataGroup = parser.add_argument_group(
title="Local Data Settings",
description="Settings associated with defining " +
"and using a local data base of pre-downloaded day-long SAC files.")
DataGroup.add_argument(
"--local-data",
action="store",
type=str,
dest="localdata",
default=None,
help="Specify a comma separated list of paths containing " +
"day-long sac files of data already downloaded. " +
"If data exists for a seismogram is already present on disk, " +
"it is selected preferentially over downloading " +
"the data using the Client interface")
DataGroup.add_argument(
"--no-data-zero",
action="store_true",
dest="ndval",
default=False,
help="Specify to force missing data to be set as zero, " +
"rather than default behaviour which sets to nan.")
"""
# Constants Settings
FreqGroup = parser.add_argument_group(
title='Frequency Settings',
description="Miscellaneous frequency settings")
FreqGroup.add_argument(
"--sampling-rate",
action="store",
type=float,
dest="new_sampling_rate",
default=5.,
help="Specify new sampling rate (float, in Hz). [Default 5.]")
FreqGroup.add_argument(
"--units",
action="store",
type=str,
dest="units",
default="DISP",
help="Choose the output seismogram units. Options are: " +
"'DISP', 'VEL', 'ACC'. [Default 'DISP']")
FreqGroup.add_argument(
"--pre-filt",
action="store",
type=str,
dest="pre_filt",
default=None,
help="Specify four comma-separated corner frequencies " +
"(float, in Hz) for deconvolution pre-filter. " +
"[Default 0.001,0.005,45.,50.]")
# Event Selection Criteria
DaysGroup = parser.add_argument_group(
title="Time Search Settings",
description="Time settings associated with searching " +
"for day-long seismograms")
DaysGroup.add_argument(
"--start",
action="store",
type=str,
dest="startT",
default="",
help="Specify a UTCDateTime compatible string representing " +
"the start day for the data search. This will override any " +
"station start times. " +
"[Default start date for each station in database]")
DaysGroup.add_argument(
"--end",
action="store",
type=str,
dest="endT",
default="",
help="Specify a UTCDateTime compatible string representing " +
"the start time for the event search. This will override any " +
"station end times [Default end date for each station in database]")
args = parser.parse_args(argv)
# Check inputs
if not exist(args.indb):
parser.error("Input file " + args.indb + " does not exist")
# create station key list
if len(args.stkeys) > 0:
args.stkeys = args.stkeys.split(',')
# create channel list
if len(args.channels) > 0:
args.channels = args.channels.split(',')
else:
args.channels = ["12", "P"]
for cha in args.channels:
if cha not in ["12", "P"]:
parser.error("Error: Channel not recognized " + str(cha))
# construct start time
if len(args.startT) > 0:
try:
args.startT = UTCDateTime(args.startT)
except Exception:
parser.error(
"Error: Cannot construct UTCDateTime from start time: " +
args.startT)
else:
args.startT = None
# construct end time
if len(args.endT) > 0:
try:
args.endT = UTCDateTime(args.endT)
except Exception:
parser.error(
"Error: Cannot construct UTCDateTime from end time: " +
args.endT)
else:
args.endT = None
# Parse restricted data settings
if args.tokenfile is not None:
args.userauth = [None, None]
else:
if args.userauth is not None:
tt = args.userauth.split(':')
if not len(tt) == 2:
msg = ("Error: Incorrect Username and Password Strings for " +
"User Authentification")
parser.error(msg)
else:
args.userauth = tt
else:
args.userauth = [None, None]
# # Parse Local Data directories
# if args.localdata is not None:
# args.localdata = args.localdata.split(',')
# else:
# args.localdata = []
# # Check NoData Value
# if args.ndval:
# args.ndval = 0.0
# else:
# args.ndval = nan
if args.units not in ['DISP', 'VEL', 'ACC']:
msg = ("Error: invalid --units argument. Choose among " +
"'DISP', 'VEL', or 'ACC'")
parser.error(msg)
if args.pre_filt is None:
args.pre_filt = [0.001, 0.005, 45., 50.]
else:
args.pre_filt = [float(val) for val in args.pre_filt.split(',')]
args.pre_filt = sorted(args.pre_filt)
if (len(args.pre_filt)) != 4:
msg = ("Error: --pre-filt should contain 4 " +
"comma-separated floats")
parser.error(msg)
return args
def main(args=None):
if args is None:
# Run Input Parser
args = get_daylong_arguments()
# Load Database
# stdb>0.1.3
try:
db, stkeys = stdb.io.load_db(fname=args.indb, keys=args.stkeys)
# stdb=0.1.3
except Exception:
db = stdb.io.load_db(fname=args.indb)
# Construct station key loop
allkeys = db.keys()
sorted(allkeys)
# Extract key subset
if len(args.stkeys) > 0:
stkeys = []
for skey in args.stkeys:
stkeys.extend([s for s in allkeys if skey in s])
else:
stkeys = db.keys()
sorted(stkeys)
# Loop over station keys
for stkey in list(stkeys):
# Extract station information from dictionary
sta = db[stkey]
# Define path to see if it exists
datapath = Path('DATA') / Path(stkey)
if not datapath.is_dir():
print('\nPath to '+str(datapath)+' doesn`t exist - creating it')
datapath.mkdir(parents=True)
# Establish client
client = Client(
base_url=args.server,
user=args.userauth[0],
password=args.userauth[1],
eida_token=args.tokenfile)
# Get catalogue search start time
if args.startT is None:
tstart = sta.startdate
else:
tstart = args.startT
# Get catalogue search end time
if args.endT is None:
tend = sta.enddate
else:
tend = args.endT
if tstart > sta.enddate or tend < sta.startdate:
continue
# Temporary print locations
tlocs = sta.location
if len(tlocs) == 0:
tlocs = ['']
for il in range(0, len(tlocs)):
if len(tlocs[il]) == 0:
tlocs[il] = "--"
sta.location = tlocs
# Update Display
print("\n|===============================================|")
print("|===============================================|")
print("| {0:>8s} |".format(
sta.station))
print("|===============================================|")
print("|===============================================|")
print("| Station: {0:>2s}.{1:5s} |".format(
sta.network, sta.station))
print("| Channel: {0:2s}; Locations: {1:15s} |".format(
sta.channel, ",".join(tlocs)))
print("| Lon: {0:7.2f}; Lat: {1:6.2f} |".format(
sta.longitude, sta.latitude))
print("| Start time: {0:19s} |".format(
sta.startdate.strftime("%Y-%m-%d")))
print("| End time: {0:19s} |".format(
sta.enddate.strftime("%Y-%m-%d")))
print("|-----------------------------------------------|")
print("| Searching day-long files: |")
print("| Start: {0:19s} |".format(
tstart.strftime("%Y-%m-%d")))
print("| End: {0:19s} |".format(
tend.strftime("%Y-%m-%d")))
# Split into 24-hour long segments
dt = 3600.*24.
t1 = tstart
t2 = tstart + dt
while t2 <= tend:
# Time stamp
tstamp = str(t1.year).zfill(4)+'.'+str(t1.julday).zfill(3)+'.'
print("\n"+"*"*60)
print("* Downloading day-long data for key {0} " +
" and day {1}.{2:03d}".format(stkey, t1.year, t1.julday))
print("*")
print("* Channels selected: "+str(args.channels)+' and vertical')
# Define file names (to check if files already exist)
# Horizontal 1 channel
file1 = datapath / (tstamp+'.'+sta.channel+'1.SAC')
# Horizontal 2 channel
file2 = datapath / (tstamp+'.'+sta.channel+'2.SAC')
# Vertical channel
fileZ = datapath / (tstamp+'.'+sta.channel+'Z.SAC')
# Pressure channel
fileP = datapath / (tstamp+'.'+sta.channel[0]+'DH.SAC')
if "P" not in args.channels:
# If data files exist, continue
if fileZ.exists() and file1.exists() and file2.exists():
if not args.ovr:
print(
"* "+tstamp +
"*SAC ")
print(
"* -> Files already exist, " +
"continuing ")
t1 += dt
t2 += dt
continue
channels = sta.channel.upper()+'1,'+sta.channel.upper() + \
'2,'+sta.channel.upper()+args.zcomp
# Get waveforms from client
try:
print("* "+tstamp +
"*SAC ")
print("* -> Downloading Seismic data... ")
sth = client.get_waveforms(
network=sta.network,
station=sta.station,
location=sta.location[0],
channel=channels,
starttime=t1,
endtime=t2,
attach_response=True)
print("* ...done")
except Exception:
print(" Error: Unable to download ?H? components - " +
"continuing")
t1 += dt
t2 += dt
continue
st = sth.merge()
elif "12" not in args.channels:
# If data files exist, continue
if fileZ.exists() and fileP.exists():
if not args.ovr:
print("* "+tstamp +
"*SAC ")
print("* -> Files already exist, " +
"continuing ")
t1 += dt
t2 += dt
continue
channels = sta.channel.upper() + args.zcomp
# Get waveforms from client
try:
print("* "+tstamp +
"*SAC ")
print("* -> Downloading Seismic data... ")
sth = client.get_waveforms(
network=sta.network,
station=sta.station,
location=sta.location[0],
channel=channels,
starttime=t1,
endtime=t2,
attach_response=True)
print("* ...done")
except Exception:
print(" Error: Unable to download ?H? components - " +
"continuing")
t1 += dt
t2 += dt
continue
try:
print("* -> Downloading Pressure data...")
stp = client.get_waveforms(
network=sta.network,
station=sta.station,
location=sta.location[0],
channel='?DH',
starttime=t1,
endtime=t2,
attach_response=True)
print("* ...done")
if len(stp) > 1:
print("WARNING: There are more than one ?DH trace")
print("* -> Keeping the highest sampling rate")
print(
"* -> Renaming channel to " +
sta.channel[0]+"DH")
if stp[0].stats.sampling_rate > \
stp[1].stats.sampling_rate:
stp = Stream(traces=stp[0])
else:
stp = Stream(traces=stp[1])
except Exception:
print(" Error: Unable to download ?DH component - " +
"continuing")
t1 += dt
t2 += dt
continue
st = sth.merge() + stp.merge()
else:
# If data files exist, continue
if (fileZ.exists() and file1.exists() and
file2.exists() and fileP.exists()):
if not args.ovr:
print("* "+tstamp +
"*SAC ")
print("* -> Files already exist, " +
"continuing ")
t1 += dt
t2 += dt
continue
channels = sta.channel.upper()+'1,'+sta.channel.upper() + \
'2,'+sta.channel.upper()+args.zcomp
# Get waveforms from client
try:
print("* "+tstamp +
"*SAC ")
print("* -> Downloading Seismic data... ")
sth = client.get_waveforms(
network=sta.network,
station=sta.station,
location=sta.location[0],
channel=channels,
starttime=t1,
endtime=t2,
attach_response=True)
print("* ...done")
except Exception:
print(" Error: Unable to download ?H? components - " +
"continuing")
t1 += dt
t2 += dt
continue
try:
print("* -> Downloading Pressure data...")
stp = client.get_waveforms(
network=sta.network,
station=sta.station,
location=sta.location[0],
channel='?DH',
starttime=t1,
endtime=t2,
attach_response=True)
print("* ...done")
if len(stp) > 1:
print("WARNING: There are more than one ?DH trace")
print("* -> Keeping the highest sampling rate")
print(
"* -> Renaming channel to " +
sta.channel[0]+"DH")
if stp[0].stats.sampling_rate > \
stp[1].stats.sampling_rate:
stp = Stream(traces=stp[0])
else:
stp = Stream(traces=stp[1])
except Exception:
print(" Error: Unable to download ?DH component - " +
"continuing")
t1 += dt
t2 += dt
continue
st = sth.merge() + stp.merge()
# Detrend, filter
st.detrend('demean')
st.detrend('linear')
st.filter(
'lowpass', freq=0.5*args.new_sampling_rate,
corners=2, zerophase=True)
st.resample(args.new_sampling_rate)
# Check streams
is_ok, st = utils.QC_streams(t1, t2, st)
if not is_ok:
t1 += dt
t2 += dt
continue
sth = st.select(component='1') + st.select(component='2') + \
st.select(component=args.zcomp)
# Remove responses
print("* -> Removing responses - Seismic data")
sth.remove_response(pre_filt=args.pre_filt, output=args.units)
# Extract traces - Z
trZ = sth.select(component=args.zcomp)[0]
trZ = utils.update_stats(
trZ, sta.latitude, sta.longitude, sta.elevation,
sta.channel+'Z')
trZ.write(str(fileZ), format='SAC')
# Extract traces - H
if "12" in args.channels:
tr1 = sth.select(component='1')[0]
tr2 = sth.select(component='2')[0]
tr1 = utils.update_stats(
tr1, sta.latitude, sta.longitude, sta.elevation,
sta.channel+'1')
tr2 = utils.update_stats(
tr2, sta.latitude, sta.longitude, sta.elevation,
sta.channel+'2')
tr1.write(str(file1), format='SAC')
tr2.write(str(file2), format='SAC')
# Extract traces - P
if "P" in args.channels:
stp = st.select(component='H')
print("* -> Removing responses - Pressure data")
stp.remove_response(pre_filt=args.pre_filt)
trP = stp[0]
trP = utils.update_stats(
trP, sta.latitude, sta.longitude, sta.elevation,
sta.channel[0]+'DH')
trP.write(str(fileP), format='SAC')
t1 += dt
t2 += dt
if __name__ == "__main__":
# Run main program
main()