Source code for rheon._spec

"""Spec builders: plain dicts, validated eagerly by the Rust core.

The public module is :mod:`rheon.spec`; its docstring says what a
spec is, what every model shares and what a builder raises. Here: the
checker each builder is wrapped in (:func:`_checked`, a ``TypeError`` per
keyword whose value has the wrong shape, a ``ValueError`` for a count below
0 or a non-finite value where infinity means nothing), the shared
parameters (:func:`_common`, which has the Rust side validate the finished
dict), and the JSON the two sides exchange (:func:`_json`, where
``inf`` becomes the string the Rust side reads).
"""

from __future__ import annotations

import functools
import json
import math
import numbers
import types
import typing
from collections.abc import Callable, Mapping, Sequence
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict, Unpack

from rheon._duration import Duration, _Expr, _is_expr, duration_text, infinity_as_number
from rheon._kwargs import CommonKwargs
from rheon._renamed import removed_keywords, renamed_keywords
from rheon._rheon import validate_spec
from rheon._spec_words import (
    _INF_OK,
    _INF_REFUSED_BY_RUST,
    _WORD_REASONS,
    _bad_word,
    _listed,
    _one_of,
    quoted,
    refusal,
    word_reason,
    words_refusal,
)

if TYPE_CHECKING:
    import polars as pl


def _who(name: Any) -> str:
    """How a refusal names a spec: ``spec "<name>"``, or, for a hand-built
    dict with no name, ``a spec with no name`` -- which read ``spec null``
    (review 2026-10-06, YA6)."""
    return "a spec with no name" if name is None else f"spec {quoted(name)}"


def _json(spec: dict[str, Any] | list[dict[str, Any]]) -> str:
    """JSON has no infinity literal, but ``half_life=inf`` is meaningful (it pins
    a coefficient), so infinities are encoded as strings the Rust side
    understands. A NaN is never meaningful in a spec and is refused here, by
    parameter name, rather than by the JSON offset serde would report. NumPy
    scalars are plain numbers here (``json`` alone refuses them).

    A raw dict may hold what a builder takes: a window expression in
    ``targets`` is a formula target, and anywhere else an expression or a
    ``timedelta`` is a duration, written as its text as the builders write it
    (review 2026-10-05, YA11: an expression under any key was read as a
    formula, so ``half_life=pl.duration(minutes=10)`` was refused as a formula
    literal that named no key)."""

    def enc(v: Any, key: str, who: Any, inner: bool = False) -> Any:
        # `key` is the parameter `v` belongs to, and `inner` whether `v` is
        # one value of it (an entry of a list, a value of a dict), not all.
        if isinstance(v, bool):
            return v
        if isinstance(v, numbers.Integral):
            return int(v)
        if isinstance(v, numbers.Real):
            v = float(v)
            if math.isnan(v):
                if inner:
                    raise ValueError(
                        f"{_who(who)}: {key} must hold numbers, but one of its values is NaN. "
                        "Replace the NaN with a number."
                    )
                raise ValueError(
                    f"{_who(who)}: {key} must be a number, but it is NaN. Set {key} to a number."
                )
            if math.isinf(v):
                return "inf" if v > 0 else "-inf"
            return v
        if isinstance(v, dict):
            # The spec's and its model table's keys are parameters; any
            # other dict is one parameter's value.
            if key in ("spec", "model"):
                return {k: enc(x, k, who) for k, x in v.items()}
            return {k: enc(x, key, who, inner=True) for k, x in v.items()}
        if isinstance(v, (list, tuple)):
            return [enc(x, key, who, inner=True) for x in v]
        if key == "targets" and _is_expr(v):
            # A window expression in `targets`, as the builders take one
            # (review R2, P5: every surface that writes a spec dict).
            return enc(formula_target(_who(who), v), key, who)
        if isinstance(v, timedelta) or _is_expr(v):
            if key in _CLOCK_KEYS:
                return duration_text(v, _who(who), key)
            raise TypeError(
                f"{_who(who)}: {key} takes no {type(v).__name__}, since it is not measured "
                "on the clock and is not a target. Pass the value the parameter takes, such "
                "as a number, a word or a column's name."
            )
        if v is not None and not isinstance(v, str):
            # Anything else is no JSON value, and `json` refused it naming
            # neither the spec nor the key (review fable2, Y4). A set's order
            # is not fixed, and a list's is the outputs' order.
            if isinstance(v, (set, frozenset)):
                raise TypeError(
                    f"{_who(who)}: {key} takes no set, since its order is not fixed and the "
                    "order of a spec's columns is the order of its outputs. Pass a list."
                )
            raise TypeError(
                f"{_who(who)}: {key} takes no {type(v).__name__}. Pass the value the parameter "
                "takes, such as a number, a word, a column's name or a list of them."
            )
        return v

    def name(s: Any) -> Any:
        return s.get("name") if isinstance(s, dict) else None

    # A list of specs is `ModelBank`'s path: each spec names its own NaN,
    # where the message read `spec null` (review 2026-09-12, D8).
    if isinstance(spec, list):
        return json.dumps([enc(s, "spec", name(s)) for s in spec])
    return json.dumps(enc(spec, "spec", name(spec)))


def _from_json(text: str) -> Any:
    """The inverse of :func:`_json`: the ``"inf"`` strings the Rust side writes
    for infinite numeric parameters become floats again, so a loaded bank's
    ``specs`` compare equal to the dicts that built it (a ``rp.target`` table
    that names its own column comes back as the column, which is what it is).
    Only the numeric parameters are touched -- a feature column may be called
    ``"inf"``."""

    def dec(v: Any, numeric: bool) -> Any:
        if isinstance(v, dict):
            # Under a numeric parameter a dict's values are numbers too:
            # `window_budget = {"thin": inf}` (review 2026-09-12, P4).
            return {k: dec(x, numeric or k in _NUMERIC_KEYS) for k, x in v.items()}
        if isinstance(v, list):
            return [dec(x, numeric) for x in v]
        if numeric and v in ("inf", "-inf"):
            return math.inf if v == "inf" else -math.inf
        return v

    return dec(json.loads(text), False)


# The builders' annotations are the contract, and these two functions read
# them, so a wrong shape is reported by parameter name ("half_life must be a
# number or a list of numbers, got str '10'") before anything is serialized.
# The Rust side checks the same things, but serde cannot name the field once it
# is inside the model's tagged union, and "expected f64" with no name is not
# much of a message.


def _matches(v: Any, hint: Any) -> bool:
    origin = typing.get_origin(hint)
    if origin in (types.UnionType, typing.Union):
        return any(_matches(v, a) for a in typing.get_args(hint))
    if origin is Literal:
        # The words a parameter takes (task 244, P-1): a str among them.
        return isinstance(v, str) and v in typing.get_args(hint)
    if hint is type(None):
        return v is None
    if origin in (list, Sequence):
        # A list or a tuple: a str is a sequence of strs too, and never what
        # a list parameter means.
        (inner,) = typing.get_args(hint)
        return isinstance(v, (list, tuple)) and all(_matches(x, inner) for x in v)
    if origin is dict:
        key, val = typing.get_args(hint)
        return isinstance(v, dict) and all(
            _matches(k, key) and _matches(x, val) for k, x in v.items()
        )
    if hint is bool:
        return isinstance(v, bool)
    if hint is float:
        return isinstance(v, numbers.Real) and not isinstance(v, bool)
    if hint is int:
        return isinstance(v, numbers.Integral) and not isinstance(v, bool)
    if hint is str:
        return isinstance(v, str)
    if hint is timedelta:
        return isinstance(v, timedelta)
    if hint is _Expr:
        # The run time's stand-in for `pl.Expr` (rheon._duration): an
        # expression exists only once Polars is imported.
        return _is_expr(v)
    if typing.is_typeddict(hint):
        # A table (`rp.target`): its keys and no other, the required ones
        # present, each value of its annotated shape (review 2026-09-26, F4:
        # a table fell through to "not read", and a wrong entry was named
        # by JSON path).
        if not isinstance(v, dict):
            return False
        # `__required_keys__` reads every key as required under
        # `from __future__ import annotations`; the annotations say which.
        hints = typing.get_type_hints(hint, include_extras=True)
        qualified = (typing.NotRequired, typing.Required)
        required = {k for k, h in hints.items() if typing.get_origin(h) is not typing.NotRequired}
        plain = {
            k: typing.get_args(h)[0] if typing.get_origin(h) in qualified else h
            for k, h in hints.items()
        }
        return (
            set(v) <= set(plain)
            and required <= set(v)
            and all(_matches(x, plain[k]) for k, x in v.items())
        )
    return True  # an annotation this does not read; the Rust side still checks


def _describe(hint: Any, plural: bool = False) -> str:
    if hint == TargetList:
        return (
            "lists of column names, rheon.target tables or formula targets"
            if plural
            else "a list of column names, rheon.target tables or formula targets"
        )
    origin = typing.get_origin(hint)
    if origin in (types.UnionType, typing.Union):
        args = [a for a in typing.get_args(hint) if a is not type(None)]
        # A clock parameter's three duration forms read as one word.
        duration = set(typing.get_args(Duration))
        if duration <= set(args):
            args = [a for a in args if a not in duration]
            parts = [_describe(a, plural) for a in args]
            parts.insert(1, "durations" if plural else "a duration")
        else:
            parts = [_describe(a, plural) for a in args]
        return " or ".join(parts)
    if origin is Literal:
        words = _one_of(typing.get_args(hint))
        return f"strs, each one of {words}" if plural else words
    if origin in (list, Sequence):
        (inner,) = typing.get_args(hint)
        return ("lists of " if plural else "a list of ") + _describe(inner, plural=True)
    if origin is dict:
        key, val = typing.get_args(hint)
        return f"a dict from {_describe(key, plural=True)} to {_describe(val, plural=True)}"
    nouns = {float: ("a number", "numbers"), int: ("an int", "ints")}
    nouns |= {bool: ("a bool", "bools"), str: ("a str", "strs")}
    one, many = nouns.get(hint, (str(hint), str(hint)))
    return many if plural else one


def _got(v: Any) -> str:
    r = repr(v)
    return f"{type(v).__name__} {r if len(r) <= 60 else r[:57] + '...'}"


#: The model keys the Rust spec skips when they are absent
#: (``skip_serializing_if`` in ``crates/rheon-polars/src/spec.rs``): a key
#: written as null there would move every spec's bytes and cost a schema
#: bump. A builder writes each of these only when it is given, so the bank
#: reports back the dict it made: a ``None`` the bank never writes made
#: ``ModelBank([s]).specs[0] != s`` for every ``marginal`` (review
#: 2026-10-05, the TB5 leg). ``holt``'s ``trend`` is written only when off.
_SKIPPED_WHEN_ABSENT: dict[str, frozenset[str]] = {
    "holt": frozenset({"trend"}),
    "hawkes": frozenset(
        {"kernel_half_lives", "window_events", "window_size", "closed", "max_state_bytes"}
    ),
    "garch": frozenset(
        {
            "vol",
            "dist",
            "truncation",
            "variance_targeting",
            "start_rows",
            "start_span",
            "horizon",
            "max_state_bytes",
        }
    ),
    "ewridge": frozenset({"gram_threads"}),
    "expectile": frozenset(
        {
            "ridge",
            "refit_rows",
            "refit_span",
            "window_rows",
            "window_size",
            "closed",
            "max_state_bytes",
            "refit_budget",
        }
    ),
    "huber": frozenset(
        {
            "huber_scale",
            "huber_scale_half_life",
            "feature_sets",
            "ridge_scale",
            "emit_huber_scale",
            "huber_refit_rows",
            "huber_refit_span",
            "max_state_bytes",
            "refit_budget",
        }
    ),
    "sgd": frozenset(
        {
            "huber_scale",
            "huber_scale_half_life",
            "huber_refit_rows",
            "huber_refit_span",
            "max_state_bytes",
            "refit_budget",
        }
    ),
    "quantile": frozenset(
        {"quantile_refit_rows", "quantile_refit_span", "max_state_bytes", "refit_budget"}
    ),
    "ew_cov": frozenset({"gram_threads"}),
    "marginal": frozenset(
        {
            "lags",
            "serial_rule",
            "cross_lags",
            "bins",
            "bin_rule",
            "bin_warm_rows",
            "bin_edges",
            "bin_budget",
            "bin_stat",
            "bin_huber_delta",
            "bin_refit_rows",
            "refit_budget",
            "shards",
            "window_lags",
            "feature_moments",
        }
    ),
    "audit": frozenset({"pairs", "distinct_cap"}),
    "kalman": frozenset({"covariance_form"}),
    "glm": frozenset({"refit_span", "max_state_bytes"}),
    "kmeans": frozenset({"warm_span", "update_every", "split_merge_every"}),
    "hmm": frozenset({"warm_span"}),
    "bocpd": frozenset({"warm_span", "hazard_rows"}),
    "corrchange": frozenset({"permute_every"}),
}


def _takes_duration(hint: Any) -> bool:
    """Whether a parameter's annotation admits a duration: the clock
    parameters, and nothing else."""
    if hint is timedelta:
        return True
    return any(_takes_duration(a) for a in typing.get_args(hint))


def _finite(value: Any) -> bool:
    if isinstance(value, (list, tuple)):
        return all(_finite(x) for x in value)
    if isinstance(value, dict):
        return all(_finite(x) for x in value.values())
    if isinstance(value, numbers.Real) and not isinstance(value, bool):
        return not math.isinf(value)
    return True


#: The int parameters whose Rust floor is 1, not 0 (review 2026-09-12, D8);
#: for a list of ints, each entry's floor.
_AT_LEAST_ONE = frozenset(
    {
        "lags",
        "cross_lags",
        "shards",
        "gram_threads",
        "update_every_rows",
        "split_merge_every_rows",
        "max_clusters",
        "resid_autocorr_lag",
        "ljung_box_lags",
        "n_clusters",
        "n_components",
        # A lasso of no sweeps never descends: every solve is a failure, and
        # the coefficients read like a fit (review 2026-10-05, PB7).
        "max_iter",
        # A cap of no rows is no schedule: every row is `coef_every = 0`
        # (docs/PLAN.md task 178), and in every row cap the clock form's `0`
        # is every row (task 196, U7).
        "max_rows_between_coefs",
        "max_rows_between_solves",
        "max_rows_between_snapshots",
        "max_rows_between_pcas",
        "max_rows_between_prunes",
        # rcov's: a jitter of 1 is none, and a stride of 1 every return; a
        # negative one was told ">= 0", and 0 then refused (task 278, b11).
        "jitter",
        "noise_stride",
        "iv_stride",
    }
)


#: The int parameters whose floor the Rust side refuses with its reason,
#: and the floor as this side's refusal of a negative one states it: a
#: negative one was told ">= 0", which is not the floor (task 278, b11).
#: Between 0 and the floor the Rust refusal, which gives the reason, is
#: left to speak.
_FLOOR = {
    "block_rows": ("1", "1 or more"),
    "preavg_rows": ("2 (3 under psd=False)", "2 or more (3 or more under psd=False)"),
    # 0 is the Rust side's to refuse, which says why: no component.
    "pca": ("1", "1 or more"),
}


def _int_floor(key: str) -> tuple[int, str, str]:
    """The least an int parameter may be here, how its refusal states the
    floor, and the values its remedy asks for."""
    if key in _FLOOR:
        return 0, *_FLOOR[key]
    floor = 1 if key in _AT_LEAST_ONE else 0
    return floor, str(floor), f"{floor} or more"


#: The int parameters that are a ``u32`` on the Rust side; every other count
#: is a ``u64`` (``usize`` on the 64-bit platforms the package ships for).
#: A count past the width was named by serde as ``model`` (review
#: 2026-10-06, YA4); ``test_an_int_past_the_rust_width_is_refused_by_name``
#: holds this table to the Rust side.
_U32 = frozenset(
    {
        "max_rows_between_coefs",
        "max_rows_between_solves",
        "max_rows_between_snapshots",
        "max_rows_between_pcas",
        "max_rows_between_prunes",
        "max_iter",
        "update_every_rows",
        "split_merge_every_rows",
        "huber_refit_rows",
        "bin_refit_rows",
        "quantile_refit_rows",
        "refit_rows",
    }
)

#: The counts whose ceiling is tighter than their width: each sizes an
#: allocation before the first row -- a ring of that many rows, or the
#: permutation draws held for a quantile -- and Rust refuses past it too
#: (``rheon_core::MAX_LAG``, ``MAX_PERM``; review 2026-10-06, CD10). For a
#: list of counts, each entry's ceiling.
_CEILING = {
    "lags": 2**20,
    "resid_autocorr_lag": 2**20,
    "robust_se_lags": 2**20,
    "ljung_box_lags": 2**20,
    # Newey and West's lags are twice it.
    "horizon_rows": 2**19,
    "n_perm": 2**20,
    # A refit's buffer is held whole from a target's first learned row.
    "huber_refit_rows": 2**20,
    "quantile_refit_rows": 2**20,
}

#: Why a count's ceiling is where it is, said after the refusal where the
#: Rust side says it too (``rheon_core::MAX_PERM``'s message).
_REFIT_ROWS_WHY = (
    "the refit holds that many rows from a target's first learned row, so the count sets "
    "aside memory before any row is seen"
)
_CEILING_WHY = {
    "n_perm": "every draw is kept, and each takes a pass over the rows",
    "huber_refit_rows": _REFIT_ROWS_WHY,
    "quantile_refit_rows": _REFIT_ROWS_WHY,
}

#: A ceiling one builder's count has that its width does not say:
#: ``hmm``'s ``n_components`` sizes its transition matrix, its square in
#: cells, and its states before the first row (``rheon_core::Hmm::MAX_K``),
#: where ``kmeans``' ``n_clusters`` is held to 2^16 by the Rust side.
_CEILING_OF = {"hmm": {"n_components": 2**10}}


def _int_ceiling(key: str, builder: str = "") -> int:
    """The most an int parameter of ``builder`` may be: its own ceiling,
    else its width."""
    own = _CEILING_OF.get(builder, {})
    if key in own:
        return own[key]
    return _CEILING.get(key, 2**32 - 1 if key in _U32 else 2**64 - 1)


def _lists(value: Any) -> Any:
    """``value`` with every tuple a list, at any depth: the dict a builder
    returns is the one the bank reports back, and ``features=("x0",)`` kept
    its tuple, so ``ModelBank([s]).specs[0] != s`` (review 2026-10-06,
    YA5)."""
    if isinstance(value, (list, tuple)):
        return [_lists(v) for v in value]
    if isinstance(value, dict):
        return {k: _lists(v) for k, v in value.items()}
    return value


#: The parameters task 144 renamed (docs/PLAN.md): an old name is refused
#: naming the new one, with no alias.
_RENAMED = {
    "halflife": "half_life",
    "long_halflife": "long_half_life",
    "coef_halflife": "coef_half_life",
    "revert_halflife": "revert_half_life",
    "select_halflife": "select_half_life",
    "level_halflife": "half_life",
    "trend_halflife": "trend_half_life",
    "label_delay": "embargo",
    "max_dclock": "gap_cap",
    "window": "window_size",
    "min_periods": "min_weight",
    "emit_resid_z": "emit_zscore",
    "scale_features": "standardize",
    "on_clock_reset": "restart_after_step_back",
    "min_backwards_jump": "restart_after_step_back",
    "ridge_decay": "ridge_scale",
    "add_intercept": "fit_intercept",
    "max_cd_iters": "max_iter",
    "cd_tol": "tol",
    "reset": "change_action",
    # Task 196 (N16): holt's level takes the spec's `half_life`. Its N14
    # names are task 538's clock forms now.
    "level_half_life": "half_life",
}

#: The builders with no ``features`` keyword (task 244, P-6), and what each
#: reads instead. A spec dict or a TOML table still says ``features = []``:
#: every spec has the key there.
_NO_FEATURES = {
    "holt": "it fits only each target's own level and trend",
    "seqtest": "it reads only its targets, or the residuals of the specs a and b name",
    "hawkes": "each of its targets is a node, whose values above 0 are its events",
    "garch": "each of its targets is a return series whose variance it models",
}

#: The parameters renamed in one builder, or whose old name another keeps
#: (docs/PLAN.md task 195, N11): ``rls``'s ``ridge`` is ``delta``, and
#: ``ridge`` is still :func:`ewridge`'s, :func:`huber`'s and :func:`quantile`'s;
#: ``kmeans``' ``k`` is ``n_clusters`` and ``hmm``'s ``n_components``. The
#: names renamed for 1.0 and read until 2.0 are refused here since: the
#: builder names the new one.
_RENAMED_IN = {
    "rls": {"ridge": "delta"},
    "kmeans": {"k": "n_clusters", "seed_rule": "init"},
    "hmm": {"k": "n_components", "seed_rule": "init", "covariance": "covariance_type"},
    "ew_class": {"covariance": "covariance_type", "window_every": "snapshot_every"},
    "ewridge": {"window_every": "snapshot_every"},
    "lasso": {"window_every": "snapshot_every", "lasso_path": "penalties"},
    "ew_cov": {"window_every": "snapshot_every", "max_rows_between_pca": "max_rows_between_pcas"},
    "marginal": {"window_every": "snapshot_every"},
    "bocpd": {
        "emission": "covariance_type",
        "prior_mean": "mean_prior",
        "prior_kappa": "mean_precision_prior",
        "prior_nu": "degrees_of_freedom_prior",
        "prior_scale": "covariance_prior",
    },
    "corrchange": {"span_rows": "window_rows", "reset_on_flag": "change_action"},
}

#: The keywords of the functions that run a stream that task 196 renamed
#: (docs/PLAN.md §18, N2): ``chunk_size`` is Polars' name on the call it
#: feeds, ``collect_batches(chunk_size=)``. :func:`_renamed_keywords`
#: refuses the old one naming the new.
_RENAMED_KEYWORDS = {"chunk_rows": "chunk_size"}


def _renamed_keywords[**P, R](fn: Callable[P, R]) -> Callable[P, R]:
    """``fn``, refusing a keyword :data:`_RENAMED_KEYWORDS` names by the new
    name, where Python would say only that it is unexpected: the refusal
    :func:`rheon._renamed.renamed_keywords` gives every helper, as
    ``<qualified name>(): <old> was renamed <new>``."""
    return renamed_keywords(f"{fn.__qualname__}()", _RENAMED_KEYWORDS)(fn)


def _shown(v: Any) -> str:
    """A value as a refusal shows it: its repr, cut at 60 characters."""
    r = repr(v)
    return r if len(r) <= 60 else r[:57] + "..."


def _keyword_problem(
    builder: str,
    who: str,
    key: str,
    value: Any,
    own: dict[str, Any],
    shared: dict[str, Any],
    inf_ok: frozenset[str],
    problems: list[Exception],
) -> None:
    """What is wrong with one keyword of a builder, added to ``problems`` as
    the exception to raise for it: a name the builder does not take, a value of
    the wrong kind or out of its range. The Rust side checks the rest once
    every keyword passes here."""
    if key == "targets" and isinstance(value, (list, tuple)):
        # A table written by hand with a relative target's keys (task 201):
        # refused by name, where the table's shape check would say only that
        # `targets` is not a list of targets.
        for t in value:
            if isinstance(t, dict) and any(k in t for k in _RELATIVE_KEYS):
                what = t.get("column", t.get("name"))
                target = "a target" if what is None else f"target {quoted(what)}"
                given = next(k for k in _RELATIVE_KEYS if k in t)
                problems.append(
                    TypeError(
                        f"{who}: {target} sets {given}, but relative targets were removed. "
                        f"{_RELATIVE_REMEDY}"
                    )
                )
                return
    if key == "features" and builder in _NO_FEATURES:
        problems.append(
            TypeError(
                f"{who}: {builder}() takes no features, since {_NO_FEATURES[builder]}. "
                "Leave out features."
            )
        )
        return
    hint = own.get(key, shared.get(key))
    if hint is None:
        new = _RENAMED.get(key) or _RENAMED_IN.get(builder, {}).get(key)
        # Named only where this builder takes the new name: `window` was
        # renamed `window_size`, which `rls` does not take.
        if new is not None and (new in own or new in shared):
            problems.append(
                TypeError(
                    f"{who}: {key} was renamed {new}, and {builder}() takes only the new name. "
                    f"Use {new}."
                )
            )
            return
        problems.append(
            TypeError(
                f"{who}: {builder}() takes no parameter {quoted(key)}. "
                "Remove it, or correct its spelling."
            )
        )
        return
    if not _matches(value, hint):
        # A word outside the ones the parameter takes is a value error, in
        # the shape every surface gives it (task 244, P-4); anything else of
        # the wrong shape is a type error.
        if (bad := _bad_word(value, hint)) is not None:
            if (reason := word_reason(who, key, bad[0])) is not None:
                problems.append(ValueError(reason))
                return
            if (why := _WORD_REASONS.get((builder, key))) is not None:
                problems.append(ValueError(f"{who}: {why.format(got=quoted(bad[0]))}"))
                return
            problems.append(ValueError(words_refusal(who, key, *bad, hint=hint)))
            return
        # A parameter that takes only words says so in its remedy.
        kind, got = _describe(hint), _got(value)
        if typing.get_origin(hint) is Literal:
            problems.append(
                TypeError(f"{who}: {key} must be {kind}, but it is {got}. Use one of those words.")
            )
        else:
            problems.append(
                TypeError(
                    f"{who}: {key} must be {kind}, but it is {got}. Pass a value of that kind."
                )
            )
        return
    # Every int parameter is a count (u32 on the Rust side), and some are
    # counts of something there must be one of: the Rust side's floor, said
    # here, where `0` passed with nothing said (review 2026-09-12, D8).
    if (
        isinstance(value, numbers.Integral)
        and not isinstance(value, bool)
        and int in (hint, *typing.get_args(hint))
    ):
        floor, stated, more = _int_floor(key)
        if value < floor:
            problems.append(
                ValueError(
                    f"{who}: {key} must be at least {stated}, but it is {value}. "
                    f"Set {key} to {more}."
                )
            )
            return
        # And at most its width, or the tighter ceiling of a count that sizes
        # an allocation (review 2026-10-06, YA4 and CD10).
        ceiling = _int_ceiling(key, builder)
        if int(value) > ceiling:
            why = _CEILING_WHY.get(key)
            said = f": {why}" if why else ""
            problems.append(
                ValueError(
                    f"{who}: {key} must be at most {ceiling}, but it is {value}{said}. "
                    f"Lower {key} to {ceiling} or below."
                )
            )
            return
    # And each entry of a list of counts (review 2026-09-26, F7: a negative
    # lag was named by serde as `model`).
    if (
        isinstance(value, (list, tuple))
        and value
        and all(isinstance(x, numbers.Integral) and not isinstance(x, bool) for x in value)
        and list[int] in (hint, *typing.get_args(hint))
    ):
        floor, stated, more = _int_floor(key)
        if min(value) < floor:
            problems.append(
                ValueError(
                    f"{who}: {key} must each be at least {stated}, but one of them is "
                    f"{min(value)}. Set each to {more}."
                )
            )
            return
        ceiling = _int_ceiling(key, builder)
        if max(value) > ceiling:
            problems.append(
                ValueError(
                    f"{who}: {key} must each be at most {ceiling}, but one of them is "
                    f"{max(value)}. Lower each to {ceiling} or below."
                )
            )
            return
    if key not in inf_ok and key not in _INF_REFUSED_BY_RUST and not _finite(value):
        if isinstance(value, (list, tuple, dict)):
            problems.append(
                ValueError(
                    f"{who}: {key} must hold finite numbers, but one of its values is "
                    f"infinite. Set each value of {key} to a finite number."
                )
            )
            return
        problems.append(
            ValueError(
                f"{who}: {key} must be finite, but it is {_shown(value)}. "
                f"Set {key} to a finite number."
            )
        )
        return


