Overview / Machine learning

Ml::Features

Beta

Takes per-entity events and delivers the vector the model expects, in the order of the spec. It exists to prevent skew between training features and production features.

Optional module: turn it on with -DETHEREAL_ML_FEATURES=ONInclude #include <ethereal/cpp/ml/features/features_spec.hpp>C layer

features_spec.hpp

#include <ethereal/cpp/ml/features/features_spec.hpp>

Feature specification of the Ml::Features module.

The TOML file that defines the pipeline, the structures it is read into, and its hash.

The same file drives the training (in Python) and the serving (here). That is the whole design. A mismatch between the numbers of the training notebook and those of the product is the number one cause of ML systems that fail silently. The exact semantics are in 'SEMANTICA.md', next to this file, and the Python reference ('tools/ml_reference/features_ref.py') follows them too.

Every transform carries its parameters as data. A z-score is a mean and a deviation in the file, never a constant in the code. That is what lets the spec hash catch a parameter change.

function

Fnv1a64

Ethereal::Ml::Features#
constexpr ETL_UINT64 Fnv1a64( const std::string_view s ) noexcept

64 bit FNV-1a (offset basis 0xcbf29ce484222325, prime 0x100000001b3).

s
Bytes to hash.
The hash.
function

Mix64

Ethereal::Ml::Features#
constexpr ETL_UINT64 Mix64( ETL_UINT64 z ) noexcept

The SplitMix64 finalizer. Spreads the bits of z.

z
Value to mix.
The mixed value.
function

CategoryCode

Ethereal::Ml::Features#
ETL_DOUBLE CategoryCode( std::string_view sText ) noexcept;

Code of a category: 'Fnv1a64' of the bytes, in the 53 bits that a double holds exactly.

An integer goes through its decimal text (see 'SEMANTICA.md').

sText
Category as text.
iValue
Category as an integer.
The code, as a double.
function

CategoryCode

Ethereal::Ml::Features#
ETL_DOUBLE CategoryCode( ETL_INT64 iValue ) noexcept;
enum

EWindowKind

Ethereal::Ml::Features#
C++
enum class   EWindowKind : ETL_UINT8
{
    /// @brief  The last N values.
    eCount = 0,

    /// @brief  The values with t > now - size.
    eDuration,

    /// @brief  The values since the start of the current fixed window.
    eTumbling,

    /// @brief  A window of 'size' that moves in steps of 'hop'.
    eHopping,

    /// @brief  Everything, since the first event of the entity.
    eAll,

    /// @brief  Weights exp(-(now - t) / tau), with tau = half life / ln 2.
    eEwma
};

Kind of window of a feature.

enum

EAggregation

Ethereal::Ml::Features#
C++
enum class   EAggregation : ETL_UINT8
{
    eCount = 0, eSum, eMean, eVariance, eStd, eMin, eMax, eRange, eMedian, ePercentile,
    eRate, eSlope, eAutocorr, eEntropy, eDistinct, eLast
};

Aggregation of a feature over its window.

The values are eCount, eSum, eMean, eVariance, eStd, eMin, eMax, eRange, eMedian, ePercentile, eRate, eSlope, eAutocorr, eEntropy, eDistinct and eLast, with the names of the spec file ("count", "sum", ...). See 'SEMANTICA.md'.

enum

ETransformKind

Ethereal::Ml::Features#
C++
enum class   ETransformKind : ETL_UINT8
{
    eZScore = 0, eMinMax, eRobust, eLog, eLog1p, eClip, eBinning, eOneHot, eOrdinal, eTarget, eHash
};

Kind of transform applied to the aggregated value.

The values are eZScore, eMinMax, eRobust, eLog, eLog1p, eClip, eBinning, eOneHot, eOrdinal, eTarget and eHash, with the names of the spec file ("zscore", "minmax", ...). The last four are the categorical ones.

enum

EEviction

Ethereal::Ml::Features#
C++
enum class   EEviction : ETL_UINT8
{
    /// @brief  The entity that has gone longest without an event leaves.
    eLru = 0,

    /// @brief  The new entity is rejected (EStatus::eTableFull).
    eReject
};

What happens when the entity table is full.

const

MAX_WINDOW

Ethereal::Ml::Features#
inline constexpr ETL_UINT32 MAX_WINDOW = 1u << 20;

Largest window size (values kept per entity and feature).

struct

SWindowSpec

Ethereal::Ml::Features#
C++
struct   SWindowSpec   final
{
    /// @brief  Kind of window.
    EWindowKind        eKind = EWindowKind::eCount;

