Skip to content

pressure_valve

← Robust filters

pressure_valve settles the disagreement: it runs all four, weighs them by how confident each one is, and returns one cleaned series, one list of flagged positions, and one pressure score per sample.

The number of days flagged out of 500, for 6 values of soglia_pressione and 6 values of k_molla.

The surface shows how many days the function flags out of 500 on the stream of the example, for 6 values of soglia_pressione, the base threshold, and 6 values of k_molla. The height is the number of days flagged.

A first example: daily order execution cost

The stream is the one of the first example of the section: 500 days of the cost of executing an order, and one bad day, day 250, at 25.0.

import numpy as np
from dense_armor.core.online.anomaly.robust_filters import pressure_valve

rng = np.random.default_rng(0)
cost = 12.0 + 1.5 * rng.standard_normal(500)
cost[250] = 25.0
clean, idx, p, thr = pressure_valve(cost, radius=15)
print(idx, round(float(p[250]), 1), round(float(np.median(thr)), 2))
[250, 303, 478] 15.6 8.48

The function flags three days: day 250, the bad one, with a pressure of 15.6, and two ordinary days, 303 and 478. The median of the threshold over the 500 days is 8.48.

The pressure of each day, the threshold and the flagged days.

The orange line is the pressure of each day, the dashed grey line is the threshold and the pink points are the three flagged days.

The same on a robot

import numpy as np
from dense_armor.core.online.anomaly.robust_filters import pressure_valve

rng = np.random.default_rng(42)
v = 0.5 + 0.1 * rng.standard_normal(3000)
v[1500] = 2.5
clean, idx, p, thr = pressure_valve(v, radius=15)
print(idx, round(float(p[1500]), 1), round(float(np.median(thr)), 2))
[949, 1500, 2707] 42.7 8.46

Of the 3,000 samples, the filter flags three: the collision at 1500 (pressure 42.7) and two noise values at 949 and 2707.

How it works

Like the four filters it returns the cleaned series and the flagged positions, and also the pressure and the threshold of each sample, as explained on the page of Robust filters.

Each of the four methods (Hampel, Tukey fences, Chauvenet, sigma clipping) returns two numbers for every sample. The first is a centre c_k: the method's estimate of the true value at that sample. The second is a scale s_k: the method's estimate of its own uncertainty. Both come from the window around the sample, and the pair differs per method:

method centre c_k scale s_k
Hampel median 1.4826 * MAD
Tukey fences median IQR / 1.349
Chauvenet mean standard deviation
sigma clipping clipped mean standard deviation

The four scales can differ a lot: a method whose window already contains an outlier reports a large scale, a method whose window is clean reports a small one.

pressure_valve weights each centre by the inverse of its variance, so a method that is sure of itself counts more than one that is not. The weight of method k is

\[w_k = \frac{1/s_k^2}{\sum_j 1/s_j^2},\]

the minimum-variance (inverse-variance) combination of independent estimates. No weight is chosen by hand.

import numpy as np

s = np.array([0.10, 0.12, 0.10, 0.30])
w = (1 / s**2) / np.sum(1 / s**2)
print(np.round(w, 3), round(float(1 / np.sqrt(np.sum(1 / s**2))), 4))
[0.356 0.248 0.356 0.04 ] 0.0597

A method with a small scale gets a large weight; a method with a large scale gets a small one. The combined estimate is more precise than any single method, and its scale is

\[s = \frac{1}{\sqrt{\sum_j 1/s_j^2}}.\]

The pressure of a new sample x is how far it lies from the combined centre, measured in units of the combined scale:

\[p = \frac{\left|x - \sum_k w_k c_k\right|}{s}.\]

In the code above the four scales are 0.10, 0.12, 0.10 and 0.30. The method with scale 0.30 gets weight 0.04; the two methods with scale 0.10 get weight 0.36 each. The combined scale is 0.0597, smaller than any of the four. The four weights are the solution of the calculation above, not numbers chosen by hand. This is the minimum-variance combination of independent estimates.

The threshold is not the same at every sample. At each sample it depends on how different the local window looks from a wider reference window of size radius * ref_mult. The difference is measured by the Jensen–Shannon divergence, a number in [0, 1]: near 0 when the two windows have the same shape (steady noise), near 1 when they have different shapes (a real change of level is under way). The threshold is

