Skip to content

Arbiter (per-point routing)

When a reading looks wrong, there are different right answers: a single glitch should be replaced, a real change should be kept. The Arbiter decides, reading by reading, which case it is, and treats it accordingly.

A shield that always replaces deviating samples looks wrong on a real robot: it will smooth out the intentional step change the operator just commanded. A shield that never replaces them looks wrong on a noisy sensor: it lets every glitch through.

The Arbiter decides, point by point, which is which. It labels every sample clean, spike, or regime, and routes each label to the right corrector:

  • clean — passes through whatever the standard shield produced.
  • spike — hard-rejected to the median of the recent causal window.
  • regime — passed through raw, fully trusted.

The examples use a joint velocity at 100 Hz (noise 0.1 around 0.5) with a one-sample collision at sample 1500 and a step to a new level, +1.0, from sample 2000.

1. The three labels

The Arbiter uses the same robust-deviation score as every other detector in the package (see Streaming):

med = median(window)
S   = 1.4826 · median(|w − med|)
z   = |x − med| / S

A sample is deviating when z > n_sigmas (default n_sigmas = 3). Then the run of consecutive deviating samples decides the label:

  • run length ≤ spike_run_max (default 2) → spike
  • longer run, and it settles → regime
  • otherwise (longer run that does not settle) → spike (the whole run is treated as noise)

"Settles" is decided by two conditions on the run:

  1. Internal coherence: the run's own spread is small compared to its distance from the pre-run median: std(run) < 0.5 · |median(run) − med|.
  2. Persistence: the median of a short window after the run is closer to the run's median than to the pre-run median.

The two together are what separates "the signal has moved to a new level" from "the sensor briefly went haywire and came back".

2. Classify the whole series

import numpy as np
rng = np.random.default_rng(42)
v = 0.5 + 0.1 * rng.standard_normal(3000)
v[1500] = 2.5
v[2000:] += 1.0
from dense_armor.core.online.protect.arbiter import classify_segments

lab, dev, unc = classify_segments(v, radius=20, ref_mult=3)
print(lab[1500], np.flatnonzero(lab == "regime")[[0, -1]], (lab == "spike").sum())
spike [1999 2026] 26

It returns the label of each sample, its robust deviation z, and an uncertainty in [0, 1] (highest near the n_sigmas boundary). The collision is a spike; samples 1999–2026 are one long, coherent, persistent run, so a regime; afterwards the reference has caught up and samples are clean again. The other 26 spikes are isolated noise values beyond 3 sigma, out of 3,000.

3. Route the labels

import numpy as np
rng = np.random.default_rng(42)
v = 0.5 + 0.1 * rng.standard_normal(3000)
v[1500] = 2.5
v[2000:] += 1.0
from dense_armor.core.online.protect.arbiter import route_and_correct

corrected, lab, dev = route_and_correct(v, radius=20, ref_mult=3)
print(round(float(corrected[1500]), 3), np.allclose(corrected[lab == "regime"], v[lab == "regime"]))
0.489 True

corrected is the same array with each label handled by its rule:

  • spike → replaced by the median of the causal window ending just before the run.
  • regime → unchanged.
  • clean → unchanged.

The collision becomes 0.489, the median before it; regime samples are left as measured (to the rounding of the default float32).

4. The reference window is causal

The window used to score every sample contains only the samples before it, never after. This matters more than it looks: a symmetric window straddling a real regime change dilutes its own MAD exactly where the detector needs it, because half the window is on the other side of the change. Causal-only means the pre-change scale is used to score the first post-change samples, which is what lets the run be detected as a run.

The same choice was made for every streaming detector in the package.

5. In Orca

Orca.protect_and_forward(..., use_arbiter=True) runs the Arbiter after Stage 1 (the adaptive stabilizer) and Stage 2 (the constant gate). Verified on the same 7 scenarios test/experiments/testKalman.py uses: never worse than the default (no Arbiter), better on 5 of 7.

from dense_armor.core.online.protect.orca import Orca

import numpy as np
rng = np.random.default_rng(0)
data = np.sin(np.linspace(0, 6, 200))[None, :] + 0.01 * rng.standard_normal((4, 200))
data[0, 50] = 999.0
orca = Orca(min_free_ram_percentage=0.05)
out = orca.protect_and_forward(lambda z: 2.0 * z, data, use_arbiter=True)
print(out.shape, orca.etichette_arbitro.shape)