def _checked[**P, R](fn: Callable[P, R]) -> Callable[P, R]:
    """Check each keyword against ``fn``'s annotations (and ``_common``'s for
    the shared parameters) so a wrong shape names the parameter."""
    skip = {"return", "common"}
    own = {k: v for k, v in typing.get_type_hints(fn).items() if k not in skip}
    shared = typing.get_type_hints(_common)
    shared = {k: v for k, v in shared.items() if k not in {"return", "name", "model"}}
    inf_ok = _INF_OK["*"] | _INF_OK.get(fn.__name__, frozenset())
    clock = frozenset(k for k, v in {**shared, **own}.items() if _takes_duration(v))

    @functools.wraps(fn)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        name = args[0] if args else kwargs.get("name")
        if not isinstance(name, str):
            got = "none is given" if name is None else f"it is {_got(name)}"
            raise TypeError(
                f"rheon.spec: a spec's name must be a str, but {got}. "
                "Pass the name of the spec's output column as its first argument."
            )
        who = f"spec {quoted(name)}"
        given = kwargs
        # Every keyword is checked, and every problem raised at once (WRITING
        # §11; task 338's decision 2): one keyword's problem does not hide the
        # next keyword's.
        problems: list[Exception] = []
        for key, value in given.items():
            if key == "name":
                continue
            _keyword_problem(fn.__name__, who, key, value, own, shared, inf_ok, problems)
        if problems:
            raise refusal(who, problems)
        # A clock parameter's duration, however it was written, is kept as
        # the text a TOML config writes and a state file stores (task 88),
        # and an infinity word as the number it names (YA7). Every tuple is a
        # list, as the bank reports the dict back (YA5).
        written = {
            key: infinity_as_number(duration_text(_lists(value), who, key))
            if key in clock
            else _lists(value)
            for key, value in given.items()
        }
        return typing.cast(Callable[..., R], fn)(*args, **written)

    return wrapper


__all__ = [
    "audit",
    "bocpd",
    "corrchange",
    "deco",
    "hmm",
    "rcov",
    "ew_class",
    "ew_cov",
    "ewridge",
    "expectile",
    "ftrl",
    "garch",
    "glm",
    "hawkes",
    "holt",
    "huber",
    "kalman",
    "kmeans",
    "lasso",
    "marginal",
    "micro",
    "output_fields",
    "pa",
    "quantile",
    "rls",
    "seqtest",
    "sgd",
]


