rheon.spec.audit¶
- rheon.spec.audit(name: str, *, columns: list[str], pairs: bool = False, distinct_cap: int | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A count of what a stream’s columns hold, read in one pass by a spec that fits nothing and predicts nothing.
Use it to find what a model cannot tell you, such as a column that is
-999on a twentieth of its rows, a feed that stopped with its last value carried forward, or a price level where a change was meant. Run it alone before choosing a model, or beside the models in the same pass (rp.ModelBank([audit, model])), andrheon.polars.ModelBank.check()reads its counts and says so. Usedescribe()for a few statistics of the columns a model has already been fed.Parameters
The stream parameters every builder takes, such as
clock,groupandsession, are inrheon.spec.gap_capis required with aclock, as for every spec, and is the line a gap is counted at. An audit takescolumnsin place oftargetsandfeatures.fit_intercepthas nothing to act on, as there is no regression. An audit counts and does not fit, so it refuses these:refused
why
half_life,lamnothing decays
weighta value is a value whatever its row weighs. To audit a weight column, list it in
columnsembargo,label_clockthere is no target to wait for
min_weightthere is no prediction to withhold
group_closea closed group’s counts would leave the bank with it, where
audit()andcheck()cannot read themThis model’s own:
columnsThe columns to audit, any number, each once. They are a spec’s
featuresin the bank’s tables (describe()lists them with role"feature"). Required, and not empty.pairsKeep each pair of columns’ correlation and the rows on which the two are equal, which
check()reads for itsduplicatefinding. Memory and work grow ask^2forkcolumns. DefaultFalse.distinct_capThe number of counters each column keeps. The distinct count is exact up to this many values, and the most repeated value’s count within
n / (distinct_cap + 1)past it.None(the default) is 256, where a value on 3% of a continuous column’s rows was found on ten seeds of ten as a sentinel; at 1,024 one on 2% was. At least 1 and at most 65,536.
Output
One output column, named after the spec, whose value in each row is a record holding
weight_sumalone, the count of rows before this one. docs/OUTPUTS.md#audit gives its type. An audit predicts nothing, so what it counted is read back withrheon.polars.ModelBank.audit(), one row per column (and withtable="pairs"andtable="clock"), and judged byrheon.polars.ModelBank.check(). What it counts in Notes defines each measurement.Raises
As every builder does (
rheon.spec),TypeErrorfortargetsand forfeatures, which an audit callscolumns, andValueErrornaming the problem for:an empty
columns, or one that names a column twice;half_life,lam,weight,embargo,label_clock,min_weightorgroup_close;a
distinct_capoutside 1 to 65,536.
The update
Per column, each row’s value
xis first classified: a null, a NaN,+inf,-infand a finite value past1e100in magnitude each add one to its own count, and anything else is usable. A usable value is added to the moments by Terriberry’s update of the central sumsM2,M3andM4, withnthe usable values before it:n' = n + 1 d = x - mean e = d / n' t = d * e * n mean' = mean + e M4' = M4 + t * e^2 * (n'^2 - 3 n' + 3) + 6 e^2 * M2 - 4 e * M3 M3' = M3 + t * e * (n' - 2) - 3 e * M2 M2' = M2 + t
and to its counter: a held value’s count adds one, a new value takes a counter while fewer than
distinct_capare held, and otherwise takes one from every counter and drops those at 0 (a Misra-Gries summary). A usable row whose row before was usable adds the pair to the lag-1 regression and counts whether the two are equal. Nothing decays.Example
This code audits a column with
-999planted on about 5% of its rows beside a random walk, and prints whatcheck()finds in each:import numpy as np rng = np.random.default_rng(4) x = rng.standard_normal(10_000) x[rng.random(10_000) < 0.05] = -999.0 # a sentinel on a twentieth of the rows level = np.cumsum(rng.standard_normal(10_000)) # a level, where a change was meant pl.DataFrame({"x": x, "level": level}).write_parquet("feed.parquet") audit = rp.spec.audit("audit", columns=["x", "level"]) bank = rp.ModelBank([audit]) bank.fit(pl.scan_parquet("feed.parquet")) # count every row, keep no output for r in bank.check().iter_rows(named=True): print(f"{r['column']}: {r['code']} ({r['value']:.3g})")
level: random_walk (-1.99) x: sentinel (0.0437) x: heavy_tails (953)
See also
rheon.polars.ModelBank.audit(), the counts, one row per column.rheon.polars.ModelBank.check(), what the counts say is wrong.rheon.polars.ModelBank.describe(), a few statistics of every column each spec has been fed.
Notes
What it counts. Per column, over every row the stream holds, in the order it holds them. Every statistic but the counts of values that are not usable is over the usable values.
measurement
definition
what is not usable
nulls, NaNs,
+inf,-infand finite values past1e100, each counted apart (describe()’snull_countlumps them together, as the models do)moments
the mean, the standard deviation (
ddof = 1), the skewsqrt(n) M3 / M2^1.5and the excess kurtosisn M4 / M2^2 - 3(scipy’s biased estimators), the smallest and the largest value. One pass, by Terriberry’s update of the central sumsM2,M3,M4, with the mean kept to twice a double’s precisionrepeats
each distinct value’s count, exact up to
distinct_capdistinct values, so the distinct count is exact up to the cap. Past it a Misra-Gries summary: a value not held takes one from every counter, and no count is more thancount_errorshort of the truth,count_errorbeing at mostn / (distinct_cap + 1). The most repeated value and the next count are read from itruns
the longest run of one value on consecutive rows, and how many rows equal the row before (out of those whose row before was usable), beside
sum p_v^2over the values’ shares, which is what independent rows would give. A row that is not usable ends a runthe smallest change
the smallest nonzero change between two consecutive usable rows, and how many changes sit at it, to the rounding two changes of one step of a grid differ by: whether the column’s repeats are one of its steps or an atom a stale feed adds
persistence
the lag-1 autocorrelation, the correlation of each usable row with the row before it where that row is usable too, and the Dickey-Fuller statistic of the same regression with a constant,
(rho - 1) / se(rho), as statsmodels’adfullergives it with no lags. A random walk reads near 0; independent rows read about-sqrt(n); a fit with no residual reads+infat a slope of 1 or more (a row counter, a clock in epoch seconds) and-infbelowlocation and spread, robustly
the median and the median absolute deviation, exact while the counts are, and otherwise from a t-digest whose centroids hold at most
2n / 200rows each, so a rank is known to about 1% of the rows. The largest robust z ismax(max - median, median - min) / (1.4826 MAD)pairs, with
pairs=Truefor every pair of columns, over the rows where both are usable, the correlation and the rows on which the two are equal
the clock, with a
clockcolumneach step between consecutive rows, the time that passed, uncapped, is a duplicate stamp (0), a gap (at or past
gap_cap, which caps the step a model ages by) or a regular step. The regular steps’ mean, population spread and coefficient of variation are kept, with the largest step of all. On a temporal clock the mean, the spread and the largest step areDurationvaluesEvery row is read. Every other model skips a row whose feature is not usable, and an audit counts it, since that is what it is for. A reset, at a session gap set to
"reset"or a step back pastrestart_after_step_back, starts its runs and its clock steps over and keeps its counts: an audit is a record of what the stream held, not a fit. An audit records the clock as fed, so a numericsession_gapchanges none of its rows or tables. A step back of the clock is refused, as for every spec: to count the steps back instead, setrestart_after_step_back(0resets at each), andsummary()’sclock_backwardsandcheck()’sstep_backcount them.predict()counts nothing, as it learns nothing. The counts are the same whether the stream comes in one chunk or a thousand, and are kept in the state, so an audit saved after one file goes on over the next. An audit predicts nothing, so it has no prediction to keep out-of-sample.Groups merge.
ModelBank.audit(pooled=True)reads one audit of every group, as if they were one stream. The counts, the moments (Pébay’s pairwise formulas), the longest run, the repeats of the row before, the lag pairs, the pairs and the clock merge exactly, up to rounding. Two do not: past the cap the counters merge as Misra-Gries summaries do (Agarwal et al. 2012, the errors added), and the digests by compressing their centroids together. A run or a lag pair across two groups is not one, so none is counted.Cost. A value costs one lookup in a hash table of a column’s counters, held or not. Past the cap, a new value takes one from every counter, which empties the table at most once in
distinct_cap + 1new values, so a continuous column pays a few operations a row at any cap. The digest compresses every 256 rows, a few comparisons a row amortized, andpairsaddsk(k - 1)/2pair sums to move a row forkcolumns. Memory does not grow with the rows. At the defaults it is about 14 KiB a column, and 72 bytes a pair, in every group. A column’s share is a table ofdistinct_capcounters, 16 bytes each and as much again of the table’s slack, and a digest of at most about 200 centroids and 256 values waiting.Measured through
fit_predict()on frames in memory, of columns drawn fromN(0, 1), the best of seven runs on an Apple M4 Pro under a load average of 22 to 24 (polars 2.0.0):what ran
million rows a second
one column, 100,000 rows, at 256 / 8,192 / 65,536 counters
9.3 / 9.4 / 9.1
ten columns, 500,000 rows
1.71
the same, with
pairs=True1.51
an
ewridgeon the same columns (nine features, one target)4.4
The saved state of those ten columns held 4.8 KB a column (
save_bytes(), 48,625 bytes, of which an unfed bank is 996), and 4.7 KB a column at fifty.