6. Streaming Arbiter (bounded delay)

The batch classify_segments needs to look after a run of deviating samples to decide whether it settled — which means it is not causal. StreamingArbiter gives the same answer with a bounded delay: each sample's final label is committed at most max_delay samples after it arrives, once the run has closed and enough context is available.

import numpy as np
rng = np.random.default_rng(42)
v = 0.5 + 0.1 * rng.standard_normal(3000)
v[1500] = 2.5
v[2000:] += 1.0
from dense_armor.core.online.protect.streaming_arbiter import StreamingArbiter

arb = StreamingArbiter(radius=20, ref_mult=3, max_delay=200)
lab = {j: l for x in v for j, l, _ in arb.update(x)}
lab.update({j: l for j, l, _ in arb.flush()})
print(len(lab), lab[1500], lab[2000])

update(x) returns a list of (index, label, corrected_value) for the samples whose final label was decided at this step; flush() finalises whatever is still pending at the end of the stream.

With max_delay at least longest_run + radius * ref_mult, the labels and corrected values equal the batch classify_segments + route_and_correct on the same series. Smaller max_delay trades exactness for latency: labels near run boundaries may change.

7. StreamingHealing

StreamingHealing is the one-sample-at-a-time version of healing_filter (dense_armor.core.online.protect.healing), a filter that replaces an isolated spike with the local baseline and lets a sustained change through.

import numpy as np
from dense_armor.core.online.protect.streaming_arbiter import StreamingHealing

rng = np.random.default_rng(42)
v = 0.5 + 0.1 * rng.standard_normal(3000)
v[1500] = 2.5
v[2000:] += 1.0
sh = StreamingHealing(radius=2, wide_mult=3, max_delay=30)
out = [o for x in v for o in sh.update(x)] + sh.flush()
print(len(out), round(out[1500][1], 3), round(out[2500][1], 3))
3000 0.479 1.555

The series has one bad sample at the position 1500 and a jump of the level from the position 2000. The output has one value for each of the 3000 samples. The bad sample comes out near the baseline (0.479, the baseline is 0.5) and a sample after the jump stays at the new level (1.555, the level is about 1.5).

healing_filter judges each point against a wide local baseline, the median of a window of radius * wide_mult samples on each side. A deviation that the majority of the narrow window of neighbours shares (same sign, amplitude above sustain_threshold) is a real change and is left as it is; an isolated deviation is replaced with the baseline. Each sample gets its corrected value as soon as the wide window around it is available, or after max_delay samples.

Known limits

The docstring of healing_filter lists the limits that were measured. The main one is that the filter decides point by point, so a collapse that comes back is taken for a real change. Three samples fall to zero on a constant series of 120 and then return; the number is the root mean squared error against the clean series, for healing_filter and for the Arbiter:

import numpy as np
from dense_armor.core.online.protect.healing import healing_filter
from dense_armor.core.online.protect.arbiter import route_and_correct

x = np.full(100, 120.0)
x[50:53] = 0.0
rmse = lambda a: float(np.sqrt(np.mean((np.asarray(a) - 120.0) ** 2)))
print(round(rmse(healing_filter(x)), 2), round(rmse(route_and_correct(x)[0]), 2))
20.78 0.0

healing_filter lets the collapse through: its error is the one of the raw series. The Arbiter groups the deviating samples into a run, looks at what happens after the run, and rejects the collapse. The docstring says that healing_filter would need a change of design to do the same, which has not been made.

The other limits of the docstring:

  • The window is centred, so the filter is not causal: it uses the points after the one it judges. StreamingHealing has to wait for radius * wide_mult samples after a sample before it decides.
  • On a smooth signal with only Gaussian noise and no jump, it loses against a simple moving median at low and medium noise (0 wins out of 30 in both cases) and wins only at high and very high noise. It is meant for signals that have real transitions to keep, not for denoising a stationary signal.
  • With 15 % of spikes instead of 5 %, it wins 30 out of 30, but the size of the advantage varies a lot from one series to another.
  • It is a Python loop of cost O(n × wide) per call: the docstring says that it must be ported to JAX before production.

8. Hand case

