Skip to content

pysmo.tools.signal

Signal processing functions for pysmo types.

Functions operate on pysmo Seismogram objects and span filtering, spectral analysis, delay estimation and array-wide arrival-time refinement, instrument response removal, and frequency-domain calculus (integration and differentiation). Filters are additionally registered in a common registry, so they can be applied generically by name as well as by calling the specific filter function directly.

Where a suitable implementation already exists in SciPy (e.g. scipy.signal), functions in this module wrap it rather than reimplementing it; others implement seismology-specific algorithms with no direct SciPy equivalent.

Functions that modify seismogram data follow the same clone convention as pysmo.functions: without clone they operate in place and return None; with clone=True they return a modified copy.

Note

The Seismogram type carries no unit label for data. Functions in this module do not track or convert physical units either — e.g. remove_response outputs whatever quantity the given response's input_units declares, and integrate/ differentiate shift between displacement/velocity/acceleration without recording which is which. Callers must keep track of the physical quantity seismogram.data represents.

Functions:

Name Description
bandpass

Apply a bandpass filter to the input seismogram.

bandstop

Apply a bandstop filter to the input seismogram.

delay

Cross correlates two seismograms to determine signal delay.

differentiate

Differentiate a seismogram in the frequency domain.

envelope

Calculates the envelope of a gaussian filtered seismogram.

filter

Apply a specified filter to the input seismogram.

gauss

Returns a gaussian filtered seismogram.

highpass

Apply a highpass filter to the input seismogram.

integrate

Integrate a seismogram in the frequency domain.

lowpass

Apply a lowpass filter to the input seismogram.

mccc

Multi-Channel Cross-Correlation (MCCC) for relative arrival times.

multi_delay

Calculates delays and correlation coefficients for a list of seismograms against a template.

multi_multi_delay

Calculates pairwise delays and correlation coefficients for a sequence of seismograms.

psd

Calculate the Power Spectral Density (PSD) of a Seismogram using Welch's method.

remove_response

Remove an instrument response from a seismogram.

bandpass