    /// @brief  eCount: N.
    ETL_UINT32        uCount = 0u;

    /// @brief  Time windows: the most values kept.
    ETL_UINT32        uCapacity = 1024u;

    /// @brief  Size, for eDuration, eTumbling and eHopping.
    ETL_INT64        iSizeNs = 0;

    /// @brief  Step, for eHopping.
    ETL_INT64        iHopNs = 0;

    /// @brief  Half life, for eEwma.
    ETL_INT64        iHalfLifeNs = 0;
};

Window of a feature.

struct

SHistogramSpec

Ethereal::Ml::Features#
C++
struct   SHistogramSpec   final
{
    /// @brief  Lower end of the range.
    ETL_DOUBLE        dMin = 0.0;

    /// @brief  Upper end of the range.
    ETL_DOUBLE        dMax = 1.0;

    /// @brief  Number of bins. Zero means no histogram.
    ETL_UINT32        uBins = 0u;
};

Fixed histogram of a median or percentile feature.

struct

STransformSpec

Ethereal::Ml::Features#
C++
struct   STransformSpec   final
{
    /// @brief  Kind of transform.
    ETransformKind    eKind = ETransformKind::eZScore;

    /// @brief  The two parameters: mean/std, min/max, median/iqr, and those of the clip.
    ETL_DOUBLE        dA = 0.0;
    ETL_DOUBLE        dB = 0.0;

    /// @brief  Binning: the bin edges.
    std::vector< ETL_DOUBLE >    Edges;

    /// @brief  Onehot, ordinal: the categories as they were written, and their codes.
    std::vector< std::string >    Categories;
    std::vector< ETL_DOUBLE >    CategoryCodes;

    /// @brief  Target: category to value, sorted by the category text, and the same by code.
    std::vector< std::pair< std::string, ETL_DOUBLE > >    Mapping;
    std::vector< std::pair< ETL_DOUBLE, ETL_DOUBLE > >        MappingCodes;

    /// @brief  Ordinal: 'unknown'. Target: 'default'.
    ETL_DOUBLE        dDefault = 0.0;

    /// @brief  Hash: number of buckets.
    ETL_UINT32        uBuckets = 0u;
};

One transform of a feature.

struct

SFeatureSpec

Ethereal::Ml::Features#
C++
struct   SFeatureSpec   final
{
    /// @brief  Name of the feature (unique in the spec).
    std::string        sName;

    /// @brief  An interaction: the product of two earlier features (no window).
    bool            bProduct = false;

    /// @brief  Names of the two features of the product.
    std::string        sProductA, sProductB;

    /// @brief  Indices of the two features of the product.
    ETL_UINT32        uProductA = 0u, uProductB = 0u;

    /// @brief  Event field the feature reads.
    std::string        sSource;

    /// @brief  When true, only events of type uEventType count.
    bool            bHasEventType = false;

    /// @brief  Event type filter.
    ETL_UINT32        uEventType = 0u;

    /// @brief  The value is a category code, not a number.
    bool            bCategorical = false;

    /// @brief  Window of the feature.
    SWindowSpec        Window;

    /// @brief  Aggregation over the window.
    EAggregation    eAggregation = EAggregation::eLast;

    /// @brief  Percentile, 0 to 100, for ePercentile.
    ETL_DOUBLE        dPercentile = 50.0;

    /// @brief  Histogram of eMedian and ePercentile.
    SHistogramSpec    Histogram;

    /// @brief  HyperLogLog precision, for 'distinct' in the 'all' window.
    ETL_UINT32        uHllPrecision = 12u;

    /// @brief  Transforms, in order.
    std::vector< STransformSpec >    Transforms;

    /// @brief  Training deciles (9 values), for the drift watch. Empty: no watch.
    std::vector< ETL_DOUBLE >    TrainDeciles;

    /// @brief  Line of the file where the feature starts (for the messages).
    ETL_UINT32        uLine = 0u;
};

One feature of the spec.

struct

SDriftSpec

Ethereal::Ml::Features#
C++
struct   SDriftSpec   final
{
    /// @brief  The last N extractions of each feature.
    ETL_UINT32        uWindow = 1000u;

    /// @brief  The PSI is computed once every this many extractions.
    ETL_UINT32        uCheckEvery = 1000u;

    /// @brief  PSI from which there is drift.
    ETL_DOUBLE        dPsiThreshold = 0.25;
};

Drift watch parameters.

struct

