Skip to content

Online Robust Mahalanobis

How far is today from usual — in units the market actually uses.

A single strange day should not ruin what the detector has learned. Online Robust Mahalanobis learns where the normal days sit and how they move together, then reports how far a new day is from that centre, measured in the usual spread. A distance of 0 means exactly usual; the default alarm is 7. A few strange days do not spoil the estimate.


The problem

A detector fitted with the sample mean and covariance can be spoiled by the very outliers it is meant to catch. A single extreme sample drags the mean away from the cloud and inflates the covariance along its own direction — so the outlier ends up looking normal under the new metric. This is the masking effect, and it is the reason classical Mahalanobis distance is dangerous on a live market stream.

Online Robust Mahalanobis fixes this with two 50 %-breakdown estimators: the geometric median for location and the median covariation matrix (MCM) for scatter. Half the samples must be corrupted before the estimate moves. One bad day moves the median by at most one step of length gamma_n.


One example: a crash among normal days

Each day has two numbers: the return in percent and the log volume. The detector learns 500 normal days (returns around 0.05 % with a spread of 0.8 %), then scores 100 new normal days and 100 days of a crash (returns around -3 %, volume up).

import numpy as np
from dense_armor.core.online.anomaly.mahalanobis import OnlineRobustMahalanobis

rng = np.random.default_rng(0)

def day(crash):
    if crash:
        return {"ret": float(rng.normal(-3.0, 1.5)), "vol": float(rng.normal(1.5, 0.3))}
    return {"ret": float(rng.normal(0.05, 0.8)), "vol": float(rng.normal(0.0, 0.3))}

det = OnlineRobustMahalanobis(feature_keys=["ret", "vol"], n_init=200)
for _ in range(500):
    det.learn_one(day(False))

ok = np.median([det.score_one(day(False)) for _ in range(100)])
cr = np.median([det.score_one(day(True)) for _ in range(100)])
print(f"normal days  {ok:.3f}")
print(f"crash days   {cr:.3f}")
normal days  1.325
crash days   7.038

The median crash day lands right at the default threshold of 7.0. This crash is a mild one in volume, so half of its days are not flagged: a limit of the default threshold on this stream, not a feature. The distance still rises more than five times over the normal days.

In this example: 1.3 on a normal day, 7.0 on a crash day. The threshold is not universal: calibrate it on your own normal days.


What the detector actually learns

The Mahalanobis distance is a scalar, but the metric behind it is an ellipsoid in the feature space. The ellipsoid is the model: inside it, the day is usual; outside it, the day is flagged.

95 % ellipsoid learned in the r2-r3 plane

Two joints' residuals of the robot case study below: first 200 healthy samples (green dots), then 30 fault samples (red crosses). The black ellipse is the 95 % quantile of the current MCM; the fault samples all fall outside.


How it works

Two running estimates, updated one sample at a time by averaged stochastic gradient (ASGD):

  • m — the geometric median. Each step has the same length gamma_n, so a distant sample moves m by at most gamma_n, no matter how far it is. That normalisation is the robustness.
  • V — the MCM. The centred outer product of each new sample is folded in with a unit-Frobenius-norm step, and the iterates are averaged to accelerate convergence (Cardot, Cénac and Zitt 2013; Cardot and Godichon-Baggioni 2017).

The score of a sample is the Mahalanobis distance under the current V_bar, computed from the eigendecomposition rather than by inverting the matrix:

D(x) = sqrt( sum_j (1 / delta_j) * <x - m_bar, P_j>^2 )

The first n_init samples are used for an offline initialisation (Weiszfeld for the median, average of centred outer products for the MCM) — without it the unit-normalised ASGD steps would start from the identity matrix and never reach the scale of the data.


Why the score stays bounded