\[\text{threshold}_i = \text{soglia\_pressione} \cdot (1 + k_{\text{molla}} \cdot \mathrm{JSD}_i),\]

where soglia_pressione (default 8.0) and k_molla are the two parameters of the code.

When the two windows look the same, JSD is near 0 and the threshold stays at its base value, 8.0. When they differ, the threshold rises and the filter tolerates a larger deviation, so a genuine change of level is not flagged as an anomaly. On the 3,000 samples above the median threshold is 8.46.

The parameters

pressure_valve(x, radius=10, soglia_pressione=8.0, n_sigmas=3.0, ref_mult=3, k_molla=3.0)

Parameter Default What it does
x required the whole series, a one-dimensional array
radius 10 half-width of the window, which is centred on each sample: radius = 15 is a window of 31 samples
soglia_pressione 8.0 the base threshold of the pressure
n_sigmas 3.0 the parameter of the internal methods
ref_mult 3 the wider reference window has radius * ref_mult samples
k_molla 3.0 how much the threshold rises when the two windows differ: threshold = soglia_pressione * (1 + k_molla * JSD)

It returns (clean, idx, pressure, threshold): pressure is the combined deviation of each sample and threshold is the threshold actually applied at that sample.

API reference

pressure_valve

pressure_valve(
    x: ndarray,
    radius: int = 10,
    soglia_pressione: float = 8.0,
    n_sigmas: float = 3.0,
    ref_mult: int = 3,
    k_molla: float = 3.0,
) -> tuple[np.ndarray, list[int], np.ndarray, np.ndarray]

Automatic orchestrator of the four detectors above: not a vote (how many methods flag the point), but a CONSTRAINED MINIMUM-VARIANCE combination -- the classic BLUE estimator (Best Linear Unbiased Estimator) of statistics, derived with a Lagrange multiplier.

Each method produces a local (center, scale) pair: Chauvenet uses mean/std (not robust, the original formulation -- the weakness is intended, see below), sigma-clipping uses mean/std iteratively cleaned of the outliers of the window, Hampel uses median/scaled MAD (1.4826*MAD), Tukey uses median/scaled IQR (IQR/1.349, the same constant that makes IQR an estimator of sigma for a Gaussian). Four independent estimates of the same "true" local center, each with its own uncertainty (scale).

Combining them not with a simple mean but by looking for the weights w_k that minimize the VARIANCE of the weighted combination Sum(w_k * centro_k), constrained to Sum(w_k) = 1 (unbiased combination) -- a constrained optimization problem, solved with a Lagrange multiplier lambda: L(w, lambda) = Sum(w_k^2 * scala_k^2) - lambda * (Sum(w_k) - 1) dL/dw_k = 0 => w_k = lambda / (2 * scala_k^2) from the constraint => w_k = (1/scala_k^2) / Sum_j(1/scala_j^2) The result (weight inversely proportional to the SQUARE of its own uncertainty) is the minimum-variance estimator among all unbiased linear combinations of independent estimates (Gauss-Markov) -- it is not a hand-picked weight, it is what the constraint imposes. A method whose scale inflates (e.g. Chauvenet when the window already contains an outlier, its std is not robust) is automatically weighted less, without needing to discard it explicitly.

Caveat: the optimality of these weights holds for INDEPENDENT unbiased estimates whose scales are their standard errors. Here the four estimates are computed on the same window (they are strongly correlated) and each scala_k is the dispersion of the data, not the standard error of the center. The combination is therefore a calibrated heuristic, not a BLUE: scala_combinata is below every scala_k by construction, and soglia_pressione=8.0 is an empirical value.

centro_combinato = Sum(w_k * centro_k) scala_combinata = 1 / sqrt(Sum(1/scala_k^2)) (the same derivation also gives the variance of the combination itself -- ALWAYS narrower than any single scala_k, it is the property that makes combining several independent estimates useful) pressione = |x[i] - centro_combinato| / scala_combinata

