pyrocko.carpet

Multi-component waveform data model.

A Carpet holds the samples of several components on a common time axis in a single 2D array. Typical uses are the waveforms of a multi-component sensor or of a sensor array, and spectrograms, where each component is a frequency band (see Carpet.component_axes).

Carpets can be stored in files of the .rug format (see pyrocko.io.rug) and are handled by Squirrel like other content (see pyrocko.squirrel.base.Squirrel.get_carpets()).

Note

This module is experimental. Its interface may still change and a warning is shown when it is used.

Functions

check_compatible(carpets)

Check that carpets have the same sampling and components.

check_overlaps(carpets_a[, carpets_b, message])

Check that carpets with the same codes do not overlap in time.

check_same_components(a, b)

Check that two carpets have the same components.

correlate(a, b[, mode, normalization, use_fft])

Cross-correlate traces and/or carpets.

join(carpets)

Join carpets which are contiguous in time.

sum(carpets[, nan_aware, normalize, dtype])

Sum carpets sample by sample.

Classes

Carpet([traces, assemble, data, nsamples, ...])

Container for multi-component waveforms with common time span and sampling.

CarpetStats(**kwargs)

Summary statistics of the data samples of a carpet.

CarpetStringFiller(carpet[, additional])

Placeholder values for Carpet.fill_template().

Exceptions

CarpetError

Base class for errors raised by Carpet operations.

CarpetOverlapError

Raised by some Carpet operations when carpets overlap but should not (see check_overlaps()).

CarpetResampleError

Raised when Carpet.resample_band() cannot be applied.

exception CarpetError[source]

Bases: Exception

Base class for errors raised by Carpet operations.

exception CarpetOverlapError[source]

Bases: CarpetError

Raised by some Carpet operations when carpets overlap but should not (see check_overlaps()).

exception CarpetResampleError[source]

Bases: CarpetError

Raised when Carpet.resample_band() cannot be applied.

class CarpetStringFiller(carpet, additional={})[source]

Bases: object

Placeholder values for Carpet.fill_template().

Gives access to the following placeholders by name:

network, station, location, channel, extra

Codes of the carpet (Carpet.codes).

network_safe, …, extra_safe, nslce_safe, nslc_safe

The same, with characters other than 0-9, A-Z, a-z, _ and - replaced by _, for use in file names. nslce_safe and nslc_safe join the codes with ..

network_dsafe, …, extra_dsafe

Like the _safe variants, but _ instead of an empty string, for use as directory names.

tmin, tmax

Start and end time as YYYY-MM-DD_HH-MM-SS.

tmin_ms, tmax_ms, tmin_us, tmax_us

The same, with milli- or microseconds.

tmin_year, tmin_month, tmin_day, tmin_jday, tmax_...

Parts of the start and end time (jday: day of the year).

julianday

Day of the year of the start time, without zero padding.

Any other name is looked up in additional.

class CarpetStats(**kwargs)[source]

Bases: Object

Summary statistics of the data samples of a carpet.

Masked samples are ignored. Non-finite values are ignored in the percentiles and counted in nan_count.

♦ min

float

Minimum value.

♦ p10

float

10th percentile.

♦ median

float

Median.

♦ p90

float

90th percentile.

♦ max

float

Maximum value.

♦ nan_count

int

Number of non-finite values (NaN, inf).

classmethod make(data, mask=None)[source]

Compute statistics of a data array.

Parameters:
Returns:

New statistics object.

Return type:

CarpetStats

class Carpet(traces=None, assemble='concatenate', data=None, nsamples=None, codes=None, component_codes=None, component_axes=None, tmin=None, deltat=None, mask=None, meta=None, stats=None)[source]

Bases: Object

Container for multi-component waveforms with common time span and sampling.

Instances of this class can be used to efficiently represent multi-component waveforms of a single sensor or of a sensor array, or spectrograms. The data samples are stored in a single 2D array where the first index runs over components and the second index over time. Metadata contains sampling interval, start time and CodesNSLCE identifiers for the carpet as a whole (codes) and for each component (component_codes). Further coordinates of the components, e.g. the frequencies of a spectrogram, can be attached as component_axes.