The literal Section 3.2 update of Guillot et al. (2025, page 7), run without safeguards, crosses the zero matrix on the SyntheticArm payload fault: with c_gamma = 1.0 the final trace(V_bar) is -2.88e-04, 19 of 80 steps have a non-positive eigenvalue, and the maximum score reaches 11.36 on healthy samples. The cause is the scale of the normalised step (~0.04 in Frobenius norm) against the scale of V (~2.6e-03): the average oscillates through the origin and 1 / delta blows up.

Two numerical guards keep the score bounded without changing the algorithm:

  • max_step_frac = 0.1 — a single large sample cannot move V by more than a fraction of its own norm.
  • Eigenvalue floor at trace(V_bar) / d * 1e-3 — keeps the metric well-defined while the ASGD is still converging.

With the guards, on the same 80 samples, the maximum score stays below the threshold (see test_mahalanobis_healthy_scores_stay_below_threshold).


What it is not

Two steps of the full paper are not implemented:

  • the Robbins–Monro reconstruction of the true covariance eigenvalues from the MCM (Section 2.3, eqs. 4–5);
  • the chi2_d(0.5) / med(D_1..n) scaling of the distances (eq. 1).

Neither is needed for flagging: the MCM metric with a calibrated threshold is already usable, and the 7.0 default is the classical value for low-dimensional Gaussians. The threshold is the one you calibrate.


Parameters

OnlineRobustMahalanobis(...), in dense_armor.core.online.anomaly.mahalanobis. learn_one(x) takes a dict with one key per channel; score_one(x) returns the distance as a float, 0.0 until the offline initialisation is done.

Parameter Default Meaning
feature_keys None the dict keys, one per channel; None takes the sorted keys of the first dict
n_init 100 samples accumulated before the offline initialisation; at least d + 1 for d channels
threshold 7.0 the alarm level on the distance
c_gamma 1.0 numerator of the step size gamma_n = c_gamma * (n + n0) ** (-gamma_exp)
gamma_exp 0.7 exponent of the step size, in (1/2, 1)
n0 0 warm-up offset in the step size
max_step_frac 0.1 cap on the step length, as a fraction of the norm of V and m; a numerical safeguard, not part of the paper
eps 1e-9 numerical guard for divisions and degenerate eigenvalues

Cost

At the benchmark defaults (n_init=100, 4 features), on one CPU thread:

  • 0.036 ms per sample for learn_one + score_one, measured on the arm stream;
  • memory flat: d + d^2 arrays, independent of stream length;
  • declared budget_s = 0.005.

Where it comes from

Guillot, Godichon-Baggioni, Robin and Sansonnet (2025), Streaming robust covariance estimation and sequential outlier detection, arXiv:2601.03957. Section and equation numbers on this page are those of arXiv v1 (7 January 2026), whose title is Online robust covariance matrix estimation and outlier detection. Geometric median recurrence: eq. 8. MCM recurrence: eq. 10. Mahalanobis distance under the MCM: eq. 1, Section 2.2. Step size gamma_n = c * n ** -gamma with gamma in (1/2, 1): Cardot, Cénac and Zitt (2013); Cardot and Godichon-Baggioni (2017).

Appendix — technical notes

The sections below are for implementers and auditors: the robot case study, the measured numbers and the development notes.

On a robot: the SyntheticArm payload fault

The residual of joints 1-4 on a SyntheticArm payload fault. The fault (5 kg added at t = 2 s) shifts the residual on joints 1-5 by tens of N·m; the healthy run stays within ±0.15 N·m.

from pathlib import Path
from dense_armor.core.online.anomaly.mahalanobis import (
    OnlineRobustMahalanobis,
)
from dense_armor.core.signals.datasets import SyntheticArm

ds = SyntheticArm(
    Path("test/fixtures/urdf/panda.urdf"),
    period_s=2.0, rate_hz=50.0, n_cycles=4,
    fault_at_s=2.0, fault="payload", payload_mass=5.0,
    noise_std=(1e-3, 5e-3, 5e-2), seed=0,
)