A single final threshold (soglia_pressione) decides -- binary trigger, like the rest of this ecosystem (utility/hybrid_engine.py, dense_evolution/healing.py): never a third intermediate state, never a blend between raw and clean. It is no longer a value "in sigma" in the classical sense (scala_combinata is narrower than every scala_k, so the same real deviation produces a higher pressure than with a single method) -- soglia_pressione=8.0 is the default calibrated directly (see test/test_robust_filters.py): on pure Gaussian noise (N=300, fixed seed) the percentiles of the pressure are 50%=1.4, 95%=4.6, 99%=6.0, 99.9%=7.6 -- 8.0 leaves 1/300 false positives while still keeping a true outlier (pressure~88) and a pair of close outliers (pressure~40) well above the threshold with a wide margin. n_sigmas remains the parameter of the internal sigma-clipping sub-step (how many sigma beyond which a neighbor is excluded in the iteration, not the final threshold).

THE SPRING (JSD): the threshold itself is not fixed. At each point the local window (radius radius, the same used by the 4 methods) is compared with a wider reference window (radius radius * ref_mult, default ref_mult=3 -- the same constant as healing_filter.py in this package) via the Jensen-Shannon divergence (_jensen_shannon, 0..1). If the two distributions are similar (stationary noise, no real transition in progress), JSD~0 and the threshold stays soglia_pressione. If they are very different (a true regime transition is in progress: the local window, closer to the new level, no longer resembles the reference window, still dominated by the old one), JSD rises and the threshold widens proportionally: soglia_effettiva[i] = soglia_pressione * (1 + k_molla * JSD[i]) "the spring yields" -- the shield becomes less nervous exactly at the points where a genuine change is more plausible, without ever ceasing to judge in binary (anomaly above soglia_effettiva, nothing else).

_jensen_shannon already uses adaptive n_bins and Laplace smoothing (see its docstring) precisely for this use: on small windows, a "naive" JSD (fixed bins, near-zero epsilon) came out HIGHER on pure stationary noise than near a true transition -- the spring would have activated everywhere, not "only where needed". With the corrected version, verified on low-amplitude stationary noise vs a true step 1.0->5.0 (radius=10, k_molla=3.0): mean soglia_effettiva ~8.3 on stationary noise, ~8.7-8.8 near the transition (higher, right direction) -- still a noisy signal by nature (it never perfectly separates the two tails), but the threshold can only WIDEN (JSD >= 0), never narrow below soglia_pressione: even in the worst case (spring that activates "unnecessarily" on noise), the result is a slightly more permissive shield, never more nervous.

No configuration required from the caller beyond the defaults: designed for a context where whoever reads the result must not choose weights or thresholds per method, only read anomalie/pressione. Verified (test/test_robust_filters.py): few false positives on pure Gaussian noise, detects a true outlier with pressure well above the threshold, does not touch a genuine sustained step.

KNOWN LIMIT, NOW RESOLVED -- mutual masking between close outliers on a nearly flat baseline (test/test_pressure_valve_vs_ orca_experiment.py, scenario "alternating impulses" +/-500 on a constant 120 background, zero real noise): the local window used for each estimate already EXCLUDES point i itself (fix applied below), but if other outliers of the same burst remain in the window (here: radius 10, 3 peaks within 2 steps of each other), median/IQR and median/MAD still stay EXACTLY 0 -- it is not a bug in their implementation, it is mathematically correct: with 18/20 points of the window identical, MAD and IQR (breakdown ~50%/~25%) see nothing anomalous. A Huber M-estimator (IRLS, see Sung et al. 2019, arXiv:1912.04982, used there for 2-qubit spectroscopy with experimental outliers) was tried as an alternative and ALSO converges to scale 0, for the same underlying reason (its final scale is itself a MAD of the residuals). Having read the paper directly (not assumed from the formula): their robust technique works because the scale sigma^2=var(O_tau) is estimated from REPEATED MEASUREMENTS on the SAME point (shot noise, M projective repetitions), a data axis orthogonal to the time window -- not available here (a single scalar series, no repetition per point), so their solution is not portable as it is.

A fallback scale from the wider reference window (radius*ref_mult) was also tried: VERIFIED NOT TO WORK, and for a structural reason, not an implementation error -- widening the window always reduces the FRACTION of outliers over the total (3 points out of 21 local = 14%, 3 out of 61 reference = 5%), so it can never make IQR/MAD (estimators with a fixed fractional breakdown) exceed the breakdown threshold that makes them collapse to zero: verified numerically, both scales stayed 0.0 even on the reference window.

