Overview / Machine learning

Ml::Anomaly

Beta

Detects anomalies and change without labels. Produces a calibrated score with a reason, for a review queue. The module never acts. Requires <code>Ml::Trees</code>.

Optional module: turn it on with -DETHEREAL_ML_ANOMALY=ONInclude #include <ethereal/cpp/ml/anomaly/anomaly_common.hpp>C layer

anomaly_common.hpp

#include <ethereal/cpp/ml/anomaly/anomaly_common.hpp>

Shared types of the Ml::Anomaly module.

What the anomaly detectors share: the detector interface, the output, the sink for findings and the allowlist.

False positives drive the design. A detector at 0.1% false positives, running over a million players, flags a thousand innocent players per pass. The output of an anomaly detector feeds a review queue. It does not decide punishments. So, in this module:

  • The output is a score with an explanation (the contributions). There is no verdict.
  • The threshold is given as a flag rate ("flag 0.1%"), so the load on the queue is predictable.
  • Findings go to a sink owned by the integrator (the Guard glue, a queue). The module does not act on any of them.
  • There is an allowlist. Legitimate outliers always exist, and flagging the same known entity forever destroys the trust in the queue.
struct

SDetectorOutput

Ethereal::Ml::Anomaly#
C++
struct   SDetectorOutput   final
{
    /// @brief  Raw score of the detector (higher is more anomalous). It is not a
    ///             probability and is not comparable between detectors. That is what the
    ///             calibration is for.
    ETL_DOUBLE                dRaw = 0.0;

    /// @brief  Where the detector writes the contribution of each feature (higher is
    ///             more responsible for the anomaly). Empty when not requested.
    std::span< float >        Contributions;
};

What a detector gives for one sample.

struct

IDetector

Ethereal::Ml::Anomaly#
C++
struct   IDetector
{
    /// @brief  Number of features the detector reads.
    ///
    virtual std::size_t FeatureCount() const ETL_NOEXCEPT = 0;


    ///
    /// Score
    ///
    /// @brief  Scores one sample.
    ///
    /// @param Features        The sample.
    /// @param pOut            Receives the raw score, and the contributions when requested.
    ///
    /// @return  eOk or an error status.
    ///
    virtual EStatus Score( std::span< const float > Features, SDetectorOutput * pOut ) ETL_NOEXCEPT = 0;


    /// @brief  Destructor.
    ///
    virtual ~IDetector() = default;
};

A detector, for the ensemble.

Implemented by the Isolation Forest, Mahalanobis, LOF and the statistical tests, and by the integrator.

struct

SAnomalyFinding

Ethereal::Ml::Anomaly#
C++
struct   SAnomalyFinding   final
{
    /// @brief  Entity key. Valid until the sink returns.
    std::string_view        sEntity;

    /// @brief  Calibrated score (0..1).
    ETL_DOUBLE                dScore = 0.0;

    /// @brief  Detectors that fired.
    ETL_UINT32                uTriggeredMask = 0u;

    /// @brief  Contribution of each feature. Valid until the sink returns.
    std::span< const float >    Contributions;

    /// @brief  Timestamp of the sample, in nanoseconds.
    ETL_INT64                iTimestampNs = 0;
};

A finding: an entity that crossed the threshold, with the reason.

struct

IFindingSink

Ethereal::Ml::Anomaly#
C++
struct   IFindingSink
{
    /// @brief  Receives one finding.
    ///
    /// @param Finding    The finding.
    ///
    virtual void OnFinding( const SAnomalyFinding & Finding ) ETL_NOEXCEPT = 0;


    /// @brief  Destructor.
    ///
    virtual ~IFindingSink() = default;
};

Where the findings go. The module never acts, it only delivers here.

class

CAllowlist

Ethereal::Ml::Anomaly#

Entities known to be legitimate. A finding about them is not delivered.

class CAllowlist final

Fixed capacity, chosen in Init, and no allocations after that. Keys are stored by their 64 bit hash (FNV-1a with the SplitMix64 finalizer). The chance of two different keys colliding in a list of one million is about 1e-8.

function

Init

#
EStatus Init( std::size_t uCapacity );

Reserves the table.

uCapacity
Maximum number of entities.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Add

#
EStatus Add( std::string_view sEntity ) noexcept;

Adds an entity. Adding one already present is not an error.

sEntity
Entity key.
eOk, eNotLoaded, or EStatus::eTableFull when the list is full.
function

Remove

#
EStatus Remove( std::string_view sEntity ) noexcept;

Removes an entity.

sEntity
Entity key.
eOk, eNotLoaded or eUnknownEntity.
function

Contains

#
bool Contains( std::string_view sEntity ) const noexcept;

true when the entity is in the list.

sEntity
Entity key.
function

Size

#
std::size_t Size() const noexcept

Number of entities in the list.

function

HashKey

Ethereal::Ml::Anomaly#
ETL_UINT64 HashKey( std::string_view s ) noexcept;

Hash of the keys (entities, streams): FNV-1a and the SplitMix64 finalizer.

s
The key.
The 64 bit hash.

calibration.hpp

#include <ethereal/cpp/ml/anomaly/calibration.hpp>

Calibration and threshold of the Ml::Anomaly module.

Both are essential and both are usually forgotten.

A raw score is not a probability and is not comparable between detectors: 0.62 from an Isolation Forest and 4.1 from a Mahalanobis say nothing about each other. The calibration is the distribution function of the scores on the training data (normal data), stored with the model as a quantile table. The calibrated score of a sample is the fraction of the training data below it. On new normal data the calibrated score is uniform in [0, 1] (the suite checks it with a Kolmogorov-Smirnov test).

The threshold is given as a rate: "flag 0.1% of the samples". The module finds the raw score that gives that rate on the training data. It is the only way for a threshold to survive a change in the data. A fixed cut on the raw score changes meaning when the data changes, and nobody notices.

