forked from megies/obspyck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
1144 lines (1068 loc) · 46.4 KB
/
util.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
#-------------------------------------------------------------------
# Filename: util.py
# Purpose: Helper functions for ObsPyck
# Author: Tobias Megies, Lion Krischer
# Email: megies@geophysik.uni-muenchen.de
# License: GPLv2
#
# Copyright (C) 2010 Tobias Megies, Lion Krischer
#---------------------------------------------------------------------
import os
import sys
import math
import platform
import shutil
import subprocess
import copy
import tempfile
import glob
import fnmatch
import warnings
from StringIO import StringIO
import PyQt4
import numpy as np
import matplotlib as mpl
from matplotlib.colors import ColorConverter
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as QFigureCanvas
from matplotlib.widgets import MultiCursor as MplMultiCursor
import obspy
obspy.arclink.client.MAX_REQUESTS = 200
from obspy import UTCDateTime, read_inventory, read, Stream
try:
from obspy.core.util import gps2DistAzimuth
except:
from obspy.signal import gps2DistAzimuth
from obspy.core.util import getMatplotlibVersion, locations2degrees
from obspy.taup.taup import getTravelTimes
from obspy.fdsn import Client as FDSNClient
from obspy.arclink import Client as ArcLinkClient
from obspy.seishub import Client as SeisHubClient
from obspy.xseed import Parser
from rotate_to_zne import (
_rotate_specific_channels_to_zne, get_orientation_from_parser,
get_orientation)
mpl.rc('figure.subplot', left=0.05, right=0.98, bottom=0.10, top=0.92,
hspace=0.28)
mpl.rcParams['font.size'] = 10
COMMANDLINE_OPTIONS = (
# XXX wasn't working as expected
#(("--debug"), {'dest': "debug", 'action': "store_true",
# 'default': False,
# 'help': "Switch on Ipython debugging in case of exception"}),
(("-c", "--config"), {
'dest': "config_file", "type": "str",
'help': "Location of obspyck config file to use. If not "
"specified, obspyck looks up '~/.obspyckrc' (an example "
"configuration will be created if the file does not "
"exist)."}),
(("-s", "--station-combination"), {
'dest': "station_combination", "type": "str", "default": None,
'help': "Station combination to fetch data for (which must be "
"defined in config file). If not specified, the default "
"station combination specified in config file is used."}),
(("-t", "--time"), {
'dest': "time", "default": None,
'help': "Starttime of seismogram to retrieve. It takes a "
"string which UTCDateTime can convert. E.g. "
"'2010-01-10T05:00:00'"}),
(("-d", "--duration"), {
'type': "float", 'dest': "duration", "default": None,
'help': "Duration of seismogram in seconds"}),
(("-o", "--starttime-offset"), {
'type': "float", 'dest': "starttime_offset",
'default': None, 'help': "Offset to add to specified starttime "
"in seconds. Thus a time from an automatic picker can be used "
"with a specified offset for the starttime. E.g. to request a "
"waveform starting 30 seconds earlier than the specified time "
"use '-o -30'."}),
# (("--noevents",), {
# 'action': "store_true",
# 'dest': "noevents", 'default': False,
# 'help': "Deactivate fetching event data using FDSNWS and "
# "plotting theoretical arrivals."}),
(("--event",), {
'dest': "event", 'type': "str",
'default': '',
'help': "Filename (or path) of event file to load."}),
)
PROGRAMS = {
'nlloc': {'filenames': {'exe': "NLLoc", 'phases': "nlloc.obs",
'summary': "nlloc.hyp",
'scatter': "nlloc.scat"}},
'hyp_2000': {'filenames': {'exe': "hyp2000",'control': "bay2000.inp",
'phases': "hyp2000.pha",
'stations': "stations.dat",
'summary': "hypo.prt"}},
'focmec': {'filenames': {'exe': "rfocmec", 'phases': "focmec.dat",
'stdout': "focmec.stdout",
'summary': "focmec.out"}}}
SEISMIC_PHASES = ('P', 'S')
PHASE_COLORS = {'P': "red", 'S': "blue", 'Mag': "green"}
COMPONENT_COLORS = {'Z': "k", 'N': "b", 'E': "r"}
PHASE_LINESTYLES = {'P': "-", 'S': "-", 'Psynth': "--", 'Ssynth': "--",
'PErr1': "-", 'PErr2': "-", 'SErr1': "-", 'SErr2': "-"}
PHASE_LINEHEIGHT_PERC = {'P': 1, 'S': 1, 'Psynth': 1, 'Ssynth': 1,
'PErr1': 0.75, 'PErr2': 0.75, 'SErr1': 0.75, 'SErr2': 0.75}
KEY_FULLNAMES = {'P': "P pick", 'Psynth': "synthetic P pick",
'PWeight': "P pick weight", 'PPol': "P pick polarity",
'POnset': "P pick onset", 'PErr1': "left P error pick",
'PErr2': "right P error pick", 'S': "S pick",
'Ssynth': "synthetic S pick", 'SWeight': "S pick weight",
'SPol': "S pick polarity", 'SOnset': "S pick onset",
'SErr1': "left S error pick", 'SErr2': "right S error pick",
'MagMin1': "Magnitude minimum estimation pick",
'MagMax1': "Magnitude maximum estimation pick",
'MagMin2': "Magnitude minimum estimation pick",
'MagMax2': "Magnitude maximum estimation pick"}
WIDGET_NAMES = ("qToolButton_clearAll", "qToolButton_clearOrigMag",
"qToolButton_clearFocMec", "qToolButton_doHyp2000",
"qToolButton_doNlloc", "qComboBox_nllocModel",
"qToolButton_doFocMec", "qToolButton_showMap",
"qToolButton_showFocMec", "qToolButton_nextFocMec",
"qToolButton_showWadati", "qToolButton_getNextEvent",
"qToolButton_updateEventList", "qToolButton_sendNewEvent",
"qToolButton_replaceEvent",
"qToolButton_deleteEvent", "qCheckBox_public",
"qCheckBox_sysop", "qLineEdit_sysopPassword", "qComboBox_eventType",
"qToolButton_previousStream", "qLabel_streamNumber",
"qComboBox_streamName", "qToolButton_nextStream",
"qToolButton_overview", "qComboBox_phaseType", "qToolButton_rotateLQT",
"qToolButton_rotateZRT", "qToolButton_filter", "qToolButton_trigger",
"qToolButton_ms", "qDoubleSpinBox_waterlevel",
"qToolButton_arpicker", "qComboBox_filterType", "qCheckBox_zerophase",
"qLabel_highpass", "qDoubleSpinBox_highpass", "qLabel_lowpass",
"qDoubleSpinBox_lowpass",
"qDoubleSpinBox_corners", "qLabel_corners", "qCheckBox_50Hz",
"qTextEdit_qml", "qPushButton_qml_update",
"qLabel_sta", "qDoubleSpinBox_sta",
"qLabel_lta", "qDoubleSpinBox_lta", "qToolButton_spectrogram",
"qCheckBox_spectrogramLog", "qLabel_wlen", "qDoubleSpinBox_wlen",
"qLabel_perlap", "qDoubleSpinBox_perlap", "qPlainTextEdit_stdout",
"qPlainTextEdit_stderr")
#Estimating the maximum/minimum in a sample-window around click
MAG_PICKWINDOW = 10
MAG_MARKER = {'marker': (8, 2, 0), 'edgewidth': 1.8, 'size': 20}
AXVLINEWIDTH = 1.5
# dictionary for key-bindings.
# XXX Qt:
#KEYS = {'setPick': "Key_A", 'setPickError': "Key_S", 'delPick': "Key_Q",
# 'setMagMin': "Key_A", 'setMagMax': "Key_S", 'delMagMinMax': "Key_Q",
# 'switchPhase': "Key_Control",
# 'prevStream': "Key_Y", 'nextStream': "Key_X", 'switchWheelZoomAxis': "Key_Shift",
# 'setWeight': {'Key_0': 0, 'Key_1': 1, 'Key_2': 2, 'Key_3': 3},
# 'setPol': {'Key_U': "up", 'Key_D': "down", 'Key_Plus': "poorup", 'Key_Minus': "poordown"},
# 'setOnset': {'Key_I': "impulsive", 'Key_E': "emergent"}}
ROTATE_LQT_COMP_MAP = {"Z": "L", "N": "Q", "E": "T"}
ROTATE_ZRT_COMP_MAP = {"Z": "Z", "N": "R", "E": "T"}
S_POL_MAP_ZRT = {'R': {'up': "forward", 'down': "backward",
'poorup': "forward", 'poordown': "backward"},
'T': {'up': "right", 'down': "left",
'poorup': "right", 'poordown': "left"}}
S_POL_PHASE_TYPE = {'R': "SV", 'T': "SH"}
POLARITY_2_FOCMEC = {'Z': {'positive': "U", 'negative': "D"},
'R': {'positive': "F", 'negative': "B"},
'T': {'positive': "R", 'negative': "L"}}
# only strings involved, so shallow copy is fine
POLARITY_CHARS = {'positive': "+", 'negative': "-", 'undecidable': "?",
None: "_"}
ONSET_CHARS = {'impulsive': "I", 'emergent': "E", 'questionable': "?",
None: "_"}
LOGLEVELS = {'normal': "CRITICAL", 'verbose': "INFO", 'debug': "DEBUG",
'quiet': 100}
ONE_SIGMA = 68.3
TWO_SIGMA = 95.4
NOT_REIMPLEMENTED_MSG = ("Feature was not reimplemented after major "
"change to QuakeML.")
class QMplCanvas(QFigureCanvas):
"""
Class to represent the FigureCanvas widget.
"""
def __init__(self, parent=None):
# Standard Matplotlib code to generate the plot
self.fig = Figure()
# initialize the canvas where the Figure renders into
QFigureCanvas.__init__(self, self.fig)
self.setParent(parent)
def matplotlib_color_to_rgb(color):
"""
Converts matplotlib colors to rgb.
"""
rgb = ColorConverter().to_rgb(color)
return [int(_i*255) for _i in rgb]
def check_keybinding_conflicts(keys):
"""
check for conflicting keybindings.
we have to check twice, because keys for setting picks and magnitudes
are allowed to interfere...
"""
for ignored_key_list in [['setMagMin', 'setMagMax', 'delMagMinMax'],
['setPick', 'setPickError', 'delPick']]:
tmp_keys = copy.deepcopy(keys)
tmp_keys2 = {}
for ignored_key in ignored_key_list:
tmp_keys.pop(ignored_key)
while tmp_keys:
key, item = tmp_keys.popitem()
if isinstance(item, dict):
while item:
k, v = item.popitem()
tmp_keys2["_".join([key, str(v)])] = k
else:
tmp_keys2[key] = item
if len(set(tmp_keys2.keys())) != len(set(tmp_keys2.values())):
err = "Interfering keybindings. Please check variable KEYS"
raise Exception(err)
def fetch_waveforms_with_metadata(options, args, config):
"""
Sets up obspy clients and fetches waveforms and metadata according to
command line options.
Now also fetches data via arclink if --arclink-ids is used.
Args are tried to read as local waveform files or metadata files.
XXX Notes: XXX
- there is a problem in the arclink client with duplicate traces in
fetched streams. therefore at the moment it might be necessary to use
"-m overwrite" option.
:returns: (dictionary with clients,
list(:class:`obspy.core.stream.Stream`s))
"""
if options.station_combination is None:
station_combination = config.get("base", "station_combination")
else:
station_combination = options.station_combination
no_metadata = config.getboolean("base", "no_metadata")
if options.time is None:
time_ = UTCDateTime(config.get("base", "time"))
else:
time_ = UTCDateTime(options.time)
t1 = time_ + config.getfloat("base", "starttime_offset")
if options.duration is None:
t2 = t1 + config.getfloat("base", "duration")
else:
t2 = t1 + options.duration
seed_ids_to_fetch = {}
seed_ids = config.get("station_combinations", station_combination)
seed_id_lookup_keys = config.options("seed_id_lookup")
for seed_id in seed_ids.split(","):
netstaloc = seed_id.rsplit(".", 1)[0]
netsta = seed_id.rsplit(".", 2)[0]
net = seed_id.rsplit(".", 3)[0]
# look up by exact SEED ID:
if seed_id in seed_id_lookup_keys:
seed_ids_to_fetch[seed_id] = config.get("seed_id_lookup", seed_id)
# look up by SEED ID down to location code
elif netstaloc in seed_id_lookup_keys:
seed_ids_to_fetch[seed_id] = config.get("seed_id_lookup",
netstaloc)
# look up by SEED ID down to station code
elif netsta in seed_id_lookup_keys:
seed_ids_to_fetch[seed_id] = config.get("seed_id_lookup", netsta)
# look up by network code
elif net in seed_id_lookup_keys:
seed_ids_to_fetch[seed_id] = config.get("seed_id_lookup", net)
clients = {}
streams = []
sta_fetched = set()
# Local files:
parsers = []
inventories = []
if args:
print "=" * 80
print "Reading local files:"
print "-" * 80
stream_tmp = Stream()
for file in args:
# try to read as metadata
try:
p = Parser(file)
except:
pass
else:
print "%s: Metadata" % file
parsers.append(p)
continue
# try to read as metadata
try:
inv = read_inventory(file)
except:
pass
else:
print "%s: Metadata" % file
inventories.append(inv)
continue
# try to read as waveforms
try:
st = read(file, starttime=t1, endtime=t2,
verify_chksum=not config.getboolean("base", "ignore_gse2_chksum_error"))
except TypeError:
print "File %s not recognized as dataless or waveform file. Skipped." % file
continue
msg = "%s: Waveforms" % file
if not st:
msg += " (not matching requested time window)"
print msg
stream_tmp += st
if len(parsers + inventories) == 0:
msg = "No station metadata for waveforms from local files."
raise Exception(msg)
for tr in stream_tmp:
if not no_metadata:
has_metadata = False
for inv in inventories:
try:
tr.attach_response(inv)
tr.stats.coordinates = inv.get_coordinates(
tr.id, tr.stats.starttime)
tr.stats.orientation = get_orientation(
inv, tr.id, tr.stats.starttime)
has_metadata = True
break
except:
continue
if not has_metadata:
for parser in parsers:
try:
tr.stats.paz = parser.getPAZ(tr.id, tr.stats.starttime)
tr.stats.coordinates = parser.getCoordinates(tr.id, tr.stats.starttime)
tr.stats.orientation = get_orientation_from_parser(parser, tr.id, tr.stats.starttime)
has_metadata = True
break
except:
continue
if not has_metadata:
print "found no metadata for %s!!!" % file
if tr.stats._format == 'GSE2':
apply_gse2_calib(tr)
ids = set([(tr.stats.network, tr.stats.station, tr.stats.location) for tr in stream_tmp])
for net, sta, loc in ids:
stream_tmp_ = stream_tmp.select(
network=net, station=sta, location=loc)
# check whether to attempt rotation
if config.has_section("rotate_channels"):
net_sta_loc = ".".join((net, sta, loc))
if net_sta_loc in config.options("rotate_channels"):
rotate_channels(st, net, sta, loc, config)
streams.append(stream_tmp_)
print "=" * 80
print "Fetching waveforms and metadata from servers:"
print "-" * 80
for seed_id, server in sorted(seed_ids_to_fetch.items()):
server_type = config.get(server, "type")
if server_type not in ("seishub", "fdsn", "jane", "arclink"):
msg = ("Unknown server type '{}' in server definition section "
"'{}' in config file.").format(server_type, server)
raise NotImplementedError(msg)
client = connect_to_server(server, config, clients)
net, sta, loc, cha = seed_id.split(".")
net_sta_loc = "%s.%s.%s" % (net, sta, loc)
# make sure we dont fetch a single station of
# one network twice (could happen with wildcards)
if any([char in net_sta_loc for char in '?*[]']):
msg = ("Wildcards in SEED IDs to fetch are only allowed in "
"channel part: {}").format(seed_id)
raise NotImplementedError(msg)
if net_sta_loc in sta_fetched:
print "%s (%s: %s) skipped! (Was already retrieved)" % (
seed_id.ljust(15), server_type, server)
continue
try:
sys.stdout.write("\r%s (%s: %s) ..." % (
seed_id.ljust(15), server_type, server))
sys.stdout.flush()
# SeisHub
if server_type == "seishub":
st = client.waveform.getWaveform(
net, sta, loc, cha, t1, t2, apply_filter=True)
if not no_metadata:
data = client.station.getList(
network=net, station=sta, datetime=t1)
if len(data) == 0:
msg = "No station metadata on server."
raise Exception(msg)
parsers = [
Parser(client.station.getResource(d['resource_name']))
for d in data]
for tr in st:
orientation = [
get_orientation_from_parser(p_, tr.id, datetime=t1)
for p_ in parsers]
coordinates = [
p_.getCoordinates(tr.id, datetime=t1)
for p_ in parsers]
paz = [
p_.getPAZ(tr.id, datetime=t1) for p_ in parsers]
# check for clashing multiple station metadata
for list_ in (orientation, coordinates, paz):
for i in range(1, len(list_))[::-1]:
if list_[i] == list_[0]:
list_.pop(i)
for list_, name in zip(
(orientation, coordinates, paz),
("orientation", "coordinates", "paz")):
if len(list_) > 1:
msg = ("Multiple matching station metadata "
"({}) on server: {}.").format(
name, list_)
raise Exception(msg)
tr.stats.orientation = orientation[0]
tr.stats.coordinates = coordinates[0]
tr.stats.paz = paz[0]
# ArcLink
elif server_type == "arclink":
st = client.getWaveform(
network=net, station=sta, location=loc, channel=cha,
starttime=t1, endtime=t2)
if not no_metadata:
parsers = {}
for net_, sta_, loc_, cha_ in set([
tuple(tr.id.split(".")) for tr in st]):
sio = StringIO()
client.saveResponse(sio, net_, sta_, loc_, cha_,
t1-10, t2+10)
sio.seek(0)
id_ = ".".join((net_, sta_, loc_, cha_))
parsers[id_] = Parser(sio)
for tr in st:
p_ = parsers[tr.id]
tr.stats.orientation = \
get_orientation_from_parser(p_, tr.id, datetime=t1)
tr.stats.coordinates = \
p_.getCoordinates(tr.id, datetime=t1)
tr.stats.paz = p_.getPAZ(tr.id, datetime=t1)
# FDSN (or JANE)
elif server_type in ("fdsn", "jane"):
st = client.get_waveforms(
network=net, station=sta, location=loc, channel=cha,
starttime=t1, endtime=t2)
if not no_metadata:
inventory = client.get_stations(
network=net, station=sta, location=loc,
level="response")
failed = st.attach_response(inventory)
if failed:
msg = ("Failed to get response for {}!").format(failed)
raise Exception(msg)
for tr in st:
tr.stats.coordinates = inventory.get_coordinates(
tr.id, tr.stats.starttime)
tr.stats.orientation = get_orientation(
inventory, tr.id, tr.stats.starttime)
sta_fetched.add(net_sta_loc)
sys.stdout.write("\r%s (%s: %s) fetched.\n" % (
seed_id.ljust(15), server_type, server))
sys.stdout.flush()
except Exception, e:
sys.stdout.write(
"\r%s (%s: %s) skipped! (Exception: %s)\n" % (
seed_id.ljust(15), server_type, server, e))
sys.stdout.flush()
continue
# check whether to attempt rotation
if not no_metadata:
if config.has_section("rotate_channels"):
if net_sta_loc in config.options("rotate_channels"):
rotate_channels(st, net, sta, loc, config)
# SeisHub
if server_type == "seishub":
for tr in st:
if tr.stats._format == 'GSE2':
apply_gse2_calib(tr)
tr.stats['_format'] = "SeisHub"
# ArcLink
elif server_type == "arclink":
for tr in st:
tr.stats['_format'] = "ArcLink"
# FDSN (or JANE)
elif server_type in ("fdsn", "jane"):
for tr in st:
tr.stats['_format'] = "FDSN"
streams.append(st)
print "=" * 80
return (clients, streams)
def rotate_channels(st, net, sta, loc, config):
net_sta_loc = ".".join((net, sta, loc))
channels = config.get("rotate_channels", net_sta_loc).split(",")
tr = st.select(id=".".join((net_sta_loc, channels[0])))[0]
paz = tr.stats.get("paz")
coordinates = tr.stats.get("coordinates")
response = tr.stats.get("response")
st = _rotate_specific_channels_to_zne(
st, net, sta, loc, channels)
for tr in st:
if paz is not None:
tr.stats.paz = copy.deepcopy(paz)
if coordinates is not None:
tr.stats.coordinates = copy.deepcopy(coordinates)
if response is not None:
tr.stats.response = copy.deepcopy(response)
def connect_to_server(server_name, config, clients):
"""
Return existing client for given server name or connect to server, add it
to the clients dictionary and return client.
:type server_name: str
:param server_name: Server name as specified by configuration file
:type config: :class:`ConfigParser.ConfigParser`
:param config: ObsPyck configuration.
:type clients: dict
:param clients: Dictionary with already connected servers, keys are server
names as specified in configuration, values are corresponding client
instances.
"""
if server_name in clients:
return clients[server_name]
server_type = config.get(server_name, "type")
# # doesnt work on obspy <1.0, so set it above on module level:
# ArcLinkClient.max_status_requests = 2000
client_classes = {
"arclink": ArcLinkClient,
"fdsn": FDSNClient,
"jane": FDSNClient,
"seishub": SeisHubClient}
if server_type not in client_classes.keys():
msg = ("Unknown server type '{}' in server definition section "
"'{}' in config file.").format(server_type, server_name)
raise NotImplementedError(msg)
config_keys = {
"arclink": (
"host", "port", "user", "password", "institution", "timeout",
"dcid_key_file", "debug", "command_delay", "status_delay"),
"fdsn": (
"base_url", "user", "password", "user_agent", "debug", "timeout"),
"jane": (
"base_url", "user", "password", "user_agent", "debug", "timeout"),
"seishub": (
"base_url", "user", "password", "timeout", "debug", "retries"),
}
config_getters = {
"port": config.getint, "timeout": config.getfloat,
"debug": config.getboolean, "command_delay": config.getfloat,
"status_delay": config.getfloat, "retries": config.getint}
kwargs = {}
for key in config_keys[server_type]:
value = config_getters.get(key, config.get)(server_name, key) or None
if value is not None:
kwargs[key] = value
client = client_classes[server_type](**kwargs)
clients[server_name] = client
return client
def merge_check_and_cleanup_streams(streams, options, config):
"""
Cleanup given list of streams so that they conform with what ObsPyck
expects.
Conditions:
- either one Z or three ZNE traces
- no two streams for any station (of same network)
- no streams with traces of different stations
:returns: (warn_msg, merge_msg, list(:class:`obspy.core.stream.Stream`s))
"""
# we need to go through streams/dicts backwards in order not to get
# problems because of the pop() statement
warn_msg = ""
merge_msg = ""
# Merge on every stream if this option is passed on command line:
for st in streams:
st.merge(method=-1)
merge_type = config.get("base", "merge")
if merge_type:
if merge_type == "safe":
for st in streams:
st.merge(method=0)
elif merge_type == "overwrite":
for st in streams:
if st.getGaps() and max([gap[-1] for gap in st.getGaps()]) < 5:
msg = 'Interpolated over gap(s) with less than 5 ' + \
'samples for station: %s.%s'
msg = msg % (st[0].stats.network, st[0].stats.station)
warn_msg += msg + "\n"
st.merge(method=1, fill_value="interpolate")
else:
st.merge(method=1)
else:
err = "Unrecognized config value for merging traces. Try " + \
"'safe' or 'overwrite' (or leave empty)."
raise Exception(err)
# Sort streams again, if there was a merge this could be necessary
for st in streams:
st.sort(reverse=True)
sta_list = set()
# XXX we need the list() because otherwise the iterator gets garbled if
# XXX removing streams inside the for loop!!
for st in list(streams):
# check for streams with mixed stations/networks and remove them
if len(st) != len(st.select(network=st[0].stats.network,
station=st[0].stats.station)):
msg = "Warning: Stream with a mix of stations/networks. " + \
"Discarding stream."
print msg
warn_msg += msg + "\n"
streams.remove(st)
continue
net_sta = "%s.%s" % (st[0].stats.network.strip(),
st[0].stats.station.strip())
# Here we make sure that a station/network combination is not
# present with two streams.
if net_sta in sta_list:
msg = ("Warning: Station/Network combination '%s' "
"already in stream list. Discarding stream.") % net_sta
print msg
warn_msg += msg + "\n"
streams.remove(st)
continue
if len(st) not in [1, 3]:
msg = 'Warning: All streams must have either one Z trace ' + \
'or a set of three ZNE traces.'
print msg
warn_msg += msg + "\n"
# remove all unknown channels ending with something other than
# Z/N/E and try again...
removed_channels = ""
for tr in st:
if tr.stats.channel[-1] not in ["Z", "N", "E"]:
removed_channels += " " + tr.stats.channel
st.remove(tr)
if len(st.traces) in [1, 3]:
msg = 'Warning: deleted some unknown channels in ' + \
'stream %s.%s' % (net_sta, removed_channels)
print msg
warn_msg += msg + "\n"
continue
else:
msg = 'Stream %s discarded.\n' % net_sta + \
'Reason: Number of traces != (1 or 3)'
print msg
warn_msg += msg + "\n"
#for j, tr in enumerate(st.traces):
# msg = 'Trace no. %i in Stream: %s\n%s' % \
# (j + 1, tr.stats.channel, tr.stats)
msg = str(st)
print msg
warn_msg += msg + "\n"
streams.remove(st)
merge_msg = '\nIMPORTANT:\nYou can try the command line ' + \
'option merge (-m safe or -m overwrite) to ' + \
'avoid losing streams due gaps/overlaps.'
continue
if len(st) == 1 and st[0].stats.channel[-1] != 'Z':
msg = 'Warning: All streams must have either one Z trace ' + \
'or a set of three ZNE traces.'
msg += 'Stream %s discarded. Reason: ' % net_sta + \
'Exactly one trace present but this is no Z trace'
print msg
warn_msg += msg + "\n"
#for j, tr in enumerate(st.traces):
# msg = 'Trace no. %i in Stream: %s\n%s' % \
# (j + 1, tr.stats.channel, tr.stats)
msg = str(st)
print msg
warn_msg += msg + "\n"
streams.remove(st)
continue
if len(st) == 3 and (st[0].stats.channel[-1] != 'Z' or
st[1].stats.channel[-1] != 'N' or
st[2].stats.channel[-1] != 'E'):
msg = 'Warning: All streams must have either one Z trace ' + \
'or a set of three ZNE traces.'
msg += 'Stream %s discarded. Reason: ' % net_sta + \
'Exactly three traces present but they are not ZNE'
print msg
warn_msg += msg + "\n"
#for j, tr in enumerate(st.traces):
# msg = 'Trace no. %i in Stream: %s\n%s' % \
# (j + 1, tr.stats.channel, tr.stats)
msg = str(st)
print msg
warn_msg += msg + "\n"
streams.remove(st)
continue
sta_list.add(net_sta)
# demean traces if not explicitly deactivated on command line
if config.getboolean("base", "zero_mean"):
for st in streams:
try:
st.detrend('simple')
st.detrend('constant')
except NotImplementedError as e:
if "Trace with masked values found." in e.message:
msg = 'Detrending/demeaning not possible for station ' + \
'(masked Traces): %s' % net_sta
warn_msg += msg + "\n"
else:
raise
return (warn_msg, merge_msg, streams)
def cleanup_streams(streams, config):
"""
Function to remove streams that do not provide the necessary metadata.
:returns: (list(:class:`obspy.core.stream.Stream`s),
list(dict))
"""
# we need to go through streams/dicts backwards in order not to get
# problems because of the pop() statement
for i in range(len(streams))[::-1]:
st = streams[i]
trZ = st.select(component="Z")[0]
if len(st) == 3:
trN = st.select(component="N")[0]
trE = st.select(component="E")[0]
sta = trZ.stats.station.strip()
net = trZ.stats.network.strip()
if not config.get("base", "no_metadata"):
try:
trZ.stats.coordinates.get("longitude")
trZ.stats.coordinates.get("latitude")
trZ.stats.coordinates.get("elevation")
trZ.stats.get("paz")
if len(st) == 3:
trN.stats.get("paz")
trE.stats.get("paz")
except:
print 'Error: Missing metadata for %s.%s. Discarding stream.' \
% (net, sta)
streams.pop(i)
continue
return streams
def setup_external_programs(options, config):
"""
Sets up temdir, copies program files, fills in PROGRAMS dict, sets up
system calls for programs.
Depends on command line options, returns temporary directory.
:param options: Command line options of ObsPyck
:type options: options as returned by :meth:`optparse.OptionParser.parse_args`
:returns: String representation of temporary directory with program files.
"""
pluginpath = config.get("base", "pluginpath") or None
if pluginpath is None:
pluginpath = os.path.dirname(os.path.abspath(__file__))
if not os.path.isdir(pluginpath):
msg = "No such directory: '%s'" % pluginpath
raise IOError(msg)
tmp_dir = tempfile.mkdtemp(prefix="obspyck-")
# set binary names to use depending on architecture and platform...
env = os.environ
architecture = platform.architecture()[0]
system = platform.system()
global SHELL
if system == "Windows":
SHELL = True
else:
SHELL = False
# link velocity models ################################################
if os.path.exists(os.path.join(pluginpath, "VELOCITY_MODELS")):
os.symlink(os.path.join(pluginpath, "VELOCITY_MODELS"),
os.path.join(tmp_dir, "VELOCITY_MODELS"))
# Setup external programs #############################################
for prog_basename, prog_dict in PROGRAMS.iteritems():
prog_srcpath = os.path.join(pluginpath, prog_basename)
prog_tmpdir = os.path.join(tmp_dir, prog_basename)
prog_dict['dir'] = prog_tmpdir
shutil.copytree(prog_srcpath, prog_tmpdir, symlinks=True)
prog_dict['files'] = {}
for key, filename in prog_dict['filenames'].iteritems():
prog_dict['files'][key] = os.path.join(prog_tmpdir, filename)
prog_dict['files']['exe'] = "__".join(\
[prog_dict['filenames']['exe'], system, architecture])
# setup clean environment
prog_dict['env'] = {}
prog_dict['env']['PATH'] = prog_dict['dir'] + os.pathsep + env['PATH']
if 'SystemRoot' in env:
prog_dict['env']['SystemRoot'] = env['SystemRoot']
# Hyp2000 #############################################################
prog_dict = PROGRAMS['hyp_2000']
prog_dict['env']['HYP2000_DATA'] = prog_dict['dir'] + os.sep
def tmp(prog_dict):
files = prog_dict['files']
for file in [files['phases'], files['stations'], files['summary']]:
if os.path.isfile(file):
os.remove(file)
return
prog_dict['PreCall'] = tmp
def tmp(prog_dict):
sub = subprocess.Popen(prog_dict['files']['exe'], shell=SHELL,
cwd=prog_dict['dir'], env=prog_dict['env'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
input = open(prog_dict['files']['control'], "rt").read()
(msg, err) = sub.communicate(input)
if system == "Darwin":
returncode = sub.returncode
else:
returncode = sub.wait()
return (msg, err, returncode)
prog_dict['Call'] = tmp
# NLLoc ###############################################################
prog_dict = PROGRAMS['nlloc']
def tmp(prog_dict):
filepattern = os.path.join(prog_dict['dir'], "nlloc*")
print filepattern
for file in glob.glob(filepattern):
os.remove(file)
return
prog_dict['PreCall'] = tmp
def tmp(prog_dict, controlfilename):
sub = subprocess.Popen([prog_dict['files']['exe'], controlfilename],
cwd=prog_dict['dir'], env=prog_dict['env'], shell=SHELL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if system == "Darwin":
returncode = sub.returncode
else:
returncode = sub.wait()
msg = "".join(sub.stdout.readlines())
err = "".join(sub.stderr.readlines())
for pattern, key in [("nlloc.*.*.*.loc.scat", 'scatter'),
("nlloc.*.*.*.loc.hyp", 'summary')]:
pattern = os.path.join(prog_dict['dir'], pattern)
newname = os.path.join(prog_dict['dir'], prog_dict['files'][key])
for file in glob.glob(pattern):
os.rename(file, newname)
return (msg, err, returncode)
prog_dict['Call'] = tmp
# focmec ##############################################################
prog_dict = PROGRAMS['focmec']
def tmp(prog_dict):
sub = subprocess.Popen(prog_dict['files']['exe'], shell=SHELL,
cwd=prog_dict['dir'], env=prog_dict['env'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if system == "Darwin":
returncode = sub.returncode
else:
returncode = sub.wait()
msg = "".join(sub.stdout.readlines())
err = "".join(sub.stderr.readlines())
return (msg, err, returncode)
prog_dict['Call'] = tmp
#######################################################################
return tmp_dir
#Monkey patch (need to remember the ids of the mpl_connect-statements to remove them later)
#See source: http://matplotlib.sourcearchive.com/documentation/0.98.1/widgets_8py-source.html
class MultiCursor(MplMultiCursor):
def __init__(self, canvas, axes, useblit=True, **lineprops):
if hasattr(self, "id1"):
self.canvas.mpl_disconnect(self.id1)
self.canvas.mpl_disconnect(self.id2)
self.canvas = canvas
self.axes = axes
xmin, xmax = axes[-1].get_xlim()
xmid = 0.5*(xmin+xmax)
self.hlines = []
self.vlines = []
self.horizOn = False
self.vertOn = True
self.lines = [ax.axvline(xmid, visible=False, **lineprops) for ax in axes]
self.visible = True
self.useblit = useblit
self.background = None
self.needclear = False
self.id1 = self.canvas.mpl_connect('motion_notify_event', self.onmove)
self.id2 = self.canvas.mpl_connect('draw_event', self.clear)
@property
def lines(self):
if getMatplotlibVersion() < [1, 3, 0]:
return self.__dict__["lines"]
else:
return self.vlines
@lines.setter
def lines(self, value):
if getMatplotlibVersion() < [1, 3, 0]:
self.__dict__["lines"] = value
else:
self.vlines = value
def gk2lonlat(x, y, m_to_km=True):
"""
This function converts X/Y Gauss-Krueger coordinates (zone 4, central
meridian 12 deg) to Longitude/Latitude in WGS84 reference ellipsoid.
We do this using pyproj (python bindings for proj4) which can be installed
using 'easy_install pyproj' from pypi.python.org.
Input can be single coordinates or coordinate lists/arrays.
Useful Links:
http://pyproj.googlecode.com/svn/trunk/README.html
http://trac.osgeo.org/proj/
http://www.epsg-registry.org/
"""
import pyproj
proj_wgs84 = pyproj.Proj(init="epsg:4326")
proj_gk4 = pyproj.Proj(init="epsg:31468")
# convert to meters first
if m_to_km:
x = x * 1000.
y = y * 1000.
lon, lat = pyproj.transform(proj_gk4, proj_wgs84, x, y)
return (lon, lat)
def readNLLocScatter(scat_filename, textviewStdErrImproved):
"""
This function reads location and values of pdf scatter samples from the
specified NLLoc *.scat binary file (type "<f4", 4 header values, then 4
floats per sample: x, y, z, pdf value) and converts X/Y Gauss-Krueger
coordinates (zone 4, central meridian 12 deg) to Longitude/Latitude in
WGS84 reference ellipsoid.
Messages on stderr are written to specified GUI textview.
Returns an array of xy pairs.
"""
# read data, omit the first 4 values (header information) and reshape
data = np.fromfile(scat_filename, dtype="<f4").astype("float")[4:]
data = data.reshape((len(data)/4, 4)).swapaxes(0, 1)
lon, lat = gk2lonlat(data[0], data[1])
return np.vstack((lon, lat, data[2]))
def errorEllipsoid2CartesianErrors(azimuth1, dip1, len1, azimuth2, dip2, len2,
len3):
"""
This method converts the location error of NLLoc given as the 3D error
ellipsoid (two azimuths, two dips and three axis lengths) to a cartesian
representation.
We calculate the cartesian representation of each of the ellipsoids three
eigenvectors and use the maximum of these vectors components on every axis.
"""
z = len1 * np.sin(np.radians(dip1))
xy = len1 * np.cos(np.radians(dip1))
x = xy * np.sin(np.radians(azimuth1))
y = xy * np.cos(np.radians(azimuth1))
v1 = np.array([x, y, z])
z = len2 * np.sin(np.radians(dip2))
xy = len2 * np.cos(np.radians(dip2))
x = xy * np.sin(np.radians(azimuth2))
y = xy * np.cos(np.radians(azimuth2))
v2 = np.array([x, y, z])
v3 = np.cross(v1, v2)
v3 /= np.sqrt(np.dot(v3, v3))
v3 *= len3
v1 = np.abs(v1)
v2 = np.abs(v2)
v3 = np.abs(v3)
error_x = max([v1[0], v2[0], v3[0]])
error_y = max([v1[1], v2[1], v3[1]])
error_z = max([v1[2], v2[2], v3[2]])
return (error_x, error_y, error_z)
def formatXTicklabels(x, *pos):
"""
Make a nice formatting for y axis ticklabels: minutes:seconds.microsec
"""
# x is of type numpy.float64, the string representation of that float
# strips of all tailing zeros
# pos returns the position of x on the axis while zooming, None otherwise