THE REAL CORRECTION: when IQR or MAD truly collapse to zero (genuinely homogeneous local window) but point i still departs from the local median, that is NOT "no information" to discard -- it is the strongest proof possible (real deviation against null local dispersion). The bug was discarding this evidence together with the degenerate estimator. Now: null-local-scale + real deviation => pressure forced to infinity (certain anomaly), bypassing the weighted combination for that point. Verified: on the real scenario "alternating impulses" (+/-500 on a 120 background without noise), before the fix pressure at the 3 peaks = 3.16/5.19/3.16 (below threshold 8.0, zero anomalies, RMSE=86.6); after the fix, all 3 peaks detected, RMSE=0.0. No regression: 223/223 tests of the suite pass, including the false-positive rate on pure Gaussian noise (unchanged) and all the other 6 scenarios of the three-way comparison.

Returns (pulito, anomalie, pressione, soglia_effettiva): pressione is the continuous combined deviation for each point, soglia_effettiva the threshold actually applied at that point (>= soglia_pressione, it shows where/how much the spring yielded).

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> x = rng.normal(0, 1, 60)
>>> x[30] = 50.0
>>> clean, idx, p, thr = pressure_valve(x, radius=5)
>>> 30 in idx
True
>>> abs(float(clean[30])) < 5.0
True
Source code in dense_armor/core/online/anomaly/robust_filters.py
def pressure_valve(
    x: np.ndarray, radius: int = 10, soglia_pressione: float = 8.0, n_sigmas: float = 3.0,
    ref_mult: int = 3, k_molla: float = 3.0,
) -> tuple[np.ndarray, list[int], np.ndarray, np.ndarray]:
    """Automatic orchestrator of the four detectors above: not a vote
    (how many methods flag the point), but a CONSTRAINED MINIMUM-VARIANCE
    combination -- the classic BLUE estimator (Best Linear Unbiased
    Estimator) of statistics, derived with a Lagrange multiplier.

    Each method produces a local (center, scale) pair: Chauvenet uses
    mean/std (not robust, the original formulation -- the weakness is
    intended, see below), sigma-clipping uses mean/std iteratively cleaned
    of the outliers of the window, Hampel uses median/scaled MAD
    (1.4826*MAD), Tukey uses median/scaled IQR (IQR/1.349, the
    same constant that makes IQR an estimator of sigma for a Gaussian).
    Four independent estimates of the same "true" local center, each with
    its own uncertainty (scale).

    Combining them not with a simple mean but by looking for the weights w_k that
    minimize the VARIANCE of the weighted combination Sum(w_k * centro_k),
    constrained to Sum(w_k) = 1 (unbiased combination) -- a
    constrained optimization problem, solved with a Lagrange multiplier
    lambda:
        L(w, lambda) = Sum(w_k^2 * scala_k^2) - lambda * (Sum(w_k) - 1)
        dL/dw_k = 0  =>  w_k = lambda / (2 * scala_k^2)
        from the constraint  =>  w_k = (1/scala_k^2) / Sum_j(1/scala_j^2)
    The result (weight inversely proportional to the SQUARE of its own
    uncertainty) is the minimum-variance estimator among all unbiased
    linear combinations of independent estimates (Gauss-Markov) -- it is not a
    hand-picked weight, it is what the constraint imposes. A method whose
    scale inflates (e.g. Chauvenet when the window already contains an
    outlier, its std is not robust) is automatically weighted less,
    without needing to discard it explicitly.

    Caveat: the optimality of these weights holds for INDEPENDENT unbiased
    estimates whose scales are their standard errors. Here the four
    estimates are computed on the same window (they are strongly correlated)
    and each scala_k is the dispersion of the data, not the standard error of
    the center. The combination is therefore a calibrated heuristic, not a
    BLUE: scala_combinata is below every scala_k by construction, and
    soglia_pressione=8.0 is an empirical value.

    centro_combinato = Sum(w_k * centro_k)
    scala_combinata  = 1 / sqrt(Sum(1/scala_k^2))   (the same derivation
                        also gives the variance of the combination itself --
                        ALWAYS narrower than any single scala_k,
                        it is the property that makes combining several
                        independent estimates useful)
    pressione        = |x[i] - centro_combinato| / scala_combinata

    A single final threshold (soglia_pressione) decides -- binary trigger,
    like the rest of this ecosystem (utility/hybrid_engine.py,
    dense_evolution/healing.py): never a third intermediate state, never a
    blend between raw and clean. It is no longer a value "in sigma" in the
    classical sense (scala_combinata is narrower than every scala_k, so the
    same real deviation produces a higher pressure than with a
    single method) -- soglia_pressione=8.0 is the default calibrated
    directly (see test/test_robust_filters.py): on pure Gaussian noise
    (N=300, fixed seed) the percentiles of the pressure are
    50%=1.4, 95%=4.6, 99%=6.0, 99.9%=7.6 -- 8.0 leaves 1/300 false
    positives while still keeping a true outlier (pressure~88) and a
    pair of close outliers (pressure~40) well above the threshold with a
    wide margin. `n_sigmas` remains the parameter of the internal
    sigma-clipping sub-step (how many sigma beyond which a neighbor is excluded
    in the iteration, not the final threshold).

    THE SPRING (JSD): the threshold itself is not fixed. At each point the local
    window (radius `radius`, the same used by the 4 methods) is compared with
    a wider reference window (radius `radius * ref_mult`,
    default ref_mult=3 -- the same constant as healing_filter.py in this
    package) via the Jensen-Shannon divergence (_jensen_shannon, 0..1).
    If the two distributions are similar (stationary noise, no real
    transition in progress), JSD~0 and the threshold stays soglia_pressione. If
    they are very different (a true regime transition is in progress: the
    local window, closer to the new level, no longer resembles the
    reference window, still dominated by the old one), JSD rises and the
    threshold widens proportionally:
        soglia_effettiva[i] = soglia_pressione * (1 + k_molla * JSD[i])
    "the spring yields" -- the shield becomes less nervous exactly at the points where
    a genuine change is more plausible, without ever ceasing to
    judge in binary (anomaly above soglia_effettiva, nothing else).

    _jensen_shannon already uses adaptive n_bins and Laplace smoothing (see its
    docstring) precisely for this use: on small windows, a "naive" JSD
    (fixed bins, near-zero epsilon) came out HIGHER on pure stationary
    noise than near a true transition -- the spring would have
    activated everywhere, not "only where needed". With the corrected version,
    verified on low-amplitude stationary noise vs a true step
    1.0->5.0 (radius=10, k_molla=3.0): mean soglia_effettiva ~8.3 on
    stationary noise, ~8.7-8.8 near the transition (higher,
    right direction) -- still a noisy signal by nature (it never
    perfectly separates the two tails), but the threshold can only WIDEN
    (JSD >= 0), never narrow below soglia_pressione: even in the
    worst case (spring that activates "unnecessarily" on noise), the result is
    a slightly more permissive shield, never more nervous.

    No configuration required from the caller beyond the defaults: designed
    for a context where whoever reads the result must not choose weights or
    thresholds per method, only read `anomalie`/`pressione`. Verified
    (test/test_robust_filters.py): few false positives on pure Gaussian
    noise, detects a true outlier with pressure well above the threshold,
    does not touch a genuine sustained step.

    KNOWN LIMIT, NOW RESOLVED -- mutual masking between close
    outliers on a nearly flat baseline (test/test_pressure_valve_vs_
    orca_experiment.py, scenario "alternating impulses" +/-500 on a constant
    120 background, zero real noise): the local window used for each
    estimate already EXCLUDES point i itself (fix applied below), but if
    other outliers of the same burst remain in the window (here:
    radius 10, 3 peaks within 2 steps of each other), median/IQR and
    median/MAD still stay EXACTLY 0 -- it is not a bug in their
    implementation, it is mathematically correct: with 18/20 points of the
    window identical, MAD and IQR (breakdown ~50%/~25%) see nothing
    anomalous. A Huber M-estimator (IRLS, see Sung et al. 2019,
    arXiv:1912.04982, used there for 2-qubit spectroscopy with experimental
    outliers) was tried as an alternative and ALSO converges to
    scale 0, for the same underlying reason (its final scale is itself a
    MAD of the residuals). Having read the paper directly (not assumed
    from the formula): their robust technique works because the scale
    sigma^2=var(O_tau) is estimated from REPEATED MEASUREMENTS on the SAME point
    (shot noise, M projective repetitions), a data axis orthogonal
    to the time window -- not available here (a single
    scalar series, no repetition per point), so their solution is
    not portable as it is.

    A fallback scale from the wider reference window (radius*ref_mult)
    was also tried: VERIFIED NOT TO WORK, and for a structural
    reason, not an implementation error -- widening the window
    always reduces the FRACTION of outliers over the total (3 points out of 21
    local = 14%, 3 out of 61 reference = 5%), so it can never make
    IQR/MAD (estimators with a fixed fractional breakdown) exceed the breakdown
    threshold that makes them collapse to zero: verified numerically,
    both scales stayed 0.0 even on the reference window.

    THE REAL CORRECTION: when IQR or MAD truly collapse to zero
    (genuinely homogeneous local window) but point i still departs
    from the local median, that is NOT "no information" to
    discard -- it is the strongest proof possible (real deviation against
    null local dispersion). The bug was discarding this evidence together with
    the degenerate estimator. Now: null-local-scale + real deviation =>
    pressure forced to infinity (certain anomaly), bypassing the
    weighted combination for that point. Verified: on the real scenario
    "alternating impulses" (+/-500 on a 120 background without noise), before the fix
    pressure at the 3 peaks = 3.16/5.19/3.16 (below threshold 8.0, zero
    anomalies, RMSE=86.6); after the fix, all 3 peaks detected,
    RMSE=0.0. No regression: 223/223 tests of the suite pass,
    including the false-positive rate on pure Gaussian noise (unchanged)
    and all the other 6 scenarios of the three-way comparison.

    Returns (pulito, anomalie, pressione, soglia_effettiva): `pressione` is
    the continuous combined deviation for each point, `soglia_effettiva` the
    threshold actually applied at that point (>= soglia_pressione, it shows
    where/how much the spring yielded).

    Examples:
        >>> import numpy as np
        >>> rng = np.random.default_rng(0)
        >>> x = rng.normal(0, 1, 60)
        >>> x[30] = 50.0
        >>> clean, idx, p, thr = pressure_valve(x, radius=5)
        >>> 30 in idx
        True
        >>> abs(float(clean[30])) < 5.0
        True
"""
    x = as_default_array(x)
    n = len(x)
    pressione = np.zeros(n, dtype=get_default_dtype())
    soglia_effettiva = np.full(n, soglia_pressione)

    for i in range(n):
        w_self = _window(x, i, radius)
        if w_self.size < 4:
            continue
        # Point i EXCLUDED from its own window (as only the sigma-clipping
        # sub-step below already did): including it allowed an extreme
        # outlier to inflate its own reference scale
        # (masking) -- verified on isolated impulses
        # (+/-500 on a constant 120 background): with the self-inclusive window, maximum
        # pressure 4.6 (below any threshold, zero anomalies detected);
        # with the exclusive window, the outlier no longer contaminates the scale
        # it is judged with.
        w = np.delete(w_self, min(i - max(0, i - radius), w_self.size - 1))
        w_riferimento = _window(x, i, radius * ref_mult)

        centri, scale = [], []

        mu, sigma = float(np.mean(w)), float(np.std(w))
        if sigma > 1e-12:
            centri.append(mu)
            scale.append(sigma)

        med = float(np.median(w))
        q1, q3 = np.percentile(w, [25, 75])
        iqr_scale = (q3 - q1) / 1.349
        if iqr_scale > 1e-12:
            centri.append(med)
            scale.append(iqr_scale)

        mad = float(np.median(np.abs(w - med)))
        scaled_mad = 1.4826 * mad
        if scaled_mad > 1e-12:
            centri.append(med)
            scale.append(scaled_mad)

        # Zero-scale-is-certain-evidence: if IQR or MAD truly collapse to
        # zero (genuinely homogeneous local window, >=25%/>=50% of the
        # points identical) BUT point i still departs from the center, it is not
        # "no information" to discard -- it is the strongest proof
        # possible (real deviation against null local dispersion).
        # The bug of the original "KNOWN LIMIT" was exactly discarding this
        # evidence together with the degenerate estimator. Not attempted: a
        # fallback scale from the wider reference window (tried and
        # verified NOT to work -- see below: widening the window
        # always reduces the fraction of outliers, it can never revive
        # a statistic with a fixed fractional breakdown point). Verified on the
        # real "alternating impulses" scenario (test/test_pressure_valve_vs_
        # orca_experiment.py, +/-500 on a 120 background without noise): before
        # this fix, pressure at the 3 peaks = 3.16/5.19/3.16 (below threshold
        # 8.0, zero anomalies, RMSE=86.6); with this fix, all 3
        # peaks detected, RMSE=0.0.
        scala_locale_nulla = (iqr_scale <= 1e-12) or (scaled_mad <= 1e-12)
        if scala_locale_nulla and abs(x[i] - med) > 1e-9:
            pressione[i] = float("inf")
            continue

        neighbor_idx = [j for j in range(max(0, i - radius), min(n, i + radius + 1)) if j != i]
        if len(neighbor_idx) >= 3:
            w_neighbors = x[neighbor_idx].astype(get_default_dtype())
            mask = np.ones(w_neighbors.shape, dtype=bool)
            for _ in range(5):
                subset = w_neighbors[mask]
                if subset.size < 2:
                    break
                mu_s, sigma_s = float(np.mean(subset)), float(np.std(subset))
                if sigma_s < 1e-12:
                    break
                new_mask = np.abs(w_neighbors - mu_s) <= n_sigmas * sigma_s
                if np.array_equal(new_mask, mask):
                    break
                mask = new_mask
            subset = w_neighbors[mask]
            if subset.size >= 1:
                mu_s, sigma_s = float(np.mean(subset)), float(np.std(subset))
                if sigma_s > 1e-12:
                    centri.append(mu_s)
                    scale.append(sigma_s)

        if not centri:
            continue

        centri_arr = np.array(centri)
        scale_arr = np.array(scale)
        pesi = (1.0 / scale_arr ** 2)
        pesi /= pesi.sum()  # w_k = (1/scala_k^2) / Sum_j(1/scala_j^2), from the Lagrange multiplier

        centro_combinato = float(np.sum(pesi * centri_arr))
        scala_combinata = float(1.0 / np.sqrt(np.sum(1.0 / scale_arr ** 2)))

        if scala_combinata > 1e-12:
            pressione[i] = abs(x[i] - centro_combinato) / scala_combinata

        if w_riferimento.size >= 4 and w.size >= 4:
            jsd = _jensen_shannon(w, w_riferimento)
            soglia_effettiva[i] = soglia_pressione * (1.0 + k_molla * jsd)

    out = np.copy(x).astype(get_default_dtype())
    anomalie = []
    for i in range(n):
        if pressione[i] > soglia_effettiva[i]:
            anomalie.append(i)
            out[i] = float(np.median(_window(x, i, radius)))
    return out, anomalie, pressione, soglia_effettiva