det = OnlineRobustMahalanobis(
    feature_keys=["r0", "r1", "r2", "r3"],
    threshold=7.0,
)

for sig, _ in ds.stream():
    q, qd, qdd = ds.trajectory(sig.t)
    tau_nom = ds.nominal_torque(q, qd, qdd)
    x = {f"r{j}": float(sig[f"tau_{j}"] - tau_nom[j]) for j in range(4)}
    _ = det.score_one(x)
    _ = det.learn_one(x)

OnlineRobustMahalanobis score on the SyntheticArm payload fault and DriftStream

Top: SyntheticArm. The fault sends the score past 100 in the first few samples after t = 2 s, then the score drops as the ASGD updates the location and the scatter estimate towards the new distribution — but the detector has already flagged every post-fault sample until the update catches up. Bottom: DriftStream. The score rises cleanly at the drift and stays above the threshold.

The learned 95 % region on the robot case

The ellipse learned on the residuals of two joints is the one drawn in What the detector actually learns: a new sample inside it has a Mahalanobis distance below chi2_2(0.95), outside it the sample is flagged. On the fault of this case the fault samples all fall outside.

Numbers

SyntheticArm (200 samples, 100 healthy, 100 fault) and DriftStream (2000 samples, one sudden drift at half), every detector built with its defaults.

Stream Protocol ROC-AUC False alarms on the healthy part Threshold at the last healthy sample
SyntheticArm learn-on-healthy 1.000 0.000 7.0000
SyntheticArm learn-on-all 1.000 0.000 7.0000
DriftStream learn-on-healthy 0.993 0.000 7.0000
DriftStream learn-on-all 0.938 0.000 7.0000

The default n_init is 100, and on SyntheticArm the healthy part has exactly 100 samples: in the benchmark run the detector is still in its initialisation when the healthy part ends, so every healthy score is 0.0 and the false-alarm value 0.000 on SyntheticArm follows from that, not from a decision of the detector. On these two streams, with the defaults, the ROC-AUC is 1.000 and 0.993, at 0.036 ms per sample on the arm.

Details

Where the rules come from

Guillot, Godichon-Baggioni, Robin and Sansonnet (arXiv:2601.03957) introduce the online median and MCM in Section 3. The recurrence for the geometric median is equation 8, for the MCM equation 10. The Mahalanobis distance under the MCM is Equation (1) in Section 2.2. The step size gamma_n = c * n ** -gamma with gamma in (1/2, 1) is from Cardot, Cénac and Zitt (2013) and Cardot and Godichon-Baggioni (2017).

The paper's full method also reconstructs the eigenvalues of the true covariance from the MCM by a Robbins-Monro scheme (equations 4-5) and scales the distances by chi2_d(0.5) / med(D_1..n) (equation 1). Neither step is implemented here.

Choices stated explicitly

  • Offline initialisation. The geometric median is initialised by the Weiszfeld algorithm (Guillot et al., equation 6). The MCM is initialised by the empirical average of the centred outer products, not the Weiszfeld offline MCM of Section A.2: with n_init of tens of samples the average is more stable than the Weiszfeld iteration, which for small samples can converge to a rank-one solution. The online ASGD refines the estimate as soon as new samples arrive.
  • Step length cap. A max_step_frac cap on the ASGD step (default 0.1) prevents a single large sample from moving V by more than a fraction of its own norm. Without the cap, c_gamma = 1 and gamma_exp = 0.7 can move V by 1 in Frobenius norm in one step, much larger than the scale of the data, and the average oscillates through zero. This is a numerical safeguard, not part of the paper.
  • Eigenvalue floor. Every eigenvalue of V_bar is floored at trace(V_bar) / d * 1e-3. The floor keeps the score bounded when the ASGD first steps drive V through zero, without changing the shape of the metric. Also a numerical safeguard.
  • No chi-squared scaling. The paper's equation 1 divides the distances by the median of the past distances, so that the calibrated threshold is the median of a chi2_d distribution. This module does not apply the scaling: the threshold is the one the user calibrates, and the default 7.0 is the classical value for low-dimensional Gaussians.
  • Step index. Guillot et al. use gamma_n = c_gamma (n + n0)^(-gamma) with n counted from the first sample (0.0395 c_gamma for the first update after n_init = 100 with gamma = 0.7). Here n also counts from the first sample (n = n_init + k at the k-th update) and the offset is one larger, gamma_n = c_gamma (n + n0 + 1)^(-gamma): the first update after n_init = 100 uses 0.0393 c_gamma. The averaged estimates use the weight 1 / (n + 1) with the same n, which is the paper's 1 / (n + 2) for the previous step index. The offset of one in gamma_n is a choice of this implementation.
  • Threshold. A fixed float, default 7.0.

