Skip to content

pulsedet

biosigpy.ppg.pulsedet.pulsedet

pulsedet(dppg: ArrayLike, sampling_frequency: float, *, method: str = 'adaptive', adaptive_alpha_amp: float = 0.2, adaptive_refract_period: float = 0.15, adaptive_tau_rr: float = 1.0, reset_after: float | None = None) -> tuple[np.ndarray, np.ndarray]

Return refined pulse maximum-upslope times and an adaptive threshold.

Parameters:

Name Type Description Default
dppg array_like

Nonempty real PPG derivative after low-pass differentiation and any filter-delay compensation. NaNs are allowed; infinities are invalid.

required
sampling_frequency float

Finite positive sampling frequency in Hz.

required
method str

Detection algorithm: "adaptive" (default), case-insensitive.

'adaptive'
adaptive_alpha_amp float

Positive amplitude multiplier defining the threshold floor, default 0.2.

0.2
adaptive_refract_period float

Positive refractory threshold-hold duration in seconds, default 0.15.

0.15
adaptive_tau_rr float

Positive decay duration after the refractory period, expressed as a fraction of the estimated pulse interval. Default is 1.0.

1.0
reset_after float or None

Positive seconds without a raw detection before restarting adaptation. Missing spans count toward elapsed time; initialization resumes when signal is available. None (default) or positive infinity disables resets.

None

Returns:

Name Type Description
t_d ndarray

One-dimensional array of quadratically refined detection times in seconds, with the first input sample at time zero. Undefined refined times are omitted. No detections yields an empty array.

threshold ndarray

One-dimensional adaptive threshold aligned with every input sample.

Notes

Adaptive state is preserved throughout the signal, including NaN spans, unless the optional inactivity reset is enabled. Missing samples do not satisfy crossings, but a crossing region can span them. Raw detections update adaptation even if missing neighbors prevent time refinement.

A finite reset_after can help after a device gain reduction leaves pulses below the previous threshold floor. It is optional and its duration depends on the application. This function does not perform preprocessing.

Source code in src/biosigpy/ppg/pulsedet.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def pulsedet(
    dppg: ArrayLike,
    sampling_frequency: float,
    *,
    method: str = "adaptive",
    adaptive_alpha_amp: float = 0.2,
    adaptive_refract_period: float = 0.15,
    adaptive_tau_rr: float = 1.0,
    reset_after: float | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    """Return refined pulse maximum-upslope times and an adaptive threshold.

    Parameters
    ----------
    dppg : array_like
        Nonempty real PPG derivative after low-pass differentiation and any
        filter-delay compensation. NaNs are allowed; infinities are invalid.
    sampling_frequency : float
        Finite positive sampling frequency in Hz.
    method : str, optional
        Detection algorithm: ``"adaptive"`` (default), case-insensitive.
    adaptive_alpha_amp : float, optional
        Positive amplitude multiplier defining the threshold floor, default 0.2.
    adaptive_refract_period : float, optional
        Positive refractory threshold-hold duration in seconds, default 0.15.
    adaptive_tau_rr : float, optional
        Positive decay duration after the refractory period, expressed as a
        fraction of the estimated pulse interval. Default is 1.0.
    reset_after : float or None, optional
        Positive seconds without a raw detection before restarting adaptation.
        Missing spans count toward elapsed time; initialization resumes when
        signal is available. None (default) or positive infinity disables resets.

    Returns
    -------
    t_d : ndarray
        One-dimensional array of quadratically refined detection times in
        seconds, with the first input sample at time zero. Undefined refined
        times are omitted. No detections yields an empty array.
    threshold : ndarray
        One-dimensional adaptive threshold aligned with every input sample.

    Notes
    -----
    Adaptive state is preserved throughout the signal, including NaN spans,
    unless the optional inactivity reset is enabled. Missing samples do not
    satisfy crossings, but a crossing region can span them. Raw detections
    update adaptation even if missing neighbors prevent time refinement.

    A finite ``reset_after`` can help after a device gain reduction leaves
    pulses below the previous threshold floor. It is optional and its duration
    depends on the application. This function does not perform preprocessing.
    """
    # Parse and validate inputs
    dppg = as_real_vector(dppg, name="dppg")
    fs = as_positive_real_scalar(sampling_frequency, name="sampling_frequency")
    if dppg.size == 0 or np.any(np.isinf(dppg)):
        raise ValueError("dppg must be nonempty and contain finite samples or NaN")
    if not isinstance(method, str) or method.lower() != "adaptive":
        raise ValueError("method must be 'adaptive'")
    alpha_amp = as_positive_real_scalar(adaptive_alpha_amp, name="adaptive_alpha_amp")
    refract_period = as_positive_real_scalar(
        adaptive_refract_period, name="adaptive_refract_period"
    )
    tau_rr = as_positive_real_scalar(adaptive_tau_rr, name="adaptive_tau_rr")
    if reset_after is None:
        reset_after = np.inf
    else:
        reset_value = np.asarray(reset_after)
        if not (reset_value.ndim == 0 and reset_value.dtype.kind in "iuf"
                and np.isposinf(reset_value)):
            reset_after = as_positive_real_scalar(reset_after, name="reset_after")
        else:
            reset_after = np.inf

    # Detect pulses while preserving adaptive state across search blocks
    detection_samples, threshold = _adaptive_threshold(
        dppg, fs, alpha_amp, refract_period, tau_rr, reset_after
    )

    # Remove duplicates and refine detection times
    detection_samples = np.unique(detection_samples)
    t_d = np.empty(0)
    if detection_samples.size:
        left = dppg[detection_samples - 1]
        center = dppg[detection_samples]
        right = dppg[detection_samples + 1]
        with np.errstate(divide="ignore", invalid="ignore"):
            delta = (left - right) / (2 * (left - 2 * center + right))
        t_d = (detection_samples + delta) / fs

    # Remove NaN values from refined detection times
    t_d = t_d[~np.isnan(t_d)]
    return t_d, threshold

Run the pulse detection and optional gain-recovery example.