The samples are held in data, a plain numpy.ndarray. Missing or invalid samples, e.g. gaps or samples polluted by artifacts, can be marked in the optional boolean mask (True = masked). Without a mask (None), all samples are valid. The values of masked samples are undefined. Methods carry the mask along: filters treat masked samples as zeros and keep them masked, and bleed() extends the masked regions to hide edge effects. masked_data gives a numpy.ma.MaskedArray view, for use with numpy.ma functions.

Some carpets, e.g. spectrograms, mark missing values with NaN instead. mask_invalid() converts NaN (and inf) into masked samples.

A carpet can also be created without data (“dataless”), e.g. to hold metadata only. In this case, component_codes and nsamples must be given.

Most methods returning a carpet create a new one, which may share the data with the original (chop(), chopper(), crop()). The filter methods (lowpass(), highpass(), smooth(), whiten(), …) modify the carpet in place.

Parameters:
  • traces (list of Trace) – If given, construct the carpet from these single-component waveforms, see assemble. data, component_codes, tmin and deltat are then taken from the traces.

  • assemble (str) – How to combine traces: 'concatenate' (default) stacks the traces in the given order, one component per trace. They must have the same time span, sampling interval and data type (see get_traces_data_as_array()). 'merge' combines traces with the same codes into one component each (sorted by codes), covering the joint time span of all traces. Samples not covered by any trace are masked (see merge_traces_data_as_array()). The traces must have the same sampling interval and sampling instants.

  • data (numpy.ndarray or numpy.ma.MaskedArray) – Data samples, indexed as (icomponent, isample). If a numpy.ma.MaskedArray is given, its mask is combined with mask.

  • mask (numpy.ndarray of bool) – Mask of invalid samples, same shape as data (True = masked).

  • nsamples (int) – Number of samples. Required for a dataless carpet, otherwise taken from data (and checked, if given).

  • codes (CodesNSLCE) – Codes identifying the carpet as a whole.

  • component_codes (list of CodesNSLCE) – Codes of the components, one per row of data. Default: empty codes for all components.

  • component_axes (dict of str to numpy.ndarray) – Auxiliary coordinate axes of the components, by name, e.g. {'frequency': frequencies}. Each array must have one value per component.

  • tmin (get_time_float()) – Time of the first sample [s].

  • deltat (float) – Sampling interval [s].

  • meta (dict) – Additional free-form metadata.

Raises:

ValueError if the arguments are inconsistent, e.g. if the number of component codes does not match the number of rows of data.

♦ codes

pyrocko.model.codes.CodesNSLCE, default: CodesNSLCE()

Codes identifying the carpet as a whole.

♦ component_codes

list of pyrocko.model.codes.CodesNSLCE objects, default: []

List of codes identifying the components.

♦ component_axes

dict of numpy.ndarray (pyrocko.guts_array.Array) objects, default: {}

Auxiliary component coordinate axes, by name, e.g. the frequencies of a spectrogram. Each axis has one value per component.

♦ nsamples

int

Number of samples.

♦ data

numpy.ndarray (pyrocko.guts_array.Array), optional

Array containing the data samples indexed as (icomponent, isample).

♦ mask

numpy.ndarray (pyrocko.guts_array.Array), optional

Mask of invalid samples, same shape as data (True = masked). None if all samples are valid.

♦ tmin

pyrocko.util.get_time_float (pyrocko.guts.Timestamp), default: str_to_time('1970-01-01 00:00:00')

Time of first sample [s].

♦ deltat

float, default: 1.0

Sampling interval [s].

♦ meta

dict of pyrocko.guts.Any objects, default: {}

Additional free-form metadata.

♦ stats

CarpetStats, optional

Summary statistics of the data samples. Computed on first access and cached; the cache is not updated when the data changes.

property masked_data

The data as numpy.ma.MaskedArray (read-only).

Shares the data samples with the carpet. Changing the mask of the returned array does not change the carpet’s mask, use set_mask() for that.

get_mask()[source]

