[cleanup] code cleanup by PyCharm

This commit is contained in:
Marcel Paffrath 2018-07-16 14:21:41 +02:00
parent 754d42c8e3
commit 7a0d3486a6
18 changed files with 285 additions and 269 deletions

115
PyLoT.py
View File

@ -48,7 +48,6 @@ from obspy.core.util import AttribDict
from pylot.core.util.obspyDMT_interface import check_obspydmt_structure from pylot.core.util.obspyDMT_interface import check_obspydmt_structure
try: try:
import pyqtgraph as pg import pyqtgraph as pg
except Exception as e: except Exception as e:
@ -195,7 +194,6 @@ class MainWindow(QMainWindow):
self.loc = False self.loc = False
def init_config_files(self, infile): def init_config_files(self, infile):
pylot_config_dir = os.path.join(os.path.expanduser('~'), '.pylot') pylot_config_dir = os.path.join(os.path.expanduser('~'), '.pylot')
if not os.path.exists(pylot_config_dir): if not os.path.exists(pylot_config_dir):
@ -210,7 +208,6 @@ class MainWindow(QMainWindow):
self._inputs.export2File(infile) self._inputs.export2File(infile)
self.infile = infile self.infile = infile
def setupUi(self): def setupUi(self):
try: try:
self.startTime = min( self.startTime = min(
@ -327,19 +324,19 @@ class MainWindow(QMainWindow):
# "Create a new event.") # "Create a new event.")
self.openEventAction = self.createAction(self, "Load event information...", self.openEventAction = self.createAction(self, "Load event information...",
self.load_data, self.load_data,
"Ctrl+M", "Ctrl+M",
openEventIcon, openEventIcon,
"Load event information for " "Load event information for "
"the displayed event.") "the displayed event.")
self.openEventAction.setEnabled(False) self.openEventAction.setEnabled(False)
self.openEventAction.setData(None) self.openEventAction.setData(None)
self.openEventsAutoAction = self.createAction(self, "Load event information &automatically ... ", self.openEventsAutoAction = self.createAction(self, "Load event information &automatically ... ",
self.load_multiple_data, self.load_multiple_data,
"Ctrl+A", "Ctrl+A",
openEventsIcon, openEventsIcon,
"Load event data automatically " "Load event data automatically "
"for all events.") "for all events.")
self.openEventsAutoAction.setEnabled(False) self.openEventsAutoAction.setEnabled(False)
self.openEventsAutoAction.setData(None) self.openEventsAutoAction.setData(None)
@ -360,7 +357,7 @@ class MainWindow(QMainWindow):
self.saveEventAction = self.createAction(self, "Save &event information ...", self.saveEventAction = self.createAction(self, "Save &event information ...",
self.saveData, "Ctrl+P", self.saveData, "Ctrl+P",
saveEventsIcon, "Save event pick data," saveEventsIcon, "Save event pick data,"
" source origin and magnitude.") " source origin and magnitude.")
self.disableSaveEventAction() self.disableSaveEventAction()
self.addEventDataAction = self.createAction(self, "Add &events ...", self.addEventDataAction = self.createAction(self, "Add &events ...",
@ -399,15 +396,15 @@ class MainWindow(QMainWindow):
"Ctrl+F", self.filter_icon, "Ctrl+F", self.filter_icon,
"""Adjust filter parameters.""") """Adjust filter parameters.""")
self.inventoryAction = self.createAction(self, "Select &Inventory ...", self.inventoryAction = self.createAction(self, "Select &Inventory ...",
self.get_new_metadata, self.get_new_metadata,
"Ctrl+I", self.inventoryIcon, "Ctrl+I", self.inventoryIcon,
"""Select metadata for current project""", """Select metadata for current project""",
False) False)
self.initMapAction = self.createAction(self, "Init array map ...", self.initMapAction = self.createAction(self, "Init array map ...",
self.init_array_map, self.init_array_map,
"Ctrl+M", self.mapIcon, "Ctrl+M", self.mapIcon,
"""Initialize array map with current metadata""", """Initialize array map with current metadata""",
False) False)
self.initMapAction.setEnabled(False) self.initMapAction.setEnabled(False)
self.selectPAction = self.createAction(self, "&P", self.alterPhase, self.selectPAction = self.createAction(self, "&P", self.alterPhase,
"Alt+P", "Alt+P",
@ -424,9 +421,9 @@ class MainWindow(QMainWindow):
"automatic pick " "automatic pick "
"data.", False) "data.", False)
self.compare_action.setEnabled(False) self.compare_action.setEnabled(False)
self.qualities_action = self.createAction(parent=self, text='Show pick qualitites...', self.qualities_action = self.createAction(parent=self, text='Show pick qualitites...',
slot=self.pickQualities, shortcut='Alt+Q', slot=self.pickQualities, shortcut='Alt+Q',
icon=qualities_icon, tip='Histogram of pick qualities') icon=qualities_icon, tip='Histogram of pick qualities')
self.qualities_action.setEnabled(False) self.qualities_action.setEnabled(False)
printAction = self.createAction(self, "&Print event ...", printAction = self.createAction(self, "&Print event ...",
@ -471,7 +468,6 @@ class MainWindow(QMainWindow):
checkable=True) checkable=True)
self.e_action.setEnabled(False) self.e_action.setEnabled(False)
componentActions = (self.z_action, self.n_action, self.e_action) componentActions = (self.z_action, self.n_action, self.e_action)
self.auto_tune = self.createAction(parent=self, text='autoTune', self.auto_tune = self.createAction(parent=self, text='autoTune',
@ -483,19 +479,19 @@ class MainWindow(QMainWindow):
self.auto_pick = self.createAction(parent=self, text='Current event', self.auto_pick = self.createAction(parent=self, text='Current event',
slot=self.autoPick, shortcut='Alt+Ctrl+A', slot=self.autoPick, shortcut='Alt+Ctrl+A',
icon=autopylot_icon, tip='Automatically pick' icon=autopylot_icon, tip='Automatically pick'
' the displayed waveforms.') ' the displayed waveforms.')
self.auto_pick.setEnabled(False) self.auto_pick.setEnabled(False)
self.auto_pick_local = self.createAction(parent=self, text='Whole project (local machine)...', self.auto_pick_local = self.createAction(parent=self, text='Whole project (local machine)...',
slot=self.autoPickProject, shortcut=None, slot=self.autoPickProject, shortcut=None,
icon=self.autopicksicon_small, tip='Automatically pick' icon=self.autopicksicon_small, tip='Automatically pick'
' the complete project on local machine.') ' the complete project on local machine.')
self.auto_pick_local.setEnabled(False) self.auto_pick_local.setEnabled(False)
self.auto_pick_sge = self.createAction(parent=self, text='Whole project (grid engine)...', self.auto_pick_sge = self.createAction(parent=self, text='Whole project (grid engine)...',
slot=self.autoPickProjectSGE, shortcut=None, slot=self.autoPickProjectSGE, shortcut=None,
icon=self.autopicksicon_small, tip='Automatically pick' icon=self.autopicksicon_small, tip='Automatically pick'
' the complete project on grid engine.') ' the complete project on grid engine.')
self.auto_pick_sge.setEnabled(False) self.auto_pick_sge.setEnabled(False)
pickActions = (self.auto_tune, self.auto_pick, self.compare_action, self.qualities_action) pickActions = (self.auto_tune, self.auto_pick, self.compare_action, self.qualities_action)
@ -527,10 +523,10 @@ class MainWindow(QMainWindow):
self.editMenu = self.menuBar().addMenu('&Edit') self.editMenu = self.menuBar().addMenu('&Edit')
editActions = (self.filterActionP, self.filterActionS, filterEditAction, None, editActions = (self.filterActionP, self.filterActionS, filterEditAction, None,
#self.selectPAction, self.selectSAction, None, # self.selectPAction, self.selectSAction, None,
self.inventoryAction, self.initMapAction, None, self.inventoryAction, self.initMapAction, None,
prefsEventAction) prefsEventAction)
#printAction) #TODO: print event? # printAction) #TODO: print event?
pickMenuActions = (self.parameterAction,) pickMenuActions = (self.parameterAction,)
self.pickMenu = self.menuBar().addMenu('&Picking') self.pickMenu = self.menuBar().addMenu('&Picking')
@ -546,13 +542,11 @@ class MainWindow(QMainWindow):
self.openProjectAction, self.saveProjectAction, self.openProjectAction, self.saveProjectAction,
self.saveProjectAsAction) self.saveProjectAsAction)
eventToolActions = (self.addEventDataAction, eventToolActions = (self.addEventDataAction,
self.openEventAction, self.openEventsAutoAction, self.openEventAction, self.openEventsAutoAction,
self.saveEventAction, self.loadlocationaction, self.saveEventAction, self.loadlocationaction,
self.loadpilotevent) self.loadpilotevent)
toolbars_keys = [ toolbars_keys = [
"FileTools", "FileTools",
"EventTools", "EventTools",
@ -892,7 +886,7 @@ class MainWindow(QMainWindow):
fext = '.xml' fext = '.xml'
for event in events: for event in events:
path = event.path path = event.path
eventname = path.split('/')[-1] #or event.pylot_id eventname = path.split('/')[-1] # or event.pylot_id
filename = os.path.join(path, 'PyLoT_' + eventname + fext) filename = os.path.join(path, 'PyLoT_' + eventname + fext)
if os.path.isfile(filename): if os.path.isfile(filename):
self.load_data(filename, draw=False, event=event, overwrite=True) self.load_data(filename, draw=False, event=event, overwrite=True)
@ -965,7 +959,7 @@ class MainWindow(QMainWindow):
button.setAutoFillBackground(True) button.setAutoFillBackground(True)
elif type(color) == str: elif type(color) == str:
button.setStyleSheet('QPushButton{border-color: %s}' button.setStyleSheet('QPushButton{border-color: %s}'
'QPushButton:checked{background-color: rgba%s}'% (color, color)) 'QPushButton:checked{background-color: rgba%s}' % (color, color))
elif type(color) == tuple: elif type(color) == tuple:
button.setStyleSheet('QPushButton{border-color: rgba%s}' button.setStyleSheet('QPushButton{border-color: rgba%s}'
'QPushButton:checked{background-color: rgba%s}' % (str(color), str(color))) 'QPushButton:checked{background-color: rgba%s}' % (str(color), str(color)))
@ -1195,7 +1189,7 @@ class MainWindow(QMainWindow):
def user_modify_path(self, reason=''): def user_modify_path(self, reason=''):
dialog = QtGui.QInputDialog(parent=self) dialog = QtGui.QInputDialog(parent=self)
new_path, executed = dialog.getText(self, 'Change Project rootpath', new_path, executed = dialog.getText(self, 'Change Project rootpath',
'{}Rename project path {}:'.format(reason, self.project.rootpath)) '{}Rename project path {}:'.format(reason, self.project.rootpath))
return new_path, executed return new_path, executed
def data_check(self): def data_check(self):
@ -1282,7 +1276,7 @@ class MainWindow(QMainWindow):
time = lat = lon = depth = mag = None time = lat = lon = depth = mag = None
if len(event.origins) == 1: if len(event.origins) == 1:
origin = event.origins[0] origin = event.origins[0]
time = origin.time + 0 # add 0 because there was an exception for time = 0s time = origin.time + 0 # add 0 because there was an exception for time = 0s
lat = origin.latitude lat = origin.latitude
lon = origin.longitude lon = origin.longitude
depth = origin.depth depth = origin.depth
@ -1335,7 +1329,7 @@ class MainWindow(QMainWindow):
for item in itemlist: for item in itemlist:
item.setEnabled(False) item.setEnabled(False)
#item color # item color
self.setItemColor(itemlist, id, event, current_event) self.setItemColor(itemlist, id, event, current_event)
model.appendRow(itemlist) model.appendRow(itemlist)
@ -1431,7 +1425,7 @@ class MainWindow(QMainWindow):
upperErrors=[uppererrorP[3], uppererrorS[3]]) upperErrors=[uppererrorP[3], uppererrorS[3]])
saved_as += str(outformat) + ' ' saved_as += str(outformat) + ' '
except TypeError: except TypeError:
print('WARNING: Format: {} not yet implemented'.format(outformat)) print('WARNING: Format: {} not yet implemented'.format(outformat))
self.get_data().setEvtData(event) self.get_data().setEvtData(event)
msg = 'Event {} saved as {} in format(s) {}'.format(event.pylot_id, fbasename, saved_as.strip()) msg = 'Event {} saved as {} in format(s) {}'.format(event.pylot_id, fbasename, saved_as.strip())
@ -1494,11 +1488,10 @@ class MainWindow(QMainWindow):
if len(eventdict) < 1: if len(eventdict) < 1:
return return
# init event selection options for autopick # init event selection options for autopick
self.compareoptions =[('tune events', self.get_ref_events, self._style['ref']['rgba']), self.compareoptions = [('tune events', self.get_ref_events, self._style['ref']['rgba']),
('test events', self.get_test_events, self._style['test']['rgba']), ('test events', self.get_test_events, self._style['test']['rgba']),
('all (picked) events', self.get_manu_picked_events, None)] ('all (picked) events', self.get_manu_picked_events, None)]
self.cmpw = CompareEventsWidget(self, self.compareoptions, eventdict, comparisons) self.cmpw = CompareEventsWidget(self, self.compareoptions, eventdict, comparisons)
self.cmpw.start.connect(self.compareMulti) self.cmpw.start.connect(self.compareMulti)
@ -1521,7 +1514,6 @@ class MainWindow(QMainWindow):
compare_widget = self.buildMultiCompareWidget(eventlist_overlap) compare_widget = self.buildMultiCompareWidget(eventlist_overlap)
compare_widget.show() compare_widget.show()
def buildMultiCompareWidget(self, eventlist): def buildMultiCompareWidget(self, eventlist):
global_comparison = Comparison(eventlist=eventlist) global_comparison = Comparison(eventlist=eventlist)
compare_widget = ComparisonWidget(global_comparison, self) compare_widget = ComparisonWidget(global_comparison, self)
@ -1793,7 +1785,7 @@ class MainWindow(QMainWindow):
nth_sample = int(settings.value("nth_sample")) if settings.value("nth_sample") else 1 nth_sample = int(settings.value("nth_sample")) if settings.value("nth_sample") else 1
npts_max = 1e7 npts_max = 1e7
npts = self.get_npts_to_plot() npts = self.get_npts_to_plot()
npts2plot = npts/nth_sample npts2plot = npts / nth_sample
if npts2plot < npts_max: if npts2plot < npts_max:
settings.setValue('large_dataset', False) settings.setValue('large_dataset', False)
else: else:
@ -2091,7 +2083,8 @@ class MainWindow(QMainWindow):
elif self.filterActionS.isChecked(): elif self.filterActionS.isChecked():
phase = 'S' phase = 'S'
if self.getFilterOptions(): if self.getFilterOptions():
if (phase == 'P' and self.filterActionP.isChecked()) or (phase == 'S' and self.filterActionS.isChecked()): if (phase == 'P' and self.filterActionP.isChecked()) or (
phase == 'S' and self.filterActionS.isChecked()):
kwargs = self.getFilterOptions()[phase].parseFilterOptions() kwargs = self.getFilterOptions()[phase].parseFilterOptions()
self.pushFilterWF(kwargs) self.pushFilterWF(kwargs)
else: else:
@ -2102,8 +2095,8 @@ class MainWindow(QMainWindow):
self.get_data().resetWFData() self.get_data().resetWFData()
if plot: if plot:
self.plotWaveformDataThread(filter=False) self.plotWaveformDataThread(filter=False)
#self.drawPicks() # self.drawPicks()
#self.draw() # self.draw()
def getAutoFilteroptions(self, phase): def getAutoFilteroptions(self, phase):
return getAutoFilteroptions(phase, self._inputs) return getAutoFilteroptions(phase, self._inputs)
@ -2423,7 +2416,7 @@ class MainWindow(QMainWindow):
# thread to prevent handling of QPixmap objects outside of # thread to prevent handling of QPixmap objects outside of
# the main thread # the main thread
self.init_fig_dict() self.init_fig_dict()
#if not self.tap: # if not self.tap:
# init TuneAutopicker object # init TuneAutopicker object
self.tap = TuneAutopicker(self, self.obspy_dmt) self.tap = TuneAutopicker(self, self.obspy_dmt)
# first call of update to init tabs with empty canvas # first call of update to init tabs with empty canvas
@ -2432,7 +2425,7 @@ class MainWindow(QMainWindow):
# creating and filling figure canvas # creating and filling figure canvas
self.tap.update.connect(self.update_autopicker) self.tap.update.connect(self.update_autopicker)
self.tap.figure_tabs.setCurrentIndex(0) self.tap.figure_tabs.setCurrentIndex(0)
#else: # else:
# self.update_autopicker() # self.update_autopicker()
# self.tap.fill_eventbox() # self.tap.fill_eventbox()
self.tap.show() self.tap.show()
@ -2463,11 +2456,11 @@ class MainWindow(QMainWindow):
if not self.apw: if not self.apw:
# init event selection options for autopick # init event selection options for autopick
self.pickoptions =[('current event', self.get_current_event, None), self.pickoptions = [('current event', self.get_current_event, None),
('tune events', self.get_ref_events, self._style['ref']['rgba']), ('tune events', self.get_ref_events, self._style['ref']['rgba']),
('test events', self.get_test_events, self._style['test']['rgba']), ('test events', self.get_test_events, self._style['test']['rgba']),
('all (picked) events', self.get_manu_picked_events, None), ('all (picked) events', self.get_manu_picked_events, None),
('all events', self.get_all_events, None)] ('all events', self.get_all_events, None)]
self.listWidget = QListWidget() self.listWidget = QListWidget()
self.setDirty(True) self.setDirty(True)
@ -2645,7 +2638,7 @@ class MainWindow(QMainWindow):
picksdict = picksdict_from_picks(evt=self.get_data().get_evt_data()) picksdict = picksdict_from_picks(evt=self.get_data().get_evt_data())
if type == 'manual': if type == 'manual':
event.addPicks(picksdict['manual']) event.addPicks(picksdict['manual'])
#event.picks.update(picks) MP MP idea # event.picks.update(picks) MP MP idea
elif type == 'auto': elif type == 'auto':
event.addAutopicks(picksdict['auto']) event.addAutopicks(picksdict['auto'])
@ -2682,7 +2675,7 @@ class MainWindow(QMainWindow):
stat_picks = self.getPicks(type=picktype)[station] stat_picks = self.getPicks(type=picktype)[station]
for phase in stat_picks: for phase in stat_picks:
if phase == 'SPt': continue # wadati SP time if phase == 'SPt': continue # wadati SP time
picks = stat_picks[phase] picks = stat_picks[phase]
if type(stat_picks[phase]) is not dict and type(stat_picks[phase]) is not AttribDict: if type(stat_picks[phase]) is not dict and type(stat_picks[phase]) is not AttribDict:
return return
@ -2801,7 +2794,7 @@ class MainWindow(QMainWindow):
lt.locate(ctrfile) lt.locate(ctrfile)
except RuntimeError as e: except RuntimeError as e:
print(e.message) print(e.message)
#finally: # finally:
# os.remove(phasefile) # os.remove(phasefile)
self.get_data().applyEVTData(lt.read_location(locpath), typ='event') self.get_data().applyEVTData(lt.read_location(locpath), typ='event')
@ -2904,7 +2897,7 @@ class MainWindow(QMainWindow):
self.array_map.eventLoc = (lat, lon) self.array_map.eventLoc = (lat, lon)
if self.get_current_event(): if self.get_current_event():
self.array_map.refresh_drawings(self.get_current_event().getPicks(), self.array_map.refresh_drawings(self.get_current_event().getPicks(),
self.get_current_event().getAutopicks(),) self.get_current_event().getAutopicks(), )
self._eventChanged[1] = False self._eventChanged[1] = False
def init_event_table(self, tabindex=2): def init_event_table(self, tabindex=2):
@ -3030,7 +3023,7 @@ class MainWindow(QMainWindow):
if hasattr(event, 'origins'): if hasattr(event, 'origins'):
if event.origins: if event.origins:
origin = event.origins[0] origin = event.origins[0]
item_time.setText(str(origin.time + 0).split('.')[0]) # +0 as workaround in case time=0s item_time.setText(str(origin.time + 0).split('.')[0]) # +0 as workaround in case time=0s
item_lon.setText(str(origin.longitude)) item_lon.setText(str(origin.longitude))
item_lat.setText(str(origin.latitude)) item_lat.setText(str(origin.latitude))
item_depth.setText(str(origin.depth)) item_depth.setText(str(origin.depth))
@ -3164,7 +3157,6 @@ class MainWindow(QMainWindow):
return return
set_inv(settings) set_inv(settings)
def calc_magnitude(self, type='ML'): def calc_magnitude(self, type='ML'):
self.init_metadata() self.init_metadata()
if not self.metadata: if not self.metadata:
@ -3289,11 +3281,11 @@ class MainWindow(QMainWindow):
if hasattr(self.project, 'metadata'): if hasattr(self.project, 'metadata'):
if self.project.metadata: if self.project.metadata:
self.init_metadata(ask_default=False) self.init_metadata(ask_default=False)
#self.init_array_map(index=0) # self.init_array_map(index=0)
return return
if hasattr(self.project, 'inv_path'): if hasattr(self.project, 'inv_path'):
self.init_metadata(ask_default=False) self.init_metadata(ask_default=False)
#self.init_array_map(index=0) # self.init_array_map(index=0)
return return
self.init_array_tab() self.init_array_tab()
@ -3350,7 +3342,6 @@ class MainWindow(QMainWindow):
self.dataPlot.setPermText(1) self.dataPlot.setPermText(1)
self.dataPlot.setPermText(0, '| Number of traces: {} |'.format(len(self.getPlotWidget().getPlotDict()))) self.dataPlot.setPermText(0, '| Number of traces: {} |'.format(len(self.getPlotWidget().getPlotDict())))
def _setDirty(self): def _setDirty(self):
self.setDirty(True) self.setDirty(True)
@ -3389,7 +3380,7 @@ class MainWindow(QMainWindow):
def helpHelp(self): def helpHelp(self):
if checkurl(): if checkurl():
form = HelpForm(self, form = HelpForm(self,
'https://ariadne.geophysik.ruhr-uni-bochum.de/trac/PyLoT/wiki') 'https://ariadne.geophysik.ruhr-uni-bochum.de/trac/PyLoT/wiki')
else: else:
form = HelpForm(self, ':/help.html') form = HelpForm(self, ':/help.html')
form.show() form.show()
@ -3594,7 +3585,7 @@ def create_window():
def main(args=None): def main(args=None):
project_filename = None project_filename = None
#args.project_filename = 'C:/Shared/AlpArray/alparray_data/project_alparray_test.plp' # args.project_filename = 'C:/Shared/AlpArray/alparray_data/project_alparray_test.plp'
pylot_infile = None pylot_infile = None
if args: if args:
if args.project_filename: if args.project_filename:

View File

@ -118,7 +118,7 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
if not parameter: if not parameter:
if inputfile: if inputfile:
parameter = PylotParameter(inputfile) parameter = PylotParameter(inputfile)
#iplot = parameter['iplot'] # iplot = parameter['iplot']
else: else:
infile = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in') infile = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in')
print('Using default input file {}'.format(infile)) print('Using default input file {}'.format(infile))
@ -151,7 +151,7 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
datastructure.setExpandFields(exf) datastructure.setExpandFields(exf)
# check if default location routine NLLoc is available and all stations are used # check if default location routine NLLoc is available and all stations are used
if real_None(parameter['nllocbin']) and station=='all': if real_None(parameter['nllocbin']) and station == 'all':
locflag = 1 locflag = 1
# get NLLoc-root path # get NLLoc-root path
nllocroot = parameter.get('nllocroot') nllocroot = parameter.get('nllocroot')
@ -289,7 +289,7 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
corr_dat = None corr_dat = None
if metadata: if metadata:
# rotate stations to ZNE # rotate stations to ZNE
#wfdat = check4rotated(wfdat, metadata) # MP MP TEMPORARILY DISABLED !!!!!!!!!!! # wfdat = check4rotated(wfdat, metadata) # MP MP TEMPORARILY DISABLED !!!!!!!!!!!
if locflag: if locflag:
print("Restitute data ...") print("Restitute data ...")
corr_dat = restitute_data(wfdat.copy(), metadata, ncores=ncores) corr_dat = restitute_data(wfdat.copy(), metadata, ncores=ncores)
@ -505,7 +505,7 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
endsplash = '''------------------------------------------\n' endsplash = '''------------------------------------------\n'
-----Finished event %s!-----\n' -----Finished event %s!-----\n'
------------------------------------------'''.format \ ------------------------------------------'''.format \
(version=_getVersionString()) % evID (version=_getVersionString()) % evID
print(endsplash) print(endsplash)
locflag = glocflag locflag = glocflag
if locflag == 0: if locflag == 0:
@ -534,9 +534,9 @@ if __name__ == "__main__":
action='store', action='store',
help='''full path to the file containing the input help='''full path to the file containing the input
parameters for autoPyLoT''') parameters for autoPyLoT''')
parser.add_argument('-p', '-P', '--iplot', type=int, parser.add_argument('-p', '-P', '--iplot', type=int,
action='store', default=0, action='store', default=0,
help='''optional, logical variable for plotting: 0=none, 1=partial, 2=all''') help='''optional, logical variable for plotting: 0=none, 1=partial, 2=all''')
parser.add_argument('-f', '-F', '--fnames', type=str, parser.add_argument('-f', '-F', '--fnames', type=str,
action='store', action='store',
help='''optional, list of data file names''') help='''optional, list of data file names''')