SPipelineSpec

Ethereal::Ml::Features#
C++
struct   SPipelineSpec   final
{
    /// @brief  Version of the spec, set by its author.
    ETL_INT64        iVersion = 1;

    /// @brief  Name of the entity key.
    std::string        sEntityKey;

    /// @brief  Capacity of the entity table.
    ETL_UINT32        uMaxEntities = 1024u;

    /// @brief  Largest entity key, in bytes.
    ETL_UINT32        uMaxKeyBytes = 64u;

    /// @brief  What happens with the table full.
    EEviction        eEviction = EEviction::eLru;

    /// @brief  How late an event may arrive and still be accepted.
    ETL_INT64        iAllowedLatenessNs = 0;

    /// @brief  Drift watch.
    SDriftSpec        Drift;

    /// @brief  The features, in output order.
    std::vector< SFeatureSpec >        Features;
};

The whole pipeline spec.

struct

SSpecError

Ethereal::Ml::Features#
C++
struct   SSpecError   final
{
    /// @brief  File name given to the parser.
    std::string        sFile;

    /// @brief  Line, from 1. Zero when there is no line.
    std::size_t        uLine = 0u;

    /// @brief  Column, from 1.
    std::size_t        uColumn = 0u;

    /// @brief  Path of the field, for example "feature[2].window.size".
    std::string        sField;

    /// @brief  What is wrong.
    std::string        sMessage;


    /// @brief  "file:line:column: field: message".
    ///
    ETL_API_NOIGN    ETL_API        std::string ToString() const;
};

Where and why the spec does not read: the file, the line, the field.

function

ParseSpec

Ethereal::Ml::Features#
EStatus ParseSpec( std::string_view sText, std::string_view sFileName, SPipelineSpec * pOut, SSpecError * pError );

Reads a spec in TOML.

sText
The TOML text.
sFileName
File name, used only in the messages.
pOut
Receives the spec.
pError
Receives the error. May be null.
eOk, or EStatus::eSpecInvalid with pError filled (file, line, field). EStatus::eNotLicensed when the library is not licensed.
function

LoadSpecFile

Ethereal::Ml::Features#
EStatus LoadSpecFile( std::string_view sPath, SPipelineSpec * pOut, SSpecError * pError );

Reads the file (UTF-8) and parses it.

sPath
Path of the file.
pOut
Receives the spec.
pError
Receives the error. May be null.
eOk, eIoError or eSpecInvalid. EStatus::eNotLicensed when the library is not licensed.
function

CanonicalSpec

Ethereal::Ml::Features#
std::string CanonicalSpec( const SPipelineSpec & Spec );

Canonical form of the spec: the bytes the hash reads.

This is not the text. It is the parsed spec, with the defaults filled in, each field in a fixed order with its label, the numbers by their 64 IEEE bits and the texts with their length. Spaces, comments, the order of the keys and "5m" against "300s" do not change it. Any parameter does.

Spec
The spec.
The canonical bytes.
function

SpecHash

Ethereal::Ml::Features#
ETL_UINT64 SpecHash( const SPipelineSpec & Spec );

'Fnv1a64' of the canonical form.

Spec
The spec.
The hash.
function

FeatureWidth

Ethereal::Ml::Features#
ETL_UINT32 FeatureWidth( const SFeatureSpec & Feature ) noexcept;

Number of outputs of a feature.

Feature
The feature.
k for a final 'onehot', 1 otherwise.

pipeline.hpp

#include <ethereal/cpp/ml/features/pipeline.hpp>

Feature pipeline of the Ml::Features module.

Events come in, per entity, and the vector the model expects comes out.

The module exists to stop the training features, computed in a Python notebook, and the serving features, computed here, from giving subtly different numbers. The model behaves in the lab and fails in the product, and nothing in the logs says why. Three things prevent it, all of them here: 1. The spec hash ('SpecHash', 'VerifyModelSpecHash'). A model trained with another spec is rejected. 2. The Python reference, which reads the same spec and gives the same numbers (the suite checks both on a corpus of fixtures). 3. The drift watch. The distribution of the output against the training one, with a report before the model degrades silently.

No allocations after 'Init'. The entity table, the windows and the sketches are all reserved in 'Init', at the size the spec asks for ('MemoryUsage' gives the figure before running). The table has a fixed capacity and an eviction policy, so a server that runs for months does not grow.

No virtual dispatch per event, and the aggregations are incremental. A window mean slides in O(1) as values enter and leave, and is never recomputed over the window.

