3.7. quakemigrate.util

Module that supplies various utility functions and classes.

copyright

2020–2023, QuakeMigrate developers.

license

GNU General Public License, Version 3 (https://www.gnu.org/licenses/gpl-3.0.html)

exception quakemigrate.util.ArchiveEmptyException[source]

Bases: Exception

Custom exception to handle empty archive.

exception quakemigrate.util.ArchiveFormatException[source]

Bases: Exception

Custom exception to handle case where Archive.format is not set.

exception quakemigrate.util.ArchivePathStructureError(archive_format)[source]

Bases: Exception

Custom exception to handle case where an invalid Archive path structure is selected.

exception quakemigrate.util.BadUpfactorException(trace)[source]

Bases: Exception

Custom exception to handle case when the chosen upfactor does not create a trace with a sampling rate that can be decimated to the target sampling rate.

exception quakemigrate.util.ChannelNameException(trace)[source]

Bases: Exception

Custom exception to handle case when waveform data header has channel names which do not conform to the IRIS SEED standard.

exception quakemigrate.util.DataAvailabilityException[source]

Bases: Exception

Custom exception to handle case when all data for the selected stations did not pass the data quality criteria specified by the user.

exception quakemigrate.util.DataGapException[source]

Bases: Exception

Custom exception to handle case when no data is found for the selected stations for a given timestep.

class quakemigrate.util.DateFormatter(fmt, precision=3)[source]

Bases: Formatter

Extend the matplotlib.ticker.Formatter class to allow for millisecond precision when formatting a tick (in days since the epoch) with a datetime.datetime.strftime format string.

Parameters
  • fmt (str) – datetime.datetime.strftime format string.

  • precision (int) – Degree of precision to which to report sub-second time intervals.

exception quakemigrate.util.InvalidPickThresholdMethodException[source]

Bases: Exception

Custom exception to handle case when the user has not selected a valid pick threshold method.

exception quakemigrate.util.InvalidTriggerThresholdMethodException[source]

Bases: Exception

Custom exception to handle case when the user has not selected a valid trigger threshold method.

exception quakemigrate.util.InvalidVelocityModelHeader(key)[source]

Bases: Exception

Custom exception to handle incorrect header columns in station file.

exception quakemigrate.util.LUTPhasesException(message)[source]

Bases: Exception

Custom exception to handle the case when the look-up table does not contain the traveltimes for the phases necessary for a given function.

exception quakemigrate.util.MagsTypeError[source]

Bases: Exception

Custom exception to handle case when an object has been provided to calculate magnitudes during locate, but it isn’t supported.

exception quakemigrate.util.NoOnsetPeak(pick_threshold)[source]

Bases: Exception

Custom exception to handle case when no values in the onset function exceed the threshold used for picking.

exception quakemigrate.util.NoScanMseedDataException[source]

Bases: Exception

Custom exception to handle case when no .scanmseed files can be found by read_coastream().

exception quakemigrate.util.NoStationAvailabilityDataException[source]

Bases: Exception

Custom exception to handle case when no .StationAvailability files can be found by read_availability().

exception quakemigrate.util.NoTriggerFilesFound[source]

Bases: Exception

Custom exception to handle case when no trigger files are found during locate. This can occur for one of two reasons - an entirely invalid time period was used (i.e. one that does not overlap at all with a period of time for which there exists TriggeredEvents.csv files) or an invalid run name was provided.

exception quakemigrate.util.NyquistException(freqmax, f_nyquist, tr_id)[source]

Bases: Exception

Custom exception to handle the case where the specified filter has a lowpass corner above the signal Nyquist frequency.

Parameters
  • freqmax (float) – Specified lowpass frequency for filter.

  • f_nyquist (float) – Nyquist frequency for the relevant waveform data.

  • tr_id (str) – ID string for the Trace.

exception quakemigrate.util.OnsetTypeError[source]

Bases: Exception

Custom exception to handle case when the onset object passed to QuakeScan is not of the default type defined in QuakeMigrate.

exception quakemigrate.util.PeakToTroughError(err)[source]

Bases: Exception

Custom exception to handle case when amplitude._peak_to_trough_amplitude encounters an anomalous set of peaks and troughs, so can’t calculate an amplitude.

exception quakemigrate.util.PickOrderException(event_uid, station, p_pick, s_pick)[source]

Bases: Exception

Custom exception to handle the case when the pick for the P phase is later than the pick for the S phase.

exception quakemigrate.util.PickerTypeError[source]

Bases: Exception

Custom exception to handle case when the phase picker object passed to QuakeScan is not of the default type defined in QuakeMigrate.

exception quakemigrate.util.ResponseNotFoundError(e, tr_id)[source]

Bases: Exception

Custom exception to handle the case where the provided response inventory doesn’t contain the response information for a trace.

Parameters
  • e (str) – Error message from ObsPy Inventory.get_response().

  • tr_id (str) – ID string for the Trace for which the response cannot be found.

exception quakemigrate.util.ResponseRemovalError(e, tr_id)[source]

Bases: Exception

Custom exception to handle the case where the response removal was not successful.

Parameters
  • e (str) – Error message from ObsPy Trace.remove_response() or Trace.simulate().

  • tr_id (str) – ID string for the Trace for which the response cannot be removed.

exception quakemigrate.util.StationFileHeaderException[source]

Bases: Exception

Custom exception to handle incorrect header columns in station file.

exception quakemigrate.util.TimeSpanException[source]

Bases: Exception

Custom exception to handle case when the user has submitted a start time that is after the end time.

quakemigrate.util.calculate_mad(x, scale=1.4826)[source]

Calculates the Median Absolute Deviation (MAD) of the input array x.

Parameters
  • x (array-like) – Input data.

  • scale (float, optional) – A scaling factor for the MAD output to make the calculated MAD factor a consistent estimation of the standard deviation of the distribution.

Returns

scaled_mad – Array of scaled mean absolute deviation values for the input array, x, scaled to provide an estimation of the standard deviation of the distribution.

Return type

array-like

quakemigrate.util.decimate(trace, sampling_rate)[source]

Decimate a trace to achieve the desired sampling rate, sr.

NOTE: data will be detrended and a cosine taper applied before decimation, in order to avoid edge effects when applying the lowpass filter before decimating.

3.7. Parameters:

traceobspy.Trace object

Trace to be decimated.

sampling_rateint

Output sampling rate.

3.7. Returns:

traceobspy.Trace object

Decimated trace.

quakemigrate.util.gaussian_1d(x, a, b, c)[source]

Create a 1-dimensional Gaussian function.

Parameters
  • x (array-like) – Array of x values.

  • a (float / int) – Amplitude (height of Gaussian).

  • b (float / int) – Mean (centre of Gaussian).

  • c (float / int) – Sigma (width of Gaussian).

Returns

f – 1-dimensional Gaussian function

Return type

function

quakemigrate.util.gaussian_3d(nx, ny, nz, sgm)[source]

Create a 3-dimensional Gaussian function.

Parameters
  • nx (array-like) – Array of x values.

  • ny (array-like) – Array of y values.

  • nz (array-like) – Array of z values.

  • sgm (float / int) – Sigma (width of gaussian in all directions).

Returns

f – 3-dimensional Gaussian function

Return type

function

quakemigrate.util.logger(logstem, log, loglevel='info')[source]

Simple logger that will output to both a log file and stdout.

Parameters
  • logstem (str) – Filestem for log file.

  • log (bool) – Toggle for logging - default is to only print information to stdout. If True, will also create a log file.

  • loglevel (str, optional) – Toggle for logging level - default is to print only “info” messages to log. To print more detailed “debug” messages, set to “debug”.

quakemigrate.util.make_directories(run, subdir=None)[source]

Make run directory, and optionally make subdirectories within it.

Parameters
  • run (pathlib.Path object) – Location of parent output directory, named by run name.

  • subdir (str, optional) – subdir to make beneath the run level.

quakemigrate.util.merge_stream(stream)[source]

Merge all traces with contiguous data, or overlapping data which exactly matches (== st._cleanup(); i.e. no clobber). Apply this on a channel by channel basis so that if any individual merge fails then only that channel will be omitted.

Parameters

stream (obspy.Stream object) – Stream to be merged.

Returns

stream_merged – Merged Stream.

Return type

obpsy.Stream object

quakemigrate.util.pairwise(iterable)[source]

Utility to iterate over an iterable pairwise.

quakemigrate.util.resample(stream, sampling_rate, resample, upfactor, starttime, endtime)[source]

Resample data in an obspy.Stream object to the specified sampling rate.

By default, this function will only perform decimation of the data. If necessary, and if the user specifies resample = True and an upfactor to upsample by upfactor = int, data can also be upsampled and then, if necessary, subsequently decimated to achieve the desired sampling rate.

For example, for raw input data sampled at a mix of 40, 50 and 100 Hz, to achieve a unified sampling rate of 50 Hz, the user would have to specify an upfactor of 5; 40 Hz x 5 = 200 Hz, which can then be decimated to 50 Hz.

NOTE: assumes any data with off-sample timing has been corrected with shift_to_sample(). If not, the resulting traces may not all contain the correct number of samples.

NOTE: data will be detrended and a cosine taper applied before decimation, in order to avoid edge effects when applying the lowpass filter.

Parameters
  • stream (obspy.Stream object) – Contains list of obspy.Trace objects to be decimated / resampled.

  • resample (bool) – If true, perform resampling of data which cannot be decimated directly to the desired sampling rate.

  • upfactor (int or None) – Factor by which to upsample the data to enable it to be decimated to the desired sampling rate, e.g. 40Hz -> 50Hz requires upfactor = 5.

Returns

stream – Contains list of resampled obspy.Trace objects at the chosen sampling rate sr.

Return type

obspy.Stream object

quakemigrate.util.shift_to_sample(stream, interpolate=False)[source]

Check whether any data in an obspy.Stream object is “off-sample” - i.e. the data timestamps are not an integer number of samples after midnight. If so, shift data to be “on-sample”.

This can either be done by shifting the timestamps by a sub-sample time interval, or interpolating the trace to the “on-sample” timestamps. The latter has the benefit that it will not affect the timing of the data, but will require additional computation time and some inevitable edge effects - though for onset calculation these should be contained within the pad windows. If you are using a sampling rate < 10 Hz, contact the QuakeMigrate developers.

Parameters
  • stream (obspy.Stream object) – Contains list of obspy.Trace objects for which to check the timing.

  • interpolate (bool, optional) – Whether to interpolate the data to correct the “off-sample” timing. Otherwise, the metadata will simply be altered to shift the timestamps “on-sample”; this will lead to a sub-sample timing offset.

Returns

stream – Waveform data with all timestamps “on-sample”.

Return type

obspy.Stream object

quakemigrate.util.time2sample(time, sampling_rate)[source]

Utility function to convert from seconds and sampling rate to number of samples.

Parameters
  • time (float) – Time to convert.

  • sampling_rate (int) – Sampling rate of input data/sampling rate at which to compute the coalescence function.

Returns

out – Time that correpsonds to an integer number of samples at a specific sampling rate.

Return type

int

quakemigrate.util.timeit(*args_, **kwargs_)[source]

Function wrapper that measures the time elapsed during its execution.

quakemigrate.util.trim2sample(time, sampling_rate)[source]

Utility function to ensure time padding results in a time that is an integer number of samples.

Parameters
  • time (float) – Time to trim.

  • sampling_rate (int) – Sampling rate of input data/sampling rate at which to compute the coalescence function.

Returns

out – Time that correpsonds to an integer number of samples at a specific sampling rate.

Return type

int

quakemigrate.util.upsample(trace, upfactor, starttime, endtime)[source]

Upsample a data stream by a given factor, prior to decimation. The upsampling is carried out by linear interpolation.

NOTE: assumes any data with off-sample timing has been corrected with shift_to_sample(). If not, the resulting traces may not all contain the correct number of samples (and desired start and end times).

Parameters
  • trace (obspy.Trace object) – Trace to be upsampled.

  • upfactor (int) – Factor by which to upsample the data in trace.

Returns

out – Upsampled trace.

Return type

obpsy.Trace object

quakemigrate.util.wa_response(convert='DIS2DIS', obspy_def=True)[source]

Generate a Wood Anderson response dictionary.

Parameters
  • convert ({'DIS2DIS', 'VEL2VEL', 'VEL2DIS'}) – Type of output to convert between; determines the number of complex zeros used.

  • obspy_def (bool, optional) – Use the ObsPy definition of the Wood Anderson response (Default). Otherwise, use the IRIS/SAC definition.

Returns

WOODANDERSON – Poles, zeros, sensitivity and gain of the Wood-Anderson torsion seismograph.

Return type

dict