Get the mask, also if all samples are valid.

Returns:

Boolean array of the shape of data, True for masked samples. A new array of False values if the carpet has no mask.

Return type:

numpy.ndarray

set_mask(mask)[source]

Set the mask.

Parameters:

mask (numpy.ndarray) – Boolean array of the shape of data (True = masked), or None to mark all samples as valid. A mask without any masked samples is stored as None.

mask_invalid()[source]

Mask non-finite samples (NaN, inf), in place.

The samples already masked stay masked.

property summary_component_codes

Short textual representation of the component codes, e.g. first and last, for summary.

property summary_entries

Entries of summary, as a tuple of strings: class name, codes, number of components, number of samples, data type, sampling interval, start and end time, and component codes.

property summary

One-line textual summary of the carpet’s metadata attributes.

itime(time, out_of_bounds='raise')[source]

Get index of the sample nearest to a given time.

Parameters:
  • time (get_time_float()) – Time [s].

  • out_of_bounds (str) – What to do if time is outside the carpet’s time span: 'raise' raises ValueError, 'clip' returns the index of the first or last sample, 'ignore' returns the index anyway (it may then be negative or too large).

Returns:

Sample index.

Return type:

int

fill_template(template, **additional)[source]

Fill placeholders in a template string with the carpet’s attributes.

Used e.g. to create file names. Placeholders can be given in str.format style, e.g. '{station}_{tmin}.rug', or in % style, e.g. '%(station)s_%(tmin)s.rug'. See CarpetStringFiller for the available names.

Parameters:
  • template (str) – Template string.

  • additional – Values for additional placeholders.

Returns:

Filled string. A template without placeholders is returned unchanged.

Return type:

str

copy(data='copy')[source]

Create a copy.

Codes, component codes, component axes, start time, sampling interval and meta are copied (shallow).

Parameters:

data (str or numpy.ndarray) – 'copy' to deeply copy the data and mask, or 'reference' to create a shallow copy, referencing the original data and mask, or 'drop' to create a dataless copy. An array given here is used as the data of the copy instead, with the mask of a numpy.ma.MaskedArray or else no mask.

Return type:

Carpet

chop(tmin, tmax, snap=(<built-in function round>, <built-in function round>))[source]

Cut out a time span.

Unlike pyrocko.trace.Trace.chop(), this does not modify the carpet but returns a new one, sharing the data with the original.

The new carpet contains the samples with indices from snap[0]((tmin - self.tmin) / deltat) up to, but excluding, snap[1]((tmax - self.tmin) / deltat), limited to the available samples. With the default rounding, tmax is therefore exclusive: chop(t, t + n*deltat) gives n samples.

Parameters:
  • tmin (get_time_float()) – Start time [s].

  • tmax (get_time_float()) – End time [s].

  • snap (tuple of two functions) – Rounding functions to convert tmin and tmax to sample indices, e.g. (math.floor, math.ceil) to include partially covered samples.

Raises:

NoData if no samples remain.

Return type:

Carpet

chopper(tinc)[source]

Iterate over consecutive time windows.

The windows start at tmin and have a length of floor(tinc / deltat) samples each. The last window may be shorter. The yielded carpets share the data with the original.

Parameters:

tinc (float) – Window length [s].

Yields:

Carpet objects.

overlaps(*args)[source]

Check if this carpet overlaps with a given time span or other carpet.

Call as overlaps(tmin, tmax) or overlaps(other_carpet). Time spans touching at a single instant count as overlapping. Only times are compared, not codes.

Returns:

True if the time spans overlap.

Return type:

bool

property tmax

End time (time of last sample, read-only).

property times

Times of the samples [s] (read-only).

Return type:

numpy.ndarray

get_trace(i, span=slice(None, None, None))[source]

Get single component waveform (shared data).

The trace refers to the raw sample values: masked samples are included with whatever value they hold. Use iter_valid_traces() to get the unmasked parts only.

Parameters:
  • i (int) – Component index.

  • span (slice) – Range of sample indices to include, default: all.

Return type:

Trace

iter_valid_traces()[source]