When the data does change, it is reported. CFlagRateMonitor counts the real flag rate in a window and reports when it is no longer the requested one (a binomial test), so the load on the review queue does not triple silently.

class

CCalibration

Ethereal::Ml::Anomaly#

Calibration of raw scores by a quantile table of the training scores.

class CCalibration final
function

Fit

#
EStatus Fit( std::span< const ETL_DOUBLE > TrainScores, ETL_UINT32 uQuantiles = 4097u );

Builds the table from the raw training scores.

Stores uQuantiles quantiles (0%, ..., 100%, from 2 to 1 048 577). More quantiles give smaller rates with precision (with 4097, each step is 0.024%).

TrainScores
Raw scores on normal training data. NaNs are ignored.
uQuantiles
Number of quantiles.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Init

#
EStatus Init( std::span< const ETL_DOUBLE > QuantileTable );

Takes a stored table.

QuantileTable
The quantiles, in ascending order.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Calibrate

#
ETL_DOUBLE Calibrate( ETL_DOUBLE dRaw ) const noexcept;

The calibrated score (0..1): the fraction of the training data below dRaw, by linear interpolation of the table.

dRaw
The raw score.
The calibrated score, or NaN without a table or with a NaN score.
function

ThresholdForRate

#
ETL_DOUBLE ThresholdForRate( ETL_DOUBLE dRate ) const noexcept;

The raw score from which the fraction dRate of the training data is flagged.

dRate
The flag rate, from 0 to 1.
The raw threshold, or NaN without a table or with a rate out of range.
function

QuantileTable

#
std::span< const ETL_DOUBLE > QuantileTable() const noexcept

The quantile table.

function

IsFitted

#
bool IsFitted() const noexcept

true when there is a table.

enum

EThresholdState

Ethereal::Ml::Anomaly#
C++
enum class   EThresholdState : ETL_UINT8
{
    /// @brief  Not enough samples yet to tell.
    eInsufficient = 0,

    /// @brief  The real rate is the requested one (within the noise).
    eHolds,

    /// @brief  The real rate moved away. The data changed, recalibrate.
    eNoLongerHolds
};

State of the threshold, as seen by CFlagRateMonitor.

class

CFlagRateMonitor

Ethereal::Ml::Anomaly#

The real flag rate, in a window of the last N decisions, against the requested one.

class CFlagRateMonitor final

Reports eNoLongerHolds when the count moves away from the expected one by more than dZ binomial deviations and by more than the relative tolerance. Both are required, so a small deviation in a large window does not fire, and a large deviation in a small window is not hidden by the noise.

function

Init

#
EStatus Init( ETL_DOUBLE dTargetRate, ETL_UINT32 uWindow, ETL_DOUBLE dTolerance = 0.2, ETL_DOUBLE dZ = 3.0 );

Reserves the window and clears the counts.

dTargetRate
The requested flag rate, in (0, 1).
uWindow
Window size in decisions, from 64 to 2^30.
dTolerance
Relative tolerance on the count.
dZ
Number of binomial deviations.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Observe

#
void Observe( bool bFlagged ) noexcept;

Records one decision.

bFlagged
true when the sample was flagged.
function

State

#
EThresholdState State() const noexcept;

The state of the threshold.

function

ObservedRate

#
ETL_DOUBLE ObservedRate() const noexcept;

The flag rate observed in the window.

change.hpp

#include <ethereal/cpp/ml/anomaly/change.hpp>

Change detection for the Ml::Anomaly module.

Detects when the behaviour of a single stream (a player, a session) changes over time. A stream is compared against its own past, not against the population, which is what catches a player who was legitimate last week.

Four detectors are provided, all with fixed state per stream and no allocations after Init:

  • CUSUM, tabular and two sided.
  • The EWMA control chart.
  • Page-Hinkley, which needs no target mean.
  • ADWIN2, an adaptive window over an exponential histogram.

Every report carries the change point, the direction and the magnitude. Sample indices are those of the stream, the first sample is index 1. After a report the detector restarts, the index keeps counting.

enum

EChangeDetector

Ethereal::Ml::Anomaly#
C++
enum class   EChangeDetector : ETL_UINT8
{
    /// @brief  Two sided tabular CUSUM.
    eCusum = 0,

    /// @brief  EWMA control chart.
    eEwma,

    /// @brief  Page-Hinkley test.
    ePageHinkley,

    /// @brief  ADWIN2 adaptive window.
    eAdwin
};

Identifies the detector that produced a report.

struct

SChangeReport

Ethereal::Ml::Anomaly#
C++
struct   SChangeReport   final
{
    /// @brief  Detector that fired.
    EChangeDetector        eDetector = EChangeDetector::eCusum;

    /// @brief  +1 when the mean went up, -1 when it went down.
    ETL_INT8            iDirection = 0;

    /// @brief  Estimated first sample of the new regime.
    ETL_UINT64            uChangePoint = 0u;

    /// @brief  Sample that made the detector fire.
    ETL_UINT64            uDetectedAt = 0u;

    /// @brief  Estimated change of the mean, in data units.
    ETL_DOUBLE            dMagnitude = 0.0;

    /// @brief  Detector statistic at the moment it fired.
    ETL_DOUBLE            dStatistic = 0.0;
};

A detected change.

struct

SCusumParams

Ethereal::Ml::Anomaly#
C++
struct   SCusumParams   final
{
    /// @brief  Target mean (mu0).
    ETL_DOUBLE    dTarget = 0.0;

    /// @brief  Standard deviation while in control.
    ETL_DOUBLE    dSigma = 1.0;

    /// @brief  Slack, in sigmas. Usually half of the shift to detect.
    ETL_DOUBLE    dK = 0.5;

    /// @brief  Decision threshold, in sigmas.
    ETL_DOUBLE    dH = 5.0;
};