Measured cost

At the benchmark defaults (n_init=100, 4 features), on one CPU thread:

  • 0.036 ms per sample for learn_one + score_one on the arm stream;
  • memory flat: d + d^2 arrays, independent of the stream length.

The budget_s declared by the class is 0.005 s.

The bug the module fixes

The literal Section 3.2 update of Guillot et al. (page 7) without the step cap and without the eigenvalue floor was reimplemented outside the library and run on the 80 healthy residuals that follow n_init = 20, on the issue scenario (joint 1 of the SyntheticArm payload fault, period_s=2.0, rate_hz=50.0, n_cycles=2, payload_mass=5.0, seed 0).

With c_gamma = 1.0 the running average V_bar crosses the zero matrix: the final trace(V_bar) is -2.88e-04. Scoring each sample before the update, 19 of the 80 steps have a non-positive eigenvalue and the maximum score is 11.36; scoring after the update, 20 steps and a maximum of 5.96. The cause is the scale of the normalised step against the scale of V: the step has Frobenius norm ~0.04, while V itself is of order 2.6e-03, so V_bar moves through the origin and 1 / delta diverges. With c_gamma equal to the variance of the residual (2.57e-03): 0 steps, trace(V_bar) = +1.37e-03, maximum 3.70.

The two guards are max_step_frac = 0.1 and the eigenvalue floor trace(V_bar) / d * 1e-3. On the same 80 samples with the guards the maximum stays below the threshold. The reproduction is the module's test test_mahalanobis_healthy_scores_stay_below_threshold, which uses the 100 healthy residuals of the issue scenario with n_init = 20 and asserts the maximum is 3.739 < 7 (80 of the 100 scores non-zero).

OCSVM is the alternative when the fault is not a shift but a change of the distribution's shape.


Appendix — the robotics case study (SyntheticArm, payload fault on joints 1–4), the measured benchmark numbers and the development notes are in the sections above, from "On a robot" to "Details". OCSVM is the alternative when the fault is not a shift but a change of the distribution's shape.

OnlineRobustMahalanobis (moved from streaming)

Some faults are visible only in the combination of channels: each joint alone looks normal, but together they disagree. OnlineRobustMahalanobis learns how the channels usually move together and scores how far a sample is from that pattern.

import numpy as np
from dense_armor.core.online.anomaly.mahalanobis import OnlineRobustMahalanobis

rng = np.random.default_rng(3)
a = rng.normal(0, 1, 500)
b = a + 0.1 * rng.normal(0, 1, 500)
m = OnlineRobustMahalanobis(feature_keys=["a", "b"])
for x, y in zip(a, b):
    m.learn_one({"a": float(x), "b": float(y)})
print(round(m.score_one({"a": 1.0, "b": 1.0}), 1), round(m.score_one({"a": 1.0, "b": -1.0}), 1))
1.2 21.8

Two joints that always move together (b follows a). The sample (1, 1) moves them together: score 1.2, normal. The sample (1, −1) moves them in opposite directions: each value alone is ordinary (one standard deviation), but the pair is unusual, score 21.8.

The score is the Mahalanobis distance