Iterate over the unmasked parts of the components, as traces.

Each contiguous range of unmasked samples of a component gives one trace (shared data).

Yields:

Trace objects.

get_traces()[source]

Get all components as traces, including masked samples.

See get_trace().

Return type:

list of Trace

get_valid_traces()[source]

Get the unmasked parts of the components as traces.

See iter_valid_traces().

Return type:

list of Trace

get_component_axis(name=None)[source]

Get coordinates of the components.

Parameters:

name (str) – Name of an entry in component_axes, or None to get the component indices.

Return type:

numpy.ndarray

mpl_draw(axes, component_axis=None, fslice=slice(None, None, None), **kwargs)[source]

Draw the carpet into Matplotlib axes, with matplotlib.axes.Axes.pcolormesh().

Time runs along the x-axis, the components along the y-axis. Masked samples are left blank.

Parameters:
  • axes (matplotlib.axes.Axes) – Axes to draw into.

  • component_axis (str) – Coordinates for the y-axis: None for the component indices, 'default' for the only entry of component_axes if there is exactly one (indices otherwise), or the name of an entry of component_axes.

  • fslice (slice) – Components to draw.

  • kwargs – Passed to pcolormesh().

Returns:

Object returned by pcolormesh().

plot(component_axis='default', component_axis_scale='linear', fslice=slice(None, None, None), path=None, **kwargs)[source]

Plot the carpet in a new Matplotlib figure.

See mpl_draw() for component_axis, fslice and kwargs.

Parameters:
  • component_axis_scale (str) – Scale of the y-axis, e.g. 'linear' or 'log'.

  • path (str) – If given, save the figure to this file instead of showing it.

snuffle(what='valid')[source]

Show the components in Snuffler.

Parameters:

what (str) – 'valid' to show only the unmasked parts (see get_valid_traces()), 'raw' to show all samples.

bleed(t)[source]

Extend masked regions and mask the edges, in place.

Masks t seconds at both ends of every contiguous range of unmasked samples, and at the start and end of the carpet. Useful to hide edge effects, e.g. of filters, near gaps.

Parameters:

t (float) – Duration to mask [s]. Nothing is done if it is shorter than one sample.

set_data(data)[source]

Replace the data samples, keeping the shape.

Parameters:

data (numpy.ndarray or numpy.ma.MaskedArray) – New data samples, with the same shape as the current ones. If a plain numpy.ndarray is given, the current mask is kept. The mask of a numpy.ma.MaskedArray replaces the current mask.

apply(f)[source]

Apply a function to the data samples, in place.

Parameters:

f (callable) – Function taking and returning a data array of the same shape, see set_data(). It gets the plain data array; masked samples hold undefined values.

reduce(f, component_codes)[source]

Combine the components with a function, in place.

Example: carpet.reduce(lambda data: data.sum(axis=0), codes) replaces all components by their sum.

Parameters:
  • f (callable) – Function taking the data array and returning a new one with the same number of samples, either 2D (icomponent, isample) or 1D (a single component). If the carpet has a mask, f gets masked_data, so that numpy.ma semantics apply (e.g. sum skips masked samples), and the mask of the result becomes the new mask.

  • component_codes (CodesNSLCE or list of these) – Codes of the new components.

component_axes is kept if the number of components stays the same, and cleared otherwise.

nyquist_check(frequency, intro='Corner frequency', warn=True, raise_exception=False)[source]

Check if a given frequency is above the Nyquist frequency of the carpet.

Parameters:
  • frequency (float) – Frequency to check [Hz].

  • intro (str) – String used to introduce the warning/error message.

  • warn (bool) – Whether to emit a warning message.

  • raise_exception (bool) – Whether to raise AboveNyquist.

lfilter(b, a, demean=True)[source]

Filter all components with scipy.signal.lfilter(), in place.

Sample data is converted to type float, possibly demeaned and filtered along the time axis using scipy.signal.lfilter(). Masked samples are set to zero before filtering and stay masked. Use bleed() afterwards to mask the filter’s transients at gaps.