CUSUM parameters.

class

CCusum

Ethereal::Ml::Anomaly#

Two sided tabular CUSUM.

class CCusum final

With z = (x - mu0) / sigma, the detector keeps S+ = max(0, S+ + z - k) and S- = max(0, S- - z - k), and fires when either goes above h. The change point is the start of the current run (the last time S was zero). The magnitude is sigma (k + S / N), as in Montgomery.

function

Init

#
EStatus Init( const SCusumParams & Params ) noexcept;

Validates the parameters and resets the detector.

Params
Detector parameters.
eOk, or eInvalidArgument when a parameter is out of range. EStatus::eNotLicensed when the library is not licensed.
function

Update

#
bool Update( const ETL_DOUBLE x, SChangeReport * const pOut ) noexcept

Feeds one sample.

x
The sample.
pOut
Receives the report when the detector fires. May be null.
true when the detector fired.
function

Reset

#
void Reset() noexcept;

Clears the sums. The sample index is kept.

function

Upper

#
ETL_DOUBLE Upper() const noexcept

Current upper sum (S+).

function

Lower

#
ETL_DOUBLE Lower() const noexcept

Current lower sum (S-).

struct

SEwmaChartParams

Ethereal::Ml::Anomaly#
C++
struct   SEwmaChartParams   final
{
    /// @brief  Target mean (mu0).
    ETL_DOUBLE    dTarget = 0.0;

    /// @brief  Standard deviation while in control.
    ETL_DOUBLE    dSigma = 1.0;

    /// @brief  Weight of the new sample, 0 < lambda <= 1.
    ETL_DOUBLE    dLambda = 0.2;

    /// @brief  Width of the control limits, in sigma_z.
    ETL_DOUBLE    dL = 3.0;

    /// @brief  true uses the exact limits, which are narrower at the start.
    ///             false uses the asymptotic limits.
    bool        bExactLimits = true;
};

EWMA chart parameters.

class

CEwmaChart

Ethereal::Ml::Anomaly#

EWMA control chart.

class CEwmaChart final

z = lambda x + (1 - lambda) z, starting at mu0. Fires outside mu0 +- L sigma sqrt( lambda / (2 - lambda) (1 - (1 - lambda)^(2t)) ). The change point is the sample where z crossed to the side it is on.

function

Init

#
EStatus Init( const SEwmaChartParams & Params ) noexcept;

Validates the parameters and resets the chart.

Params
Chart parameters.
eOk, or eInvalidArgument when a parameter is out of range. EStatus::eNotLicensed when the library is not licensed.
function

Update

#
bool Update( const ETL_DOUBLE x, SChangeReport * const pOut ) noexcept

Feeds one sample.

x
The sample.
pOut
Receives the report when the chart fires. May be null.
true when the chart fired.
function

Reset

#
void Reset() noexcept;

Restarts the chart at the target mean. The sample index is kept.

function

Value

#
ETL_DOUBLE Value() const noexcept

Current value of z.

struct

SPageHinkleyParams

Ethereal::Ml::Anomaly#
C++
struct   SPageHinkleyParams   final
{
    /// @brief  Magnitude tolerance, in data units.
    ETL_DOUBLE    dDelta = 0.005;

    /// @brief  Decision threshold.
    ETL_DOUBLE    dLambda = 50.0;

    /// @brief  The test does not fire before this many samples, while the mean settles.
    ETL_UINT32    uMinSamples = 30u;
};

Page-Hinkley parameters.

class

CPageHinkley

Ethereal::Ml::Anomaly#

Page-Hinkley test, both directions.

class CPageHinkley final

Increases: m = sum (x - mean_t - delta), fires when m - min(m) > lambda. Decreases: m' = sum (x - mean_t + delta), fires when max(m') - m' > lambda.

function

Init

#
EStatus Init( const SPageHinkleyParams & Params ) noexcept;

Validates the parameters and resets the test.

Params
Test parameters.
eOk, or eInvalidArgument when a parameter is out of range. EStatus::eNotLicensed when the library is not licensed.
function

Update

#
bool Update( ETL_DOUBLE x, SChangeReport * pOut ) noexcept;

Feeds one sample.

x
The sample.
pOut
Receives the report when the test fires. May be null.
true when the test fired.
function

Reset

#
void Reset() noexcept;

Clears the running mean and sums. The sample index is kept.

const

ADWIN_MAX_ROWS

Ethereal::Ml::Anomaly#
inline constexpr ETL_UINT32 ADWIN_MAX_ROWS = 32u;

Rows of the exponential histogram. Row i holds buckets of 2^i values, so the window can hold about 5 * 2^32 values.

const

ADWIN_BUCKETS

Ethereal::Ml::Anomaly#
inline constexpr ETL_UINT32 ADWIN_BUCKETS = 5u;

Buckets per row (M in the paper).

const

ADWIN_ROW0_CAPACITY

Ethereal::Ml::Anomaly#
inline constexpr ETL_UINT32 ADWIN_ROW0_CAPACITY = 40u;

Buckets kept in row 0 (the input row) before a merge. Merges wait for the next check, or for row 0 to fill up, and are done in one pass.

struct

SAdwinParams

Ethereal::Ml::Anomaly#
C++
struct   SAdwinParams   final
{
    /// @brief  Confidence. Probability of a false cut in one check.
    ETL_DOUBLE    dDelta = 0.002;

    /// @brief  The window is checked once every uClock samples.
    ETL_UINT32    uClock = 32u;

    /// @brief  Minimum number of values on each side of a cut.
    ETL_UINT32    uMinSide = 5u;

    /// @brief  Range of the values. The Bernstein term assumes it.
    ETL_DOUBLE    dRange = 1.0;
};

ADWIN parameters.

class

CAdwin

Ethereal::Ml::Anomaly#

