rheon.polars.eval.seqtest

rheon.polars.eval.seqtest(df: pl.DataFrame, *, targets: Sequence[str] | None = None, a: str | None = None, b: str | None = None, a_suffix: str = '', b_suffix: str = '', group: str | Iterable[str] | None = None, min_weight: float = 0.0, name: str = 'seqtest') → pl.DataFrame[source]
rheon.polars.eval.seqtest(df: pl.LazyFrame, *, targets: Sequence[str] | None = None, a: str | None = None, b: str | None = None, a_suffix: str = '', b_suffix: str = '', group: str | Iterable[str] | None = None, min_weight: float = 0.0, name: str = 'seqtest') → pl.LazyFrame

Test a sign sequentially by betting, over a frame or a query.

Use it to gather evidence, row by row, that a column’s sign leans one way, or that one spec predicts closer than another on more rows, with evidence you may read at every row (see Notes for the null that holds). It computes what rheon.spec.seqtest() writes, field for field and row for row, with Polars expressions. For a stream too long to hold, give it a query of the output, or run the seqtest model in the bank, whose memory is the size of its state.

Parameters

df

The frame: in column mode, one holding the columns tested; in compare mode, one a bank returned, holding both specs’ output columns. Or a query of either, a LazyFrame, which gives a query back (see Returns).

targets

In column mode, the columns whose sign is tested, which column mode needs. In compare mode, the targets whose residuals are compared: t means resid_<t><a_suffix> of a against resid_<t><b_suffix> of b. None, the default, takes every target the two share.

a, b

The names of two specs’ output columns, for compare mode; give both or neither. The sign tested is that of |resid_b| - |resid_a|, positive when a was closer.

a_suffix, b_suffix

The suffix of the residual field each side’s slot carries, such as "__r0.1" for one grid point of a grid; "" by default.

group

One key column, as a spec’s group is, or a list of them, to run one test per group in row order (.over(group)); None, the default, runs one.

min_weight

The rows a group must have before a field other than weight_sum is filled; 0 by default.

name

The name of the column added, "seqtest" by default.

Returns

df with a record column name added, holding per target t, each read before the row, as the bank writes them:

log_e_pos_<t>, log_e_neg_<t>, n_pos_<t>, n_neg_<t>

In column mode: the log wealth of the bet that the sign is positive and of the bet that it is negative, and the signs counted.

log_e_a_<t>, log_e_b_<t>, wins_a_<t>, wins_b_<t>

In compare mode: the same, for “a was closer” and “b was closer”.

weight_sum

The rows before this one in its group. Every other field is null until it reaches min_weight.

Given a LazyFrame, a LazyFrame of the same, which reads df one chunk at a time when it runs (see Notes).

Raises

ValueError

When:

  • df already has a column name, which the result would replace;

  • a is given without b, or b without a;

  • column mode has no targets;

  • the two specs share no residual field;

  • a target has no residual on one side (the error names the fields that side has).

OutputColumnNotFoundError

df has no column a or b. It is both Polars’ ColumnNotFoundError and a KeyError.

TypeError

df is neither a DataFrame nor a LazyFrame, or a or b names a column that is not a record.

ColumnNotFoundError

df does not have a group column. It is both Polars’ ColumnNotFoundError and a ValueError.

Polars’ ColumnNotFoundError

df does not have a column-mode target.

Update equation

Per target, with s the row’s sign (+1, -1 or 0), and n_pos and n_neg the signs counted before the row:

lam_pos = max(0, (n_pos - n_neg) / (n_pos + n_neg + 1))
lam_neg = max(0, (n_neg - n_pos) / (n_pos + n_neg + 1))
log_e_pos += log1p(lam_pos * s)
log_e_neg += log1p(-lam_neg * s)

lam_pos and lam_neg are the shares of wealth each bet stakes on the row, read from the signs before it.

Examples

This code reads df from Example data:

ridge = rp.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0)
x0_only = rp.spec.ewridge("x0_only", targets=["y"], features=["x0"], half_life=100.0)
out = rp.ModelBank([ridge, x0_only]).fit_predict(df)
evidence = rp.eval.seqtest(out, a="ridge", b="x0_only")
last = evidence["seqtest"].struct.unnest().row(-1, named=True)    # the last row's fields
print(f"ridge closer on {last['wins_a_y']:.0f} rows, x0_only on {last['wins_b_y']:.0f}")
log_e = last["log_e_a_y"]                                        # ridge's log evidence
print(f"log evidence for ridge {log_e:.1f}, past ln 20: {log_e > np.log(20)}")
ridge closer on 290 rows, x0_only on 105
log evidence for ridge 41.8, past ln 20: True

See also

Notes

The evidence can be read at every row. Each target has two bets, one on each direction: reject a direction at the 5% level the first time its bet’s log wealth reaches ln 20, about 3.0. Watching both bets at once, to test either direction at 5%, needs ln 40. A value of zero bets nothing and counts nothing, and so does one the bank would not learn from: null, NaN, infinite, or past its input bound of 1e100 in magnitude. In compare mode the value is the difference |resid_b| - |resid_a|, and the bound is on it, where diebold_mariano() bounds each residual.

The 5% holds under a null about every row: at each row, whatever came before, the next sign is no more likely positive than negative. Then each bet’s wealth is a nonnegative supermartingale started at 1, and by Ville’s inequality it reaches 20 with probability at most 5%, read at every row, not only the last. That null is more than “the two specs are equally close”: signs that run break it with neither spec closer on average, and the bet that follows the run grows, in either direction. On simulated streams of 5,000 rows from two equally accurate specs, each bet reached ln 20 on 3.6% of streams where their errors were independent, and on 61% (a closer) and 62% (b closer) where each spec’s errors followed an autoregression at 0.9, on 88% one or the other at ln 40. Where errors persist, test one row in each block of rows longer than their memory: filter the frame to those rows first. The bank’s model adds what a frame in memory does not have, the clock (session, restart_after_step_back), and its output is held to this function’s to the last bit.

Given a query, the result is the frame’s to the bit, and this holds one chunk and a few numbers per key, beside what Polars reads of the query ahead of it. Each chunk carries in, per group, the rows and the signs counted before it and each bet’s log wealth after its last row, and adds that wealth to its own first term, so the sums run on in the frame’s order. A query is refused as its frame would be, with the same message, before it runs. A scan of a parquet file reads its row groups ahead of a slower consumer, as many as Polars’ thread count sizes, and under Polars’ defaults that read-ahead is most of what the process holds: Cut what Polars reads ahead bounds it. Written to a file with sink_parquet, the test of two specs of a scan by a key of four values, the file in row groups of 100,000 rows, held at most 149 MiB at a million rows, 159 MiB at four million and 157 MiB at sixteen million with four threads (POLARS_MAX_THREADS=4), the read-ahead cut to one row group (POLARS_ROW_GROUP_PREFETCH_SIZE=1) and the allocator told to return freed pages at once (_RJEM_MALLOC_CONF=dirty_decay_ms:0,muzzy_decay_ms:0); under Polars’ defaults, 349, 646 and 1,155 MiB. Each figure is the most memory the process held, about 48 MiB of it Python and Polars before the call, measured on macOS (an M4 Pro, py-polars 2.0.0).