\[D(x) = \sqrt{\sum_{j=1}^{d} \frac{\langle x - \bar m,\; P_j\rangle^2}{\delta_j}},\]

where \(\bar m\) is the robust centre (the geometric median, the point with the smallest total distance to all samples), \(P_j\) are the main directions in which the channels vary together and \(\delta_j\) how much they vary along each one (eigenvectors and eigenvalues of the median covariation matrix, a robust version of the covariance). Both are updated at every sample by a small step towards the new data:

\[m_{n+1} = m_n + \gamma_{n+1}\,\frac{X_{n+1} - m_n}{\lVert X_{n+1} - m_n\rVert}, \qquad \gamma_n = c_\gamma\,(n + n_0)^{-\gamma},\]

and the same for the covariation matrix with the outer product \((X - m)(X - m)^\top\). Dividing by the distance means one absurd sample moves the estimate by at most \(\gamma\), whatever its size: that is what makes it robust. Source: Guillot, Godichon-Baggioni, Robin and Sansonnet (arXiv:2601.03957), the online scheme of section 3.2 (the recursion of the median is equation 8, in Appendix A.1; section numbers are those of arXiv v1).

Density of the Mahalanobis distance of an outlier under four contamination scenarios, from Guillot et al.

From Guillot et al. (arXiv:2601.03957), Figure 2: density of the (log10) Mahalanobis distance of an outlier under four contamination scenarios (A–D); the dotted line is the inlier threshold. The further a curve sits to the right of the line, the easier the outlier is to flag. Reproduced under the paper's CC BY 4.0 licence.

OnlineRobustMahalanobis

OnlineRobustMahalanobis(
    c_gamma: float = 1.0,
    gamma_exp: float = 0.7,
    n0: int = 0,
    n_init: int = 100,
    max_step_frac: float = 0.1,
    feature_keys: Sequence[str] | None = None,
    eps: float = 1e-09,
    seed: int | None = None,
    threshold: float = 7.0,
)

Bases: AnomalyDetector

Online robust Mahalanobis scorer for multichannel signals.

learn_one(x) accepts a dict of features (one per channel). For the first n_init samples the location and the dispersion are accumulated; at step n_init the geometric median and the median covariation matrix are estimated offline (Weiszfeld for the median, average of centred outer products for the MCM). From n_init + 1 on, both are updated by averaged stochastic gradient (Cardot et al. 2013, Cardot and Godichon-Baggioni 2017).

score_one(x) returns the Mahalanobis distance

D(x) = sqrt( sum_j (1 / delta[j]) * <x - m_bar, P[:, j]>^2 )

where P[:, j] is the j-th eigenvector of V_bar and delta[j] is the corresponding eigenvalue of the averaged MCM. 0.0 until the offline initialisation is complete.

Parameters:

Name Type Description Default
c_gamma float

numerator of the step size gamma_n = c_gamma * (n + n0) ** (-gamma_exp) for the averaged stochastic gradient updates.

1.0
gamma_exp float

exponent of the step size; must be in (1/2, 1) for convergence (Cardot et al. 2013).

0.7
n0 int

warm-up offset in the step size.

0
n_init int

number of samples accumulated before the offline initialisation. The paper uses 100 in the simulations (section 4.1). Must be at least d + 1 where d is the number of features; with fewer samples the offline initialisation falls back to the identity matrix, the case the module docstring says never reaches the scale of the data.

100
max_step_frac float

cap on the ASGD step length, as a fraction of the current Frobenius norm of V (and of the Euclidean norm of m). The paper's step size gamma_n = c_gamma * (n + n0) ** -gamma_exp can, at c_gamma = 1, move V by 1 in Frobenius norm in a single step, much larger than the scale of the data: without a cap the averaged MCM oscillates through zero and its eigenvalues become negative. Default 0.1. This is a numerical safeguard, not part of the paper.

0.1
feature_keys Sequence[str] | None

list of dict keys, one per channel. None takes the sorted keys of the first dict seen.

