-
Notifications
You must be signed in to change notification settings - Fork 7
/
pytheas.py
5842 lines (5506 loc) · 278 KB
/
pytheas.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
================================================================================
Pytheas: an open-source software solution for local shear-wave splitting studies
================================================================================
Pytheas is a tool that aims to introduce a new mentality in shear-wave splitting analysis
from local recordings, incorporating manual, semi- and fully- automatic methods under one
Graphical User Interface. Integrating databases and offering compatibility with popular data
and metadata file formats, Pytheas is designed with the simplification of analysis in mind,
while, at the same time, enhanching the effectiveness of processing and quality control of results.
Pytheas is released under the GNU GPLv3 license.
Authors: Spingos I. & Kaviris G. (c) 2019-2020
Special thanks to Millas C. for testing the software and providing valuable feedback from the
very early stages of this endeavor!
For any issues, comments or suggestions please contact us at ispingos@geol.uoa.gr or through GitHub
at https://www.github.com/ispingos/pytheas-splitting
"""
LIC_STR=("""
Pytheas // PYThon sHear - wavE Analysis Suite
Copyright (C) 2019-2020 Spingos I. & Kaviris G.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
For additional information, questions or suggestions
please contact: ispingos@geol.uoa.gr
""")
global VERSION
global VERDATE
VERSION="0.2.1"
VERDATE="31/07/2020"
## first get script's path
import os
global WORKDIR
WORKDIR=os.path.dirname(os.path.realpath(__file__))
## splash screen ##
print("..: Starting module imports...")
# using tk cause it's easier/faster for this (and is in the PSL)
import tkinter as tk
splroot = tk.Tk()
splroot.overrideredirect(True)
# get screen width/height and set as global
global SCWIDTH
global SCHEIGHT
SCWIDTH = splroot.winfo_screenwidth()
SCHEIGHT = splroot.winfo_screenheight()
# grab image file and get its dimensions
splfile = os.path.join(WORKDIR, 'etc', 'images', 'splash_color.png')
splimage = tk.PhotoImage(file=splfile)
iwidth = splimage.width(); iheight=splimage.height()
# scale it to 40% of screen for better display
scale=SCWIDTH*0.4/iwidth
splimage=splimage.subsample(int(round(1/scale)))
iwidth=splimage.width(); iheight=splimage.height()
# center image
x=(SCWIDTH-iwidth)/2
y=(SCHEIGHT-iheight)/2
splroot.geometry('%dx%d+%d+%d' % (iwidth, iheight, x, y))
# init canvas
canvas=tk.Canvas(splroot,height=iheight,width=iwidth)
canvas.create_image(iwidth/2,iheight/2,image=splimage)
canvas.pack()
# show splash
splroot.update()
## imports ##
print("..: Loading modules...")
import sys
import shutil
import logging
from logging.handlers import RotatingFileHandler
import operator
import traceback
import time
import datetime
from glob import glob
import numpy as np
import scipy
from PyQt5 import QtWidgets, QtCore, QtGui
# ensure we're using Qt5 as the MPL backend
import matplotlib
matplotlib.use("Qt5Agg")
# continue with imports
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.ticker import LinearLocator, NullLocator
from matplotlib.collections import LineCollection
from matplotlib.backends.backend_qt5agg \
import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backend_bases import MouseEvent
from matplotlib.widgets import MultiCursor
import configparser
from obspy import read, Stream, UTCDateTime, read_events, read_inventory
from obspy.geodetics.base import degrees2kilometers, gps2dist_azimuth
from obspy.taup import TauPyModel
from obspy.taup.taup_create import get_builtin_model_files as taup_get_builtin_model_files
from obspy.taup.velocity_model import VelocityModel
# pytheas imports
from lib import eigenvalue as SC
from lib import clustering as CA
from lib import rotationcorrelation as RC
from lib import db_handler as DB
from lib import tools
from lib import parsers
#-- make required directories
try:
os.makedirs(os.path.join(WORKDIR, 'logs'))
except: # if folder already exists
pass
try:
os.makedirs(os.path.join(WORKDIR, 'etc', 'options'))
except: # if folder already exists
pass
try:
os.makedirs(os.path.join(WORKDIR, 'etc', 'evcor'))
except: # if folder already exists
pass
try:
os.makedirs(os.path.join(WORKDIR, 'etc', 'index'))
except: # if folder already exists
pass
# init the log file
logfile=WORKDIR+os.sep+"logs%s%s_Pytheas.log" % (os.sep,UTCDateTime().strftime("%Y%m%d%H%M%S"))
# read the last used maxBytes value
try:
with open(WORKDIR + os.sep + "etc%soptions%slog_max_bytes" % (os.sep,os.sep), 'r') as fid:
MAX_BYTES = float(fid.read())
except FileNotFoundError:
MAX_BYTES = 50.
with open(WORKDIR + os.sep + "etc%soptions%slog_max_bytes" % (os.sep,os.sep), 'w') as fid:
fid.write(str(MAX_BYTES))
# setup rotating files
ROOT_LOGGER = logging.getLogger()
ROOT_LOGGER.setLevel(logging.DEBUG)
root_handler = RotatingFileHandler(logfile, maxBytes=MAX_BYTES * 1000000, # 50 MB
backupCount=100)
root_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
ROOT_LOGGER.addHandler(root_handler)
# setup logging to terminal
terminal=logging.StreamHandler()
terminal.setLevel(logging.DEBUG)
terminal.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logging.getLogger().addHandler(terminal)
# kill splash
splroot.destroy()
## Main Class ##
class Pytheas(QtWidgets.QMainWindow):
"""
Main class of the Pytheas software. Is responsible for building the
GUI and handling all functionality connected to it.
Uses a :class:`~PyQt5.QtWidgets.QMainWindow`
"""
def __init__(self):
"""Initiliaze main app window and setups labels, flags etc."""
logging.info("Start Application...")
# init the main window
QtWidgets.QMainWindow.__init__(self)
# variables
self.evWin = None
self.stWin = None
# check for default dirs. create them if needed
self.checkDefaultDirs()
# read configuration files
self.generalCNF = parsers.parseGeneralCnf(os.path.join(WORKDIR, 'etc', 'options', 'general.cnf'))
self.pkCNF = parsers.parsePickerCnf(os.path.join(WORKDIR, 'etc', 'options', 'picker.cnf'))
self.caCNF = parsers.parseClusteringCnf(os.path.join(WORKDIR, 'etc', 'options', 'clustering.cnf'))
self.tpCNF = parsers.parseTaupCnf(os.path.join(WORKDIR, 'etc', 'options', 'taup.cnf'))
self.gradeCNF = parsers.parseGradeCnf(os.path.join(WORKDIR, 'etc', 'options', 'grading.cnf'))
self.filterCNF = parsers.ParseFilterCnf(os.path.join(WORKDIR, 'etc', 'options', 'filters.cnf'))
# set icon and initial GUI params
self.appIcon = os.path.join(WORKDIR, 'etc', 'images', 'Pytheas_ICO.ico')
self.globalName = "Pytheas"
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setWindowTitle(self.globalName + ' v' + str(VERSION))
self.setWindowIcon(QtGui.QIcon(self.appIcon))
# set validators
self.validateInt = QtGui.QIntValidator()
self.validateFloat = QtGui.QDoubleValidator()
## set toolbar menus and actions
self.activateMenus = []
# set file menu
logging.debug("Set File Menu...")
self.fileMenu=QtWidgets.QMenu("&File",self)
self.fileMenu.addAction("&Open Catalogue",self.openCatWindow,QtCore.Qt.SHIFT+QtCore.Qt.Key_O)
self.fileMenu.addAction("&Preferences",self.prefWindow,QtCore.Qt.SHIFT+QtCore.Qt.Key_P)
self.fileMenu.addSeparator()
self.fileMenu.addAction("&Quit",self.onlyQuit)
self.menuBar().addMenu(self.fileMenu) # Add Open menu to bar
# set database menu
logging.debug("Set Database Menu...")
self.dbMenu=QtWidgets.QMenu("&Database",self)
self.dbMenu.addAction("Save As...",self.saveAsDB)
self.dbMenu.addAction("Load New",self.loadNewDB)
self.dbMenu.addAction("Save Solution to Database",self.saveSolution,QtCore.Qt.CTRL+QtCore.Qt.Key_S)
self.dbMenu.addAction("Load Solution from Database",self.getSolution)
self.dbMenu.addAction("Export...",self.dbWindowQuery)
self.dbMenu.addAction("Export Active",self.exportActive)
self.dbMenu.addAction("Export Figure",self.exportFigure)
self.menuBar().addMenu(self.dbMenu) # add db menu bar
self.dbMenu.setEnabled(False)
self.activateMenus.append(self.dbMenu)
# set view menu
logging.debug("Set View Menu...")
self.viewMenu=QtWidgets.QMenu("&View",self)
self.viewMenu.addAction("&Grid",self.changeGrid)
self.actionGrid=self.viewMenu.actions()[0] # Since only one item so far. Maybe add an if check?
self.actionGrid.setCheckable(True)
self.actionGrid.setChecked(False)
self.viewMenu.addAction("&Center S",self.centerS)
self.viewMenu.addAction("&Set X Axis Limits",self.applyXAxisLimits)
self.menuBar().addMenu(self.viewMenu) # add view menu bar
self.viewMenu.setEnabled(False)
self.activateMenus.append(self.viewMenu)
# set visual inspection menu
logging.debug("Set Visual Inspection Menu...")
self.visualMenu=QtWidgets.QMenu("&Manual",self)
self.visualMenu.addAction("&Initial Stage",self.goToInitial,QtCore.Qt.CTRL+QtCore.Qt.Key_1)
self.visualMenu.addAction("&Rotated Stage",self.goToRotated,QtCore.Qt.CTRL+QtCore.Qt.Key_2)
self.visualMenu.addAction("&Corrected Stage",self.goToCorrected,QtCore.Qt.CTRL+QtCore.Qt.Key_3)
self.visualMenu.addSeparator()
self.visualMenu.addAction("&Set phi",self.getPhi)
self.visualMenu.addAction("&Set time-delay",self.applyTimedelay,QtCore.Qt.CTRL+QtCore.Qt.Key_D)
self.visualMenu.addAction("&Set grade",self.getGrade,QtCore.Qt.CTRL+QtCore.Qt.Key_X)
self.visualMenu.addAction("&Set comment",self.getComment,QtCore.Qt.CTRL+QtCore.Qt.Key_G)
self.menuBar().addMenu(self.visualMenu) # Add Visual menu to bar
self.visualMenu.setEnabled(False)
self.activateMenus.append(self.visualMenu)
# set other methods menu
self.splitMenu=QtWidgets.QMenu("&Splitting",self)
self.splitMenu.addAction("&Set Shear-wave Window",self.getMaxAin)
self.splitMenu.addSeparator()
self.actRT=QtWidgets.QAction("&ZRT", checkable=True, checked=True)
self.actQT=QtWidgets.QAction("&LQT", checkable=True, checked=False)
self.rotGrp=QtWidgets.QActionGroup(self)
self.rotGrp.setExclusive(True)
self.rotGrp.addAction(self.actRT)
self.rotGrp.addAction(self.actQT)
self.splitMenu.addAction(self.actRT)
self.splitMenu.addAction(self.actQT)
self.splitMenu.addSeparator()
self.splitMenu.addAction("&Rotation-Correlation",self.applyRC,QtCore.Qt.CTRL+QtCore.Qt.Key_K)
self.splitMenu.addAction("&Eigenvalue",lambda: self.applyEV('EV'),QtCore.Qt.CTRL+QtCore.Qt.Key_L)
self.splitMenu.addAction("&Minimum Energy",lambda: self.applyEV('ME'),QtCore.Qt.CTRL+QtCore.Qt.Key_E)
self.splitMenu.addSeparator()
self.splitMenu.addAction("&Cluster Analysis (EV)",lambda: self.applyCA('EV',self.stream,self.filtered,self.freqmin,self.freqmax,
self.sPick,self.baz,self.ain,True,False
),QtCore.Qt.CTRL+QtCore.Qt.Key_T)
self.splitMenu.addAction("&Cluster Analysis (ME)",lambda: self.applyCA('ME',self.stream,self.filtered,self.freqmin,self.freqmax,
self.sPick,self.baz,self.ain,True,False
),QtCore.Qt.CTRL+QtCore.Qt.Key_U)
self.splitMenu.addAction("&Cluster Analysis (RC)",lambda: self.applyCA('RC',self.stream,self.filtered,self.freqmin,self.freqmax,
self.sPick,self.baz,self.ain,True,False
),QtCore.Qt.CTRL+QtCore.Qt.Key_Y)
self.splitMenu.addSeparator()
self.splitMenu.addAction("&Catalogue Cluster Analysis",self.caMultWindow,QtCore.Qt.SHIFT+QtCore.Qt.Key_A)
self.menuBar().addMenu(self.splitMenu) # Add Splitting menu to bar
self.splitMenu.setEnabled(False)
self.activateMenus.append(self.splitMenu)
# set navigation menu
logging.debug("Set Navigation Menu...")
self.navMenu=QtWidgets.QMenu("&Navigate",self)
self.navMenu.addAction("&Station List",self.stationsListWindow,QtCore.Qt.SHIFT+QtCore.Qt.Key_S)
self.navMenu.addAction("&Next Station",self.nextStation,QtCore.Qt.CTRL+QtCore.Qt.Key_W)
self.navMenu.addAction("&Previous Station",self.prevStation,QtCore.Qt.CTRL+QtCore.Qt.Key_Q)
self.navMenu.addSeparator()
self.navMenu.addAction("&Event List",self.eventsListWindow,QtCore.Qt.SHIFT+QtCore.Qt.Key_E)
self.navMenu.addAction("&Next Event",self.nextEvent,QtCore.Qt.SHIFT+QtCore.Qt.Key_N)
self.navMenu.addAction("&Previous Event",self.prevEvent,QtCore.Qt.SHIFT+QtCore.Qt.Key_B)
self.menuBar().addMenu(self.navMenu)
self.navMenu.setEnabled(False)
self.activateMenus.append(self.navMenu)
# set tools menu
logging.debug("Set Tools Menu...")
self.toolsMenu=QtWidgets.QMenu("&Tools",self)
self.toggleAR=QtWidgets.QAction("&AR-AIC", checkable=True, checked=False)
self.toggleAR.triggered.connect(self.changeAR)
self.toolsMenu.addAction(self.toggleAR)
self.toolsMenu.addSeparator()
# TODO: This is not yet ready
# self.toolsMenu.addAction("&Estimate Instrument Orientation",self.estimateOrientationMode,QtCore.Qt.CTRL+QtCore.Qt.Key_P)
self.toolsMenu.addSeparator()
self.toolsMenu.addAction("&Bandpass Filter",self.applyBandFilter,QtCore.Qt.CTRL+QtCore.Qt.Key_B)
self.toolsMenu.addAction("&Bandpass Preset 1", self.apply_preset_filter_1, QtCore.Qt.CTRL+QtCore.Qt.Key_F)
self.toolsMenu.addAction("&Bandpass Preset 2", self.apply_preset_filter_2, QtCore.Qt.CTRL+QtCore.Qt.Key_H)
self.toolsMenu.addAction("&Recommend Filter",self.applyRecFilter)
self.toolsMenu.addAction("&Auto-select Filter", self.automatic_filter_selection, QtCore.Qt.CTRL+QtCore.Qt.Key_A)
self.toolsMenu.addAction("&Remove filter",self.removeFilter,QtCore.Qt.CTRL+QtCore.Qt.Key_R)
self.toolsMenu.addAction("&Show Horizontal Spectra",self.plotSpectrum)
self.menuBar().addMenu(self.toolsMenu)
self.toolsMenu.setEnabled(False)
self.activateMenus.append(self.toolsMenu)
# disable actions to avoid errors before loading any data
for menu in self.activateMenus:
for action in menu.actions():
action.setEnabled(False)
# set the main widget and layout
logging.debug("Set Main Widget and Layout...")
self.mainWidg=QtWidgets.QWidget(self)
self.vLayout=QtWidgets.QVBoxLayout(self.mainWidg)
self.vLayout.setAlignment(QtCore.Qt.AlignCenter)
self.mainWidg.setStyleSheet("background-color:white;")
# Qt magic
self.dumWidg=QtWidgets.QWidget()
# set grid layout for the information widget
self.gLayout=QtWidgets.QGridLayout()
self.gLayout.setAlignment(QtCore.Qt.AlignCenter)
# set fonts for the information widget
self.lblFont=QtGui.QFont("Calibri",11,QtGui.QFont.Bold)
self.inpFont=QtGui.QFont("Calibri",11,QtGui.QFont.Normal)
# add the labels where information will be shown
self.lblOrigin=QtWidgets.QLabel("Pytheas v.%s" % VERSION,font=QtGui.QFont("Calibri",14,QtGui.QFont.Bold))
self.lblOrigin.setAlignment(QtCore.Qt.AlignCenter)
self.lblStation=QtWidgets.QLabel("V. Date: %s" % VERDATE,font=QtGui.QFont("Calibri",14,QtGui.QFont.Bold))
self.lblStation.setAlignment(QtCore.Qt.AlignCenter)
self.lblAIN=QtWidgets.QLabel("incidence ("+u"\u00b0"+"):",font=self.lblFont)
self.inpAIN=QtWidgets.QLabel("45",font=self.inpFont)
self.lblBAZ=QtWidgets.QLabel("backazimuth (N"+u"\u00b0"+"E):",font=self.lblFont)
self.inpBAZ=QtWidgets.QLabel("270",font=self.inpFont)
self.lblEPI=QtWidgets.QLabel("epicentral (km):",font=self.lblFont)
self.inpEPI=QtWidgets.QLabel("30",font=self.inpFont)
self.lblMAG=QtWidgets.QLabel("magnitude:",font=self.lblFont)
self.lblMAG.setFixedSize(64,20)
self.inpMAG=QtWidgets.QLabel("1.0",font=self.inpFont)
self.inpMAG.setFixedSize(32,20)
self.lblSNR=QtWidgets.QLabel("SNR:",font=self.lblFont)
self.inpSNR=QtWidgets.QLabel("5.9",font=self.inpFont)
self.lblSYS=QtWidgets.QLabel("System",font=self.lblFont)
self.inpSYS=QtWidgets.QLabel("ZNE",font=self.inpFont)
self.lblV2H=QtWidgets.QLabel("V<H",font=self.lblFont)
self.inpV2H=QtWidgets.QCheckBox()
self.inpV2H.setChecked(False)
self.inpV2H.toggled.connect(self.disableV2HToggle)
self.lblPHI=QtWidgets.QLabel("φ (N"+u"\u00b0"+"E):",font=self.lblFont)
self.inpPHI=QtWidgets.QLabel("130",font=self.inpFont)
self.lblTD=QtWidgets.QLabel("t<sub>d</sub> (ms): ",font=self.lblFont)
self.inpTD=QtWidgets.QLabel("50",font=self.inpFont)
self.lblPOL=QtWidgets.QLabel("pol (N"+u"\u00b0"+"E):",font=self.lblFont)
self.inpPOL=QtWidgets.QLabel("30",font=self.inpFont)
self.lblGRD=QtWidgets.QLabel("grade: ",font=self.lblFont)
self.lblGRD.setFixedSize(64,20)
self.inpGRD=QtWidgets.QLabel("X",font=self.inpFont)
self.inpGRD.setFixedSize(32,20)
self.lblFLT=QtWidgets.QLabel("Filter (Hz):",font=self.lblFont)
self.inpFLT=QtWidgets.QLabel("1.0|20.0",font=self.inpFont)
self.lblORN=QtWidgets.QLabel("Orient",font=self.lblFont)
self.inpORN=QtWidgets.QLabel("0.0",font=self.inpFont)
self.lblMET=QtWidgets.QLabel("Method:",font=self.lblFont)
self.inpMET=QtWidgets.QLabel("MAN",font=self.inpFont)
# add labels to grid
# first int is row, second int is column
self.gLayout.addWidget(self.lblOrigin,1,5)
self.gLayout.addWidget(self.lblStation,1,7)
self.gLayout.addWidget(self.lblAIN,2,1)
self.gLayout.addWidget(self.inpAIN,2,2)
self.gLayout.addWidget(self.lblBAZ,2,3)
self.gLayout.addWidget(self.inpBAZ,2,4)
self.gLayout.addWidget(self.lblEPI,2,5)
self.gLayout.addWidget(self.inpEPI,2,6)
self.gLayout.addWidget(self.lblMAG,2,7)
self.gLayout.addWidget(self.inpMAG,2,8)
self.gLayout.addWidget(self.lblSNR,2,9)
self.gLayout.addWidget(self.inpSNR,2,10)
self.gLayout.addWidget(self.lblSYS,2,11)
self.gLayout.addWidget(self.inpSYS,2,12)
self.gLayout.addWidget(self.lblV2H,2,13)
self.gLayout.addWidget(self.inpV2H,2,14)
self.gLayout.addWidget(self.lblPHI,3,1)
self.gLayout.addWidget(self.inpPHI,3,2)
self.gLayout.addWidget(self.lblTD,3,3)
self.gLayout.addWidget(self.inpTD,3,4)
self.gLayout.addWidget(self.lblPOL,3,5)
self.gLayout.addWidget(self.inpPOL,3,6)
self.gLayout.addWidget(self.lblGRD,3,7)
self.gLayout.addWidget(self.inpGRD,3,8)
self.gLayout.addWidget(self.lblORN,3,9)
self.gLayout.addWidget(self.inpORN,3,10)
self.gLayout.addWidget(self.lblFLT,3,11)
self.gLayout.addWidget(self.inpFLT,3,12)
self.gLayout.addWidget(self.lblMET,3,13)
self.gLayout.addWidget(self.inpMET,3,14)
# add the grid layout to the dummy widget and add it to
# the main layout
self.dumWidg.setLayout(self.gLayout)
self.vLayout.addWidget(self.dumWidg)
# make the placeholder MPL plot and add it to the main widget
logging.debug("Add Matplotlib plot...")
self.figDict=self.makeFig()
self.activeFig=self.figDict["FIGURE"]
self.axZ=self.figDict["TRACE"]["Z"]
self.axN=self.figDict["TRACE"]["N"]
self.axE=self.figDict["TRACE"]["E"]
self.axPolar=self.figDict["POLAR"]
self.axPart1=self.figDict["HOD1"]
self.axPart2=self.figDict["HOD2"]
self.axPart3=self.figDict["HOD3"]
self.colPal=self.figDict["PALETTE"]
self.addFig(self.activeFig)
# set the cursor
#self.mCursor=MultiCursor(self.activeFig.canvas,(self.axZ,self.axN,self.axE,self.axPolar),
# horizOn=True,vertOn=True,color='red', linewidth=1.5, linestyle='--')
# small hack
self.caCNF.maxTd = self.generalCNF.maxTd
# clean logs
self.cleanLogs()
# read inventory
try:
self.inventory,self.xmlInventory=self.readStations(self.tpCNF.stations)
except: # no station file! show a warning to the user...
logging.exception("Could not find station file %s" % self.tpCNF.stations)
winTitle="StationXML Warning"
genText="Could not read the StationXML!"
infText="Could not read %s " % self.tpCNF.stations
self.warnMsgBox(genText,infText,winTitle)
self.inventory=None
# set flags and various initial parameters
self.flagReset()
self.maxAin=np.inf
self.minSNR=0.0
# all done!
logging.debug("Set focus, central widget and navigation toolbar...")
self.setCentralWidget(self.mainWidg)
## SCIENCE FUNCTIONS ##
def calcV2H(self,pick,start=-0.5,end=0.5):
"""
Calculate the vertical to horizontal ratio of amplitudes for both
channels.
:type pick: float
:param pick: the arrival of the S-wave relative to the trace's start time (in s)
:type start: float, optional
:param start: start of the window for which the V/H ratio will be calculated,
relative to the S-arrival (in s). Defaults to -0.5.
:type end: float, optional
:param end: end of the window for which the V/H ratio will be calculated,
relative to the S-arrival (in s). Defaults to 0.5.
:returns: True if V<H and False if V>H
"""
## adjust windows to S pick
sps=self.stream[0].stats.sampling_rate
winstart=pick+start
idxstart=int(np.floor(sps*winstart))
winend=pick+end
idxend=int(np.ceil(sps*winend))
if (idxstart < 0) or (idxend > self.stream[0].stats.npts):
logging.warning("Not enough samples for V2H based on pick")
return False
## get arrays
H1="N"; H2="E"
if self.stageRotated: H1="R"; H2="T"
Z=self.stream.select(component="Z")[0].data[idxstart:idxend]
N=self.stream.select(component=H1)[0].data[idxstart:idxend]
E=self.stream.select(component=H2)[0].data[idxstart:idxend]
## return the ratios
return any((np.abs(Z).max()<np.abs(N).max(),np.abs(Z).max()<np.abs(E).max()))
def calcSNR(self,pick,winNoise=None,winSignal=None):
"""
Calculates the Signal-to-Noise Ratio (SNR) around the S-arrival (if picked)
or the middle of the selected signal window. The equation used is:
SNR = ( RMSsignal / RMSnoise)**2, where RMS = sqrt(sum(A**2))
The SNR is acquired for each horizontal component and their mean is defined
as the final value.
:type pick: float
:param pick: the arrival of the S-wave relative to the trace's start time (in s)
:type winNoise: float or None, optional
:param winNoise: start of the noise window (its end is the S-arrival/middle of window).
If None, its value is acquired from the Preferences. Defaults to None.
:type winSignal: float or None, optional
:param winSignal: end of the signal window (its start is the S-arrival/middle of window).
If None, its value is acquired from the Preferences. Defaults to None.
:returns: the average SNR of the horizontal waveforms
"""
# get windows bounds from Preferences?
if winNoise is None:
winNoise=self.generalCNF.snrStart
if winSignal is None:
winSignal=self.generalCNF.snrEnd
# grab the two horizontal waveforms
if self.stageRotated:
M1=self.stream.select(component="R")[0].data
M2=self.stream.select(component="T")[0].data
else:
M1=self.stream.select(component="N")[0].data
M2=self.stream.select(component="E")[0].data
# get indices of the signal and noise windows
idxNoise=int(np.floor((pick+winNoise)*self.stream[0].stats.sampling_rate))
idxSignl=int(np.ceil((pick+winSignal)*self.stream[0].stats.sampling_rate))
# however, if the bounds are beyond the length of the waveform...
if (idxNoise < 0) or (idxSignl > self.stream[0].stats.npts):
logging.warning("Not enough samples for SNR based on pick")
return 0
idxPick=int(pick*self.stream[0].stats.sampling_rate)
# calculate SNR for N/F channels
noise=M1[idxNoise:idxSignl]
signl=M1[idxPick:idxSignl]
RMSnoise=np.sqrt(np.mean(noise**2))
RMSsignl=np.sqrt(np.mean(signl**2))
SNR1=(RMSsignl/RMSnoise)**2
# calculate SNR for E/S channels
noise=M2[idxNoise:idxSignl]
signl=M2[idxPick:idxSignl]
RMSnoise=np.sqrt(np.mean(noise**2))
RMSsignl=np.sqrt(np.mean(signl**2))
SNR2=(RMSsignl/RMSnoise)**2
# get average SNR
SNR=(SNR1+SNR2)/2.0
if tools.isnone(SNR): # final check, just to be sure
SNR=0.0
return SNR
def tdCheck(self,td):
"""
Checks that the input time delay value is proper according to the
sampling rate and corrects it if it isn't.
:type td: float
:param td: the input time-delay (in s)
:returns: the corrected time-delay
"""
logging.debug("input td: "+str(td))
# get values straight from the trace object
df=self.stream[0].stats.delta
sps=self.stream[0].stats.sampling_rate
# convert dt to samples
td*=sps
# if no modulo then is fine
if td % sps:
td=np.ceil(td)
td*=df # convert back to s
logging.debug("input td was corrected to "+str(td))
else:
td*=df # convert back to s
logging.debug("input td is correct!")
return td
def rotation(self,phi,stream,method):
"""
Rotate the traces according to the measured Sfast polarization.
:type phi: float
:param phi: the Sfast polarization direction
:type stream: :class:`~obspy.core.stream.Stream`
:param stream: the stream containing the waveforms to be rotated
:type method: str
:param method: determines which rotation to perform. Must be either
"NE->RT" or "RT->NE".
:returns: the Stream object with the rotated waveforms.
"""
# first check start times. Differences of 1 sample or less
# are allowed.
delta=stream[0].stats.delta
try:
startNorth=stream.select(component="N")[0].stats.starttime
startEast=stream.select(component="E")[0].stats.starttime
except IndexError:
startNorth=stream.select(component="R")[0].stats.starttime
startEast=stream.select(component="T")[0].stats.starttime
if abs(startNorth - startEast) > delta:
raise ValueError("Components are not synced!")
# make the rotation matrix
M=tools.Rmatrix2D(phi)
# according to requested rotation
if method.upper() == "NE->RT":
ne=np.asarray((
stream.select(component="N")[0].data,
stream.select(component="E")[0].data
))
rt=np.dot(M,ne)
# assign new values to stream
stream.select(component="N")[0].data=rt[0]
stream.select(component="N")[0].stats.channel=\
stream.select(component="N")[0].stats.channel[:2]+"R"
stream.select(component="E")[0].data=rt[1]
stream.select(component="E")[0].stats.channel=\
stream.select(component="E")[0].stats.channel[:2]+"T"
elif method.upper() == "RT->NE":
rt=np.asarray((
stream.select(component="R")[0].data,
stream.select(component="T")[0].data
))
ne=np.dot(M.T,rt)
# assign new values to stream
stream.select(component="R")[0].data=ne[0]
stream.select(component="R")[0].stats.channel=\
stream.select(component="R")[0].stats.channel[:2]+"N"
stream.select(component="T")[0].data=ne[1]
stream.select(component="T")[0].stats.channel=\
stream.select(component="T")[0].stats.channel[:2]+"E"
return stream
def timedelay(self,td,stream,warning=True):
"""
Wrapper for adding the time-delay to the slow (transverse) component. Changes
occur in-place, so a new stream is not returned.
:type td: float
:param td: the time-delay
:type stream: :class:`~obspy.core.stream.Stream`
:param stream: stream where the time-delay will be added to
:type warning: bool, optional
:param warning: selects whether to log a warning if the time-delay
is attempted to be added in the initial stage. Defaults to True.
"""
if warning:
if not self.stageRotated and not self.stageCorrected:
logging.warning("Traces aren't rotated!")
return
try:
return tools.timedelay(td,stream)
except IndexError:
logging.warning("Traces have not been rotated!")
## ARCHIVING FUNCTIONS ##
def checkDefaultDirs(self):
"""Make the default directories."""
index_dir = os.path.join(WORKDIR, 'etc', 'index')
options_dir = os.path.join(WORKDIR, 'etc', 'options')
evcor_dir = os.path.join(WORKDIR, 'etc', 'evcor')
if not os.path.isdir(index_dir):
os.makedirs(index_dir)
logging.debug("Created %s" % index_dir)
if not os.path.isdir(options_dir):
os.makedirs(options_dir)
logging.debug("Created %s" % options_dir)
if not os.path.isdir(evcor_dir):
os.makedirs(evcor_dir)
logging.debug("Created %s" % evcor_dir)
def getTree(self,path):
"""
Get tree of directories that contain waveforms. It is mandatory for the
final branch to be named after the event code, e.g. %Y-%m-%d-%H-%M-%S
:type path: str
:param path: master directory that contains separate event folders.
:returns: a list of the event directories found
"""
fullEvents={}; n=0
for root,dirs,files in os.walk(path):
if files and not dirs:
n+=1
logging.debug("Adding path to event %i"%n)
fullEvents[os.path.split(root)[-1]]=root
return fullEvents
def getActiveStations(self):
"""
Gets station names that exist both in the waveform directory of the
active event and have arrivals in the catalogue.
:returns: a list of the station names
"""
evFolder=self.fullEvents[self.activeEvent]
staList=sorted(
self.statsDict[self.activeEvent],
key=lambda x:self.statsDict[self.activeEvent][x]["AN"]
)
activeStations=[]
for station in staList:
path=evFolder+os.sep+"*."+station+".*"
path = os.path.join(evFolder, '*.%s.*' % station)
try:
if glob(path)[0]:
activeStations.append(station)
except:
pass
return activeStations
def getActiveEvents(self):
"""
Gets events that exist both in the data directory and the
catalogue
:returns: a list of the active events
"""
activeEvents=[]
for event in sorted(self.evsDict):
try:
path=self.fullEvents[event]
if glob(path)[0]:
activeEvents.append(event)
except:
continue
return activeEvents
def readStations(self,staFile):
"""
Read the stations information file. Must be either a
StationXML or an ASCII file in the format:
station network latitude longitude elevation
:type staFile: str
:param staFile: path to the station information file
:returns: if the file is StationXML returns a tuple with
(a dict containing the station information,
the :class:`~obspy.core.stream.Inventory` object),
otherwise returns (a dict containing the station information, None)
"""
try:
# simple check to validate file is of xml type, as obspy's
# read_inventory sometimes parses non-xml files as xml
with open(staFile, 'r') as fid:
check_line = fid.readline()
if not '?xml version' in check_line:
raise TypeError('Input file is not StationXML')
# read the xml
xml=read_inventory(staFile)
inventory={}
for net in xml:
for sta in net:
inventory.update({sta.code:{"network":net.code,"latitude":sta.latitude,
"longitude":sta.longitude,"elevation":sta.elevation}})
return inventory, xml
except TypeError:
xml=None
with open(staFile,"r") as fid: staLines=fid.readlines()
return {x.split()[0]:
{
"network":x.split()[1],"latitude":float(x.split()[2]),
"longitude":float(x.split()[3]),"elevation":float(x.split()[4])
} for x in staLines
}, xml
except:
raise IOError("Could not read station file %s" % staFile)
def readEventCat(self,catFile):
"""
Read a simple catalogue file in the format of:
(origin time must be in the first 23 columns)
year mo da hr mn second latit longi depth magnitude
^
23
:type catFile: str
:param catFile: path to the catalogue file
:returns: (dict with event information, dict with arrival information)
"""
# initialize dictionaries
evsDict={}; statsDict={}
frmt="%Y-%m-%d-%H-%M-%S"
# read the file
with open(catFile,"r") as fid: catLines=fid.readlines()
for evid,line in enumerate(catLines):
try:
evDict=tools.initPytheasDict("event")
origin=UTCDateTime(line[:23])
dateKey=origin.strftime(frmt)
evlat=float(line[23:].strip().split()[0])
evlon=float(line[23:].strip().split()[1])
evdep=float(line[23:].strip().split()[2])
if not evdep:
evdep = 0.1 # temporary fix
mag=float(line[23:].strip().split()[3])
evDict["YEAR"]=origin.year
evDict["Mo"]=origin.month
evDict["Da"]=origin.day
evDict["HR"]=origin.hour
evDict["MN"]=origin.minute
evDict["SEC"]=origin.second+origin.microsecond/10**6
evDict["ORIGIN"]=origin
evDict["LAT"]=evlat; evDict["LON"]=evlon; evDict["DEPTH"]=evdep
evDict["MAG"]=mag; evDict["evID"]=str(evid)
# start adding stations
statsDict.update({dateKey:{}})
for station in sorted(self.inventory):
try:
staDict=tools.initPytheasDict("station")
# get distance and azimuth
dist,az,baz=gps2dist_azimuth(evlat,evlon,
self.inventory[station]["latitude"],
self.inventory[station]["longitude"])
# calculate ain for direct linear raypath #
ain=np.rad2deg(np.arctan((dist/1000.)/evdep))
# store values to dictionary
staDict['STA']=station
staDict['NET']=self.inventory[station]['network']
staDict['DIST']=dist/1000.
staDict['BAZ']=baz; staDict['AN']=ain
statsDict[dateKey].update({station:staDict})
except:
logging.exception("Could not process %s for %s" % (station,dateKey))
continue
# store values
evsDict.update({dateKey:evDict})
except:
logging.exception("Could not process %s" % dateKey)
continue
return evsDict,statsDict
def readQML(self,qmlFile):
"""
Read a QuakeML file.
:type catFile: str
:param catFile: path to the QuakeML file
:returns: (dict with event information, dict with arrival information)
"""
# Set event ID before running any loops
evID=0
# Read the actual QuakeML file.
logging.info("Attempting to read %s"%qmlFile)
try:
events=read_events(qmlFile)
except:
logging.exception("Could not read %s"%qmlFile)
return
# Create a dictionary for the event and arrival information.
evsDict={}; statsDict={}
for evid,event in enumerate(events):
try:
# first, update the evDict object
prefOrig=event.preferred_origin()
rid=prefOrig.resource_id
origin=prefOrig.time
originZero=UTCDateTime(year=origin.year,month=origin.month,day=origin.day,
hour=origin.hour,minute=origin.minute,second=0)
lat=prefOrig.latitude
lon=prefOrig.longitude
if tools.isnone(lat) or tools.isnone(lon):
logging.warning('Event %s does not have location information. Skipping...' % origin)
continue
try:
dep = prefOrig.depth/1000. # depth should be in km
if not dep:
dep = 0.1 # temporary fix
except TypeError: # is depth None?
dep = 0.1
# set pref mag before searching for corresponding r-id
mag=event.preferred_magnitude()
if mag is None:
magVal=np.nan
else:
for magRef in event.magnitudes:
if magRef.origin_id == rid:
mag=magRef
magVal=mag.mag
# parse to evDict object
evDict={'YEAR':origin.year,'Mo':origin.month,'Da':origin.day,'HR':origin.hour,
'MN':origin.minute,'SEC':origin.second+origin.microsecond/10**6, 'ORIGIN':origin,
'LAT':lat,'LON':lon,'DEPTH':dep,
'MAG':magVal,'evID':str(evid)}
frmt="%Y-%m-%d-%H-%M-%S"
dateKey=origin.strftime(frmt)
# now, need to make the staDict object
picksRef=event.picks; staDict={}; picks={}
for arr in prefOrig.arrivals:
pid=arr.pick_id
phase=arr.phase
# get the epicentral distance
try: # distance should be written in the file
dist=degrees2kilometers(arr.distance)
except:
dist=np.nan
# get the backazimuth
try:
baz=arr.backazimuth
except AttributeError: # if baz is not there, maybe az?
try:
baz=(arr.azimuth+180) % 360
except: # no az either?
baz=None
# get the angle of incidence
try: # if ain is not written
ain=arr.incidence_angle
except AttributeError: # maybe the takeoff is
try:
# calcualte the incidence angle from the takeoff
# as seen in Kapetanidis (2017).
ih=arr.takeoff_angle # takeoff angle
vTop=np.float(self.vmodel.evaluate_below(0,'s')) # velocity at station
vSrc=np.float(self.vmodel.evaluate_below(dep,'s')) # velocity at source
ain=np.rad2deg(np.arcsin((vTop/vSrc)*np.sin(np.deg2rad(ih))))
except:
ain=np.nan
## TODO: this should be added as a user-switch
##if dist > degrees2kilometers(1): # accept ONLY local phases. should this be a user option?
## continue
# check for phase and select
if phase not in ["p","P","s","S"]: # "P"/"S" accepted only cause of erroneous registration
continue # of direct upward local phases in the QuakeML
for tmp in picksRef: # get the station info for the arrival
if tmp.resource_id == pid: # match arrival to pick
station=tmp.waveform_id.station_code
network=tmp.waveform_id.network_code
component=tmp.waveform_id.channel_code
ptime=tmp.time
if not network: # can this happen?
network="XX" # should skip in that case?
if not station:
station="XXX"
continue
if not component:
component="XXX"
if any((tools.isnone(ain), tools.isnone(baz), tools.isnone(dist))):
# get distance and azimuth
if station not in self.inventory:
continue
gps=gps2dist_azimuth(
lat,lon,
self.inventory[station]["latitude"],
self.inventory[station]["longitude"]
)
# replace values where needed
if tools.isnone(dist):
dist=gps[0]/1000.
if tools.isnone(baz):
baz=gps[2]
if tools.isnone(ain):
# calculate ain for direct linear raypath
ain=np.rad2deg(np.arctan((dist)/dep))
if tools.isnone(ain): ain = 90.0
# get phase information
if phase in ['p','P']:
temp={'STA':station,'NET':network,'COM':component,
'DIST':dist,'BAZ':baz,'AN':ain,
'SECP':ptime-originZero,'TOBSP':ptime-origin}
if station in staDict:
staDict[station].update(temp)
else:
staDict.update({station:temp})
elif phase in ['s','S']:
temp={'STA':station,'NET':network,'COM':component, # re-adding these in case no
'DIST':dist,'BAZ':baz,'AN':ain, # P-arrival was found in the
'SECS':ptime-originZero,'TOBSS':ptime-origin} # QuakeML
if station in staDict:
staDict[station].update(temp)
else:
staDict.update({station:temp})
if not staDict:
logging.warning("No picks found for %s" % dateKey)
for station in sorted(self.inventory):
try:
tempDict=tools.initPytheasDict("station")
# get distance and azimuth
dist,az,baz=gps2dist_azimuth(lat,lon,
self.inventory[station]["latitude"],
self.inventory[station]["longitude"])
# calculate ain for direct linear raypath #
if dep == 0.0:
dep = 0.1 # hack to permit ain calc
ain=np.rad2deg(np.arctan((dist/1000.)/dep))
if tools.isnone(ain): ain = 0.0
# store values to dictionary
tempDict['STA']=station
tempDict['NET']=self.inventory[station]['network']
tempDict['DIST']=dist/1000.
tempDict['BAZ']=baz
tempDict['AN']=ain
staDict.update({station:tempDict})
except:
logging.exception("Could not process %s for %s" % (station,dateKey))