Window of 9 samples [10, 11, 9, 10, 12, 10, 11, 9, 10], then a run of 3 samples [15, 16, 15.5], then 4 samples [15, 15, 15, 15].

  • med of the pre-run window is 10, MAD = 1, S = 1.4826.
  • Score for the first run sample: |15 − 10| / 1.4826 = 3.37 > 3 → deviating.
  • Same for the other two run samples.
  • Run length = 3 > spike_run_max = 2: it is not a spike.
  • std(run) = std([15, 16, 15.5]) = 0.41, |median(run) − med| = |15.5 − 10| = 5.5, 0.5 · 5.5 = 2.75; 0.41 < 2.75, so the run is internally coherent.
  • Median of 4 post-run samples is 15; |15 − 15.5| = 0.5 < |15 − 10| = 5: it persists.
  • Label: regime. The 3 samples pass through unchanged.

Change the three samples to [15, 8, 16]: 15 and 16 deviate, but 8 does not (|8 − 10| / 1.4826 = 1.35 < 3), so there are two runs of length 1, not one run of three. Labels: spike, clean, spike: 15 and 16 are replaced by 10, the 8 is kept.

9. Any detector of the library

The Arbiter decides with its own window by default; with detector= any detector of the library can decide, and the Arbiter keeps its rule on the length of the run.

9.1 A point detector decides which samples deviate

A price series with one bad tick at the sample 60 and a jump of the level from the sample 150 to the sample 199. A point detector is one with score_one and learn_one: a sample deviates when its score is above threshold.

import numpy as np
from dense_armor.core.online.protect.arbiter import classify_segments
from dense_armor.core.online.anomaly.filters import HampelScorer

r = np.random.default_rng(0)
px = r.normal(0, 1, 300)
px[60] += 15.0
px[150:200] += 8.0
lab, dev, unc = classify_segments(px, detector=HampelScorer(), threshold=3.0)
print([i for i, l in enumerate(lab) if l == 'spike'], [i for i, l in enumerate(lab) if l == 'regime'][:3])
[4, 6, 60, 219, 270, 284] [150, 151, 152]

The sample 60 is a spike. The regime labels start at the sample 150, where the level moved. The detector adapts to the new level, so a run is labelled regime only while its samples still deviate. The window of the Arbiter is not used to decide which samples deviate, but it still gives the reference level that the run is compared with.

9.2 The threshold of each detector

threshold is the score above which a sample deviates. If it is not given, the Arbiter takes detector.threshold when the detector has one, and n_sigmas otherwise. The scores of the detectors are not on one scale, so the default is not good for all of them. On the series of 9.1, with the threshold of each detector:

detector threshold used label of the sample 60 samples labelled spike samples labelled regime
none (the window of the Arbiter) - spike 5 23
HampelScorer 3 spike 6 16
TukeyScorer 3.0 (n_sigmas) spike 1 8
ChauvenetScorer 0.5 clean 205 72
SigmaClipScorer 3.0 (n_sigmas) spike 7 3
streamDS 3.0 (n_sigmas) spike 5 23
LODA 4 clean 19 0
HalfSpaceTrees 1e+09 clean 0 0
LocalOutlierFactor 1.5 spike 23 19
OnlineRobustMahalanobis 7 clean 0 0
OneClassSGD 1e+09 clean 0 0
OnlineIsolationForest 0.6 spike 81 0

With their own threshold, six detectors label the sample 60 as spike (HampelScorer, TukeyScorer, SigmaClipScorer, streamDS, LocalOutlierFactor and OnlineIsolationForest) and five leave it clean. HalfSpaceTrees and OneClassSGD have a threshold of 1e9, so no sample deviates, and OnlineRobustMahalanobis with 7 flags none either: for them threshold must be given. LODA (threshold 4) flags 19 samples and not the sample 60, ChauvenetScorer (threshold 0.5) flags 205 samples and not the sample 60, OnlineIsolationForest (0.6) flags 81 and LocalOutlierFactor (1.5) flags 23: their score is not in the unit of a threshold in sigma, so each one needs the threshold of its own page.

9.3 An event detector confirms a regime

An event detector is one with update and drift_detected. It decides nothing about single samples: when it signals during a run of deviating samples, that run is a regime, even a short one. The label of the sample 60, with no detector, with ADWIN and with BayesianOnlineChangepoint:

import numpy as np
from dense_armor.core.online.protect.arbiter import classify_segments
from dense_armor.core.online.drift import ADWIN, BayesianOnlineChangepoint

