Skip to content

Version 0.4.0: causal mode (no look-ahead) for timecorr and features - #153

Merged
jeremymanning merged 26 commits into
masterfrom
causal-mode
Nov 24, 2026
Merged

jeremymanning merged 26 commits into
masterfrom
causal-mode

Conversation

@jeremymanning

Copy link
Copy Markdown
Member

Version 0.4.0: causal mode

tc.timecorr and tc.features gain a causal mode in which row t of the output is computed from rows 0..t of the input only.

What is added

  • Keyword-only causal, min_samples and fit_timepoints in timecorr, features, two_path_step and the estimator functions (wcorr, autofc, isfc, wisfc); refit_every and return_model in features.
  • tc.FeaturesModel, returned by features(..., causal=True, return_model=True): the reducers fitted on the first fit_timepoints rows, with transform(data) to apply them to other data. It can be pickled.
  • Rows without enough samples are NaN (warm-up); return_info entries of causal calls report them.
  • refit_every=m refits the reducers at rows fit_timepoints + j*m on the rows before each of them and keeps the columns of the first fit.
  • Tutorial docs/tutorial/causal.ipynb on the daily returns of the 49 Industry Portfolios, an API section, and the changelog entry.

What is tested

  • Row t is bit-identical when the rows after t are replaced (finite values, NaN, inf) and agrees to 1e-9 when they are removed, at every row before several cuts, for the estimator, features, fitted models, transform and refits (tests/test_causal_*.py; exhaustive grids are marked slow).
  • The documented exceptions (eigenvector-based graph measures where leading eigenvalues coincide, tstat_combine where it is ill-conditioned, functions and models outside the listed ones, which run with a warning) are in the docstrings and docs/api.rst.
  • Calls without causal=True are unchanged; the outputs frozen in tests/test_legacy_pipeline.py, tests/test_legacy_timecorr.py and tests/test_kernels_reference.py still pass.

Also in this release

  • install_requires now asks for hypertools>=1.1: helpers.reduce passes random_state=, which hypertools 0.8 does not accept (tests/test_packaging.py).

The changelog date is still "Unreleased"; it is set when the release is made.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL

jeremymanning and others added 26 commits November 23, 2026 10:44
…, isfc, wisfc

With causal=True nothing computed for timepoint t reads a sample after t:
each chunk of 128 kernel rows is multiplied with the columns it weights and
centered on a reference from earlier rows, the zero-variance rule is
relative to that reference, infinite and overflowing samples are missing,
and rows with too few effective samples are NaN. timecorr implies a
backward kernel and raises for arguments without a causal form.

causal=False is unchanged. tests/test_estimator.py::
test_timecorr_positional_order fails: it lists the keyword-only arguments of
timecorr as exactly events and events_params.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…w reaches raises

With min_samples=None only the rule of 3 weighted, observed samples leaves a
row undefined, so the NaN rows of causal=True are the zero rows of
causal=False for the same backward kernel. A number (>= 1) adds the
effective-sample rule; one above the largest effective sample size of the
kernel's rows raises ValueError naming that maximum.

test_timecorr_positional_order lists the keyword-only arguments timecorr
has now (events, events_params, causal, min_samples), as approved.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…ength of the series

A number raises only when a built-in kernel cannot reach it with any number
of earlier timepoints (helpers._kernel_reach, from the kernel's lag profile
function, which LagKernel now carries); the rows of a short series that do
not reach it are NaN, so a prefix of a series never raises where the series
does not. A kernel given as an array or by a function of the user's has no
profile and never raises.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…very prefix runs

A row is computed with the sums for complete data exactly when no timepoint
it weights has a NaN sample, and with the pairwise sums otherwise (NaN
samples are zero-filled after centering), so replacing later rows by NaN,
inf or finite values changes no bit of an earlier row. Before, a chunk of
kernel rows took the pairwise path when any of its rows had a NaN, which
moved ill-conditioned earlier rows by up to 6e-8.

A series of one timepoint is no longer taken for a delta kernel (only a
kernel whose lag profile reaches one sample is), and a kernel without
weight gives NaN rows instead of an error.

A kernel-weighted standard deviation below 1e-9 of the magnitude of the
kernel-weighted mean counts as zero variance (causal estimator only).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…eed no fit