Parameters:
  • b (numpy.ndarray) – Numerator coefficients.

  • a (numpy.ndarray) – Denominator coefficients.

  • demean (bool) – Subtract the mean of each component (of the unmasked samples) before filtering.

lowpass(order, corner, nyquist_warn=True, nyquist_exception=False, demean=True)[source]

Filter all components using a Butterworth lowpass, in place.

Sample data is converted to type float, possibly demeaned and filtered using scipy.signal.lfilter(). Filter coefficients are generated with scipy.signal.butter().

Parameters:
  • order (int) – Order of the filter.

  • corner (float) – Corner frequency of the filter [Hz].

  • demean (bool) – Subtract mean before filtering.

  • nyquist_warn (bool) – Warn if corner frequency is greater than Nyquist frequency.

  • nyquist_exception (bool) – Raise pyrocko.trace.AboveNyquist if corner frequency is greater than Nyquist frequency.

highpass(order, corner, nyquist_warn=True, nyquist_exception=False, demean=True)[source]

Filter all components using a Butterworth highpass, in place.

Sample data is converted to type float, possibly demeaned and filtered using scipy.signal.lfilter(). Filter coefficients are generated with scipy.signal.butter().

Parameters:
  • order (int) – Order of the filter.

  • corner (float) – Corner frequency of the filter [Hz].

  • demean (bool) – Subtract mean before filtering.

  • nyquist_warn (bool) – Warn if corner frequency is greater than Nyquist frequency.

  • nyquist_exception (bool) – Raise AboveNyquist if corner frequency is greater than Nyquist frequency.

fold(t, method=<function mean>)[source]

Downsample by combining blocks of samples.

Blocks of nfold = round(t / deltat) consecutive samples are combined into one with method. The blocks are aligned to multiples of the new sampling interval nfold * deltat in absolute time, so that folded carpets of different time spans fit together. Incomplete blocks at the start and end are dropped. If the carpet has a mask, method gets a numpy.ma.MaskedArray: with numpy.mean() (or other functions supporting masked arrays), masked samples are skipped and a block is only masked if all its samples are masked.

Parameters:
  • t (float) – New sampling interval [s], rounded to a multiple of deltat.

  • method (callable) – Function to combine the samples of a block, called as method(data, axis=2) on an array of shape (ncomponents, nblocks, nfold), e.g. numpy.mean() (default) or numpy.max().

Raises:

NoData if no complete block remains.

Returns:

New carpet.

Return type:

Carpet

smooth(t, window=<function hanning>)[source]

Smooth along the time axis with a moving weighted average, in place.

Each sample is replaced by the average of the valid samples around it, weighted with the window. Masked samples and samples beyond the ends of the carpet are left out of the average, and the weights of the remaining samples are renormalized. So, a constant signal is left unchanged, also next to gaps and at the ends. The mask is not changed.

Parameters:
  • t (float) – Window length [s], rounded to an odd number of samples.

  • window (callable) – Function returning the window for a given number of samples, e.g. numpy.hanning() (default).

filter_frequency_cos_taper(f1, f2, f3, f4)[source]

Bandpass filter with a cosine taper in the frequency domain, in place.

The spectrum is multiplied by a taper which rises from 0 at f1 to 1 at f2, and falls from 1 at f3 to 0 at f4 (see pyrocko.trace.costaper()). See apply_via_fft().

Parameters:
  • f1 (float) – Frequency [Hz] where the taper starts to rise from 0.

  • f2 (float) – Frequency [Hz] where the taper reaches 1.

  • f3 (float) – Frequency [Hz] where the taper starts to fall from 1.

  • f4 (float) – Frequency [Hz] where the taper reaches 0.

whiten(deltaf, window=<function hanning>)[source]

Spectral whitening, in place.

The spectrum of each component is divided by its amplitude spectrum, smoothed over a frequency band of width deltaf. See apply_via_fft(). The smoothing window is normalized to unit sum, so that the resulting amplitude spectrum is close to one.

Parameters:
  • deltaf (float) – Width of the smoothing window [Hz].

  • window (callable) – Function returning the smoothing window for a given number of samples.