r = np.random.default_rng(0)
px = r.normal(0, 1, 300)
px[60] += 15.0
px[150:200] += 8.0
for d in (None, ADWIN(), BayesianOnlineChangepoint()):
    lab = classify_segments(px, detector=d)[0]
    print(type(d).__name__, lab[60])
NoneType spike
ADWIN spike
BayesianOnlineChangepoint regime

ADWIN does not signal during any run, so the labels are those of the Arbiter alone. BayesianOnlineChangepoint signals on the single bad tick, so it turns the spike of the sample 60 into a regime: a detector that reacts to one outlier should not be used here.

9.4 In a stream

StreamingArbiter(detector=..., threshold=...) decides with the same detector. The detector is used as it is given, so it learns the stream; classify_segments works on a copy. With max_delay large enough the labels are the ones of the batch function:

import numpy as np
from dense_armor.core.online.protect.arbiter import classify_segments
from dense_armor.core.online.anomaly.filters import HampelScorer
from dense_armor.core.online.protect.streaming_arbiter import StreamingArbiter

r = np.random.default_rng(0)
px = r.normal(0, 1, 300)
px[60] += 15.0
px[150:200] += 8.0
sa = StreamingArbiter(max_delay=400, detector=HampelScorer(), threshold=3.0)
out = [e for v in px for e in sa.update(float(v))] + sa.flush()
batch = classify_segments(px, detector=HampelScorer(), threshold=3.0)[0]
print([l for _, l, _ in sorted(out)] == list(batch))
True

9.5 The same on a robot

An accelerometer channel with one glitch at the sample 60 and a change of level from the sample 150. The code is the same, with the names of the robot.

import numpy as np
from dense_armor.core.online.protect.arbiter import classify_segments
from dense_armor.core.online.anomaly.filters import HampelScorer

r = np.random.default_rng(0)
ax = r.normal(0, 1, 300)
ax[60] += 15.0
ax[150:200] += 8.0
lab, dev, unc = classify_segments(ax, detector=HampelScorer(), threshold=3.0)
print([i for i, l in enumerate(lab) if l == 'spike'], [i for i, l in enumerate(lab) if l == 'regime'][:3])
[4, 6, 60, 219, 270, 284] [150, 151, 152]

Any other object is not used: the Arbiter works as if no detector had been given.

API reference

arbiter

core/online/protect/arbiter.py

Routes each point to the right specialist instead of forcing a single one on the whole signal -- born from the real comparison in test/test_pressure_valve_vs_orca_experiment.py: hybrid_shield (phi_ab) clearly wins on isolated impulses (A, B, C, G) but loses on a sustained regime change (F), pressure_valve does the exact opposite. Neither beats the other everywhere -- the real difference between the two cases is the DURATION of the deviation, not its amplitude.

APPROACH: each point is compared with a WIDE reference window (radius*ref_mult, the same scale used by the JSD "spring" of pressure_valve) -- deliberately not with the narrow local window, which in the benchmark was seen to collapse (median/MAD/IQR exactly 0) when several nearby outliers end up in the same small window. This window is CAUSAL (_window_causal: only points BEFORE i, never after) -- a symmetric window, used right across a level transition, would mix the old and the new level in its own scale, diluting the deviation that should trigger the threshold (this was the case in the first version of this module, fixed after a real case that was not detected -- see the history in CHANGELOG.md [1.1.10]). Once the "deviating" points are marked, the LENGTH of the consecutive run of deviating points decides: short (<= spike_run_max) = isolated impulse, long = genuine regime change.

DEGENERATE CASE (exactly flat baseline, robust scale = 0): this is not an estimator problem -- see the KNOWN LIMIT in the docstring of pressure_valve, a Huber M-estimator converges to scale 0 anyway for the same structural reason. Here we never divide by a zero scale: if the dispersion of the reference window is below epsilon, ANY non-zero departure from the median is treated as deviating, without needing a threshold in sigma (on a truly constant baseline, "different from constant" is already the answer, nothing more is needed).