Not thread safe. One pipeline per thread, or a lock held by the integrator.

const

NO_FIELD_ID

Ethereal::Ml::Features#
inline constexpr ETL_UINT32 NO_FIELD_ID = 0xFFFFFFFFu;

A field with no id (it is looked up by name).

enum

EFieldType

Ethereal::Ml::Features#
C++
enum class   EFieldType : ETL_UINT8
{
    /// @brief  A double.
    eDouble = 0,

    /// @brief  A 64 bit integer.
    eInt,

    /// @brief  A text.
    eString,

    /// @brief  A boolean.
    eBool
};

Type of the value of an event field.

struct

SFieldValue

Ethereal::Ml::Features#
C++
struct   SFieldValue   final
{
    /// @brief  Name of the field.
    std::string_view    sName;

    /// @brief  Id of the field, or NO_FIELD_ID.
    ETL_UINT32            uFieldId = NO_FIELD_ID;

    /// @brief  Which of the values below is used.
    EFieldType            eType = EFieldType::eDouble;

    /// @brief  Value, for eBool.
    bool                bValue = false;

    /// @brief  Value, for eDouble.
    ETL_DOUBLE            dValue = 0.0;

    /// @brief  Value, for eInt.
    ETL_INT64            iValue = 0;

    /// @brief  Value, for eString. Not copied.
    std::string_view    sValue;


    ///
    /// Double
    ///
    /// @brief  Builds a double field.
    ///
    /// @param s        Name of the field.
    /// @param d        Value.
    ///
    /// @return  The field.
    ///
    static SFieldValue Double( const std::string_view s, const ETL_DOUBLE d ) ETL_NOEXCEPT
    {
        SFieldValue F;
        F.sName = s;
        F.eType = EFieldType::eDouble;
        F.dValue = d;
        return F;
    }


    ///
    /// Int
    ///
    /// @brief  Builds an integer field.
    ///
    /// @param s        Name of the field.
    /// @param i        Value.
    ///
    /// @return  The field.
    ///
    static SFieldValue Int( const std::string_view s, const ETL_INT64 i ) ETL_NOEXCEPT
    {
        SFieldValue F;
        F.sName = s;
        F.eType = EFieldType::eInt;
        F.iValue = i;
        return F;
    }


    ///
    /// String
    ///
    /// @brief  Builds a text field. The text is not copied.
    ///
    /// @param s        Name of the field.
    /// @param v        Value.
    ///
    /// @return  The field.
    ///
    static SFieldValue String( const std::string_view s, const std::string_view v ) ETL_NOEXCEPT
    {
        SFieldValue F;
        F.sName = s;
        F.eType = EFieldType::eString;
        F.sValue = v;
        return F;
    }


    ///
    /// Bool
    ///
    /// @brief  Builds a boolean field.
    ///
    /// @param s        Name of the field.
    /// @param b        Value.
    ///
    /// @return  The field.
    ///
    static SFieldValue Bool( const std::string_view s, const bool b ) ETL_NOEXCEPT
    {
        SFieldValue F;
        F.sName = s;
        F.eType = EFieldType::eBool;
        F.bValue = b;
        return F;
    }
};

A field of an event, with name and type.

uFieldId, when given (from 'CFeaturePipeline::FieldId', once, at setup), saves the lookup by name on every event.

struct

SEvent

Ethereal::Ml::Features#
C++
struct   SEvent   final
{
    /// @brief  sizeof( SEvent ), for versioning.
    ETL_UINT32                            iStructSize = sizeof( SEvent );

    /// @brief  Time of the event, in nanoseconds.
    ETL_INT64                            iTimestampNs = 0;

    /// @brief  Type of the event, for the features with an event type filter.
    ETL_UINT32                            iEventType = 0u;

    /// @brief  Fields of the event.
    std::span< const SFieldValue >        Fields;
};

An event: the time (ns), the type, and the fields.

struct

SNamedValue

Ethereal::Ml::Features#
C++
struct   SNamedValue   final
{
    /// @brief  Name of the output.
    std::string_view    sName;

    /// @brief  Value of the output.
    float                fValue = 0.0f;
};

An output with its name.

struct

SDriftReport

Ethereal::Ml::Features#
C++
struct   SDriftReport   final
{
    /// @brief  Index of the feature in the spec.
    std::size_t            uFeature = 0u;

    /// @brief  Name of the feature.
    std::string_view    sName;

    /// @brief  Population stability index.
    ETL_DOUBLE            dPsi = 0.0;