normalize(deltat, window=<function hanning>)[source]

Time-domain normalization, in place.

Each component is divided by its running mean absolute amplitude, i.e. its sample-wise absolute value, smoothed over a time window of length deltat (see smooth(), masked samples are left out). This is the running absolute mean normalization commonly used in ambient noise processing. Samples where this amplitude is zero are set to zero.

Parameters:
  • deltat (float) – Length of the smoothing window [s].

  • window (callable) – Function returning the smoothing window for a given number of samples.

apply_via_fft(f, ntrans_min=0)[source]

Apply a function to the spectra of the components, in place.

The spectra are computed with get_spectrum(), passed to f, and the result is transformed back to the time domain and cut to the original number of samples.

Parameters:
  • f (callable) – Function called as f(frequency_delta, ntrans, spectrum), returning the modified spectrum (see get_spectrum() for the arguments).

  • ntrans_min (int) – Minimum FFT length.

get_spectrum(ntrans_min=0)[source]

Get the spectra of the components.

Masked samples are replaced by zeros. The data is zero-padded to the next power of two of at least ntrans_min and the number of samples, and transformed with numpy.fft.rfft().

Parameters:

ntrans_min (int) – Minimum FFT length.

Returns:

(frequency_delta, ntrans, spectrum): frequency spacing [Hz], FFT length, and complex spectra indexed as (icomponent, ifrequency).

Return type:

tuple

get_cross_spectrum(ntrans_min=0)[source]

Get the cross spectra of all pairs of components.

Parameters:

ntrans_min (int) – Minimum FFT length, see get_spectrum().

Returns:

(frequency_delta, ntrans, cross_spectrum), where cross_spectrum[i, j, k] is S_i(f_k) * conj(S_j(f_k)) for the spectra S of components i and j.

Return type:

tuple

get_component_codes_grouped(codes_projection)[source]

Group the components by their codes.

Parameters:

codes_projection (CodesProjection) – Determines the grouping, see group_key().

Returns:

Component indices by group key.

Return type:

dict of list of int

get_energy(codes_projection=None, postprocessing=None)[source]

Get the energy, i.e. the sum of squared samples, of groups of components.

The components are grouped with codes_projection, e.g. the three components of a sensor. Masked input samples do not contribute. Samples with zero energy, e.g. where all input samples are masked, are masked (and set to 1).

Parameters:
  • codes_projection (CodesProjection) – Grouping of the components and codes of the resulting components. Default: one group per sensor, i.e. by network, station, location and channel code without the component character. The resulting components get these codes and the extra code P.

  • postprocessing (callable) – Function applied to the result, see apply().

Returns:

New carpet, one component per group.

Return type:

Carpet

get_rms(codes_projection=None)[source]

Get the RMS amplitude, i.e. the square root of the energy, of groups of components.

Like get_energy(), but with the square root applied.

Parameters:

codes_projection (CodesProjection) – Grouping of the components, see get_energy().

Returns:

New carpet, one component per group.

Return type:

Carpet

get_log_rms(codes_projection=None)[source]

Get the natural logarithm of the RMS amplitude of groups of components.

Like get_rms(), but logarithmic. Before taking the logarithm, the energy is smoothed over three samples with weights (0.25, 0.5, 0.25). Masked samples and samples beyond the ends are left out of the average.

Parameters:

codes_projection (CodesProjection) – Grouping of the components, see get_energy().

Returns:

New carpet, one component per group. Masked samples are set to zero.

Return type:

Carpet

get_log10_rms(codes_projection=None)[source]

Get the decadic logarithm of the RMS amplitude of groups of components.

Like get_log_rms(), but with the decadic logarithm.

Parameters:

codes_projection (CodesProjection) – Grouping of the components, see get_energy().

Returns:

New carpet, one component per group. Masked samples are set to zero.

Return type:

Carpet

crop(fslice=slice(None, None, None))[source]

Select a range of components.

Parameters:

fslice (slice) – Components to keep. The component axes are cut accordingly.

Returns:

New carpet, sharing the data with the original.