ADWIN2 with the variance aware bound.

class CAdwin final

eps = sqrt( 2/m sigma^2 ln(2/delta') ) + 2R/(3m) ln(2/delta'), with m = 1 / (1/n0 + 1/n1), R the range of the values and delta' = delta / C, where C is the number of cuts a check looks at (the bucket boundaries). By the union bound, the chance of a false cut in one check is at most delta.

The state is fixed, about 3.4 KB (32 rows of 5 buckets plus 40 buckets in the input row).

function

Init

#
EStatus Init( const SAdwinParams & Params ) noexcept;

Validates the parameters and empties the window.

Params
Detector parameters.
eOk, or eInvalidArgument when a parameter is out of range. EStatus::eNotLicensed when the library is not licensed.
function

Reset

#
void Reset() noexcept;

Empties the window. The sample index and the check counter are kept.

function

Update

#
bool Update( const ETL_DOUBLE x, SChangeReport * const pOut ) noexcept

Feeds one sample.

Inlined. Storing the sample and counting is all that runs on most samples. The check runs out of line once every uClock samples. As an out of line call, this path cost about 17 cycles, most of it in the call itself.

x
The sample.
pOut
Receives the report on a cut. May be null.
true when the window was cut.
function

Width

#
ETL_UINT64 Width() const noexcept

Number of values in the window.

function

Mean

#
ETL_DOUBLE Mean() const noexcept;

Mean of the values in the window.

function

Checks

#
ETL_UINT64 Checks() const noexcept

Number of checks so far, which is the number of chances for a false cut.

struct

SStreamMonitorParams

Ethereal::Ml::Anomaly#
C++
struct   SStreamMonitorParams   final
{
    /// @brief  Maximum number of streams (entities).
    ETL_UINT32                uCapacity = 1024u;

    /// @brief  When the table is full, true rejects the new stream and false
    ///             evicts the least recently used one.
    bool                    bRejectWhenFull = false;

    /// @brief  Detectors enabled for every stream.
    bool                    bCusum = true;
    bool                    bEwma = false;
    bool                    bPageHinkley = false;
    bool                    bAdwin = false;

    /// @brief  Parameters of each detector.
    SCusumParams            Cusum;
    SEwmaChartParams        Ewma;
    SPageHinkleyParams        PageHinkley;
    SAdwinParams            Adwin;
};

Stream monitor parameters.

class

CStreamMonitor

Ethereal::Ml::Anomaly#

Change detectors for many streams, in a table of fixed capacity.

class CStreamMonitor final

Works like the entity table of Ml::Features, so a server that runs for months does not grow. Streams are stored by the 64 bit hash of their key.

constructor

CStreamMonitor

#
CStreamMonitor() noexcept;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const SStreamMonitorParams & Params );

Validates the parameters and reserves the whole table.

This is the only call that allocates.

Params
Monitor parameters.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Update

#
EStatus Update( std::string_view sStream, ETL_DOUBLE x, std::span< SChangeReport > Out, std::size_t * pReports ) noexcept;

Feeds one sample of a stream.

sStream
Stream key.
x
The sample.
Out
Receives the reports, up to one per detector.
pReports
Receives the number of reports.
eOk, eBufferTooSmall when Out is too short, eTableFull, eNotLoaded or eInvalidArgument.
function

Reset

#
EStatus Reset( std::string_view sStream ) noexcept;

Removes a stream and its detectors from the table.

sStream
Stream key.
eOk, eUnknownEntity or eNotLoaded.
function

StreamCount

#
std::size_t StreamCount() const noexcept;

Number of streams in the table.

function

Evicted

#
ETL_UINT64 Evicted() const noexcept;

Number of streams evicted to make room.

function

Rejected

#
ETL_UINT64 Rejected() const noexcept;

Number of new streams rejected with the table full.

function

BytesPerStream

#
static std::size_t BytesPerStream( const SStreamMonitorParams & Params ) noexcept;

Bytes used by one stream with the given configuration.

function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept;

Bytes used by the whole table.

ensemble.hpp

#include <ethereal/cpp/ml/anomaly/ensemble.hpp>

Anomaly ensemble of the Ml::Anomaly module.

Several detectors, one calibrated score, the reason, and the findings.

Each detector is calibrated on the training data before being combined, because raw scores are not comparable. The combination is done on the calibrated scores (or on the standardized z), and the result is calibrated again by the ensemble itself. So 'fScore' is uniform on normal data, and a threshold of "flag 0.1%" means 0.1% whatever the combination.

  • eMax: the largest calibrated score (catches what any one detector sees).
  • eMean: the mean of the z (the raw score of each detector, minus its training mean, over its deviation).
  • eWeighted: the mean of the calibrated scores, with the weights given to AddDetector.
  • eRankAverage: the mean of the calibrated scores (the ranks against the training data).

The module never acts. Process delivers to the IFindingSink the entities that cross the threshold and are not in the allowlist. The output goes to a review queue and punishes no one (see the note in 'anomaly_common.hpp').

enum

ECombine

Ethereal::Ml::Anomaly#
C++
enum class   ECombine : ETL_UINT8
{
    /// @brief  The largest calibrated score.
    eMax = 0,

    /// @brief  The mean of the standardized raw scores (z).
    eMean,

    /// @brief  The weighted mean of the calibrated scores.
    eWeighted,

    /// @brief  The mean of the calibrated scores (ranks against the training data).
    eRankAverage
};

How the ensemble combines the detectors.

enum

EExplain

Ethereal::Ml::Anomaly#
C++
enum class   EExplain : ETL_UINT8
{
    /// @brief  Only the samples that cross the threshold (the default).
    eWhenFlagged = 0,

    /// @brief  All samples (tests, offline analysis).
    eAlways,

    /// @brief  None.
    eNever
};

When the ensemble asks the detectors for contributions.

