bugfix: correct erroneous and add new doctests

This commit is contained in:
Sebastian Wehling-Benatelli 2023-04-10 19:14:23 +02:00
parent efb117177c
commit e68fc849f0
5 changed files with 58 additions and 32 deletions

View File

@ -76,7 +76,7 @@ from pylot.core.util.utils import fnConstructor, getLogin, \
full_range, readFilterInformation, pick_color_plt, \ full_range, readFilterInformation, pick_color_plt, \
pick_linestyle_plt, identifyPhaseID, excludeQualityClasses, \ pick_linestyle_plt, identifyPhaseID, excludeQualityClasses, \
transform_colors_mpl, transform_colors_mpl_str, getAutoFilteroptions, check_all_obspy, \ transform_colors_mpl, transform_colors_mpl_str, getAutoFilteroptions, check_all_obspy, \
check_all_pylot, get_Bool, get_None check_all_pylot, get_bool, get_None
from pylot.core.util.gui import make_pen from pylot.core.util.gui import make_pen
from pylot.core.util.event import Event from pylot.core.util.event import Event
from pylot.core.io.location import create_creation_info, create_event from pylot.core.io.location import create_creation_info, create_event
@ -2271,7 +2271,7 @@ class MainWindow(QMainWindow):
# wfst += self.get_data().getWFData().select(component=alter_comp) # wfst += self.get_data().getWFData().select(component=alter_comp)
plotWidget = self.getPlotWidget() plotWidget = self.getPlotWidget()
self.adjustPlotHeight() self.adjustPlotHeight()
if get_Bool(settings.value('large_dataset')) == True: if get_bool(settings.value('large_dataset')) == True:
self.plot_method = 'fast' self.plot_method = 'fast'
else: else:
self.plot_method = 'normal' self.plot_method = 'normal'
@ -3712,7 +3712,7 @@ class MainWindow(QMainWindow):
filename = fnm[0] + '.plp' filename = fnm[0] + '.plp'
self.project.parameter = self._inputs self.project.parameter = self._inputs
settings = QSettings() settings = QSettings()
autosaveXML = get_Bool(settings.value('autosaveXML', True)) autosaveXML = get_bool(settings.value('autosaveXML', True))
if autosaveXML: if autosaveXML:
self.exportEvents() self.exportEvents()
if not self.project.save(filename): return False if not self.project.save(filename): return False
@ -3736,7 +3736,7 @@ class MainWindow(QMainWindow):
self.metadata.clear_inventory() self.metadata.clear_inventory()
self.project.parameter = self._inputs self.project.parameter = self._inputs
settings = QSettings() settings = QSettings()
autosaveXML = get_Bool(settings.value('autosaveXML', True)) autosaveXML = get_bool(settings.value('autosaveXML', True))
if autosaveXML: if autosaveXML:
self.exportEvents() self.exportEvents()
if not self.project.save(): return False if not self.project.save(): return False

View File