    /// @brief  Mean of the last extractions.
    ETL_DOUBLE            dRecentMean = 0.0;

    /// @brief  How many extractions the PSI saw.
    ETL_UINT64            uSamples = 0u;
};

A drift report: the distribution of a feature moved away from the training one.

struct

IDriftSink

Ethereal::Ml::Features#
C++
struct   IDriftSink
{
    ///
    /// OnDrift
    ///
    /// @brief  Called once when a feature starts drifting.
    ///
    /// @param Report    The report.
    ///
    virtual void OnDrift( const SDriftReport & Report ) ETL_NOEXCEPT = 0;


    /// @brief  Virtual destructor.
    ///
    virtual ~IDriftSink() = default;
};

Receives the drift reports (the Telemetry glue connects it, when present).

struct

SPipelineParams

Ethereal::Ml::Features#
C++
struct   SPipelineParams   final
{
    /// @brief  Clock of the idle eviction ('EvictIdle'). Null: the time of the
    ///             events (the highest watermark seen).
    Time::IClock *        pClock = nullptr;

    /// @brief  Drift reports. Null: drift is not watched.
    IDriftSink *        pDriftSink = nullptr;
};

Runtime parameters of the pipeline.

struct

SPipelineCounters

Ethereal::Ml::Features#
C++
struct   SPipelineCounters   final
{
    /// @brief  Events accepted.
    ETL_UINT64        uEvents = 0u;

    /// @brief  Events later than the allowed lateness.
    ETL_UINT64        uLateDropped = 0u;

    /// @brief  Events out of order, within the allowed lateness.
    ETL_UINT64        uReordered = 0u;

    /// @brief  NaN or infinite values, ignored.
    ETL_UINT64        uNonFinite = 0u;

    /// @brief  A text in a numeric feature.
    ETL_UINT64        uTypeMismatch = 0u;

    /// @brief  Values that left the window before their time (window full).
    ETL_UINT64        uWindowOverflow = 0u;

    /// @brief  Entities evicted by the policy (LRU) or by the idle eviction.
    ETL_UINT64        uEntitiesEvicted = 0u;

    /// @brief  New entities rejected (policy 'reject').
    ETL_UINT64        uTableFullRejected = 0u;

    /// @brief  Drift reports sent.
    ETL_UINT64        uDriftReports = 0u;
};

What was counted (and not hidden).

class

CFeaturePipeline

Ethereal::Ml::Features#

The feature pipeline.

class CFeaturePipeline final
constructor

CFeaturePipeline

#
CFeaturePipeline() noexcept;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const SPipelineSpec & Spec, const SPipelineParams & Params = SPipelineParams() );

Builds the pipeline from the spec.

Everything is reserved here.

Spec
The spec.
Params
Runtime parameters.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

MemoryUsage

#
static EStatus MemoryUsage( const SPipelineSpec & Spec, std::size_t * pOut );

Memory a spec will ask for, before building it.

Spec
The spec.
pOut
Receives the bytes.
eOk or eInvalidArgument.
function

MemoryUsage

#
EStatus MemoryUsage( std::size_t * pOut ) const noexcept;

Memory of this pipeline (the same figure).

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

Update

#
EStatus Update( std::string_view sEntityKey, const SEvent & Event ) noexcept;

Feeds one event of an entity. No allocations.

sEntityKey
Entity key.
Event
The event.
eOk, EStatus::eLateEvent (counted and dropped), EStatus::eTableFull (new entity with the table full and the 'reject' policy), eInvalidArgument or eNotLoaded.
function

Extract

#
EStatus Extract( std::string_view sEntityKey, std::span< float > Out ) noexcept;

Vector of the entity, in spec order, at the time of its last event.

sEntityKey
Entity key.
Out
Receives FeatureCount() values.
eOk, eBufferTooSmall, eUnknownEntity or eNotLoaded.
function

ExtractNamed

#
EStatus ExtractNamed( std::string_view sEntityKey, std::span< SNamedValue > Out ) noexcept;

Same as Extract, with the names.

sEntityKey
Entity key.
Out
Receives FeatureCount() values.
eOk, eBufferTooSmall, eUnknownEntity or eNotLoaded.
function

Reset

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

Forgets an entity.

sEntityKey
Entity key.
eOk, eUnknownEntity or eNotLoaded.
function

EvictIdle

#
EStatus EvictIdle( Time::SDuration IdleFor ) noexcept;

Drops the entities with no events for more than IdleFor.

