polars_online.gram.solve_subsets

polars_online.gram.solve_subsets(grams: Sequence[Gram], subsets: Sequence[Sequence[int]], *, targets: Sequence[str | int] | None = None, features: Sequence[str | int] | None = None, ridge: float | Sequence[float] = 0.0, standardize: bool = False, path: dict[str, Any] | None = None, within: bool = False, target_signs: Any = None, threads: int | None = None, jobs: Sequence[Mapping[str, Any]] | pl.DataFrame | None = None) → list[Any][source]

Merge each subset of the Grams and fit it, for many subsets at once.

Use it for many fits over pooled Grams in one call, such as each block’s own fit (the spread of a coefficient’s t across the blocks says how stable it is), the halves of a stability selection (each a merge of about half the blocks), and their null runs under random signs. For one merge and one fit, use merge() and then solve(), coef_stats() or lars_path(). To walk paths on Grams without merging them, use lars_paths().

Parameters

grams

The Grams, each as gram() returns it, all with the same columns and targets, and each with means_by_target and cross_centered.

subsets

One list of positions in grams per fit, each naming a Gram at most once, since a Gram twice in one merge counts its rows twice. [[0], [1], ...] fits each Gram alone. A subset’s parts are pooled as merge() pools them.

targets

The targets to fit, by name or position. Default None, every target. Refused beside jobs, whose jobs name their own.

features

As for solve().

ridge, standardize

As for solve(). A sequence of ridges fits each value, and gives coef, se and t one row per value and resid_var, sigma2 and r2 one entry per value, with n once. Not read under path, since a path is in correlation form.

path

None, the default, for a ridge fit with its statistics, as solve() and then coef_stats() give them. Or a dict of lars_path()’s max_iter, max_active and penalty_weights ({} for none of them) for each target’s lasso path instead. The key’s older name, max_steps, is read as max_iter, with a PolarsOnlineDeprecationWarning. Any other key is refused.

within

True pools each subset within its parts, as merge() with within=True: each fit’s intercept is nan, and a ridge fit’s degrees of freedom lose one per part. Default False, the union.

target_signs

None, the default, or an array of shape (len(grams), draws), each entry +1 or -1, only with within=True. Column d is a draw: a sign s_i for each Gram, which multiplies its targets’ centered cross-moments before each subset is pooled, c = sum T_i s_i c_i / T. That is what negating Gram i’s target rows gives, since its co-moments, its target weights and its target variances do not move, so a draw needs no second merge of the co-moments. Every subset is fitted once per draw, so a draw of random signs is a null run of a selection: what it chooses where no column’s effect keeps its sign across the Grams. Under a union a negated Gram’s target mean moves the gaps between the parts’ means too, and the shortcut does not hold, so it is refused there.

threads

How many threads the subsets are fitted on, beside each other: None, the default, is the process’s threads, and an integer that many threads, as ModelBank takes it. Each fit is one thread’s arithmetic, so the numbers are the same at any count. Refused unless an integer of at least 1, or None.

jobs

None, the default, fits every subset, draw and target on features. Otherwise the fits to run, each on columns of its own: a list of mappings, as pl.DataFrame.to_dicts() gives them, or a Polars DataFrame of them, one row per job. A job’s keys are

  • "subset", a position in subsets;

  • "target", a name or position, as in targets;

  • "draw", a column of target_signs, given with it and only with it;

  • "features", the job’s columns, as features names them; missing or None is features, and so every feature when that is None too;

  • "penalty_weights", for a path only: one per column of the job. Missing or None is path’s, which must then have one per column of the job too, or every weight 1.

A job’s fit is that of its columns merged alone, to the bit (Notes).

Returns

One list per subset, with one dict per target. A ridge fit’s dict has coef, the coefficients over the Gram’s columns, and coef_stats()’ resid_var, sigma2, r2, n, se and t; under a sequence of ridges each number but n has one row or entry per ridge. A path’s dict is lars_path()’s. With target_signs, one such list per draw. With jobs, one such dict per job, in their order, over every column of the Grams: 0, or nan for se and t, at a column the job does not read.

Raises

ValueError

When:

  • grams is empty, or the Grams differ in columns or targets;

  • a subset is empty, or holds a position out of range or twice;

  • without within, a subset of several holds a Gram pooled within parts (as merge());

  • target_signs is given without within, has another shape, or holds an entry other than +1 or -1;

  • path has an unknown key, a limit below 1, or penalty_weights of the wrong length or not finite and above 0, as for lars_path();

  • with jobs: targets is given; a job has a key it does not take, lacks its subset or target, has a subset or draw out of range, a draw without target_signs or none with them, features that are one name, hold the intercept or name a column twice, or penalty_weights without path, of another length than its columns, or not finite and above 0;

  • a Gram has no means_by_target or cross_centered, which merge() forms after pooling and this does not;

  • for a ridge fit, ridge is not finite and at least 0, or a Gram has no target moments (as coef_stats());

  • threads is below 1.

WrongTypeError

jobs is neither a list nor a DataFrame, a job is not a mapping, or a limit in path is not a whole number. It is both a TypeError and a ValueError.

TypeError

threads is not an integer or None, or path gives both max_iter and its older name max_steps.

KeyError, IndexError