[docs] class Target(TypedDict): """A target column under a name of its own, written as a table. It is what :func:`rheon.target` returns, and a ``[[specs]]`` target table in the command line's TOML. ``column`` is the column the model learns, read as it is. ``name`` is the name its output fields carry, ``column``'s when it is not given. .. rubric:: Examples .. code-block:: python price: rp.Target = {"column": "y", "name": "price"} # as rp.target("y", name="price") print(price == rp.target("y", name="price")) .. code-block:: text True """ column: str name: NotRequired[str]
[docs] class FormulaTarget(TypedDict): """A formula target, written as a table. It is what an expression over the window operators that looks ahead becomes in a spec's ``targets``, and a ``[[specs]]`` target table with ``name`` and ``formula`` in the command line's TOML. ``name`` is the expression's alias, which the output fields carry. ``formula`` is the expression's compact tree (:mod:`rheon.polars.ops`), holding at least one window operator that looks ahead (``reverse=True``). .. rubric:: Examples .. code-block:: python ahead = rp.ewm_mean("y", half_life=5.0, window_size=10.0, reverse=True).alias("y_ahead") spec = rp.spec.ewridge("m", targets=[ahead], features=["x0"], half_life=50.0) print(list(spec["targets"][0]), spec["targets"][0]["name"]) # a FormulaTarget .. code-block:: text ['name', 'formula'] y_ahead """ name: str formula: list[Any]
#: What a builder's ``targets`` takes: column names, with #: :func:`rheon.target` tables and window expressions #: (:mod:`rheon.polars.ops`, looking ahead) among them, in a list or a tuple. #: A ``Sequence``, which is covariant, so a ``list[str]`` a caller already has #: type-checks, and so do a list of tables, a list of expressions and a mix: #: ``list`` is invariant, and a union of two lists refused all three (review #: 2026-10-05, YA4). A ``str`` is a sequence of strs to a type checker; the #: builders refuse one by name when they run. #: A type checker reads ``pl.Expr``; the run time reads the stand-in #: ``rheon._duration._Expr``, so the builders' annotations resolve without #: Polars. if TYPE_CHECKING: TargetList = Sequence[str | Target | FormulaTarget | pl.Expr] else: TargetList = Sequence[str | Target | FormulaTarget | _Expr] #: The keys of task 107a's relative target, removed in task 201: a target #: table naming one is refused by name, with :data:`_RELATIVE_REMOVED`. _RELATIVE_KEYS = ("relative_to", "relative") #: What a relative target is told to do on the Python side; the Rust side #: says the same of a spec dict, a TOML file and a saved state, with the #: command line's input file in place of the query. _RELATIVE_REMEDY = ( "Compute the target as a column with Polars' with_columns in the query before the bank, " 'such as lf.with_columns(ret=pl.col("p") - pl.col("mid")), and name that column in ' "targets." ) #: What ``rp.target`` says of ``relative_to`` and ``relative``. _RELATIVE_REMOVED = ( "relative targets were removed, and relative_to and relative with them. " + _RELATIVE_REMEDY ) def target_name(t: str | Target | FormulaTarget) -> str: """The name a target's output fields carry: a string target's own, a table's ``name``, or its ``column`` when it gives none.""" if isinstance(t, str): return t if "formula" in t: return typing.cast(FormulaTarget, t)["name"] return t.get("name", t["column"]) def target_columns(t: str | Target | FormulaTarget) -> list[str]: """The columns a target reads: a string target's own; a table's ``column``; a formula's columns. What a plan must keep for the bank (review 2026-09-26, D1/F1).""" if isinstance(t, str): return [t] if "formula" in t: from rheon.polars import _formula return _formula.columns(typing.cast(FormulaTarget, t)["formula"]) return [t["column"]] def formula_target(who: str, expr: pl.Expr) -> Target | FormulaTarget: """A window expression as a target table (docs/PLAN.md task 104): named by its alias, holding at least one operator looking ahead. A bare column under an alias, ``pl.col("p").alias("price")``, is Polars' spelling of ``rp.target("p", name="price")``, and is read as it (task 244, M-11).""" from rheon.polars import _formula tree = _formula.to_tree(expr, who) name = expr.meta.output_name() # The alias names the target; the tree kept is the formula under it. if isinstance(tree, list) and tree and tree[0] == "alias": name = tree[2] tree = tree[1] if isinstance(tree, list) and len(tree) == 2 and tree[0] == "col": column = tree[1] if name == column: raise ValueError( f"{who}: target pl.col({column!r}) is the column itself, with no name of its " f"own. Write the string {column!r} in targets, or name the target with " f'.alias("...") or rheon.target({column!r}, name="...").' ) return target(column, name=name) if name.startswith(_formula.PREFIX): raise ValueError( f"{who}: target {_shown(str(expr))} needs a name, but it has only the name of its " f'window operator. Name it with .alias("...").' ) if name in _formula.columns(tree): # Unaliased, a positional expression is named after its leftmost # column, here one the formula itself reads; the bank could never # add the target beside it (task 159, P1). raise ValueError( f"{who}: target {quoted(name)} takes its name from a column its formula reads, so " f"the bank cannot add it beside that column. Give it a name of its own with " '.alias("...").' ) if not _formula.looks_ahead(tree): # Name the call that makes the column: with_windows for a formula over # operators looking back, Polars' with_columns for one of the row alone, # which with_windows refuses in turn (README-ITERATIONS, E11). if _formula.operators(tree): raise ValueError( f"{who}: target {quoted(name)} holds no window operator looking ahead (ewm_mean, " "ewm_sum, ewm_rate or ewm_quantile with reverse=True), so it is known at its own " "row. Add it as a column with rp.stream.with_windows in the query before the bank, " "and name that column in targets." ) raise ValueError( f"{who}: target {quoted(name)} holds no window operator, so it is known at its own " "row. Add it as a column with Polars' with_columns in the query before the bank, " "and name that column in targets." ) return {"name": name, "formula": tree}
[docs] @removed_keywords("rheon.target", _RELATIVE_KEYS, _RELATIVE_REMOVED) def target(column: str, *, name: str | None = None) -> Target: """Name a target column's output fields after a name of your own. Use it in a spec's ``targets`` when the column's own name is not the name you want the fields to carry. For a target computed from its own row's columns, make a column with Polars' ``with_columns`` in the query before the bank, and for one computed from the rows after it, give a formula target (:mod:`rheon.polars.ops`). .. rubric:: Parameters ``column`` The column the model learns, read as it is. A target's column used as a feature is refused, whatever its name. ``name`` The name its output fields carry: ``rp.target("p", name="price")`` writes ``pred_price`` and the rest. ``None``, the default, uses the column's name, as a string target does, and so does a ``name`` equal to the column. .. rubric:: Returns A :class:`Target` table, ``{"column": column, "name": name}``, with ``name`` left out when it is not given. .. rubric:: Raises ``TypeError`` ``column`` or ``name`` is not a str, or ``relative_to`` or ``relative`` is given: relative targets were removed, and the message says how to compute one as a column. ``ValueError`` ``column`` or ``name`` is empty. .. rubric:: Examples This code reads ``df`` from `Example data <https://github.com/rheon-dev/rheon/blob/main/docs/EXAMPLE-DATA.md>`_: .. code-block:: python spec = rp.spec.ewridge( "m", targets=[rp.target("y", name="price")], features=["x0"], half_life=50.0 ) print(rp.target("y", name="price"), rp.spec.output_fields(spec)[:2]) .. code-block:: text {'column': 'y', 'name': 'price'} ['pred_price', 'resid_price'] .. rubric:: See also - :mod:`rheon.polars.ops`, the window operators a formula target is built from. .. rubric:: Notes Polars' own spelling of a column under another name, ``pl.col("p").alias("price")``, is read in ``targets`` as this same target. In the command line's TOML the same target is a table: ``targets = ["ret_5m", { column = "p", name = "price" }]``. For a return, a log ratio (``(pl.col("p") / pl.col("mid")).log()``) or a difference sits about zero, where ``hit_rate`` reads its sign. A plain ratio sits about 1, where two positive numbers always agree in sign. """ if not isinstance(column, str): raise TypeError( f"rheon.target: column must be a str, but it is {_got(column)}. " "Pass the name of the target's column." ) if not column: raise ValueError( "rheon.target: column must name a column, but it is empty. " "Pass the name of the target's column." ) out: Target = {"column": column} if name is not None: if not isinstance(name, str): raise TypeError( f"rheon.target({column!r}): name must be a str, but it is {_got(name)}. " "Pass the name the target's fields take, or leave name out." ) if not name: raise ValueError( f"rheon.target({column!r}): name must not be empty, since it names the target's " "fields. Pass a name, or leave name out to use the column's." ) out["name"] = name return out
def _common( name: str, model: dict[str, Any], *, targets: TargetList, features: list[str], fit_intercept: bool = True, clock: str | None = None, half_life: float | Duration | list[float | Duration] | None = None, lam: float | None = None, gap_cap: float | Duration | None = None, restart_after_step_back: float | Duration | None = None, session: str | None = None, session_gap: float | Duration | None = None, weight: str | None = None, min_weight: float | list[float] | None = None, min_settled_frac: float | None = None, max_error_inflation: float | None = None, emit_error_inflation: bool = False, emit_se_coef: bool = False, emit_clocks: bool = False, coef_every: float | Duration | None = None, max_rows_between_coefs: int | None = None, emit_sigma: bool = False, emit_zscore: bool = False, emit_selected: bool = False, emit_averaged: bool = False, average_eta: float | None = None, emit_metrics: bool = False, conformal: float | None = None, conformal_rate: float | Literal["auto"] | None = None, resid_quantiles: list[float] | None = None, emit_autocorr: bool = False, resid_autocorr_lag: int | None = None, emit_drift: bool = False, drift_delta: float | None = None, drift_threshold: float | Duration | None = None, drift_action: Literal["flag", "reset"] = "flag", drift_kind: Literal["page_hinkley", "cusum", "adwin", "ddm", "eddm", "kswin"] | None = None, drift_options: Mapping[str, float | int | bool] | None = None, emit_calibration: bool = False, calibration_half_life: float | Duration | None = None, emit_breaks: bool = False, breaks_half_life: float | Duration | None = None, emit_robust_se: bool = False, robust_se_half_life: float | Duration | None = None, robust_se_lags: int | None = None, emit_specification: bool = False, specification_half_life: float | Duration | None = None, ljung_box_lags: int | None = None, horizon_rows: int | None = None, emit_tails: bool = False, tails_half_life: float | Duration | None = None, emit_influence: bool = False, influence_half_life: float | Duration | None = None, emit_feature_health: bool = False, feature_health_half_life: float | Duration | None = None, embargo: float | Duration | None = None, label_clock: str | Sequence[str] | None = None, max_held_rows: int | None = None, held_overflow: Literal["refuse", "drop_oldest"] | None = None, group: str | None = None, group_close: Literal["monotone", "session"] | None = None, ) -> dict[str, Any]: written: list[str | Target | FormulaTarget] = [ formula_target(f"spec {quoted(name)}", t) if _is_expr(t) else typing.cast("str | Target | FormulaTarget", t) for t in targets ] spec = { "name": name, "model": model, "targets": written, "features": features, "fit_intercept": fit_intercept, "clock": clock, "half_life": half_life, "lam": lam, "gap_cap": gap_cap, "restart_after_step_back": restart_after_step_back, "session": session, "session_gap": session_gap, "weight": weight, "min_weight": min_weight, "min_settled_frac": min_settled_frac, "max_error_inflation": max_error_inflation, "emit_error_inflation": emit_error_inflation, "emit_se_coef": emit_se_coef, "emit_clocks": emit_clocks, "coef_every": coef_every, "max_rows_between_coefs": max_rows_between_coefs, "emit_sigma": emit_sigma, "emit_zscore": emit_zscore, "emit_selected": emit_selected, "emit_averaged": emit_averaged, "average_eta": average_eta, "emit_metrics": emit_metrics, "conformal": conformal, "conformal_rate": conformal_rate, "resid_quantiles": resid_quantiles, "emit_autocorr": emit_autocorr, "resid_autocorr_lag": resid_autocorr_lag, "emit_drift": emit_drift, "drift_delta": drift_delta, "drift_threshold": drift_threshold, "drift_action": drift_action, "emit_calibration": emit_calibration, "calibration_half_life": calibration_half_life, "emit_breaks": emit_breaks, "breaks_half_life": breaks_half_life, "emit_robust_se": emit_robust_se, "robust_se_half_life": robust_se_half_life, "robust_se_lags": robust_se_lags, "emit_specification": emit_specification, "specification_half_life": specification_half_life, "ljung_box_lags": ljung_box_lags, "horizon_rows": horizon_rows, "emit_tails": emit_tails, "tails_half_life": tails_half_life, "emit_influence": emit_influence, "influence_half_life": influence_half_life, "emit_feature_health": emit_feature_health, "feature_health_half_life": feature_health_half_life, "embargo": embargo, "group": group, "group_close": group_close, } # Written only when given, as the Rust spec writes them, so a spec # without them is the dict it always was. if label_clock is not None: spec["label_clock"] = label_clock if isinstance(label_clock, str) else list(label_clock) if max_held_rows is not None: spec["max_held_rows"] = max_held_rows if held_overflow is not None: spec["held_overflow"] = held_overflow if drift_kind is not None: spec["drift_kind"] = drift_kind if drift_options is not None: spec["drift_options"] = dict(drift_options) validate_spec(_json(spec)) return spec def _mirror_target( name: str, kind: str, features: list[str], common: Any, statistic: str, noun: str = "features", ) -> list[str]: """The ``targets`` a model with no target hands the plumbing: its first feature. ``targets=`` is refused by name, and so is an empty ``features``, which the Rust side names for every other model and these indexed before it could (review 2026-10-05, YA1 and YA5: an ``IndexError``, and a ``TypeError`` naming ``_common()``). ``noun`` is what the builder calls its features: ``audit``'s are ``columns``.""" # Both problems at once, where both hold. problems: list[Exception] = [] if "targets" in common: problems.append( TypeError( f"spec {quoted(name)}: {kind}() takes no targets, since {statistic} the " f"{noun}. Leave out targets." ) ) if not features: problems.append( ValueError( f"spec {quoted(name)}: {noun} must name at least one column, but it is empty. " f"List the columns in {noun}." ) ) if problems: raise refusal(f"spec {quoted(name)}", problems) return [features[0]]
[docs] @_checked def ewridge( name: str, *, targets: TargetList, features: list[str], ridge: float | list[float] | None = None, feature_sets: dict[str, list[str]] | None = None, standardize: bool = False, ridge_scale: Literal["mean", "sum"] = "mean", coef_prior: list[list[float]] | None = None, session_shrink: float | None = None, long_half_life: float | Duration | None = None, solve_every: float | Duration | None = None, max_rows_between_solves: int | None = None, gram_block_rows: int | None = None, gram_threads: int | Literal["auto"] | None = None, target_gaps: Literal["own_rows", "pairwise"] = "own_rows", window_size: float | Duration | None = None, closed: Literal["right", "both"] = "right", snapshot_every: float | Duration | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal["thin", "refuse"], float] | None = None, **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Exponentially weighted ridge regression on running sums. Use it as the default model for a numeric target, where one set of running sums fits a grid of ridge values and feature sets for one extra solve each, and a row takes no more time to learn for the grid. Use :func:`kalman` for coefficients that drift, :func:`huber` or :func:`quantile` for outliers or a quantile, and :func:`lasso` for a sparse fit. Use :func:`sgd` or :func:`pa` where learning a row must take O(k) time for ``k`` features: this model takes O(k²). .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight``, ``group`` and the diagnostics, are in :mod:`rheon.spec`. This model's own: ``ridge`` The penalty that pulls the slopes toward ``coef_prior``, or toward 0, so that a fit on few rows or collinear features stays determined. In the features' squared units, unless ``standardize``. Default ``1e-6``, a ridge too small to move a fit on features of unit scale that still keeps its solve determined. For features far from unit scale, set ``standardize=True``: on features far smaller than 1, such as returns, the default ridge outweighs the data, and on features far larger it may not keep a nearly collinear solve determined. Finite and at least 0: ``0`` is plain least squares. It never penalizes the intercept, except under ``ridge_scale = "sum"``. A list of two or more values fits one slot per value from the same sums, reported side by side as ``pred_<t>__r<ridge>``. A list of one value is no grid, and a value listed twice is refused. ``feature_sets`` Named subsets of ``features``, each fitted from the same sums, reported as ``pred_<t>__<set>``. Default: one fit over every feature. Only the named sets are fitted, so to keep a fit on every feature, name a set that holds them all. With two or more sets, ``emit_selected`` reports the set doing best. A single set is no grid: it is fitted alone, and its fields take no suffix. Refused when it names no set, names a set twice, holds an empty set, or names a column not in ``features`` or one twice in a set. ``standardize`` Solve on the correlation matrix and unscale the coefficients after, so that ``ridge`` means the same whatever the features' units, and a feature whose variance is zero, which would make the system singular, is dropped from the solve. Without an intercept it scales by each column's root mean square instead, and drops only a column that is all zero (*Standardizing without an intercept* in Notes). Default ``False``, which keeps ``ridge`` in the features' squared units, as a plain ridge regression has it. :func:`huber` and :func:`quantile` standardize the same way. ``ridge_scale`` What the ridge is scaled against, which decides whether its pull lasts or fades. ``S`` and ``eta`` are the running means of *The update*, ``W`` the weight behind them, and ``p`` the product of every decay the stream has applied: .. list-table:: :header-rows: 1 :widths: 14 40 46 * - setting - the prior - the system * - ``"mean"`` (the default) - a fixed per-observation penalty whose pull is permanent: "always stay near this belief" - ``(S + ridge * D) beta = eta``, the intercept unpenalized * - ``"sum"`` - sits on the decaying sum scale and fades as data arrives, the usual warm start: "begin at yesterday's fit and let evidence take over" - :func:`rls`'s, ``(W S + p * ridge * I) beta = W eta``, penalizing every coefficient, **the intercept's included** The default keeps the ridge a penalty, as in a plain ridge regression. ``"sum"`` is refused beside ``standardize``, beside any grid of ``ridge`` values and feature sets (two or more ``ridge`` values, or two or more sets), and beside ``window_size``. ``coef_prior`` The coefficients to shrink toward instead of zero, such as yesterday's fit: one vector per target, in the features' original units, ``len(features) + 1`` long when there is an intercept. Default none, which shrinks toward zero. The intercept's entry is read only under ``ridge_scale = "sum"``, the one solve that penalizes the intercept. Refused with the wrong number of vectors, a vector of the wrong length, or a value that is not finite. ``session_shrink`` A middle way between a session's decay and a full reset: at each session change, blend this session's running sums with the long run's, ``session_shrink`` being the long run's share, in ``[0, 1]``. ``0`` keeps this session's sums, and ``1`` takes the long run's moments at this session's weight. Default none, no blend. It moves the running sums' means and moments, where ``session_gap`` only decays their weight. It needs a ``session`` column and ``long_half_life``. It is refused beside ``session_gap = "reset"``, which resets the model at the change, beside ``group_close = "session"``, which closes the group there, and beside ``window_size``. ``long_half_life`` The half-life of the long run that ``session_shrink`` blends in, in clock units, above 0; ``inf`` keeps the whole history. A second set of running sums, the slow twin, decays at it. Default none, which keeps no twin, and refused without ``session_shrink``. ``solve_every`` How often the model solves for its coefficients, in clock units, at least 0: ``0`` solves on every row, and ``inf`` never on the clock. Left out, the schedule is by weight: a solve once the weight learned since the last reaches ``ln 2 / 50`` of the weight the fit holds, which in steady state is every ``half_life / 50`` of clock, at any row spacing. Under ``half_life = inf`` and under ``lam``, the default solves on every row. A prediction uses the coefficients of the last solve, so a coarser schedule is faster and its coefficients older. *The solve schedule* in Notes gives the rules at the schedule's edges. ``max_rows_between_solves`` The most rows between two solves, whatever the clock does, at least 1. Default off, so the clock or the weight alone sets the schedule. ``1`` solves on every row, so the coefficients are current at every row. ``gram_block_rows`` For a fit over hundreds of features: hold that many rows back and add them to the ``k x k`` matrix of the running sums in one matrix product, in place of adding each row to it as it is learned. Default 0, off: the gain is for fits of hundreds of features, and the held rows travel in the state. Refused where no schedule spaces the solves (``solve_every <= 0``, the default under ``lam`` and ``half_life = inf``, or ``max_rows_between_solves <= 1``), beside ``window_size``, and past 256 MiB of held rows. ``gram_threads`` The most of the bank's threads one update of the ``k x k`` matrix may use: a whole number of at least 1, or ``"auto"``. Default ``"auto"`` (``None`` acts as it), which splits an update only where the bank has idle threads. The threads are the bank's own, so it never adds one, and the output is the same to the bit at every count. *Threads* in Notes gives the rule ``"auto"`` follows. ``target_gaps`` Which rows a target's fit is read from where the target is null on some: .. list-table:: :header-rows: 1 :widths: 16 44 40 * - setting - the feature covariance is taken over - what that gives * - ``"own_rows"`` (the default) - the target's own rows, so its fit is the fit of those rows alone; targets present on the same rows share one matrix, and one that goes missing where the others are present takes a copy and keeps its own from then on - several targets keep one ``k x k`` matrix per pattern of missing rows, and a single target keeps one * - ``"pairwise"`` - every row, the way pandas' ``DataFrame.cov`` takes a pairwise-complete covariance: one matrix whatever the gaps - exact when the gaps have nothing to do with the features; where they do, each slope is scaled by the ratio of the feature's variance on the target's rows to its variance on all of them Keep the default where the gaps depend on the features, as with a target present only on trade rows between market-data rows. Either way ``weight_sum`` counts every row, and a null target is still predicted. ``window_size`` A hard window: the age, in clock units, finite and above 0, at which a row counts for nothing, where the decay alone would leave ``0.5 ** (age / half_life)`` of it. Inside the hard window the weights are still exponential, so this is an exponentially weighted regression under a hard window, not rolling least squares. Default none. It is refused beside ``ridge_scale = "sum"``, whose prior's scale is the product of every decay the stream applied, which a hard window cuts the data of but not the prior. It is refused beside ``session_shrink``, whose slow twin is a second set of running sums under a longer half-life, and beside ``gram_block_rows``. ``closed`` Which edge of the hard window holds the row exactly ``window_size`` old, in Polars' words (``rolling_sum_by(closed=)``). ``"right"``, the default, keeps the rows less than ``window_size`` old, as the window operators (:func:`rheon.polars.ewm_mean <rheon.polars.ops.ewm_mean>`) and ``rolling_sum_by`` do. ``"both"`` keeps that row too, and is refused without ``window_size``. ``"left"`` and ``"none"`` would leave out the row the hard window ends at, which a model cannot do, since it reads its fit after learning that row: both are refused. ``snapshot_every`` How often the hard window takes a snapshot of the running sums, in clock units, finite and at least 0: a number of the clock's units, a duration on a temporal clock (``"1m"``), or ``0`` for every row. Default none: every row, unless ``max_rows_between_snapshots`` is given. A coarser cadence divides the hard window's memory, and can only shorten the hard window it keeps. Refused without ``window_size``. ``max_rows_between_snapshots`` The most rows between two snapshots, at least 1. Whichever of it and ``snapshot_every`` comes first takes a snapshot. Default off, so the clock alone spaces them. Refused without ``window_size``. ``window_budget`` A bound, in MiB above 0, on the memory each hard window's ring of snapshots takes, and what happens at it: .. list-table:: :header-rows: 1 :widths: 30 70 * - ``window_budget`` - at the bound * - ``{"thin": mib}`` - drops every other snapshot and doubles the spacing between the rest, the clock's or the rows' or both, as often as it takes; like ``snapshot_every``, that can only shorten the hard window * - ``{"refuse": mib}`` - refuses the chunk, naming the ring's size and its cadence * - unset - refuses past 256 MiB per ring; ``{"refuse": float("inf")}`` is no bound Refused without ``window_size``. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields. `docs/OUTPUTS.md#ewridge <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#ewridge>`_ gives each field's type and when it is null: ``pred_<t>``, ``resid_<t>`` Per target: the prediction, and ``y - pred`` where the target is not null. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's predictions were withheld, null where they were not. ``coef`` Per (target, ridge value, feature set) slot in the order the ``pred`` fields declare them, the intercept then one entry per feature, zero for a feature outside the slot's set. :func:`coef_index` maps each position to its term, and :func:`coef_fields` names the column each becomes when the output column is unnested. ``support_coef`` On ``coef``'s rows, each coefficient's data share, laid out like ``coef``: how much of the fit after the row the data determined rather than the ridge (:mod:`rheon.spec`). plus the fields of the diagnostics switched on, as :mod:`rheon.spec` describes them. Under a half-life grid every field is suffixed per instance (the part of the model that fits one half-life), and under a ridge or feature-set grid each slot's fields (:mod:`rheon.spec`, "What a spec writes"). A combined grid joins the suffixes, as ``pred_y__mkt_r0.1``. :meth:`rheon.polars.ModelBank.gram` returns the sums behind the fit, one entry per Gram (under ``target_gaps = "own_rows"``, one per set of targets present on the same rows). A group that closes writes one row per Gram to :meth:`rheon.polars.ModelBank.closed_groups`. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for: - a ``ridge`` below 0 or not finite, or listed twice; - a ``feature_sets`` that names no set, names one twice, holds an empty set, or names a column not in ``features`` or one twice in a set; - a ``coef_prior`` with the wrong number of vectors, a vector of the wrong length, or a value that is not finite; - a ``ridge_scale`` other than ``"mean"`` or ``"sum"``, and ``"sum"`` beside ``standardize``, any grid of ``ridge`` values and feature sets (two or more of either), or ``window_size``; - a ``session_shrink`` outside ``[0, 1]``, or without ``long_half_life`` or ``session``, or beside ``session_gap = "reset"``, ``group_close = "session"`` or ``window_size``; - a ``long_half_life`` not above 0, or without ``session_shrink``; - a ``solve_every`` below 0, and a ``max_rows_between_solves`` or ``max_rows_between_snapshots`` of 0; - a ``gram_block_rows`` beside ``window_size``, without a solve cadence, or past 256 MiB of held rows, and a ``gram_threads`` of 0; - a ``window_size`` not finite or not above 0; a ``closed`` of ``"left"`` or ``"none"``; a ``snapshot_every`` below 0 or not finite; a ``window_budget`` not above 0; and ``closed="both"``, ``snapshot_every``, ``max_rows_between_snapshots`` or ``window_budget`` without ``window_size``. .. rubric:: The update Per row, ``w`` is the row's weight, ``λ = 0.5 ** (Δclock / half_life)`` its decay (``lam ** Δclock`` under ``lam``), and ``z`` the features with the intercept in front. ``Δclock`` is the clock's step since the last row the model did not skip, capped at ``gap_cap``, or ``session_gap`` at a session change, as the glossary's *decay* says. Under the default ``target_gaps = "own_rows"``, ``W_j`` is the weight behind target ``j`` over the rows that target is present on, and ``S_j`` and ``eta_j`` are its running means of ``z z'`` and of ``z * y_j`` over those rows. Under ``"pairwise"`` the slopes solve the centered system of *Target gaps* in Notes instead, with the feature covariance taken over every row. ``beta0_j`` is the target's ``coef_prior``, 0 without one: .. code-block:: text W_j' = λ * W_j + w S_j' = (λ * W_j * S_j + w * z z') / W_j' eta_j' = (λ * W_j * eta_j + w * z * y_j) / W_j' on the schedule: (S_j + ridge * D) beta_j = eta_j + ridge * D * beta0_j D = I with a 0 at the intercept .. rubric:: Example This code fits a slope that drifts from 1 to 3, under two ridge values, and prints the slope each found at the last row. A half-life of 500 rows lags the drift a little, and the ridge of 0.5 divides the slope by about ``1 + 0.5 / var(x)``: .. code-block:: python import numpy as np rng = np.random.default_rng(1) x = rng.standard_normal(5_000) slope = 1.0 + np.arange(5_000) / 2_500 # the true slope, row by row y = slope * x + 0.5 * rng.standard_normal(5_000) pl.DataFrame({"x": x, "y": y}).write_parquet("drift.parquet") rr = rp.spec.ewridge( "rr", targets=["y"], features=["x"], half_life=500.0, ridge=[1e-6, 0.5], # one fit per value, from the same sums ) bank = rp.ModelBank([rr]) bank.fit(pl.scan_parquet("drift.parquet")) # learn every row, keep no output print(f"the true slope at the last row: {slope[-1]:.2f}") for r in bank.coef().filter(pl.col("term") == "x").iter_rows(named=True): print(f"ridge {r['ridge']:g}: slope {r['coef']:.2f}") .. code-block:: text the true slope at the last row: 3.00 ridge 1e-06: slope 2.70 ridge 0.5: slope 1.81 .. rubric:: See also - `ewridge in docs/MODELS.md <https://github.com/rheon-dev/rheon/blob/main/docs/MODELS.md#ewridge--exponentially-weighted-ridge-regression>`_: recipes on data whose answer is known, and what the model is checked against. - :func:`rls`, the fit ``ridge_scale="sum"`` gives, by recursive least squares, which loses half as many digits on a nearly collinear design. - :func:`huber`, these sums with each row down-weighted by its residual, which takes this model's ``feature_sets`` and ``ridge_scale``. - :meth:`rheon.polars.ModelBank.gram` and :mod:`rheon.gram`, to read the sums back, pool them and solve them offline. .. rubric:: Notes **The sums.** The sums are means, not totals, so they stay bounded over a stream of any length. Every fit in a grid is solved from them, which is why a grid of ridge values and feature sets costs a solve each, and a row is learned once whatever the grid. A list of half-lives keeps one set of sums each. The second moments are kept centered (a weighted Welford update), so a feature far from zero loses no precision. **The solve.** The solve is a Cholesky factorization. A near-singular system is retried with a small jitter added to its diagonal, growing at each try, so each try is a rung of a ladder of jitters. A solve that needed one is counted in :meth:`rheon.polars.ModelBank.solve_failures`. A count above zero points at constant or collinear features, or too few rows for the features. A wide solve runs on the bank's threads, and its result is the same to the bit whatever their number (``RHEON_MAX_THREADS``, or the machine's cores): at 2,000 features a factorization and solve took 18 ms on eight threads against 68 on one. **The condition check.** A system can factorize and still be too nearly singular for its solve to keep a digit. Rounding can leave a matrix past ``1/u`` in condition positive definite, with ``u = 2**-53``. Its coefficients then come out wrong by more than their own size: two features equal to within ``1e-11`` of their spread gave slopes of -364.1 and 363.1 for a truth of 1 and -2. So each factorization estimates the condition of the system ``A`` with each column scaled by the root of its diagonal, ``H = E^-1 A E^-1`` with ``E = diag(sqrt(a_ii + delta))``. That is what a Cholesky solve is accurate to, whatever the features' units. A factorization that needed a jitter ``delta`` on the diagonal is judged as the system it solves, ``A + delta I``. On a design where one column is an exact combination of the others, the first rung's ``delta``, ``1e-12`` of the mean diagonal, leaves ``||H^-1||_1`` near ``1e12``, past the limit from about 30 coefficients. An upper bound from the factor decides most systems for a fraction of one solve, and the rest take an estimate of ``||H^-1||_1`` by Hager and Higham's method (LAPACK's ``dlacn2``), about four solves, from the factor in ``O(k^2)``. The factorization and solve are backward stable, with a backward error of at most ``gamma_{3k+1}`` in each of ``H``'s entries, where ``gamma_m = m u / (1 - m u)``, and so ``k * gamma_{3k+1}`` in its 1-norm. So the forward error of the scaled coefficients is at most ``2 kappa eta / (1 - kappa eta)``, with ``kappa eta = k * gamma_{3k+1} * ||H^-1||_1``. Where that bound reaches 1, no digit is promised: .. code-block:: text withheld where 3 * k * gamma_{3k+1} * ||H^-1||_1 >= 1 (k = 3: ||H^-1||_1 >= 1.0e14; k = 10: 9.7e12; k = 50: 4.0e11) There the fit is withheld: ``coef``, ``support_coef`` and the predictions are null, ``withheld_reason`` reads ``ill_conditioned``, and the solve is counted in ``solve_failures``. The next solve whose system is within the limit reports again. A ridge, ``standardize`` with a ridge, or fewer collinear features keep a system inside it. ``rls`` rotates the design where this model squares it, and loses half as many digits to the same design. **The ridge's two scales.** ``S`` is a weighted mean, so the two settings of ``ridge_scale`` mean two different priors. Under ``"sum"`` a constant target of 5 reads an intercept of 3.5 at row 20 under ``ridge=10``, ``half_life=50``, and 4.95 at row 200, until the prior fades. A ``coef_prior`` intercept is what it shrinks toward. **Standardizing without an intercept.** Under ``standardize`` without an intercept nothing is centered. The system is scaled by each column's root mean square instead, a fit through the origin is least squares through the origin, and the column dropped is one that is all zero. **The session blend.** On a session boundary the fit's moments become a mixture of the two data sets, ``1 - f`` of this session's and ``f`` of the long run's, ``f`` being ``session_shrink``: .. code-block:: text m' = (1 - f) * m_fast + f * m_slow C' = (1 - f) * C_fast + f * C_slow + f * (1 - f) * (m_fast - m_slow)(m_fast - m_slow)' for the means and the centered moments. The weight stays this session's, so ``weight_sum``, the warm-up gates and the solve schedule do not move. The blend changes the moments and nothing else. The coefficients stay as last solved until the next solve the schedule brings due, which reads the blended moments together with every row learned since. So the output is continuous in ``f``, and ``0`` is the same as no ``session_shrink``, to the bit. For the new session's first rows to read the blend at once, solve on every row (``max_rows_between_solves = 1``). The solve on the new session's first row then reads it, and the row after is predicted from it. With ``ridge_scale = "sum"`` the prior keeps this session's scale too, so at ``1`` the fit is the twin's moments under this session's prior. **The solve schedule.** ``solve_every = inf`` never solves on the clock: the sums are collected and nothing is solved but where the row cap and a target's first rows say. Any value of ``1e18`` or more does the same, past the end of any stream on every clock. ``1e18`` seconds is 3.2e10 years, ``1e18`` rows is 31.7 years at a billion rows a second, and on a number clock it is 31.7 years of epoch nanoseconds. The schedule by weight solves more often during warm-up and after a gap, where the fit moves most. A half-life far longer than the stream still solves, at rows further apart as the weight grows. The coefficients are solved from the sums as they stood at the last solve. The floor is the least of a row per unknown (``k + 1``, ``k`` without an intercept), ``min_weight`` and each target's own value of it. The schedule by weight runs no solve that comes due while the weight is below ``(1 - ln 2 / 50)(1 - 2**-16)`` of the floor, whether the weight or ``max_rows_between_solves`` brings it due, unless a hard window is set. Until the next solve comes due, the weight learned since is less than ``ln 2 / 50`` of the weight, so every row stays below the floor and is withheld, and none could read the solve. The ``2**-16`` covers the weight's rounding. The schedule moves on as after the solve. So every prediction, residual and spread is the one running every due solve would give, to the bit, apart from two rare cases: a target whose weight has decayed to exactly 0 below the floor, and a fit whose factorization fails at every rung. There a later row reads the last fit solved. ``coef`` there is the last fit solved, null before the first, and a solve not run is not counted in ``solve_failures``. So a group whose weight never reaches the floor, such as one of two rows over two features, reports no ``coef`` on any row, in ``bank.coef()`` or as a closed group. To keep every solve, give ``min_weight = 0``, which makes the floor 0 and withholds no prediction for its weight, or ``solve_every = 0``, which solves on every row by the clock and runs every solve. The solves not run are most of the warm-up's at a thousand features, and a fit there runs several times faster until the weight reaches the floor. The weight brings a solve due each time it has grown by ``ln 2 / 50``, about 1.4%: at rows of weight 1 and a weight of 1,000, every 14 rows. A row cap brings more solves due than that only where it is shorter, and a row cap of 1 brings one due on every row, so the skip saves most there. A given ``solve_every`` runs every solve its clock or its row cap brings due. No share of the weight bounds the weight learned between two of those, so it can cross the floor before the next one, and a row then reads the fit of a solve that ran below the floor. With ``solve_every = inf``, a row cap of 3, six features and rows of weight 1 with no decay, the solve on the sixth row, below the floor of 7, serves the eighth and ninth rows. A given ``solve_every`` above 0 and below ``1e18`` starts with a first period that solves by weight: once the weight learned since the last solve reaches ``ln 2 / 50`` of the weight the fit holds, under ``half_life = inf`` and ``lam`` too, where the default solves on every row. The period lasts until ``solve_every`` has passed since the group's first row or its last reset, or until ``max_rows_between_solves`` rows with weight have been learned. On the row clock, that start is a row before the first row. So an early fit of a few rows is not held for a whole period. The row that ends the period solves, and the schedule's clock and row count run from there. On a wide fit the period's solves can be most of the time. At 1,000 features and ``min_weight = 50``, ``solve_every = 1e9`` beside ``max_rows_between_solves = 1000`` solved 185 times in its first 1,000 rows, and ran 20,000 rows at 5,400 a second. ``solve_every = inf`` with the same row cap solved on rows 50, 1,050 and every 1,000 rows after, at 16,800 a second (an M4 Pro on two threads, load near 10). For solves by a row cap alone, give ``solve_every = inf``. A target's first solve falls on the row its weight reaches ``k + 1`` (``k`` without an intercept), where the schedule has not solved it sooner, whatever ``min_weight`` above that says. ``min_weight`` withholds the output alone, so the fit is the same at any ``min_weight`` from ``k + 1`` up, on every schedule. A row of weight 0 is clock alone: it never solves and is no row of the cap. A solve that comes due on one waits for the next row with weight, and the solves fall where they would without it. **Blocked updates.** Holding rows back gains from a few hundred features: with blocks of 256 rows, a fit that never solved learned its rows 5.1 to 6.6 times as fast as adding each row as it came, from 256 to 2,000 features. With a solve every 512 rows it was about 4 times as fast. Under ``gram_block_rows`` the matrix is brought up to date at the end of each block and before every solve, so the block never exceeds the solve cadence. ``weight_sum``, the timing of every prediction and chunk invariance are unchanged to the bit. The blocked sum is the same sum in another order, so a blocked fit agrees with an unblocked one to rounding. Each target's cross-moments with the features wait for the block as well, and are merged from the same pass over its rows. So a target adds little beside the product: at 200 features about 0.13 ns per feature and row (0.18 where the target has gaps), against 0.35 for adding its cross-moments row by row (one fit, one core of an Apple M4 Pro). A target's weight, mean and variance still take every row. The held rows travel in the state file, with each target's value on them. They are refused over 256 MiB, counting the slow twin of ``session_shrink`` and, under ``target_gaps = "own_rows"``, a block per target. **Threads.** ``gram_threads`` runs the update of the ``k x k`` matrix on up to that many threads: the block's matrix product under ``gram_block_rows``, and each row's rank-one update without it. The bank's ``threads`` sets how many threads it has (``RHEON_MAX_THREADS``, or one per core, when it is ``None``). The option caps how many of them one spec's update may take, so a count above the bank's number of threads runs on that number. A solve is not capped by this count: its factorization can use every thread the bank has. Each entry of the matrix is still summed by one thread in one order, because the product is cut into pieces by ``k`` alone, never by the count. So the output is the same to the bit at every count. ``"auto"`` splits only where the bank has idle threads. On each chunk the bank counts the pieces of work it runs side by side, one per spec and group, ``T``, on its ``P`` threads. When ``2 * T <= P``, each update may use ``2 * P // T`` threads, at most ``P``. Otherwise it uses one. Twice the even share lets a thread whose group is done take pieces of another group's update. The rule reads the two counts and nothing else, so it does not depend on timing. Measured on 14 cores against a count of 1: one group at 2,000 features learned 3.0 times as fast, and 3.5 times with ``gram_block_rows=256``. Four groups at 800 features learned 1.6 times as fast, and seven were even to 1.1 times. From eight groups up, a split of every count was even or up to 10% slower, so ``"auto"`` does not split there. With every fast core already running a group, splitting each row's update only adds the cost of handing it out. Up to 256 columns (the features and the intercept) the product is one piece, and below 725 a row's update stays on one thread, so the option changes nothing there. Being the same to the bit at every count, it is a setting and not part of the state. A saved bank resumes under the count of the specs given to ``load``, or, given none, under the count in the saved spec. **The hard window.** A hard window is exact. The weighted totals behind the means, ``W * S``, are sums of per-row contributions. So everything at or before a time ``u`` is ``λ_u`` times the totals as they stood then, ``λ_u`` being the decay from ``u`` to now, and subtracting that leaves the hard window. The model keeps a ring of snapshots to do it, so its memory grows with the snapshots the hard window holds: one per row by default, or one per ``snapshot_every``. A half-life grid is one instance per entry, each with its own ring. ``snapshot_every`` spaces the snapshots on the clock, as ``solve_every`` spaces solves, and ``max_rows_between_snapshots`` caps the rows between them, as ``max_rows_between_solves`` caps the rows between solves. A row of weight zero counts, a gap capped at ``gap_cap`` counts as the cap, and without a clock column the clock is the row's number. Under a clock spacing, every row at most ``window_size - snapshot_every`` old is kept and none older than ``window_size``. So the hard window kept is in ``[window_size - snapshot_every, window_size]`` in clock units, exactly, with ``snapshot_every`` the spacing in force: a thinning ``window_budget`` doubles it. A burst of rows inside one spacing takes no snapshot of its own. The bank plays each chunk's clock through its rings' snapshot schedule before it learns a row, so a chunk that would pass a refusing ``window_budget`` is refused whole and the bank goes on as it was. Under ``drift_action="reset"``, whose resets that check cannot foresee, the ring finds the overrun as the rows go in instead. The bank then refuses every later ``fit_predict``, ``predict`` and ``save``: load its last save with :meth:`rheon.polars.ModelBank.load`, and feed it the rows since. ``weight_sum``, ``sigma`` and ``zscore`` are read over the hard window as well, so the spread describes the rows the fit describes. The spread keeps a ring of its own for it, two floats and a row count a slot, bounded with the fit's. Everything that reads the spread reads it over the hard window too: drift's scale, the conformal band, and the ranking ``emit_selected`` and ``emit_averaged`` take. The coefficients are the hard window's as of the last solve, so a coarse ``solve_every`` reports a hard window that has since moved on. **Target gaps.** Target ``j`` keeps its mean ``ybar_j``, the column means ``m_j`` and the centered cross-moments ``c_j``, the exponentially weighted mean of ``(x - m_j)(y_j - ybar_j)``, over the rows it is present on. Its slopes solve ``(C + ridge * I) beta = c_j``, with intercept ``ybar_j - m_j . beta``. ``target_gaps`` decides which rows the feature covariance ``C`` is taken over. """ model: dict[str, Any] = { "type": "ewridge", "ridge": ridge, # `{}` is written as `[]`, which the Rust side refuses by name, as it # refuses a dict spec's `[]`: read as `None` it was no sets, in # silence (review 2026-10-06, YA5). "feature_sets": ( [[k, list(v)] for k, v in feature_sets.items()] if feature_sets is not None else None ), "standardize": standardize, "ridge_scale": ridge_scale, "coef_prior": coef_prior, "session_shrink": session_shrink, "long_half_life": long_half_life, "solve_every": solve_every, "max_rows_between_solves": max_rows_between_solves, "gram_block_rows": gram_block_rows, "gram_threads": gram_threads, "target_gaps": target_gaps, "window_size": window_size, "closed": closed, "snapshot_every": snapshot_every, "max_rows_between_snapshots": max_rows_between_snapshots, "window_budget": window_budget, } # Written only when given, as the Rust spec skips it when absent. if gram_threads is None: del model["gram_threads"] if ridge_scale not in ("mean", "sum"): raise ValueError( words_refusal(f"spec {quoted(name)}", "ridge_scale", ridge_scale, ("mean", "sum")) ) return _common(name, model, targets=targets, features=features, **common)
def _numeric_keys() -> frozenset[str]: """Every parameter, across the builders, whose annotation admits a float. Every builder in ``__all__``: a list kept by hand named sixteen of twenty-one, and a float of the other five -- ``bocpd``'s ``hazard``, say -- came back from a state file as the string ``"inf"`` (review 2026-09-12, D8).""" keys = set() helpers = {"output_fields", "output_index", "coef_fields", "coef_index"} builders = [globals()[name] for name in __all__ if name not in helpers] for fn in (_common, *builders): for key, hint in typing.get_type_hints(getattr(fn, "__wrapped__", fn)).items(): leaves = {hint, *typing.get_args(hint)} leaves |= {a for h in list(leaves) for a in typing.get_args(h)} leaves |= {a for h in list(leaves) for a in typing.get_args(h)} if float in leaves: keys.add(key) return frozenset(keys) def _clock_keys() -> frozenset[str]: """Every parameter, across the builders, whose annotation admits a duration: the clock parameters, where a raw dict may hold an expression or a ``timedelta`` as a builder takes one (:func:`_json`).""" helpers = {"output_fields", "output_index", "coef_fields", "coef_index"} builders = [globals()[name] for name in __all__ if name not in helpers] return frozenset( key for fn in (_common, *builders) for key, hint in typing.get_type_hints(getattr(fn, "__wrapped__", fn)).items() if _takes_duration(hint) )
[docs] @_checked def rls( name: str, *, targets: TargetList, features: list[str], delta: float | None = None, coef_prior: list[list[float]] | None = None, **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Recursive least squares, which solves the ridge fit exactly on every row. Use it where every row's prediction must come from coefficients solved through the row before it, with a prior that fades as rows arrive. Use :func:`ewridge` for a long stream whose features can hold one value for a long time, which winds this fit up (*Wind-up* in Notes), and :func:`huber` with ``ridge_scale="sum"`` for this fit under a Huber loss. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight``, ``group`` and the diagnostics, are in :mod:`rheon.spec`. This model's own: ``delta`` The prior's strength: the fit starts from ``A_0 = delta * I``, which is ``P_0 = I / delta`` in the classic RLS notation. In the units of ``A``, a decayed sum of ``w * z z'``: the features' squared units, summed over rows. Default 1.0, which weighs the prior about as much as one row whose features are of unit scale. It is :func:`ewridge`'s ``ridge`` under ``ridge_scale = "sum"``, not under its default: it penalizes the intercept too, and it fades as rows arrive. Finite and above 0. ``ridge`` is refused here, with a message naming ``delta``. ``coef_prior`` The coefficients the fit starts from and is shrunk toward, one vector per target in the features' original units, ``len(features) + 1`` long when there is an intercept. Default none, which starts from zeros. Refused with the wrong number of vectors, a vector of the wrong length, or a value that is not finite. ``min_weight`` is checked against the weight of the rows the model learned (those with every target present), decayed, so rows with a null target do not warm up a fit they never reached. ``weight_sum`` counts every row. The factor ``R`` of *The update* is shared between the targets, so a row with any null target is predicted for every target and learned for none. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields. `docs/OUTPUTS.md#rls <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#rls>`_ gives each field's type and when it is null: ``pred_<t>``, ``resid_<t>`` Per target: the prediction, and ``y - pred`` where the target is not null. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's predictions were withheld, null where they were not. ``coef`` Per target, the intercept (unless ``fit_intercept=False``) then one entry per feature (:func:`coef_index`). plus the fields of the diagnostics switched on, as :mod:`rheon.spec` describes them. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for a ``delta`` not finite or not above 0, and a ``coef_prior`` with the wrong number of vectors, a vector of the wrong length, or a value that is not finite. ``TypeError`` for ``ridge``, which this model calls ``delta``. .. rubric:: The update Per row, ``w`` is the row's weight, ``λ = 0.5 ** (Δclock / half_life)`` its decay (``lam ** Δclock`` under ``lam``), and ``z`` the features with the intercept in front. ``beta0_j`` is target ``j``'s ``coef_prior``, 0 without one: .. code-block:: text A <- λ * A + w * z z' b_j <- λ * b_j + w * y_j * z beta_j = A^-1 b_j A_0 = delta * I b_0j = delta * beta0_j The model keeps the factor ``R`` of ``A = R'R`` and ``u_j = R^-T b_j``, not ``A`` itself: a row is folded in by Givens rotations, and ``beta`` is read off by one back-substitution (the square-root form). ``Δclock`` is the clock's step since the last row the model did not skip, capped at ``gap_cap``, or ``session_gap`` at a session change. .. rubric:: Example This code fits a plane with an intercept of 1 and slopes of 2 and -0.5, with no decay, and prints the coefficients found: .. code-block:: python import numpy as np rng = np.random.default_rng(2) x0, x1 = rng.standard_normal(2_000), rng.standard_normal(2_000) y = 1.0 + 2.0 * x0 - 0.5 * x1 + 0.3 * rng.standard_normal(2_000) pl.DataFrame({"x0": x0, "x1": x1, "y": y}).write_parquet("plane.parquet") rls = rp.spec.rls( "rls", targets=["y"], features=["x0", "x1"], half_life=float("inf"), delta=1e-3, # a weak prior, which the rows outweigh ) bank = rp.ModelBank([rls]) bank.fit(pl.scan_parquet("plane.parquet")) # learn every row, keep no output print("planted: intercept 1.00, x0 2.00, x1 -0.50") for r in bank.coef().iter_rows(named=True): print(f"{r['term']}: {r['coef']:.2f}") .. code-block:: text planted: intercept 1.00, x0 2.00, x1 -0.50 intercept: 1.02 x0: 2.00 x1: -0.50 .. rubric:: See also - :func:`ewridge`, the same fit under ``ridge_scale="sum"``, solved on a schedule, whose default ``ridge`` does not wind up. - :func:`huber`, with ``ridge_scale="sum"``, this fit with each row down-weighted by its residual. - :func:`kalman`, for coefficients that drift as a random walk. .. rubric:: Notes **The square-root form.** In the textbook recursion on the inverse ``P``, rounding makes ``P`` asymmetric, and the recursion multiplies the asymmetry by the inverse of the row's decay factor each row. One extreme row can also cancel a direction of ``P`` to zero, which freezes that coefficient for good. The square-root form has neither failure. Its result is :func:`ewridge` under ``ridge_scale = "sum"`` solved on every row, to better than 1e-9. **Wind-up.** A feature that holds one value for a long time winds the fit up, so use :func:`ewridge` for a long stream whose features can go quiet. The prior fades with the sums, so nothing holds a coefficient in a direction the data stop exciting. A feature held at a value ``c`` other than 0 shows the fit only ``intercept + c * slope``. The information that tells the slope from the intercept then decays with every row, with nothing to renew it. Once it is under a rounding step, rounding sets the slope, and the slope wanders. A feature constant from its first row winds up the same way. Held at exactly 0, it excites nothing in that direction, and the slope stays where it was. :func:`ewridge`'s default ``ridge`` is a penalty on the means that never fades, and it centers each feature, so it does not wind up. Measured with ``half_life=20`` (a row a clock unit), ``delta=1`` and noise 0.17, on a feature held for 150 half-lives after 300 rows of moving, then moving again for 200 rows (10 half-lives). The fit held for some 30 half-lives in every case measured: .. list-table:: :header-rows: 1 * - the run - the slope while held (0.5 in the data) - it first passes 1 - ``pred - y`` once it moves: rms / worst * - ``rls``, held at 0.87 - -3.1e13 to 3.0e13 - 54 half-lives in - 3.1e11 / 4.4e12 * - ``rls``, held at 1,000 - -8.3e9 to 8.1e9 - 43 - 8.3e7 / 1.2e9 * - ``rls``, held at 1e8 - -4.6e5 to 4.5e5 - 62 - 4.6e3 / 6.5e4 * - ``rls``, constant at 0.37 from the first row - -3.0e13 to 3.1e13 - 50 - 7.0e11 / 9.9e12 * - ``rls``, constant at 1,000 from the first row - - 59 - * - ``rls``, constant at 1e8 from the first row - - 76 - * - ``rls``, held at 0 - 0.41 to 0.53 - never - 0.20 / 0.74 * - ``ewridge`` (``ridge=1e-6``, solved every row), any of these - 0 to 0.51 - never - 0.19 to 0.20 / 0.37 to 0.74 """ model: dict[str, Any] = {"type": "rls", "delta": delta, "coef_prior": coef_prior} return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def lasso( name: str, *, targets: TargetList, features: list[str], penalties: list[float], l1_ratio: float | None = None, select_half_life: float | Duration | None = None, solve_every: float | Duration | None = None, max_rows_between_solves: int | None = None, window_size: float | Duration | None = None, closed: Literal["right", "both"] = "right", snapshot_every: float | Duration | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal["thin", "refuse"], float] | None = None, max_iter: int | None = None, tol: float | None = None, target_gaps: Literal["own_rows", "pairwise"] = "own_rows", **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """A lasso or elastic-net path on running sums, with the penalty chosen as the stream runs. Use it for a sparse fit, where some features should get a coefficient of exactly zero: every penalty of the path is predicted, and ``penalty_selected_<t>`` names the one with the lowest exponentially weighted out-of-sample squared error so far, at no extra solve. Use :func:`ewridge` for a dense fit, and :func:`ftrl` for a sparse logistic fit of a 0/1 target. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight``, ``group`` and the diagnostics, are in :mod:`rheon.spec`. This model's own: ``penalties`` The penalties of the path, strictly decreasing, each finite and at least 0. Required, and not empty. Each penalty is a grid point, with a prediction of its own, reported as ``pred_<t>__p<penalty>``, such as ``pred_y__p0.1``. A list of one value is no grid, and its fields take no suffix. The L1 part of a penalty is in the target's units, and the ridge part has none (*Units* in Notes). ``l1_ratio`` The share of the penalty that is L1, in ``[0, 1]``. Default 1, the lasso. Below 1 the fit is an elastic net. ``select_half_life`` The half-life of the exponentially weighted squared out-of-sample error each grid point is ranked by, in clock units, above 0. Default: the model's half-life, so the choice forgets at the pace the fit does. ``inf`` ranks on the weighted mean of every error counted so far (inside the hard window under one). ``penalty_selected_<t>`` is reported as it stood before the row: the grid point the errors of the rows before it chose, not the one its own error then chose. Before the first row a target's errors count on (*The selection* in Notes), ``penalty_selected_<t>`` is the last grid point, and a tie between grid points keeps the first in ``penalties`` order. ``solve_every``, ``max_rows_between_solves`` The solve schedule, as for :func:`ewridge`. A target's first solve falls on the row it reaches a row of positive weight per coefficient, ``k + 1`` rows for ``k`` features with an intercept and ``k`` without, whatever ``min_weight`` says, where the schedule has not solved it sooner. ``window_size``, ``closed`` A hard window on the rows the path is fitted from, in clock units, as for :func:`ewridge`: a row ``window_size`` old or older is not in the running sums, and ``closed="both"`` keeps the one exactly that old. The selection's errors are cut at the hard window with the sums, so the penalty chosen is the one that fits the hard window, not rows the fit has dropped. So a hard window can change which coefficients are zero, not only their values: a feature with no evidence inside it goes to exactly zero. ``weight_sum``, ``sigma`` and ``zscore`` are the hard window's too. ``snapshot_every``, ``max_rows_between_snapshots``, ``window_budget`` As for :func:`ewridge`: ``snapshot_every`` spaces the hard window's snapshots on the clock, in clock units, ``max_rows_between_snapshots`` caps the rows between them, whichever comes first, and ``window_budget`` bounds each ring in MiB and thins or refuses past the bound. Each is refused without ``window_size``. ``max_iter``, ``tol`` Within a solve, the descent stops after ``max_iter`` sweeps (default 100, at least 1), or after a sweep that moved no coefficient ``b_i`` of *The update* by ``tol`` times the larger of ``s_y`` and the largest ``|c_i|``, or moved none at all. ``tol`` defaults to ``1e-10``, and is finite and above 0. ``s_y`` is the target's spread over the rows the fit reads: its standard deviation, or its root mean square without an intercept, where the fit is not centered. A descent that runs out of sweeps first is counted in :meth:`rheon.polars.ModelBank.solve_failures`, one per target and grid point, unless the rows behind its Gram are too few for the features to settle in ``max_iter`` sweeps on any data (*The descent* in Notes). ``target_gaps`` Which rows a target's feature correlations are taken over where the target is null on some: ``"own_rows"``, the default, or ``"pairwise"``, as for :func:`ewridge`. The cross-correlations are centered at the target's own means either way. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields. `docs/OUTPUTS.md#lasso <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#lasso>`_ gives each field's type and when it is null: ``pred_<t>``, ``resid_<t>`` Per target: the prediction, and ``y - pred`` where the target is not null. Under two or more ``penalties``, one per grid point, suffixed as ``pred_<t>__p<penalty>``. ``penalty_selected_<t>`` Per target, the penalty of the grid point in force before the row, such as ``0.01``: the one with the lowest exponentially weighted out-of-sample error. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's predictions were withheld, null where they were not. ``coef`` Per target and grid point, the intercept (unless ``fit_intercept=False``) then one entry per feature (:func:`coef_index`). plus the fields of the diagnostics switched on, as :mod:`rheon.spec` describes them. ``weight_sum``, ``coef`` and ``penalty_selected_<t>`` take no suffix for the grid point. :meth:`rheon.polars.ModelBank.gram` returns the sums behind the path, as for :func:`ewridge`. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for: - a ``penalties`` that is empty, not strictly decreasing, or holds a value below 0 or not finite; - an ``l1_ratio`` outside ``[0, 1]``; - a ``select_half_life`` not above 0, and a ``tol`` not finite or not above 0; - a ``max_iter`` below 1, a ``solve_every`` below 0, and a ``max_rows_between_solves`` or ``max_rows_between_snapshots`` below 1; - a ``target_gaps`` other than ``"own_rows"`` or ``"pairwise"``; - a ``window_size`` not finite or not above 0; a ``closed`` of ``"left"`` or ``"none"``; a ``snapshot_every`` below 0 or not finite; a ``window_budget`` that is not one key, ``"thin"`` or ``"refuse"``, or whose MiB is not above 0; and ``closed="both"``, ``snapshot_every``, ``max_rows_between_snapshots`` or ``window_budget`` without ``window_size``; - ``emit_error_inflation``, ``emit_influence``, ``emit_se_coef`` or ``emit_robust_se``, which need a leverage, a covariance or a least-squares fit that the lasso's chosen coefficients do not have. .. rubric:: The update The running sums are :func:`ewridge`'s. On the schedule, for each penalty ``l`` in ``penalties``, the model solves by coordinate descent on the standardized, centered sums (without an intercept, on the raw moments, each feature scaled by its root mean square, and no intercept is recovered). ``C`` is the features' correlation matrix, ``s_i`` feature ``i``'s standard deviation, ``c_i = cov(x_i, y) / s_i`` its covariance with the target over its standard deviation, and ``b_i = beta_i * s_i`` its coefficient in standardized units. Each sweep sets, for every ``i``: .. code-block:: text rho_i = c_i - sum_{j != i} C_ij b_j b_i = soft(rho_i, l * l1_ratio) / (C_ii + l * (1 - l1_ratio)) soft(v, t) = sign(v) * max(|v| - t, 0) then the coefficients are unscaled, ``beta_i = b_i / s_i``, with the intercept recovered as ``ybar - m . beta``, ``ybar`` the target's mean and ``m`` the features'. The descent starts the first grid point from the last solve's fit, and each later grid point from the one before it. .. rubric:: Example This code fits a target on four features, of which only ``x0`` and ``x1`` play a part, and prints the slopes at each penalty: .. code-block:: python import numpy as np rng = np.random.default_rng(6) x = rng.standard_normal((5_000, 4)) y = 2.0 * x[:, 0] - 1.0 * x[:, 1] + rng.standard_normal(5_000) frame = pl.DataFrame({f"x{i}": x[:, i] for i in range(4)} | {"y": y}) frame.write_parquet("sparse.parquet") las = rp.spec.lasso( "las", targets=["y"], features=["x0", "x1", "x2", "x3"], half_life=float("inf"), penalties=[0.1, 0.01], # decreasing; every point is predicted ) bank = rp.ModelBank([las]) bank.fit(pl.scan_parquet("sparse.parquet")) # learn every row, keep no output print("planted: x0 2, x1 -1, x2 0, x3 0") slopes = bank.coef().filter(pl.col("term") != "intercept") wide = slopes.pivot(on="term", index="penalty", values="coef") for r in wide.iter_rows(named=True): found = ", ".join(f"{t} {r[t]:.2f}" for t in ["x0", "x1", "x2", "x3"]) print(f"penalty {r['penalty']:g}: {found}") .. code-block:: text planted: x0 2, x1 -1, x2 0, x3 0 penalty 0.1: x0 1.87, x1 -0.90, x2 0.00, x3 0.00 penalty 0.01: x0 1.96, x1 -0.99, x2 -0.01, x3 -0.00 .. rubric:: See also - :func:`ewridge`, the running sums this model solves, under a ridge. - :func:`rheon.gram.lasso_path`, the same descent run offline on a Gram. - :func:`ftrl`, a sparse fit of a 0/1 target. .. rubric:: Notes **Units.** The target is centered but not scaled, so the threshold ``l * l1_ratio`` is in the target's units, while the ridge part ``l * (1 - l1_ratio)`` is added to a correlation and has none. So for a pure lasso, ``y`` and ``l`` scaled by 10 scale the predictions by 10 and zero the same coefficients. For an elastic net they do not. The standardized coefficients are in the target's units, so the stopping rule has none: for a pure lasso, ``y`` and ``penalties`` scaled by a power of two give the same fit scaled, to the bit, stopped on the same sweeps. **The selection.** A row of weight 0 adds no error: the errors keep their values and only their weight decays, so without a hard window the choice does not move, and under one it moves only as the hard window drops rows. A target's errors count once the fit holds a row of it per coefficient: ``k + 1`` rows of positive weight with an intercept, ``k`` without, inside the hard window under one. They count whatever ``min_weight`` says, which withholds the output alone: the selection scores the prediction on a row the gate withholds, so the penalty chosen, as the fit, is the same at any ``min_weight``, and one target's choice does not depend on another's threshold. **The descent.** :func:`rheon.gram.lasso_path` runs the same descent with ten times the sweeps by default, 1,000, because it starts its path from zero. A solve here starts its first grid point from the last solve's fit, which the rows since then have moved only a little once the moments stop moving much, and each later point from the one before it. On 15 features correlated at ``0.8 ** |i - j|``, solved on every row of 20,000 at seven penalties, 798 of the 140,000 descents ran out of their 100 sweeps; 1,000 sweeps left 44, at 1% more sweeps in all. A cyclic descent contracts the error along two columns of correlation ``rho`` by ``rho**2`` a sweep. That is about ``1 - 4 / kappa``, with ``kappa = (1 + rho) / (1 - rho)`` their correlation matrix's condition number, so each e-fold takes about ``kappa / 4`` sweeps. Where columns nearly repeat each other most descents can run out: on 800 rows of two columns 0.1 apart (``kappa`` near 400) at a penalty of 0.001, 798 of 799. A descent that runs out of sweeps while the rows are too few for the features is the fit's warm-up, and is not counted. A sweep shrinks the error by about ``1 - 2 * lmin``, ``lmin`` the smallest eigenvalue of the correlation matrix (with the penalty's ridge share added to its diagonal), so settling to ``tol`` takes about ``ln(1/tol) / (2 * lmin)`` sweeps. ``n`` independent rows of ``k`` features give at best ``lmin = (1 - sqrt(k / dof)) ** 2``, with ``dof`` the Kish size ``n`` less one for an intercept, and correlated features only less. Where that best case would not settle in ``max_iter`` sweeps, about 2.3 rows a feature at 100 sweeps and 1.25 at 1,000, the cap hit comes from the rows and says nothing about the data, so it is not counted; the fit is still where the descent stopped. Past it every cap hit is counted, as is every one under a decay whose Kish size stays below that bound (about ``(1 + lam) / (1 - lam)`` rows for ``lam`` the decay a row), or under a ``window_size`` whose window holds fewer rows than that bound once rows have aged out of it: no more rows would lift it, so the stream is never out of its warm-up. A ``max_iter`` below ``ln(1/tol) / 2``, about 12 sweeps, is counted always, since no number of rows would settle it. """ model: dict[str, Any] = { "type": "lasso", "penalties": penalties, "l1_ratio": l1_ratio, "select_half_life": select_half_life, "solve_every": solve_every, "max_rows_between_solves": max_rows_between_solves, "max_iter": max_iter, "tol": tol, "target_gaps": target_gaps, "window_size": window_size, "closed": closed, "snapshot_every": snapshot_every, "max_rows_between_snapshots": max_rows_between_snapshots, "window_budget": window_budget, } return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def kalman( name: str, *, targets: TargetList, features: list[str], coef_half_life: float | Duration | list[float | Duration] | None = None, q: list[float] | None = None, obs_var: float | None = None, p0: float | None = None, share_p: bool = False, revert_half_life: float | Duration | list[float | Duration] | None = None, standardize: bool = True, covariance_form: Literal["covariance", "square_root"] = "covariance", **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """A regression whose coefficients drift, tracked by a Kalman filter. Use it where a coefficient moves at a drift rate of its own, faster than one half-life for the whole fit can follow, or where a coefficient no row supports should be forgotten (``revert_half_life``). Use :func:`ewridge` for coefficients that hold still over a half-life, and :func:`rls` for an exact fit whose prior fades. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight``, ``group`` and the diagnostics, are in :mod:`rheon.spec`. Here ``half_life`` drives the standardization and the residual variance, not the coefficients' drift. This model's own: ``coef_half_life`` How fast a coefficient may drift, as a half-life in clock units, on standardized features: an observation ``D`` clock units after the target's last adds the process noise ``(ln 2 * D / h_i) ** 2`` times the noise ``R_j``, with ``h_i`` the coefficient's half-life. The half-life is the same whether rows come every unit or every hundredth, and whether the target is seen on every row or one in ten (*The drift* in Notes). It is each standardized direction's memory with the others held still, and a direction of correlated features is learned more slowly (*Correlated features* in Notes). A scalar, or one value per coefficient with the intercept first where there is one, each above 0. ``inf`` gives that coefficient no drift: the filter takes it as constant and goes on learning it from every row. Required unless ``q`` is given, and refused beside it. Under ``standardize`` the drift is per standard deviation of each feature as the moments stand: a slope's random walk in the caller's units has a variance of ``R_j * (ln 2 * D / h_i) ** 2 / s_i ** 2`` per observation, ``s_i`` the feature's standard deviation. The diagnostics' statistics read the fit's memory as the shortest finite entry (the model's ``half_life`` where every entry is ``inf``), and their readiness waits for the longer of the longest finite entry and ``half_life``. The CUSUM under ``emit_breaks`` reads the intercept's entry as the memory at which a level in the target is absorbed, and ``inf`` there leaves the CUSUM a plain sum. ``q`` The process noise given outright, ``q_i`` per coefficient, in place of the derivation from ``coef_half_life``, added as ``q_i * D ** 2`` on each row that observes the target. One value per coefficient, the intercept first where there is one, each finite and at least 0. Exactly one of ``q`` and ``coef_half_life`` is given. Its units are a coefficient's squared per clock unit squared. Under ``standardize`` a slope is in the target's units per standard deviation of its feature, so ``q_i`` is in the target's squared units per clock unit squared. Without it, a slope's ``q_i`` is in the target's units over the feature's, squared, per clock unit squared. The intercept's is the target's squared units per clock unit squared either way. ``q`` is measured against the noise estimate, ``q_i / R_j``, which is how the estimate reaches the gain under ``q`` (*The noise* in Notes). ``obs_var`` A fixed observation noise in place of the estimated one: the variance of the target about its prediction, in the target's squared units, finite and above 0. Default none, which estimates it as the exponentially weighted (EW) variance of the target's out-of-sample residuals. It scales ``se_coef``. Under ``coef_half_life`` the gain does not depend on its value, and under ``q`` it is the ``R_j`` that ``q`` is measured against. ``P`` is then absolute, and starts at ``p0 * obs_var`` on the intercept, and on each slope too where ``standardize=False``. Under ``standardize`` each slope's prior waits for its feature's scale (*The prior* in Notes). ``p0`` The prior variance of each slope, in units of the noise: a ratio, with no units under ``standardize``. Without ``standardize`` a slope's prior ``p0 * R`` carries its feature's units, so ``p0`` is in one over the feature's squared units there. Default 1.0, a prior as uncertain as one observation. Finite and above 0. From about 1e8 the default ``covariance_form`` loses digits; ``"square_root"`` keeps them (*The square root* in Notes). ``share_p`` Keep one ``P`` for every target, where by default each target has its own. Targets observed on the same rows would each carry the same ``P``, so one update of the ``n x n`` matrix a row then serves every target, ``n`` the number of coefficients. Every prediction is then the per-target filter's, to the bit, except under ``q``, which the shared ``P`` measures against the targets' mean noise. Default ``False``, so that each target's memory follows its own rows: where a target is null on rows another is present on, the shared ``P`` takes those rows too (*A shared P* in Notes). ``revert_half_life`` A reversion half-life ``kappa_i`` per coefficient, in clock units, above 0: between observations the coefficient shrinks toward zero by ``2 ** (-d / kappa_i)``, so the filter forgets a coefficient no row has supported for a while, where a random walk would carry it unchanged. Default ``inf``, the random walk, which adds nothing. A scalar applies to every coefficient, the intercept included. A list gives one per coefficient, intercept first, and ``[inf, h, h]`` leaves the intercept a random walk. Under ``standardize`` the pull is toward zero in the standardized coordinates: a slope toward "no effect", the intercept toward "the target averages zero". A reverting coefficient's uncertainty stays bounded across a run of rows that observe nothing (*Reversion* in Notes). ``standardize`` Run the filter on standardized features, so ``coef_half_life`` and ``p0`` mean the same thing whatever the columns' scale. Default ``True``. Each row is standardized against the EW means ``m_i`` and standard deviations ``s_i`` of the rows before it, ``z_i = (x_i - m_i) / s_i``. Without an intercept the features are scaled by their root mean square and not centered, as for :func:`ewridge`. The reported coefficients are in the original units either way, and the moments' changes move no prediction (*Standardizing* in Notes). With ``standardize=False``, ``q`` all zeros, no ``revert_half_life`` and a fixed ``obs_var``, the filter is exactly Bayesian linear regression. For a coefficient per current standard deviation, which moves with the scale, z-score the column in the query before the bank and give it with ``standardize = False``. `Scale a feature by its spread <https://github.com/rheon-dev/rheon/blob/main/docs/how-to/scale-a-feature-by-its-spread.md>`_ builds the column with :func:`rheon.polars.ewm_mean <rheon.polars.ops.ewm_mean>` and :func:`rheon.polars.ewm_std <rheon.polars.ops.ewm_std>`. ``covariance_form`` How the filter holds ``P``. ``"covariance"``, the default, holds ``P`` and updates it as ``P_j <- P_j - g z' P_j``, which subtracts two numbers of ``P``'s size to leave one of the posterior's, so it rounds at ``u * p0``, ``u`` the unit roundoff. ``"square_root"`` holds a triangular ``C`` with ``P = C C'`` and updates ``C``, which rounds at ``u * sqrt(p0)`` (*The square root* in Notes). Use it for a vague prior, ``p0`` of about 1e8 or more. It costs time on every row: 1.14 to 1.72 times the covariance form's with no drift, and 2.4 to 16 times under ``coef_half_life`` or ``q``, at 5 to 50 coefficients on arm64, since each row's drift then updates the factor once per coefficient. At ``p0 = 1`` the two agree to about 1e-9 of a prediction. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields. `docs/OUTPUTS.md#kalman <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#kalman>`_ gives each field's type and when it is null: ``pred_<t>``, ``resid_<t>`` Per target: the prediction, and ``y - pred`` where the target is not null. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's predictions were withheld, null where they were not. It reads a reason of the shared gates (:mod:`rheon.spec`), such as ``below_min_weight`` on the first rows under the default ``min_weight``. It reads ``below_warm_rows`` while no coefficient of the target has its prior set yet (*The prior* in Notes), as without an intercept before a feature's scale is usable. A target's first row has no prediction, since the model has learned nothing to predict from: with ``min_weight=0``, ``pred_<t>`` and ``withheld_reason`` both read null there. ``coef`` Per target, the intercept (unless ``fit_intercept=False``) then one entry per feature, in the original units, after the row is learned (:func:`coef_index`). plus the fields of the diagnostics switched on, as :mod:`rheon.spec` describes them. ``se_coef`` and ``error_inflation`` read the filter's own covariance, and are exact only under the model (*Standard errors* in Notes). .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for: - neither or both of ``coef_half_life`` and ``q``; - a ``coef_half_life`` or ``revert_half_life`` whose list is neither one value nor one per coefficient, or with a value not above 0; - a ``q`` whose list is not one value per coefficient, or with a value below 0 or not finite; - an ``obs_var`` or ``p0`` not finite or not above 0; - ``emit_robust_se``: the filter's covariance is its own posterior, which ``emit_se_coef`` reports. .. rubric:: The update Per target ``j``, per row, ``d`` is the row's clock step, the clock's step since the last row the model did not skip, capped at ``gap_cap`` (or ``session_gap`` at a session change). ``w`` is the row's weight, ``z`` its standardized features with the intercept in front, ``y_j`` the target, ``b_j`` the coefficients and ``kappa_i`` the ``revert_half_life``: .. code-block:: text b_j <- Phi b_j Phi = diag(2 ** (-d / kappa_i)) the reversion P_j <- Phi P_j Phi every row D_j <- D_j + d the clock since P_j's last observation P_j <- P_j + Q * D_j ** 2, D_j <- 0 the drift, on a row that observes y_j v = z' P_j z + 1 / w the innovation's variance g = P_j z / v the gain b_j <- b_j + g (y_j - z' b_j) P_j <- P_j - g z' P_j ``P_j`` is the coefficients' covariance in units of the observation noise ``R_j``, so the covariance itself is ``R_j * P_j``. ``Q`` is the process noise in the same units, ``(ln 2 / h_i) ** 2`` from ``coef_half_life`` or ``q_i / R_j`` from ``q``. ``R_j`` is the target's EW residual variance, or ``obs_var``. Under ``obs_var`` the filter runs on the covariance itself: ``P_j`` and ``Q`` are ``R_j`` times the above, and ``v`` is ``z' P_j z + R_j / w``. A reverting coefficient's drift over a gap ``D`` is ``Q_i * r_i(D) ** 2`` in place of ``Q_i * D ** 2``, with ``r_i(D) = (1 - 2 ** (-D / kappa_i)) / theta_i`` and ``theta_i = ln 2 / kappa_i``. .. rubric:: Example This code fits a slope that steps from 1 to 3 at row 2,000, and prints the slope the filter found just before the step, 10 rows after it and 100 rows after it: .. code-block:: python import numpy as np rng = np.random.default_rng(3) x = rng.standard_normal(4_000) slope = np.where(np.arange(4_000) < 2_000, 1.0, 3.0) # the true slope y = slope * x + 0.2 * rng.standard_normal(4_000) pl.DataFrame({"x": x, "y": y}).write_parquet("step.parquet") k = rp.spec.kalman( "k", targets=["y"], features=["x"], half_life=200.0, coef_half_life=20.0, # how fast a coefficient may drift, in rows coef_every=0, # write coef on every row ) out = pl.scan_parquet("step.parquet").rheon.fit_predict([k]).collect() coef = out["k"].struct.field("coef") for row in (1_999, 2_010, 2_100): print(f"row {row}: true slope {slope[row]:.0f}, found {coef[row][1]:.2f}") .. code-block:: text row 1999: true slope 1, found 0.96 row 2010: true slope 3, found 1.55 row 2100: true slope 3, found 2.95 .. rubric:: See also - :func:`ewridge`, for coefficients that hold still over a half-life. - :func:`rls`, the fit this filter gives with no drift, a fixed noise, ``standardize=False``, no ``revert_half_life`` and ``half_life=inf``, at ``delta = 1 / p0``. - :meth:`rheon.polars.ModelBank.predict`, which moves the coefficients by ``Phi`` over the clock since the last learned row. .. rubric:: Notes **The noise.** ``R_j`` is per target, and its weight ages on every row, a row with no prediction or with weight 0 included. It learns from the filter's own prediction on every row the filter predicts, whether or not ``min_weight`` lets that prediction out. ``min_weight`` withholds the output alone, so the fit, the variance and a ``q`` read against it are the same at any ``min_weight``. A row with no prediction, before the filter has sized the target's coefficients, still moves them and adds to the target's weight. Only the residual variance learns nothing from it. A row of weight 0, or one whose target is null, ages the target's weight and learns nothing for it. Under ``coef_half_life`` the noise is a scale, not a weight: the gain never reads the noise estimate. The model's noise is one constant per target. The prior (``p0`` times it) and the drift (``(ln 2 * D / h) ** 2`` times it) are multiples of it, so it cancels from the gain. The estimate scales only ``se_coef``: ``error_inflation`` and its gate read ``P`` in units of the noise, and wait only until the target has a residual variance. Under ``q`` the estimate reaches the gain only through ``q_i / R_j``. A filter with the estimate inside the gain weighs each row by the inverse of the noise as it stood before the row, so a burst of large residuals inflates it and the rows after count for less than the burst did. In a run of that filter with no drift, a fifth of the first 500 rows 50 too high held the slopes at ``[-25.5, 33.6]``, where least squares on the same rows gives ``[4.1, -1.4]``. The residual variance starts at the target's first prediction. Under ``q``, before a target's first residual the row's own squared innovation stands in for the noise, and a row whose innovation is exactly 0 adds no drift. Scaling a target by ``c`` scales its predictions by ``c``, at any ``p0``, when ``obs_var`` and ``q``, where given, are scaled by ``c ** 2``. **States saved with the estimate in the gain.** A state saved by a release that put the noise estimate inside the gain goes on as it was fitted, with the estimate in the gain. **The drift.** The drift is charged once, on the row that next observes the target, for the whole clock since the last one (``D_j``, or under ``share_p`` since any target's row), because ``Q * D ** 2`` is not additive over a split gap. Charged per row, a row of weight 0 inside a gap would shrink the gap's noise and move every later prediction, by 0.197 in the target's units at ``coef_half_life = 20``. And a target seen on one row in 10 would forget 3.6 times slower on the clock than one seen on every row: 270 clock units against 75, measured at the same ``coef_half_life``. The noise ``(ln 2 * D / h_i) ** 2`` matches the steady-state gain of recursive least squares under a half-life ``h_i`` (:func:`rls`) to first order in ``D / h_i``: within 1% for observations closer than half a half-life, and within 4% at one. **Correlated features.** Under correlated features, a direction of the design's correlation with eigenvalue ``lambda`` is learned with a memory of about ``h / sqrt(lambda)`` (Ljung and Gunnarsson 1990), where recursive least squares under a half-life forgets every direction at ``h``. At a correlation of 0.9 and ``h = 50`` the memories measured 37.5 and 160.5 clock units, against 36.3 and 158.1 predicted. Under ``coef_half_life`` the gain reads no noise estimate, so a step in the truth is learned at that memory however much it inflates the residual variance. **The prior.** Without ``obs_var`` the intercept's prior is diffuse. The first row that observes the target fills the intercept with its whole innovation, ``b_0 = y - z' b``, at a variance of ``z' P z + 1 / w``. That is the limit of a prior that knows nothing of the level. So a level in the target moves every prediction by the level, to the rounding of a number of its size, from the first. It needs neither ``p0`` nor a noise: with no process noise the filter is least squares with the ridge ``1 / p0`` on each slope and none on the intercept, the noise's estimate playing no part. Unstandardized, each slope's prior is ``p0`` from the start. Standardized, it is ``p0`` from the first row that observes the target on which its feature's scale is usable, and until then the slope is 0 and takes no correction. While no coefficient is sized the target is not predicted, and with an intercept every row after the first has one sized. With ``obs_var`` given, unstandardized and with no process noise, the filter is the ridge regression with penalty ``1 / p0``. A covariance whose diagonal goes below 0 is sized again at ``p0``. **The square root.** Under ``covariance_form="square_root"`` the filter holds ``C``, upper triangular with ``P_j = C C'``. A row with ``f = C' z``, ``a_0 = 1 / w`` (``R_j / w`` under ``obs_var``) and ``a_j = a_(j-1) + f_j ** 2`` updates each column ``C_j`` of ``C`` in turn (Carlson 1973), to the factor of the posterior, with nothing subtracted at ``P``'s size: .. code-block:: text C_j <- sqrt(a_(j-1) / a_j) C_j - f_j / sqrt(a_(j-1) a_j) * sum_(i<j) C_i f_i The drift, a slope's prior and the reversion each update ``C`` by plane rotations. Against the posterior solved directly, on 300 rows of three features with unlike means and scales, unstandardized and with no drift: at ``p0 = 1e12`` the covariance form was 6.7e-5 off in a coefficient and the square root 1.0e-13; at 1e15, 1.3e-2 against 9.6e-14. Through the bank, the square root's predictions at ``p0`` of 1e8, 1e10 and 1e12 came within 2.4e-9, 2.4e-11 and 2.4e-13 of those at 1e14, the ``1 / p0`` the prior's own weight moves them by; the covariance form's stayed up to 0.19 apart at every one. **Standardizing.** The filter's state is held in the coordinates of an *anchor*, the moments at its last re-map, and maps the process noise and the priors, defined in the moments as they stand, into them exactly. When the moments drift from the anchor (a scale by more than twice or less than half, a mean by more than the anchor's scale), the state follows them to their new coordinates, ``b <- A b`` and ``P <- A P A'``: .. code-block:: text A_00 = 1, A_0i = (m_i - m^a_i) / s^a_i, A_ii = s_i / s^a_i with ``m^a``, ``s^a`` the anchor and ``m``, ``s`` the moments after the row. So a change in the moments moves no prediction, no predictive variance and no coefficient in the original units, from the first row. A feature reaches the filter only through its standardized value ``z``, so features scaled by a power of two predict the same to the bit. A filter read through the moments as they stand, the alternative, lets a finite half-life's own wander in the moments move every prediction. It was measured on ``y = 2 x + e`` with one feature ``x ~ N(0, 1)``, R² 0.99998, 30,000 rows and both half-lives 50. Over rows 10,000 to 30,000 its out-of-sample error stood 223 noise variances above the noise (the median of seeds 0 to 4, which ranged from 212 to 244). This filter stands 0.014 above it there, as the unstandardized one does. The anchor gives the same filter, to rounding, as a re-map on every row, and is a fifth cheaper a row at ten features (221 against 277 nanoseconds). A re-map past what a stretch of data makes (a scale by more than 1024 times either way, or a mean by more than 1024 of the anchor's scale) is not followed, and the state is read in the new coordinates. **Reversion.** A reverting coefficient's drift ``Q_i * r_i(D) ** 2`` is ``Q_i * D ** 2`` for a gap well under ``kappa_i``, and never more than ``Q_i / theta_i ** 2``. At observations one clock unit apart it is short of ``Q_i`` by about ``ln 2 / kappa_i`` of it. At observations ``D`` apart, a reverting coefficient reaches the stationary prior variance ``Q_i * r_i(D) ** 2 / (1 - phi_i ** 2)`` with ``phi_i = 2 ** (-D / kappa_i)``, a stationary AR(1) instead of an unbounded walk. The reversion runs on every row, a row that observes nothing included, being the same over a gap however it is cut. A prediction propagates the state by the same ``Phi`` over the row's clock gap. :meth:`rheon.polars.ModelBank.predict` moves the coefficients by ``Phi`` over the clock distance from the last learned row, capped by ``gap_cap``. So however far past the data, a coefficient has shrunk by ``2 ** (-gap_cap / kappa_i)`` at most, and the prediction is the intercept alone only where ``gap_cap`` spans several of the slopes' reversion half-lives and the intercept's is ``inf``. **A shared P.** ``P``'s recursion reads neither the targets nor the noise, since it is held in units of the noise. Every target observed on a row takes its gain from ``P`` as the row finds it, and ``P`` takes the row once, so the order of the targets moves no prediction. Where a target is null on rows another is present on, that target's memory follows the others' rows. A target first seen after the others has its intercept filled by its first innovation, as the diffuse prior fills each target's. Under ``q`` the shared ``P`` measures it against the mean noise over the targets that have one. A target's ``se_coef`` reads ``P`` times its own noise. **Standard errors.** ``se_coef`` reads the filter's own covariance ``R_j * P_j``, and ``error_inflation`` is ``sqrt(1 + z' P⁻ z)``, with ``P⁻`` the covariance in units of the noise that the row's update starts from, after the reversion and the drift. Both are exact *under the model*, which says the coefficients walk at the noise ``coef_half_life`` implies. On a truth that does not move, that walk is variance the coefficients do not have. The standard errors then come out about ``sqrt(2)`` too large: a mean squared error over ``se_coef ** 2`` of 0.47 to 0.50 at ``coef_half_life`` 50 and 200, against 0.95 to 1.06 on a walk of the implied variance. And with ``R`` the EW variance of the out-of-sample residuals, which already carry the estimation error, ``error_inflation`` counts that error twice: the mean squared error over ``R * error_inflation ** 2`` is 0.96 at ``coef_half_life`` 50. """ model: dict[str, Any] = { "type": "kalman", "coef_half_life": coef_half_life, "q": q, "obs_var": obs_var, "p0": p0, "share_p": share_p, "revert_half_life": revert_half_life, "standardize": standardize, "covariance_form": covariance_form, } words = ("covariance", "square_root") if covariance_form not in words: raise ValueError( words_refusal(f"spec {quoted(name)}", "covariance_form", covariance_form, words) ) # Written only where it is not the default, as the Rust spec skips it there. if covariance_form == "covariance": del model["covariance_form"] return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def ftrl( name: str, *, targets: TargetList, features: list[str], alpha: float | None = None, beta: float | None = None, l1: float | None = None, l2: float | None = None, strict_binary: bool = False, loss: Literal["logistic", "squared"] = "logistic", **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Logistic regression for a 0/1 target, or a sparse linear regression, by FTRL-proximal. Use it for a 0/1 target, or where an L1 penalty should zero the coefficients of features with too little evidence: it is McMahan et al.'s (2013) algorithm, the standard for click prediction, with a learning rate per coefficient. Use :func:`lasso` for an L1 penalty on the mean scale, which more rows or heavier ones do not outweigh, and :func:`sgd` for other losses. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight``, ``group`` and the diagnostics, are in :mod:`rheon.spec`. None of ``alpha``, ``beta``, ``l1`` and ``l2`` is free of units (*Units* in Notes). This model's own: ``alpha`` The learning-rate scale, in a coefficient's units: the target (log-odds, under the logistic loss) per unit of the feature. Default 0.1, which keeps a coefficient's first step under 0.1 in its units. Finite and above 0. A larger ``alpha`` follows a break sooner, and moves more from row to row once the fit has reached its steady state (*Breaks* in Notes). ``beta`` The learning rate's smoothing, which keeps the first steps from being too large, in a gradient's units: the target times the feature. Default 1.0, the value McMahan et al. suggest. Finite and at least 0. ``l1`` The L1 penalty, which zeroes a coefficient whose summed evidence is below it, in the summed gradient's units. Default 0.0, no L1 penalty. Finite and at least 0. It weighs against the rows' summed evidence, not a mean (*Weights and the penalties* in Notes). ``l2`` The L2 penalty, which shrinks every coefficient toward zero as a ridge does, in the feature's squared units. Default 1.0, which adds a tenth to the default prior's ``beta / alpha`` of 10. Finite and at least 0. ``strict_binary`` Under ``loss = "logistic"``, make a call that reads the target (a call that learns, or ``predict``) refuse a chunk whose target is not 0 or 1, naming the row, before any model learns from it. Default ``False``: such a target is clamped into ``[0, 1]``. Refused beside ``"squared"``, which reads the target as it stands. ``loss`` ``"logistic"`` (the default) for a 0/1 target: ``pred`` is a probability. ``"squared"`` for a continuous target: ``pred`` is the linear prediction, and the model is a sparse linear regression with no solves and the L1 support :func:`ewridge` does not have. The two differ in the link, and in how the target is read: ``"logistic"`` clamps it into ``[0, 1]``, takes ``strict_binary`` and refuses a formula target. The gradient is ``(p - y) * z`` either way. ``min_weight`` counts the rows the target was present on, at their weights, decayed, where ``weight_sum`` counts every row. So rows with a null target do not warm up coefficients they never moved, and neither does a row the model does not learn from because its squared gradient would overflow. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields. `docs/OUTPUTS.md#ftrl <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#ftrl>`_ gives each field's type and when it is null: ``pred_<t>``, ``resid_<t>`` Per target: the prediction, a probability under ``"logistic"``, and ``y - pred`` where the target is not null. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's predictions were withheld, null where they were not: a reason of the shared gates (:mod:`rheon.spec`), such as ``below_min_weight`` on the first rows under the default ``min_weight``. ``coef`` Per target, the intercept (unless ``fit_intercept=False``) then one entry per feature, after the row is learned (:func:`coef_index`). plus the fields of the diagnostics switched on, as :mod:`rheon.spec` describes them. Under ``"logistic"``, ``emit_metrics`` reads the fit as probabilities against the 0/1 targets, in its own fields: ``hit_rate_<slot>`` is the accuracy at 0.5, ``r2_<slot>`` the Brier skill score and ``ic_<slot>`` the point-biserial correlation. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for: - a ``loss`` other than ``"logistic"`` or ``"squared"``; - an ``alpha`` not finite or not above 0, and a ``beta``, ``l1`` or ``l2`` not finite or below 0; - ``strict_binary`` beside ``"squared"``; - under ``"logistic"``, a formula target: the model fits a probability to a 0/1 target. And, from a call that learns or ``predict``, ``ValueError`` for a chunk with a target other than 0 or 1 under ``strict_binary``, naming the row. .. rubric:: The update Here ``z`` is the row's features, with the intercept's 1 under ``fit_intercept``, ``w`` its weight, ``y`` the target, and ``zz``, ``n`` and ``d`` the sums kept per coefficient ``i``. ``λ = 0.5 ** (Δclock / half_life)`` (``lam ** Δclock`` under ``lam``) is the decay since the last row the target was learned from, ``Δclock`` the clock's step since then, each step capped at ``gap_cap`` (or ``session_gap`` at a session change): .. code-block:: text b_i = 0 if |zz_i| <= l1 else -(zz_i - sign(zz_i) l1) / (r_i + l2) r_i = beta / alpha + d_i (under a half-life) = (beta + sqrt(n_i)) / alpha (without one: river's closed form) p = sigmoid(z . b) (z . b itself under loss="squared") n_i <- λ * n_i ; zz_i <- λ * zz_i ; d_i <- λ * d_i (on a row the target is learned from) g_i = (p - y) * z_i * w s_i = (sqrt(n_i + g_i^2) - sqrt(n_i)) / alpha zz_i += g_i - s_i * b_i ; n_i += g_i^2 ; d_i += s_i ``b`` holds the coefficients, ``p`` is the prediction made before the row is learned, and ``r_i`` is coefficient ``i``'s rate. .. rubric:: Example This code fits a logistic regression to 0/1 targets drawn with an intercept of 0.5, a slope of 1.5 on ``x0`` and none on ``x1``, and prints the coefficients found. The L1 penalty zeroes ``x1``'s: .. code-block:: python import numpy as np rng = np.random.default_rng(4) x0, x1 = rng.standard_normal(20_000), rng.standard_normal(20_000) p = 1.0 / (1.0 + np.exp(-(0.5 + 1.5 * x0))) # x1 plays no part y = (rng.random(20_000) < p).astype(float) pl.DataFrame({"x0": x0, "x1": x1, "y": y}).write_parquet("clicks.parquet") click = rp.spec.ftrl( "click", targets=["y"], features=["x0", "x1"], half_life=float("inf"), l1=50.0, # zeroes a coefficient whose evidence is below it ) bank = rp.ModelBank([click]) bank.fit(pl.scan_parquet("clicks.parquet")) # learn every row, keep no output coef = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)} print(f"intercept {coef['intercept']:.2f}, x0 {coef['x0']:.2f}") print(f"x1 is exactly 0: {coef['x1'] == 0.0}") .. code-block:: text intercept 0.49, x0 1.52 x1 is exactly 0: True .. rubric:: See also - :func:`lasso`, an L1 penalty on the mean scale, solved on running sums. - :func:`sgd`, gradient steps under other losses. .. rubric:: Notes **Under a half-life.** The sums decay on the model's clock like every other model's. The fit after a row the target is learned from minimizes FTRL's objective. That is a fixed regularizer, ``l1 |b|_1 + (beta / alpha + l2) |b|^2 / 2``, against the rows' linearized losses and proximal terms, each weighted by its age on the clock. So old evidence counts for less against the prior. In steady state the penalties act as a mean-scale ridge of ``(1 - f) * (beta / alpha + l2)``, ``f`` the decay factor over one row's clock. Under ``loss="squared"`` at the default ``alpha``, ``beta`` and ``l2``, one row a clock unit, a constant 5 is fitted at 4.65 at ``half_life = 100`` and 4.96 at 1000. Without a half-life the fit is the ``FTRLProximal`` of the Python library river, to 1e-12 row for row. **Breaks.** Under a half-life the fit follows a break at the pace of its steps, not of its half-life. A coefficient steps by its gradient over the root of its recent squared gradients. Once those sums hold the break's large gradients, a coefficient closes on the break at about ``2 * alpha * sqrt(1 - f)`` a row, ``f`` the decay factor over one row's clock, however large the error. Just after the break, before the sums have grown, it moves faster, by up to about ``alpha`` in one row. So ``D / (2 * alpha * sqrt(1 - f))`` estimates the rows a break that moves a coefficient by ``D`` takes to follow, and is not a bound. Under ``loss="squared"`` on one feature with noise of spread 0.3, over breaks of 2 and 20 in the intercept, at half-lives of 200 and 1000 and ``alpha`` from 0.1 to 1 (two seeds each), the rows to close 90% of the break came to 0.37 to 1.54 times the estimate. The large gradients just after a break increase the sums that divide every step for about a half-life. The table was measured under ``loss="squared"`` on two features at ``half_life = 200``, one row a clock unit, after a change of regime that moved the intercept by 46. The table gives the worst of 50 seeds, the largest coefficient gap to the decayed least squares: .. list-table:: :header-rows: 1 * - ``alpha`` - at its steady state, before the break - 4 half-lives after - 8 half-lives after - 12 half-lives after * - 0.1, the default - 0.17 - 34.4 - 28.5 - 19.9 * - 0.3 - 0.24 - 18.4 - 2.7 - 0.86 * - 1.0 - 0.43 - 2.7 - 0.61 - 0.85 At the default the intercept closed at 0.011 a row from 4 to 12 half-lives after the break, against ``2 * alpha * sqrt(1 - f)`` = 0.012. So a larger ``alpha`` follows a break sooner, and it moves more from row to row at its steady state: at ``alpha = 1`` the gap stops shrinking by 8 half-lives, within twice its steady state's. Over the 24 half-lives after the noise quadrupled, the default came at most 0.23 from the decayed least squares, and ``alpha = 1`` came 1.17 from it. **Rows the target is not learned from.** The model learns nothing about the target from some rows: a row where it is absent, a row of weight 0, and a row whose squared gradient would overflow. Each leaves the sums as the last row the target was learned from left them. So the fit does not move, as :func:`ewridge`'s does not, and a row of weight 0 moves the clock alone, as in every model. The next row the target is learned from is predicted with that fit, then ages the sums by the whole clock since and learns. The gap ages the evidence and not the prior. The fit of a constant 5, at ``half_life = 100`` and at its steady state (4.65), stands at 0.75 of that fit after that row when the gap was one half-life, and at 0.15 of it when it was five. **Weights and the penalties.** A row's weight is an importance weight, as in the learner Vowpal Wabbit: the gradient carries it, against penalties in absolute weight. So a heavier stream overcomes ``l1`` and ``l2`` sooner (``tests/test_second_opinion.py`` holds the fit to Vowpal Wabbit's, weighted). ``l1``, ``l2`` and ``beta`` are a prior of fixed mass against evidence that grows with weight and density, which FTRL's regret bound rests on. So under a half-life the effective penalty is ``l1 / W`` for the weight ``W`` the half-life holds, and more rows in a half-life, or heavier ones, outweigh it sooner. For a penalty on the mean scale, invariant to both, use :func:`lasso`. **Units.** A coefficient is ``zz_i`` over ``r_i + l2``, and ``g_i`` is the target (a probability, under the logistic loss) times the feature, at the row's weight. So ``beta`` is in the units of ``sqrt(n_i)``, a gradient, ``alpha`` in the coefficient's, the target per unit of the feature, ``l1`` in the summed gradient's, and ``l2`` in ``r_i``'s, the feature squared. With ``fit_intercept=False``, every feature scaled by ``c`` fits the same model at ``alpha / c``, ``beta * c``, ``l1 * c`` and ``l2 * c**2``. The intercept's 1 does not scale, and the four are shared by every coefficient, so with an intercept there is no such equivalence. **Features at a level.** ``ftrl`` does not center a feature. A coefficient's error reaches the prediction multiplied by the feature's value, so a feature that sits at a level ``L`` carries it at ``L`` times its size. On the stream of ``crates/rheon-core/tests/held_values.rs``, with one of three features at ``L``, the squared loss's error is about ``0.018 * L``: 18.3 at 1,000 and at -1,000, and 1.8e6 at 1e8, against 0.75 at 0.5. Standardize or z-score such a feature before the bank, as `Scale a feature by its spread <https://github.com/rheon-dev/rheon/blob/main/docs/how-to/scale-a-feature-by-its-spread.md>`_ shows. There is no ``standardize`` here because ``l1`` zeroes a coefficient in the feature's own units: a scale inside the model would move which coefficients it zeroes as the feature's spread moved. """ model: dict[str, Any] = { "type": "ftrl", "alpha": alpha, "beta": beta, "l1": l1, "l2": l2, "strict_binary": strict_binary, "loss": loss, } return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def ew_cov( name: str, *, features: list[str], stats: list[Literal["mean", "var", "std", "cov", "corr", "partial_corr", "mahal", "lag_corr"]] | None = None, bias: bool = False, precision_prior: float | None = None, mahal_quantiles: list[float] | None = None, pca: int | None = None, pca_every: float | Duration | None = None, max_rows_between_pcas: int | None = None, lags: list[int] | None = None, gram_threads: int | Literal["auto"] | None = None, window_size: float | Duration | None = None, closed: Literal["right", "both"] = "right", snapshot_every: float | Duration | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal["thin", "refuse"], float] | None = None, **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Exponentially weighted moments of the feature columns, and the statistics read off them. Use it for the running means, spreads, correlations, principal components or Mahalanobis distances of a stream's columns, read before each row, so an output can be a feature for that same row without leaking it. It fits no target: use :func:`ewridge` for a regression on the same co-moments, and :func:`rcov` for a block's covariance under microstructure noise. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight`` and ``group``, are in :mod:`rheon.spec`. This model reads ``features`` and takes no ``targets``. ``fit_intercept`` has nothing to act on, as there is no regression. Nothing that reads residuals applies, and each such switch is refused by name: ``emit_sigma``, ``emit_metrics``, ``conformal``, ``emit_drift`` and the rest. ``coef_every`` and ``max_rows_between_coefs`` are refused, as there are no coefficients. This model's own: ``stats`` Which statistics to write, from ``mean``, ``var``, ``std``, ``cov``, ``corr``, ``partial_corr``, ``mahal`` and ``lag_corr``. Default ``["mean", "std", "corr"]``, so a single feature needs ``stats`` without ``cov``, ``corr`` and ``partial_corr``, which need two columns. ``partial_corr`` and ``mahal`` need ``precision_prior``, ``lag_corr`` needs ``lags``, and ``mahal_quantiles`` needs ``mahal``. ``[]`` writes no statistic, only ``weight_sum``, ``settled_frac`` and ``withheld_reason``, and learns all the same. The spec's value is then its state, read back with :meth:`rheon.polars.ModelBank.gram` and :meth:`rheon.polars.ModelBank.describe`. That is the form for a wide set of columns, where even the means are ``k`` values a row (``k`` the number of features) that nobody reads. ``bias`` Polars' ``bias``, with its default ``False``: ``var``, ``std`` and ``cov`` are then Polars' ``ewm_var`` and ``ewm_std`` and the covariance they imply, on a clock of one row a step and with Polars' default ``adjust=True``. That multiplies the weighted means by the factor ``c`` of *The update*, Bessel's correction at Kish's effective size (*Bias* in Notes). ``True`` reports the weighted means as kept, which is what :meth:`rheon.polars.ModelBank.gram` returns under either. Under ``False``, a second moment is null while the moments hold a single row, of any weight, as Polars' is. Under ``True`` it reads 0. ``precision_prior`` A ridge on the co-moments, in the features' squared units, finite and above 0: it makes the precision matrix ``P`` of *The update* solvable on each row it is read (O(k³), only when asked for). Like :func:`rls`'s prior it fades as rows arrive. Default ``None``, no ridge. Needed by ``partial_corr`` and ``mahal`` alone: the other statistics read the co-moments themselves, which need no inverse, so ``None`` adds no ridge to them. :func:`ew_class` and :func:`hmm` require it, since every row they predict reads an inverse. ``mahal_quantiles`` Levels in ``(0, 1)`` at which to keep the exponentially weighted quantile of the past ``mahal`` distances (``mahal_q<p>``), at the model's half-life and each row's weight, within ``tanh(1/128)`` (0.78%) of the exact one. That is a threshold from the stream's own history instead of a table, so ``mahal > mahal_q0.99`` is one row in a hundred without assuming a distribution. The row's own distance joins after it is read. ``pca`` Track the top ``pca`` principal components of the covariance, at least 1 and at most the number of features. Per component ``j``: .. list-table:: :header-rows: 1 :widths: 34 66 * - field - what it holds * - ``pc<j>_var`` - its eigenvalue * - ``pc<j>_share`` - its share of the total variance * - ``pc<j>_loading_<feature>`` - its unit loading on each column * - ``pc<j>_score`` - the row's coordinate ``v_j . (x - m)`` The first refresh makes each component's largest loading in magnitude positive. Each later refresh turns a component to within 90° of its previous loadings, so a component and its score never flip sign from one refresh to the next (*Principal components* in Notes). ``pca_every``, ``max_rows_between_pcas`` How often the eigendecomposition, O(k³), is refreshed after the row is learned: every ``pca_every`` clock units or every ``max_rows_between_pcas`` rows, whichever comes first, as ``solve_every`` and ``max_rows_between_solves`` schedule a regression's solve. ``pca_every`` is a number of the clock's units, a duration on a temporal clock (``"5m"``), or ``0`` for every row, finite and at least 0. ``max_rows_between_pcas`` is at least 1. With neither given, every row. Both are refused without ``pca``. Between refreshes the loadings are frozen, so a row's scores never depend on the chunking. ``lags`` Lagged cross-moments beside the contemporaneous ones (*Lags* in Notes). Lags are counted in learned rows within the group, not clock units, and must be strictly increasing, ``>= 1`` and at most 2^20 (1,048,576), the ring being sized before the first row. The list order is the output order. Add ``"lag_corr"`` to ``stats`` to write ``lag_corr_l<l>_<a>_<b>`` = ``C_l[a,b] / sqrt(C_0[a,a] * C_0[b,b])`` per lag and ordered pair, the auto terms included. That is ``k²`` fields a lag, since a lagged matrix is not symmetric. Or read ``lags`` and ``lag_comoments`` (an ``(L, k, k)`` array) from :meth:`rheon.polars.ModelBank.gram`. ``gram_threads`` The largest number of the bank's threads that learning one row into the ``k x k`` co-moments may use: a whole number of at least 1, or ``"auto"``, as :func:`ewridge`'s ``gram_threads`` is. It never adds a thread to the bank's. Default ``"auto"``, which splits a row's learning only where the bank has idle threads. The output is the same to the bit at every count (*Threads* in Notes). ``window_size``, ``closed`` A hard window on the history, in clock units, finite and above 0: a row ``window_size`` old or older contributes nothing at all, where the exponential weight alone would still leave ``0.5 ** (age / half_life)`` of it, 12.5% at three half-lives. ``closed`` is ``"right"`` (the default) or ``"both"``, which keeps the row exactly that old, as for :func:`ewridge`. Inside the hard window the weights are still exponential, so this is not a flat mean over its rows: each row keeps the weight it has without one. ``window_size`` is refused beside ``lags`` and ``mahal_quantiles``, which run over a history it does not cut (*The hard window* in Notes). ``snapshot_every``, ``max_rows_between_snapshots``, ``window_budget`` The hard window's snapshots, as for :func:`ewridge`. ``snapshot_every`` spaces them on the clock (``"1m"``, or a number of the clock's units) and ``max_rows_between_snapshots`` caps the rows between them, whichever comes first. ``window_budget`` bounds each ring in MiB and thins or refuses past the bound. By default a snapshot on every row, and no budget. ``closed="both"`` and these three are refused without ``window_size``. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields, read before the row is learned. `docs/OUTPUTS.md#ew_cov <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#ew_cov>`_ gives each field's type and when it is null: ``mean_<column>``, ``var_<column>``, ``std_<column>`` Per column, as ``stats`` asks: the mean, the variance and the standard deviation, as ``mean_x0``. ``cov_<column>_<column>``, ``corr_<column>_<column>``, ``partial_corr_<column>_<column>`` Per pair, unordered, ``i < j``, as ``corr_x0_x1``. ``lag_corr_l<l>_<a>_<b>`` Per lag and ordered pair, under ``lags``. ``mahal``, ``mahal_q<p>`` The row's Mahalanobis distance from the mean, and the quantiles of its past values ``mahal_quantiles`` asks for. ``pc<j>_var``, ``pc<j>_share``, ``pc<j>_loading_<feature>``, ``pc<j>_score`` Under ``pca``, as the table under ``pca`` says. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's statistics were withheld, null where they were not. The statistics are null until ``min_weight``, which defaults to the number of features plus one and which the bank floors at 2: a variance needs two rows, so a lower ``min_weight``, ``0`` included, is taken as 2, and is not refused. The rows the floor holds back read ``below_min_weight``, as the gate's do. The moments themselves are :meth:`rheon.polars.ModelBank.gram`'s ``means``, ``comoments``, ``lags`` and ``lag_comoments``, the weighted means as kept whatever ``bias`` is, with ``n_kish`` to correct them by. A group that closes writes them to :meth:`rheon.polars.ModelBank.closed_groups` with ``eig_vals`` and ``eig_vecs`` of those ``comoments`` under ``pca``. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), ``TypeError`` for ``targets``, which this model does not take, and ``ValueError`` naming the problem for: - a statistic not in the list, ``cov``, ``corr`` or ``partial_corr`` over one column, ``partial_corr`` or ``mahal`` without ``precision_prior``, and ``lag_corr`` without ``lags``; - a ``precision_prior`` not finite or not above 0; - an empty ``lags``, one that does not increase, or a lag below 1 or above 2^20; - an empty ``mahal_quantiles``, one without ``mahal``, or a level outside ``(0, 1)``; - a ``pca`` of 0 or past the features, a ``pca_every`` below 0 or not finite, a ``max_rows_between_pcas`` of 0, and ``pca_every`` or ``max_rows_between_pcas`` without ``pca``; - a ``gram_threads`` of 0, or a string other than ``"auto"``; - a statistic or a ``mahal_quantiles`` level listed twice; - a ``window_size`` not finite or not above 0, ``window_size`` beside ``lags`` or ``mahal_quantiles``, a ``closed`` of ``"left"`` or ``"none"``, a ``snapshot_every`` below 0 or not finite, a ``max_rows_between_snapshots`` below 1, a ``window_budget`` that is not one key, ``"thin"`` or ``"refuse"``, or whose MiB is not above 0, and ``closed="both"``, ``snapshot_every``, ``max_rows_between_snapshots`` or ``window_budget`` without ``window_size``; - a switch that reads residuals, such as ``emit_sigma``, and ``coef_every``. .. rubric:: The update Per row, ``w`` is the row's weight, ``λ = 0.5 ** (Δclock / half_life)`` its decay (``lam ** Δclock`` under ``lam``), and ``x`` the row's features. ``Δclock`` is the clock's step since the last row the model did not skip, capped at ``gap_cap``, or ``session_gap`` at a session change. The means ``m`` and the centered co-moments ``C`` are kept as weighted means, in Welford's form, beside the weight ``W`` and the sum of the squared weights ``Q``: .. code-block:: text W' = λ * W + w Q' = λ**2 * Q + w**2 a = λ * W / W' b = w / W' (a + b = 1) delta = x - m m' = m + b * delta C'_ij = a * C_ij + a * b * delta_i * delta_j The second moments are read off ``C`` times a factor ``c``, and ``corr_ij = C_ij / sqrt(C_ii C_jj)``, from which ``c`` cancels: .. code-block:: text c = W**2 / (W**2 - Q) (1 under bias=True) var_i = c * C_ii std_i = sqrt(var_i) cov_ij = c * C_ij With ``P = (c * (C + s * precision_prior * I))^-1``, read before the row, and ``s`` the prior's scale (1 on the first row, times ``a`` on each row after): .. code-block:: text partial_corr_ij = -P_ij / sqrt(P_ii P_jj) mahal = sqrt((x - m)' P (x - m)) With ``W`` and ``m`` the weight and mean before the row, and both deviations against that mean, each lag ``l`` of ``lags`` keeps: .. code-block:: text C_l' = a * C_l + a * b * (x_t - m) (x_{t-l} - m)' .. rubric:: Example This code plants two columns with spreads 2 and 1 and a correlation of 0.6, and prints what the model reads before the last row: .. code-block:: python import numpy as np rng = np.random.default_rng(5) a, b = rng.standard_normal(10_000), rng.standard_normal(10_000) x0 = 2.0 * a # spread 2 x1 = 0.6 * a + 0.8 * b # correlation 0.6 with x0 pl.DataFrame({"x0": x0, "x1": x1}).write_parquet("pair.parquet") mv = rp.spec.ew_cov( "mv", features=["x0", "x1"], half_life=float("inf"), stats=["std", "corr"], # std_x0, std_x1 and corr_x0_x1 ) out = pl.scan_parquet("pair.parquet").rheon.fit_predict([mv]).collect().unnest("mv") last = out.row(-1, named=True) # read before the last row is learned print("planted: std_x0 2.00, corr 0.60") print(f"found: std_x0 {last['std_x0']:.2f}, corr {last['corr_x0_x1']:.2f}") .. code-block:: text planted: std_x0 2.00, corr 0.60 found: std_x0 2.01, corr 0.60 .. rubric:: See also - :func:`ewridge`, a regression on the same running co-moments. - :func:`ew_class` and :func:`hmm`, which classify rows by Gaussians on these moments. - :func:`rcov`, a block's covariance robust to microstructure noise. - :meth:`rheon.polars.ModelBank.gram`, to read the moments back. .. rubric:: Notes **Precision.** A variance stays accurate when the columns sit on a large offset, where the raw ``E[x^2] - m^2`` form loses it. **Against Polars.** Learning a row in O(k²) replaces the O(k²) passes a pure-Polars pairwise exponentially weighted correlation needs. For moments on data that fits in memory, Polars can compute the same moments under a ``window_size`` when you weight each row yourself in ``df.rolling(clock, period=window_size).agg(...)``. There each row is weighted ``2 ** (-age / half_life)`` from the window's last row, ``c`` comes from those weights, and the result is shifted one row, since a row's moments are read before the row. On 20,000 rows about a minute apart, a three-hour hard window (``window_size="3h"``, about 180 rows) and a half-life of 30 minutes, the mean of a column near 100 agreed to 8.5e-14, its variance to 6.4e-14 and its correlation with a second column to 4.3e-14. The reason to reach for the spec is a stream, a saved state, or the work: Polars recomputes each window, so its work grows with ``n`` rows times the rows of a window, where this model's grows with ``n``. **Bias.** The factor ``c`` is ``n / (n - 1)`` at Kish's effective size ``n = W**2 / Q``, the number of equally weighted rows the moments are worth: Bessel's correction, ``ddof=1`` for ``n`` unit rows with no decay. At a half-life of 20 rows it is 1.018 in steady state, at 2 rows 1.207. ``c`` multiplies the ridge on the co-moments with them, so it divides ``mahal`` by ``sqrt(c)``, multiplies ``pc<j>_var`` by its value at the refresh, and moves no correlation, share, loading or score. **Principal components.** The components are the same to the bit whatever the bank's thread count (``RHEON_MAX_THREADS``): the eigensolver runs at a fixed parallel degree of eight. A row of weight zero advances both refresh schedules, as the hard window's snapshot cadence counts it, and a gap capped at ``gap_cap`` counts as the cap. Without a clock column the clock is the row's number. **Lags.** ``C_l`` uses the same ``a`` and ``b`` the co-moments use, so lag 0 would be ``comoments`` exactly. The lagged statistics are defined by this recursion, both legs centered at the mean before each row, not as a lagged covariance of the whole stream about the final mean, which a frame in memory would compute. The ring of past rows is emptied on a clock break: a row whose clock step ``gap_cap`` shortened, whether the step follows one row or a run of skipped rows, or a session change. After a clock break, "the row ``l`` back" is not a row ``l`` ago. A zero-weight row ages the matrices and does not enter the ring. A group's first rows read ``lag_corr`` null until ``min_weight``, at least two rows of weight, since one row has no variance to divide by. ``C_l`` starts at 0 and takes its first product when a learned row has one ``l`` rows back, so after those rows ``lag_corr`` reads 0.0, not null, while the group has learned no more than ``l`` rows before the row. **Threads.** Learning a row is bound by memory: at 2,000 features a spec that wrote no statistic learned 2.5 times as fast on eight threads and 3.1 times on fourteen (measured on 2026-10-08). Below 725 features learning a row stays on one thread, and the lagged cross-moments of ``lags`` always do. **The hard window.** It is exact, because an exponentially weighted sum contains its own past. Everything at or before a time ``u`` is ``lam ** (t - u)`` times the running sums as they stood at ``u``, so subtracting that leaves precisely the rest. What the model keeps is a ring of snapshots, one per row by default, so its memory grows with the snapshots the hard window keeps rather than with the state alone. A snapshot is ``k² + k + 3`` eight-byte numbers, so a 1,000-row hard window over 20 columns is about 3 MB per group. Spacing the snapshots with ``snapshot_every`` or ``max_rows_between_snapshots`` divides the memory, and a clock spacing alone holds a ring to at most ``window_size / snapshot_every + 2`` snapshots whatever the row rate. Four things to know before reading the numbers under a hard window: .. list-table:: :header-rows: 1 :widths: 34 66 * - the caveat - why * - the guarantee is one-sided - the boundary is the oldest snapshot still inside the hard window, so what is dropped is always a superset of what the hard window excludes; under a coarser cadence the hard window kept is shorter than asked by at most one snapshot's spacing, never longer: in ``[window_size - snapshot_every, window_size]`` in clock units, exactly, under a clock spacing, with ``snapshot_every`` the spacing in force (a thinning budget doubles it) * - the clock is the decayed one - ``window_size`` is measured on the clock the decay uses, after ``gap_cap`` caps a gap and after a ``session_gap`` is applied * - the edge is a discontinuity - a row aging out drops its whole weight at once, so the series has small steps an exponentially weighted mean without a hard window does not * - it is a subtraction - precision falls with the fraction discarded: negligible at ``window_size = 3 * half_life`` (an eighth of the mass), worse as the hard window shortens toward the half-life ``weight_sum`` becomes the weight inside the hard window, which stops growing once the hard window fills, so ``min_weight`` withholds on a quantity with a ceiling. A clock gap longer than ``window_size`` empties it. The row after the gap reads the hard window as the row before the gap left it, since a row's fields are read before its own decay, as ``weight_sum`` is. The rows after it report nulls rather than stale numbers, until the hard window holds ``min_weight`` again. ``mahal``, ``partial_corr`` and the principal components read the hard window's moments too, ``bias``'s factor is the hard window's ``W`` and ``Q``, and the refresh of the principal components waits on the hard window's weight. """ model: dict[str, Any] = { "type": "ew_cov", "stats": stats, "bias": bias, "precision_prior": precision_prior, "mahal_quantiles": mahal_quantiles, "pca": pca, "pca_every": pca_every, "max_rows_between_pcas": max_rows_between_pcas, "lags": lags, "gram_threads": gram_threads, "window_size": window_size, "closed": closed, "snapshot_every": snapshot_every, "max_rows_between_snapshots": max_rows_between_snapshots, "window_budget": window_budget, } # Written only when given, as the Rust spec skips it when absent. if gram_threads is None: del model["gram_threads"] targets = _mirror_target(name, "ew_cov", features, common, "its statistics are over") return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def pa( name: str, *, targets: TargetList, features: list[str], mode: Literal["pa", "pa1", "pa2"] = "pa1", c: float | None = None, eps: float | None = None, coef_min: float | list[float] | None = None, coef_max: float | list[float] | None = None, coef_sum: float | None = None, standardize: bool = True, **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Passive-aggressive regression, which moves the fit by the smallest step that brings each row within a margin of its target. Use it for a fit in O(k) time a row, ``k`` the number of features, with no learning rate to tune. A row whose prediction is within ``eps`` standard deviations of its target moves nothing, and any other row moves the fit toward it by the smallest change, capped by ``c`` under ``pa1`` and damped under ``pa2`` (Crammer et al. 2006). Use :func:`sgd` for other losses or a learning rate, and :func:`ewridge` for an exact fit on running sums. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight``, ``group`` and the diagnostics, are in :mod:`rheon.spec`. This model's own: ``mode`` ``"pa"``, ``"pa1"`` (the default) or ``"pa2"``. Prefer the bounded modes when outliers are possible: plain ``"pa"`` moves the fit as far as it takes to satisfy a single bad row. ``c`` Under ``pa1``, the cap on the step size ``tau``. It is in the target's units over the units of ``q``, the row's squared length: the features' squared units, or none under ``standardize``, where ``c`` is in the target's units alone. So what the cap does depends on the target's scale (*c and the target's units* in Notes). Under ``pa2``, ``c`` sets the damping ``1 / (2c)`` added to ``q``, in ``q``'s units and free of the target's. Default 1.0, which caps a step of ``pa1`` at one unit of the target per unit of ``q``. Above 0. ``inf`` caps nothing, so either bounded mode is then ``"pa"``. ``"pa"`` reads no ``c`` and refuses one. ``eps`` The margin, in units of ``sigma``, the target's own exponentially weighted (EW) standard deviation: a row whose prediction is inside it moves nothing. Finite and at least 0. Default 0.01: residuals under 1% of the target's own spread do not move the fit. On a target a fit predicts closely, the default margin can be many noise standard deviations wide (*The margin* in Notes). ``coef_min``, ``coef_max``, ``coef_sum`` Constraints on the slopes, exactly as for :func:`sgd`. Default: no constraint. The projection follows each step, so the step does not meet the row's margin exactly: it is the closest feasible coefficient to the one that would. A truth outside the feasible set is never reached, so the model keeps stepping against the walls. A small ``c`` keeps those steps small. ``standardize`` Take the step in standardized coordinates, with :func:`sgd`'s scaler, its rule and its warm-up. Each row is standardized against the running moments with the row admitted, ``z_i = (x_i - m_i) / s_i`` (``z_i = x_i / s_i``, the root mean square, without an intercept), and a box or a sum is projected with its bounds carried over. Default ``True``. Without it, ``q`` and ``c`` are in the features' units, so one feature in thousands makes every step tiny and one in thousandths makes the cap bind on most steps. Once the scaler has warmed up, a change in the moments moves no prediction (*Standardizing* in Notes). ``min_weight`` counts the rows the target was present on, at their weights, decayed, where ``weight_sum`` counts every row, so rows with a null target do not warm up coefficients they never moved. A row's weight below 1 scales ``tau``, so a half-weight row moves the fit half as far. In the step, a weight above 1 counts as 1, though ``weight_sum``, each target's weight, the scaler and ``sigma`` take the full weight. In a model that keeps running sums, a row of weight 2 counts as two rows of weight 1. Here the step aims at the row's constraint, so a weight past 1 would overshoot. A constant weight of 2 would make the plain ``"pa"`` step oscillate without settling. The coefficients do not decay, so one very heavy row would move the fit with no way back. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields. `docs/OUTPUTS.md#pa <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#pa>`_ gives each field's type and when it is null: ``pred_<t>``, ``resid_<t>`` Per target: the prediction, and ``y - pred`` where the target is not null. ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row. ``withheld_reason`` Why the row's predictions were withheld, null where they were not: a reason of the shared gates (:mod:`rheon.spec`), such as ``below_min_weight`` on the first rows under the default ``min_weight``. ``coef`` Per target, the intercept (unless ``fit_intercept=False``) then one entry per feature, after the row is learned (:func:`coef_index`). plus the fields of the diagnostics switched on, as :mod:`rheon.spec` describes them. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for: - a ``mode`` other than ``"pa"``, ``"pa1"`` or ``"pa2"``; - a ``c`` not above 0, and any ``c`` beside ``mode="pa"``, which reads none; - an ``eps`` not finite or below 0; - ``coef_min``, ``coef_max`` and ``coef_sum``, checked as for :func:`sgd`. .. rubric:: The update Here ``z`` is the row's features, the intercept's 1 inside it, ``b`` the coefficients, ``w`` the row's weight and ``p = z . b`` the prediction. ``sigma`` is the target's own EW standard deviation as the row arrives, ``loss = max(0, |y - p| - eps * sigma)`` and ``q = ||z||^2``: .. code-block:: text pa tau = loss / q (unbounded) pa1 tau = min(c, loss / q) (capped at c) pa2 tau = loss / (q + 1 / (2c)) (damped by c) b += min(w, 1) * tau * sign(y - p) * z That is the step with ``standardize=False``, ``z = [1, x]``. Under ``standardize``, the default, ``z`` is the row standardized. Once the scaler has warmed up, the coefficients are held in the caller's units, the prediction is ``p = [1, x] . b``, and the step is mapped into the caller's units by the row's own means ``m_i`` and standard deviations ``s_i``: .. code-block:: text step = min(w, 1) * tau * sign(y - p) b_i += step * z_i / s_i b_0 += step - sum_i m_i * step * z_i / s_i .. rubric:: Example This code fits a plane with an intercept of 1 and slopes of 2 and -0.5, each step capped at 0.1, and prints the coefficients found at the last row: .. code-block:: python import numpy as np rng = np.random.default_rng(5) x0, x1 = rng.standard_normal(5_000), rng.standard_normal(5_000) y = 1.0 + 2.0 * x0 - 0.5 * x1 + 0.3 * rng.standard_normal(5_000) pl.DataFrame({"x0": x0, "x1": x1, "y": y}).write_parquet("pa.parquet") pa = rp.spec.pa( "pa", targets=["y"], features=["x0", "x1"], half_life=200.0, mode="pa1", c=0.1, # each step is capped at c ) bank = rp.ModelBank([pa]) bank.fit(pl.scan_parquet("pa.parquet")) # learn every row, keep no output for r in bank.coef().iter_rows(named=True): print(f"{r['term']}: {r['coef']:.2f}") .. code-block:: text intercept: 0.89 x0: 2.04 x1: -0.56 .. rubric:: See also - :func:`sgd`, gradient steps with a learning rate, under several losses, with the same scaler and constraints. - :func:`ewridge`, an exact fit on running sums. - `pa in docs/MODELS.md <https://github.com/rheon-dev/rheon/blob/main/docs/MODELS.md#pa--passive-aggressive-regression>`_: recipes on data whose answer is known. .. rubric:: Notes **The margin's scale.** The margin, ``eps * sigma`` on each side of the prediction, is a tube, as :func:`sgd`'s is. ``sigma`` is the target's own EW standard deviation as the row arrives. It is the spread of ``y`` around its EW mean, over the rows with the target and a weight above 0, whatever the fit, each ``y`` joining after its own row is judged. Before the target has a ``sigma`` above 0, which takes two weighted rows of different values, the tube has no width and every row moves the fit. A tube of 0.1 in the target's own units would hold a target in hundredths on every row: passive forever, every prediction 0.0 and R² -0.05, where the same target unscaled reached 0.96. ``sigma`` is not a scale of the residuals, such as the one :func:`huber`'s cut is drawn in. The fit starts from zero coefficients, so its first residuals are the target's whole level. On a target at 1,000 with a spread of 2 they put the residual's standard deviation near 1,000, so a tube of ``eps = 0.1`` drawn in it would be about 100 wide and hold every row. Without decay it would never narrow: R² -52 at a half-life of 1e9. **c and the target's units.** ``pa1``'s ``tau`` is in the target's units over ``q``'s, so a cap of 1 caps every step of a target in thousands and none of a target in thousandths. The figures in *The margin* are for a target of spread about 2. ``pa2``'s ``c`` is added to ``q`` as ``1 / (2c)``, in ``q``'s units, so it is free of the target's. Under ``"pa"`` and ``"pa2"`` a target scaled by ``a`` fits as the unscaled one, scaled by ``a``. Under ``"pa1"`` it does so only while the cap does not bind. **The margin.** In units of the noise, on a target a fit predicts to R², ``sigma`` is the noise's standard deviation over ``sqrt(1 - R²)``, so the tube is ``eps / sqrt(1 - R²)`` noise standard deviations wide. At the default 0.01: .. list-table:: :header-rows: 1 * - R² - 0.5 - 0.978 - 0.9975 - 0.9998 - 0.99998 * - the tube, in noise standard deviations - 0.014 - 0.067 - 0.20 - 0.71 - 2.2 A tube well inside the noise damps nothing: every row outside it is projected onto its edge, and only a cap that binds damps then. A wider tube damps too, while the cap does not bind: the fit moves only on the rows in the noise's tails, and they keep pulling it back. But a tube many noise standard deviations wide holds the fit wherever it first lands inside it. Measured (``pa1``, one feature, a target of spread about 2, no decay; the out-of-sample error above the noise, in noise variances, median over seeds): .. list-table:: :header-rows: 1 * - R² - the defaults - ``c = 0.1`` - ``eps = 0.1`` - ``eps = 0.5`` * - 0.978 - 1.15 - 0.33 - 0.57 - 0.06 * - 0.99998 - 0.14 - 0.14 - 65 (25 to 347) - 1,496 At R² 0.978 the default tube, 0.067 noise standard deviations, damps nothing, and a cap of 1 binds on few rows of a target of spread 2: a cap of 0.1 or a wider tube damps more. At R² 0.99998 the default tube is 2.2 noise standard deviations and no cap binds. A tube of 0.1 (22 of them) or 0.5 holds the fit wherever it first lands, from 25 to 347 noise variances over 20 seeds at 0.1. Over 108 streams and the three modes, the default had the smallest worst regret (R² from 0.5 to 0.99998, a level of 0 or plus or minus 1,000, a half-life of 50, 500 or none, one feature or five). The default was also measured against a tube drawn in the residuals' spread, capped by the target's spread. Without decay, that spread kept the large residuals of the first rows forever: under ``pa2`` it left a target at a level of 1,000 at R² 0.76 to 0.80. **On a level that moves, give a larger c or difference the target.** The fit starts from zero coefficients, and a ``pa1`` cap of 1 moves the intercept about one unit a row. On a target falling from 1,000 to -1,000 at 0.5 a row (half-life 200, noise 0.3), the intercept stood at 51.5 at row 50 and 401 at row 400, and met the level near row 670. With the level as a feature too, the capped steps, mapped into the caller's units through the scaler, swung the fit far past the level instead. A drift that the intercept carries alone keeps a lag at any ``c``: 2.2 on average over rows 800 to 1,600 at ``c = 1000``. About half of it is the tube, ``eps * sigma``, whose ``sigma`` holds the drift (97 to 143 here). With ``eps = 0`` the lag was 1.1. Differencing the target and the moving features, ``y - y.shift(1)``, takes the level out of the fit: the level is then the last row's ``y`` plus the predicted change, and the change carries noise of 0.42 here. Measured as ``pred - y``: .. list-table:: :header-rows: 1 * - the run - row 800 - row 1,600 - every row within 3 from row * - the defaults, the level a feature - 1,790 - -3.2 - 2,795 * - ``c = 10``, the level a feature - 0.67 - 1.1 - 467 * - ``c = 1000``, the level a feature - -0.52 - -0.60 - 11 * - the defaults, the level the intercept's alone - 1.3 - 2.1 - never: 2.7 rms over rows 800 to 1,600 * - differenced, the level read back - -0.73 - -0.05 - 12 **Decay.** The coefficients keep no running sums, so there is nothing in them for the clock to decay: each step moves the fit toward the current row and keeps nothing else, and older rows survive only through the coefficients they left behind. The clock decays ``weight_sum`` and each target's own weight, which ``min_weight`` reads, so ``min_weight`` means the same thing as in every model. It decays the scaler and ``sigma`` too. The coefficients have no half-life. **Standardizing.** Until Kish's count of the rows the moments have learned reaches 22, the coefficients are held in the standardized coordinates and read back in the caller's units through the moments as they stand. On the row that count reaches 22, the coefficients are converted to the caller's units once, and from then on held there, the step mapped into them as *The update* shows. The step still puts the row where the update's equations say. The row's change of prediction is ``step * ||z||^2``, so an uncapped step at weight 1 leaves it on the tube's edge, and one at weight ``w < 1`` goes that fraction of the way. The prediction reads no moment, so a change in the moments moves none of it. The alternative, a fit read through the moments as they stand, lets a finite half-life's own wander in the moments move every prediction. At a half-life of 50 and R² 0.99998 that cost 31.8 noise variances of out-of-sample error above the noise, where the fit without ``standardize`` had 0.18. Past the warm-up a box or a sum bounds the coefficients in the caller's units and is projected as for :func:`sgd`. The scaler reads each row in the stream's own unit of weight, one row's of the stream, and its history keeps at least that weight into any row, as for :func:`sgd` (*Decay and the rate* there). The step is divided by the row's scale, and after a long gap a history decayed to almost nothing read the row against a scale of one row: over rows 6 to 100 after a gap of 30 half-lives or more the error at the 99th percentile over seeds was up to 6,000 times that of the same stream with no gap, and is now within 1.1 times of it. At weights of 1/8 on 8 features the row, read at weight 1, was too large a share of the moments, and the error was 1,720 noise variances; read in the stream's unit it is 0.097, and at constant weights of 1 or more every prediction is the one at weights of 1, to the bit. """ model: dict[str, Any] = { "type": "pa", "mode": mode, "c": c, "eps": eps, "coef_min": coef_min, "coef_max": coef_max, "coef_sum": coef_sum, "standardize": standardize, } return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def seqtest( name: str, *, targets: TargetList, a: str | None = None, b: str | None = None, a_suffix: str | None = None, b_suffix: str | None = None, **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """A sequential test of a target's sign by betting, whose evidence can be read at any row. Use it to ask whether a target is positive more often than negative, or, with ``a`` and ``b``, whether one spec of the bank predicts closer than another. You can read the answer at every row and act the first time it is enough, which a p-value checked over and over does not allow. Use :func:`rheon.polars.eval.seqtest` for the same test over a frame in memory, and :func:`rheon.polars.eval.compare_specs` for several specs' scores over the whole stream in one table. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``group``, ``session`` and ``restart_after_step_back``, are in :mod:`rheon.spec`. This model is not a regression and makes no prediction. It reads only its ``targets`` (or the residuals of the specs ``a`` and ``b`` name) and takes no ``features``: a spec dict or a TOML table says ``features = []``. A trial is a row, so ``weight`` is refused. A test that forgot its losses would not keep its guarantee, so ``half_life`` and ``lam`` are refused. ``min_weight`` defaults to 0, and ``fit_intercept`` has nothing to act on. The test resets at a session change under ``session_gap = "reset"`` and at a step back past ``restart_after_step_back``, and starts over at each session span under ``group_close = "session"``. This model's own: ``a``, ``b``, ``a_suffix``, ``b_suffix`` Compare two specs of the same bank. Each target ``t`` names a residual field both carry: ``resid_<t>`` on each side, plus the side's grid suffix when it is a grid (``a_suffix="@h50"`` picks ``resid_<t>@h50`` of ``a``, and ``"__r0.1"`` a ridge value). The sign tested is that of ``|resid_b| - |resid_a|``, positive when ``a`` was closer on the row. Any loss that grows with ``|resid|`` (squared, absolute, Huber) gives the same sign, so this tests "``a`` beats ``b``" under any of them. The bank runs ``a`` and ``b`` first, so the comparison reads the same out-of-sample residuals their output columns report. A row where either side is null (warm-up, a skipped row) is a row the test sits out. Default none: the test is of each target's own sign. ``a`` and ``b`` are given together, and a suffix only beside them. Two instances of one grid (an instance is the part of a model that fits one half-life), such as ``a_suffix="@h20"`` against ``b_suffix="@h400"``, are a comparison like any other. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields, per target ``t`` and read before the row is learned. `docs/OUTPUTS.md#seqtest <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#seqtest>`_ gives each field's type and when it is null: ``log_e_pos_<t>``, ``log_e_neg_<t>`` The log wealth (``log E``) of the two gamblers of *The update*, one betting that the target is positive and one that it is negative. 0 is no evidence, and ``log(20)``, about 3.0, is level 0.05. ``n_pos_<t>``, ``n_neg_<t>`` The signs counted so far (``Int64``). A zero or null target bets nothing and counts nothing. ``weight_sum`` The weight the model has accumulated before the row, decayed by nothing: the count of rows before it. ``settled_frac`` Always null, since nothing decays. ``withheld_reason`` Why the row's fields were withheld: null on every row at the default ``min_weight`` of 0, and ``below_min_weight`` where a ``min_weight`` given is not yet reached. With ``a`` and ``b``, these fields take the place of ``log_e_pos_<t>``, ``log_e_neg_<t>``, ``n_pos_<t>`` and ``n_neg_<t>``: ``log_e_a_<t>``, ``log_e_b_<t>`` The log wealth of the gambler betting that ``a`` is closer on the next row, and of the one betting that ``b`` is: ``log_e_a_<t>`` past ``log(1/alpha)`` is evidence at level ``alpha`` that ``a`` beats ``b``. ``wins_a_<t>``, ``wins_b_<t>`` The rows so far on which ``a`` was closer, and on which ``b`` was (``Int64``). A tie, or a row where either side is null, counts for neither. There is no ``coef``, and no diagnostic that reads residuals applies, since the model makes no prediction. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), ``TypeError`` for ``features``, which this model does not take, and ``ValueError`` naming the problem for: - ``weight``, ``half_life`` or ``lam``; - ``a`` without ``b`` or the reverse, and a suffix without them; - ``a`` and ``b`` naming the same spec with no suffix or the same one, or either naming this spec. The bank refuses, by name, when it is built: a side that is not in the bank or is itself a ``seqtest``, and a target either side has no residual for. .. rubric:: The update The model keeps, per target, the wealth of two gamblers: ``E_pos`` bets that the next sign is positive, and ``E_neg`` that it is negative, each 1 at the first row. The row's value is reduced to its sign ``s`` in ``{-1, 0, +1}``. ``n_pos`` and ``n_neg`` are the counts of positive and negative rows before this one, and ``n = n_pos + n_neg``: .. code-block:: text stake_pos = max(0, (n_pos - n_neg) / (n + 1)) E_pos *= 1 + stake_pos * s stake_neg = max(0, (n_neg - n_pos) / (n + 1)) E_neg *= 1 - stake_neg * s The stakes are computed from the rows before. ``(E_pos + E_neg) / 2`` is the two-sided e-value (*The guarantee* in Notes). .. rubric:: Example This code tests two targets, one positive half the time and one 58% of the time, and prints the most evidence each reached and the first row where it passed level 0.05: .. code-block:: python import numpy as np rng = np.random.default_rng(3) fair = rng.standard_normal(2_000) # positive half the time up = 0.2 + rng.standard_normal(2_000) # positive 58% of the time pl.DataFrame({"fair": fair, "up": up}).write_parquet("signs.parquet") sign = rp.spec.seqtest("sign", targets=["fair", "up"]) out = pl.scan_parquet("signs.parquet").rheon.fit_predict([sign]).collect() out = out.unnest("sign") for t in ["fair", "up"]: e = out[f"log_e_pos_{t}"] crossed = (e >= np.log(20)).arg_true() # level 0.05 first = crossed[0] if len(crossed) else None print(f"{t}: largest log_e_pos {e.max():.2f}, first row past log(20): {first}") .. code-block:: text fair: largest log_e_pos 0.51, first row past log(20): None up: largest log_e_pos 19.81, first row past log(20): 46 .. rubric:: See also - :func:`rheon.polars.eval.seqtest`, the same computation in Polars expressions over a frame in memory. - :func:`rheon.polars.eval.compare_specs`, several specs' scores in one table. .. rubric:: Notes **The stake.** ``(n_pos - n_neg) / (n + 1)`` is ``2p - 1`` for the Krichevsky-Trofimov estimate ``p = (n_pos + 1/2) / (n + 1)`` of ``P(s = +1)``. That is the stake a gambler with a ``Beta(1/2, 1/2)`` prior puts on the next sign, clipped so that each side bets only on the direction it tests. **The guarantee.** Under the null (given everything before it, a row is at least as likely to be negative as positive), ``E_pos`` is a non-negative supermartingale with ``E_pos[0] = 1``. Ville's inequality then gives ``P(max_t E_pos[t] >= 1/alpha) <= alpha``. That is the whole guarantee. ``log_e_pos >= log(1/alpha)`` on any row rejects "no more positives than negatives" at level ``alpha``, and the stream can be read at every row and stopped the moment it crosses. A p-value cannot be: checking it repeatedly inflates its error rate. Nothing about the target but its sign is assumed: no independence of the sizes, no bound, no variance. What it does not test is the size: a stream up by a hair 60% of the time and down by a mile the rest rejects. """ model: dict[str, Any] = { "type": "seqtest", "a": a, "b": b, "a_suffix": a_suffix, "b_suffix": b_suffix, } return _common(name, model, targets=targets, features=[], **common)
[docs] @_checked def marginal( name: str, *, targets: TargetList, features: list[str], lags: list[int] | None = None, cross_lags: list[int] | None = None, serial_rule: Literal["truncated", "bartlett", "geometric"] | None = None, bins: int | None = None, bin_rule: Literal["quantile", "fixed"] | None = None, bin_warm_rows: int | None = None, bin_edges: dict[str, list[float]] | list[list[float]] | None = None, bin_budget: float | None = None, bin_stat: Literal["mean", "huber"] = "mean", bin_huber_delta: float | None = None, bin_refit_rows: int | None = None, refit_budget: float | None = None, shards: int | Literal["auto"] | None = None, window_size: float | Duration | None = None, closed: Literal["right", "both"] = "right", snapshot_every: float | Duration | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal["thin", "refuse"], float] | None = None, window_lags: bool = False, feature_moments: Literal["per_target", "shared"] = "per_target", **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Each feature's exponentially weighted moments with each target, read back as a table. Use it to screen thousands of features against a few targets in one pass: each pair ``(x_j, y_t)`` is its own two-column :func:`ew_cov`, so a row takes ``O(p * T)`` time for ``p`` features and ``T`` targets, where one ``ew_cov`` over every column takes ``O((p + T)²)``. Use :func:`ew_cov` for the joint covariance of a few columns, and :func:`ewridge` or :func:`lasso` for a joint fit of the target on every feature. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight`` and ``group``, are in :mod:`rheon.spec`. ``coef_every`` and ``max_rows_between_coefs`` are refused, as there are no coefficients, and ``fit_intercept`` has nothing to act on. The model makes no prediction, so no diagnostic that reads residuals applies, and each such switch is refused by name. A column may not be both a target and a feature. ``min_weight`` defaults to 3: two rows give a correlation of ±1 whatever the data, and three give the first one with content. Below a target's ``min_weight`` its pairs' ``corr``, ``beta``, ``t_stat``, ``t_stat_serial``, lag correlations, ``phi_x``, ``phi_y`` and split (``split_gain``, ``split_at`` and ``split_gain_t``) are null, and so is every pair's while ``settled_frac`` is below ``min_settled_frac``. The moments and ``n_serial`` are reported either way. This model's own: ``lags``, ``cross_lags``, ``serial_rule`` The pair's moments at each lag of ``lags`` too: a strictly increasing list, each lag at least 1 and at most 2^20 (1,048,576), since the ring of rows is sized before the first row. Default none, no lags. A lag counts learned rows within the group, not rows where that target was present, since the ring is shared: for a sparsely present target the lag is a row distance, not an observation distance. They add four list columns per pair to the table. ``lag_corr_xx`` and ``lag_corr_yy`` are the two series' own autocorrelations. ``lag_corr_xy`` is the feature now against the target ``l`` rows back, and ``lag_corr_yx`` the target now against the feature ``l`` rows back (*Leads and lags* in Notes). The pair is the same statistic ``ew_cov(lags=)`` computes, to the bit. As there, a lagged moment starts at 0 and takes its first product when a learned row has one ``l`` rows back, so each lag reads 0.0, not null, while a group has learned no more than ``l`` rows. Below ``min_weight`` the lag correlations are null, as ``corr`` is, and so are ``phi_x`` and ``phi_y``, which are fitted from them. ``cross_lags`` keeps the two cross-correlations at fewer lags: strictly increasing, each one of ``lags``, and ``[]`` for none, which leaves the ``lag_corr_xy`` and ``lag_corr_yx`` columns out. By default they are kept at every lag. ``lag_corr_xy`` and ``lag_corr_yx`` are then lists over ``cross_lags``, in its order. The autocorrelations, and ``n_serial`` built from them, are kept at every lag whatever it says, and are the same to the bit. A lead or lag of a row or two is the usual question, and the cross terms are two thirds of the lag work. ``lags=[1, 2, 5, 10, 20, 50], cross_lags=[1]`` keeps the serial correction over fifty rows and the lead and lag at one row, at eight lagged moments per pair instead of eighteen. ``serial_rule`` turns the lags into a count of rows that allows for serial dependence, ``n_serial``, and ``t_stat_serial``, the statistic against it (*The serial count* in Notes). Default none: no ``n_serial`` or ``t_stat_serial``. The rule says how the count sums the kept lags: .. list-table:: :header-rows: 1 :widths: 16 50 34 * - rule - the bracket - ``n_serial`` and ``t_stat_serial`` null when * - ``"truncated"`` - the kept lags as they are - the bracket is zero or below (two series whose autocorrelations have opposite signs) * - ``"bartlett"`` - lag ``l`` weighted by ``1 - l / (L + 1)``, ``L`` the longest kept lag, as Newey and West do: the long lags, whose estimates are the noisiest, count less, and over every lag ``1..L`` the bracket stays positive where the lagged products form a positive-definite sequence - with lags missing it can still reach zero, as under ``"truncated"`` * - ``"geometric"`` - ``rho(l) = phi^l`` fitted per series by least squares on ``log rho`` over the kept lags with ``rho > 0``, and the tail summed in closed form: the right choice when both series are exponentially weighted, and the reason the lags need not be dense; the fitted ``phi_x`` and ``phi_y`` are reported - fewer than two kept lags are positive on either side ``bins``, ``bin_rule``, ``bin_warm_rows``, ``bin_edges``, ``bin_budget`` The nonlinear view. Every statistic of a pair named so far (``corr``, ``beta``, ``t_stat`` and the lag correlations) is linear, and a feature can be strongly related to a target with ``corr`` at zero: a threshold, a V, a saturation. Default none: no bins. With ``bins = 16`` each pair also reports the target's weight, mean and variance inside each of the feature's bins, its response curve, in ``bin_edges``, ``bin_n``, ``bin_mean_y`` and ``bin_var_y``. It reports the best single cut of that curve too. ``split_gain`` is the fraction of the target's variance the cut removes, a regression stump's gain, directly comparable with ``corr²``. ``split_at`` is where it falls. ``split_gain_t`` is the ``t_stat`` a ``corr`` would need to match it. Read ``split_gain_t`` as a ranking, not a p-value: the cut was chosen by maximizing over ``bins - 1`` candidates, which the statistic does not know. It uses ``n_serial`` in place of ``n_kish`` when ``serial_rule`` gives one. The edges are fixed once and never move, so a bin means the same thing for the life of the stream. ``bin_edges`` sets them outright, as a list per feature in ``features`` order or a dict keyed by feature name: exact, and comparable across runs and groups. ``bins``, ``bin_rule`` and ``bin_warm_rows`` describe learning them, and are refused beside it. Otherwise they are learned from the first ``bin_warm_rows`` learned rows (default 1,000) under ``bin_rule``. ``"quantile"`` (the default) gives equal weight per bin. A value that carries more than a bin's share, such as an indicator's zero, fills a bin of its own, and the remaining bins share what is left. ``"fixed"`` gives equal widths between the smallest and largest value seen. A feature keeps only the bins it can support, so the lists are ragged: a binary feature gets two bins whatever ``bins`` says, and a constant one a single bin and no split. Until the edges are fixed the bin columns are empty and the split columns null (*The warm-up of the bins* in Notes). ``bin_budget`` bounds the memory, per group, and per half-life when ``half_life`` is a list (every one keeps its own): .. list-table:: :header-rows: 1 :widths: 44 56 * - what - about * - the hold, until the edges are fixed - ``bin_warm_rows * (8 * features + 16 * targets + 64)`` bytes * - the histogram, for good - ``32 * features * targets * bins`` bytes Each is refused up front past ``bin_budget`` MiB, 256 by default and ``float("inf")`` for no bound. At the warm-up's last row the two exist at once, while the held rows are replayed into the histogram, so that row's peak is their sum. ``bin_stat``, ``bin_huber_delta`` Each bin's location. ``"mean"``, the default, is the weighted mean, which one spike in a thin bin moves by its size times its share: a row of 50 among twenty rows near 0 moves it by 2.4, a shape where there is none. ``"huber"`` is Huber's M-estimate of location, learned in one pass (*The update*): a row's weight is cut back by how far it lies from the bin's location before it, as :func:`huber` weighs a regression's rows. ``bin_huber_delta`` is the cut in units of the target's robust scale, default 1.345, :func:`huber`'s, and above 0. ``float("inf")`` clips nothing, which is the mean to the bit. Under ``"huber"``, ``bin_mean_y`` is the location and ``bin_n`` the rows' weight, as under the mean. ``bin_var_y`` is the weighted mean square of the deviations clipped at the cut, the variance where nothing is clipped. ``split_gain`` is read from those (*The Huber location* in Notes). ``bin_refit_rows``, ``refit_budget`` The refit of the first rows under ``"huber"``: once ``bin_refit_rows`` learned rows (rows of positive weight) are in, every target's location and scale and every bin's location are refit to the converged batch fit of those rows, once (*The refit of the first rows* in Notes). The default is ``max(500, 30 * bins)``, ``bins`` the most any feature has: a bin needs about 30 rows at the refit. ``0`` turns the refit off. Under ``"mean"``, or ``bin_huber_delta=inf``, there is nothing to refit, so the default is 0, and either key given is refused. ``refit_budget`` bounds the rows the refit holds over all of a spec's groups, in MiB, 320 by default and ``float("inf")`` for no bound. Each new group reserves its hold when it first appears. The group that would pass the bound keeps the one pass, as does every new group after it. A readiness warning says so once, and :meth:`rheon.polars.ModelBank.summary`'s ``refit_given_up`` counts their targets. ``shards`` Split the pair work across the bank's threads: a count of ranges of features, or ``"auto"`` for as many as the width keeps busy. Default none, so the pairs run row by row on the group's thread. The threads are the bank's, which the bank's ``threads`` sizes: ``shards`` cuts one spec's work so that more of them can take it, and never adds a thread. Every number is the same to the bit whatever the count, so it is a setting and not part of the state (*Shards* in Notes). ``window_size``, ``closed`` A hard window on the rows the pairs are computed from, in clock units, as for :func:`ewridge`: a row ``window_size`` old or older counts for nothing, and ``closed="both"`` keeps the one exactly that old. Inside the hard window the weights are still exponential. Every moment a pair is built from is cut at the hard window (the weight, both means and the three centered second moments), so ``corr``, ``beta`` and ``t_stat`` describe the hard window and nothing else. That matters most for a screen: two regimes of opposite sign average to nothing over a long history. The ``weight_sum`` the output column writes and the one the table reports are the weight inside the hard window. ``lags`` under a hard window take ``window_lags=True`` (its entry gives the memory). ``bins`` or ``bin_edges`` and ``window_size`` are refused together, since each snapshot would hold the whole histogram. ``snapshot_every``, ``max_rows_between_snapshots``, ``window_budget`` As for :func:`ewridge`: ``snapshot_every`` spaces the hard window's snapshots on the clock, in clock units, ``max_rows_between_snapshots`` caps the rows between them, whichever comes first, and ``window_budget`` bounds each ring in MiB. Each is refused without ``window_size``. ``window_lags`` Accept ``lags`` under a ``window_size``, and the memory that takes. Default ``False``. Each of the hard window's snapshots then also holds the lag moments, in doubles, for ``L`` lags, ``C`` cross lags, ``p`` features and ``T`` targets: .. list-table:: :header-rows: 1 :widths: 44 56 * - a snapshot holds - doubles * - without lags - ``(3*p + 5)*T`` * - the lag moments beside them - ``2*L*T + 2*(L + C)*p*T``, about ``2*(L + C) / 3`` times its size: the lagged products and, beside each lag, the lagged rows' own sums * - with ``cross_lags=[]``, the least - ``2*L*(p + 1)*T``; ``n_serial`` does not read the cross terms So, for many features, a snapshot is 2.3 times the size at one lag, and 7.7 times at five lags with the default cross lags (every lag). The snapshots count in ``window_budget``. Without ``window_lags``, ``lags`` and ``window_size`` together are refused with this spec's own numbers. ``window_lags=True`` without both ``window_size`` and ``lags`` is refused (*Lags under a hard window* in Notes). ``feature_moments`` Where the feature's mean and variance are kept. ``"per_target"``, the default, keeps them per pair, over the rows the pair's target was present. ``"shared"`` keeps one per feature, over every learned row, and each pair only its covariance (*The update*). Where every target is on every learned row the two report the same numbers, to the bit. Where a target is absent on some rows, ``"shared"`` is a different estimator: ``mean_x`` and ``var_x`` are the feature's over every learned row, and ``cov`` is the target's rows centered on that mean, so ``corr``, ``beta`` and ``t_stat`` move with it. That is sound where the absence says nothing about the feature (*Shared feature moments* in Notes). Refused with a ``window_size``. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of one field, ``weight_sum``: the weight the model has accumulated before the row and before the row's own decay. `docs/OUTPUTS.md#marginal <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#marginal>`_ gives its type. The pairs live in the state, and :meth:`rheon.polars.ModelBank.marginal` reads them: one row per (group, instance, feature, target), an instance being the part of the model that fits one half-life, with the moments, ``corr``, ``beta``, ``t_stat``, ``n_kish``, and the columns ``lags`` and ``bins`` add. That method documents every column. A group that closes writes the same pairs to :meth:`rheon.polars.ModelBank.closed_groups` as ``pair_*`` columns, one entry per pair. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), and ``ValueError`` naming the problem for: - ``bin_edges`` that miss or add a feature, that are not finite and increasing, or that give no feature an edge (every feature one open bin, with no response curve and no cut; one feature without edges beside others is taken, and reports a single bin); - ``bins``, ``bin_rule`` or ``bin_warm_rows`` beside ``bin_edges``, ``bin_rule`` or ``bin_warm_rows`` without ``bins``, and ``bins`` or ``bin_edges`` beside ``window_size``; - ``bins`` below 2, or a ``bin_warm_rows`` below ``bins``; - an empty ``lags`` (leave ``lags`` out for none), ``serial_rule`` or ``cross_lags`` without ``lags``, ``lags`` or ``cross_lags`` that do not increase, a lag below 1 or past 2^20, and a cross lag not in ``lags``; - ``lags`` beside ``window_size`` without ``window_lags``, and ``window_lags`` without both; - ``bin_budget`` without bins or not above 0, and bins past ``bin_budget``; - ``bin_stat="huber"`` without bins, and ``bin_huber_delta`` under ``"mean"`` or not above 0; - ``bin_refit_rows`` or ``refit_budget`` under ``"mean"`` or ``bin_huber_delta=inf``, and a ``refit_budget`` not above 0; - ``shards`` below 1, or a string other than ``"auto"``; - ``feature_moments="shared"`` beside ``window_size``; - a ``serial_rule``, ``bin_rule``, ``bin_stat`` or ``feature_moments`` not in the list; - a ``window_size`` not finite or not above 0, a ``closed`` of ``"left"`` or ``"none"``, a ``snapshot_every`` below 0 or not finite, a ``max_rows_between_snapshots`` below 1, a ``window_budget`` that is not one key, ``"thin"`` or ``"refuse"``, or whose MiB is not above 0, and ``closed="both"``, ``snapshot_every``, ``max_rows_between_snapshots`` or ``window_budget`` without ``window_size``. .. rubric:: The update Per row, ``w`` is the row's weight and ``λ = 0.5 ** (Δclock / half_life)`` its decay (``lam ** Δclock`` under ``lam``), ``Δclock`` the clock's step since the last row the model did not skip, capped at ``gap_cap`` (or ``session_gap`` at a session change). Per target ``t``, on a row where ``y_t`` is present, with ``W_t`` the target's weight before the row, ``Q_t`` the sum of its squared weights, ``m_y`` and ``m_x[t,j]`` the means and ``S_yy``, ``S_xx`` and ``S_xy`` the centered second moments, each a weighted mean: .. code-block:: text W'_t = λ * W_t + w a = λ * W_t / W'_t b = w / W'_t Q'_t = λ^2 * Q_t + w^2 S'_yy = a * S_yy + a * b * (y_t - m_y)^2 S'_xx[t,j] = a * S_xx[t,j] + a * b * (x_j - m_x[t,j])^2 S'_xy[t,j] = a * S_xy[t,j] + a * b * (x_j - m_x[t,j]) * (y_t - m_y) m' = m + b * (value - m) for m_y and each m_x[t,j] The deviations are from the means before the row. A null target decays that target (``W_t *= λ``, ``Q_t *= λ^2``) and learns nothing for it, and a null feature skips the row. Under ``feature_moments="shared"``, ``a`` and ``b`` are the row's mix over the model's weight ``W``, taken on every learned row, and ``a_t``, ``b_t`` the target's: .. code-block:: text dx_j = x_j - m_x[j] the shared mean before the row S'_xx[j] = a * S_xx[j] + a * b * dx_j**2 m_x[j] += b * dx_j S'_xy[t,j] = a_t * S_xy[t,j] + a_t * b_t * dx_j * (y_t - m_y) on t's rows Under ``bin_stat="huber"``, a bin's location ``m`` and its weight ``Omega`` move as: .. code-block:: text c = bin_huber_delta * sigma_t the cut omega = w * min(1, c / |y - m|) Omega' = λ * Omega + omega m' = m + (omega / Omega') * (y - m) ``sigma_t`` is the target's robust scale, read before the row: the exponentially weighted median of ``|y - m_t|`` over 0.6745, ``m_t`` the target's own location by the same recursion. .. rubric:: Example This code screens three features against a target that moves with ``x0``, not at all with ``x1``, and by a step where ``|x2|`` passes 1, which no correlation sees. It prints each pair's ``corr`` and the gain of its best cut: .. code-block:: python import numpy as np rng = np.random.default_rng(4) x0, x1, x2 = rng.standard_normal((3, 5_000)) y = 0.5 * x0 + np.where(np.abs(x2) > 1.0, 1.0, -0.5) + rng.standard_normal(5_000) pl.DataFrame({"x0": x0, "x1": x1, "x2": x2, "y": y}).write_parquet("screen.parquet") pairs = rp.spec.marginal( "pairs", targets=["y"], features=["x0", "x1", "x2"], half_life=float("inf"), bins=8, # each pair's response curve, and its best cut ) bank = rp.ModelBank([pairs]) bank.fit(pl.scan_parquet("screen.parquet")) # learn every row, keep no output for r in bank.marginal("pairs").iter_rows(named=True): print(f"{r['feature']}: corr {r['corr']:+.2f}, split_gain {r['split_gain']:.2f}") .. code-block:: text x0: corr +0.38, split_gain 0.09 x1: corr +0.00, split_gain 0.00 x2: corr -0.00, split_gain 0.08 .. rubric:: See also - :meth:`rheon.polars.ModelBank.marginal`, the table of pairs and every column it holds. - :func:`ew_cov`, the joint covariance whose arithmetic each pair uses. - :func:`huber`, whose weighting ``bin_stat="huber"`` gives each bin. .. rubric:: Notes **Against ew_cov.** The arithmetic is ``ew_cov``'s, so a pair's means and variances equal those an ``ew_cov(bias=True)`` over the two columns reports, to the bit, and its ``cov`` and ``corr`` agree with that ``ew_cov``'s within a few roundings. The pair's variances and ``cov`` are the weighted means as kept, with no correction for bias, where ``ew_cov``'s default ``bias=False`` multiplies them by its correction. The pair rounds each row's product as ``(a * b * (x_j - m_x)) * (y_t - m_y)``, and ``ew_cov``, which keeps one triangle of its symmetric matrix, multiplies the other way round. **Leads and lags.** For two series that describe the same moment, a feature whose ``lag_corr_yx[0]`` exceeds its ``corr`` leads the target, and one whose ``lag_corr_xy[0]`` does follows it. That reading does not hold against a target that looks ahead, one built from the rows after its own. There the target ``l`` rows back is built partly from the feature's newest ``l`` rows, so a feature built from the same news shows ``lag_corr_xy`` above ``corr`` however it is sampled. **The serial count.** ``t_stat`` is built on ``n_kish``, which is right for unequal weights and silent about serial dependence. On a smooth stream consecutive rows are nearly the same observation, and the variance of a sample correlation is not ``1/n`` but ``[1 + 2 * sum_l rho_x(l) * rho_y(l)] / n`` (Bartlett 1935). ``n_serial`` is ``n_kish`` divided by that bracket, and ``t_stat_serial`` the statistic against it. It was measured on 1,000 pairs of independent AR(1) series, ``phi_x = 0.9`` and ``phi_y = 0.8``, each 3,000 rows with no decay, ``lags = [1, 2, 3, 5, 8, 13]`` and ``"geometric"``. There ``t_stat`` spread with a standard deviation of 2.52, near Bartlett's ``sqrt(1 + 2 * 0.72 / (1 - 0.72)) = 2.48``, and passed 1.96 on 45% of them: significance that is not there. ``t_stat_serial`` spread 1.04 and passed on 5.4%, its ``n_serial`` a median 511 of ``n_kish = 3000``. The lags add ``(L + 2C) * p * T + L * T`` doubles beside the pair moments, for ``L`` lags of which ``C`` keep the cross terms. They also hold a ring of ``max(lags)`` learned rows. **The warm-up of the bins.** The rows of the bins' warm-up are held, not spent. The moment the edges exist every one of them is replayed with its own decay, so the histogram is what it would have been had the edges been known before the first row. That holds to the bit, or to about 1e-15 of the data's scale where rows of weight zero fall inside the warm-up, whose decays are carried to the next held row as one product. Decay reaches the histogram as it reaches the pair moments, so a clock step capped at ``gap_cap`` decays it by the same factor as them. The bins take ``O(bins)`` of state per pair, one search of the edges per feature per row, and a constant per pair. **The Huber location.** Its fixed point is the Huber M-location of the bin's decayed sample, and one row moves it by at most ``c * w / Omega'``, that is ``c * w / (λ * Omega + omega)``. The scale ``sigma_t`` is one per target, not per feature: a cut is for a row far from the target's spread, the same row whichever feature bins it, and per feature it would take a quantile sketch per pair. The sketch keeps each deviation in units of the first, as :func:`huber`'s does, so a rescaled target rescales the cuts and the locations to rounding. A bin's first row is judged against ``m_t``. Until the target has a scale above 0, its first two rows, nothing is clipped, as :func:`huber` down-weights nothing before its scale exists. It was measured against statsmodels' batch M-location of each bin on 20,000 rows in 16 bins, with no decay and spikes of 50 on 1%, 5% and 12% of the rows, the worst of five seeds. With the default refit of the first 500 rows it lands within 0.0002, 0.0012 and 0.003 of the target's scale, and in one pass with no refit (``bin_refit_rows=0``) within 0.0008, 0.002 and 0.03, where the mean is off by 0.45, 1.5 and 3. It keeps a fifth more per cell, 40 bytes in place of 32, and up to 9 KB per target, and a row takes 0.75 to 0.9 times the mean's throughput. **The refit of the first rows.** One pass weighs each row against the location and the scale before it, and over the first rows those are still moving. A share of spikes then pulls the first locations, the scale learns the pulled deviations, the cut is drawn wide, and the spikes go on entering at nearly full weight. Without decay the bins stay there: captured. Measured on 16 bins with spikes of about 20 of the target's scales and no decay, the worst of 50 streams had a bin 1.3 scales from statsmodels' M-location after 2,000 rows at 12% spikes, and 3.5 at 20%. So the refit fits the target's location and MAD scale jointly, as statsmodels' ``RLM`` fits a constant with ``scale_est="mad"``. Its scale is rebuilt from the converged deviations, and each bin's location is solved exactly at the cut that scale gives. Then the stream goes on in one pass. The refit runs after the row is learned, on a count of rows, so it is the same whatever the chunking. It moves no weight: ``bin_n``, ``weight_sum`` and every pair moment are those of the one pass. With it the same worst streams were 0.015 and 0.14 scales away after 2,000 rows, and 0.004 and 0.057 after 20,000. A bin whose rows are mostly spikes at the refit has its location among them, rightly for those rows, and the rows after it bring it back only slowly. At 20% spikes, 12.5 rows a bin left 6 of 50 streams half a scale off after 20,000 rows, and 31 rows a bin left none. These figures are at the default cut, ``bin_huber_delta=1.345``. A wider cut converges more slowly: at 2.5 with 12% spikes, the worst of 50 streams was 0.30 scales off after 1,000 rows with the refit, against 1.25 without it. With learned edges the warm-up already holds its rows: the refit runs when the edges are fixed, over every held row, if the count is within ``bin_warm_rows``, and holds no row of its own. With ``bin_edges``, or a count past the warm-up, the model holds the rows until the count: ``bin_refit_rows * (8 * features + 16 * targets + 64)`` bytes per group, 4 MB at 1,000 features. The refit itself runs once, in about 1 ms at 10 features, 13 ms at 1,000 and 110 ms at 10,000 over 500 rows, and a row after it takes the time it took before the refit. **Shards.** The bank's threads run its groups and specs in parallel already, so one wide spec on one group is one thread's work while the rest wait. With ``shards`` its pairs are cut into ranges of features, and each range runs on a thread of its own, a block of rows at a time. A saved bank resumes under the count of the specs given to ``load``, or under the saved one when given none. ``"auto"`` sizes itself to the machine it runs on. It estimates the pair work of a block of rows from the width, the lags and the bins, and splits the block into as many ranges as hold a tenth of a millisecond each, up to twice the bank's threads. The moments alone of fewer than about 1,300 pairs stay whole. Through the bank at 10,000 features on 14 threads, ``"auto"`` ran 1.2 times as fast at one target and 4.9 times with nine targets, lags and bins. The bank's own work on each row does not split (measured on 2026-09-25). **Lags under a hard window.** Each lag correlation under a hard window is that of the rows inside it, each row's product with the row ``l`` back taken about the hard window's own means. The moments are kept about a fixed origin, each series' first value, and read about the hard window's means when asked. A hard window's first ``l`` rows take the rows before it as partners, where ``statsmodels``' ``acf`` of the hard window's rows stops its products at the edge: on 50 AR(1) series, 500 rows a hard window, the two parted by 0.0068 at most. **Shared feature moments.** With a tenth of a target's rows absent at a half-life of 69 rows, measured, ``corr`` moved by at most 0.0065 and ``var_x`` by 2.5% at the median. At 20,000 pairs ``"shared"`` runs 2.7 times as fast at ten targets and 3.2 times at thirty, the same at one, and a ten-target state is under half the size (measured on 2026-09-29). With ``lags`` it keeps the feature's autocovariance per feature too, and at ten targets runs 4.6 times as fast with no cross lags. """ edges: list[list[float]] | None # `spec "m":` as every other refusal, where these read `marginal 'm':` # (review 2026-10-06, YA6). who = _who(name) if isinstance(bin_edges, dict): # Both problems at once, where both hold. problems: list[Exception] = [] missing = [f for f in features if f not in bin_edges] if missing: problems.append( ValueError( f"{who}: bin_edges must give edges for every feature, but it has none for " f"{_listed([quoted(f) for f in missing])}. Add a list of edges for each, " "or pass a list of lists in the order of features." ) ) extra = [f for f in bin_edges if f not in features] if extra: problems.append( ValueError( f"{who}: bin_edges must name only features, but it names " f"{_listed([quoted(f) for f in extra])}, which " f"{'is not a feature' if len(extra) == 1 else 'are not features'}. " f"Remove {'it' if len(extra) == 1 else 'them'} from bin_edges, or add " f"{'it' if len(extra) == 1 else 'them'} to features." ) ) if problems: raise refusal(who, problems) edges = [list(bin_edges[f]) for f in features] elif bin_edges is not None: edges = [list(e) for e in bin_edges] if len(edges) != len(features): raise ValueError( f"{who}: bin_edges must hold one list of edges for each feature, " f"{len(features)} in all, but it holds {len(edges)}. Give one list for each " "feature, in the order of features." ) else: edges = None model: dict[str, Any] = { "type": "marginal", "lags": lags, "cross_lags": cross_lags, "serial_rule": serial_rule, "bins": bins, "bin_rule": bin_rule, "bin_warm_rows": bin_warm_rows, "bin_edges": edges, "bin_budget": bin_budget, "bin_stat": None if bin_stat == "mean" else bin_stat, "bin_huber_delta": bin_huber_delta, "bin_refit_rows": bin_refit_rows, "refit_budget": refit_budget, "shards": shards, "window_size": window_size, "closed": closed, "snapshot_every": snapshot_every, "max_rows_between_snapshots": max_rows_between_snapshots, "window_budget": window_budget, "window_lags": window_lags or None, "feature_moments": None if feature_moments == "per_target" else feature_moments, } # The keys the Rust spec skips when absent are written only when given, # as `holt`'s `trend` is, so `ModelBank.specs` is the dict made here. skipped = _SKIPPED_WHEN_ABSENT["marginal"] model = {k: v for k, v in model.items() if v is not None or k not in skipped} return _common(name, model, targets=targets, features=features, **common)
[docs] @_checked def deco( name: str, *, features: list[str], dynamics: Literal["ew", "linear"] = "ew", alpha: float | None = None, beta: float | None = None, blocks: dict[str, list[str]] | None = None, **common: Unpack[CommonKwargs], ) -> dict[str, Any]: """Engle and Kelly's dynamic equicorrelation, one number for the whole correlation matrix of the features. Use it to track how correlated many series are on average, at ``O(n)`` a row for ``n`` features, where keeping all ``n(n-1)/2`` correlations moving takes ``O(n²)``. Use :func:`ew_cov` for each pair's correlation, and this model's ``blocks`` for one number per block of features and per pair of blocks. .. rubric:: Parameters The stream parameters every builder takes, such as ``clock``, ``half_life``, ``gap_cap``, ``min_weight`` and ``group``, are in :mod:`rheon.spec`. This model reads ``features``, at least two, and takes no ``targets``. ``fit_intercept`` has nothing to act on, as there is no regression, and each switch that reads residuals is refused, as is ``emit_feature_health``. ``half_life`` or ``lam`` is required: both the standardizer and the level decay on it. This model's own: ``dynamics`` How the level follows the rows' estimates: ``"ew"`` (the default, since it runs on the clock and needs no parameters of its own), an exponentially weighted mean of them on the clock, or ``"linear"``, the linear dynamics of *The update*, which step once per row. ``"linear"`` needs ``alpha`` and ``beta``, and ``"ew"`` refuses them. ``alpha``, ``beta`` The linear dynamics' weights on the row's estimate and on the previous level, each at least 0, with ``alpha + beta < 1``. Default none: required under ``"linear"``, refused under ``"ew"``. ``blocks`` A name to a subset of ``features``: the model then estimates one number per block and one per pair of blocks, which is the useful middle between one correlation and all of them. Every feature must be in exactly one block, and a block needs at least two. Default none: one block of every feature. .. rubric:: Output One output column, named after the spec, whose value in each row is a record of these fields, all but ``coef`` read from the state before the row, so they are safe as features for that same row. `docs/OUTPUTS.md#deco <https://github.com/rheon-dev/rheon/blob/main/docs/OUTPUTS.md#deco>`_ gives each field's type and when it is null: ``u`` The row's own estimate of the equicorrelation. Null on a row where fewer than two of its block's columns have a positive variance before the row, or where every standardized value is 0. ``rho`` The level as it stood before the row. ``loglik`` The row's Gaussian log-density in standardized coordinates under that level. Null on a row where any column has no positive variance before the row, and where the levels hold no correlation matrix that the density can be solved for (*Blocks* in Notes). ``weight_sum`` The weight the model has accumulated before the row and before the row's own decay. ``settled_frac`` How far the model had come toward its steady state under decay before the row, null where nothing decays. ``withheld_reason`` Why the row's fields were withheld, null where they were not: ``below_min_weight`` on the rows before ``weight_sum`` reaches ``min_weight``. A field the model has no value for yet reads null with no reason beside it: ``u`` until a block's columns have a variance (the first two rows of a group), and ``rho`` until the row after the first ``u``. The default ``min_weight`` withholds those rows anyway. ``coef`` The levels after the row, in the order of the ``rho`` fields: ``coef`` on a row is ``rho`` on the next. With ``K`` named blocks, ``u`` becomes ``u_<A>`` per block then ``u_<A>_<B>`` per pair, and ``rho`` likewise, with one ``loglik`` over all of them. .. rubric:: Raises As every builder does (:mod:`rheon.spec`), ``TypeError`` for ``targets``, and ``ValueError`` naming the problem for: - fewer than two features, or no ``half_life`` or ``lam``; - a ``dynamics`` other than ``"ew"`` or ``"linear"``; - ``alpha`` or ``beta`` under ``"ew"``, either missing under ``"linear"``, either below 0 or not a number, and ``alpha + beta`` of 1 or more; - ``blocks`` that name no block, leave a feature out of every block, put one in two, list one twice in a block, name a column not in ``features``, or hold a block of fewer than two; - a switch that reads residuals, such as ``emit_sigma``, and ``emit_feature_health``. .. rubric:: The update The row is standardized against the means ``m_i`` and variances ``v_i`` that exponentially weighted running sums hold before the row, ``zeta_i = (x_i - m_i) / sqrt(v_i)``. With ``S1 = sum(zeta)`` and ``S2 = sum(zeta * zeta)`` over the ``n`` features, the row's estimate is Engle and Kelly's Lemma 2.3: .. code-block:: text u = (S1**2 - S2) / ((n - 1) * S2) = mean_{i != j} zeta_i zeta_j / mean_i zeta_i**2 which lies in ``[-1 / (n - 1), 1]``, both ends reached. Between two blocks ``A`` and ``B`` the estimate is ``u_AB = S1_A S1_B / sqrt(n_A n_B S2_A S2_B)``. The level then follows one of two dynamics, with ``w`` the row's weight and ``λ = 0.5 ** (Δclock / half_life)`` its decay (``lam ** Δclock`` under ``lam``). ``Δclock`` is the clock's step since the last row the model did not skip, capped at ``gap_cap``, or ``session_gap`` at a session change: .. code-block:: text "ew": W' = λ * W + w, b = w / W' rho' = rho + b * (u - rho) (rho = u at W = 0) "linear": rho' = (1 - alpha - beta) * rho_bar' + alpha * u + beta * rho rho' = u (on the first row) rho' = rho (at w = 0) where ``rho_bar`` is the ``"ew"`` recursion run alongside as the target of the linear one. .. rubric:: Example This code plants eight series whose pairs are correlated 0.2 for 10,000 rows and 0.6 after, and prints the level before the last row of each half. It moves with the correlation and stays below it, the estimate's downward bias (*The estimate's downward bias* in Notes): .. code-block:: python import numpy as np rng = np.random.default_rng(6) c = np.repeat([0.2, 0.6], 10_000) # the pairs' correlation, row by row common = rng.standard_normal(20_000) cols = { f"r{i}": np.sqrt(c) * common + np.sqrt(1 - c) * rng.standard_normal(20_000) for i in range(8) } pl.DataFrame(cols).write_parquet("returns.parquet") eq = rp.spec.deco("eq", features=list(cols), half_life=500.0) out = pl.scan_parquet("returns.parquet").rheon.fit_predict([eq]).collect().unnest("eq") print(f"correlation 0.2: rho {out['rho'][9_999]:.2f}") print(f"correlation 0.6: rho {out['rho'][-1]:.2f}") .. code-block:: text correlation 0.2: rho 0.15 correlation 0.6: rho 0.39 .. rubric:: See also - :func:`ew_cov`, every pair's correlation, at ``O(n²)`` a row. - :func:`corrchange`, a test for a change in a pair's correlation. .. rubric:: Notes **The clock.** The ``"ew"`` dynamics run on the clock. The linear one steps once per row, as a DCC model's does (Engle's dynamic conditional correlation, a GARCH-like recursion on the correlation matrix). So across a gap capped at ``gap_cap`` its own terms take one row's step, as across a millisecond, and only ``rho_bar`` moves on the clock. A row of weight 0 moves neither: it advances the clock and learns nothing, as everywhere. Otherwise the linear recursion has no row weights, as the paper's has none: a positive weight reaches ``rho`` only through ``rho_bar``, so rows of weight 0.5 and 2 move it by the same ``alpha * u``. **Departures from the paper.** Two from Engle and Kelly (2012), on purpose. Its eq. 21 has a free intercept and applies correlation targeting to the DCC ``Q`` recursion, not to the linear one. Writing the intercept as ``(1 - alpha - beta) * rho_bar`` is this library's reparameterization, chosen because a streaming model has no sample to fit a free intercept on. And the paper permits ``alpha + beta`` slightly above 1 under numerical bounds, where this model refuses it. **The estimate's downward bias.** The paper notes that ``u`` is a downward biased estimate of the equicorrelation (``E[u]`` is about 0.20 for a true 0.30 at ``n = 6`` series). It offers an alternative, ``1 - (1 / (n - 1)) * sum((zeta_i - zeta_bar)**2)``, which this does not compute. Use ``u`` as a signal that moves with the market's correlation, not as the correlation. ``rho`` is not an ``ew_cov``'s ``corr`` over the columns, since the mean of a ratio is not the ratio of means. **A constant column.** A column whose variance is exactly zero, constant from its first row (the only way an exponentially weighted variance is exactly zero), has no standardized value. It is left out of its block's sums, so ``n`` counts the columns that have one. Its block reads the correlation among its other columns, and so does a pair it is in. A block left with fewer than two has no ``u`` on the row, nor a pair with an empty side. Nor does a row whose ``S2`` is 0. Each value keeps its own weight ``W``: one with no ``u`` on a row learns nothing and does not decay, while the others learn. ``loglik`` needs every column, and is null on such a row. **Blocks.** ``loglik`` is null where the levels hold no correlation matrix, or hold one too close to singular for its density to keep a digit: each level can be inside ``(-1, 1)`` while the blocks' levels together are not. Then the factor of the ``K x K`` system the density solves needs a shift on its diagonal, or its condition passes the point where the solve's forward-error bound reaches 1. Such levels come from the first rows of a warm-up, when they rest on one or two rows. One block never reaches that point. """ model: dict[str, Any] = { "type": "deco", "dynamics": dynamics, "alpha": alpha, "beta": beta, # `{}` as `[]`, refused by name as `feature_sets={}` is (YA5). "blocks": [[k, list(v)] for k, v in blocks.items()] if blocks is not None else None, } targets = _mirror_target(name, "deco", features, common, "its equicorrelation is over") return _common(name, model, targets=targets, features=features, **common)
#: The model types with no target column: their outputs are read from the #: state before each row, their ``targets`` mirror ``features[0]`` for the #: plumbing, and nothing residual-based applies to them. ``ew_class`` is #: not one -- its label column travels as the target -- though it predicts #: no number either, and refuses the residual switches the same way. # The changepoint detectors', the classifier's, the clustering models', the regimes', the realised # covariance's, the robust regressions', `sgd`'s and the trend's builders live in files of their own # (the 250 KB cap); read back here, # after everything they use, for `__all__`, the key tables below and # `rheon.spec`. from rheon._spec_audit import audit # noqa: E402 from rheon._spec_changepoint import bocpd, corrchange # noqa: E402 from rheon._spec_class import ew_class # noqa: E402 from rheon._spec_cluster import kmeans, micro # noqa: E402 from rheon._spec_expectile import expectile # noqa: E402 from rheon._spec_garch import garch # noqa: E402 from rheon._spec_glm import glm # noqa: E402 from rheon._spec_gradient import sgd # noqa: E402 from rheon._spec_point import hawkes # noqa: E402 from rheon._spec_regimes import hmm, rcov # noqa: E402 from rheon._spec_robust import huber, quantile # noqa: E402 from rheon._spec_trend import holt # noqa: E402 UNSUPERVISED = frozenset( {"ew_cov", "kmeans", "micro", "deco", "rcov", "hmm", "corrchange", "bocpd", "audit"} ) _NUMERIC_KEYS = _numeric_keys() _CLOCK_KEYS = _clock_keys() # The field helpers live beside this module, which they read (its _json), # and stay importable from here. from rheon import _spec_fields # noqa: E402 output_fields = _spec_fields.output_fields output_index = _spec_fields.output_index coef_fields = _spec_fields.coef_fields coef_index = _spec_fields.coef_index _coef_index_schema = _spec_fields._coef_index_schema