They are expensive. Those of the Isolation Forest are the exact TreeSHAP (~0.75 ms on a forest of 100 trees, against ~0.6 us for the score). Only a flagged sample needs a reason, so by default only those pay for it (the detectors score twice, and the second pass gives the same value).

struct

SAnomalyResult

Ethereal::Ml::Anomaly#
C++
struct   SAnomalyResult   final
{
    /// @brief  Calibrated score, 0..1 (uniform on normal data).
    float                        fScore = 0.0f;

    /// @brief  Fraction of the detectors that agree with the decision.
    float                        fConfidence = 0.0f;

    /// @brief  Bit d set: detector d alone crossed the threshold.
    ETL_UINT32                    iTriggeredMask = 0u;

    /// @brief  Combination of the detector contributions. Valid until the next
    ///             sample. Empty when not requested (see @ref EExplain).
    std::span< const float >    Contributions;
};

Result for one sample.

const

ENSEMBLE_MAX_DETECTORS

Ethereal::Ml::Anomaly#
inline constexpr std::size_t ENSEMBLE_MAX_DETECTORS = 32u;

Maximum number of detectors (the bits of 'iTriggeredMask').

class

CAnomalyEnsemble

Ethereal::Ml::Anomaly#

Several calibrated detectors combined into one calibrated score.

class CAnomalyEnsemble final
function

Init

#
EStatus Init( std::size_t uFeatures, ECombine eMode = ECombine::eMax, ETL_DOUBLE dFlagRate = 0.001 );

Sets the shape of the ensemble and reserves the work buffers.

uFeatures
Number of features of each sample.
eMode
How the detectors are combined.
dFlagRate
Fraction of normal samples to flag (0.001 = 0.1%).
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

AddDetector

#
EStatus AddDetector( IDetector * pDetector, float fWeight = 1.0f );

Adds a detector (before Fit).

The detector belongs to the caller and must live as long as the ensemble.

pDetector
The detector.
fWeight
Weight for eWeighted, positive and finite.
eOk, eNotLoaded, eInvalidArgument or eTableFull.
function

Fit

#
EStatus Fit( const SFeatureMatrix & NormalData );

Calibrates each detector and the ensemble on normal data.

Allocates (only here).

NormalData
Normal samples, rows x columns (at least 100 rows).
eOk, eNotLoaded, eInvalidArgument, eOutOfMemory or the error of a detector.
function

SerializeCalibration

#
EStatus SerializeCalibration( std::vector< ETL_UINT8 > * pOut ) const;

The calibration, to be stored with the model.

Format 'ETLE': the quantile tables of each detector and of the ensemble, and the mean and deviation of each detector. A threshold only means the same tomorrow if the calibration is the same.

pOut
Receives the bytes.
eOk, eInvalidArgument, eNotLoaded or eOutOfMemory.
function

LoadCalibration

#
EStatus LoadCalibration( std::span< const ETL_UINT8 > Bytes );

Loads a stored calibration, in an ensemble with the same detectors (after the AddDetector calls, instead of Fit).

Allocates (only here).

Bytes
The serialized calibration.
EStatus::eSpecMismatch when it was made for another number of detectors or features, or another combination. EStatus::eBadMagic, EStatus::eVersionTooNew, EStatus::eTruncated, EStatus::eCorrupt. EStatus::eNotLicensed when the library is not licensed.
function

Score

#
EStatus Score( std::span< const float > Features, SAnomalyResult * pOut ) noexcept;

Scores one sample. No allocations.

Features
The sample.
pOut
Receives the result.
eOk, eInvalidArgument, eNotLoaded, eFeatureMismatch or the error of a detector.
function

Process

#
EStatus Process( std::string_view sEntity, ETL_INT64 iTimestampNs, std::span< const float > Features, SAnomalyResult * pOut ) noexcept;

Score, and the finding to the sink when it crosses the threshold and the entity is not in the allowlist. It does not act.

sEntity
Entity key.
iTimestampNs
Timestamp of the sample, in nanoseconds.
Features
The sample.
pOut
Receives the result.
The same as Score.
function

SetFindingSink

#
void SetFindingSink( IFindingSink * p ) noexcept

Sets the sink of the findings (null: none).

function

SetExplain

#
void SetExplain( EExplain e ) noexcept

Sets when contributions are computed.

function

Explain

#
EExplain Explain() const noexcept

When contributions are computed.

function

SetAllowlist

#
void SetAllowlist( const CAllowlist * p ) noexcept

Sets the allowlist (null: none).

function

SetFlagRate

#
EStatus SetFlagRate( ETL_DOUBLE dFlagRate ) noexcept;

Sets the flag rate, in (0, 1).

dFlagRate
Fraction of normal samples to flag.
eOk or eInvalidArgument.
function

FlagRate

#
ETL_DOUBLE FlagRate() const noexcept

The flag rate.

function

DetectorCount

#
std::size_t DetectorCount() const noexcept

Number of detectors.

function

DetectorCalibration

#
const CCalibration & DetectorCalibration( std::size_t d ) const noexcept

Calibration of detector d.

function

Calibration

#
const CCalibration & Calibration() const noexcept

Calibration of the ensemble.

function

LastCombined

#
ETL_DOUBLE LastCombined() const noexcept

The combined value (before the calibration of the ensemble), for the tests.

function

Suppressed

#
ETL_UINT64 Suppressed() const noexcept

Findings silenced by the allowlist.

iforest.hpp

#include <ethereal/cpp/ml/anomaly/iforest.hpp>

Isolation Forest of the Ml::Anomaly module.

The workhorse. Cheap, effective on tabular data, and with no distance metric to tune.

There is one tree descent in the SDK. An Isolation Forest is a set of trees whose leaves hold the path length, so it is a model of Ml::Trees ('.etltree' with the 'eAnomaly' objective and the 'eIsolation' transform). It is loaded, validated and descended by the same code (loading tested against hostile files, branchless AVX2 descent). Training is done in Python (scikit-learn). 'tools/ml_reference/export_iforest.py' exports it and 'etl-trees convert --format sklearn-iforest' converts it.

The score is the one of scikit-learn: 2^(-E[h(x)] / c(psi)), with E[h] the mean path length (the leaf depth plus c(samples in the leaf)) and c(psi) the normalization. 0.5 is normal, close to 1 is anomalous. It is '-score_samples' (scikit-learn returns it with the sign flipped).

The reason for each flag: the contributions are the exact TreeSHAP of the normalized path, with the sign flipped (positive means the feature isolated the point faster and pushed it towards anomalous). They add up to the mean training path minus the path of the point.

class

CIsolationForest

Ethereal::Ml::Anomaly#

Isolation Forest detector, over a Trees::CTreeModel.

class CIsolationForest final : public IDetector
function

Load

#
EStatus Load( std::span< const ETL_UINT8 > Model, Trees::ELoadCheck eCheck = Trees::ELoadCheck::eFull );

Loads from memory (borrowed, 16 byte aligned, as CTreeModel).

Model
The model bytes.
eCheck
How much of the model is validated.
The status of the load, or EStatus::eUnsupported when the model is not an Isolation Forest. EStatus::eNotLicensed when the library is not licensed.
function

LoadFile

#
EStatus LoadFile( std::string_view sPath, Trees::ELoadCheck eCheck = Trees::ELoadCheck::eFull );

Loads from a file.

sPath
Path of the model.
eCheck
How much of the model is validated.
The same as Load. EStatus::eNotLicensed when the library is not licensed.
function

FeatureCount

#
std::size_t FeatureCount() const noexcept override

Number of features.

function

Score

#
EStatus Score( std::span< const float > Features, SDetectorOutput * pOut ) noexcept override;

The anomaly score (0..1) in 'dRaw', and the contributions when requested. No allocations.

Features
The sample.
pOut
Receives the score and the contributions.
eOk, eInvalidArgument, eBufferTooSmall or the error of the model.
function

ScoreBatch

#
EStatus ScoreBatch( const SFeatureMatrix & In, std::span< float > Out ) const noexcept;

Scores many rows (the fast path of Trees).

In
The rows.
Out
Receives one score per row.
The status of the model.
function

Model

#
const Trees::CTreeModel & Model() const noexcept

The tree model.

lof.hpp

#include <ethereal/cpp/ml/anomaly/lof.hpp>

Local Outlier Factor of the Ml::Anomaly module.

Detection by density. Catches the groups of anomalies the Isolation Forest can miss (a small, dense cluster in a place where nobody should be).

It costs much more than the Isolation Forest. Each sample looks for the k nearest neighbors in the reference set (brute force, O(n d)). With 10 000 points of 5 dimensions that is tens of microseconds (the README publishes the measure as a function of the size of the set). It suits the review queue. Keep it off hot paths. A faster search comes in through the INeighborSearch seam (the VectorIndex, when present).

The model is the reference set: representative normal points, the distance to the k-th neighbor of each one and their local density ('_distances_fit_X_' and '_lrd' in scikit-learn), loaded with the model. The score does not need the whole training data.

The score is the one of scikit-learn with 'novelty=True' ('-score_samples'): lrd(x) = 1 / ( mean_o( max( d(x, o), kdist(o) ) ) + 1e-10 ) LOF(x) = mean_o( lrd(o) / lrd(x) ) with o in the k neighbors of x. About 1: as dense as the neighborhood. Much larger than 1: isolated.

struct

INeighborSearch

Ethereal::Ml::Anomaly#
C++
struct   INeighborSearch
{
    ///
    /// Search
    ///
    /// @brief  The @p k reference points closest to @p Query.
    ///
    /// @param Query        The point.
    /// @param k            Number of neighbors.
    /// @param Indices        Receives the indices, in ascending order of distance.
    /// @param Distances    Receives the Euclidean distances, in ascending order.
    ///
    /// @return  eOk or an error status.
    ///
    virtual EStatus Search( std::span< const ETL_DOUBLE > Query, ETL_UINT32 k, std::span< ETL_UINT32 > Indices,
                            std::span< ETL_DOUBLE > Distances ) ETL_NOEXCEPT = 0;


    /// @brief  Destructor.
    ///
    virtual ~INeighborSearch() = default;
};

Seam for the neighbor search (brute force is the default).

class

CLocalOutlierFactor

Ethereal::Ml::Anomaly#

Local Outlier Factor detector.

class CLocalOutlierFactor final : public IDetector
function

Init

#
EStatus Init( std::span< const ETL_DOUBLE > Reference, std::size_t uDims, std::span< const ETL_DOUBLE > KDistance, std::span< const ETL_DOUBLE > LocalDensity, ETL_UINT32 k );

Takes the reference set, the distance to the k-th neighbor and the local density of each point, and k.

Copies everything (allocates only here).

Reference
Reference set, n x d, row major.
uDims
Dimensions (d).
KDistance
Distance to the k-th neighbor of each point.
LocalDensity
Local density of each point.
k
Number of neighbors.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Fit

#
EStatus Fit( std::span< const ETL_DOUBLE > Reference, std::size_t uDims, ETL_UINT32 k );

Builds the model from the reference set alone, as the 'fit' of scikit-learn.

The k neighbors of each point (not counting itself), the distance to the k-th and the local density. O(n^2 d), meant for building the model once.

Reference
Reference set, n x d, row major.
uDims
Dimensions (d).
k
Number of neighbors.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Serialize

#
EStatus Serialize( std::vector< ETL_UINT8 > * pOut ) const;

The serialized model.

Format 'ETLO': the magic, the version, n, d, k, and the three vectors.