IdleFor
Idle time.
eOk or eNotLoaded.
function

VerifyModelSpecHash

#
EStatus VerifyModelSpecHash( ETL_UINT64 uModelSpecHash ) const noexcept;

Checks the spec hash a model was trained with.

uModelSpecHash
Hash the model keeps (for example 'CTreeModel::SpecHash()').
eOk, EStatus::eSpecMismatch when the model was trained with another spec, or eNotLoaded.
function

SpecHash

#
ETL_UINT64 SpecHash() const noexcept;

Hash of the spec.

function

FeatureCount

#
std::size_t FeatureCount() const noexcept;

Number of outputs (a final 'onehot' gives one per category).

function

FeatureName

#
std::string_view FeatureName( std::size_t uIndex ) const noexcept;

Name of an output. Empty when out of range.

function

FieldId

#
ETL_UINT32 FieldId( std::string_view sFieldName ) const noexcept;

Id of a field, for 'SFieldValue::uFieldId'.

sFieldName
Name of the field.
The id, or NO_FIELD_ID when no feature reads the field.
function

EntityCount

#
std::size_t EntityCount() const noexcept;

Number of entities in the table.

function

Counters

#
SPipelineCounters Counters() const noexcept;

Copy of the counters.

sketches.hpp

#include <ethereal/cpp/ml/features/sketches.hpp>

Sketches of the Ml::Features module.

Fixed memory, mergeable and serializable:

  • CHyperLogLog, how many distinct values (relative error about 1.04 / sqrt(2^p)).
  • CCountMinSketch, the frequency of one key among many. Never below the truth, above it by at most eps * N with probability 1 - delta.
  • CBloomFilter, "have I seen this?". No false negatives, false positives at the requested rate.
  • CFixedHistogram, quantiles with the error of one bin, and a value can be removed. That is what a sliding window needs, and the t-digest does not do it.

Mergeable is what matters on a server. Each shard computes its own and they are merged at the end, and the result is the same as a single pass (bit for bit in the HyperLogLog, the count-min, the Bloom filter and the histogram: merging is max, sum or OR, with no loss at all).

Allocations only in 'Init', none after. The hashes are those of 'features_spec.hpp' (FNV-1a and the SplitMix64 finalizer), the same as the Python reference.

function

HashValue

Ethereal::Ml::Features#
ETL_UINT64 HashValue( ETL_DOUBLE dValue ) noexcept;

Hash of a numeric value: the bits of the double (-0 counts as +0), mixed.

The same one the pipeline uses for 'distinct' and 'entropy'.

dValue
The value.
The hash.
function

HashText

Ethereal::Ml::Features#
inline ETL_UINT64 HashText( const std::string_view s ) noexcept

Hash of a text: 'Mix64( Fnv1a64( s ) )'.

s
The text.
The hash.
class

CHyperLogLog

Ethereal::Ml::Features#

HyperLogLog distinct counter.

class CHyperLogLog final
function

Init

#
EStatus Init( ETL_UINT32 uPrecision );

Reserves 2^p registers of one byte.

uPrecision
p, from 4 to 16.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

AddHash

#
void AddHash( ETL_UINT64 uHash ) noexcept;

Adds a hash.

uHash
The hash.
function

AddText

#
void AddText( const std::string_view s ) noexcept

Adds a text, by 'HashText'.

s
The text.
function

AddValue

#
void AddValue( const ETL_DOUBLE d ) noexcept

Adds a value, by 'HashValue'.

d
The value.
function

Estimate

#
ETL_DOUBLE Estimate() const noexcept;

The estimate (with the Flajolet correction for small counts).

function

Merge

#
EStatus Merge( const CHyperLogLog & Other ) noexcept;

Merges another one of the same precision: the max of each register.

Other
The other sketch.
eOk, or eInvalidArgument when the precisions differ.
function

Clear

#
void Clear() noexcept;

Zeroes the registers.

function

Precision

#
ETL_UINT32 Precision() const noexcept

Precision p. Zero before Init.

function

StandardError

#
static ETL_DOUBLE StandardError( ETL_UINT32 uPrecision ) noexcept;

Typical relative error (one standard deviation): 1.04 / sqrt(2^p).

uPrecision
p.
The error.
function

SerializedSize

#
std::size_t SerializedSize() const noexcept;

Bytes written by Serialize.

function

Serialize

#
EStatus Serialize( std::span< ETL_UINT8 > Out, std::size_t * pWritten ) const noexcept;

Writes the sketch.