bandpass(
    seismogram: T,
    freqmin: float = 0.1,
    freqmax: float = 0.5,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None

Apply a bandpass filter to the input seismogram.

Parameters:

Name Type Description Default
seismogram T

The input seismogram to be filtered.

required
freqmin float

The minimum frequency of the bandpass filter (in Hz).

0.1
freqmax float

The maximum frequency of the bandpass filter (in Hz).

0.5
corners int

The number of corners (poles) for the Butterworth filter.

2
zerophase bool

If True, apply the filter in both forward and reverse directions to achieve zero phase distortion.

False
clone bool

If True, return a new Seismogram object with the filtered data. If False, modify the input seismogram in place.

False

Returns:

Type Description
T | None

A new Seismogram object containing the filtered data when called with clone=True.

Source code in src/pysmo/tools/signal/_filter/_butter.py
@register_filter
def bandpass[T: Seismogram](
    seismogram: T,
    freqmin: float = 0.1,
    freqmax: float = 0.5,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None:
    """Apply a bandpass filter to the input seismogram.

    Args:
        seismogram: The input seismogram to be filtered.
        freqmin: The minimum frequency of the bandpass filter (in Hz).
        freqmax: The maximum frequency of the bandpass filter (in Hz).
        corners: The number of corners (poles) for the Butterworth filter.
        zerophase: If `True`, apply the filter in both forward and reverse
            directions to achieve zero phase distortion.
        clone: If `True`, return a new Seismogram object with the filtered
            data. If `False`, modify the input seismogram in place.

    Returns:
        A new Seismogram object containing the filtered data when called with `clone=True`.
    """
    fe = 0.5 / seismogram.delta.total_seconds()
    low = freqmin / fe
    high = freqmax / fe

    if not (0 < low < 1):
        raise ValueError(
            f"freqmin ({freqmin}) is invalid for sampling rate {1 / seismogram.delta.total_seconds()} Hz."
        )
    if not (0 < high < 1):
        raise ValueError(
            f"freqmax ({freqmax}) is invalid for sampling rate {1 / seismogram.delta.total_seconds()} Hz."
        )
    if freqmin >= freqmax:
        raise ValueError("freqmin must be less than freqmax.")

    sos = iirfilter(corners, [low, high], btype="band", ftype="butter", output="sos")

    if clone:
        seismogram = deepcopy(seismogram)

    if zerophase:
        seismogram.data = sosfiltfilt(sos, seismogram.data)
    else:
        seismogram.data = sosfilt(sos, seismogram.data)

    return seismogram if clone else None

bandstop

bandstop(
    seismogram: T,
    freqmin: float = 0.1,
    freqmax: float = 0.5,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None

Apply a bandstop filter to the input seismogram.

Parameters:

Name Type Description Default
seismogram T

The input seismogram to be filtered.

required
freqmin float

The minimum frequency of the bandstop filter (in Hz).

0.1
freqmax float

The maximum frequency of the bandstop filter (in Hz).

0.5
corners int

The number of corners (poles) for the Butterworth filter.

2
zerophase bool

If True, apply the filter in both forward and reverse directions to achieve zero phase distortion.

False
clone bool

If True, return a new Seismogram object with the filtered data. If False, modify the input seismogram in place.

False

Returns:

Type Description
T | None

A new Seismogram object containing the filtered data when called with clone=True.

Source code in src/pysmo/tools/signal/_filter/_butter.py
@register_filter
def bandstop[T: Seismogram](
    seismogram: T,
    freqmin: float = 0.1,
    freqmax: float = 0.5,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None:
    """Apply a bandstop filter to the input seismogram.

    Args:
        seismogram: The input seismogram to be filtered.
        freqmin: The minimum frequency of the bandstop filter (in Hz).
        freqmax: The maximum frequency of the bandstop filter (in Hz).
        corners: The number of corners (poles) for the Butterworth filter.
        zerophase: If `True`, apply the filter in both forward and reverse
            directions to achieve zero phase distortion.
        clone: If `True`, return a new Seismogram object with the filtered
            data. If `False`, modify the input seismogram in place.

    Returns:
        A new Seismogram object containing the filtered data when called with `clone=True`.
    """
    fe = 0.5 / seismogram.delta.total_seconds()
    low = freqmin / fe
    high = freqmax / fe

    if not (0 < low < 1):
        raise ValueError(
            f"freqmin ({freqmin}) is invalid for sampling rate {1 / seismogram.delta.total_seconds()} Hz."
        )
    if not (0 < high < 1):
        raise ValueError(
            f"freqmax ({freqmax}) is invalid for sampling rate {1 / seismogram.delta.total_seconds()} Hz."
        )
    if freqmin >= freqmax:
        raise ValueError("freqmin must be less than freqmax.")

    sos = iirfilter(
        corners, [low, high], btype="bandstop", ftype="butter", output="sos"
    )

    if clone:
        seismogram = deepcopy(seismogram)

    if zerophase:
        seismogram.data = sosfiltfilt(sos, seismogram.data)
    else:
        seismogram.data = sosfilt(sos, seismogram.data)

    return seismogram if clone else None

delay

delay(
    seismogram1: Seismogram,
    seismogram2: Seismogram,
    total_delay: bool = False,
    max_shift: Timedelta | None = None,
    abs_max: bool = False,
) -> tuple[Timedelta, float]

Cross correlates two seismograms to determine signal delay.

This function is a wrapper around the correlate function. The default behaviour is to call the correlate function with mode="full" using the full length data of the input seismograms. This is the most robust option, but also the slowest.

If an approximate delay is known (e.g. because a particular phase is being targeted using a computed arrival time), the search space can be limited by setting the max_shift parameter to a value. The length of the seismogram data used for the cross-correlation is then set such that the calculated delay lies within +/- max_shift.

Note

max_shift intentionally does not take the begin times of the seismograms into consideration. Thus, calling delay() with total_delay=True may return a delay that is larger than max_shift.

Implications of setting the max_shift parameter are as follows:

  • This mode requires the seismograms to be of equal length.
  • If the true delay (i.e. the amount of time the seismograms should be shifted by) lies within the max_shift range, and also produces the highest correlation, the delay time returned is identical for both methods.
  • If the true delay lies outside the max_shift range and produces the highest correlation, the delay time returned will be incorrect when max_shift is set.
  • In the event that the true delay lies within the max_shift range but the maximum signal correlation occurs outside, it will be correctly retrieved when the max_shift parameter is set, while not setting it yields an incorrect result.

Parameters:

Name Type Description Default
seismogram1 Seismogram

First seismogram to use for cross correlation.

required
seismogram2 Seismogram

Second seismogram to use for cross correlation.

required
total_delay bool

Include the difference in begin_time in the delay.

False
max_shift Timedelta | None

Maximum (absolute) length of the delay.

None
abs_max bool

Return the delay corresponding to absolute maximum.

False

Returns:

Name Type Description
delay Timedelta

Time delay of the second seismogram with respect to the first.

cc float

Normalised cross-correlation value of the overlapping seismograms after shifting (uses scipy.stats.mstats.pearsonr for the calculation). This value ranges from -1 to 1, with 1 indicating a perfect correlation, 0 indicating no correlation, and -1 indicating a perfect anti-correlation.

Examples:

To illustrate the delay() function: this reads a seismogram from a SAC file, then generates a second seismogram from it with a shift in the data and in the begin time. That makes the true delay known, so it can be compared against the computed delay:

>>> from pysmo import MiniSeismogram
>>> from pysmo.classes import SAC
>>> from pysmo.functions import detrend, clone_to_mini
>>> from pysmo.tools.signal import delay
>>> from datetime import timedelta
>>> import numpy as np
>>>
>>> # Create a Seismogram from a SAC file and detrend it:
>>> seis1 = SAC.from_file("example.sac").seismogram
>>> detrend(seis1)
>>>
>>> # Create a second seismogram from the first with
>>> # a different begin_time and a shift in the data:
>>> seis2 = clone_to_mini(MiniSeismogram, seis1)
>>> nroll = 1234
>>> seis2.data = np.roll(seis2.data, nroll)
>>> begin_time_delay = timedelta(seconds=100)
>>> seis2.begin_time += begin_time_delay
>>>
>>> # The signal delay is the number of samples shifted * delta:
>>> (signal_delay := nroll * seis1.delta).total_seconds()
61.7
>>>
>>> # Call the delay function with the two seismograms and verify
>>> # that the caclulated_delay is equal to the known signal delay:
>>> calculated_delay, _ = delay(seis1, seis2)
>>> calculated_delay == signal_delay
True
>>>

Since the true delay is known, this can mimic a scenario where an approximate delay is known before the cross-correlation, which can be used to limit the search space and speed up the calculation. Here, max_shift is set to the known signal delay plus 1 second:

>>> max_shift = signal_delay + timedelta(seconds=1)
>>> calculated_delay, _ = delay(seis1, seis2, max_shift=max_shift)
>>> # As before, the calculated delay should be equal to the signal delay:
>>> calculated_delay == signal_delay
True
>>>

Setting total_delay=True also takes into account the difference in begin_time between the two seismograms:

>>> calculated_delay, _ = delay(seis1, seis2, total_delay=True, max_shift=signal_delay+timedelta(seconds=1))
>>> # With `total_delay=True`, the calculated delay should be equal to
>>> # the signal delay plus the begin time difference:
>>> calculated_delay == signal_delay + (seis2.begin_time - seis1.begin_time)
True
>>>

To demonstrate the abs_max parameter, the second seismogram's data is sign-flipped:

>>> seis2.data *= -1
>>> calculated_delay, cc = delay(seis1, seis2)
>>> # Without `abs_max=True`, the calculated delay is no longer equal
>>> # to the true signal delay (as expected):
>>> calculated_delay == signal_delay
False
>>> # The normalised cross-correlation value is also not very high
>>> cc
np.float64(0.5094230)
>>>
>>> calculated_delay, cc = delay(seis1, seis2, abs_max=True)
>>> # with `abs_max=True`, the signal delay is again retrieved:
>>> calculated_delay == signal_delay
True
>>> # And, as the signals are completely opposite, the normalised
>>> # cross-correlation value is -1:
>>> np.testing.assert_approx_equal(cc, -1)
>>>
Source code in src/pysmo/tools/signal/_delay.py
def delay(
    seismogram1: Seismogram,
    seismogram2: Seismogram,
    total_delay: bool = False,
    max_shift: pd.Timedelta | None = None,
    abs_max: bool = False,
) -> tuple[pd.Timedelta, float]:
    """Cross correlates two seismograms to determine signal delay.

    This function is a wrapper around the [`correlate`][scipy.signal.correlate]
    function. The default behaviour is to call the correlate function with
    `#!py mode="full"` using the full length data of the input seismograms.
    This is the most robust option, but also the slowest.

    If an approximate delay is known (e.g. because a particular phase is being
    targeted using a computed arrival time), the search space can be limited
    by setting the `max_shift` parameter to a value. The length of the
    seismogram data used for the cross-correlation is then set such that the
    calculated delay lies within +/- `max_shift`.

    Note:
        `max_shift` intentionally does *not* take the begin times of the
        seismograms into consideration. Thus, calling `#!py delay()` with
        `#!py total_delay=True` may return a delay that is larger than
        `max_shift`.

    Implications of setting the `max_shift` parameter are as follows:

    - This mode requires the seismograms to be of equal length.
    - If the true delay (i.e. the amount of time the seismograms _should_ be
      shifted by) lies within the `max_shift` range, and also produces the
      highest correlation, the delay time returned is identical for both
      methods.
    - If the true delay lies outside the `max_shift` range and produces the
      highest correlation, the delay time returned will be incorrect when
      `max_shift` is set.
    - In the event that the true delay lies within the `max_shift` range but
      the maximum signal correlation occurs outside, it will be correctly
      retrieved when the `max_shift` parameter is set, while not setting it
      yields an incorrect result.


    Args:
        seismogram1: First seismogram to use for cross correlation.
        seismogram2: Second seismogram to use for cross correlation.
        total_delay: Include the difference in `begin_time` in the delay.
        max_shift: Maximum (absolute) length of the delay.
        abs_max: Return the delay corresponding to absolute maximum.

    Returns:
        delay: Time delay of the second seismogram with respect to the first.
        cc: Normalised cross-correlation value of the overlapping
            seismograms *after* shifting (uses
            [`scipy.stats.mstats.pearsonr`][] for the calculation). This value
            ranges from -1 to 1, with 1 indicating a perfect correlation, 0
            indicating no correlation, and -1 indicating a perfect
            anti-correlation.

    Examples:
        To illustrate the `delay()` function: this reads a seismogram from a
        SAC file, then generates a second seismogram from it with a shift in
        the data and in the begin time. That makes the true delay known, so
        it can be compared against the computed delay:

        ```python
        >>> from pysmo import MiniSeismogram
        >>> from pysmo.classes import SAC
        >>> from pysmo.functions import detrend, clone_to_mini
        >>> from pysmo.tools.signal import delay
        >>> from datetime import timedelta
        >>> import numpy as np
        >>>
        >>> # Create a Seismogram from a SAC file and detrend it:
        >>> seis1 = SAC.from_file("example.sac").seismogram
        >>> detrend(seis1)
        >>>
        >>> # Create a second seismogram from the first with
        >>> # a different begin_time and a shift in the data:
        >>> seis2 = clone_to_mini(MiniSeismogram, seis1)
        >>> nroll = 1234
        >>> seis2.data = np.roll(seis2.data, nroll)
        >>> begin_time_delay = timedelta(seconds=100)
        >>> seis2.begin_time += begin_time_delay
        >>>
        >>> # The signal delay is the number of samples shifted * delta:
        >>> (signal_delay := nroll * seis1.delta).total_seconds()
        61.7
        >>>
        >>> # Call the delay function with the two seismograms and verify
        >>> # that the caclulated_delay is equal to the known signal delay:
        >>> calculated_delay, _ = delay(seis1, seis2)
        >>> calculated_delay == signal_delay
        True
        >>>
        ```

        Since the true delay is known, this can mimic a scenario where an
        approximate delay is known before the cross-correlation, which can be
        used to limit the search space and speed up the calculation. Here,
        `max_shift` is set to the known signal delay plus 1 second:

        ```python
        >>> max_shift = signal_delay + timedelta(seconds=1)
        >>> calculated_delay, _ = delay(seis1, seis2, max_shift=max_shift)
        >>> # As before, the calculated delay should be equal to the signal delay:
        >>> calculated_delay == signal_delay
        True
        >>>
        ```

        Setting `total_delay=True` also takes into account the difference
        in `begin_time` between the two seismograms:

        ```python
        >>> calculated_delay, _ = delay(seis1, seis2, total_delay=True, max_shift=signal_delay+timedelta(seconds=1))
        >>> # With `total_delay=True`, the calculated delay should be equal to
        >>> # the signal delay plus the begin time difference:
        >>> calculated_delay == signal_delay + (seis2.begin_time - seis1.begin_time)
        True
        >>>
        ```

        To demonstrate the `abs_max` parameter, the second seismogram's data
        is sign-flipped:

        ```python
        >>> seis2.data *= -1
        >>> calculated_delay, cc = delay(seis1, seis2)
        >>> # Without `abs_max=True`, the calculated delay is no longer equal
        >>> # to the true signal delay (as expected):
        >>> calculated_delay == signal_delay
        False
        >>> # The normalised cross-correlation value is also not very high
        >>> cc
        np.float64(0.5094230)
        >>>
        >>> calculated_delay, cc = delay(seis1, seis2, abs_max=True)
        >>> # with `abs_max=True`, the signal delay is again retrieved:
        >>> calculated_delay == signal_delay
        True
        >>> # And, as the signals are completely opposite, the normalised
        >>> # cross-correlation value is -1:
        >>> np.testing.assert_approx_equal(cc, -1)
        >>>
        ```
    """

    _check_same_delta(seismogram1, seismogram2)

    if max_shift is not None and len(seismogram1.data) != len(seismogram2.data):
        raise ValueError(
            "Input seismograms must be of equal length when using `max_shift`."
        )

    data1, data2 = seismogram1.data, seismogram2.data
    delta = seismogram1.delta

    if max_shift is not None:
        max_lag_in_samples = math.ceil(max_shift / delta)
        data1 = np.pad(data1, max_lag_in_samples)
        corr = _correlate(data1, data2, mode="valid")
    else:
        corr = _correlate(data1, data2, mode="full")

    corr_index = np.argmax(corr)

    if abs_max and np.max(corr) < -1 * np.min(corr):
        corr_index = np.argmin(corr)

    if max_shift is not None:
        shift = -int(corr_index - max_lag_in_samples)
    else:
        shift = int(len(data2) - 1 - corr_index)

    delay = shift * delta

    # find overlapping parts of seismograms after alignment
    if shift < 0:
        data1 = data1[-shift:]
    else:
        data2 = data2[shift:]
    if len(data1) > len(data2):
        data1 = data1[: len(data2)]
    else:
        data2 = data2[: len(data1)]

    cc, _ = _pearsonr(data1, data2)

    if total_delay:
        delay += seismogram2.begin_time - seismogram1.begin_time

    return delay, cc

differentiate

differentiate(
    seismogram: T, clone: bool = False
) -> T | None

Differentiate a seismogram in the frequency domain.

Multiplies the FFT of seismogram.data by \(i\omega\) at each rfftfreq bin, then inverse transforms back to the time domain. The DC bin is correctly zeroed (\(i\omega = 0\)), since a constant offset differentiates to zero.

Parameters:

Name Type Description Default
seismogram T

Seismogram object.

required
clone bool

Operate on a clone of the input seismogram.

False

Returns:

Type Description
T | None

Differentiated Seismogram object if called with

T | None

clone=True.

Raises:

Type Description
ValueError

If seismogram.data is empty.

Examples:

A synthetic sine wave with a known closed-form derivative (\(\omega \cos(\omega t)\)) is used to verify the result:

>>> import numpy as np
>>> import pandas as pd
>>> from pysmo import MiniSeismogram
>>> from pysmo.tools.signal import differentiate
>>> dt = 0.1
>>> npts = 250  # an exact number of cycles of the 1 Hz signal below
>>> t = np.arange(npts) * dt
>>> omega = 2 * np.pi * 1.0
>>> seismogram = MiniSeismogram(
...     begin_time=pd.Timestamp("2010-02-27T06:30:00Z"),
...     delta=pd.Timedelta(seconds=dt),
...     data=np.sin(omega * t),
... )
>>> velocity = differentiate(seismogram, clone=True)
>>> expected = omega * np.cos(omega * t)
>>> np.allclose(velocity.data, expected, atol=1e-6)
True
>>>
Source code in src/pysmo/tools/signal/_calculus.py
def differentiate[T: Seismogram](seismogram: T, clone: bool = False) -> T | None:
    r"""Differentiate a seismogram in the frequency domain.

    Multiplies the FFT of `seismogram.data` by $i\omega$ at each
    [`rfftfreq`][numpy.fft.rfftfreq] bin, then inverse transforms back to the
    time domain. The DC bin is correctly zeroed ($i\omega = 0$), since a
    constant offset differentiates to zero.

    Args:
        seismogram: Seismogram object.
        clone: Operate on a clone of the input seismogram.

    Returns:
        Differentiated [`Seismogram`][pysmo.Seismogram] object if called with
        `clone=True`.

    Raises:
        ValueError: If `seismogram.data` is empty.

    Examples:
        A synthetic sine wave with a known closed-form derivative
        ($\omega \cos(\omega t)$) is used to verify the result:

        ```python
        >>> import numpy as np
        >>> import pandas as pd
        >>> from pysmo import MiniSeismogram
        >>> from pysmo.tools.signal import differentiate
        >>> dt = 0.1
        >>> npts = 250  # an exact number of cycles of the 1 Hz signal below
        >>> t = np.arange(npts) * dt
        >>> omega = 2 * np.pi * 1.0
        >>> seismogram = MiniSeismogram(
        ...     begin_time=pd.Timestamp("2010-02-27T06:30:00Z"),
        ...     delta=pd.Timedelta(seconds=dt),
        ...     data=np.sin(omega * t),
        ... )
        >>> velocity = differentiate(seismogram, clone=True)
        >>> expected = omega * np.cos(omega * t)
        >>> np.allclose(velocity.data, expected, atol=1e-6)
        True
        >>>
        ```
    """
    if len(seismogram.data) == 0:
        raise ValueError("Cannot differentiate an empty seismogram.")

    if clone:
        seismogram = deepcopy(seismogram)

    dt = seismogram.delta.total_seconds()
    npts = len(seismogram.data)
    freqs = np.fft.rfftfreq(npts, d=dt)
    omega = 2 * np.pi * freqs

    spectrum = np.fft.rfft(seismogram.data)
    spectrum *= 1j * omega
    seismogram.data = np.fft.irfft(spectrum, n=npts)

    return seismogram if clone else None

envelope

envelope(
    seismogram: T,
    fc: float,
    alpha: float,
    clone: bool = False,
) -> T | None

Calculates the envelope of a gaussian filtered seismogram.

Parameters:

Name Type Description Default
seismogram T

Seismogram object.

required
fc float

Centre frequency of the Gaussian filter (in Hz).

required
alpha float

Dimensionless shape parameter controlling the filter width. Larger values produce a narrower (more selective) filter.

required
clone bool

Operate on a clone of the input seismogram.

False

Returns:

Type Description
T | None

Seismogram containing the envelope.

Examples:

>>> from pysmo.classes import SAC
>>> from pysmo.tools.signal import envelope
>>> seis = SAC.from_file("example.sac").seismogram
>>> fc = 0.02 # Centre Gaussian filter at 0.02 Hz (50s period)
>>> alpha = 50 # Set alpha (which determines filterwidth) to 50
>>> envelope_seis = envelope(seis, fc, alpha, clone=True)
>>>
Source code in src/pysmo/tools/signal/_filter/_gauss.py
@register_filter
def envelope[T: Seismogram](
    seismogram: T, fc: float, alpha: float, clone: bool = False
) -> T | None:
    """Calculates the envelope of a gaussian filtered seismogram.

    Args:
        seismogram: Seismogram object.
        fc: Centre frequency of the Gaussian filter (in Hz).
        alpha: Dimensionless shape parameter controlling the filter width.
            Larger values produce a narrower (more selective) filter.
        clone: Operate on a clone of the input seismogram.

    Returns:
        Seismogram containing the envelope.

    Examples:
        ```python
        >>> from pysmo.classes import SAC
        >>> from pysmo.tools.signal import envelope
        >>> seis = SAC.from_file("example.sac").seismogram
        >>> fc = 0.02 # Centre Gaussian filter at 0.02 Hz (50s period)
        >>> alpha = 50 # Set alpha (which determines filterwidth) to 50
        >>> envelope_seis = envelope(seis, fc, alpha, clone=True)
        >>>
        ```
    """
    if clone:
        seismogram = deepcopy(seismogram)
    seismogram.data = _gauss(seismogram, fc, alpha)[0]
    return seismogram if clone else None

filter

filter(
    seismogram: T,
    filter_name: FilterName,
    clone: bool = False,
    **filter_options: bool | int | float
) -> T | None

Apply a specified filter to the input seismogram.

This function is a convenience wrapper that calls other filters in this module.

Parameters:

Name Type Description Default
seismogram T

The input seismogram to be filtered.

required
filter_name FilterName

The type of filter to apply.

required
clone bool

If True, return a new Seismogram object with the filtered data. If False, modify the input seismogram in place.

False
**filter_options bool | int | float

Filter parameters passed to the specified filter function.

{}

Returns:

Type Description
T | None

A new Seismogram object containing the filtered data when called with clone=True.

Raises:

Type Description
ValueError

If filter_name is not a registered filter.

Examples:

>>> from pysmo.classes import SAC
>>> from pysmo.tools.signal import filter
>>> seis = SAC.from_file("example.sac").seismogram
>>>
>>> # create a new filtered seismogram with a lowpass filter
>>> filtered_seis = filter(seis, "lowpass", freqmax=0.5, clone=True)
>>>
>>> # or update in place with a bandpass filter
>>> filter(seis, "bandpass", freqmin=0.1, freqmax=0.5)
>>>
Source code in src/pysmo/tools/signal/_filter/_filter.py
def filter[T: Seismogram](
    seismogram: T,
    filter_name: FilterName,
    clone: bool = False,
    **filter_options: bool | int | float,
) -> T | None:
    """Apply a specified filter to the input seismogram.

    This function is a convenience wrapper that calls other filters in this module.

    Args:
        seismogram: The input seismogram to be filtered.
        filter_name: The type of filter to apply.
        clone: If `True`, return a new Seismogram object with the filtered
            data. If `False`, modify the input seismogram in place.
        **filter_options: Filter parameters passed to the specified filter
            function.

    Returns:
        A new Seismogram object containing the filtered data when called with `clone=True`.

    Raises:
        ValueError: If `filter_name` is not a registered filter.

    Examples:
        ```python
        >>> from pysmo.classes import SAC
        >>> from pysmo.tools.signal import filter
        >>> seis = SAC.from_file("example.sac").seismogram
        >>>
        >>> # create a new filtered seismogram with a lowpass filter
        >>> filtered_seis = filter(seis, "lowpass", freqmax=0.5, clone=True)
        >>>
        >>> # or update in place with a bandpass filter
        >>> filter(seis, "bandpass", freqmin=0.1, freqmax=0.5)
        >>>
        ```
    """

    try:
        filter_func = _FILTER_REGISTRY[filter_name]
    except KeyError:
        # This fallback handles cases where FilterName is updated but
        # the function isn't decorated yet.
        valid_filters = ", ".join(_FILTER_REGISTRY.keys())
        raise ValueError(
            f"Filter '{filter_name}' is not registered. Available: {valid_filters}"
        )

    if clone:
        return filter_func(seismogram, clone=True, **filter_options)
    filter_func(seismogram, clone=False, **filter_options)
    return None

gauss

gauss(
    seismogram: T,
    fc: float,
    alpha: float,
    clone: bool = False,
) -> T | None

Returns a gaussian filtered seismogram.

Parameters:

Name Type Description Default
seismogram T

Seismogram object.

required
fc float

Centre frequency of the Gaussian filter (in Hz).

required
alpha float

Dimensionless shape parameter controlling the filter width. Larger values produce a narrower (more selective) filter.

required
clone bool

Operate on a clone of the input seismogram.

False

Returns:

Type Description
T | None

Gaussian filtered seismogram.

Examples:

>>> from pysmo.classes import SAC
>>> from pysmo.tools.signal import gauss
>>> seis = SAC.from_file("example.sac").seismogram
>>> fc = 0.02 # Centre Gaussian filter at 0.02 Hz (50s period)
>>> alpha = 50 # Set alpha (which determines filterwidth) to 50
>>> gauss_seis = gauss(seis, fc, alpha, clone=True)
>>>
Source code in src/pysmo/tools/signal/_filter/_gauss.py
@register_filter
def gauss[T: Seismogram](
    seismogram: T, fc: float, alpha: float, clone: bool = False
) -> T | None:
    """Returns a gaussian filtered seismogram.

    Args:
        seismogram: Seismogram object.
        fc: Centre frequency of the Gaussian filter (in Hz).
        alpha: Dimensionless shape parameter controlling the filter width.
            Larger values produce a narrower (more selective) filter.
        clone: Operate on a clone of the input seismogram.

    Returns:
        Gaussian filtered seismogram.

    Examples:
        ```python
        >>> from pysmo.classes import SAC
        >>> from pysmo.tools.signal import gauss
        >>> seis = SAC.from_file("example.sac").seismogram
        >>> fc = 0.02 # Centre Gaussian filter at 0.02 Hz (50s period)
        >>> alpha = 50 # Set alpha (which determines filterwidth) to 50
        >>> gauss_seis = gauss(seis, fc, alpha, clone=True)
        >>>
        ```
    """
    if clone:
        seismogram = deepcopy(seismogram)
    seismogram.data = _gauss(seismogram, fc, alpha)[1]
    return seismogram if clone else None

highpass

highpass(
    seismogram: T,
    freqmin: float = 0.1,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None

Apply a highpass filter to the input seismogram.

Parameters:

Name Type Description Default
seismogram T

The input seismogram to be filtered.

required
freqmin float

The minimum frequency of the highpass filter (in Hz).

0.1
corners int

The number of corners (poles) for the Butterworth filter.

2
zerophase bool

If True, apply the filter in both forward and reverse directions to achieve zero phase distortion.

False
clone bool

If True, return a new Seismogram object with the filtered data. If False, modify the input seismogram in place.

False

Returns:

Type Description
T | None

A new Seismogram object containing the filtered data when called with clone=True.

Source code in src/pysmo/tools/signal/_filter/_butter.py
@register_filter
def highpass[T: Seismogram](
    seismogram: T,
    freqmin: float = 0.1,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None:
    """Apply a highpass filter to the input seismogram.

    Args:
        seismogram: The input seismogram to be filtered.
        freqmin: The minimum frequency of the highpass filter (in Hz).
        corners: The number of corners (poles) for the Butterworth filter.
        zerophase: If `True`, apply the filter in both forward and reverse
            directions to achieve zero phase distortion.
        clone: If `True`, return a new Seismogram object with the filtered
            data. If `False`, modify the input seismogram in place.

    Returns:
        A new Seismogram object containing the filtered data when called with `clone=True`.
    """
    fe = 0.5 / seismogram.delta.total_seconds()
    low = freqmin / fe

    if not (0 < low < 1):
        raise ValueError(
            f"freqmin ({freqmin}) is invalid for sampling rate {1 / seismogram.delta.total_seconds()} Hz."
        )

    sos = iirfilter(corners, low, btype="high", ftype="butter", output="sos")

    if clone:
        seismogram = deepcopy(seismogram)

    if zerophase:
        seismogram.data = sosfiltfilt(sos, seismogram.data)
    else:
        seismogram.data = sosfilt(sos, seismogram.data)

    return seismogram if clone else None

integrate

integrate(seismogram: T, clone: bool = False) -> T | None

Integrate a seismogram in the frequency domain.

Divides the FFT of seismogram.data by \(i\omega\) at each rfftfreq bin (\(\omega > 0\)), then inverse transforms back to the time domain. The DC bin is set to 0.0 rather than divided by. Working in the frequency domain avoids the unbounded low-frequency drift a cumulative time-domain integrator introduces.

Parameters:

Name Type Description Default
seismogram T

Seismogram object.

required
clone bool

Operate on a clone of the input seismogram.

False

Returns:

Type Description
T | None

Integrated Seismogram object if called with

T | None

clone=True.

Raises:

Type Description
ValueError

If seismogram.data is empty.

Examples:

A synthetic cosine wave with a known closed-form integral (\(\sin(\omega t)\)) is used to verify the result:

>>> import numpy as np
>>> import pandas as pd
>>> from pysmo import MiniSeismogram
>>> from pysmo.tools.signal import integrate
>>> dt = 0.1
>>> npts = 250  # an exact number of cycles of the 1 Hz signal below
>>> t = np.arange(npts) * dt
>>> omega = 2 * np.pi * 1.0
>>> seismogram = MiniSeismogram(
...     begin_time=pd.Timestamp("2010-02-27T06:30:00Z"),
...     delta=pd.Timedelta(seconds=dt),
...     data=omega * np.cos(omega * t),
... )
>>> displacement = integrate(seismogram, clone=True)
>>> expected = np.sin(omega * t)
>>> np.allclose(displacement.data, expected, atol=1e-6)
True
>>>
Source code in src/pysmo/tools/signal/_calculus.py
def integrate[T: Seismogram](seismogram: T, clone: bool = False) -> T | None:
    r"""Integrate a seismogram in the frequency domain.

    Divides the FFT of `seismogram.data` by $i\omega$ at each
    [`rfftfreq`][numpy.fft.rfftfreq] bin ($\omega > 0$), then inverse
    transforms back to the time domain. The DC bin is set to `0.0` rather
    than divided by. Working in the frequency domain avoids the unbounded
    low-frequency drift a cumulative time-domain integrator introduces.

    Args:
        seismogram: Seismogram object.
        clone: Operate on a clone of the input seismogram.

    Returns:
        Integrated [`Seismogram`][pysmo.Seismogram] object if called with
        `clone=True`.

    Raises:
        ValueError: If `seismogram.data` is empty.

    Examples:
        A synthetic cosine wave with a known closed-form integral
        ($\sin(\omega t)$) is used to verify the result:

        ```python
        >>> import numpy as np
        >>> import pandas as pd
        >>> from pysmo import MiniSeismogram
        >>> from pysmo.tools.signal import integrate
        >>> dt = 0.1
        >>> npts = 250  # an exact number of cycles of the 1 Hz signal below
        >>> t = np.arange(npts) * dt
        >>> omega = 2 * np.pi * 1.0
        >>> seismogram = MiniSeismogram(
        ...     begin_time=pd.Timestamp("2010-02-27T06:30:00Z"),
        ...     delta=pd.Timedelta(seconds=dt),
        ...     data=omega * np.cos(omega * t),
        ... )
        >>> displacement = integrate(seismogram, clone=True)
        >>> expected = np.sin(omega * t)
        >>> np.allclose(displacement.data, expected, atol=1e-6)
        True
        >>>
        ```
    """
    if len(seismogram.data) == 0:
        raise ValueError("Cannot integrate an empty seismogram.")

    if clone:
        seismogram = deepcopy(seismogram)

    dt = seismogram.delta.total_seconds()
    npts = len(seismogram.data)
    freqs = np.fft.rfftfreq(npts, d=dt)
    omega = 2 * np.pi * freqs

    spectrum = np.fft.rfft(seismogram.data)
    integrated_spectrum = np.zeros_like(spectrum)
    integrated_spectrum[1:] = spectrum[1:] / (1j * omega[1:])
    seismogram.data = np.fft.irfft(integrated_spectrum, n=npts)

    return seismogram if clone else None

lowpass

lowpass(
    seismogram: T,
    freqmax: float = 0.5,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None

Apply a lowpass filter to the input seismogram.

Parameters:

Name Type Description Default
seismogram T

The input seismogram to be filtered.

required
freqmax float

The maximum frequency of the lowpass filter (in Hz).

0.5
corners int

The number of corners (poles) for the Butterworth filter.

2
zerophase bool

If True, apply the filter in both forward and reverse directions to achieve zero phase distortion.

False
clone bool

If True, return a new Seismogram object with the filtered data. If False, modify the input seismogram in place.

False

Returns:

Type Description
T | None

A new Seismogram object containing the filtered data when called with clone=True.

Source code in src/pysmo/tools/signal/_filter/_butter.py
@register_filter
def lowpass[T: Seismogram](
    seismogram: T,
    freqmax: float = 0.5,
    corners: int = 2,
    zerophase: bool = False,
    clone: bool = False,
) -> T | None:
    """Apply a lowpass filter to the input seismogram.

    Args:
        seismogram: The input seismogram to be filtered.
        freqmax: The maximum frequency of the lowpass filter (in Hz).
        corners: The number of corners (poles) for the Butterworth filter.
        zerophase: If `True`, apply the filter in both forward and reverse
            directions to achieve zero phase distortion.
        clone: If `True`, return a new Seismogram object with the filtered
            data. If `False`, modify the input seismogram in place.

    Returns:
        A new Seismogram object containing the filtered data when called with `clone=True`.
    """
    fe = 0.5 / seismogram.delta.total_seconds()
    high = freqmax / fe

    if not (0 < high < 1):
        raise ValueError(
            f"freqmax ({freqmax}) is invalid for sampling rate {1 / seismogram.delta.total_seconds()} Hz."
        )

    sos = iirfilter(corners, high, btype="low", ftype="butter", output="sos")

    if clone:
        seismogram = deepcopy(seismogram)

    if zerophase:
        seismogram.data = sosfiltfilt(sos, seismogram.data)
    else:
        seismogram.data = sosfilt(sos, seismogram.data)

    return seismogram if clone else None

mccc

mccc(
    seismograms: Sequence[Seismogram],
    min_cc: float = 0.5,
    damping: float = 0.1,
    abs_max: bool = False,
) -> tuple[
    list[Timedelta],
    list[Timedelta],
    Timedelta,
    list[float],
    list[float],
]

Multi-Channel Cross-Correlation (MCCC) for relative arrival times.

Computes all pairwise cross-correlation delays using multi_multi_delay, then solves for self-consistent relative time shifts using a weighted least-squares inversion with a zero-mean constraint and Tikhonov regularisation. Pairs whose correlation coefficient falls below min_cc are excluded from the inversion.

The returned times list sums to zero by construction, so the values represent relative shifts around the group mean.

Parameters:

Name Type Description Default
seismograms Sequence[Seismogram]

Sequence of Seismogram objects. All must share the same sampling interval.

required
min_cc float

Minimum correlation coefficient required to include a pair in the inversion.

0.5
damping float

Tikhonov regularisation strength. Set to 0 to disable.

0.1
abs_max bool

If True, uses absolute max correlation (polarity insensitive) for the pairwise delays.

False

Returns:

Name Type Description
times list[Timedelta]

List of relative arrival times.

errors list[Timedelta]

List of standard errors.

rmse Timedelta

Root-mean-square error of the fit.

cc_means list[float]

Mean correlation coefficient for each seismogram.

cc_stds list[float]

Standard deviation of correlation coefficients for each seismogram.

Raises:

Type Description
ValueError

If any seismogram has a different sampling rate than the others (raised by multi_multi_delay).

Notes

The returned statistics provide key diagnostic information: - Cycle Skip: High errors combined with high cc_means and low cc_stds suggests a cycle skip (the waveform matches perfectly but on the wrong peak). - Noisy Seismogram: Low cc_means combined with high errors and cc_stds indicates poor data quality or significant site-response distortion. - Array Coherence: The rmse measures the overall fit. High rmse even with high cc_means suggests the array is too large or sparse for a single coherent arrival time (e.g., crossing a major tectonic boundary).

Examples:

Create seismograms with known shifts and recover them with mccc:

>>> from pysmo import MiniSeismogram
>>> from pysmo.tools.signal import mccc
>>> import numpy as np
>>>
>>> # Build three seismograms with known shifts (in samples):
>>> data = np.sin(np.linspace(0, 8 * np.pi, 1000))
>>> shifts = [0, 5, -10]
>>> seismograms = [MiniSeismogram(data=np.roll(data, s)) for s in shifts]
>>>
>>> # Run MCCC inversion:
>>> times, errors, rmse, cc, cc_std = mccc(seismograms)
>>>
>>> # The relative times sum to approximately zero:
>>> abs(sum(t.total_seconds() for t in times)) < 1e-5
True
>>>
>>> # Pairwise differences recover the known shifts
>>> # (times[i] - times[j] ≈ (shifts[i] - shifts[j]) * delta):
>>> round((times[1] - times[0]).total_seconds())
5
>>> round((times[2] - times[0]).total_seconds())
-10
>>>

Use abs_max=True to recover shifts for polarity-flipped signals:

>>> # Create a set of seismograms where one has inverted polarity:
>>> seismograms[1].data *= -1
>>>
>>> # Run MCCC with abs_max=True:
>>> times, errors, rmse, cc, cc_std = mccc(seismograms, abs_max=True)
>>>
>>> # Shifts are still correctly recovered:
>>> round((times[1] - times[0]).total_seconds())
5
>>> # The correlation coefficient for the flipped signal is negative:
>>> cc[1] < -0.9
True
>>>
References

VanDecar, J. C., and R. S. Crosson. “Determination of Teleseismic Relative Phase Arrival Times Using Multi-Channel Cross-Correlation and Least Squares.” Bulletin of the Seismological Society of America, vol. 80, no. 1, Feb. 1990, pp. 150–69, https://doi.org/10.1785/BSSA0800010150.

Source code in src/pysmo/tools/signal/_delay.py
def mccc(
    seismograms: Sequence[Seismogram],
    min_cc: float = 0.5,
    damping: float = 0.1,
    abs_max: bool = False,
) -> tuple[
    list[pd.Timedelta], list[pd.Timedelta], pd.Timedelta, list[float], list[float]
]:
    """Multi-Channel Cross-Correlation (MCCC) for relative arrival times.

    Computes all pairwise cross-correlation delays using
    [`multi_multi_delay`][pysmo.tools.signal.multi_multi_delay], then solves
    for self-consistent relative time shifts using a weighted least-squares
    inversion with a zero-mean constraint and Tikhonov regularisation. Pairs
    whose correlation coefficient falls below `min_cc` are excluded from the
    inversion.

    The returned `times` list sums to zero by construction, so the values
    represent relative shifts around the group mean.

    Args:
        seismograms: Sequence of Seismogram objects. All must share the same
            sampling interval.
        min_cc: Minimum correlation coefficient required to include a pair
            in the inversion.
        damping: Tikhonov regularisation strength. Set to 0 to disable.
        abs_max: If `True`, uses absolute max correlation (polarity insensitive)
            for the pairwise delays.

    Returns:
        times: List of relative arrival times.
        errors: List of standard errors.
        rmse: Root-mean-square error of the fit.
        cc_means: Mean correlation coefficient for each seismogram.
        cc_stds: Standard deviation of correlation coefficients for each seismogram.

    Raises:
        ValueError: If any seismogram has a different sampling rate than the
            others (raised by `multi_multi_delay`).

    Notes:
        The returned statistics provide key diagnostic information:
        - **Cycle Skip**: High `errors` combined with high `cc_means` and low
          `cc_stds` suggests a cycle skip (the waveform matches perfectly but
          on the wrong peak).
        - **Noisy Seismogram**: Low `cc_means` combined with high `errors` and
          `cc_stds` indicates poor data quality or significant site-response
          distortion.
        - **Array Coherence**: The `rmse` measures the overall fit. High `rmse`
          even with high `cc_means` suggests the array is too large or sparse
          for a single coherent arrival time (e.g., crossing a major tectonic
          boundary).

    Examples:
        Create seismograms with known shifts and recover them with `mccc`:

        ```python
        >>> from pysmo import MiniSeismogram
        >>> from pysmo.tools.signal import mccc
        >>> import numpy as np
        >>>
        >>> # Build three seismograms with known shifts (in samples):
        >>> data = np.sin(np.linspace(0, 8 * np.pi, 1000))
        >>> shifts = [0, 5, -10]
        >>> seismograms = [MiniSeismogram(data=np.roll(data, s)) for s in shifts]
        >>>
        >>> # Run MCCC inversion:
        >>> times, errors, rmse, cc, cc_std = mccc(seismograms)
        >>>
        >>> # The relative times sum to approximately zero:
        >>> abs(sum(t.total_seconds() for t in times)) < 1e-5
        True
        >>>
        >>> # Pairwise differences recover the known shifts
        >>> # (times[i] - times[j] ≈ (shifts[i] - shifts[j]) * delta):
        >>> round((times[1] - times[0]).total_seconds())
        5
        >>> round((times[2] - times[0]).total_seconds())
        -10
        >>>
        ```

        Use `abs_max=True` to recover shifts for polarity-flipped signals:

        ```python
        >>> # Create a set of seismograms where one has inverted polarity:
        >>> seismograms[1].data *= -1
        >>>
        >>> # Run MCCC with abs_max=True:
        >>> times, errors, rmse, cc, cc_std = mccc(seismograms, abs_max=True)
        >>>
        >>> # Shifts are still correctly recovered:
        >>> round((times[1] - times[0]).total_seconds())
        5
        >>> # The correlation coefficient for the flipped signal is negative:
        >>> cc[1] < -0.9
        True
        >>>
        ```

    References:
        VanDecar, J. C., and R. S. Crosson. “Determination of Teleseismic
        Relative Phase Arrival Times Using Multi-Channel Cross-Correlation and
        Least Squares.” Bulletin of the Seismological Society of America,
        vol. 80, no. 1, Feb. 1990, pp. 150–69,
        <https://doi.org/10.1785/BSSA0800010150>.
    """
    n_traces = len(seismograms)
    zero_delta = pd.Timedelta(0)

    if n_traces < 2:
        return (
            [zero_delta] * n_traces,
            [zero_delta] * n_traces,
            zero_delta,
            [1.0] * n_traces,
            [0.0] * n_traces,
        )

    delay_matrix, cc_matrix = multi_multi_delay(seismograms, abs_max=abs_max)

    # Calculate cc_means and cc_stds (standard deviation of CCs) excluding diagonal
    mask = ~np.eye(n_traces, dtype=bool)
    cc_off_diag = cc_matrix[mask].reshape(n_traces, n_traces - 1)
    cc_means = np.mean(cc_off_diag, axis=1).tolist()
    cc_stds = np.std(cc_off_diag, axis=1, ddof=0).tolist()

    # Convert numpy.timedelta64 array to float seconds for linear algebra
    delay_matrix_seconds = delay_matrix / np.timedelta64(1, "s")

    # Build linear system (g @ m = d)
    rows: list[np.ndarray] = []
    data_vec: list[float] = []
    weights: list[float] = []

    for i in range(n_traces):
        for j in range(i + 1, n_traces):
            cc = cc_matrix[i, j]
            # When abs_max is True, we care about the absolute correlation strength
            cc_to_check = abs(cc) if abs_max else cc
            if cc_to_check < min_cc:
                continue

            lag_seconds = delay_matrix_seconds[i, j]

            row = np.zeros(n_traces)
            row[i] = -1.0
            row[j] = 1.0

            rows.append(row)
            data_vec.append(lag_seconds)
            weights.append(cc**2)

    if not rows:
        return (
            [zero_delta] * n_traces,
            [zero_delta] * n_traces,
            zero_delta,
            cc_means,
            cc_stds,
        )

    g = np.array(rows)
    d = np.array(data_vec)
    w = np.array(weights)

    # Apply weights
    g_weighted = g * w[:, np.newaxis]
    d_weighted = d * w

    # Zero-mean constraint (sum of times = 0)
    constraint_weight = np.sum(w)
    g_system = np.vstack([g_weighted, np.ones(n_traces) * constraint_weight])
    d_system = np.concatenate([d_weighted, [0.0]])

    # Tikhonov regularisation
    if damping > 0:
        g_system = np.vstack([g_system, damping * np.eye(n_traces)])
        d_system = np.concatenate([d_system, np.zeros(n_traces)])

    # Solve least squares
    solution, _, _, _ = lstsq(g_system, d_system)

    # Compute statistics
    predicted = g @ solution
    residuals = d - predicted
    sse = np.sum((residuals**2) * w)
    dof = max(len(d) - n_traces, 1)
    sigma_squared = sse / dof

    try:
        cov_matrix = sigma_squared * inv(g_system.T @ g_system)
        std_errors = np.sqrt(np.abs(np.diag(cov_matrix)))
    except np.linalg.LinAlgError:
        std_errors = np.zeros(n_traces)

    times = [pd.Timedelta(seconds=float(t)) for t in solution]
    errors = [pd.Timedelta(seconds=float(e)) for e in std_errors]
    rmse = pd.Timedelta(seconds=float(np.sqrt(sse / len(d))))

    return times, errors, rmse, cc_means, cc_stds

multi_delay

multi_delay(
    template: Seismogram,
    seismograms: Sequence[Seismogram],
    abs_max: bool = False,
) -> tuple[list[Timedelta], list[float]]

Calculates delays and correlation coefficients for a list of seismograms against a template.

This function uses FFT-based cross-correlation to efficiently compute delays for multiple seismograms at once against a single template. This is faster than calling delay in a loop, as the template FFT is computed only once.

Parameters:

Name Type Description Default
template Seismogram

Template seismogram object.

required
seismograms Sequence[Seismogram]

Sequence of Seismogram objects.

required
abs_max bool

If True, uses absolute max correlation (polarity insensitive).

False

Returns:

Name Type Description
delays list[Timedelta]

Delays of each input seismogram relative to template.

ccs list[float]

Correlation coefficients at maximum correlation for each seismogram.

Raises:

Type Description
ValueError

If any seismogram has a different sampling rate than the template.

Note

Seismograms with zero standard deviation (i.e. constant data) cannot be meaningfully normalised. A UserWarning is issued for each such trace and its normalised values are treated as zero, which results in a correlation coefficient of 0 for that trace. In an MCCC workflow this effectively excludes the trace from the inversion via the min_cc threshold.

Examples:

Create a template seismogram and several shifted copies, then use multi_delay to recover the known shifts:

>>> from pysmo import MiniSeismogram
>>> from pysmo.tools.signal import multi_delay
>>> import numpy as np
>>>
>>> # Create a template seismogram with sinusoidal data:
>>> data = np.sin(np.linspace(0, 8 * np.pi, 1000))
>>> template = MiniSeismogram(data=data)
>>>
>>> # Create shifted copies (shifts in samples):
>>> shifts = [0, 10, -5]
>>> seismograms = [MiniSeismogram(data=np.roll(data, s)) for s in shifts]
>>>
>>> # Calculate delays for all seismograms at once:
>>> delays, ccs = multi_delay(template, seismograms)
>>> [d.total_seconds() for d in delays]
[0.0, 10.0, -5.0]
>>>

Use abs_max=True for polarity-insensitive matching:

>>> flipped = MiniSeismogram(data=-np.roll(data, 10))
>>> delays, ccs = multi_delay(template, [flipped], abs_max=True)
>>> delays[0].total_seconds()
10.0
>>> ccs[0] < 0
True
>>>
Source code in src/pysmo/tools/signal/_delay.py
def multi_delay(
    template: Seismogram, seismograms: Sequence[Seismogram], abs_max: bool = False
) -> tuple[list[pd.Timedelta], list[float]]:
    """Calculates delays and correlation coefficients for a list of seismograms against a template.

    This function uses FFT-based cross-correlation to efficiently compute delays
    for multiple seismograms at once against a single template. This is faster
    than calling [`delay`][pysmo.tools.signal.delay] in a loop, as the template
    FFT is computed only once.

    Args:
        template: Template seismogram object.
        seismograms: Sequence of Seismogram objects.
        abs_max: If `True`, uses absolute max correlation (polarity insensitive).

    Returns:
        delays: Delays of each input seismogram relative to template.
        ccs: Correlation coefficients at maximum correlation for each seismogram.

    Raises:
        ValueError: If any seismogram has a different sampling rate than the template.

    Note:
        Seismograms with zero standard deviation (i.e. constant data) cannot be
        meaningfully normalised. A `UserWarning` is issued for each such trace and
        its normalised values are treated as zero, which results in a correlation
        coefficient of 0 for that trace. In an MCCC workflow this effectively
        excludes the trace from the inversion via the `min_cc` threshold.

    Examples:
        Create a template seismogram and several shifted copies, then use
        `multi_delay` to recover the known shifts:

        ```python
        >>> from pysmo import MiniSeismogram
        >>> from pysmo.tools.signal import multi_delay
        >>> import numpy as np
        >>>
        >>> # Create a template seismogram with sinusoidal data:
        >>> data = np.sin(np.linspace(0, 8 * np.pi, 1000))
        >>> template = MiniSeismogram(data=data)
        >>>
        >>> # Create shifted copies (shifts in samples):
        >>> shifts = [0, 10, -5]
        >>> seismograms = [MiniSeismogram(data=np.roll(data, s)) for s in shifts]
        >>>
        >>> # Calculate delays for all seismograms at once:
        >>> delays, ccs = multi_delay(template, seismograms)
        >>> [d.total_seconds() for d in delays]
        [0.0, 10.0, -5.0]
        >>>
        ```

        Use `abs_max=True` for polarity-insensitive matching:

        ```python
        >>> flipped = MiniSeismogram(data=-np.roll(data, 10))
        >>> delays, ccs = multi_delay(template, [flipped], abs_max=True)
        >>> delays[0].total_seconds()
        10.0
        >>> ccs[0] < 0
        True
        >>>
        ```
    """
    if not seismograms:
        return [], []

    _check_same_delta(template, seismograms)

    # setup dimensions & FFT length
    n_traces = len(seismograms)
    len_t = len(template.data)
    len_s = max(len(s.data) for s in seismograms)

    # pad to avoid circular convolution artefacts
    # (length >= len_template + len_signal - 1)
    n_fft = next_fast_len(len_s + len_t - 1)

    # pad and normalise template
    t_data = template.data
    t_mean = np.mean(t_data)
    t_std = np.std(t_data)
    if t_std == 0:
        warnings.warn(
            "Template seismogram has zero standard deviation (constant data). "
            "Cross-correlation results will be zero for all traces.",
            UserWarning,
            stacklevel=2,
        )
        t_std = 1.0
    template_padded = np.zeros(n_fft, dtype=float)
    template_padded[:len_t] = (t_data - t_mean) / t_std

    # normalise *before* padding to keep stats valid
    seismogram_matrix = np.zeros((n_traces, n_fft), dtype=float)
    for i, s in enumerate(seismograms):
        data = s.data
        mean = np.mean(data)
        std = np.std(data)
        if std == 0:
            warnings.warn(
                f"Seismogram at index {i} has zero standard deviation (constant data). "
                "Its cross-correlation coefficient will be zero.",
                UserWarning,
                stacklevel=2,
            )
            std = 1.0
        seismogram_matrix[i, : len(data)] = (data - mean) / std

    # forward FFT (rfft is faster for real data)
    t_freq = rfft(template_padded, n=n_fft)
    s_freq = rfft(seismogram_matrix, n=n_fft, axis=1)

    # cross-correlation in frequency domain
    cc_freq = s_freq * np.conj(t_freq)

    # inverse FFT & scale (div by len(template) for Pearson approx)
    cc_matrix = irfft(cc_freq, n=n_fft, axis=1) / len_t

    # find maxima
    if abs_max:
        max_indices = np.argmax(np.abs(cc_matrix), axis=1)
    else:
        max_indices = np.argmax(cc_matrix, axis=1)

    # convert circular indices to signed lags
    mid_point = n_fft // 2
    signed_lags = np.where(max_indices <= mid_point, max_indices, max_indices - n_fft)
    delta = template.delta
    delays = [int(lag) * delta for lag in signed_lags]
    ccs: list[float] = cc_matrix[np.arange(n_traces), max_indices].tolist()

    return delays, ccs

multi_multi_delay

multi_multi_delay(
    seismograms: Sequence[Seismogram], abs_max: bool
) -> tuple[NDArray[timedelta64], NDArray[floating]]

Calculates pairwise delays and correlation coefficients for a sequence of seismograms.

This function cross-correlates every seismogram with every other seismogram in the sequence using FFT-based cross-correlation. All FFTs are computed once and combined via broadcasting, making this significantly faster than calling delay for each pair individually.

The result at delays[i, j] is the delay of seismogram j relative to seismogram i (treating i as the reference). The delay matrix is antisymmetric: delays[i, j] == -delays[j, i], and the diagonal is zero.

Note

Unlike most pysmo functions, this returns numpy.timedelta64 values rather than Timedelta. This avoids the overhead of an object array and allows efficient vectorised arithmetic in downstream functions such as mccc. Convert individual elements with pandas.Timedelta(delays[i, j]) if needed.

Parameters:

Name Type Description Default
seismograms Sequence[Seismogram]

Sequence of Seismogram objects.

required
abs_max bool

If True, uses absolute max correlation (polarity insensitive).

required

Returns:

Name Type Description
delays NDArray[timedelta64]

2D array of shape (N, N) with delay times as numpy.timedelta64 values, where N = len(seismograms).

cc_matrix NDArray[floating]

2D array of shape (N, N) with correlation coefficients.

Raises:

Type Description
ValueError

If any seismogram has a different sampling rate than the others.

Note

Seismograms with zero standard deviation (i.e. constant data) cannot be meaningfully normalised. A UserWarning is issued for each such trace and its normalised values are treated as zero, resulting in correlation coefficients of 0 for all pairs involving that trace.

Examples:

Create seismograms with known shifts and compute all pairwise delays:

>>> from pysmo import MiniSeismogram
>>> from pysmo.tools.signal import multi_multi_delay
>>> import pandas as pd
>>> import numpy as np
>>>
>>> data = np.sin(np.linspace(0, 8 * np.pi, 1000))
>>> seismograms = [
...     MiniSeismogram(data=data.copy()),
...     MiniSeismogram(data=np.roll(data, 5)),
...     MiniSeismogram(data=np.roll(data, -10)),
... ]
>>>
>>> delays, cc_matrix = multi_multi_delay(seismograms, abs_max=False)
>>> delays.shape
(3, 3)
>>> # delay of seismogram 1 relative to seismogram 0:
>>> pd.Timedelta(delays[0, 1]).total_seconds()
5.0
>>> # delay of seismogram 2 relative to seismogram 0:
>>> pd.Timedelta(delays[0, 2]).total_seconds()
-10.0
>>> # antisymmetric: delays[i, j] == -delays[j, i]
>>> pd.Timedelta(delays[1, 0]).total_seconds()
-5.0
>>>
Source code in src/pysmo/tools/signal/_delay.py
def multi_multi_delay(
    seismograms: Sequence[Seismogram],
    abs_max: bool,
) -> tuple[npt.NDArray[np.timedelta64], npt.NDArray[np.floating]]:
    """Calculates pairwise delays and correlation coefficients for a sequence of seismograms.

    This function cross-correlates every seismogram with every other seismogram
    in the sequence using FFT-based cross-correlation. All FFTs are computed once
    and combined via broadcasting, making this significantly faster than calling
    [`delay`][pysmo.tools.signal.delay] for each pair individually.

    The result at `delays[i, j]` is the delay of seismogram `j` relative to
    seismogram `i` (treating `i` as the reference). The delay matrix is
    antisymmetric: `delays[i, j] == -delays[j, i]`, and the diagonal is zero.

    Note:
        Unlike most pysmo functions, this returns `numpy.timedelta64` values
        rather than [`Timedelta`][pandas.Timedelta]. This avoids the overhead
        of an object array and allows efficient vectorised arithmetic in
        downstream functions such as [`mccc`][pysmo.tools.signal.mccc].
        Convert individual elements with `pandas.Timedelta(delays[i, j])` if
        needed.

    Args:
        seismograms: Sequence of Seismogram objects.
        abs_max: If `True`, uses absolute max correlation (polarity insensitive).

    Returns:
        delays: 2D array of shape `(N, N)` with delay times as
            `numpy.timedelta64` values, where `N = len(seismograms)`.
        cc_matrix: 2D array of shape `(N, N)` with correlation coefficients.

    Raises:
        ValueError: If any seismogram has a different sampling rate than the others.

    Note:
        Seismograms with zero standard deviation (i.e. constant data) cannot be
        meaningfully normalised. A `UserWarning` is issued for each such trace and
        its normalised values are treated as zero, resulting in correlation
        coefficients of 0 for all pairs involving that trace.

    Examples:
        Create seismograms with known shifts and compute all pairwise delays:

        ```python
        >>> from pysmo import MiniSeismogram
        >>> from pysmo.tools.signal import multi_multi_delay
        >>> import pandas as pd
        >>> import numpy as np
        >>>
        >>> data = np.sin(np.linspace(0, 8 * np.pi, 1000))
        >>> seismograms = [
        ...     MiniSeismogram(data=data.copy()),
        ...     MiniSeismogram(data=np.roll(data, 5)),
        ...     MiniSeismogram(data=np.roll(data, -10)),
        ... ]
        >>>
        >>> delays, cc_matrix = multi_multi_delay(seismograms, abs_max=False)
        >>> delays.shape
        (3, 3)
        >>> # delay of seismogram 1 relative to seismogram 0:
        >>> pd.Timedelta(delays[0, 1]).total_seconds()
        5.0
        >>> # delay of seismogram 2 relative to seismogram 0:
        >>> pd.Timedelta(delays[0, 2]).total_seconds()
        -10.0
        >>> # antisymmetric: delays[i, j] == -delays[j, i]
        >>> pd.Timedelta(delays[1, 0]).total_seconds()
        -5.0
        >>>
        ```
    """
    n = len(seismograms)
    if n < 2:
        return np.empty((n, n), dtype="timedelta64[ns]"), np.empty((n, n), dtype=float)

    _check_same_delta(seismograms[0], seismograms)

    lengths = np.array([len(s.data) for s in seismograms])
    max_len = int(lengths.max())

    # pad to avoid circular convolution artefacts
    n_fft = next_fast_len(2 * max_len - 1)

    # normalise and pad all seismograms
    data_matrix = np.zeros((n, n_fft), dtype=float)
    for i, s in enumerate(seismograms):
        data = s.data
        std = np.std(data)
        if std == 0:
            warnings.warn(
                f"Seismogram at index {i} has zero standard deviation (constant data). "
                "Its cross-correlation coefficients will be zero for all pairs.",
                UserWarning,
                stacklevel=2,
            )
            std = 1.0
        data_matrix[i, : len(data)] = (data - np.mean(data)) / std

    # forward FFT (computed once for all seismograms)
    s_freq = rfft(data_matrix, n=n_fft, axis=1)

    # cross-correlation via broadcasting: (N, 1, freq) * (1, N, freq)
    # row i = reference, column j = target
    cc_freq = s_freq[np.newaxis, :, :] * np.conj(s_freq[:, np.newaxis, :])

    # inverse FFT & scale by reference length
    cc_matrix = irfft(cc_freq, n=n_fft, axis=2)
    cc_matrix /= lengths[:, np.newaxis, np.newaxis]

    # find maxima
    if abs_max:
        max_indices = np.argmax(np.abs(cc_matrix), axis=2)
    else:
        max_indices = np.argmax(cc_matrix, axis=2)

    # convert circular indices to signed lags
    mid_point = n_fft // 2
    signed_lags = np.where(max_indices <= mid_point, max_indices, max_indices - n_fft)
    # Array multiplication converts pandas.Timedelta to numpy.timedelta64
    delays = signed_lags * seismograms[0].delta

    # extract coefficients at max indices
    i_idx, j_idx = np.meshgrid(np.arange(n), np.arange(n), indexing="ij")
    ccs = cc_matrix[i_idx, j_idx, max_indices]

    return delays, ccs

psd

psd(
    seismogram: Seismogram,
    nperseg: int,
    nfft: int,
    scaling: str = "density",
) -> tuple[ndarray, ndarray]

Calculate the Power Spectral Density (PSD) of a Seismogram using Welch's method.

This is a convenience wrapper around welch.

Parameters:

Name Type Description Default
seismogram Seismogram

The Seismogram object.

required
nperseg int

Length of each segment for Welch's method.

required
nfft int

Length of the FFT used.

required
scaling str

The scaling method for the PSD. Defaults to "density".

'density'

Returns:

Type Description
ndarray

A tuple containing the frequencies and the Power Spectral Density.

ndarray

The f=0Hz component is dropped to avoid division by zero in subsequent

tuple[ndarray, ndarray]

calculations.

Source code in src/pysmo/tools/signal/_spectral.py
def psd(
    seismogram: Seismogram, nperseg: int, nfft: int, scaling: str = "density"
) -> tuple[np.ndarray, np.ndarray]:
    """Calculate the Power Spectral Density (PSD) of a Seismogram using Welch's method.

    This is a convenience wrapper around [`welch`][scipy.signal.welch].

    Args:
        seismogram: The Seismogram object.
        nperseg: Length of each segment for Welch's method.
        nfft: Length of the FFT used.
        scaling: The scaling method for the PSD. Defaults to "density".

    Returns:
        A tuple containing the frequencies and the Power Spectral Density.
        The f=0Hz component is dropped to avoid division by zero in subsequent
        calculations.
    """
    sampling_frequency = 1 / seismogram.delta.total_seconds()
    freqs, psd_values = signal.welch(  # type: ignore[call-overload]
        seismogram.data,
        fs=sampling_frequency,
        nperseg=nperseg,
        nfft=nfft,
        scaling=scaling,
    )
    # Drop f=0Hz to avoid dividing by 0
    return freqs[1:], psd_values[1:]

remove_response

remove_response(
    seismogram: T,
    response: Response,
    pre_filt: (
        tuple[float, float, float, float] | None
    ) = None,
    clone: bool = False,
) -> T | None

Remove an instrument response from a seismogram.

Two modes are available, chosen by whether pre_filt is given:

pre_filt=None (default) — sensitivity-only division. Divides seismogram.data by response.reference_sensitivity alone, in the time domain. No FFT, no frequency-dependent correction: this is only correct where the true instrument response is flat with \(\approx 0\) phase, i.e. within the sensor's own passband, and is appropriate when the signal of interest is confined to that flat band (the common case for a well-chosen broadband instrument). It will not correct roll-off near the sensor's corner frequencies or any digital decimation stages; for that, use pre_filt. Note this divides by reference_sensitivity, not overall_sensitivity — the latter has the analog stage's \(A_0\) normalisation factor folded in (see Response.overall_sensitivity).

For a SacPZ-derived response, this path's output is typically not in the units input_units declares: by SAC convention (followed by e.g. the EarthScope SACPZ web service and rdseed -p), the SENSITIVITY header (reference_sensitivity) stays in the sensor's native units (e.g. M/S**2 for an accelerometer), while poles/zeros/overall_sensitivity — and therefore input_units, and the full-deconvolution path below — are normalised to displacement. This is a convention of the producer, not something SacPZ/parse_sacpz enforce or verify — a hand-written SAC PZ file that doesn't follow it will not exhibit this split. A StationXML-derived response has no such split: both paths agree with input_units.

pre_filt given — spectral deconvolution. Deconvolves seismogram.data by the instrument response's full complex transfer function \(H(f)\), applying a four-corner cosine taper \(\text{taper}(f)\):

\[Y(f) = X(f) \cdot \frac{\text{taper}(f)}{H(f)}\]

The effective filter response \(\frac{\text{taper}(f)}{H(f)}\) is forced to zero outside \((f_1, f_4)\) (skipping division by \(H(f)\) where \(\text{taper}(f) = 0\)), and cosine-tapered at the edges (\(f_1 < f_2 \le f_3 < f_4\), in Hz), so frequencies excluded from the passband are never amplified. There is no additional stabilisation: if \(H(f)\) is zero or very small at a frequency inside \((f_1, f_4)\), division amplifies noise without limit, and an exact zero produces non-finite values (\(\infty\) or \(\text{NaN}\)) that poison the entire output once inverse-transformed. Consequently, \(f_1\) must remain strictly above 0 Hz, since velocity- and acceleration-output sensors have a zero at DC by construction (2 or 3 zeros at the origin, respectively — that is what makes it a velocity/acceleration sensor, not a displacement one).

The right bound for \(f_4\) also depends on whether response actually carries digital FIR/IIR decimation stages — not just whether it satisfies StagedResponse, since e.g. StationXML always satisfies that protocol but its stages is empty for a document with no digital stage on record:

  • No digital stages (stages empty, e.g. a SAC PZ-derived response, or a StationXML document without one): only the analog poles/zeros/sensitivity go into \(H(f)\). Pushing \(f_4\) above roughly 80% of the seismogram's own Nyquist frequency triggers the UserWarning described below — the analog-only approximation ignores the roll-off and phase a real digitiser's decimation filter would otherwise contribute near its own Nyquist.
  • Digital stages present (stages non-empty): they are folded into \(H(f)\) too, so \(f_4\) should also stay clear of their own cutoff — bound it by the stages' own Nyquist (half their input_sample_rate), not just the seismogram's, since a stage's own zeros cluster in its stopband near/above that frequency. Stages are also assumed to have had their own filter delay already corrected out of the recorded data (ResponseStage.correction, matching FDSN StationXML's Decimation/Correction, as is standard for archived data) — if that assumption doesn't hold for a given response, the deconvolved output will carry a spurious time shift equal to that correction.

No other preprocessing is performed in the deconvolution path: seismogram.data is not zero-padded, demeaned, detrended, or tapered in the time domain before the FFT. Since rfft/irfft implicitly treat the data as one period of a periodic signal, an uncorrected mean/trend or an abrupt jump between the segment's start and end will produce wraparound artefacts in the deconvolved output rather than being cleanly removed. Detrend and taper the seismogram first (e.g. with pysmo.functions.detrend and pysmo.functions.taper), as is standard practice before any FFT-based deconvolution.

Parameters:

Name Type Description Default
seismogram T

The seismogram to deconvolve.

required
response Response

The instrument response to remove. Output is in whatever physical units response.input_units declares; no unit conversion is performed (see integrate/ differentiate to convert between displacement/velocity/acceleration afterwards).

required
pre_filt tuple[float, float, float, float] | None

Optional four corner frequencies \((f_1, f_2, f_3, f_4)\) in Hz defining a cosine taper applied before division: zero below \(f_1\), cosine ramp up to \(f_2\), flat through \([f_2, f_3]\), cosine ramp down to \(f_4\), zero above \(f_4\). None (the default) skips spectral deconvolution entirely and instead divides by response.reference_sensitivity in the time domain — see above. Not derived automatically — see Examples for how to choose a starting point.

None
clone bool

Operate on a clone of the input seismogram.

False

Returns:

Type Description
T | None

Processed Seismogram object if called with

T | None

clone=True.

Raises:

Type Description
ValueError

If seismogram.data is empty; if pre_filt is None and response.reference_sensitivity is also None; or, when pre_filt is given, if its lower corner \(f_1\) is not above 0, its corners are not strictly increasing (\(f_1 < f_2 \le f_3 < f_4\)), or its upper corner exceeds the seismogram's Nyquist frequency.

Warns:

Type Description
UserWarning

If pre_filt is given and response's stages is empty (whether because it does not satisfy StagedResponse at all, as is always the case for a response parsed from a SAC PZ file, or because it does but has no digital stage on record) and pre_filt's upper corner is above a conservative 80% of the seismogram's own Nyquist frequency (a heuristic margin, not a precise bound) — the analog-only approximation gets progressively less accurate towards Nyquist, where a real digitiser's decimation filter would otherwise contribute roll-off and phase. Or, if stages is non-empty and pre_filt's upper corner is above 80% of the slowest stage's own Nyquist frequency (half its input_sample_rate) — beyond that point scipy.signal.freqz wraps around and returns an aliased value for that stage instead of its actual roll-off.

Examples:

The examples below build on the same setup: example.sac's own real response — a broadband seismometer and digitiser, from a genuine StationXML document for the actual station and epoch that recorded it.

Sensitivity-only division:

>>> from pathlib import Path
>>> from pysmo.classes import SAC, StationXML
>>> from pysmo.tools.signal import remove_response
>>> xml = Path("example_response.xml").read_bytes()
>>> original = SAC.from_file("example.sac").seismogram
>>> response = StationXML.from_bytes(xml, time=original.begin_time)
>>> seismogram = remove_response(original, response, clone=True)
>>> len(seismogram.data) == len(original.data)
True
>>>

Full spectral deconvolution, detrended and tapered first to avoid the wraparound artefacts described above. \(f_4\) is bounded by both the seismogram's own Nyquist and the digital stages' (a stage is only meaningful up to half its own input_sample_rate); \(f_1\) is read off the analog poles' own corner, below which deconvolution mostly amplifies sensor noise. Neither bound is computed automatically — the right choice is study-dependent (e.g. teleseismic earthquakes vs. ambient noise), so this is left to the caller:

>>> from pysmo.functions import detrend, taper
>>> nyquist = 0.5 / original.delta.total_seconds()
>>> stage_nyquist = min(stage.input_sample_rate / 2 for stage in response.stages)
>>> f4 = 0.8 * min(nyquist, stage_nyquist)
>>> f3 = f4 * 0.9
>>> f1 = min(abs(pole) for pole in response.poles if pole != 0) / 10
>>> f2 = f1 * 10
>>> pre_filt = (f1, f2, f3, f4)
>>> prepped = detrend(original, clone=True)
>>> taper(prepped, 0.05)
>>> deconvolved = remove_response(prepped, response, pre_filt=pre_filt, clone=True)
>>> len(deconvolved.data) == len(original.data)
True
>>>

Tip

\(f_1\)\(f_4\) above are chosen from the instrument and the sampling rate — but deconvolution divides by the response across that whole band, so what actually determines whether the result is trustworthy is the data's own amplitude at each of those frequencies, not just where the instrument and sample rate look reasonable on paper. A technically-defensible pre_filt can still amplify noise into a poor result if the data itself has little real amplitude somewhere within that band.

With the earthquake's own dominant period band sitting well within response's flat passband, the sensitivity-only and full-deconvolution paths agree closely in both amplitude and shape:

>>> import numpy as np
>>> gain_only = remove_response(prepped, response, clone=True)
>>> gain_only_rms = np.sqrt(np.mean(gain_only.data**2))
>>> deconvolved_rms = np.sqrt(np.mean(deconvolved.data**2))
>>> round(float(gain_only_rms / deconvolved_rms), 3)  # ~1: amplitude match
1.082
>>> round(float(np.corrcoef(gain_only.data, deconvolved.data)[0, 1]), 3)  # ~1: shape match
0.926
>>>

Seeing the two paths plotted together makes that agreement concrete rather than abstract:

>>> from pysmo.tools.plotutils import plotseis
>>> fig = plotseis(gain_only, deconvolved)
>>> _ = fig.gca().set_ylabel(f"Velocity ({response.input_units})")
>>> _ = fig.gca().legend(["Sensitivity only", "Full deconvolution"])
>>>
Sensitivity-only vs full deconvolution Sensitivity-only vs full deconvolution
Source code in src/pysmo/tools/signal/_response.py
def remove_response[T: Seismogram](
    seismogram: T,
    response: Response,
    pre_filt: tuple[float, float, float, float] | None = None,
    clone: bool = False,
) -> T | None:
    r"""Remove an instrument response from a seismogram.

    Two modes are available, chosen by whether `pre_filt` is given:

    **`pre_filt=None` (default) — sensitivity-only division.** Divides
    `seismogram.data` by `response.reference_sensitivity` alone, in the time
    domain. No FFT, no frequency-dependent correction: this is only correct
    where the true instrument response is flat with $\approx 0$ phase, i.e. within
    the sensor's own passband, and is appropriate when the signal of interest
    is confined to that flat band (the common case for a well-chosen broadband
    instrument). It will *not* correct roll-off near the sensor's corner
    frequencies or any digital decimation stages; for that, use `pre_filt`.
    Note this divides by `reference_sensitivity`, not `overall_sensitivity` —
    the latter has the analog stage's $A_0$ normalisation factor folded in (see
    [`Response.overall_sensitivity`][pysmo.Response.overall_sensitivity]).

    For a [`SacPZ`][pysmo.classes.SacPZ]-derived `response`, this path's output
    is typically *not* in the units `input_units` declares: by SAC convention
    (followed by e.g. the EarthScope SACPZ web service and `rdseed -p`), the
    `SENSITIVITY` header (`reference_sensitivity`) stays in the sensor's
    native units (e.g. `M/S**2` for an accelerometer), while
    `poles`/`zeros`/`overall_sensitivity` — and therefore `input_units`, and
    the full-deconvolution path below — are normalised to displacement. This
    is a convention of the *producer*, not something `SacPZ`/`parse_sacpz`
    enforce or verify — a hand-written SAC PZ file that doesn't follow it will
    not exhibit this split. A [`StationXML`][pysmo.classes.StationXML]-derived
    `response` has no such split: both paths agree with `input_units`.

    **`pre_filt` given — spectral deconvolution.** Deconvolves `seismogram.data`
    by the instrument response's full complex transfer function $H(f)$,
    applying a four-corner cosine taper $\text{taper}(f)$:

    $$Y(f) = X(f) \cdot \frac{\text{taper}(f)}{H(f)}$$

    The effective filter response $\frac{\text{taper}(f)}{H(f)}$ is forced to
    zero outside $(f_1, f_4)$ (skipping division by $H(f)$ where $\text{taper}(f) = 0$),
    and cosine-tapered at the edges ($f_1 < f_2 \le f_3 < f_4$, in Hz), so frequencies
    excluded from the passband are never amplified. There is no additional
    stabilisation: if $H(f)$ is zero or very small at a frequency inside
    $(f_1, f_4)$, division amplifies noise without limit, and an exact zero
    produces non-finite values ($\infty$ or $\text{NaN}$) that poison the entire
    output once inverse-transformed. Consequently, $f_1$ must remain strictly
    above 0 Hz, since velocity- and acceleration-output sensors have a zero at DC
    by construction (2 or 3 zeros at the origin, respectively — that is what makes
    it a velocity/acceleration sensor, not a displacement one).

    The right bound for $f_4$ also depends on whether `response` actually carries
    digital FIR/IIR decimation stages — not just whether it satisfies
    [`StagedResponse`][pysmo.StagedResponse], since e.g.
    [`StationXML`][pysmo.classes.StationXML] always satisfies that protocol but its
    `stages` is empty for a document with no digital stage on record:

    - **No digital stages** (`stages` empty, e.g. a SAC PZ-derived response, or a
      `StationXML` document without one): only the analog poles/zeros/sensitivity go
      into $H(f)$. Pushing $f_4$ above roughly 80% of the seismogram's own Nyquist
      frequency triggers the `UserWarning` described below — the analog-only
      approximation ignores the roll-off and phase a real digitiser's decimation
      filter would otherwise contribute near its own Nyquist.
    - **Digital stages present** (`stages` non-empty): they are folded into $H(f)$
      too, so $f_4$ should also stay clear of their own cutoff — bound it by the
      stages' own Nyquist (half their `input_sample_rate`), not just the
      seismogram's, since a stage's own zeros cluster in its stopband near/above
      that frequency. Stages are also assumed to have had their own filter delay
      already corrected out of the recorded data (`ResponseStage.correction`,
      matching FDSN StationXML's `Decimation/Correction`, as is standard for
      archived data) — if that assumption doesn't hold for a given `response`,
      the deconvolved output will carry a spurious time shift equal to that
      correction.

    No other preprocessing is performed in the deconvolution path:
    `seismogram.data` is not zero-padded, demeaned, detrended, or tapered in
    the time domain before the FFT. Since `rfft`/`irfft` implicitly treat
    the data as one period of a periodic signal, an uncorrected mean/trend
    or an abrupt jump between the segment's start and end will produce
    wraparound artefacts in the deconvolved output rather than being cleanly
    removed. Detrend and taper the seismogram first (e.g. with
    [`pysmo.functions.detrend`][] and
    [`pysmo.functions.taper`][]), as is standard
    practice before any FFT-based deconvolution.

    Args:
        seismogram: The seismogram to deconvolve.
        response: The instrument response to remove. Output is in whatever
            physical units `response.input_units` declares; no unit
            conversion is performed (see
            [`integrate`][pysmo.tools.signal.integrate]/
            [`differentiate`][pysmo.tools.signal.differentiate] to convert
            between displacement/velocity/acceleration afterwards).
        pre_filt: Optional four corner frequencies $(f_1, f_2, f_3, f_4)$ in Hz
            defining a cosine taper applied before division: zero below
            $f_1$, cosine ramp up to $f_2$, flat through $[f_2, f_3]$, cosine
            ramp down to $f_4$, zero above $f_4$. `None` (the default) skips
            spectral deconvolution entirely and instead divides by
            `response.reference_sensitivity` in the time domain — see above.
            Not derived automatically — see Examples for how to choose a
            starting point.
        clone: Operate on a clone of the input seismogram.

    Returns:
        Processed [`Seismogram`][pysmo.Seismogram] object if called with
        `clone=True`.

    Raises:
        ValueError: If `seismogram.data` is empty; if `pre_filt` is `None`
            and `response.reference_sensitivity` is also `None`; or, when
            `pre_filt` is given, if its lower corner $f_1$ is not above 0, its
            corners are not strictly increasing ($f_1 < f_2 \le f_3 < f_4$), or
            its upper corner exceeds the seismogram's Nyquist frequency.

    Warns:
        UserWarning: If `pre_filt` is given and `response`'s `stages` is
            empty (whether because it does not satisfy
            [`StagedResponse`][pysmo.StagedResponse] at all, as is always
            the case for a response parsed from a SAC PZ file, or because it
            does but has no digital stage on record) and `pre_filt`'s upper
            corner is above a conservative 80% of the seismogram's own
            Nyquist frequency (a heuristic margin, not a precise bound) —
            the analog-only approximation gets progressively less accurate
            towards Nyquist, where a real digitiser's decimation filter
            would otherwise contribute roll-off and phase. Or, if `stages`
            is non-empty and `pre_filt`'s upper corner is above 80% of the
            slowest stage's own Nyquist frequency (half its
            `input_sample_rate`) — beyond that point `scipy.signal.freqz`
            wraps around and returns an aliased value for that stage instead
            of its actual roll-off.

    Examples:
        The examples below build on the same setup: `example.sac`'s own real
        response — a broadband seismometer and digitiser, from a genuine StationXML
        document for the actual station and epoch that recorded it.

        Sensitivity-only division:

        ```python
        >>> from pathlib import Path
        >>> from pysmo.classes import SAC, StationXML
        >>> from pysmo.tools.signal import remove_response
        >>> xml = Path("example_response.xml").read_bytes()
        >>> original = SAC.from_file("example.sac").seismogram
        >>> response = StationXML.from_bytes(xml, time=original.begin_time)
        >>> seismogram = remove_response(original, response, clone=True)
        >>> len(seismogram.data) == len(original.data)
        True
        >>>
        ```

        Full spectral deconvolution, detrended and tapered first to avoid the
        wraparound artefacts described above. $f_4$ is bounded by both the
        seismogram's own Nyquist and the digital stages' (a stage is only meaningful
        up to half its own `input_sample_rate`); $f_1$ is read off the analog poles'
        own corner, below which deconvolution mostly amplifies sensor noise. Neither
        bound is computed automatically — the right choice is study-dependent (e.g.
        teleseismic earthquakes vs. ambient noise), so this is left to the caller:

        ```python
        >>> from pysmo.functions import detrend, taper
        >>> nyquist = 0.5 / original.delta.total_seconds()
        >>> stage_nyquist = min(stage.input_sample_rate / 2 for stage in response.stages)
        >>> f4 = 0.8 * min(nyquist, stage_nyquist)
        >>> f3 = f4 * 0.9
        >>> f1 = min(abs(pole) for pole in response.poles if pole != 0) / 10
        >>> f2 = f1 * 10
        >>> pre_filt = (f1, f2, f3, f4)
        >>> prepped = detrend(original, clone=True)
        >>> taper(prepped, 0.05)
        >>> deconvolved = remove_response(prepped, response, pre_filt=pre_filt, clone=True)
        >>> len(deconvolved.data) == len(original.data)
        True
        >>>
        ```

        !!! tip

            $f_1$–$f_4$ above are chosen from the instrument and the
            sampling rate — but deconvolution divides by the response
            across that whole band, so what actually determines whether the
            result is trustworthy is the *data's* own amplitude at each of
            those frequencies, not just where the instrument and sample
            rate look reasonable on paper. A technically-defensible
            `pre_filt` can still amplify noise into a poor result if the
            data itself has little real amplitude somewhere within that
            band.

        With the earthquake's own dominant period band sitting well within
        `response`'s flat passband, the sensitivity-only and full-deconvolution paths
        agree closely in both amplitude and shape:

        ```python
        >>> import numpy as np
        >>> gain_only = remove_response(prepped, response, clone=True)
        >>> gain_only_rms = np.sqrt(np.mean(gain_only.data**2))
        >>> deconvolved_rms = np.sqrt(np.mean(deconvolved.data**2))
        >>> round(float(gain_only_rms / deconvolved_rms), 3)  # ~1: amplitude match
        1.082
        >>> round(float(np.corrcoef(gain_only.data, deconvolved.data)[0, 1]), 3)  # ~1: shape match
        0.926
        >>>
        ```

        Seeing the two paths plotted together makes that agreement concrete
        rather than abstract:

        ```python
        >>> from pysmo.tools.plotutils import plotseis
        >>> fig = plotseis(gain_only, deconvolved)
        >>> _ = fig.gca().set_ylabel(f"Velocity ({response.input_units})")
        >>> _ = fig.gca().legend(["Sensitivity only", "Full deconvolution"])
        >>>
        ```

        <!-- invisible-code-block: python
        ```
        >>> import matplotlib.pyplot as plt
        >>> plt.close("all")
        >>> if savedir:
        ...     plt.style.use("dark_background")
        ...     fig = plotseis(gain_only, deconvolved)
        ...     _ = fig.gca().set_ylabel(f"Velocity ({response.input_units})")
        ...     _ = fig.gca().legend(["Sensitivity only", "Full deconvolution"])
        ...     fig.savefig(
        ...         savedir / "response_removal_comparison-dark.png",
        ...         transparent=True,
        ...         bbox_inches="tight",
        ...     )
        ...
        ...     plt.style.use("default")
        ...     fig = plotseis(gain_only, deconvolved)
        ...     _ = fig.gca().set_ylabel(f"Velocity ({response.input_units})")
        ...     _ = fig.gca().legend(["Sensitivity only", "Full deconvolution"])
        ...     fig.savefig(
        ...         savedir / "response_removal_comparison.png",
        ...         transparent=True,
        ...         bbox_inches="tight",
        ...     )
        >>>
        ```
        -->

        <figure markdown="span">
        ![Sensitivity-only vs full deconvolution](../../../images/sybil/response_removal_comparison.png#only-light){ loading=lazy }
        ![Sensitivity-only vs full deconvolution](../../../images/sybil/response_removal_comparison-dark.png#only-dark){ loading=lazy }
        </figure>
    """
    if len(seismogram.data) == 0:
        raise ValueError("Cannot remove response from an empty seismogram.")

    if pre_filt is None:
        if response.reference_sensitivity is None:
            raise ValueError(
                "remove_response's sensitivity-only path (pre_filt=None) "
                "requires response.reference_sensitivity, which is None on "
                "this response. overall_sensitivity is not a substitute: it "
                "has response's A0 normalisation factor folded in and would "
                "mis-scale the result. Either supply reference_sensitivity "
                "(SAC PZ's SENSITIVITY header or StationXML's "
                "InstrumentSensitivity/Value) or pass pre_filt for full "
                "spectral deconvolution, which only needs overall_sensitivity."
            )
        if clone:
            seismogram = deepcopy(seismogram)
        seismogram.data = seismogram.data / response.reference_sensitivity
        return seismogram if clone else None

    dt = seismogram.delta.total_seconds()
    nyquist = 0.5 / dt

    f1, f2, f3, f4 = pre_filt
    if f1 <= 0:
        raise ValueError(
            f"pre_filt's lower corner ({f1}) must be above 0: a velocity- or "
            "acceleration-output sensor has a zero at DC by construction, so "
            "f1 <= 0 would divide by that zero."
        )
    if not (f1 < f2 <= f3 < f4):
        raise ValueError(
            f"pre_filt corners {pre_filt} must satisfy f1 < f2 <= f3 < f4."
        )
    if f4 > nyquist:
        raise ValueError(
            f"pre_filt's upper corner ({f4}) exceeds the seismogram's "
            f"Nyquist frequency ({nyquist})."
        )

    if clone:
        seismogram = deepcopy(seismogram)

    freqs = np.fft.rfftfreq(len(seismogram.data), d=dt)

    h = _analog_transfer_function(response, freqs)

    if isinstance(response, StagedResponse):
        h = h * _digital_transfer_function(response, freqs)
        has_stages = bool(response.stages)
        if has_stages:
            stage_nyquist = (
                min(stage.input_sample_rate for stage in response.stages) / 2
            )
            if f4 > 0.8 * stage_nyquist:
                warnings.warn(
                    "pre_filt's upper corner is above 80% of the digital "
                    "stages' own Nyquist frequency (half the slowest "
                    "stage's input_sample_rate): scipy.signal.freqz is "
                    "periodic, so evaluating a decimation stage beyond its "
                    "own Nyquist returns an aliased, non-physical value "
                    "rather than the stage's actual roll-off. Bound f4 by "
                    "min(seismogram_nyquist, stage_nyquist) instead.",
                    UserWarning,
                    stacklevel=2,
                )
    else:
        has_stages = False

    if not has_stages and f4 > 0.8 * nyquist:
        warnings.warn(
            "pre_filt's upper corner is above 80% of the Nyquist "
            "frequency, but response has no digital stages (e.g. a SAC "
            "PZ-derived response): the analog-only approximation does "
            "not account for the roll-off/phase a real digitiser's "
            "decimation filter contributes near its own Nyquist.",
            UserWarning,
            stacklevel=2,
        )

    taper = _pre_filt_taper(freqs, pre_filt)
    # Frequencies outside (f1, f4) are already excluded by the taper (0
    # there); dividing by h at those points is pointless and, if h is
    # also 0 (e.g. DC for a sensor with a zero at the origin), would turn
    # a harmless 0 into 0/0 = nan. Skip the division wherever taper == 0.
    filt = np.divide(
        taper, h, out=np.zeros_like(taper, dtype=complex), where=taper != 0
    )

    spectrum = np.fft.rfft(seismogram.data)
    seismogram.data = np.fft.irfft(spectrum * filt, n=len(seismogram.data))

    return seismogram if clone else None