With causal=True both paths use backward kernels and the causal estimator;
kernel parameters must be given for every order on both paths; rfun and
delta_rfun must be None or graph measures (a fitted reducer raises
NotImplementedError naming fit_timepoints); eye_weights, the default
subject weights of wisfc and events given as features raise ValueError; a
min_samples no built-in kernel of the call can reach raises before
anything is computed. Undefined rows are NaN and are missing data for the
next order, so the warm-up accumulates; graph measures are computed for
the defined rows. return_info entries of causal calls have weights_params
and warmup_rows, and constant_columns ignores the NaN rows.

Causal estimator: the data are centered anew for every group of 16 kernel
rows on the kernel-weighted mean at the group's first row (rows after a
level step or after the junk first values of a higher order were
ill conditioned about one reference per 128 rows: 9e-8 from the exact
value, 6e-8 between a series and its prefix); timepoints without any
sample have no weight in any row, so the undefined rows of an earlier
order do not put later rows on the pairwise path; the columns of a chunk
do not depend on which rows the data leave undefined.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…he causal arguments

Approved by the project owner: the list of keyword-only names in
test_events_signatures_keep_positional_order grows; the positional-order assertion is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…known for every built-in kernel

Fixes from the review of 9f02d23.

- Events: with causal=True, boundaries at or beyond the end of the data are
  ignored (times the series has not reached) and events that leave no row
  with 3 weights give rows of NaN instead of an error, so f(x[:T], events=B)
  runs and equals the first T rows of f(x, events=B) for every T >= 1
  (timecorr, features, two_path_step; shared, per-subject and by-order
  events).  A built-in kernel cut by events into blocks of one timepoint is
  not taken for a delta kernel.  Without causal both checks are unchanged.
- min_samples: _kernel_reach is decisive for every built-in kernel and
  parameter value.  Sums that have not converged (t_weights with few degrees
  of freedom, very wide kernels) are completed from the profile's formula
  (geometric series, survival functions with Euler-Maclaurin terms; an upper
  bound for a wide mexican_hat_weights), so an unreachable min_samples
  raises instead of returning rows of NaN.  uniform_weights has no limit and
  never raises.
- Tests: the next-order test of the constant-column rule now computes order
  2 (a feeding column constant to 1e-12, and duplicated features), under
  replacement and removal; it fails when _causal_zero_variance is disabled.
- Docs: what the guarantee covers under removal (eigenvector-based graph
  measures at degenerate matrices are not covered).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…odel and return_model

- timecorr, features, two_path_step: fit_timepoints=n (keyword-only,
  causal=True).  Every reducer that is fitted to data (hypertools models,
  WeightedStrength, Communities with its shift null, the automatic reducers
  and the feeding fallback) is fitted on rows [0, n) and applied, frozen, to
  every row.  features and two_path_step run the pipeline on the first n rows
  alone (so the fits do not change, bit for bit, whatever follows) and then
  on every row; timecorr fits on the first n rows of its correlations.  A
  fitted reducer without fit_timepoints raises ValueError (also a
  NotImplementedError, as the tests of the earlier step expect).
- features: return_model=True returns a tc.FeaturesModel (new module
  timecorr/model.py) with transform(data, return_delta, return_info,
  events=), the fits by (order, path), the settings of the call; picklable.
- Summaries: the streamed passes take the causal estimator (undefined rows
  are left out of fits and are rows of NaN in outputs; wisfc with fixed
  subject weights is streamed), a frozen fit skips pass 1, the shift null
  shifts among the rows with data, and no column is set to its mean.
- Models: fitted with hypertools' return_model and applied to all rows; must
  reproduce their training rows to 1e-9 (MDS, SpectralEmbedding,
  LocallyLinearEmbedding raise).  PCA is fitted with svd_solver="full" (the
  randomized solver does not reproduce its rows).  Output columns that are
  constant on the training rows up to round-off are frozen at their training
  mean, so the next order does not correlate round-off.
- return_info of causal calls: "fit_timepoints" for fitted steps.
- Summary objects are not reported as functions of the user's.
- Tests: tests/test_causal_fit.py; the keyword-only name lists of the two
  signature tests gain fit_timepoints and return_model.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…alueError

The error was also a NotImplementedError, kept only for assertions written
earlier on this branch; those now expect ValueError.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
features(..., causal=True, fit_timepoints=n, refit_every=m) fits at rows
n + j*m, each fit on the rows before its row; rows from a fit to the next
are those of the call with that fit alone.  The structure is the first
fit's; components and communities are matched to the fit before, order by
order; a fit without the structure keeps the fit before (return_info:
refit_rows, refit_kept_previous).  The model holds the last fit
(model.refits).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
- Models: only linear maps applied row by row are taken (components_, the
  training rows reproduced, rows reduced alone as together); UMAP,
  KernelPCA, Isomap and the like raise before anything is computed.