View File

@ -17,6 +17,7 @@ from pylot.core.util.utils import common_range, fit_curve
from scipy import integrate, signal from scipy import integrate, signal
from scipy.optimize import curve_fit from scipy.optimize import curve_fit
def richter_magnitude_scaling(delta): def richter_magnitude_scaling(delta):
distance = np.array([0, 10, 20, 25, 30, 35, 40, 45, 50, 60, 70, 75, 85, 90, 100, 110, distance = np.array([0, 10, 20, 25, 30, 35, 40, 45, 50, 60, 70, 75, 85, 90, 100, 110,
120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 230, 240, 250, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 230, 240, 250,
@ -225,7 +226,7 @@ class LocalMagnitude(Magnitude):
sqH = np.sqrt(power_sum) sqH = np.sqrt(power_sum)
# get time array # get time array
th=np.arange(0, st[0].stats.npts/st[0].stats.sampling_rate, st[0].stats.delta) th = np.arange(0, st[0].stats.npts / st[0].stats.sampling_rate, st[0].stats.delta)
# get maximum peak within pick window # get maximum peak within pick window
iwin = getsignalwin(th, t0 - stime, self.calc_win) iwin = getsignalwin(th, t0 - stime, self.calc_win)
ii = min([iwin[len(iwin) - 1], len(th)]) ii = min([iwin[len(iwin) - 1], len(th)])
@ -245,9 +246,9 @@ class LocalMagnitude(Magnitude):
ax.plot(th[iwin], sqH[iwin], 'g') ax.plot(th[iwin], sqH[iwin], 'g')
ax.plot([t0 - stime, t0 - stime], [0, max(sqH)], 'r', linewidth=2) ax.plot([t0 - stime, t0 - stime], [0, max(sqH)], 'r', linewidth=2)
ax.set_title('Station %s, Channel %s, RMS Horizontal Trace, ' ax.set_title('Station %s, Channel %s, RMS Horizontal Trace, '
'WA-peak-to-peak=%6.3f mm' % (st[0].stats.station, 'WA-peak-to-peak=%6.3f mm' % (st[0].stats.station,
st[0].stats.channel, st[0].stats.channel,
wapp)) wapp))
ax.set_xlabel('Time [s]') ax.set_xlabel('Time [s]')
ax.set_ylabel('Displacement [mm]') ax.set_ylabel('Displacement [mm]')
ax = fig.add_subplot(212) ax = fig.add_subplot(212)
@ -257,15 +258,16 @@ class LocalMagnitude(Magnitude):
ax.plot([t0 - stime, t0 - stime], [0, max(sqH)], 'r', linewidth=2) ax.plot([t0 - stime, t0 - stime], [0, max(sqH)], 'r', linewidth=2)
ax.set_title('Channel %s, RMS Horizontal Trace, ' ax.set_title('Channel %s, RMS Horizontal Trace, '
'WA-peak-to-peak=%6.3f mm' % (st[1].stats.channel, 'WA-peak-to-peak=%6.3f mm' % (st[1].stats.channel,
wapp)) wapp))
ax.set_xlabel('Time [s]') ax.set_xlabel('Time [s]')
ax.set_ylabel('Displacement [mm]') ax.set_ylabel('Displacement [mm]')
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return wapp, fig return wapp, fig
def calc(self): def calc(self):
@ -309,7 +311,7 @@ class LocalMagnitude(Magnitude):
a0 = a0 * 1e03 # mm to nm (see Havskov & Ottemöller, 2010) a0 = a0 * 1e03 # mm to nm (see Havskov & Ottemöller, 2010)
magnitude = ope.StationMagnitude(mag=np.log10(a0) \ magnitude = ope.StationMagnitude(mag=np.log10(a0) \
+ self.wascaling[0] * np.log10(delta) + self.wascaling[1] + self.wascaling[0] * np.log10(delta) + self.wascaling[1]
* delta + self.wascaling[ * delta + self.wascaling[
2]) 2])
magnitude.origin_id = self.origin_id magnitude.origin_id = self.origin_id
magnitude.waveform_id = pick.waveform_id magnitude.waveform_id = pick.waveform_id
@ -372,7 +374,7 @@ class MomentMagnitude(Magnitude):
def calc(self): def calc(self):
for a in self.arrivals: for a in self.arrivals:
if a.phase not in 'pP': if a.phase not in 'pP':
continue continue
# make sure calculating Mo only from reliable onsets # make sure calculating Mo only from reliable onsets
# NLLoc: time_weight = 0 => do not use onset! # NLLoc: time_weight = 0 => do not use onset!

View File

@ -17,6 +17,7 @@ from pylot.core.util.utils import fnConstructor, full_range, remove_underscores,
import pylot.core.loc.velest as velest import pylot.core.loc.velest as velest
from pylot.core.util.obspyDMT_interface import qml_from_obspyDMT from pylot.core.util.obspyDMT_interface import qml_from_obspyDMT
class Data(object): class Data(object):
""" """
Data container with attributes wfdata holding ~obspy.core.stream. Data container with attributes wfdata holding ~obspy.core.stream.
@ -284,7 +285,7 @@ class Data(object):
mstation_ext = mstation + '_' mstation_ext = mstation + '_'
for k in range(len(picks_copy)): for k in range(len(picks_copy)):
if ((picks_copy[k].waveform_id.station_code == mstation) or if ((picks_copy[k].waveform_id.station_code == mstation) or
(picks_copy[k].waveform_id.station_code == mstation_ext)) and \ (picks_copy[k].waveform_id.station_code == mstation_ext)) and \
(picks_copy[k].method_id == 'auto'): (picks_copy[k].method_id == 'auto'):
del picks_copy[k] del picks_copy[k]
break break
@ -416,7 +417,6 @@ class Data(object):
self.dirty = False self.dirty = False
return True return True
def appendWFData(self, fnames, synthetic=False): def appendWFData(self, fnames, synthetic=False):
""" """
Read waveform data from fnames and append it to current wf data Read waveform data from fnames and append it to current wf data

View File

@ -456,11 +456,11 @@ defaults = {'rootpath': {'type': str,
'namestring': 'Wadati tolerance'}, 'namestring': 'Wadati tolerance'},
'jackfactor': {'type': float, 'jackfactor': {'type': float,
'tooltip': 'pick is removed if the variance of the subgroup with the pick removed is larger than the mean variance of all subgroups times safety factor', 'tooltip': 'pick is removed if the variance of the subgroup with the pick removed is larger than the mean variance of all subgroups times safety factor',
'value': 5.0, 'value': 5.0,
'min': 0., 'min': 0.,
'max': np.inf, 'max': np.inf,
'namestring': 'Jackknife safety factor'}, 'namestring': 'Jackknife safety factor'},
'WAscaling': {'type': (float, float, float), 'WAscaling': {'type': (float, float, float),
'tooltip': 'Scaling relation (log(Ao)+Alog(r)+Br+C) of Wood-Anderson amplitude Ao [nm] \ 'tooltip': 'Scaling relation (log(Ao)+Alog(r)+Br+C) of Wood-Anderson amplitude Ao [nm] \

View File

@ -245,7 +245,7 @@ def picksdict_from_picks(evt):
if picker.startswith('smi:local/'): if picker.startswith('smi:local/'):
picker = picker.split('smi:local/')[1] picker = picker.split('smi:local/')[1]
except IndexError: except IndexError:
picker = 'manual' # MP MP TODO maybe improve statement picker = 'manual' # MP MP TODO maybe improve statement
try: try:
onsets = picksdict[picker][station] onsets = picksdict[picker][station]
except KeyError as e: except KeyError as e:
@ -346,6 +346,7 @@ def picks_from_picksdict(picks, creation_info=None):
picks_list.append(pick) picks_list.append(pick)
return picks_list return picks_list
def reassess_pilot_db(root_dir, db_dir, out_dir=None, fn_param=None, verbosity=0): def reassess_pilot_db(root_dir, db_dir, out_dir=None, fn_param=None, verbosity=0):
import glob import glob
@ -916,9 +917,9 @@ def merge_picks(event, picks):
network = pick.waveform_id.network_code network = pick.waveform_id.network_code
method = pick.method_id method = pick.method_id
for p in event.picks: for p in event.picks:
if p.waveform_id.station_code == station\ if p.waveform_id.station_code == station \
and p.waveform_id.network_code == network\ and p.waveform_id.network_code == network \
and p.phase_hint == phase\ and p.phase_hint == phase \
and (str(p.method_id) in str(method) and (str(p.method_id) in str(method)
or str(method) in str(p.method_id)): or str(method) in str(p.method_id)):
p.time, p.time_errors, p.waveform_id.network_code, p.method_id = time, err, network, method p.time, p.time_errors, p.waveform_id.network_code, p.method_id = time, err, network, method
@ -972,14 +973,14 @@ def getQualitiesfromxml(xmlnames, ErrorsP, ErrorsS, plotflag=1):
phase = identifyPhase(loopIdentifyPhase(Pick.phase_hint)) phase = identifyPhase(loopIdentifyPhase(Pick.phase_hint))
if phase == 'P': if phase == 'P':
if ((mpick.waveform_id.station_code == mstation) or if ((mpick.waveform_id.station_code == mstation) or
(mpick.waveform_id.station_code == mstation_ext)) and \ (mpick.waveform_id.station_code == mstation_ext)) and \
((mpick.method_id).split('/')[1] == 'auto') and \ ((mpick.method_id).split('/')[1] == 'auto') and \
(mpick.time_errors['uncertainty'] <= ErrorsP[3]): (mpick.time_errors['uncertainty'] <= ErrorsP[3]):
del mpick del mpick
break break
elif phase == 'S': elif phase == 'S':
if ((mpick.waveform_id.station_code == mstation) or if ((mpick.waveform_id.station_code == mstation) or
(mpick.waveform_id.station_code == mstation_ext)) and \ (mpick.waveform_id.station_code == mstation_ext)) and \
((mpick.method_id).split('/')[1] == 'auto') and \ ((mpick.method_id).split('/')[1] == 'auto') and \
(mpick.time_errors['uncertainty'] <= ErrorsS[3]): (mpick.time_errors['uncertainty'] <= ErrorsS[3]):
del mpick del mpick
@ -1032,19 +1033,19 @@ def getQualitiesfromxml(xmlnames, ErrorsP, ErrorsS, plotflag=1):
P0perc = 0 P0perc = 0
if len(Pw1) > 0: if len(Pw1) > 0:
P1perc = 100 / numPweights * len(Pw1) P1perc = 100 / numPweights * len(Pw1)
else: else:
P1perc = 0 P1perc = 0
if len(Pw2) > 0: if len(Pw2) > 0:
P2perc = 100 / numPweights * len(Pw2) P2perc = 100 / numPweights * len(Pw2)
else: else:
P2perc = 0 P2perc = 0
if len(Pw3) > 0: if len(Pw3) > 0:
P3perc = 100 / numPweights * len(Pw3) P3perc = 100 / numPweights * len(Pw3)
else: else:
P3perc = 0 P3perc = 0
if len(Pw4) > 0: if len(Pw4) > 0:
P4perc = 100 / numPweights * len(Pw4) P4perc = 100 / numPweights * len(Pw4)
else: else:
P4perc = 0 P4perc = 0
if len(Sw0) > 0: if len(Sw0) > 0:
S0perc = 100 / numSweights * len(Sw0) S0perc = 100 / numSweights * len(Sw0)
@ -1052,19 +1053,19 @@ def getQualitiesfromxml(xmlnames, ErrorsP, ErrorsS, plotflag=1):
S0perc = 0 S0perc = 0
if len(Sw1) > 0: if len(Sw1) > 0:
S1perc = 100 / numSweights * len(Sw1) S1perc = 100 / numSweights * len(Sw1)
else: else:
S1perc = 0 S1perc = 0
if len(Sw2) > 0: if len(Sw2) > 0:
S2perc = 100 / numSweights * len(Sw2) S2perc = 100 / numSweights * len(Sw2)
else: else:
S2perc = 0 S2perc = 0
if len(Sw3) > 0: if len(Sw3) > 0:
S3perc = 100 / numSweights * len(Sw3) S3perc = 100 / numSweights * len(Sw3)
else: else:
S3perc = 0 S3perc = 0
if len(Sw4) > 0: if len(Sw4) > 0:
S4perc = 100 / numSweights * len(Sw4) S4perc = 100 / numSweights * len(Sw4)
else: else:
S4perc = 0 S4perc = 0
weights = ('0', '1', '2', '3', '4') weights = ('0', '1', '2', '3', '4')

View File

@ -16,7 +16,7 @@ from pylot.core.pick.charfuns import HOScf, AICcf, ARZcf, ARHcf, AR3Ccf
from pylot.core.pick.picker import AICPicker, PragPicker from pylot.core.pick.picker import AICPicker, PragPicker
from pylot.core.pick.utils import checksignallength, checkZ4S, earllatepicker, \ from pylot.core.pick.utils import checksignallength, checkZ4S, earllatepicker, \
getSNR, fmpicker, checkPonsets, wadaticheck getSNR, fmpicker, checkPonsets, wadaticheck
from pylot.core.util.utils import getPatternLine, gen_Pool,\ from pylot.core.util.utils import getPatternLine, gen_Pool, \
real_Bool, identifyPhaseID real_Bool, identifyPhaseID
from obspy.taup import TauPyModel from obspy.taup import TauPyModel
@ -95,7 +95,7 @@ def autopickevent(data, param, iplot=0, fig_dict=None, fig_dict_wadatijack=None,
print('Could not pick a station: {}\nReason: {}'.format(station, result)) print('Could not pick a station: {}\nReason: {}'.format(station, result))
# no Wadati/JK for single station (also valid for tuning mode) # no Wadati/JK for single station (also valid for tuning mode)
if len(stations) == 1: if len(stations) == 1:
return all_onsets return all_onsets
# quality control # quality control
@ -133,7 +133,8 @@ def call_autopickstation(input_tuple):
print('Running in interactive mode') print('Running in interactive mode')
# multiprocessing not possible with interactive plotting # multiprocessing not possible with interactive plotting
try: try:
return autopickstation(wfstream, pickparam, verbose, fig_dict=fig_dict, iplot=iplot, metadata=metadata, origin=origin) return autopickstation(wfstream, pickparam, verbose, fig_dict=fig_dict, iplot=iplot, metadata=metadata,
origin=origin)
except Exception as e: except Exception as e:
return e, wfstream[0].stats.station return e, wfstream[0].stats.station
@ -343,7 +344,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
# make sure pstart and pstop are inside zdat[0] # make sure pstart and pstop are inside zdat[0]
pstart = max(pstart, 0) pstart = max(pstart, 0)
pstop = min(pstop, len(zdat[0])*zdat[0].stats.delta) pstop = min(pstop, len(zdat[0]) * zdat[0].stats.delta)
if not use_taup is True or origin: if not use_taup is True or origin:
Lc = pstop - pstart Lc = pstop - pstart
@ -586,7 +587,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
FM) FM)
print(msg) print(msg)
msg = 'autopickstation: Refined P-Pick: {} s | P-Error: {} s'.format(zdat[0].stats.starttime \ msg = 'autopickstation: Refined P-Pick: {} s | P-Error: {} s'.format(zdat[0].stats.starttime \
+ mpickP, Perror) + mpickP, Perror)
print(msg) print(msg)
Sflag = 1 Sflag = 1
@ -620,7 +621,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
ndat = edat ndat = edat
pickSonset = (edat is not None and ndat is not None and len(edat) > 0 and len( pickSonset = (edat is not None and ndat is not None and len(edat) > 0 and len(
ndat) > 0 and Pweight < 4) ndat) > 0 and Pweight < 4)
if pickSonset: if pickSonset:
# determine time window for calculating CF after P onset # determine time window for calculating CF after P onset
@ -628,8 +629,8 @@ def autopickstation(wfstream, pickparam, verbose=False,
round(max([mpickP + sstart, 0])), # MP MP relative time axis round(max([mpickP + sstart, 0])), # MP MP relative time axis
round(min([ round(min([
mpickP + sstop, mpickP + sstop,
edat[0].stats.endtime-edat[0].stats.starttime, edat[0].stats.endtime - edat[0].stats.starttime,
ndat[0].stats.endtime-ndat[0].stats.starttime ndat[0].stats.endtime - ndat[0].stats.starttime
])) ]))
] ]
@ -724,7 +725,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
if not slope: if not slope:
slope = 0 slope = 0
if (slope >= minAICSslope and if (slope >= minAICSslope and
aicarhpick.getSNR() >= minAICSSNR and aicarhpick.getpick() is not None): aicarhpick.getSNR() >= minAICSSNR and aicarhpick.getpick() is not None):
aicSflag = 1 aicSflag = 1
msg = 'AIC S-pick passes quality control: Slope: {0} counts/s, ' \ msg = 'AIC S-pick passes quality control: Slope: {0} counts/s, ' \
'SNR: {1}\nGo on with refined picking ...\n' \ 'SNR: {1}\nGo on with refined picking ...\n' \
@ -866,7 +867,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
Serror = pickerr[ipick] Serror = pickerr[ipick]
msg = 'autopickstation: Refined S-Pick: {} s | S-Error: {} s'.format(hdat[0].stats.starttime \ msg = 'autopickstation: Refined S-Pick: {} s | S-Error: {} s'.format(hdat[0].stats.starttime \
+ mpickS, Serror) + mpickS, Serror)
print(msg) print(msg)
# get SNR # get SNR
@ -912,7 +913,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
# re-create stream object including both horizontal components # re-create stream object including both horizontal components
hdat = edat.copy() hdat = edat.copy()
hdat += ndat hdat += ndat
else: else:
print('autopickstation: No horizontal component data available or ' print('autopickstation: No horizontal component data available or '
'bad P onset, skipping S picking!') 'bad P onset, skipping S picking!')
@ -1216,11 +1217,11 @@ def iteratepicker(wf, NLLocfile, picks, badpicks, pickparameter, fig_dict=None):
print( print(
"iteratepicker: The following picking parameters have been modified for iterative picking:") "iteratepicker: The following picking parameters have been modified for iterative picking:")
print( print(
"pstart: %fs => %fs" % (pstart_old, pickparameter.get('pstart'))) "pstart: %fs => %fs" % (pstart_old, pickparameter.get('pstart')))
print( print(
"pstop: %fs => %fs" % (pstop_old, pickparameter.get('pstop'))) "pstop: %fs => %fs" % (pstop_old, pickparameter.get('pstop')))
print( print(
"sstop: %fs => %fs" % (sstop_old, pickparameter.get('sstop'))) "sstop: %fs => %fs" % (sstop_old, pickparameter.get('sstop')))
print("pickwinP: %fs => %fs" % ( print("pickwinP: %fs => %fs" % (
pickwinP_old, pickparameter.get('pickwinP'))) pickwinP_old, pickparameter.get('pickwinP')))
print("Precalcwin: %fs => %fs" % ( print("Precalcwin: %fs => %fs" % (

View File

@ -164,9 +164,9 @@ class AICPicker(AutoPicker):
iplot = int(self.iplot) iplot = int(self.iplot)
except: except:
if self.iplot == True or self.iplot == 'True': if self.iplot == True or self.iplot == 'True':
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
# find NaN's # find NaN's
nn = np.isnan(self.cf) nn = np.isnan(self.cf)
@ -215,8 +215,8 @@ class AICPicker(AutoPicker):
tsafety = self.TSNR[1] # safety gap, AIC is usually a little bit too late tsafety = self.TSNR[1] # safety gap, AIC is usually a little bit too late
left_corner_ind = max([icfmax - lpickwindow, 2]) left_corner_ind = max([icfmax - lpickwindow, 2])
right_corner_ind = icfmax + int(tsafety / self.dt) right_corner_ind = icfmax + int(tsafety / self.dt)
aic_snip = aicsmooth[left_corner_ind : right_corner_ind] aic_snip = aicsmooth[left_corner_ind: right_corner_ind]
minima = argrelmin(aic_snip)[0] # 0th entry of tuples for axes minima = argrelmin(aic_snip)[0] # 0th entry of tuples for axes
if len(minima) > 0: if len(minima) > 0:
pickindex = minima[-1] + left_corner_ind pickindex = minima[-1] + left_corner_ind
self.Pick = self.Tcf[pickindex] self.Pick = self.Tcf[pickindex]
@ -261,10 +261,11 @@ class AICPicker(AutoPicker):
tslope = self.TSNR[3] # slope determination window tslope = self.TSNR[3] # slope determination window
if tsafety >= 0: if tsafety >= 0:
islope = np.where((self.Tcf <= min([self.Pick + tslope + tsafety, self.Tcf[-1]])) \ islope = np.where((self.Tcf <= min([self.Pick + tslope + tsafety, self.Tcf[-1]])) \
& (self.Tcf >= self.Pick)) # TODO: put this in a seperate function like getsignalwin & (self.Tcf >= self.Pick)) # TODO: put this in a seperate function like getsignalwin
else: else:
islope = np.where((self.Tcf <= min([self.Pick + tslope, self.Tcf[-1]])) \ islope = np.where((self.Tcf <= min([self.Pick + tslope, self.Tcf[-1]])) \
& (self.Tcf >= self.Pick + tsafety)) # TODO: put this in a seperate function like getsignalwin & (
self.Tcf >= self.Pick + tsafety)) # TODO: put this in a seperate function like getsignalwin
# find maximum within slope determination window # find maximum within slope determination window
# 'cause slope should be calculated up to first local minimum only! # 'cause slope should be calculated up to first local minimum only!
try: try:
@ -306,11 +307,13 @@ class AICPicker(AutoPicker):
ax.set_title(self.Data[0].stats.station) ax.set_title(self.Data[0].stats.station)
if plt_flag in [1, 2]: if plt_flag in [1, 2]:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return return
iislope = islope[0][0:imax+1] iislope = islope[0][0:imax + 1]
# MP MP change slope calculation # MP MP change slope calculation
# get all maxima of aicsmooth # get all maxima of aicsmooth
iaicmaxima = argrelmax(aicsmooth)[0] iaicmaxima = argrelmax(aicsmooth)[0]
@ -320,7 +323,7 @@ class AICPicker(AutoPicker):
iaicmax = aicmax[0] iaicmax = aicmax[0]
else: else:
iaicmax = -1 iaicmax = -1
dataslope = aicsmooth[pickindex : iaicmax] dataslope = aicsmooth[pickindex: iaicmax]
# calculate slope as polynomal fit of order 1 # calculate slope as polynomal fit of order 1
xslope = np.arange(0, len(dataslope), 1) xslope = np.arange(0, len(dataslope), 1)
P = np.polyfit(xslope, dataslope, 1) P = np.polyfit(xslope, dataslope, 1)
@ -344,8 +347,8 @@ class AICPicker(AutoPicker):
fig = self.fig fig = self.fig
fig._tight = True fig._tight = True
ax1 = fig.add_subplot(211) ax1 = fig.add_subplot(211)
if len(self.Tcf) > len(cf): # why? LK if len(self.Tcf) > len(cf): # why? LK
self.Tcf = self.Tcf[0:len(self.Tcf)-1] self.Tcf = self.Tcf[0:len(self.Tcf) - 1]
ax1.plot(self.Tcf, cf / max(cf), color=self._linecolor, linewidth=0.7, label='(HOS-/AR-) Data') ax1.plot(self.Tcf, cf / max(cf), color=self._linecolor, linewidth=0.7, label='(HOS-/AR-) Data')
ax1.plot(self.Tcf, aicsmooth / max(aicsmooth), 'r', label='Smoothed AIC-CF') ax1.plot(self.Tcf, aicsmooth / max(aicsmooth), 'r', label='Smoothed AIC-CF')
if self.Pick is not None: if self.Pick is not None:
@ -368,7 +371,8 @@ class AICPicker(AutoPicker):
label='Signal Window') label='Signal Window')
ax2.axvspan(self.Tcf[iislope[0]], self.Tcf[iislope[-1]], color='g', alpha=0.2, lw=0, ax2.axvspan(self.Tcf[iislope[0]], self.Tcf[iislope[-1]], color='g', alpha=0.2, lw=0,
label='Slope Window') label='Slope Window')
ax2.plot(self.Tcf[pickindex : iaicmax], datafit, 'g', linewidth=2, label='Slope') # MP MP changed temporarily! ax2.plot(self.Tcf[pickindex: iaicmax], datafit, 'g', linewidth=2,
label='Slope') # MP MP changed temporarily!
if self.slope is not None: if self.slope is not None:
ax1.set_title('Station %s, SNR=%7.2f, Slope= %12.2f counts/s' % (self.Data[0].stats.station, ax1.set_title('Station %s, SNR=%7.2f, Slope= %12.2f counts/s' % (self.Data[0].stats.station,
@ -384,8 +388,10 @@ class AICPicker(AutoPicker):
if plt_flag in [1, 2]: if plt_flag in [1, 2]:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
if plt_flag == 3: if plt_flag == 3:
stats = self.Data[0].stats stats = self.Data[0].stats
@ -409,9 +415,9 @@ class PragPicker(AutoPicker):
iplot = int(self.getiplot()) iplot = int(self.getiplot())
except: except:
if self.getiplot() == True or self.getiplot() == 'True': if self.getiplot() == True or self.getiplot() == 'True':
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
if self.getpick1() is not None: if self.getpick1() is not None:
print('PragPicker: Get most likely pick from HOS- or AR-CF using pragmatic picking algorithm ...') print('PragPicker: Get most likely pick from HOS- or AR-CF using pragmatic picking algorithm ...')
@ -450,11 +456,11 @@ class PragPicker(AutoPicker):
# prominent trend: decrease aus # prominent trend: decrease aus
# flat: use given aus # flat: use given aus
cfdiff = np.diff(cfipick) cfdiff = np.diff(cfipick)
if len(cfdiff)<20: if len(cfdiff) < 20:
print('PragPicker: Very few samples for CF. Check LTA window dimensions!') print('PragPicker: Very few samples for CF. Check LTA window dimensions!')
i0diff = np.where(cfdiff > 0) i0diff = np.where(cfdiff > 0)
cfdiff = cfdiff[i0diff] cfdiff = cfdiff[i0diff]
if len(cfdiff)<1: if len(cfdiff) < 1:
print('PragPicker: Negative slope for CF. Check LTA window dimensions! STOP') print('PragPicker: Negative slope for CF. Check LTA window dimensions! STOP')
self.Pick = None self.Pick = None
return return
@ -478,7 +484,7 @@ class PragPicker(AutoPicker):
break break
# now we look to the left # now we look to the left
if len(self.cf) > ipick1 +1: if len(self.cf) > ipick1 + 1:
for i in range(ipick1, max([ipick1 - lpickwindow + 1, 2]), -1): for i in range(ipick1, max([ipick1 - lpickwindow + 1, 2]), -1):
if self.cf[i + 1] > self.cf[i] and self.cf[i - 1] >= self.cf[i]: if self.cf[i + 1] > self.cf[i] and self.cf[i - 1] >= self.cf[i]:
if cfsmooth[i - 1] * (1 + aus1) >= cfsmooth[i]: if cfsmooth[i - 1] * (1 + aus1) >= cfsmooth[i]:
@ -489,7 +495,7 @@ class PragPicker(AutoPicker):
cfpick_l = self.cf[i] cfpick_l = self.cf[i]
break break
else: else:
msg ='PragPicker: Initial onset too close to start of CF! \ msg = 'PragPicker: Initial onset too close to start of CF! \
Stop finalizing pick to the left.' Stop finalizing pick to the left.'
print(msg) print(msg)
@ -519,15 +525,18 @@ class PragPicker(AutoPicker):
ax.plot(Tcfpick, cfipick, color=self._linecolor, linewidth=0.7, label='CF') ax.plot(Tcfpick, cfipick, color=self._linecolor, linewidth=0.7, label='CF')
ax.plot(Tcfpick, cfsmoothipick, 'r', label='Smoothed CF') ax.plot(Tcfpick, cfsmoothipick, 'r', label='Smoothed CF')
if pickflag > 0: if pickflag > 0:
ax.plot([self.Pick, self.Pick], [min(cfipick), max(cfipick)], self._pickcolor_p, linewidth=2, label='Pick') ax.plot([self.Pick, self.Pick], [min(cfipick), max(cfipick)], self._pickcolor_p, linewidth=2,
label='Pick')
ax.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime) ax.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime)
ax.set_yticks([]) ax.set_yticks([])
ax.set_title(self.Data[0].stats.station) ax.set_title(self.Data[0].stats.station)
ax.legend(loc=1) ax.legend(loc=1)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return return

View File

@ -16,7 +16,6 @@ from obspy.core import Stream, UTCDateTime
from pylot.core.util.utils import real_Bool, real_None from pylot.core.util.utils import real_Bool, real_None
def earllatepicker(X, nfac, TSNR, Pick1, iplot=0, verbosity=1, fig=None, linecolor='k'): def earllatepicker(X, nfac, TSNR, Pick1, iplot=0, verbosity=1, fig=None, linecolor='k'):
""" """
Function to derive earliest and latest possible pick after Diehl & Kissling (2009) Function to derive earliest and latest possible pick after Diehl & Kissling (2009)
@ -143,13 +142,16 @@ def earllatepicker(X, nfac, TSNR, Pick1, iplot=0, verbosity=1, fig=None, linecol
ax.plot(t, x, color=linecolor, linewidth=0.7, label='Data') ax.plot(t, x, color=linecolor, linewidth=0.7, label='Data')
ax.axvspan(t[inoise[0]], t[inoise[-1]], color='y', alpha=0.2, lw=0, label='Noise Window') ax.axvspan(t[inoise[0]], t[inoise[-1]], color='y', alpha=0.2, lw=0, label='Noise Window')
ax.axvspan(t[isignal[0]], t[isignal[-1]], color='b', alpha=0.2, lw=0, label='Signal Window') ax.axvspan(t[isignal[0]], t[isignal[-1]], color='b', alpha=0.2, lw=0, label='Signal Window')
ax.plot([t[0], t[int(len(t)) - 1]], [nlevel, nlevel], color=linecolor, linewidth=0.7, linestyle='dashed', label='Noise Level') ax.plot([t[0], t[int(len(t)) - 1]], [nlevel, nlevel], color=linecolor, linewidth=0.7, linestyle='dashed',
label='Noise Level')
ax.plot(t[pis[zc]], np.zeros(len(zc)), '*g', ax.plot(t[pis[zc]], np.zeros(len(zc)), '*g',
markersize=14, label='Zero Crossings') markersize=14, label='Zero Crossings')
ax.plot([t[0], t[int(len(t)) - 1]], [-nlevel, -nlevel], color=linecolor, linewidth=0.7, linestyle='dashed') ax.plot([t[0], t[int(len(t)) - 1]], [-nlevel, -nlevel], color=linecolor, linewidth=0.7, linestyle='dashed')
ax.plot([Pick1, Pick1], [max(x), -max(x)], 'b', linewidth=2, label='mpp') ax.plot([Pick1, Pick1], [max(x), -max(x)], 'b', linewidth=2, label='mpp')
ax.plot([LPick, LPick], [max(x) / 2, -max(x) / 2], color=linecolor, linewidth=0.7, linestyle='dashed', label='lpp') ax.plot([LPick, LPick], [max(x) / 2, -max(x) / 2], color=linecolor, linewidth=0.7, linestyle='dashed',
ax.plot([EPick, EPick], [max(x) / 2, -max(x) / 2], color=linecolor, linewidth=0.7, linestyle='dashed', label='epp') label='lpp')
ax.plot([EPick, EPick], [max(x) / 2, -max(x) / 2], color=linecolor, linewidth=0.7, linestyle='dashed',
label='epp')
ax.plot([Pick1 + PickError, Pick1 + PickError], ax.plot([Pick1 + PickError, Pick1 + PickError],
[max(x) / 2, -max(x) / 2], 'r--', label='spe') [max(x) / 2, -max(x) / 2], 'r--', label='spe')
ax.plot([Pick1 - PickError, Pick1 - PickError], ax.plot([Pick1 - PickError, Pick1 - PickError],
@ -162,8 +164,10 @@ def earllatepicker(X, nfac, TSNR, Pick1, iplot=0, verbosity=1, fig=None, linecol
ax.legend(loc=1) ax.legend(loc=1)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return EPick, LPick, PickError return EPick, LPick, PickError
@ -197,9 +201,9 @@ def fmpicker(Xraw, Xfilt, pickwin, Pick, iplot=0, fig=None, linecolor='k'):
iplot = int(iplot) iplot = int(iplot)
except: except:
if iplot == True or iplot == 'True': if iplot == True or iplot == 'True':
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
warnings.simplefilter('ignore', np.RankWarning) warnings.simplefilter('ignore', np.RankWarning)
@ -359,8 +363,10 @@ def fmpicker(Xraw, Xfilt, pickwin, Pick, iplot=0, fig=None, linecolor='k'):
ax2.set_yticks([]) ax2.set_yticks([])
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return FM return FM
@ -654,7 +660,7 @@ def wadaticheck(pickdic, dttolerance, iplot=0, fig_dict=None):
checkedSPtimes.append(checkedSPtime) checkedSPtimes.append(checkedSPtime)
pickdic[key]['S']['marked'] = marker pickdic[key]['S']['marked'] = marker
#pickdic[key]['S']['marked'] = marker # pickdic[key]['S']['marked'] = marker
print("wadaticheck: the following stations failed the check:") print("wadaticheck: the following stations failed the check:")
print(badstations) print(badstations)
@ -696,8 +702,8 @@ def wadaticheck(pickdic, dttolerance, iplot=0, fig_dict=None):
ax.plot(Ppicks, SPtimes, 'ro', label='Skipped S-Picks') ax.plot(Ppicks, SPtimes, 'ro', label='Skipped S-Picks')
if wfitflag == 0: if wfitflag == 0:
ax.plot(Ppicks, wdfit, color=linecolor, linewidth=0.7, label='Wadati 1') ax.plot(Ppicks, wdfit, color=linecolor, linewidth=0.7, label='Wadati 1')
ax.plot(Ppicks, wdfit+dttolerance, color='0.9', linewidth=0.5, label='Wadati 1 Tolerance') ax.plot(Ppicks, wdfit + dttolerance, color='0.9', linewidth=0.5, label='Wadati 1 Tolerance')
ax.plot(Ppicks, wdfit-dttolerance, color='0.9', linewidth=0.5) ax.plot(Ppicks, wdfit - dttolerance, color='0.9', linewidth=0.5)
ax.plot(checkedPpicks, wdfit2, 'g', label='Wadati 2') ax.plot(checkedPpicks, wdfit2, 'g', label='Wadati 2')
ax.plot(checkedPpicks, checkedSPtimes, color=linecolor, ax.plot(checkedPpicks, checkedSPtimes, color=linecolor,
linewidth=0, marker='o', label='Reliable S-Picks') linewidth=0, marker='o', label='Reliable S-Picks')
@ -764,9 +770,9 @@ def checksignallength(X, pick, TSNR, minsiglength, nfac, minpercent, iplot=0, fi
iplot = int(iplot) iplot = int(iplot)
except: except:
if real_Bool(iplot): if real_Bool(iplot):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
assert isinstance(X, Stream), "%s is not a stream object" % str(X) assert isinstance(X, Stream), "%s is not a stream object" % str(X)
@ -828,8 +834,10 @@ def checksignallength(X, pick, TSNR, minsiglength, nfac, minpercent, iplot=0, fi
ax.set_yticks([]) ax.set_yticks([])
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return returnflag return returnflag
@ -1054,16 +1062,15 @@ def checkZ4S(X, pick, zfac, checkwin, iplot, fig=None, linecolor='k'):
:return: returnflag; 0 if onset failed test, 1 if onset passed test :return: returnflag; 0 if onset failed test, 1 if onset passed test
:rtype: int :rtype: int
""" """
plt_flag = 0 plt_flag = 0
try: try:
iplot = int(iplot) iplot = int(iplot)
except: except:
if real_Bool(iplot): if real_Bool(iplot):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
assert isinstance(X, Stream), "%s is not a stream object" % str(X) assert isinstance(X, Stream), "%s is not a stream object" % str(X)
@ -1165,8 +1172,10 @@ def checkZ4S(X, pick, zfac, checkwin, iplot, fig=None, linecolor='k'):
ax.set_xlabel('Time [s] since %s' % zdat[0].stats.starttime) ax.set_xlabel('Time [s] since %s' % zdat[0].stats.starttime)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try:
except SyntaxError: pass input()
except SyntaxError:
pass
plt.close(fig) plt.close(fig)
return returnflag return returnflag
@ -1191,19 +1200,20 @@ def getQualityFromUncertainty(uncertainty, Errors):
if uncertainty <= Errors[0]: if uncertainty <= Errors[0]:
quality = 0 quality = 0
elif (uncertainty > Errors[0]) and \ elif (uncertainty > Errors[0]) and \
(uncertainty <= Errors[1]): (uncertainty <= Errors[1]):
quality = 1 quality = 1
elif (uncertainty > Errors[1]) and \ elif (uncertainty > Errors[1]) and \
(uncertainty <= Errors[2]): (uncertainty <= Errors[2]):
quality = 2 quality = 2
elif (uncertainty > Errors[2]) and \ elif (uncertainty > Errors[2]) and \
(uncertainty <= Errors[3]): (uncertainty <= Errors[3]):
quality = 3 quality = 3
elif uncertainty > Errors[3]: elif uncertainty > Errors[3]:
quality = 4 quality = 4
return quality return quality
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest

View File

@ -94,7 +94,7 @@ class Array_map(QtGui.QWidget):
self.comboBox_phase.currentIndexChanged.connect(self._refresh_drawings) self.comboBox_phase.currentIndexChanged.connect(self._refresh_drawings)
self.comboBox_am.currentIndexChanged.connect(self._refresh_drawings) self.comboBox_am.currentIndexChanged.connect(self._refresh_drawings)
self.canvas.mpl_connect('motion_notify_event', self.mouse_moved) self.canvas.mpl_connect('motion_notify_event', self.mouse_moved)
#self.zoom_id = self.basemap.ax.figure.canvas.mpl_connect('scroll_event', self.zoom) # self.zoom_id = self.basemap.ax.figure.canvas.mpl_connect('scroll_event', self.zoom)
def _from_dict(self, function, key): def _from_dict(self, function, key):
return function(self.stations_dict.values(), key=lambda x: x[key])[key] return function(self.stations_dict.values(), key=lambda x: x[key])[key]
@ -159,7 +159,6 @@ class Array_map(QtGui.QWidget):
self.main_box.addWidget(self.canvas, 1) self.main_box.addWidget(self.canvas, 1)
self.main_box.addWidget(self.status_label, 0) self.main_box.addWidget(self.status_label, 0)
def init_stations(self): def init_stations(self):
def stat_info_from_parser(parser): def stat_info_from_parser(parser):
stations_dict = {} stations_dict = {}
@ -354,7 +353,7 @@ class Array_map(QtGui.QWidget):
def add_cbar(self, label): def add_cbar(self, label):
self.cbax_bg = inset_axes(self.main_ax, width="6%", height="75%", loc=5) self.cbax_bg = inset_axes(self.main_ax, width="6%", height="75%", loc=5)
cbax = inset_axes(self.main_ax, width='2%', height='70%', loc=5) cbax = inset_axes(self.main_ax, width='2%', height='70%', loc=5)
cbar = self.main_ax.figure.colorbar(self.sc_picked, cax = cbax) cbar = self.main_ax.figure.colorbar(self.sc_picked, cax=cbax)
cbar.set_label(label) cbar.set_label(label)
cbax.yaxis.tick_left() cbax.yaxis.tick_left()
cbax.yaxis.set_label_position('left') cbax.yaxis.set_label_position('left')

View File

@ -33,7 +33,7 @@ class Metadata(object):
for index, inventory in enumerate(self.inventories): for index, inventory in enumerate(self.inventories):
if index < 2 or (ntotal - index) < 3: if index < 2 or (ntotal - index) < 3:
repr += '{}\n'.format(inventory) repr += '{}\n'.format(inventory)
if ntotal > 4 and int(ntotal/2) == index: if ntotal > 4 and int(ntotal / 2) == index:
repr += '...\n' repr += '...\n'
if ntotal > 4: if ntotal > 4:
repr += '\nTotal of {} inventories. Use Metadata.inventories to see all.'.format(ntotal) repr += '\nTotal of {} inventories. Use Metadata.inventories to see all.'.format(ntotal)
@ -79,11 +79,10 @@ class Metadata(object):
self.inventories.remove(path_to_inventory) self.inventories.remove(path_to_inventory)
for filename in self.inventory_files.keys(): for filename in self.inventory_files.keys():
if filename.startswith(path_to_inventory): if filename.startswith(path_to_inventory):
del(self.inventory_files[filename]) del (self.inventory_files[filename])
for seed_id in self.seed_ids.keys(): for seed_id in self.seed_ids.keys():
if self.seed_ids[seed_id].startswith(path_to_inventory): if self.seed_ids[seed_id].startswith(path_to_inventory):
del(self.seed_ids[seed_id]) del (self.seed_ids[seed_id])
def get_metadata(self, seed_id, time=None): def get_metadata(self, seed_id, time=None):
""" """
@ -123,7 +122,6 @@ class Metadata(object):
fname = self.seed_ids[seed_id] fname = self.seed_ids[seed_id]
return self.inventory_files[fname] return self.inventory_files[fname]
def read_all(self): def read_all(self):
""" """
Read all metadata files found in all inventories Read all metadata files found in all inventories
@ -134,7 +132,6 @@ class Metadata(object):
if not self.read_single_file(inv_fname): if not self.read_single_file(inv_fname):
continue continue
def read_single_file(self, inv_fname): def read_single_file(self, inv_fname):
""" """
Try to read a single file as Parser/Inventory and add its dictionary to inventory files if reading sudceeded. Try to read a single file as Parser/Inventory and add its dictionary to inventory files if reading sudceeded.
@ -157,7 +154,6 @@ class Metadata(object):
'data': robj} 'data': robj}
return True return True
def get_coordinates(self, seed_id, time=None): def get_coordinates(self, seed_id, time=None):
""" """
Get coordinates of given seed id. Get coordinates of given seed id.
@ -176,7 +172,6 @@ class Metadata(object):
return return
return metadata['data'].get_coordinates(seed_id, time) return metadata['data'].get_coordinates(seed_id, time)
def get_paz(self, seed_id, time): def get_paz(self, seed_id, time):
""" """
@ -195,13 +190,11 @@ class Metadata(object):
resp = metadata['data'].get_response(seed_id, time) resp = metadata['data'].get_response(seed_id, time)
return resp.get_paz(seed_id) return resp.get_paz(seed_id)
def _read_inventory_data(self, seed_id=None): def _read_inventory_data(self, seed_id=None):
for inventory in self.inventories: for inventory in self.inventories:
if self._read_metadata_iterator(path_to_inventory=inventory, station_seed_id=seed_id): if self._read_metadata_iterator(path_to_inventory=inventory, station_seed_id=seed_id):
return return
def _read_metadata_iterator(self, path_to_inventory, station_seed_id): def _read_metadata_iterator(self, path_to_inventory, station_seed_id):
""" """
Search for metadata for a specific station iteratively. Search for metadata for a specific station iteratively.
@ -236,7 +229,6 @@ class Metadata(object):
continue continue
print('Could not find metadata for station_seed_id {} in path {}'.format(station_seed_id, path_to_inventory)) print('Could not find metadata for station_seed_id {} in path {}'.format(station_seed_id, path_to_inventory))
def _read_metadata_file(self, path_to_inventory_filename): def _read_metadata_file(self, path_to_inventory_filename):
""" """
function reading metadata files (either dataless seed, xml or resp) function reading metadata files (either dataless seed, xml or resp)
@ -262,7 +254,6 @@ class Metadata(object):
return file_type, robj return file_type, robj
return None, None return None, None
@staticmethod @staticmethod
def _read_dless(path_to_inventory): def _read_dless(path_to_inventory):
exc = None exc = None
@ -272,7 +263,6 @@ class Metadata(object):
parser = None parser = None
return parser, exc return parser, exc
@staticmethod @staticmethod
def _read_inventory_file(path_to_inventory): def _read_inventory_file(path_to_inventory):
exc = None exc = None
@ -283,7 +273,6 @@ class Metadata(object):
return inv, exc return inv, exc
def time_from_header(header): def time_from_header(header):
""" """
Function takes in the second line from a .gse file and takes out the date and time from that line. Function takes in the second line from a .gse file and takes out the date and time from that line.
@ -494,7 +483,6 @@ def read_metadata(path_to_inventory):
# return metadata_objects # return metadata_objects
def restitute_trace(input_tuple): def restitute_trace(input_tuple):
def no_metadata(tr, seed_id): def no_metadata(tr, seed_id):
print('no metadata file found ' print('no metadata file found '

View File

@ -16,7 +16,6 @@ from pylot.core.loc import hyposat
from pylot.core.loc import nll from pylot.core.loc import nll
from pylot.core.loc import velest from pylot.core.loc import velest
# determine system dependent path separator # determine system dependent path separator
system_name = platform.system() system_name = platform.system()
if system_name in ["Linux", "Darwin"]: if system_name in ["Linux", "Darwin"]:

View File

@ -4,6 +4,7 @@
import os import os
from obspy import UTCDateTime from obspy import UTCDateTime
def check_obspydmt_structure(path): def check_obspydmt_structure(path):
''' '''
Check path for obspyDMT event structure. Check path for obspyDMT event structure.
@ -16,6 +17,7 @@ def check_obspydmt_structure(path):
return True return True
return False return False
def check_obspydmt_eventfolder(folder): def check_obspydmt_eventfolder(folder):
try: try:
time = folder.split('.')[0] time = folder.split('.')[0]
@ -25,6 +27,7 @@ def check_obspydmt_eventfolder(folder):
except Exception as e: except Exception as e:
return False, e return False, e
def qml_from_obspyDMT(path): def qml_from_obspyDMT(path):
import pickle import pickle
from obspy.core.event import Event, Magnitude, Origin from obspy.core.event import Event, Magnitude, Origin
@ -41,4 +44,3 @@ def qml_from_obspyDMT(path):
ev.magnitudes.append(mag) ev.magnitudes.append(mag)
ev.origins.append(origin) ev.origins.append(origin)
return ev return ev

View File

@ -33,8 +33,8 @@ class Thread(QThread):
self._executed = False self._executed = False
self._executedError = e self._executedError = e
traceback.print_exc() traceback.print_exc()
exctype, value = sys.exc_info ()[:2] exctype, value = sys.exc_info()[:2]
self._executedErrorInfo = '{} {} {}'.\ self._executedErrorInfo = '{} {} {}'. \
format(exctype, value, traceback.format_exc()) format(exctype, value, traceback.format_exc())
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
@ -75,6 +75,7 @@ class Worker(QRunnable):
''' '''
Worker class to be run by MultiThread(QThread). Worker class to be run by MultiThread(QThread).
''' '''
def __init__(self, fun, args, def __init__(self, fun, args,
progressText=None, progressText=None,
pb_widget=None, pb_widget=None,
@ -82,7 +83,7 @@ class Worker(QRunnable):
super(Worker, self).__init__() super(Worker, self).__init__()
self.fun = fun self.fun = fun
self.args = args self.args = args
#self.kwargs = kwargs # self.kwargs = kwargs
self.signals = WorkerSignals() self.signals = WorkerSignals()
self.progressText = progressText self.progressText = progressText
self.pb_widget = pb_widget self.pb_widget = pb_widget
@ -96,9 +97,9 @@ class Worker(QRunnable):
try: try:
result = self.fun(self.args) result = self.fun(self.args)
except: except:
exctype, value = sys.exc_info ()[:2] exctype, value = sys.exc_info()[:2]
print(exctype, value, traceback.format_exc()) print(exctype, value, traceback.format_exc())
self.signals.error.emit ((exctype, value, traceback.format_exc ())) self.signals.error.emit((exctype, value, traceback.format_exc()))
else: else:
self.signals.result.emit(result) self.signals.result.emit(result)
finally: finally:
@ -140,13 +141,13 @@ class MultiThread(QThread):
def run(self): def run(self):
if self.redirect_stdout: if self.redirect_stdout:
sys.stdout = self sys.stdout = self
try: try:
if not self.ncores: if not self.ncores:
self.ncores = multiprocessing.cpu_count() self.ncores = multiprocessing.cpu_count()
pool = multiprocessing.Pool(self.ncores) pool = multiprocessing.Pool(self.ncores)
self.data = pool.map_async(self.func, self.args, callback=self.emitDone) self.data = pool.map_async(self.func, self.args, callback=self.emitDone)
#self.data = pool.apply_async(self.func, self.shotlist, callback=self.emitDone) #emit each time returned # self.data = pool.apply_async(self.func, self.shotlist, callback=self.emitDone) #emit each time returned
pool.close() pool.close()
self._executed = True self._executed = True
except Exception as e: except Exception as e:

View File

@ -28,12 +28,14 @@ except Exception as e:
print('PyLoT: Could not import pyqtgraph. {}'.format(e)) print('PyLoT: Could not import pyqtgraph. {}'.format(e))
pg = None pg = None
def _pickle_method(m): def _pickle_method(m):
if m.im_self is None: if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name) return getattr, (m.im_class, m.im_func.func_name)
else: else:
return getattr, (m.im_self, m.im_func.func_name) return getattr, (m.im_self, m.im_func.func_name)
def getAutoFilteroptions(phase, parameter): def getAutoFilteroptions(phase, parameter):
filtername = {'P': 'bpz2', filtername = {'P': 'bpz2',
'S': 'bph2'} 'S': 'bph2'}
@ -41,9 +43,10 @@ def getAutoFilteroptions(phase, parameter):
print('autoPickParameter: No filter options for phase {}.'.format(phase)) print('autoPickParameter: No filter options for phase {}.'.format(phase))
return return
freqmin, freqmax = parameter.get(filtername[phase]) freqmin, freqmax = parameter.get(filtername[phase])
filteroptions = FilterOptions(type='bandpass', freq=[freqmin, freqmax], order=4) # order=4 default from obspy filteroptions = FilterOptions(type='bandpass', freq=[freqmin, freqmax], order=4) # order=4 default from obspy
return filteroptions return filteroptions
def readDefaultFilterInformation(fname): def readDefaultFilterInformation(fname):
""" """
Read default filter information from pylot.in file Read default filter information from pylot.in file
@ -679,7 +682,7 @@ def pick_color(picktype, phase, quality=0):
bpc = base_phase_colors(picktype, phase) # returns dict like {'modifier': 'g', 'rgba': (0, 0, 255, 255)} bpc = base_phase_colors(picktype, phase) # returns dict like {'modifier': 'g', 'rgba': (0, 0, 255, 255)}
rgba = bpc['rgba'] rgba = bpc['rgba']
modifier = bpc['modifier'] modifier = bpc['modifier']
intensity = 255.*quality/min_quality intensity = 255. * quality / min_quality
rgba = modify_rgba(rgba, modifier, intensity) rgba = modify_rgba(rgba, modifier, intensity)
return rgba return rgba
@ -791,6 +794,7 @@ def base_phase_colors(picktype, phase):
phasecolors = style_settings.phasecolors phasecolors = style_settings.phasecolors
return phasecolors[picktype][phase] return phasecolors[picktype][phase]
def transform_colors_mpl_str(colors, no_alpha=False): def transform_colors_mpl_str(colors, no_alpha=False):
""" """
Transforms rgba color values to a matplotlib string of color values with a range of [0, 1] Transforms rgba color values to a matplotlib string of color values with a range of [0, 1]
@ -809,6 +813,7 @@ def transform_colors_mpl_str(colors, no_alpha=False):
colors_mpl = '({}, {}, {}, {})'.format(*colors_mpl) colors_mpl = '({}, {}, {}, {})'.format(*colors_mpl)
return colors_mpl return colors_mpl
def transform_colors_mpl(colors): def transform_colors_mpl(colors):
""" """
Transform rgba colors from [0, 255] to [0, 1] Transform rgba colors from [0, 255] to [0, 1]
@ -821,6 +826,7 @@ def transform_colors_mpl(colors):
colors_mpl = tuple([color / 255. for color in colors]) colors_mpl = tuple([color / 255. for color in colors])
return colors_mpl return colors_mpl
def remove_underscores(data): def remove_underscores(data):
""" """
takes a `obspy.core.stream.Stream` object and removes all underscores takes a `obspy.core.stream.Stream` object and removes all underscores
@ -976,7 +982,8 @@ def check4rotated(data, metadata=None, verbosity=1):
wfstream[2], azimuts[2], dips[2]) wfstream[2], azimuts[2], dips[2])
print('check4rotated: rotated trace {} to ZNE'.format(trace_id)) print('check4rotated: rotated trace {} to ZNE'.format(trace_id))
# replace old data with rotated data, change the channel code to ZNE # replace old data with rotated data, change the channel code to ZNE
z_index = dips.index(min(dips)) # get z-trace index, z has minimum dip of -90 (dip is measured from 0 to -90, with -90 being vertical) z_index = dips.index(min(
dips)) # get z-trace index, z has minimum dip of -90 (dip is measured from 0 to -90, with -90 being vertical)
wfstream[z_index].data = z wfstream[z_index].data = z
wfstream[z_index].stats.channel = wfstream[z_index].stats.channel[0:-1] + 'Z' wfstream[z_index].stats.channel = wfstream[z_index].stats.channel[0:-1] + 'Z'
del trace_ids[z_index] del trace_ids[z_index]
@ -1206,8 +1213,8 @@ def check_event_folder(path):
folder = path.split('/')[-1] folder = path.split('/')[-1]
# for pylot: select only folders that start with 'e', containin two dots and have length 12 # for pylot: select only folders that start with 'e', containin two dots and have length 12
if (folder.startswith('e') if (folder.startswith('e')
and len(folder.split('.')) == 3 and len(folder.split('.')) == 3
and len(folder) == 12): and len(folder) == 12):
ev_type = 'pylot' ev_type = 'pylot'
elif check_obspydmt_eventfolder(folder)[0]: elif check_obspydmt_eventfolder(folder)[0]:
ev_type = 'obspydmt' ev_type = 'obspydmt'

View File

@ -17,6 +17,7 @@ import time
import numpy as np import numpy as np
import matplotlib import matplotlib
matplotlib.use('QT4Agg') matplotlib.use('QT4Agg')
from matplotlib.figure import Figure from matplotlib.figure import Figure
@ -381,8 +382,8 @@ class ComparisonWidget(QWidget):
ax = axes_dict[phase]['exp'] ax = axes_dict[phase]['exp']
xlims = ax.get_xlim() xlims = ax.get_xlim()
ylims = ax.get_ylim() ylims = ax.get_ylim()
#ax.fill_between([xlims[0], 0], ylims[0], ylims[1], color=(0.9, 1.0, 0.9, 0.5), label='earlier than manual') # ax.fill_between([xlims[0], 0], ylims[0], ylims[1], color=(0.9, 1.0, 0.9, 0.5), label='earlier than manual')
#ax.fill_between([0, xlims[1]], ylims[0], ylims[1], color=(1.0, 0.9, 0.9, 0.5), label='later than manual') # ax.fill_between([0, xlims[1]], ylims[0], ylims[1], color=(1.0, 0.9, 0.9, 0.5), label='later than manual')
legend = ax.legend() legend = ax.legend()
legend.draggable() legend.draggable()
@ -474,7 +475,7 @@ class WaveformWidgetPG(QtGui.QWidget):
self.pen_linecolor_syn = self.pg.mkPen((100, 0, 255, 255)) self.pen_linecolor_syn = self.pg.mkPen((100, 0, 255, 255))
self.reinitMoveProxy() self.reinitMoveProxy()
self._proxy = self.pg.SignalProxy(self.plotWidget.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved) self._proxy = self.pg.SignalProxy(self.plotWidget.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
#self.plotWidget.getPlotItem().setDownsampling(auto=True) # self.plotWidget.getPlotItem().setDownsampling(auto=True)
def reinitMoveProxy(self): def reinitMoveProxy(self):
self.vLine = self.pg.InfiniteLine(angle=90, movable=False, pen=self.pen_multicursor) self.vLine = self.pg.InfiniteLine(angle=90, movable=False, pen=self.pen_multicursor)
@ -524,7 +525,7 @@ class WaveformWidgetPG(QtGui.QWidget):
self.syn_checkbox = QtGui.QCheckBox('synthetics') self.syn_checkbox = QtGui.QCheckBox('synthetics')
self.addQCboxItem('processed', 'green') self.addQCboxItem('processed', 'green')
self.addQCboxItem('raw', 'black') self.addQCboxItem('raw', 'black')
#self.perm_qcbox_right.setAlignment(2) # self.perm_qcbox_right.setAlignment(2)
self.setLayout(self.main_layout) self.setLayout(self.main_layout)
def getPlotDict(self): def getPlotDict(self):
@ -608,7 +609,7 @@ class WaveformWidgetPG(QtGui.QWidget):
print('Warning: Could not set zoom limits') print('Warning: Could not set zoom limits')
for n, (network, station, channel) in enumerate(nsc): for n, (network, station, channel) in enumerate(nsc):
n+=1 n += 1
st = st_select.select(network=network, station=station, channel=channel) st = st_select.select(network=network, station=station, channel=channel)
trace = st[0].copy() trace = st[0].copy()
st_syn = wfsyn.select(network=network, station=station, channel=channel) st_syn = wfsyn.select(network=network, station=station, channel=channel)
@ -645,10 +646,11 @@ class WaveformWidgetPG(QtGui.QWidget):
trace_syn.normalize(np.max(np.abs(trace_syn.data)) * 2) trace_syn.normalize(np.max(np.abs(trace_syn.data)) * 2)
# TODO: change this to numpy operations instead of lists? # TODO: change this to numpy operations instead of lists?
times = np.array([time for index, time in enumerate(time_ax) if not index % nth_sample]) times = np.array([time for index, time in enumerate(time_ax) if not index % nth_sample])
times_syn = np.array([time for index, time in enumerate(time_ax_syn) if not index % nth_sample] if st_syn else []) times_syn = np.array(
[time for index, time in enumerate(time_ax_syn) if not index % nth_sample] if st_syn else [])
trace.data = np.array([datum + n for index, datum in enumerate(trace.data) if not index % nth_sample]) trace.data = np.array([datum + n for index, datum in enumerate(trace.data) if not index % nth_sample])
trace_syn.data = np.array([datum + n for index, datum in enumerate(trace_syn.data) trace_syn.data = np.array([datum + n for index, datum in enumerate(trace_syn.data)
if not index % nth_sample] if st_syn else []) if not index % nth_sample] if st_syn else [])
plots.append((times, trace.data, plots.append((times, trace.data,
times_syn, trace_syn.data)) times_syn, trace_syn.data))
self.setPlotDict(n, (station, channel, network)) self.setPlotDict(n, (station, channel, network))
@ -665,11 +667,11 @@ class WaveformWidgetPG(QtGui.QWidget):
''' '''
npixel = self.orig_parent.width() npixel = self.orig_parent.width()
ndata = len(trace.data) ndata = len(trace.data)
pts_per_pixel = ndata/npixel pts_per_pixel = ndata / npixel
if pts_per_pixel < 2: if pts_per_pixel < 2:
return trace.data, time_ax return trace.data, time_ax
remaining_samples = ndata%pts_per_pixel remaining_samples = ndata % pts_per_pixel
npixel = ndata//pts_per_pixel npixel = ndata // pts_per_pixel
if remaining_samples: if remaining_samples:
data = trace.data[:-remaining_samples] data = trace.data[:-remaining_samples]
else: else:
@ -849,7 +851,7 @@ class PylotCanvas(FigureCanvas):
break break
if not ax_check: return if not ax_check: return
#self.updateCurrentLimits() #maybe put this down to else: # self.updateCurrentLimits() #maybe put this down to else:
# calculate delta (relative values in axis) # calculate delta (relative values in axis)
old_x, old_y = self.press_rel old_x, old_y = self.press_rel
@ -902,13 +904,13 @@ class PylotCanvas(FigureCanvas):
d_upper = abs(origin - upper_b) d_upper = abs(origin - upper_b)
if positive: if positive:
d_lower *= 1 - 1/factor d_lower *= 1 - 1 / factor
d_upper *= 1 - 1/factor d_upper *= 1 - 1 / factor
lower_b += d_lower lower_b += d_lower
upper_b -= d_upper upper_b -= d_upper
else: else:
d_lower /= 1 + 1/factor d_lower /= 1 + 1 / factor
d_upper /= 1 + 1/factor d_upper /= 1 + 1 / factor
lower_b -= d_lower lower_b -= d_lower
upper_b += d_upper upper_b += d_upper
@ -1133,9 +1135,9 @@ class PylotCanvas(FigureCanvas):
if noiselevel is not None: if noiselevel is not None:
for level in [-noiselevel[channel], noiselevel[channel]]: for level in [-noiselevel[channel], noiselevel[channel]]:
ax.plot([time_ax[0], time_ax[-1]], ax.plot([time_ax[0], time_ax[-1]],
[n+level, n+level], [n + level, n + level],
color = linecolor, color=linecolor,
linestyle = 'dashed') linestyle='dashed')
self.setPlotDict(n, (station, channel, network)) self.setPlotDict(n, (station, channel, network))
if plot_additional and additional_channel: if plot_additional and additional_channel:
compare_stream = wfdata.select(channel=additional_channel) compare_stream = wfdata.select(channel=additional_channel)
@ -1217,7 +1219,7 @@ class PylotCanvas(FigureCanvas):
def insertLabel(self, pos, text): def insertLabel(self, pos, text):
pos = pos / max(self.axes[0].ylim) pos = pos / max(self.axes[0].ylim)
axann = self.axes[0].annotate(text, xy=(.03, pos), axann = self.axes[0].annotate(text, xy=(.03, pos),
xycoords='axes fraction') xycoords='axes fraction')
axann.set_bbox(dict(facecolor='lightgrey', alpha=.6)) axann.set_bbox(dict(facecolor='lightgrey', alpha=.6))
def setZoomBorders2content(self): def setZoomBorders2content(self):
@ -1441,7 +1443,6 @@ class PickDlg(QDialog):
self.multicompfig.draw() self.multicompfig.draw()
self.multicompfig.setFocus() self.multicompfig.setFocus()
# set plot labels # set plot labels
self.setPlotLabels() self.setPlotLabels()
@ -1467,7 +1468,6 @@ class PickDlg(QDialog):
self.setWindowTitle('Pickwindow on station: {}'.format(self.getStation())) self.setWindowTitle('Pickwindow on station: {}'.format(self.getStation()))
self.setWindowState(QtCore.Qt.WindowMaximized) self.setWindowState(QtCore.Qt.WindowMaximized)
def setupUi(self): def setupUi(self):
menuBar = QtGui.QMenuBar(self) menuBar = QtGui.QMenuBar(self)
if not self._embedded: if not self._embedded:
@ -1512,11 +1512,11 @@ class PickDlg(QDialog):
checkable=True, checkable=True,
shortcut='S') shortcut='S')
self.autoFilterAction = createAction(parent=self, text='Automatic Filtering', self.autoFilterAction = createAction(parent=self, text='Automatic Filtering',
slot=self.toggleAutoFilter, slot=self.toggleAutoFilter,
icon=key_a_icon, icon=key_a_icon,
tip='Filter automatically before initial pick', tip='Filter automatically before initial pick',
checkable=True, checkable=True,
shortcut='Ctrl+A') shortcut='Ctrl+A')
self.zoomAction = createAction(parent=self, text='Zoom', self.zoomAction = createAction(parent=self, text='Zoom',
slot=self.zoom, icon=zoom_icon, slot=self.zoom, icon=zoom_icon,
tip='Zoom into waveform', tip='Zoom into waveform',
@ -1604,8 +1604,8 @@ class PickDlg(QDialog):
_dialtoolbar.addSeparator() _dialtoolbar.addSeparator()
est_label = QLabel('Estimated onsets:') est_label = QLabel('Estimated onsets:')
est_label.setStyleSheet('QLabel {' est_label.setStyleSheet('QLabel {'
'padding:2px;' 'padding:2px;'
'padding-left:5px}') 'padding-left:5px}')
_dialtoolbar.addWidget(est_label) _dialtoolbar.addWidget(est_label)
_dialtoolbar.addWidget(self.plot_arrivals_button) _dialtoolbar.addWidget(self.plot_arrivals_button)
_dialtoolbar.addSeparator() _dialtoolbar.addSeparator()
@ -1805,16 +1805,15 @@ class PickDlg(QDialog):
picksMenu.addSeparator() picksMenu.addSeparator()
filterOptionsAction = createAction(parent=self, text="&Filter parameter ...", filterOptionsAction = createAction(parent=self, text="&Filter parameter ...",
slot=self.filterOptions, slot=self.filterOptions,
shortcut='Ctrl+F', shortcut='Ctrl+F',
icon=self.orig_parent.filter_icon) icon=self.orig_parent.filter_icon)
filterMenu = menuBar.addMenu('Filter') filterMenu = menuBar.addMenu('Filter')
filterMenu.addAction(self.filterActionP) filterMenu.addAction(self.filterActionP)
filterMenu.addAction(self.filterActionS) filterMenu.addAction(self.filterActionS)
filterMenu.addAction(self.autoFilterAction) filterMenu.addAction(self.autoFilterAction)
filterMenu.addAction(filterOptionsAction) filterMenu.addAction(filterOptionsAction)
def filterOptions(self): def filterOptions(self):
if self.orig_parent.adjustFilterOptions(): if self.orig_parent.adjustFilterOptions():
phase = None phase = None
@ -1953,7 +1952,7 @@ class PickDlg(QDialog):
self.draw() self.draw()
else: else:
self.draw() self.draw()
#self.pick_block = self.togglePickBlocker() # self.pick_block = self.togglePickBlocker()
self.disconnect_pick_delete() self.disconnect_pick_delete()
def deactivatePicking(self): def deactivatePicking(self):
@ -2101,7 +2100,7 @@ class PickDlg(QDialog):
def calcNoiseScaleFactor(noiselevel, zoomfactor=5., norm=1): def calcNoiseScaleFactor(noiselevel, zoomfactor=5., norm=1):
# calculate factor to upscale a trace normed to 'norm' in a way that all values # calculate factor to upscale a trace normed to 'norm' in a way that all values
# zoomfactor*noiselevel are found within -0.5*norm and 0.5*norm # zoomfactor*noiselevel are found within -0.5*norm and 0.5*norm
scaleFactor = (norm/2.) / (zoomfactor * noiselevel) scaleFactor = (norm / 2.) / (zoomfactor * noiselevel)
return scaleFactor return scaleFactor
def setIniPick(self, gui_event): def setIniPick(self, gui_event):
@ -2175,7 +2174,7 @@ class PickDlg(QDialog):
try: try:
data.detrend('linear') data.detrend('linear')
data.filter(**filteroptions) data.filter(**filteroptions)
#wfdata.filter(**filteroptions)# MP MP removed filtering of original data # wfdata.filter(**filteroptions)# MP MP removed filtering of original data
except ValueError as e: except ValueError as e:
self.qmb = QtGui.QMessageBox(QtGui.QMessageBox.Icon.Information, self.qmb = QtGui.QMessageBox(QtGui.QMessageBox.Icon.Information,
'Denied', 'setIniPick{}: Could not filter waveform: {}'.format(phase, e)) 'Denied', 'setIniPick{}: Could not filter waveform: {}'.format(phase, e))
@ -2211,7 +2210,7 @@ class PickDlg(QDialog):
x_res = getResolutionWindow(np.mean(snr), parameter.get('extent')) x_res = getResolutionWindow(np.mean(snr), parameter.get('extent'))
xlims = [ini_pick - x_res, ini_pick + x_res] xlims = [ini_pick - x_res, ini_pick + x_res]
ylims = list(np.array([-.5, .5]) + [0, len(data)-1]) ylims = list(np.array([-.5, .5]) + [0, len(data) - 1])
title = self.getStation() + ' picking mode' title = self.getStation() + ' picking mode'
if filterphase: if filterphase:
@ -2298,8 +2297,8 @@ class PickDlg(QDialog):
self.disconnectPressEvent() self.disconnectPressEvent()
self.enable_ar_buttons() self.enable_ar_buttons()
self.zoomAction.setEnabled(True) self.zoomAction.setEnabled(True)
#self.pick_block = self.togglPickBlocker() # self.pick_block = self.togglPickBlocker()
#self.resetZoom() # self.resetZoom()
self.leave_picking_mode() self.leave_picking_mode()
def savePick(self, phase, phasepicks): def savePick(self, phase, phasepicks):
@ -2335,7 +2334,7 @@ class PickDlg(QDialog):
if self.getPicks(picktype): if self.getPicks(picktype):
if phase is not None and not phase == 'SPt': if phase is not None and not phase == 'SPt':
if (type(self.getPicks(picktype)[phase]) is dict if (type(self.getPicks(picktype)[phase]) is dict
or type(self.getPicks(picktype)[phase]) is AttribDict): or type(self.getPicks(picktype)[phase]) is AttribDict):
picks = self.getPicks(picktype)[phase] picks = self.getPicks(picktype)[phase]
elif phase is None: elif phase is None:
for phase in self.getPicks(picktype): for phase in self.getPicks(picktype):
@ -2368,7 +2367,7 @@ class PickDlg(QDialog):
label='{}-Pick (quality: {})'.format(phase, quality), picker=5) label='{}-Pick (quality: {})'.format(phase, quality), picker=5)
self.phaseLines[phase] = vl self.phaseLines[phase] = vl
if spe: if spe:
ax.fill_between([mpp-spe, mpp+spe], ylims[0], ylims[1], ax.fill_between([mpp - spe, mpp + spe], ylims[0], ylims[1],
alpha=.25, color=color, label='{}-SPE'.format(phase)) alpha=.25, color=color, label='{}-SPE'.format(phase))
if picks['epp']: if picks['epp']:
linestyle_epp, width_epp = pick_linestyle_plt(picktype, 'epp') linestyle_epp, width_epp = pick_linestyle_plt(picktype, 'epp')
@ -2414,7 +2413,7 @@ class PickDlg(QDialog):
def on_motion(self, event): def on_motion(self, event):
x = event.xdata x = event.xdata
if x is not None: if x is not None:
time_code = 'T = {}, t = {} [s]'.format(self.stime+x, x) time_code = 'T = {}, t = {} [s]'.format(self.stime + x, x)
user_help = ' - Left-Click to Drag | Right-Click to Pan-Zoom |' \ user_help = ' - Left-Click to Drag | Right-Click to Pan-Zoom |' \
' Mousewheel to Zoom | Middle-Click to Delete Pick' ' Mousewheel to Zoom | Middle-Click to Delete Pick'
self.statusbar.showMessage(time_code + user_help) self.statusbar.showMessage(time_code + user_help)
@ -2516,10 +2515,10 @@ class PickDlg(QDialog):
allpicks[picktype].pop(phase) allpicks[picktype].pop(phase)
# delete line from vlines dictionary # delete line from vlines dictionary
if phase in self.phaseLines.keys(): if phase in self.phaseLines.keys():
del(self.phaseLines[phase]) del (self.phaseLines[phase])
# information output # information output
msg = 'Deleted {} pick for phase {}, at timestamp {} (relative time: {} s)' msg = 'Deleted {} pick for phase {}, at timestamp {} (relative time: {} s)'
print(msg.format(picktype, phase, self.getStartTime()+pick_rel, pick_rel)) print(msg.format(picktype, phase, self.getStartTime() + pick_rel, pick_rel))
self.setDirty(True) self.setDirty(True)
def identify_selected_picks(self, x): def identify_selected_picks(self, x):
@ -2545,8 +2544,6 @@ class PickDlg(QDialog):
pick_rel, phase, picktype = X[index] pick_rel, phase, picktype = X[index]
return allpicks, pick_rel, phase, picktype return allpicks, pick_rel, phase, picktype
def drawPhaseText(self): def drawPhaseText(self):
self.drawPicks(picktype='manual', textOnly=True) self.drawPicks(picktype='manual', textOnly=True)
self.drawPicks(picktype='auto', textOnly=True) self.drawPicks(picktype='auto', textOnly=True)
@ -2583,7 +2580,7 @@ class PickDlg(QDialog):
return return
self.cur_xlim = self.multicompfig.axes[0].get_xlim() self.cur_xlim = self.multicompfig.axes[0].get_xlim()
self.cur_ylim = self.multicompfig.axes[0].get_ylim() self.cur_ylim = self.multicompfig.axes[0].get_ylim()
#self.multicompfig.updateCurrentLimits() # self.multicompfig.updateCurrentLimits()
data = self.getWFData().copy() data = self.getWFData().copy()
title = self.getStation() title = self.getStation()
if filter: if filter:
@ -2677,7 +2674,6 @@ class PickDlg(QDialog):
rval = False rval = False
return rval return rval
def resetPlot(self): def resetPlot(self):
self.resetZoom() self.resetZoom()
self.refreshPlot() self.refreshPlot()
@ -2716,8 +2712,8 @@ class PickDlg(QDialog):
# set channel labels # set channel labels
self.multicompfig.setYTickLabels(pos, labels) self.multicompfig.setYTickLabels(pos, labels)
#self.multicompfig.setXLims(ax, self.getXLims()) # self.multicompfig.setXLims(ax, self.getXLims())
#self.multicompfig.setYLims(ax, self.getYLims()) # self.multicompfig.setYLims(ax, self.getYLims())
def zoom(self): def zoom(self):
if self.zoomAction.isChecked() and self.pick_block: if self.zoomAction.isChecked() and self.pick_block:
@ -2779,7 +2775,7 @@ class CanvasWidget(QWidget):
''' '''
def __init__(self, parent, canvas): def __init__(self, parent, canvas):
QtGui.QWidget.__init__(self, parent)#, 1) QtGui.QWidget.__init__(self, parent) # , 1)
canvas = canvas canvas = canvas
self.main_layout = QtGui.QVBoxLayout() self.main_layout = QtGui.QVBoxLayout()
self.setLayout(self.main_layout) self.setLayout(self.main_layout)
@ -2792,6 +2788,7 @@ class MultiEventWidget(QWidget):
''' '''
''' '''
def __init__(self, options=None, parent=None, windowflag=1): def __init__(self, options=None, parent=None, windowflag=1):
QtGui.QWidget.__init__(self, parent, windowflag) QtGui.QWidget.__init__(self, parent, windowflag)
@ -2851,7 +2848,7 @@ class MultiEventWidget(QWidget):
self.pb.setRange(0, 0) self.pb.setRange(0, 0)
self.pb.setVisible(False) self.pb.setVisible(False)
#space holder for progressbar # space holder for progressbar
self._pb_space = QtGui.QWidget() self._pb_space = QtGui.QWidget()
self.rb_layout.addWidget(self.start_button) self.rb_layout.addWidget(self.start_button)
@ -2869,7 +2866,7 @@ class MultiEventWidget(QWidget):
eventlist = func() eventlist = func()
if not type(eventlist) == list: if not type(eventlist) == list:
eventlist = [eventlist] eventlist = [eventlist]
tooltip='' tooltip = ''
for index, event in enumerate(eventlist): for index, event in enumerate(eventlist):
if not event: if not event:
continue continue
@ -2885,13 +2882,13 @@ class MultiEventWidget(QWidget):
for rb in self.rb_dict.values(): for rb in self.rb_dict.values():
if rb.isChecked(): if rb.isChecked():
check_events = (rb.toolTip() == 'No events for this selection') check_events = (rb.toolTip() == 'No events for this selection')
self.start_button.setEnabled(not(check_events)) self.start_button.setEnabled(not (check_events))
def enable(self, bool): def enable(self, bool):
for rb in self.rb_dict.values(): for rb in self.rb_dict.values():
rb.setEnabled(bool) rb.setEnabled(bool)
self.start_button.setEnabled(bool) self.start_button.setEnabled(bool)
self.pb.setVisible(not(bool)) self.pb.setVisible(not (bool))
self._pb_space.setVisible(bool) self._pb_space.setVisible(bool)
self.eventbox.setEnabled(bool) self.eventbox.setEnabled(bool)
self.button_clear.setEnabled(bool) self.button_clear.setEnabled(bool)
@ -2973,7 +2970,7 @@ class AutoPickWidget(MultiEventWidget):
def reinitEvents2plot(self): def reinitEvents2plot(self):
for eventID, eventDict in self.events2plot.items(): for eventID, eventDict in self.events2plot.items():
for widget_key, widget in eventDict.items(): for widget_key, widget in eventDict.items():
del(widget) del (widget)
self.events2plot = {} self.events2plot = {}
self.eventbox.clear() self.eventbox.clear()
self.refresh_plot_tabs() self.refresh_plot_tabs()
@ -3507,7 +3504,7 @@ class TuneAutopicker(QWidget):
if hasattr(self, 'pdlg_widget'): if hasattr(self, 'pdlg_widget'):
if self.pdlg_widget: if self.pdlg_widget:
self.pdlg_widget.setParent(None) self.pdlg_widget.setParent(None)
del(self.pdlg_widget) del (self.pdlg_widget)
if hasattr(self, 'overview'): if hasattr(self, 'overview'):
self.overview.setParent(None) self.overview.setParent(None)
if hasattr(self, 'p_tabs'): if hasattr(self, 'p_tabs'):
@ -4725,8 +4722,9 @@ class FilterOptionsDialog(QDialog):
'S': FilterOptions()} 'S': FilterOptions()}
self.setWindowTitle(titleString) self.setWindowTitle(titleString)
self.filterOptionWidgets = {'P': FilterOptionsWidget(self.filterOptions['P'], self.parent().getAutoFilteroptions('P')), self.filterOptionWidgets = {
'S': FilterOptionsWidget(self.filterOptions['S'], self.parent().getAutoFilteroptions('S'))} 'P': FilterOptionsWidget(self.filterOptions['P'], self.parent().getAutoFilteroptions('P')),
'S': FilterOptionsWidget(self.filterOptions['S'], self.parent().getAutoFilteroptions('S'))}
self.setupUi() self.setupUi()
self.updateUi() self.updateUi()
self.connectButtons() self.connectButtons()
@ -5074,7 +5072,7 @@ class HelpForm(QDialog):
toolBar.addWidget(self.pageLabel) toolBar.addWidget(self.pageLabel)
self.webBrowser = QWebView() self.webBrowser = QWebView()
self.webBrowser.load(page) self.webBrowser.load(page)
#self.webBrowser.load('C:/Shared/code/git/pylot/pylot/core/util/map_test.html') # self.webBrowser.load('C:/Shared/code/git/pylot/pylot/core/util/map_test.html')
layout = QVBoxLayout() layout = QVBoxLayout()
layout.addWidget(toolBar) layout.addWidget(toolBar)

View File

@ -5,18 +5,18 @@
# the base color # the base color
phasecolors = { phasecolors = {
'manual': { 'manual': {
'P':{ 'P': {
'rgba': (0, 0, 255, 255), 'rgba': (0, 0, 255, 255),
'modifier': 'g'}, 'modifier': 'g'},
'S':{ 'S': {
'rgba': (255, 0, 0, 255), 'rgba': (255, 0, 0, 255),
'modifier': 'b'} 'modifier': 'b'}
}, },
'auto':{ 'auto': {
'P':{ 'P': {
'rgba': (140, 0, 255, 255), 'rgba': (140, 0, 255, 255),
'modifier': 'g'}, 'modifier': 'g'},
'S':{ 'S': {
'rgba': (255, 140, 0, 255), 'rgba': (255, 140, 0, 255),
'modifier': 'b'} 'modifier': 'b'}
} }
@ -24,8 +24,8 @@ phasecolors = {
# Set plot colors and stylesheet for each style # Set plot colors and stylesheet for each style
stylecolors = { stylecolors = {
'default':{ 'default': {
'linecolor':{ 'linecolor': {
'rgba': (0, 0, 0, 255)}, 'rgba': (0, 0, 0, 255)},
'background': { 'background': {
'rgba': (255, 255, 255, 255)}, 'rgba': (255, 255, 255, 255)},
@ -67,4 +67,3 @@ stylecolors = {
'filename': 'bright.qss'} 'filename': 'bright.qss'}
} }
} }

View File

@ -7,6 +7,7 @@ from obspy.io.xseed import Parser
from pylot.core.util.dataprocessing import Metadata from pylot.core.util.dataprocessing import Metadata
from tests.utils import HidePrints from tests.utils import HidePrints
class TestMetadata(unittest.TestCase): class TestMetadata(unittest.TestCase):
def setUp(self): def setUp(self):
@ -16,9 +17,12 @@ class TestMetadata(unittest.TestCase):
self.m = Metadata(metadata_folder) self.m = Metadata(metadata_folder)
def test_get_coordinates_sucess(self): def test_get_coordinates_sucess(self):
expected = {'Z': {u'elevation': 607.0, u'longitude': 12.87571, u'local_depth': 0.0, u'azimuth': 0.0, u'latitude': 49.14502, u'dip': -90.0}, expected = {'Z': {u'elevation': 607.0, u'longitude': 12.87571, u'local_depth': 0.0, u'azimuth': 0.0,
'E': {u'azimuth': 90.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502, u'local_depth': 0.0, u'longitude': 12.87571}, u'latitude': 49.14502, u'dip': -90.0},
'N': {u'azimuth': 0.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502, u'local_depth': 0.0, u'longitude': 12.87571} 'E': {u'azimuth': 90.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502,
u'local_depth': 0.0, u'longitude': 12.87571},
'N': {u'azimuth': 0.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502, u'local_depth': 0.0,
u'longitude': 12.87571}
} }
result = {} result = {}
for channel in ('Z', 'N', 'E'): for channel in ('Z', 'N', 'E'):
@ -28,9 +32,12 @@ class TestMetadata(unittest.TestCase):
self.assertDictEqual(result[channel], expected[channel]) self.assertDictEqual(result[channel], expected[channel])
def test_get_coordinates_sucess_no_time(self): def test_get_coordinates_sucess_no_time(self):
expected = {'Z': {u'elevation': 607.0, u'longitude': 12.87571, u'local_depth': 0.0, u'azimuth': 0.0, u'latitude': 49.14502, u'dip': -90.0}, expected = {'Z': {u'elevation': 607.0, u'longitude': 12.87571, u'local_depth': 0.0, u'azimuth': 0.0,
'E': {u'azimuth': 90.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502, u'local_depth': 0.0, u'longitude': 12.87571}, u'latitude': 49.14502, u'dip': -90.0},
'N': {u'azimuth': 0.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502, u'local_depth': 0.0, u'longitude': 12.87571} 'E': {u'azimuth': 90.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502,
u'local_depth': 0.0, u'longitude': 12.87571},
'N': {u'azimuth': 0.0, u'dip': 0.0, u'elevation': 607.0, u'latitude': 49.14502, u'local_depth': 0.0,
u'longitude': 12.87571}
} }
result = {} result = {}
for channel in ('Z', 'N', 'E'): for channel in ('Z', 'N', 'E'):
@ -63,8 +70,10 @@ class TestMetadataAdding(unittest.TestCase):
fpath = os.path.join(self.metadata_folders[0], 'DATALESS.BW.WETR..HHZ') fpath = os.path.join(self.metadata_folders[0], 'DATALESS.BW.WETR..HHZ')
self.m.add_inventory_file(fpath) self.m.add_inventory_file(fpath)
# adding an inventory file should append its folder to the list of inventories and the file to the # adding an inventory file should append its folder to the list of inventories and the file to the
self.assertEqual([os.path.join(self.metadata_folders[0], 'DATALESS.BW.WETR..HHZ')], self.m.inventory_files.keys()) # does the filename exist in inventory files? self.assertEqual([os.path.join(self.metadata_folders[0], 'DATALESS.BW.WETR..HHZ')],
self.assertEqual(['data', 'invtype'], self.m.inventory_files[os.path.join(self.metadata_folders[0], 'DATALESS.BW.WETR..HHZ')].keys()) # is the required information attacht to the filename? self.m.inventory_files.keys()) # does the filename exist in inventory files?
self.assertEqual(['data', 'invtype'], self.m.inventory_files[os.path.join(self.metadata_folders[0],
'DATALESS.BW.WETR..HHZ')].keys()) # is the required information attacht to the filename?
self.assertDictEqual({}, self.m.seed_ids) self.assertDictEqual({}, self.m.seed_ids)
self.assertEqual([self.metadata_folders[0]], self.m.inventories) self.assertEqual([self.metadata_folders[0]], self.m.inventories)