None
eps float

numerical guard for divisions and degenerate eigenvalues. Additionally, every eigenvalue of V_bar is floored at trace(V_bar) / d * 1e-3: during the first ASGD steps the unit-normalised gradient can drive V through zero, and the floor keeps the score bounded without changing the shape of the metric. This is a numerical safeguard, not part of the paper.

1e-09
seed int | None

unused in this minimal version, kept for interface stability with the full version.

None
threshold float

distance above which is_outlier returns True. Default 7.0 (calibrated on the seeded Gaussian benchmark; with the MCM eigenvalues the score lives on a scale comparable to the chi-squared one, so the classical 7.0 is a reasonable starting point for a low-dimensional signal).

7.0

Raises:

Type Description
ValueError

on a non-positive parameter or a bad feature_keys size.

Examples:

>>> import numpy as np
>>> from dense_armor.core.online.anomaly.mahalanobis import (
...     OnlineRobustMahalanobis,
... )
>>> rng = np.random.default_rng(0)
>>> model = OnlineRobustMahalanobis(
...     feature_keys=["a", "b"], n_init=200
... )
>>> for _ in range(500):
...     x = rng.standard_normal(2)
...     _ = model.learn_one(
...         {"a": float(x[0]), "b": float(x[1])}
...     )
>>> inlier = model.score_one({"a": 0.0, "b": 0.0})
>>> outlier = model.score_one({"a": 10.0, "b": 10.0})
>>> outlier > inlier
True
References

Guillot, A., Godichon-Baggioni, A., Robin, S., Sansonnet, L. (2025). arXiv:2601.03957. Sections 2.3, 3.2, 3.3, 3.4.

Source code in dense_armor/core/online/anomaly/mahalanobis.py
def __init__(
    self,
    c_gamma: float = 1.0,
    gamma_exp: float = 0.7,
    n0: int = 0,
    n_init: int = 100,
    max_step_frac: float = 0.1,
    feature_keys: Sequence[str] | None = None,
    eps: float = 1e-9,
    seed: int | None = None,
    threshold: float = 7.0,
) -> None:
    if c_gamma <= 0:
        raise ValueError(f"c_gamma must be > 0, got {c_gamma}")
    if not (0.5 < gamma_exp < 1.0):
        raise ValueError(f"gamma_exp must be in (1/2, 1), got {gamma_exp}")
    if n0 < 0:
        raise ValueError(f"n0 must be >= 0, got {n0}")
    if n_init < 2:
        raise ValueError(f"n_init must be >= 2, got {n_init}")
    if not (0.0 < max_step_frac <= 1.0):
        raise ValueError(f"max_step_frac must be in (0, 1], got {max_step_frac}")
    self.c_gamma = float(c_gamma)
    self.gamma_exp = float(gamma_exp)
    self.n0 = int(n0)
    self.n_init = int(n_init)
    self.max_step_frac = float(max_step_frac)
    self.feature_keys = feature_keys
    self.eps = eps
    self.seed = seed
    self.threshold = float(threshold)
    self._dim: int | None = None
    self._m: np.ndarray | None = None
    self._m_bar: np.ndarray | None = None
    self._V: np.ndarray | None = None
    self._V_bar: np.ndarray | None = None
    self._delta: np.ndarray | None = None
    self._P: np.ndarray | None = None
    self._n: int = 0
    self._n_after_init: int = 0
    self._ready: bool = False
    self._keys: list[str] | None = None
    self._init_buf: list[np.ndarray] = []
    self.n_missing_: int = 0

learn_one

learn_one(
    x: dict, t: float | None = None
) -> OnlineRobustMahalanobis

Learn one sample.

Parameters:

Name Type Description Default
x dict

dict of one feature per channel.

required
t float | None

unused.

None

Returns:

Type Description
OnlineRobustMahalanobis

self.