- A subject without a defined row keeps its place in a frozen reduction
  (NaN rows), so missing later rows change no earlier row.
- A fitted summary in a model holds copies of its arrays: changing or
  refitting the caller's reducer object leaves the model as it was.
- A model with as many components as columns is the identity (padded as
  without causal), not an error.
- The reach of a kernel is computed from the lags its restrictions keep:
  exclude_timepoints with every kernel, uniform included; no limit for a
  boxcar of infinite width; known for very wide kernels.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…g subset in every run

The four causal test files took 402 s; their not-slow selection now takes
117 s (844 of 2016 tests).  No parametrization or assertion is removed: _grid
marks the combinations outside a pairwise (or per-level) covering subset as
slow and keeps the combinations that found defects (level steps of 1e4 at
the first row and mid-series under every perturbation, every prefix, the
refit-row cuts).  The 5033 x 49 timing test is slow.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…te=, which 0.8 lacks)

install_requires and requirements.txt said hypertools>=0.8, but
helpers.reduce calls hyp.reduce(..., random_state=0), an argument that
hypertools has from 1.0 on, so the default tc.features call raised
TypeError with hypertools 0.8.x.  tests/test_packaging.py reads the
declared requirements and the installed hypertools.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…r chunk

Review of f4625f6, two findings.