Out
Output buffer.
pWritten
Receives the bytes written. May be null.
eOk, eBufferTooSmall or eNotLoaded.
function

Deserialize

#
EStatus Deserialize( std::span< const ETL_UINT8 > In );

Reads a sketch written by Serialize.

In
Input bytes.
eOk, eTruncated, eBadMagic, eVersionTooNew or eCorrupt. EStatus::eNotLicensed when the library is not licensed.
function

AddTo

#
static void AddTo( ETL_UINT8 * pRegisters, ETL_UINT32 uPrecision, ETL_UINT64 uHash ) noexcept;

Adds a hash to registers owned by the caller.

The pipeline keeps the registers in the memory of each entity.

pRegisters
2^p registers.
uPrecision
p.
uHash
The hash.
function

EstimateOf

#
static ETL_DOUBLE EstimateOf( const ETL_UINT8 * pRegisters, ETL_UINT32 uPrecision ) noexcept;

Estimate over registers owned by the caller.

pRegisters
2^p registers.
uPrecision
p.
The estimate.
class

CCountMinSketch

Ethereal::Ml::Features#

Count-min sketch.

class CCountMinSketch final
function

Init

#
EStatus Init( ETL_UINT32 uWidth, ETL_UINT32 uDepth );

Reserves the counters.

uWidth
Width, rounded up to a power of 2.
uDepth
Depth (rows).
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

InitForError

#
EStatus InitForError( ETL_DOUBLE dEpsilon, ETL_DOUBLE dDelta );

Init by the errors: width e/eps, depth ln(1/delta).

dEpsilon
Error, as a fraction of the total.
dDelta
Probability of exceeding the error.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

AddHash

#
void AddHash( ETL_UINT64 uHash, ETL_UINT64 uCount = 1u ) noexcept;

Adds a count to a hash.

uHash
The hash.
uCount
The count.
function

AddText

#
void AddText( const std::string_view s, const ETL_UINT64 uCount = 1u ) noexcept

Adds a count to a text, by 'HashText'.

s
The text.
uCount
The count.
function

EstimateHash

#
ETL_UINT64 EstimateHash( ETL_UINT64 uHash ) const noexcept;

The estimate of a hash. Never below the true count.

uHash
The hash.
function

EstimateText

#
ETL_UINT64 EstimateText( const std::string_view s ) const noexcept

The estimate of a text, by 'HashText'.

s
The text.
function

Total

#
ETL_UINT64 Total() const noexcept

Sum of everything added (the N of the error eps * N).

function

Merge

#
EStatus Merge( const CCountMinSketch & Other ) noexcept;

Merges another one of the same shape: the sum of each counter.

Other
The other sketch.
eOk, or eInvalidArgument when the shapes differ.
function

Clear

#
void Clear() noexcept;

Zeroes the counters and the total.

function

Width

#
ETL_UINT32 Width() const noexcept

Width (a power of 2).

function

Depth

#
ETL_UINT32 Depth() const noexcept

Depth.

function

SerializedSize

#
std::size_t SerializedSize() const noexcept;

Bytes written by Serialize.

function

Serialize

#
EStatus Serialize( std::span< ETL_UINT8 > Out, std::size_t * pWritten ) const noexcept;

Writes the sketch.

Out
Output buffer.
pWritten
Receives the bytes written. May be null.
eOk, eBufferTooSmall or eNotLoaded.
function

Deserialize

#
EStatus Deserialize( std::span< const ETL_UINT8 > In );

Reads a sketch written by Serialize.

In
Input bytes.
eOk, eTruncated, eBadMagic, eVersionTooNew or eCorrupt. EStatus::eNotLicensed when the library is not licensed.
class

CBloomFilter

Ethereal::Ml::Features#

Bloom filter.

class CBloomFilter final
function

Init

#
EStatus Init( ETL_UINT64 uBits, ETL_UINT32 uHashes );

Reserves the bits.

uBits
Bits, rounded up to a power of 2, at least 64.
uHashes
Number of hashes per key.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

InitForCapacity

#
EStatus InitForCapacity( ETL_UINT64 uExpected, ETL_DOUBLE dFalsePositiveRate );

Init by what is expected: n elements, with the false positive rate p.

uExpected
n.
dFalsePositiveRate
p.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

AddHash

#
void AddHash( ETL_UINT64 uHash ) noexcept;

Adds a hash.

uHash
The hash.
function

AddText

#
void AddText( const std::string_view s ) noexcept

Adds a text, by 'HashText'.

s
The text.
function