@ -22,7 +22,7 @@ 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, get_quality_class getSNR, fmpicker, checkPonsets, wadaticheck, get_quality_class
from pylot.core.util.utils import getPatternLine, gen_Pool, \ from pylot.core.util.utils import getPatternLine, gen_Pool, \
get_Bool, identifyPhaseID, get_None, correct_iplot get_bool, identifyPhaseID, get_None, correct_iplot
def autopickevent(data, param, iplot=0, fig_dict=None, fig_dict_wadatijack=None, ncores=0, metadata=None, origin=None): def autopickevent(data, param, iplot=0, fig_dict=None, fig_dict_wadatijack=None, ncores=0, metadata=None, origin=None):
@ -477,7 +477,7 @@ class AutopickStation(object):
if self.pickparams["sstart"] < 0: if self.pickparams["sstart"] < 0:
self.pickparams["sstart"] = 0 self.pickparams["sstart"] = 0
if get_Bool(self.pickparams["use_taup"]) is False: if get_bool(self.pickparams["use_taup"]) is False:
# correct user mistake where a relative cuttime is selected (pstart < 0) but use of taupy is disabled/ has # correct user mistake where a relative cuttime is selected (pstart < 0) but use of taupy is disabled/ has
# not the required parameters # not the required parameters
exit_taupy() exit_taupy()
@ -525,7 +525,7 @@ class AutopickStation(object):
:rtype: dict :rtype: dict
""" """
if get_Bool(self.pickparams['use_taup']) is True and self.origin is not None: if get_bool(self.pickparams['use_taup']) is True and self.origin is not None:
try: try:
# modify pstart, pstop, sstart, sstop to be around theoretical onset if taupy should be used, # modify pstart, pstop, sstart, sstop to be around theoretical onset if taupy should be used,
# else do nothing # else do nothing
@ -544,7 +544,7 @@ class AutopickStation(object):
if self.horizontal_traces_exist(): if self.horizontal_traces_exist():
if (self.p_results.weight is not None and self.p_results.weight < 4) or \ if (self.p_results.weight is not None and self.p_results.weight < 4) or \
get_Bool(self.pickparams.get('use_taup')): get_bool(self.pickparams.get('use_taup')):
try: try:
self.pick_s_phase() self.pick_s_phase()
except MissingTraceException as mte: except MissingTraceException as mte:
@ -1148,7 +1148,7 @@ class AutopickStation(object):
''.format(self.s_results.weight, self.s_results.snr, self.s_results.snrdb)) ''.format(self.s_results.weight, self.s_results.snr, self.s_results.snrdb))
def pick_s_phase(self): def pick_s_phase(self):
if get_Bool(self.pickparams.get('use_taup')) is True: if get_bool(self.pickparams.get('use_taup')) is True:
cuttimesh = (self.pickparams.get('sstart'), self.pickparams.get('sstop')) cuttimesh = (self.pickparams.get('sstart'), self.pickparams.get('sstop'))
else: else:
# determine time window for calculating CF after P onset # determine time window for calculating CF after P onset

View File