As for solve() and lars_path(): a job’s column or target the Grams do not have is a KeyError, and its position out of range an IndexError, each naming the job.

Examples

This code reads df from Example data:

spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"],
                       half_life=float("inf"), group="stock_id")
bank = po.ModelBank([spec])
bank.fit_predict(df)
blocks = bank.gram("ridge")                     # one Gram per stock
# A ridge fit in each block alone, and x0's t in each.
each = po.gram.solve_subsets(blocks, [[i] for i in range(len(blocks))], ridge=1e-6)
print([round(float(fits[0]["t"][1]), 1) for fits in each])
[38.8, 36.1, 37.8, 41.2]

See also

Notes

A path over each pair of blocks, its null runs under random signs, and a screen of its own for each job, on the example’s blocks:

spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"],
                       half_life=float("inf"), group="stock_id")
bank = po.ModelBank([spec])
bank.fit_predict(df)
blocks = bank.gram("ridge")                     # one Gram per stock
halves = po.gram.solve_subsets(blocks, [[0, 1], [2, 3]], path={"max_active": 1})
signs = np.random.default_rng(0).choice([-1.0, 1.0], size=(len(blocks), 20))
null = po.gram.solve_subsets(blocks, [[0, 1], [2, 3]], path={"max_active": 1},
                             within=True, target_signs=signs)   # a list per draw
jobs = [{"subset": 0, "draw": 0, "target": "y", "features": ["x0"]},
        {"subset": 1, "draw": 3, "target": "y", "features": ["x1", "x0"]}]
screened = po.gram.solve_subsets(blocks, [[0, 1], [2, 3]], path={"max_active": 1},
                                 within=True, target_signs=signs, jobs=jobs)
print([h[0]["active"][-1] for h in halves],          # each half's first column
      len(null), len(null[0]),                       # 20 draws of 2 subsets
      [j["active"][-1] for j in screened])           # each job's first column
[['x0'], ['x0']] 20 2 [['x0'], ['x0']]

The ridge fit is

(A + ridge * I) b = r_t            A, r_t as solve() forms them
b_0       = ybar_t - m_t . b       the intercept, with one
resid_var = S_yy - 2 b' r_t + b' A b
sigma2    = resid_var * n / (n - p)      n = target_n_kish
se        = sqrt(diag(inv(A)) * sigma2 / n),   t = b / se
se_0      = sqrt((1 + m_t' inv(A) m_t) * sigma2 / n)

with p the columns with variance and the intercept, or under within the columns with variance and the parts the target has rows in. A column of none, such as a constant that standardize drops at 0, has no coefficient to estimate and spends no degree of freedom. With an intercept, A is the columns’ centered co-moments, r_t the target’s centered cross-moments, m_t its column means, ybar_t its mean and S_yy its variance. Without one they are the raw moments and E[y**2], as coef_stats() reads them, and there is no se_0. Under within the intercept has none either. Under standardize the system is solved in correlation form, as solve() solves it.

The ridge fit’s system and the inverse its errors read are both factorized by Cholesky, where solve() runs numpy’s symmetric eigendecomposition and coef_stats() its inverse, so the two agree to rounding: the system’s condition number times 1e-16, measured within 5e-13 of each number’s size at 2,000 columns. A system whose factorization fails, such as a constant column under a ridge of 0, gives nan here, where solve() divides by an eigenvalue of 0 or of rounding size. A nearly singular one gives what any solve of it gives, rounding noise. A column of no variance, such as a constant that standardize drops at 0, has nan for its se and t, and the other columns’ are read from the inverse of the columns kept, as a fit without it gives them.

The Grams are read once, into memory the call holds while it runs, and every subset is merged and fitted there, on the process’s threads, without a Python copy of a matrix per subset. The copy is the Grams’ size again for the call’s length. A subset’s merge is formed on the columns its fits read and the intercept alone, and dropped when its fits are done. Its targets share one factorization. The merge is merge()’s arithmetic entry for entry, so it agrees with it to the bit. For 38 Grams and 100 subsets of 19, measured on an M4 Pro on 2026-11-08 under a load near 10, it took 0.015 s at 200 columns and 3.3 s at 2,000, where the loop of merge(), solve() and coef_stats() took 0.51 s and 80 s.

Jobs. Each subset is merged once, on the intercept and every column its jobs read, and each draw pools its cross-moments again once per subset. A job’s fit is that of its columns merged alone, to the bit: a path is lars_path() on subset(merge(parts, within=within), ["intercept", *features]) (without "intercept" on a Gram through the origin) of the subset’s Grams, each with its targets’ cross-moments times its sign in the draw. A ridge fit is this call’s on [subsets[subset]], target_signs[:, [draw]], features and targets=[target]. Jobs that share a subset, draw and columns share that design’s factorization, and the jobs run beside each other on the threads, as the subsets do. A screen per subset, per target and per draw, as complementary-pairs stability selection runs, is then one call. It was measured on an M4 Pro on 2026-11-08 under a load near 5, with 100 subsets of 19 of 38 Grams, 11 draws and 10 targets: 11,000 jobs, each a path to 10 columns on 400 of 1,500 columns. The call took 13 ms a subset. The loop took 700 ms a subset: merge() of the subset’s signed Grams for each draw, then subset() and lars_path() for each job.