HISTORY (limit found and then fixed in the same session): the first version used a SYMMETRIC reference window, and scenario F (structural break, permanent level jump) was not detected as 'regime' -- deviazione[i] stayed 0 over the whole sequence around the transition, because the symmetric window, used right across the jump, contained half the old level and half the new one, inflating its own scale (MAD) instead of staying small. A first test had mistaken this for a success (RMSE 0.0 with route_and_correct standalone), but it was an artifact: the raw data of that scenario already coincide EXACTLY with the target (the "corruption" is the jump itself, not added noise), so "pass everything raw" gives RMSE 0 regardless of how each point is labelled -- the real test was the integrated Orca pipeline (core/online/protect/orca.py, _applica_arbitro), where the missed detection translated into SAFE but not improving behaviour (9.4007 identical with or without the arbiter). With the CAUSAL window (above), detection becomes real and verifiable: on scenario F, indices 60-74 (exact, verified -- the real transition is at 60) are labelled 'regime', and through the real Orca pipeline the RMSE drops from 9.4007 (default) to 6.0449 (use_arbiter=True) -- a real improvement, no longer a tie. See test/test_arbiter_orca_integration.py for the full verification on the 7 scenarios with this fix.

classify_segments

classify_segments(
    x: ndarray,
    radius: int = 10,
    ref_mult: int = 3,
    n_sigmas: float = 3.0,
    spike_run_max: int = 2,
    eps: float = 1e-09,
    detector=None,
    threshold: float | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]

detector (default None, the window of this module) can be any detector of the library: - a point detector (it has score_one and learn_one, like HampelScorer or LODA): its score replaces the 'is this point deviating?' test of the window; a point deviates when the score is above threshold (default: detector.threshold if it has one, else n_sigmas). The run length rule that decides spike or regime stays the one of this module; - an event detector (it has update and drift_detected, like ADWIN or PageHinkley): it replaces nothing; a run of deviating points during which it signals a change is labelled 'regime'. The detector is cloned (if it has clone), so the object given is not changed. Any other object is not used.

Returns (etichette, deviazione, incertezza): etichette -- array of strings 'clean'/'spike'/'regime', one per point. A non-finite point is 'clean' and is left out of the reference windows of the following points, as in streamDD. deviazione -- |x[i] - reference| / scale (or only |x[i]-reference| if the scale is degenerate), same unit for every point. incertezza -- 0..1, how close the point is to the decision boundary (deviating/clean threshold, or spike/regime threshold on the length of the run) -- not how "correct" it is, but how precarious the classification itself is.