pOut
Receives the bytes.
eOk, eInvalidArgument or eNotLoaded.
function

Load

#
EStatus Load( std::span< const ETL_UINT8 > Bytes );

Loads a serialized model.

Bytes
The bytes of the 'ETLO' format.
eOk, eTruncated, eBadMagic, eVersionTooNew, eCorrupt or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

SetNeighborSearch

#
void SetNeighborSearch( INeighborSearch * p ) noexcept

Sets an external neighbor search (null: brute force).

The search must give the same points, in the same index order.

function

FeatureCount

#
std::size_t FeatureCount() const noexcept override

Number of features.

function

Score

#
EStatus Score( std::span< const float > Features, SDetectorOutput * pOut ) noexcept override;

Scores one sample. The contributions are zeros.

function

Factor

#
EStatus Factor( std::span< const ETL_DOUBLE > X, ETL_DOUBLE * pLof ) noexcept;

The LOF in double (the input is not rounded).

X
The sample.
pLof
Receives the LOF.
eOk, eNotLoaded, eFeatureMismatch or the error of the search.
function

ReferenceSize

#
std::size_t ReferenceSize() const noexcept

Number of points in the reference set.

mahalanobis.hpp

#include <ethereal/cpp/ml/anomaly/mahalanobis.hpp>

Mahalanobis distance of the Ml::Anomaly module.