Details

  • Why the base threshold is 8.0. On pure stationary noise (N = 300, fixed seed) the pressure percentiles are 50% = 1.4, 95% = 4.6, 99% = 6.0, 99.9% = 7.6. A base threshold of 8.0 sits above the 99.9th percentile, so on average fewer than one sample in 300 crosses it. A true outlier reaches a pressure well above the base threshold: the collision in the example above, for instance, has pressure 42.7.

  • Why Chauvenet keeps its non-robust scale. The Chauvenet rule is used here in its original 1863 formulation, with the mean and the standard deviation of the window. When the window contains an outlier, that scale inflates, and the minimum-variance weights automatically lower Chauvenet's influence. Replacing Chauvenet's mean and standard deviation with a robust centre and scale would change the rule; keeping the original and letting the weighting handle the outlier is the choice made here.

  • Jensen–Shannon on small windows. _jensen_shannon uses adaptive bins and Laplace smoothing. A naive version with fixed bins gave a higher divergence on stationary noise than on a real transition, the opposite of what the threshold formula needs: the threshold would rise on noise and would not rise near a transition. Adaptive bins fix this by sizing the histogram to the range the window actually covers.

  • Sources. Pearson, R. K. et al. (2016), "Generalized Hampel filters", EURASIP J. Adv. Signal Process., eqs. 3–4. Chauvenet, W. (1863), A Manual of Spherical and Practical Astronomy, vol. 2. Tukey, J. W. (1977), Exploratory Data Analysis.