Source code in dense_armor/core/online/protect/arbiter.py
def classify_segments(
    x: np.ndarray, radius: int = 10, ref_mult: int = 3,
    n_sigmas: float = 3.0, spike_run_max: int = 2, eps: float = 1e-9,
    detector=None, threshold: float | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    ``detector`` (default None, the window of this module) can be any detector of the library:
      - a point detector (it has ``score_one`` and ``learn_one``, like HampelScorer or LODA): its score
        replaces the 'is this point deviating?' test of the window; a point deviates when the score is
        above ``threshold`` (default: ``detector.threshold`` if it has one, else ``n_sigmas``). The run
        length rule that decides spike or regime stays the one of this module;
      - an event detector (it has ``update`` and ``drift_detected``, like ADWIN or PageHinkley): it replaces
        nothing; a run of deviating points during which it signals a change is labelled 'regime'.
    The detector is cloned (if it has ``clone``), so the object given is not changed. Any other object
    is not used.

    Returns (etichette, deviazione, incertezza):
      etichette   -- array of strings 'clean'/'spike'/'regime', one per point.
                     A non-finite point is 'clean' and is left out of the
                     reference windows of the following points, as in
                     streamDD.
      deviazione  -- |x[i] - reference| / scale (or only |x[i]-reference|
                     if the scale is degenerate), same unit for every point.
      incertezza  -- 0..1, how close the point is to the decision boundary
                     (deviating/clean threshold, or spike/regime threshold on
                     the length of the run) -- not how "correct" it is,
                     but how precarious the classification itself is.
    """
    x = as_default_array(x).ravel()
    n = x.size
    deviante = np.zeros(n, dtype=bool)
    deviazione = np.zeros(n, dtype=get_default_dtype())
    scarto_normalizzato = np.zeros(n, dtype=get_default_dtype())  # |dev|/threshold, for the uncertainty
    med_rif = np.zeros(n, dtype=get_default_dtype())  # median of the reference window, per point

    kind = _detector_kind(detector)
    det = detector.clone() if kind and hasattr(detector, "clone") else detector
    thr = _detector_threshold(detector, threshold, n_sigmas, eps) if kind == "point" else None
    events: list[int] = []
    finite_seen: deque = deque(maxlen=radius * ref_mult)
    for i in range(n):
        if not np.isfinite(x[i]):
            continue
        w_rif = np.array(finite_seen, dtype=x.dtype)
        finite_seen.append(x[i])
        score = None
        if kind == "point":
            score = float(det.score_one({"x": float(x[i])}))
            det.learn_one({"x": float(x[i])})
        elif kind == "event":
            det.update(float(x[i]))
            if det.drift_detected:
                events.append(i)
        if w_rif.size < 4:
            continue
        med, scala = _robust_center_scale(w_rif)
        med_rif[i] = med
        scarto = abs(x[i] - med)
        if score is not None:
            if np.isfinite(score):
                deviazione[i] = score
                deviante[i] = score > thr
                scarto_normalizzato[i] = score / thr
        elif scala < eps:
            # Degenerate baseline: no division, "different from constant"
            # is already the answer. scarto_normalizzato saturates at a clearly
            # high/low value (never near the boundary by construction),
            # so the uncertainty on these points stays low -- the
            # degenerate case is the ONLY one where the decision is truly unambiguous.
            deviazione[i] = scarto
            deviante[i] = scarto > eps
            scarto_normalizzato[i] = 0.0 if deviante[i] else 10.0
        else:
            deviazione[i] = scarto / scala
            deviante[i] = deviazione[i] > n_sigmas
            scarto_normalizzato[i] = deviazione[i] / n_sigmas

    etichette = np.full(n, "clean", dtype=object)
    incertezza = np.zeros(n, dtype=get_default_dtype())

    # Uncertainty on the deviating/clean threshold: near scarto_normalizzato==1
    # (i.e. exactly at the n_sigmas boundary) -> maximum ambiguity.
    incertezza_soglia = np.exp(-4.0 * (scarto_normalizzato - 1.0) ** 2)

    i = 0
    while i < n:
        if not deviante[i]:
            incertezza[i] = incertezza_soglia[i]
            i += 1
            continue
        j = i
        while j < n and deviante[j]:
            j += 1
        run_len = j - i
        if any(i <= e < j for e in events):
            label = "regime"
        elif run_len <= spike_run_max:
            label = "spike"
        else:
            # A long run is a real regime change only if its points
            # SETTLE on a new coherent level -- it is not enough that
            # they are "different from the old one", they must also be similar
            # TO EACH OTHER. Verified: 3 alternating impulses (+500,-500,+500,
            # scenario A) are a run of length 3 (> spike_run_max
            # default 2), but their INTERNAL dispersion is huge
            # (std~471) -- without this check they were mistaken for a
            # regime and passed raw, RMSE 86.6 instead of ~0. A run
            # that really settles (scenario F) has small internal dispersion
            # compared with the size of the jump itself.
            run_vals = x[i:j]
            run_spread = float(np.std(run_vals))
            run_jump = float(abs(np.median(run_vals) - med_rif[i]))
            coerente = run_spread < 0.5 * max(run_jump, eps)

            # Internal coherence is not enough: a temporary collapse that then
            # RETURNS to the old level (scenario C, 3 zeros then return to
            # 120) is internally as coherent as a true regime (internal
            # spread zero in both cases) -- the real difference is seen
            # ONLY by looking at what happens right after the run:
            # a true regime (scenario F) stays near the NEW level,
            # a collapse returns towards the OLD one. Without this
            # check scenario C stayed at RMSE 20.8 instead of ~0
            # (mistaken for a regime, passed raw instead of rejected).
            post_lo, post_hi = j, min(n, j + radius)
            post_vals = x[post_lo:post_hi]
            post_vals = post_vals[np.isfinite(post_vals)]
            if post_vals.size:
                post_med = float(np.median(post_vals))
                run_med = float(np.median(run_vals))
                persiste = abs(post_med - run_med) < abs(post_med - med_rif[i])
            else:
                persiste = True  # end of series: no "after" to check

            label = "regime" if (coerente and persiste) else "spike"
        etichette[i:j] = label
        # Uncertainty on the spike/regime threshold: near run_len==spike_run_max
        # -> maximum ambiguity on the length; combined (mean) with the one
        # on the deviating/clean threshold of the single points of the run.
        incertezza_run = float(np.exp(-1.0 * (run_len - spike_run_max) ** 2))
        incertezza[i:j] = 0.5 * incertezza_soglia[i:j] + 0.5 * incertezza_run
        i = j

    return etichette, deviazione, incertezza

route_and_correct

route_and_correct(
    x: ndarray,
    radius: int = 10,
    ref_mult: int = 3,
    n_sigmas: float = 3.0,
    spike_run_max: int = 2,
    detector=None,
    threshold: float | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]
Applies the classification and corrects each point according to its label

'clean'/'regime' -> passes the raw value (a genuine regime change must not be rejected, same philosophy as the constant gate of Orca); 'spike' -> replaced with the median of the wide reference window (robust, not contaminated by the single short impulse).

Returns (pulito, etichette, incertezza).

Source code in dense_armor/core/online/protect/arbiter.py
def route_and_correct(
    x: np.ndarray, radius: int = 10, ref_mult: int = 3,
    n_sigmas: float = 3.0, spike_run_max: int = 2,
    detector=None, threshold: float | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Applies the classification and corrects each point according to its label:
      'clean'/'regime' -> passes the raw value (a genuine regime change
                          must not be rejected, same philosophy as the
                          constant gate of Orca);
      'spike'          -> replaced with the median of the wide reference
                          window (robust, not contaminated by the single
                          short impulse).

    Returns (pulito, etichette, incertezza)."""
    x = as_default_array(x).ravel()
    n = x.size
    etichette, _, incertezza = classify_segments(
        x, radius, ref_mult, n_sigmas, spike_run_max, detector=detector, threshold=threshold
    )

    pulito = np.copy(x)
    for i in range(n):
        if etichette[i] == "spike":
            w_rif = _window(x, i, radius * ref_mult)
            w_rif = w_rif[np.isfinite(w_rif)]
            if w_rif.size:
                pulito[i] = float(np.median(w_rif))

    return pulito, etichette, incertezza

streaming_arbiter

utility/streaming_arbiter.py

One-sample-at-a-time version of arbiter.classify_segments + route_and_correct.

The batch function decides spike vs regime by grouping consecutive deviant points into runs and looking at what happens after the run (to distinguish a genuine regime shift from a transient collapse that returns). This is fundamentally non-causal: the decision for a point requires future context. StreamingArbiter therefore decides with a bounded delay: each sample gets a provisional label at once (deviant / normal, from the causal window) and a final label (clean / spike / regime) after at most max_delay samples.

With max_delay large enough to cover both the longest run and the widest window the batch correction uses (radius * ref_mult), the final labels and corrected values equal the batch classify_segments + route_and_correct on the same series. With smaller max_delay, labels near run boundaries may change (documented in the latency table of arbiter.md).

StreamingArbiter

StreamingArbiter(
    radius: int = 10,
    ref_mult: int = 3,
    n_sigmas: float = 3.0,
    spike_run_max: int = 2,
    max_delay: int = 40,
    eps: float = 1e-09,
    detector=None,
    threshold: float | None = None,
)

Bounded-delay streaming version of arbiter.classify_segments.

update(x) adds a sample and returns the list of samples whose final label was decided at this step, as (index, label, corrected_value). flush() finalises everything still pending (call it at the end of a series).

Parameters

radius, ref_mult, n_sigmas, spike_run_max, eps Same meaning and defaults as arbiter.classify_segments. detector, threshold Any detector of the library, as in arbiter.classify_segments: a point detector (score_one and learn_one) decides which samples deviate, with threshold (default detector.threshold, else n_sigmas); an event detector (update and drift_detected) turns a run of deviating samples during which it signals a change into 'regime'. The detector is used as given: it learns the stream. max_delay Maximum number of future samples the streaming version will wait before committing to a final label. With max_delay at least longest_run + radius * ref_mult, the result is identical to the batch function; smaller values trade exactness for lower latency.

Examples

import numpy as np from dense_armor.core.online.protect.streaming_arbiter import StreamingArbiter rng = np.random.default_rng(0) x = list(rng.normal(0, 1, 100)) + [50.0] + list(rng.normal(0, 1, 100)) sa = StreamingArbiter(radius=10, max_delay=200) decided = [] for v in x: ... decided.extend(sa.update(v)) decided.extend(sa.flush()) spike_idx = [i for i, lab, _ in decided if lab == "spike"] 100 in spike_idx True

Source code in dense_armor/core/online/protect/streaming_arbiter.py
def __init__(self, radius: int = 10, ref_mult: int = 3,
             n_sigmas: float = 3.0, spike_run_max: int = 2,
             max_delay: int = 40, eps: float = 1e-9,
             detector=None, threshold: float | None = None):
    self.radius = radius
    self.ref_mult = ref_mult
    self.n_sigmas = n_sigmas
    self.spike_run_max = spike_run_max
    self.max_delay = int(max_delay)
    self.eps = eps
    self.detector = detector
    self._kind = _detector_kind(detector)
    self._thr = _detector_threshold(detector, threshold, n_sigmas, eps) if self._kind == "point" else None
    self._events: list[int] = []
    self._x: list[float] = []
    self._deviante: list[bool] = []
    self._med_rif: list[float] = []
    self._labels: list[str | None] = []
    self._corrected: list[float] = []
    self._next_undecided: int = 0
    self._emitted: list[tuple[int, str, float]] = []

update

update(x: float) -> list[tuple[int, str, float]]

Add a sample and return the samples finalised at this step.

Source code in dense_armor/core/online/protect/streaming_arbiter.py
def update(self, x: float) -> list[tuple[int, str, float]]:
    """Add a sample and return the samples finalised at this step."""
    self._emitted = []
    self._x.append(float(x))
    self._labels.append(None)
    self._corrected.append(float(x))
    self._compute_deviante(len(self._x) - 1)
    self._sweep(forced=False)
    return list(self._emitted)

flush

flush() -> list[tuple[int, str, float]]

Finalise every sample still pending.

Source code in dense_armor/core/online/protect/streaming_arbiter.py
def flush(self) -> list[tuple[int, str, float]]:
    """Finalise every sample still pending."""
    self._emitted = []
    self._sweep(forced=True)
    return list(self._emitted)

StreamingHealing

StreamingHealing(
    radius: int = 2,
    sustain_threshold: float = 0.7,
    wide_mult: int = 3,
    max_delay: int = 30,
)

One-sample-at-a-time version of healing.healing_filter.

healing_filter judges each point against a wide local baseline and replaces it when the deviation is not shared by the majority of a narrow window of neighbours. It uses a symmetric wide window, so the streaming version decides with the same bounded-delay idea as StreamingArbiter: each sample gets a corrected value as soon as the wide symmetric window around it is fully available.

Parameters

radius, sustain_threshold, wide_mult Same meaning and defaults as healing.healing_filter. max_delay Maximum number of samples to wait before finalising.

Examples

import numpy as np from dense_armor.core.online.protect.streaming_arbiter import StreamingHealing rng = np.random.default_rng(0) x = list(rng.normal(0, 0.1, 50)) + [5.0] + list(rng.normal(0, 0.1, 50)) sh = StreamingHealing(radius=2, wide_mult=3, max_delay=100) out = [] for v in x: ... out.extend(sh.update(v)) out.extend(sh.flush()) out = [v for _, v in sorted(out, key=lambda t: t[0])] abs(out[50]) < 1.0 True

Source code in dense_armor/core/online/protect/streaming_arbiter.py
def __init__(self, radius: int = 2, sustain_threshold: float = 0.7,
             wide_mult: int = 3, max_delay: int = 30):
    self.radius = radius
    self.sustain_threshold = sustain_threshold
    self.wide_mult = wide_mult
    self.max_delay = int(max_delay)
    self._x: list[float] = []
    self._decided: list[float | None] = []
    self._next: int = 0
    self._emitted: list[tuple[int, float]] = []

Details

The Arbiter grew out of a real benchmark where hybrid_engine-style rejection won on isolated impulses while pressure_valve's tolerance won on a sustained level change, with neither beating the other everywhere. The obvious answer — pick one per situation — required a classifier for "situation", and the run-length + coherence rule is what the benchmark showed to be the right classifier for the cases that appeared.

The reference window is causal for a specific reason found during validation: a symmetric window straddling a real transition dilutes its own MAD at exactly the positions where the transition is being classified, so a run that starts right at the change is scored against a scale that is half on the old level and half on the new, and neither side wins. Causal-only means the pre-change scale is used for the first post-change samples, which is what lets the run be recognized as a run.