MayContainHash

#
bool MayContainHash( ETL_UINT64 uHash ) const noexcept;

false: it surely was not added. true: it probably was.

uHash
The hash.
function

MayContainText

#
bool MayContainText( const std::string_view s ) const noexcept

Same as MayContainHash, for a text.

s
The text.
function

Merge

#
EStatus Merge( const CBloomFilter & Other ) noexcept;

Merges another one of the same shape: the OR of the bits.

Other
The other filter.
eOk, or eInvalidArgument when the shapes differ.
function

Clear

#
void Clear() noexcept;

Zeroes the bits.

function

Bits

#
ETL_UINT64 Bits() const noexcept

Number of bits (a power of 2).

function

Hashes

#
ETL_UINT32 Hashes() const noexcept

Number of hashes per key.

function

SerializedSize

#
std::size_t SerializedSize() const noexcept;

Bytes written by Serialize.

function

Serialize

#
EStatus Serialize( std::span< ETL_UINT8 > Out, std::size_t * pWritten ) const noexcept;

Writes the filter.

Out
Output buffer.
pWritten
Receives the bytes written. May be null.
eOk, eBufferTooSmall or eNotLoaded.
function

Deserialize

#
EStatus Deserialize( std::span< const ETL_UINT8 > In );

Reads a filter written by Serialize.

In
Input bytes.
eOk, eTruncated, eBadMagic, eVersionTooNew or eCorrupt. EStatus::eNotLicensed when the library is not licensed.
class

CFixedHistogram

Ethereal::Ml::Features#

Histogram with fixed bins.

class CFixedHistogram final
function

Init

#
EStatus Init( ETL_DOUBLE dMin, ETL_DOUBLE dMax, ETL_UINT32 uBins );

Reserves uBins equal bins over [dMin, dMax).

Values outside the range go to the end bins.

dMin
Lower end.
dMax
Upper end.
uBins
Number of bins.
eOk, eInvalidArgument or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Add

#
void Add( ETL_DOUBLE dValue ) noexcept;

Adds a value. NaN is ignored.

dValue
The value.
function

Remove

#
void Remove( ETL_DOUBLE dValue ) noexcept;

Removes a value added before (its bin loses one).

dValue
The value.
function

Percentile

#
ETL_DOUBLE Percentile( ETL_DOUBLE dPercent ) const noexcept;

The quantile dPercent, with the rule of 'SEMANTICA.md'.

dPercent
0 to 100.
The quantile. NaN when empty.
function

Count

#
ETL_UINT64 Count() const noexcept

Number of values.

function

Merge

#
EStatus Merge( const CFixedHistogram & Other ) noexcept;

Merges another one of the same shape: the sum of each bin.

Other
The other histogram.
eOk, or eInvalidArgument when the shapes differ.
function

Clear

#
void Clear() noexcept;

Zeroes the bins.

function

SerializedSize

#
std::size_t SerializedSize() const noexcept;

Bytes written by Serialize.

function

Serialize

#
EStatus Serialize( std::span< ETL_UINT8 > Out, std::size_t * pWritten ) const noexcept;

Writes the histogram.

Out
Output buffer.
pWritten
Receives the bytes written. May be null.
eOk, eBufferTooSmall or eNotLoaded.
function

Deserialize

#
EStatus Deserialize( std::span< const ETL_UINT8 > In );

Reads a histogram written by Serialize.

In
Input bytes.
eOk, eTruncated, eBadMagic, eVersionTooNew or eCorrupt. EStatus::eNotLicensed when the library is not licensed.
function

BucketOf

#
static ETL_UINT32 BucketOf( ETL_DOUBLE dValue, ETL_DOUBLE dMin, ETL_DOUBLE dMax, ETL_UINT32 uBins ) noexcept;

Bin of a value, over counters owned by the caller.

dValue
The value.
dMin
Lower end.
dMax
Upper end.
uBins
Number of bins.
The bin, from 0 to uBins - 1.
function

PercentileOf

#
static ETL_DOUBLE PercentileOf( const ETL_UINT32 * pCounts, ETL_UINT32 uBins, ETL_UINT64 uTotal, ETL_DOUBLE dMin, ETL_DOUBLE dMax, ETL_DOUBLE dPercent ) noexcept;

Quantile over counters owned by the caller.

pCounts
The bins.
uBins
Number of bins.
uTotal
Sum of the bins.
dMin
Lower end.
dMax
Upper end.
dPercent
0 to 100.
The quantile. NaN when empty.