Return type:

Carpet

resample_band(fmin, fmax, nf, registration='cell', scale='log', component_axis='frequency')[source]

Resample the components to regularly spaced bins of a component axis.

Typically used to bring a spectrogram to nf frequency bands, regularly spaced on a logarithmic or linear frequency scale. The value of each new band is the average of the data over the band, computed by integrating (trapezoidal rule, on the chosen scale) along the component axis, which must be increasing.

Components whose axis value does not meet the scale’s condition, e.g. frequency 0 for logarithmic scale, are dropped first. Masked and NaN input samples count as zero in the integration. Bands outside the range of the component axis, or with a result of exactly zero, are set to NaN. The result has no mask.

Parameters:
  • fmin (float) – Lower end of the range of the new bands. Default: lower end of the component axis.

  • fmax (float) – Upper end of the range of the new bands. Default: upper end of the component axis.

  • nf (int) – Number of new bands.

  • registration (str) – 'cell': fmin and fmax are the outer edges of the first and last band. 'node': they are (approximately) the centres of the first and last band.

  • scale (str or tuple) – 'log', 'lin', or a tuple (f, f_inverse, condition) of functions for a custom scale, e.g. (numpy.log, numpy.exp, lambda y: y > 0).

  • component_axis (str) – Name of the component axis in component_axes. If it is not present, the component indices are used.

Raises:

CarpetResampleError if the scale is invalid, the component axis is not increasing, or no data is in the requested range.

Returns:

New carpet with nf components, empty component codes, and the band centres as component axis component_axis.

Return type:

Carpet

correlate(a, b, mode='valid', normalization=None, use_fft=False)[source]

Cross-correlate traces and/or carpets.

Each of a and b can be a Trace or a Carpet. Components are correlated pairwise with pyrocko.trace.correlate(), see there for the other arguments.

Returns:

For two traces, the correlation trace. Otherwise a carpet with one component per pair of components (for two carpets, ordered by the components of a, then those of b).

Return type:

Trace or Carpet

join(carpets)[source]

Join carpets which are contiguous in time.

Carpets with the same codes, number of components, sampling interval and data type are concatenated if one starts right after the other ends. Carpets without samples are dropped. Component codes and component axes are taken from the first carpet of each joined group. Masks are joined as well.

Parameters:

carpets (list of Carpet) – Carpets to join.

Returns:

Joined carpets, sorted by codes and start time.

Return type:

list of Carpet

check_same_components(a, b)[source]

Check that two carpets have the same components.

Compares the number of components, the component codes and the component axes.

Raises:

CarpetError if the components differ.

check_compatible(carpets)[source]

Check that carpets have the same sampling and components.

The carpets must have the same sampling interval, start time and number of samples, and the same components (see check_same_components()).

Raises:

CarpetError if the carpets are not compatible.

sum(carpets, nan_aware=False, normalize=False, dtype=<class 'float'>)[source]

Sum carpets sample by sample.

The carpets must be compatible (see check_compatible()).

Parameters:
  • carpets (list of Carpet) – Carpets to sum.

  • nan_aware (bool) – If True, non-finite values (NaN, inf) are skipped. Otherwise they propagate into the sum. Masked samples are always skipped.

  • normalize (bool) – If True, divide by the number of finite, unmasked values summed, i.e. compute the average.

  • dtype (numpy.dtype) – Data type of the sum.

Raises:

CarpetError if no carpets are given, a carpet has no data, or the carpets are not compatible.

Returns:

New carpet, with codes .SUM... and the components of the first carpet. Samples with no finite, unmasked values are NaN. The result has no mask.

Return type:

Carpet

check_overlaps(carpets_a, carpets_b=None, message='Carpets overlap.')[source]

Check that carpets with the same codes do not overlap in time.

Parameters:
  • carpets_a (list of Carpet) – Carpets to check.

  • carpets_b (list of Carpet) – If given, check each carpet of carpets_a against these instead of against the others in carpets_a.

  • message (str) – Beginning of the error message.

Raises:

CarpetOverlapError on the first overlap found.