An outlier in several dimensions, accounting for the correlation between the features. D = sqrt( (x - mu)' S^-1 (x - mu) ).

The inverse is computed once, on load, as the Cholesky decomposition S = L L'. Each sample is then two substitutions (nothing is inverted) with no allocations.

A nearly singular matrix is not hypothetical: two features that are the same measure under another name, a feature that is constant in training, more features than samples. Without regularization the Cholesky either fails or "passes" with a rounding pivot (1e-16), and the inverse gives absurd scores instead of an error. Here, when a pivot is below 1e-12 of the largest (or negative), lambda I is added to S (lambda relative to the mean trace), ten times larger each time, until the decomposition is sound. RidgeApplied tells how much was needed.

The contributions decompose D^2: c_f = (x - mu)_f (S^-1 (x - mu))_f, which add up to D^2. One can be negative (the correlation "explains" part of the deviation of another). The largest is the feature most responsible.

class

CMahalanobis

Ethereal::Ml::Anomaly#

Mahalanobis distance detector.

class CMahalanobis final : public IDetector
function

Init

#
EStatus Init( std::span< const ETL_DOUBLE > Mean, std::span< const ETL_DOUBLE > Covariance, ETL_DOUBLE dRidge = 0.0 );

Takes the mean and the covariance and decomposes the covariance.

Allocates (only here).

Mean
The mean, d values.
Covariance
The covariance, d x d, row major, symmetric.
dRidge
A lambda relative to the mean trace, added from the start (0: only what the matrix needs).
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Fit

#
EStatus Fit( std::span< const ETL_DOUBLE > Data, std::size_t uColumns, ETL_DOUBLE dRidge = 0.0 );

Computes the mean and the sample covariance (n - 1), as 'numpy.cov', and calls Init.

Data
Samples, rows x columns, row major.
uColumns
Number of columns (features).
dRidge
See Init.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

FeatureCount

#
std::size_t FeatureCount() const noexcept override

Number of features.

function

Score

#
EStatus Score( std::span< const float > Features, SDetectorOutput * pOut ) noexcept override;

D in 'dRaw', and the contributions (which add up to D^2) when requested.

Features
The sample.
pOut
Receives the distance and the contributions.
eOk, eInvalidArgument, eNotLoaded or eFeatureMismatch.
function

Distance

#
EStatus Distance( std::span< const ETL_DOUBLE > X, ETL_DOUBLE * pDistance, std::span< ETL_DOUBLE > Contributions = {} ) noexcept;

The same in double (the input is not rounded to float).

X
The sample.
pDistance
Receives D.
Contributions
Receives the contributions when not empty.
eOk, eNotLoaded or eFeatureMismatch.
function

RidgeApplied

#
ETL_DOUBLE RidgeApplied() const noexcept

The lambda that was added (absolute, 0 with a sound matrix).

statistics.hpp

#include <ethereal/cpp/ml/anomaly/statistics.hpp>

Statistical outlier tests of the Ml::Anomaly module.

The z score, the modified z score (median and MAD), IQR and Grubbs.

Trivial, accurate everywhere, and almost always written wrong: with a mean over a distribution that already has the outliers in it. The mean and the standard deviation are dragged by the outliers themselves, and z stops seeing them (10% of extreme values are enough for that). The median and the MAD are not dragged. That is what the modified z score is for, and the suite shows both side by side.

The conventions are those of the reference (scipy/numpy), so the numbers compare without translation:

  • z: (x - mean) / population standard deviation ('scipy.stats.zscore', ddof = 0).
  • Modified z: 0.6745 (x - median) / MAD (Iglewicz and Hoaglin). With a zero MAD, the mean absolute deviation is used: 1.253314 (x - median) / MeanAD. With both zero, 0 at the median and +-infinity elsewhere.
  • IQR: quartiles by linear interpolation ('numpy.percentile'). The fences are Q1 - k IQR and Q3 + k IQR.
  • Grubbs (two sided): G = max |x - mean| / s (sample s), against G_c = (n-1)/sqrt(n) * sqrt( t^2 / (n - 2 + t^2) ), t the alpha/(2n) quantile of Student's t with n - 2 degrees.

The batch functions do not allocate. The median and the quartiles sort a copy in a 'Scratch' buffer of the caller.

function

ZScores

Ethereal::Ml::Anomaly#
EStatus ZScores( std::span< const ETL_DOUBLE > X, std::span< ETL_DOUBLE > Out ) noexcept;

The z score of each value. With a zero deviation, all are 0.

X
The values.
Out
Receives one z per value (at least X.size()).
eOk or eInvalidArgument.
function

MedianAndMad

Ethereal::Ml::Anomaly#
EStatus MedianAndMad( std::span< const ETL_DOUBLE > X, std::span< ETL_DOUBLE > Scratch, ETL_DOUBLE * pMedian, ETL_DOUBLE * pMad ) noexcept;

The median and the MAD (unscaled), sorting a copy in Scratch.

X
The values.
Scratch
Work buffer, at least X.size().
pMedian
Receives the median.
pMad
Receives the MAD.
eOk or eInvalidArgument.
function

ModifiedZScores

Ethereal::Ml::Anomaly#
EStatus ModifiedZScores( std::span< const ETL_DOUBLE > X, std::span< ETL_DOUBLE > Scratch, std::span< ETL_DOUBLE > Out ) noexcept;

The modified z score of each value.

X
The values.
Scratch
Work buffer, at least X.size().
Out
Receives one score per value (at least X.size()).
eOk or eInvalidArgument.
function

Percentile

Ethereal::Ml::Anomaly#
EStatus Percentile( std::span< const ETL_DOUBLE > X, std::span< ETL_DOUBLE > Scratch, ETL_DOUBLE q, ETL_DOUBLE * pOut ) noexcept;

The quantile q (0..100) by linear interpolation ('numpy.percentile').

X
The values.
Scratch
Work buffer, at least X.size().
q
The quantile, from 0 to 100.
pOut
Receives the quantile.
eOk or eInvalidArgument.
function

IqrFences

Ethereal::Ml::Anomaly#
EStatus IqrFences( std::span< const ETL_DOUBLE > X, std::span< ETL_DOUBLE > Scratch, ETL_DOUBLE k, ETL_DOUBLE * pLow, ETL_DOUBLE * pHigh ) noexcept;

The IQR fences: Q1 - k IQR and Q3 + k IQR (k = 1.5 is Tukey's).

X
The values.
Scratch
Work buffer, at least X.size().
k
Width of the fences, in IQRs.
pLow
Receives the lower fence.
pHigh
Receives the upper fence.
eOk or eInvalidArgument.
struct

SGrubbsResult

Ethereal::Ml::Anomaly#
C++
struct   SGrubbsResult   final
{
    /// @brief  The statistic G.
    ETL_DOUBLE        dG = 0.0;

    /// @brief  Critical value for the requested alpha.
    ETL_DOUBLE        dCritical = 0.0;

    /// @brief  Index of the value farthest from the mean.
    std::size_t        uIndex = 0u;

    /// @brief  G > G_c.
    bool            bOutlier = false;
};

Result of the Grubbs test.

function

Grubbs

Ethereal::Ml::Anomaly#
EStatus Grubbs( std::span< const ETL_DOUBLE > X, ETL_DOUBLE dAlpha, SGrubbsResult * pOut ) noexcept;

The Grubbs test (two sided, one outlier). Needs n >= 3.

X
The values.
dAlpha
Significance level, in (0, 1).
pOut
Receives the result.
eOk or eInvalidArgument.
function

StudentTCdf

Ethereal::Ml::Anomaly#
ETL_DOUBLE StudentTCdf( ETL_DOUBLE t, ETL_DOUBLE dDegrees ) noexcept;

Distribution function of Student's t.

By the regularized incomplete beta function, evaluated as a continued fraction.

t
The point.
dDegrees
Degrees of freedom.
P( T <= t ), or NaN with invalid arguments.
function

StudentTQuantile

Ethereal::Ml::Anomaly#
ETL_DOUBLE StudentTQuantile( ETL_DOUBLE p, ETL_DOUBLE dDegrees ) noexcept;

Quantile of Student's t, by bisection down to double precision.

p
The probability, in (0, 1).
dDegrees
Degrees of freedom.
The quantile, or NaN with invalid arguments.
class

CStatisticalDetector

Ethereal::Ml::Anomaly#

One statistical test per feature, against stored reference statistics (those of the training data).

class CStatisticalDetector final : public IDetector

The score of a sample is the largest |test| over the features, and the contribution of each feature is its |test|.

enum

EKind

#
C++
enum class   EKind : ETL_UINT8
{
    /// @brief  Mean and standard deviation of the reference.
    eZScore = 0,

    /// @brief  Median and MAD of the reference.
    eModifiedZScore,

    /// @brief  Fences of the reference. The distance outside them, in IQRs.
    eIqr
};

The test applied to each feature.

function

Fit

#
EStatus Fit( EKind eKind, std::span< const ETL_DOUBLE > Reference, std::size_t uColumns, ETL_DOUBLE dIqrK = 1.5 );

Computes the statistics from a reference sample.

Allocates (only here).

eKind
The test.
Reference
Rows x columns, row major.
uColumns
Number of columns (features).
dIqrK
Width of the IQR fences.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Init

#
EStatus Init( EKind eKind, std::span< const ETL_DOUBLE > A, std::span< const ETL_DOUBLE > B, ETL_DOUBLE dIqrK = 1.5 );

Takes statistics already computed.

eKind
The test.
A
Mean, median or Q1, one per feature.
B
Deviation, MAD or Q3, one per feature.
dIqrK
Width of the IQR fences.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

FeatureCount

#
std::size_t FeatureCount() const noexcept override

Number of features.

function

Score

#
EStatus Score( std::span< const float > Features, SDetectorOutput * pOut ) noexcept override;

Scores one sample. See IDetector::Score.

function

Test

#
ETL_DOUBLE Test( std::size_t uFeature, ETL_DOUBLE x ) const noexcept;

The signed test of one feature.

The z score, the modified z score, or the distance to the fence in IQRs (negative below, positive above, 0 between the fences).

uFeature
Index of the feature.
x
The value.
The test, or NaN with an invalid feature or a NaN value.