Source code in dense_armor/core/online/anomaly/mahalanobis.py
def learn_one(self, x: dict, t: float | None = None) -> "OnlineRobustMahalanobis":
    """Learn one sample.

    Args:
        x: dict of one feature per channel.
        t: unused.

    Returns:
        ``self``.
    """
    self._time_step(t)
    if not isinstance(x, dict) or not x:
        self.n_missing_ += 1
        return self
    try:
        y = self._to_vec(x)
    except (KeyError, TypeError, ValueError):
        self.n_missing_ += 1
        return self
    if not np.isfinite(y).all():
        self.n_missing_ += 1
        return self
    if self._dim is None:
        self._dim = int(y.size)
    if self._n < self.n_init:
        self._init_buf.append(y.copy())
        self._n += 1
        if self._n == self.n_init:
            self._offline_init()
        return self

    self._n_after_init += 1
    n = self.n_init + self._n_after_init
    gamma = self._gamma(n)

    assert self._m is not None and self._m_bar is not None
    assert self._V is not None and self._V_bar is not None

    diff = y - self._m
    nrm = float(np.linalg.norm(diff))
    if nrm > self.eps:
        step_m = min(
            gamma,
            self.max_step_frac * float(np.linalg.norm(self._m)) + self.eps,
        )
        self._m = self._m + step_m * diff / nrm
    self._m_bar = self._m_bar + (1.0 / (n + 1)) * (self._m - self._m_bar)

    outer = np.outer(y - self._m_bar, y - self._m_bar)
    dV = outer - self._V
    nrm_V = float(np.linalg.norm(dV, "fro"))
    if nrm_V > self.eps:
        step_V = min(
            gamma,
            self.max_step_frac * float(np.linalg.norm(self._V, "fro")) + self.eps,
        )
        self._V = self._V + step_V * dV / nrm_V
    self._V_bar = self._V_bar + (1.0 / (n + 1)) * (self._V - self._V_bar)

    if n % 10 == 0 or n < 10:
        try:
            delta, P = np.linalg.eigh(self._V_bar)
            trace = float(np.trace(self._V_bar))
            floor = max(
                trace / max(self._dim or 1, 1) * 1e-3,
                self.eps,
            )
            self._delta = np.maximum(delta, floor)
            self._P = P
            self._ready = True
        except np.linalg.LinAlgError:
            pass
    return self

score_one

score_one(x: dict, t: float | None = None) -> float

Score one sample.

Parameters:

Name Type Description Default
x dict

dict of one feature per channel.

required
t float | None

unused.

None

Returns:

Type Description
float

Mahalanobis distance under the current MCM. 0.0 before

float

the offline initialisation is complete or on a non-finite

float

input.

Source code in dense_armor/core/online/anomaly/mahalanobis.py
def score_one(self, x: dict, t: float | None = None) -> float:
    """Score one sample.

    Args:
        x: dict of one feature per channel.
        t: unused.

    Returns:
        Mahalanobis distance under the current MCM. ``0.0`` before
        the offline initialisation is complete or on a non-finite
        input.
    """
    self._time_step(t)
    if not self._ready:
        return 0.0
    try:
        y = self._to_vec(x)
    except (KeyError, TypeError, ValueError):
        return 0.0
    if not np.isfinite(y).all():
        return 0.0
    assert self._m_bar is not None
    assert self._P is not None and self._delta is not None
    diff = y - self._m_bar
    proj = self._P.T @ diff
    d2 = float(np.sum((proj**2) / self._delta))
    return float(np.sqrt(max(d2, 0.0)))

is_outlier

is_outlier(x: dict, threshold: float | None = None) -> bool

Boolean wrapper around :meth:score_one.

Source code in dense_armor/core/online/anomaly/mahalanobis.py
def is_outlier(self, x: dict, threshold: float | None = None) -> bool:
    """Boolean wrapper around :meth:`score_one`."""
    thr = self.threshold if threshold is None else float(threshold)
    return self.score_one(x) > thr