Mahalanobis Distance — Machine Learning/Anomaly Detection
Machine_Learning/Anomaly_Detection/Mahalanobis_Distance · 1 input / 1 output port(s) at insert · exports to Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text
Description#
The block's own DESCRIPTION_HTML, rendered verbatim — the same text the config dialog's info panel and the library navigator show. Fix a wrong sentence in the block's .cpp (R-D9), never here.
Mahalanobis Distance
Machine Learning / Anomaly Detection
How far the current sample sits from the distribution a model was fitted on: y = √((u − μ)' · Sinv · (u − μ)), measured in standard deviations along each correlated direction rather than in raw units.
It is the one monitor here that uses the covariance structure. A sample can sit inside every individual feature's range and still be far away, if the features moved in a combination the training data never showed – which is exactly the case a per-feature range check cannot see. Put it beside a deployed model to tell "the model is extrapolating" from "the model is predicting".
Ports
- u – the feature column, [d,1], where d is the number of entries in Mean. The size is checked rather than broadcast.
- Output – y, a [1,1] scalar: the distance, or its square. This block reduces a vector to one number, so it changes the signal dimension.
Parameters
- Mean – μ, a [d,1] column: the centre of the fitted distribution. The number of entries sets d.
- Inverse Covariance – Sinv, a [d,d] matrix, and note that it is the inverse. This block does not invert anything: matrix inversion is O(d³), needs pivoting to be numerically sound, and the HDL targets cannot do it at all. Invert the fitted covariance once where the model was trained and paste the result here, exactly as you would any other weight. For a distance to be real, Sinv must be positive semi-definite – which the inverse of a genuine covariance always is.
- Output
- Distance – y = √q, in units of standard deviations. The default, and the one to read when a human is looking at the number.
- Squared distance – y = q, skipping the root. This is usually the better one to threshold: under the fitted model q follows a chi-squared distribution with d degrees of freedom, so a limit can be looked up rather than guessed, and no square root is computed at all.
- Sampling Time (s) – zero or less inherits the solver's rate; a positive value runs the block at that period.
Code export
All ten targets: Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog and PLC Structured Text. μ and Sinv are baked into the generated code as literals at full precision; there is no tunable parameter, because a fitted statistic is not something to retune on the target.
The three HDL targets are simulation-only, for two independent
reasons: the distance form contains a square root, and the quadratic form
squares the input's dynamic range while a novelty score is unbounded
above by construction – it is large exactly when something has gone wrong,
which is the worst case to let saturate. They read the port with
to_real, compute in real, and quantize back with
to_fx. They simulate correctly and are not offered for synthesis.
Simulink bridge
None. Neither the Statistics and Machine Learning Toolbox nor
the Deep Learning Toolbox is installed here, so a bridge could not be run
against a parity testbench even if one were written – and it is that
toolbox's mahal / pdist2 that would be the reference.
Base Simulink has no equivalent: the quadratic form there is a Subtract, a
matrix Gain, a Dot Product and a Sqrt wired together, and mapping this block onto
any one of the four would claim an equivalence false for the other three. The
bridge reports the block rather than dropping it silently, and it has no
parity testbench, which is the documented consequence of
Support::None rather than a gap. Code export verification still
covers it across all ten languages.
Notes
- Algebraic and stateless: the output depends only on the current sample, so the score reacts immediately and carries no memory of how long the input has been drifting. Follow it with a filter if you want persistence.
- No state space, deliberately: the map is quadratic in u and then takes a root, so it is nonlinear twice over and no A/B/C/D is true of it.
- The full d×d form is summed, not the upper triangle. A fitted Sinv is symmetric, but nothing here enforces it, and summing every term means the block computes what you actually gave it rather than quietly symmetrizing a matrix you may have pasted wrong.
- With Sinv = the identity this reduces to plain Euclidean distance from μ, which is a useful thing to check a configuration against.
Code facts#
| Fact | Value |
|---|---|
| registered type | Machine_Learning/Anomaly_Detection/Mahalanobis_Distance |
| family | Machine_Learning/Anomaly_Detection |
| solver environment class | ICoreBlock_0_Machine_Learning_1_Anomaly_Detection_2_Mahalanobis_Distance |
| source | src/ICoreSDK/ICoreBlockLibrary/Blocks/Machine_Learning/Anomaly_Detection/Mahalanobis_Distance/ICoreBlock_0_Machine_Learning_1_Anomaly_Detection_2_Mahalanobis_Distance.cpp |
| header | src/ICoreSDK/ICoreBlockLibrary/Blocks/Machine_Learning/Anomaly_Detection/Mahalanobis_Distance/ICoreBlock_0_Machine_Learning_1_Anomaly_Detection_2_Mahalanobis_Distance.h |
| default size on canvas | 130 × 80 px |
| ports at insert | 1 in, 1 out |
| code generators implemented | Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text |
Ports#
| # | Direction | Signal type | Description label |
|---|---|---|---|
| 1 | in | ICoreDouble | u |
| 2 | out | ICoreDouble | y |
Ports the constructor creates. A block whose port list changes with its configuration adds or removes ports at load time; the count above is the one a freshly inserted block has.
Configuration variables#
| Config variable | Default | Simulink parameter |
|---|---|---|
Mean | [0.2; -0.4; 0.6] | — |
Inverse Covariance | [1.5 0.3 -0.2; 0.3 0.9 0.4; -0.2 0.4 2.1] | — |
Output | Distance%~%Squared distance~~Distance | — |
Every block also carries Sampling Time (s) from ICoreBlockSolverEnvironment: zero or less inherits the solver's rate, a positive value runs the block at that period.
Simulink bridge#
| support | Support::None |
| Simulink path | — |
| port-count rule | PortsParam::None |
SampleTime parameter | yes |
Caveat (shown to the user): no verifiable Simulink equivalent. The reference would be the Statistics and Machine Learning Toolbox (mahal/pdist2), which is not installed on this machine, so a bridge could not be run against a parity testbench even if one were written. DSP System Toolbox is installed but ships no covariance-weighted distance. Base Simulink assembles the quadratic form from a Subtract, a matrix Gain, a Dot Product and a Sqrt, and mapping onto any one of the four would claim an equivalence false for the other three. Re-create it from those and paste the same mean and inverse covariance
Catalog contract: src/ICoreSDK/ICoreCoder/ICoreCommandSystem/SimulinkBridge/ICoreSimulinkBlockCatalog.h
Description vs code#
The checker has a blind spot here — it could not resolve something (a grouped port bullet, a computed config name), which is reported and never counted as a pass. A reader has to settle it:
B0every stimulus in the sample errored — cross-checks skipped
The verdict above is
tools/docs/check_block_descriptions.py(P7.1), which compares LISTS. It cannot read a sentence: "stateless" on a block with a state, an initial-value semantic the recursion does not implement, a "not synthesizable" caveat the HDL banner contradicts. That is the agent audit (P7.3) on BLOCK_DESCRIPTION_AUDIT.md, and this tool's green is not a substitute for one.
File banner (developer view)#
The top comment of the block's .cpp — the maths, the realization and the export strategy, addressed to whoever changes it. It must not contradict the description above (P7.5).
Mahalanobis Distance — how far this sample sits from the distribution the model was fitted on q = (u - mu)' * Sinv * (u - mu) y = sqrt(q), or q itself as a mode
The one monitor that uses the COVARIANCE STRUCTURE rather than per-feature ranges. A sample can sit inside every individual feature's envelope and still be far away, if the features moved in a combination the training data never showed -- and that is exactly the case an Input_Domain_Monitor style range check cannot see.
⚠ Sinv is the INVERSE covariance, taken as config. No block body inverts a matrix: it is O(d^3), it needs pivoting to be numerically sound, and the three HDL targets cannot do it at all. It is a fitted artefact like any weight -- invert it once where the model was trained.
⚠ The three HDL targets are SIMULATION-ONLY, on two independent grounds. The distance form has a square root; and the quadratic form SQUARES the input's dynamic range while a novelty score is unbounded above by construction -- it is large precisely when something is wrong, which is the case you least want saturating in Q16.16. That is Recursive IIR's reasoning, not Standard_Scaler's: the escape hatch is taken here because the ARITHMETIC needs it, not because nobody looked.
⚠ The full d x d form is emitted, not the upper triangle. A fitted Sinv is symmetric, but nothing here enforces that and a user may paste one that is not; summing every term means the block computes what was actually given rather than silently symmetrizing it.
Sample results#
No stimulus produced a sampled output in this rig — Invalid input size at: ICore Blocks/Home/Mahalanobis Distance. That is a fact about the single-block rig, not a verdict on the block: an offline batch fit, a block whose output only appears at onSolverFinish, or one that needs a driven environment cannot be exercised alone.
Category unsampled · sample time 0.1 · 60 steps · commit ccf005c8 · produced by docsSample --out <folder> --steps 60
Sample data: docs/generated/samples/Machine_Learning__Anomaly_Detection__Mahalanobis_Distance.json