[clean-up] some code cosmetics and started to implement eventinformation

This commit is contained in:
Sebastian Wehling-Benatelli 2016-09-02 14:21:59 +02:00
parent f1d806c154
commit 76a856aa11
3 changed files with 94 additions and 57 deletions

View File

@ -150,7 +150,7 @@ class MainWindow(QMainWindow):
self.DataPlot.mpl_connect('button_press_event', self.DataPlot.mpl_connect('button_press_event',
self.pickOnStation) self.pickOnStation)
self.DataPlot.mpl_connect('axes_enter_event', self.DataPlot.mpl_connect('axes_enter_event',
lambda event: self.tutorUser()) lambda event: self.tutor_user())
_layout.addWidget(self.DataPlot) _layout.addWidget(self.DataPlot)
manupicksicon = self.style().standardIcon(QStyle.SP_DialogYesButton) manupicksicon = self.style().standardIcon(QStyle.SP_DialogYesButton)
@ -256,7 +256,7 @@ class MainWindow(QMainWindow):
"automatic pick " "automatic pick "
"data.", False) "data.", False)
printAction = self.createAction(self, "&Print event ...", printAction = self.createAction(self, "&Print event ...",
self.printEvent, QKeySequence.Print, self.show_event_information, QKeySequence.Print,
print_icon, print_icon,
"Print waveform overview.") "Print waveform overview.")
helpAction = self.createAction(self, "&Help ...", self.helpHelp, helpAction = self.createAction(self, "&Help ...", self.helpHelp,
@ -448,7 +448,7 @@ class MainWindow(QMainWindow):
def getWFFnames(self): def getWFFnames(self):
try: try:
evt = self.getData().getEvtData() evt = self.get_data().get_evt_data()
if evt.picks: if evt.picks:
for pick in evt.picks: for pick in evt.picks:
try: try:
@ -503,7 +503,7 @@ class MainWindow(QMainWindow):
def getEventFileName(self): def getEventFileName(self):
if self.get_fnames() is None: if self.get_fnames() is None:
self.set_fname(self.getData().getEventFileName()) self.set_fname(self.get_data().getEventFileName())
return self.get_fnames() return self.get_fnames()
def saveData(self): def saveData(self):
@ -530,32 +530,32 @@ class MainWindow(QMainWindow):
fbasename = self.getEventFileName() fbasename = self.getEventFileName()
exform = settings.value('data/exportFormat', 'QUAKEML') exform = settings.value('data/exportFormat', 'QUAKEML')
try: try:
self.getData().applyEVTData(self.getPicks()) self.get_data().applyEVTData(self.getPicks())
except OverwriteError: except OverwriteError:
msgBox = QMessageBox() msgBox = QMessageBox()
msgBox.setText("Picks have been modified!") msgBox.setText("Picks have been modified!")
msgBox.setInformativeText( msgBox.setInformativeText(
"Do you want to save the changes and overwrite the picks?") "Do you want to save the changes and overwrite the picks?")
msgBox.setDetailedText(self.getData().getPicksStr()) msgBox.setDetailedText(self.get_data().getPicksStr())
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel) msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save) msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_() ret = msgBox.exec_()
if ret == QMessageBox.Save: if ret == QMessageBox.Save:
self.getData().resetPicks() self.get_data().resetPicks()
return self.saveData() return self.saveData()
elif ret == QMessageBox.Cancel: elif ret == QMessageBox.Cancel:
return False return False
try: try:
self.getData().exportEvent(fbasename, exform) self.get_data().exportEvent(fbasename, exform)
except FormatError as e: except FormatError as e:
fbasename, exform = getSavePath(e) fbasename, exform = getSavePath(e)
except AttributeError as e: except AttributeError as e:
fbasename, exform = getSavePath(e) fbasename, exform = getSavePath(e)
if not fbasename: if not fbasename:
return False return False
self.getData().exportEvent(fbasename, exform) self.get_data().exportEvent(fbasename, exform)
self.setDirty(False) self.setDirty(False)
self.updateStatus('Event saved as %s' % (fbasename + exform)) self.update_status('Event saved as %s' % (fbasename + exform))
return True return True
def getComponent(self): def getComponent(self):
@ -564,7 +564,7 @@ class MainWindow(QMainWindow):
def setComponent(self, component): def setComponent(self, component):
self.dispComponent = component self.dispComponent = component
def getData(self, type='manual'): def get_data(self, type='manual'):
if type == 'auto': if type == 'auto':
return self.autodata return self.autodata
return self.data return self.data
@ -633,7 +633,7 @@ class MainWindow(QMainWindow):
ans = self.data.setWFData(self.getWFFnames()) ans = self.data.setWFData(self.getWFFnames())
else: else:
ans = False ans = False
self._stime = getGlobalTimes(self.getData().getWFData())[0] self._stime = getGlobalTimes(self.get_data().getWFData())[0]
if ans: if ans:
self.plotWaveformData() self.plotWaveformData()
return ans return ans
@ -645,8 +645,8 @@ class MainWindow(QMainWindow):
comp = self.getComponent() comp = self.getComponent()
title = 'section: {0} components'.format(zne_text[comp]) title = 'section: {0} components'.format(zne_text[comp])
alter_comp = COMPNAME_MAP[comp] alter_comp = COMPNAME_MAP[comp]
wfst = self.getData().getWFData().select(component=comp) wfst = self.get_data().getWFData().select(component=comp)
wfst += self.getData().getWFData().select(component=alter_comp) wfst += self.get_data().getWFData().select(component=alter_comp)
self.getPlotWidget().plotWFData(wfdata=wfst, title=title, mapping=False) self.getPlotWidget().plotWFData(wfdata=wfst, title=title, mapping=False)
self.draw() self.draw()
plotDict = self.getPlotWidget().getPlotDict() plotDict = self.getPlotWidget().getPlotDict()
@ -673,17 +673,17 @@ class MainWindow(QMainWindow):
self.draw() self.draw()
def pushFilterWF(self, param_args): def pushFilterWF(self, param_args):
self.getData().filterWFData(param_args) self.get_data().filterWFData(param_args)
def filterWaveformData(self): def filterWaveformData(self):
if self.getData(): if self.get_data():
if self.getFilterOptions() and self.filterAction.isChecked(): if self.getFilterOptions() and self.filterAction.isChecked():
kwargs = self.getFilterOptions().parseFilterOptions() kwargs = self.getFilterOptions().parseFilterOptions()
self.pushFilterWF(kwargs) self.pushFilterWF(kwargs)
elif self.filterAction.isChecked(): elif self.filterAction.isChecked():
self.adjustFilterOptions() self.adjustFilterOptions()
else: else:
self.getData().resetWFData() self.get_data().resetWFData()
self.plotWaveformData() self.plotWaveformData()
self.drawPicks() self.drawPicks()
self.draw() self.draw()
@ -727,11 +727,11 @@ class MainWindow(QMainWindow):
for key, value in settings.value("filterdefaults"): for key, value in settings.value("filterdefaults"):
self.setFilterOptions(FilterOptions(**value), key) self.setFilterOptions(FilterOptions(**value), key)
except Exception as e: except Exception as e:
self.updateStatus('Error ...') self.update_status('Error ...')
emsg = QErrorMessage(self) emsg = QErrorMessage(self)
emsg.showMessage('Error: {0}'.format(e)) emsg.showMessage('Error: {0}'.format(e))
else: else:
self.updateStatus('Filter loaded ... ' self.update_status('Filter loaded ... '
'[{0}: {1} Hz]'.format( '[{0}: {1} Hz]'.format(
self.getFilterOptions().getFilterType(), self.getFilterOptions().getFilterType(),
self.getFilterOptions().getFreq())) self.getFilterOptions().getFreq()))
@ -749,7 +749,7 @@ class MainWindow(QMainWindow):
def setSeismicPhase(self, phase): def setSeismicPhase(self, phase):
self.seismicPhase = self.seismicPhaseButtonGroup.getValue() self.seismicPhase = self.seismicPhaseButtonGroup.getValue()
self.updateStatus('Seismic phase changed to ' self.update_status('Seismic phase changed to '
'{0}'.format(self.getSeismicPhase())) '{0}'.format(self.getSeismicPhase()))
def pickOnStation(self, gui_event): def pickOnStation(self, gui_event):
@ -759,14 +759,14 @@ class MainWindow(QMainWindow):
if wfID is None: return if wfID is None: return
station = self.getStationName(wfID) station = self.getStationName(wfID)
self.updateStatus('picking on station {0}'.format(station)) self.update_status('picking on station {0}'.format(station))
data = self.getData().getWFData() data = self.get_data().getWFData()
pickDlg = PickDlg(self, data=data.select(station=station), pickDlg = PickDlg(self, data=data.select(station=station),
station=station, station=station,
picks=self.getPicksOnStation(station)) picks=self.getPicksOnStation(station))
if pickDlg.exec_(): if pickDlg.exec_():
self.setDirty(True) self.setDirty(True)
self.updateStatus('picks accepted ({0})'.format(station)) self.update_status('picks accepted ({0})'.format(station))
replot = self.addPicks(station, pickDlg.getPicks()) replot = self.addPicks(station, pickDlg.getPicks())
if replot: if replot:
self.plotWaveformData() self.plotWaveformData()
@ -776,11 +776,11 @@ class MainWindow(QMainWindow):
self.drawPicks(station) self.drawPicks(station)
self.draw() self.draw()
else: else:
self.updateStatus('picks discarded ({0})'.format(station)) self.update_status('picks discarded ({0})'.format(station))
if not self.getLocflag() and self.check4Loc(): if not self.get_loc_flag() and self.check4Loc():
self.setLocflag(True) self.set_loc_flag(True)
elif self.getLocflag() and not self.check4Loc(): elif self.get_loc_flag() and not self.check4Loc():
self.setLocflag(False) self.set_loc_flag(False)
def addListItem(self, text): def addListItem(self, text):
self.listWidget.addItem(text) self.listWidget.addItem(text)
@ -802,7 +802,7 @@ class MainWindow(QMainWindow):
# Create the worker thread and run it # Create the worker thread and run it
self.thread = AutoPickThread(parent=self, self.thread = AutoPickThread(parent=self,
func=autopickevent, func=autopickevent,
data=self.getData().getWFData(), data=self.get_data().getWFData(),
param=autopick_parameter) param=autopick_parameter)
self.thread.message.connect(self.addListItem) self.thread.message.connect(self.addListItem)
self.thread.start() self.thread.start()
@ -842,7 +842,7 @@ class MainWindow(QMainWindow):
return rval return rval
def updatePicks(self, type='manual'): def updatePicks(self, type='manual'):
picks = picksdict_from_picks(evt=self.getData(type).getEvtData()) picks = picksdict_from_picks(evt=self.get_data(type).get_evt_data())
if type == 'manual': if type == 'manual':
self.picks.update(picks) self.picks.update(picks)
elif type == 'auto': elif type == 'auto':
@ -944,7 +944,38 @@ class MainWindow(QMainWindow):
finally: finally:
os.remove(phasepath) os.remove(phasepath)
self.getData().applyEVTData(lt.read_location(locpath), type='event') self.get_data().applyEVTData(lt.read_location(locpath), type='event')
self.get_data().get_evt_data().magnitudes.append(self.calc_magnitude())
def calc_magnitude(self):
e = self.get_data().get_evt_data()
settings = QSettings()
if e.origins:
o = e.origins[0]
mags = dict()
for a in o.arrivals:
pick = a.pick_id.get_referred_object()
station = pick.waveform_id.station_code
wf = self.get_data().getWFData().select(station=station)
onset = pick.time
fninv = settings.value("inventoryFile", None)
if fninv is None:
fninv = QFileDialog.getOpenFileName()
ans = QMessageBox.question(self, self.tr("Make default..."),
self.tr("New inventory filename set.\n" + \
"Do you want to make it the default value?"),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if ans == QMessageBox.Yes:
settings.setValue("inventoryFile", fninv)
settings.sync()
w0, fc = calcsourcespec(wf, onset, fninv, 3000., a.distance, a.azimuth, a.takeoff_angle, 60., 0)
stat_mags = calcMoMw(wf, w0, 2700., 3000., a.distance, fninv)
mags[station] = stat_mags
mag = np.median([M[1] for M in mags.values()])
return Magnitude(mag=mag, magnitude_type='Mw')
else:
return None
def check4Loc(self): def check4Loc(self):
return self.picksNum() > 4 return self.picksNum() > 4
@ -968,29 +999,35 @@ class MainWindow(QMainWindow):
num += len(phases) num += len(phases)
return num return num
def getLocflag(self): def get_loc_flag(self):
return self.loc return self.loc
def setLocflag(self, value): def set_loc_flag(self, value):
self.loc = value self.loc = value
def updateStatus(self, message, duration=5000): def check_loc_plt(self):
evt = self.get_data().get_evt_data()
if evt.origins and evt.magnitudes:
return True
return False
def update_status(self, message, duration=5000):
self.statusBar().showMessage(message, duration) self.statusBar().showMessage(message, duration)
if self.getData() is not None: if self.get_data() is not None:
if not self.getData().isNew(): if not self.get_data().isNew():
self.setWindowTitle( self.setWindowTitle(
"PyLoT - processing event %s[*]" % self.getData().getID()) "PyLoT - processing event %s[*]" % self.get_data().getID())
elif self.getData().isNew(): elif self.get_data().isNew():
self.setWindowTitle("PyLoT - New event [*]") self.setWindowTitle("PyLoT - New event [*]")
else: else:
self.setWindowTitle( self.setWindowTitle(
"PyLoT - seismic processing the python way[*]") "PyLoT - seismic processing the python way[*]")
self.setWindowModified(self.dirty) self.setWindowModified(self.dirty)
def tutorUser(self): def tutor_user(self):
self.updateStatus('select trace to pick on station ...', 10000) self.update_status('select trace to pick on station ...', 10000)
def printEvent(self): def show_event_information(self):
pass pass
def createNewEvent(self): def createNewEvent(self):

View File

@ -77,17 +77,17 @@ class Data(object):
def __add__(self, other): def __add__(self, other):
assert isinstance(other, Data), "operands must be of same type 'Data'" assert isinstance(other, Data), "operands must be of same type 'Data'"
if other.isNew() and not self.isNew(): if other.isNew() and not self.isNew():
picks_to_add = other.getEvtData().picks picks_to_add = other.get_evt_data().picks
old_picks = self.getEvtData().picks old_picks = self.get_evt_data().picks
for pick in picks_to_add: for pick in picks_to_add:
if pick not in old_picks: if pick not in old_picks:
old_picks.append(pick) old_picks.append(pick)
elif not other.isNew() and self.isNew(): elif not other.isNew() and self.isNew():
new = other + self new = other + self
self.evtdata = new.getEvtData() self.evtdata = new.get_evt_data()
elif self.isNew() and other.isNew(): elif self.isNew() and other.isNew():
pass pass
elif self.getEvtData().get('id') == other.getEvtData().get('id'): elif self.get_evt_data().get('id') == other.get_evt_data().get('id'):
other.setNew() other.setNew()
return self + other return self + other
else: else:
@ -97,7 +97,7 @@ class Data(object):
def getPicksStr(self): def getPicksStr(self):
picks_str = '' picks_str = ''
for pick in self.getEvtData().picks: for pick in self.get_evt_data().picks:
picks_str += str(pick) + '\n' picks_str += str(pick) + '\n'
return picks_str return picks_str
@ -166,7 +166,7 @@ class Data(object):
# try exporting event via ObsPy # try exporting event via ObsPy
try: try:
self.getEvtData().write(fnout + fnext, format=evtformat) self.get_evt_data().write(fnout + fnext, format=evtformat)
except KeyError as e: except KeyError as e:
raise KeyError('''{0} export format raise KeyError('''{0} export format
not implemented: {1}'''.format(evtformat, e)) not implemented: {1}'''.format(evtformat, e))
@ -267,7 +267,7 @@ class Data(object):
""" """
self.getEvtData().picks = [] self.get_evt_data().picks = []
def restituteWFData(self, invdlpath, streams=None): def restituteWFData(self, invdlpath, streams=None):
""" """
@ -402,7 +402,7 @@ class Data(object):
return st, restflag return st, restflag
def getEvtData(self): def get_evt_data(self):
""" """
@ -433,16 +433,16 @@ class Data(object):
""" """
#firstonset = find_firstonset(picks) #firstonset = find_firstonset(picks)
if self.getEvtData().picks: if self.get_evt_data().picks:
raise OverwriteError('Actual picks would be overwritten!') raise OverwriteError('Actual picks would be overwritten!')
else: else:
picks = picks_from_picksdict(picks) picks = picks_from_picksdict(picks)
self.getEvtData().picks = picks self.get_evt_data().picks = picks
# if 'smi:local' in self.getID() and firstonset: # if 'smi:local' in self.getID() and firstonset:
# fonset_str = firstonset.strftime('%Y_%m_%d_%H_%M_%S') # fonset_str = firstonset.strftime('%Y_%m_%d_%H_%M_%S')
# ID = ResourceIdentifier('event/' + fonset_str) # ID = ResourceIdentifier('event/' + fonset_str)
# ID.convertIDToQuakeMLURI(authority_id=authority_id) # ID.convertIDToQuakeMLURI(authority_id=authority_id)
# self.getEvtData().resource_id = ID # self.get_evt_data().resource_id = ID
def applyEvent(event): def applyEvent(event):
@ -454,11 +454,11 @@ class Data(object):
if not self.isNew(): if not self.isNew():
self.setEvtData(event) self.setEvtData(event)
else: else:
# prevent overwriting uncertainty information # prevent overwriting original pick information
picks = copy.deepcopy(self.getEvtData().picks) picks = copy.deepcopy(self.get_evt_data().picks)
event.picks = picks event = merge_picks(event, picks)
# apply event information from location # apply event information from location
self.getEvtData().update(event) self.get_evt_data().update(event)
applydata = {'pick': applyPicks, applydata = {'pick': applyPicks,
'event': applyEvent} 'event': applyEvent}

View File

@ -530,7 +530,7 @@ class PickDlg(QDialog):
# set attribute holding data # set attribute holding data
if data is None: if data is None:
try: try:
data = parent.getData().getWFData().copy() data = parent.get_data().getWFData().copy()
self.data = data.select(station=station) self.data = data.select(station=station)
except AttributeError as e: except AttributeError as e:
errmsg = 'You either have to put in a data or an appropriate ' \ errmsg = 'You either have to put in a data or an appropriate ' \