Models: probes on training rows cannot show that a transform is row-wise (a
PCA subclass that centers larger batches passed them and moved row 60 by
0.297 when later rows changed).  The guarantee now covers scikit-learn's PCA,
IncrementalPCA, TruncatedSVD, FastICA and FactorAnalysis by exact class; any
other model that has components_ and passes the probes runs with one
UserWarning per call, like a function of the user's.  A model that cannot
reduce one row alone ('SparsePCA') raises a ValueError that says so (it
raised numpy's vsplit error), and a refit reorders a copy of a model that
cannot be pickled (it reordered the fit itself and then rejected it).

Smoothing (cfun=None): values are on the scale of the data, so 1e-9 absolute
cannot hold at a level of 1e8 (values 1.5e-8 apart).  Each chunk is centered
on its first row's weighted mean (no later sample), so sums are exact to the
round-off of the variation: removal at an offset of 1e8 changed rows by 2
ulp, now 0; a step of 1e8 at the first row still gives 3 ulp.  The causal
documentation states the tested bound (1e-9 or 8 ulp of the largest
magnitude) and a test ties the sentence to the tolerance.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…4.0, CLAUDE.md

docs/tutorial/causal.ipynb (in the gallery): the look-ahead of an ordinary
backward-kernel call on 20 years of daily returns of 49 industries, the
causal call under removal and replacement of later days, a FeaturesModel
fitted on the days before 2015 and applied to all days, warm-up rows and
min_samples, refit_every, and the ValueError for missing kernel parameters.
docs/api.rst: a Causal features section with FeaturesModel (stubs in
docs/generated).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…columns

With the default reducers refit_every was inert on real data: the output
width of a communities step is its number of communities of 2 or more
nodes, and a refit with the first fit's number of clusters rarely has it
(weakly attached nodes are singletons in one fit and members in the next).
On the 5033 x 49 industry returns (fit_timepoints=2517, refit_every=1000)
both refits were left out and the output was that of one fit.

A refit now clusters its rows with n0, n0 + 1, n0 - 1, ... n0 +- 5 clusters
(between 2 and the number of features) and takes the first clustering with
the first fit's number of such communities; on the industry returns the fit
at 4517 is used (15 clusters, 10 columns) and the one at 3517 is still left
out (no count from 9 to 19 gives 10).  A fit that is left out is no longer
silent: one UserWarning per call names the rows and the step.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…ight wisfc steps are checked up front

return_info: when a refit of a Communities(n=n0) step took another number
of clusters (the search around n0 for the first fit's columns), the entry's
"effective" showed Communities(n=n0).  It now shows the object with the
number of clusters of the fit the entry describes (model._effective); the
entries of model.transform say the same.  Non-causal entries are untouched.

max_memory_gb: _check_streamed_steps did not know that causal mode streams
functools.partial(tc.wisfc, subject_weights=...), so a streamed step of a
later order that could not fit raised MemoryError only when it ran, after
the fit pass and the earlier orders (4 s in the case measured: 3 subjects,
2000 x 12, order 2 on 24 features), not before order 1 as for isfc.  It
takes causal= now.  No result was wrong.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…ve", the up-front check, smoothing reference

CHANGELOG: refit_every describes the search of cluster counts n0, n0 + 1,
n0 - 1, ... n0 +- 5 for the first fit's number of communities of 2 or more
nodes, and the one UserWarning for fits left out; return_info's "effective"
with refits; the per-chunk reference of causal smoothing; the up-front
MemoryError for streamed fixed-weight wisfc steps.  CLAUDE.md: the same for
model.py (_same_width, _effective) and higher_order.py, and the reach of a
Mexican hat wider than about 2 million samples (an upper bound about 1%
above the limit: measured ratios 1.0100 to 1.0103 for sigma 2.1e6 to 1e100).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
Section 4 no longer fixes the number of communities.  It runs
refit_every=1000 with the default reducers, records the warnings of the
call and prints model.refits, "refit_rows", "refit_kept_previous", the
clusters of the last fit and the warning; the figure shows the later fits
that were used.  In the saved run the fit at row 4517 is used (15 clusters,
10 columns) and the fit at row 3517 is left out.  Executed in place (89 s).
CHANGELOG and CLAUDE.md describe the section as it is now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
A smoothed row (cfun=None in features) can be partly NaN.  _on_defined
masked only rows that are entirely NaN, so such a row reached
hypertools.reduce, which fills missing values in from every row it is
given: with x = RandomState(0).randn(60, 6), x[30:40, 0] = NaN,
rfun="PCA", fit_timepoints=30, events=[30], replacing rows 41 on changed
row 35 by 4.76.  A model is now fitted on, and applied to, the rows
without any NaN or infinite value; the others are rows of NaN
(_defined_rows(complete=True)).  Summaries and graph measures keep their
rule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…mples

Without max_memory_gb the rows per block of a streamed step followed from
whether the whole recording holds a NaN sample, and the round-off of a row
depends on its block: with x = RandomState(0).randn(150, 100) and
WeightedStrength() or Communities(n=4), NaN in rows 101 on changed bits of
earlier rows ([53, 88]: 0.5167779106238817 to ...819), in features and in
model.transform.  With the causal estimator every recording is read in the
blocks of one with NaN samples.  Calls without causal=True are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…s rfun; tstat_combine's conditioning is documented

A combine function that is not one of timecorr's is called with every row
and got no warning: it is now named in the one UserWarning about functions
of the user's (timecorr, features, two_path_step), like cfun and rfun.

timecorr(causal=True, cfun=None, rfun='PCA') asked for fit_timepoints,
although smoothing returns the smoothed samples whatever rfun is (as
without causal): with cfun=None nothing about rfun is checked.

tstat_combine divides by the spread of the subjects' correlations; where
they nearly coincide (always with two subjects and isfc) removal of later
rows changes a statistic by about 1e-9 of its magnitude (0.12 on 3.8e7),
not by 1e-9.  The arithmetic is unchanged; the docstrings say so, and a
test holds replacement to no bit and a well-conditioned case to 1e-9.
Docstrings also state that a model reads rows without missing values.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
api.rst: a frozen constant model column is its training mean only for
values within the tolerance (not at every row); tstat_combine under
removal; combine functions of the user's; models read complete rows; the
refit search.  CHANGELOG 0.4.0 and CLAUDE.md: the same, the blocks of
streamed steps, smoothing and rfun.  Tutorial: combine in the list of
functions of your own (text only).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…ngs changed)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
A smoothed row (cfun=None in features) can be partly NaN.  For such a row
"eigenvector_centrality", "pagerank_centrality", WeightedStrength and
Communities raised, so NaN in one column of later rows turned a call that
ran into an error, and "strength" returned a partly NaN row.  A defined
row is now one without any NaN or infinite value for every reducer
(models since ee71703; summaries and graph measures here): the others are
left out of fits and are rows of NaN in the output.  Rows of the causal
estimator are entirely NaN or finite, so correlation paths are unchanged.
Docstrings, api.rst, CHANGELOG and CLAUDE.md say so.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
…s the indentation); no platform round-off asserted

The tstat_combine removal difference (0.12 on 3.8e7 on macOS) is 0 on Linux, so the
test no longer requires it to exceed 1e-9.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL
@jeremymanning
jeremymanning marked this pull request as ready for review November 24, 2026 01:09
@jeremymanning
jeremymanning merged commit 589c2a1 into master Nov 24, 2026
6 checks passed
@jeremymanning
jeremymanning deleted the causal-mode branch November 24, 2026 14:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant