pressure_valve¶
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 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))
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 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))
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
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))
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
The pressure of a new sample x is how far it lies from the combined centre, measured in
units of the combined scale:
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
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
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | |
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_shannonuses 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.