@ -15,7 +15,7 @@ import numpy as np
from obspy.core import Stream, UTCDateTime from obspy.core import Stream, UTCDateTime
from scipy.signal import argrelmax from scipy.signal import argrelmax
from pylot.core.util.utils import get_Bool, get_None, SetChannelComponents from pylot.core.util.utils import get_bool, get_None, SetChannelComponents
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'):
@ -63,7 +63,7 @@ def earllatepicker(X, nfac, TSNR, Pick1, iplot=0, verbosity=1, fig=None, linecol
try: try:
iplot = int(iplot) iplot = int(iplot)
except: except:
if get_Bool(iplot): if get_bool(iplot):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
@ -816,7 +816,7 @@ def checksignallength(X, pick, minsiglength, pickparams, iplot=0, fig=None, line
try: try:
iplot = int(iplot) iplot = int(iplot)
except: except:
if get_Bool(iplot): if get_bool(iplot):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
@ -1130,7 +1130,7 @@ def checkZ4S(X, pick, pickparams, iplot, fig=None, linecolor='k'):
try: try:
iplot = int(iplot) iplot = int(iplot)
except: except:
if get_Bool(iplot): if get_bool(iplot):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
@ -1499,7 +1499,7 @@ def get_pickparams(pickparam):
first_motion_params = dict(zip(first_motion_names, fm_parameter_values)) first_motion_params = dict(zip(first_motion_names, fm_parameter_values))
signal_length_params = dict(zip(signal_length_names, sl_parameter_values)) signal_length_params = dict(zip(signal_length_names, sl_parameter_values))
p_params['use_taup'] = get_Bool(p_params['use_taup']) p_params['use_taup'] = get_bool(p_params['use_taup'])
return p_params, s_params, first_motion_params, signal_length_params return p_params, s_params, first_motion_params, signal_length_params

View File

@ -327,20 +327,41 @@ def get_None(value):
return value return value
def get_Bool(value): def get_bool(value):
""" """
Convert string representations of bools to their true boolean value Convert string representations of bools to their true boolean value
:param value: :param value:
:type value: str, bool :type value: str, bool, int, float
:return: true boolean value :return: true boolean value
:rtype: bool :rtype: bool
>>> get_bool(True)
True
>>> get_bool(False)
False
>>> get_bool(0)
False
>>> get_bool(0.)
False
>>> get_bool(0.1)
True
>>> get_bool(2)
True
>>> get_bool(-1)
False
>>> get_bool(-0.3)
False
""" """
if value in ['True', 'true']: if type(value) == bool:
return value
elif value in ['True', 'true']:
return True return True
elif value in ['False', 'false']: elif value in ['False', 'false']:
return False return False
elif value > 0. or value > 0:
return True
else: else:
return value return False
def four_digits(year): def four_digits(year):
@ -352,8 +373,8 @@ def four_digits(year):
:return: four digit year correspondent :return: four digit year correspondent
:rtype: int :rtype: int
>>> four_digits(20) >>> four_digits(75)
1920 1975
>>> four_digits(16) >>> four_digits(16)
2016 2016
>>> four_digits(00) >>> four_digits(00)
@ -510,6 +531,11 @@ def is_executable(fn):
:param fn: path to the file to be tested :param fn: path to the file to be tested
:return: True or False :return: True or False
:rtype: bool :rtype: bool
>>> is_executable('/bin/ls')
True
>>> is_executable('/var/log/system.log')
False
""" """
return os.path.isfile(fn) and os.access(fn, os.X_OK) return os.path.isfile(fn) and os.access(fn, os.X_OK)
@ -616,13 +642,13 @@ def find_horizontals(data):
:param data: waveform data :param data: waveform data
:type data: `obspy.core.stream.Stream` :type data: `obspy.core.stream.Stream`
:return: components list :return: components list
:rtype: list :rtype: List(str)
..example:: ..example::
>>> st = read() >>> st = read()
>>> find_horizontals(st) >>> find_horizontals(st)
[u'N', u'E'] ['N', 'E']
""" """
rval = [] rval = []
for tr in data: for tr in data:
@ -897,11 +923,11 @@ def check4doubled(data):
def get_stations(data): def get_stations(data):
""" """
Get list of all station names in data stream Get list of all station names in data-stream
:param data: stream containing seismic traces :param data: stream containing seismic traces
:type data: `~obspy.core.stream.Stream` :type data: `~obspy.core.stream.Stream`
:return: list of all station names in data, no duplicates :return: list of all station names in data, no duplicates
:rtype: list of str :rtype: List(str)
""" """
stations = [] stations = []
for tr in data: for tr in data:
@ -957,7 +983,7 @@ def check4rotated(data, metadata=None, verbosity=1):
if len(wfs_in) < 3: if len(wfs_in) < 3:
print(f"Stream {wfs_in=}, has not enough components to rotate.") print(f"Stream {wfs_in=}, has not enough components to rotate.")
return wfs_in return wfs_in
# check if any traces in this station need to be rotated # check if any traces in this station need to be rotated
trace_ids = [trace.id for trace in wfs_in] trace_ids = [trace.id for trace in wfs_in]
if not rotation_required(trace_ids): if not rotation_required(trace_ids):
@ -1188,7 +1214,7 @@ def correct_iplot(iplot):
try: try:
iplot = int(iplot) iplot = int(iplot)
except ValueError: except ValueError:
if get_Bool(iplot): if get_bool(iplot):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0

View File

@ -53,7 +53,7 @@ from pylot.core.util.utils import prepTimeAxis, full_range, demeanTrace, isSorte
pick_linestyle_plt, pick_color_plt, \ pick_linestyle_plt, pick_color_plt, \
check4rotated, check4doubled, merge_stream, identifyPhase, \ check4rotated, check4doubled, merge_stream, identifyPhase, \
loopIdentifyPhase, trim_station_components, transformFilteroptions2String, \ loopIdentifyPhase, trim_station_components, transformFilteroptions2String, \
identifyPhaseID, get_Bool, get_None, pick_color, getAutoFilteroptions, SetChannelComponents, \ identifyPhaseID, get_bool, get_None, pick_color, getAutoFilteroptions, SetChannelComponents, \
station_id_remove_channel station_id_remove_channel
from autoPyLoT import autoPyLoT from autoPyLoT import autoPyLoT
from pylot.core.util.thread import Thread from pylot.core.util.thread import Thread
@ -1876,7 +1876,7 @@ class PickDlg(QDialog):
self.sChannels.triggered.connect(self.updateChannelSettingsS) self.sChannels.triggered.connect(self.updateChannelSettingsS)
settings = QSettings() settings = QSettings()
self.autoFilterAction.setChecked(get_Bool(settings.value('autoFilter'))) self.autoFilterAction.setChecked(get_bool(settings.value('autoFilter')))
# create other widget elements # create other widget elements
phaseitems = [None] + list(FILTERDEFAULTS.keys()) phaseitems = [None] + list(FILTERDEFAULTS.keys())
@ -2355,7 +2355,7 @@ class PickDlg(QDialog):
settings = QSettings() settings = QSettings()
phaseID = self.getPhaseID(phase) phaseID = self.getPhaseID(phase)
if get_Bool(settings.value('useGuiFilter')) or gui_filter: if get_bool(settings.value('useGuiFilter')) or gui_filter:
filteroptions = self.filteroptions[phaseID] filteroptions = self.filteroptions[phaseID]
else: else:
filteroptions = getAutoFilteroptions(phaseID, self.parameter) filteroptions = getAutoFilteroptions(phaseID, self.parameter)
@ -3025,7 +3025,7 @@ class PickDlg(QDialog):
@staticmethod @staticmethod
def getChannelSettingsP(channel): def getChannelSettingsP(channel):
settings = QSettings() settings = QSettings()
rval = get_Bool(settings.value('p_channel_{}'.format(channel))) rval = get_bool(settings.value('p_channel_{}'.format(channel)))
compclass = SetChannelComponents.from_qsettings(settings) compclass = SetChannelComponents.from_qsettings(settings)
components = ['Z'] components = ['Z']
for component in components[:]: for component in components[:]:
@ -3040,7 +3040,7 @@ class PickDlg(QDialog):
@staticmethod @staticmethod
def getChannelSettingsS(channel): def getChannelSettingsS(channel):
settings = QSettings() settings = QSettings()
rval = get_Bool(settings.value('s_channel_{}'.format(channel))) rval = get_bool(settings.value('s_channel_{}'.format(channel)))
compclass = SetChannelComponents.from_qsettings(settings) compclass = SetChannelComponents.from_qsettings(settings)
components = ['N', 'E'] components = ['N', 'E']
for component in components[:]: for component in components[:]:
@ -5194,7 +5194,7 @@ class FilterOptionsDialog(QDialog):
'S': QtWidgets.QGroupBox('S Filter')} 'S': QtWidgets.QGroupBox('S Filter')}
settings = QSettings() settings = QSettings()
overwriteFilter = get_Bool(settings.value('useGuiFilter')) overwriteFilter = get_bool(settings.value('useGuiFilter'))
self.overwriteFilterCheckbox = QCheckBox('Overwrite filteroptions') self.overwriteFilterCheckbox = QCheckBox('Overwrite filteroptions')
self.overwriteFilterCheckbox.setToolTip('Overwrite filter settings for refined pick with GUI settings') self.overwriteFilterCheckbox.setToolTip('Overwrite filter settings for refined pick with GUI settings')