diff --git a/CHANGELOG.md b/CHANGELOG.md index a6141fec..144c0122 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,218 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.4.0] - Unreleased + +### Added + +- Causal mode: `causal=True` (keyword-only; default False) in `tc.timecorr`, + `tc.features` and `tc.two_path_step`, and in the estimator and correlation + functions `tc.wcorr`, `tc.autofc`, `tc.isfc` and `tc.wisfc`. Row `t` of + every output is computed from rows `0..t` of the data only. What is + documented and tested: + - when the rows after `t` are replaced by any values (finite, NaN or inf), + row `t` is unchanged bit for bit, with every supported reducer; + - when the rows after `t` are removed, row `t` is unchanged to 1e-9 + (absolute) for outputs that depend continuously on the correlations: no + reduction, `"strength"`, the summaries (`tc.WeightedStrength`, + `tc.Communities`) and the linear models listed below once fitted. Removal + changes the correlations by round-off, and the eigenvector-based graph + measures (`"eigenvector_centrality"`, `"pagerank_centrality"`, + `"pagerank_centrality_abs"`) can differ by more at a correlation matrix + whose leading eigenvalues coincide, and the t statistics of + `tc.tstat_combine` where the subjects' correlations nearly coincide + (always with two subjects and `tc.isfc`): they divide by the spread + across subjects and agree to about 1e-9 of their magnitude instead (0.12 + on 3.8e7 in the case measured; replacement changes no bit); + - with `include_zero=False`, row `t` is also unchanged when row `t` itself + changes; + - with a fitted reducer (`fit_timepoints=n`, below) this holds for rows + `t >= n`; a row `t < n` is unchanged when rows from `n` on are replaced or + removed; + - smoothed values (`cfun=None`) are on the scale of the data (each chunk of + 128 rows is centered on the kernel-weighted mean at its first row, which + is added back, never on a mean over later rows): under removal + they agree to round-off relative to the magnitude of the data (to 1e-9 or + 8 units in the last place of the largest magnitude of the data, whichever + is larger); replacement changes no bit; + - a series of any length runs (one row included), and its output is the + first rows of the output of a longer series. + + Largest differences recorded during development (`tests/test_causal_*.py` + hold the checks): under replacement 0.0 in every case (the estimator; + `features` at orders 1 to 4; fitted reducers; refits); under removal 1.6e-13 + for the estimator, at most 7.8e-12 for `features` with reducers that need + no fit (at most 5.6e-13 on series with level steps of up to 1e8 standard + deviations), 2.2e-14 with fitted reducers, and at most 2.9e-15 with refits, + cuts at and around a refit row included. +- In causal mode: + - the kernels are backward (`include_timepoints` may be left out; + `"forward"` / `"post"` raises `ValueError`), and kernel parameters must be + given, in `features` for both paths and every order: widths are not chosen + from the data (`weights_params=None` raises `ValueError`; `{}` for a + kernel without parameters); + - `inf`, `-inf` and samples with `|x| > 1e150` are missing data, like NaN; + - a timepoint with fewer than 3 observed timepoints in its kernel row is a + row of NaN (the rows that are 0 without `causal`), the diagonal included. + `min_samples` (keyword-only, default None) also sets the effective sample + size `(sum |w|)**2 / sum w**2` a row needs (compared with a relative + tolerance of 1e-12); a number that a built-in kernel of the call cannot + reach with any number of earlier timepoints raises `ValueError` before + anything is computed. In `features` the NaN rows of an order's feeding + features are missing data for the next order, so each order has more of + them; reducers skip them and return them as NaN; + - a feature whose kernel-weighted standard deviation at a timepoint is below + 1e-9 of the magnitude of its kernel-weighted mean has correlation 0 with + every feature there (a column constant up to round-off); + - these raise `ValueError`, with a message that names an alternative: + `tc.eye_weights` on either path (co-fluctuations use series z-scored over + the whole recording: use a kernel with a width); `cfun=tc.wisfc` (its + default subject weights use the whole recording: use + `functools.partial(tc.wisfc, subject_weights=...)`); `events` given as + features to segment (give boundaries; that they are known at their own + time is the caller's responsibility; boundaries at or beyond the end of + the data are ignored); a kernel array, or a kernel function of your own, + with weight above the diagonal; a reducer that is fitted to data without + `fit_timepoints`; + - a function of your own as `cfun`, `combine`, `rfun` or `delta_rfun` is called as + without `causal`, with one `UserWarning` that the guarantee does not cover + what it does (removal is not covered either for a kernel function of your + own whose weights depend on the number of timepoints); + - with `max_memory_gb`, a step of a later order that is streamed and cannot + fit raises `MemoryError` before order 1 runs, as without `causal`; this + includes the steps streamed with + `functools.partial(tc.wisfc, subject_weights=...)`, which are streamed in + causal mode only; + - without `max_memory_gb`, a streamed step reads every recording in the + blocks of one with NaN samples, so that NaN samples after a row change + no bit of it; + - `tc.timecorr(..., causal=True, cfun=None)` (smoothing) does not use + `rfun`, as without `causal`, and asks for no `fit_timepoints`; + - the decoders have no causal mode. +- `fit_timepoints=n` (keyword-only; `timecorr`, `features`, `two_path_step`; + needs `causal=True`): every reducer that is fitted to data is fitted on rows + `0..n-1` and then applied, unchanged, to every row: hypertools models, + `tc.WeightedStrength`, `tc.Communities` (with `n=None` its shift null runs + on those rows) and the automatic reducers of `features` (`"auto"`, the + defaults), whose feeding step chooses between communities and weighted + strength on those rows. None and the graph measures need no fit. The fits + of a series and of a longer series with the same first `n` rows are equal + bit for bit. + - Every reducer (a model, a summary, a graph measure) reads the rows without + any NaN or infinite value only: any other row (a smoothed row of + `cfun=None` in `features` can be partly NaN) is left out of the fit and is + a row of NaN in the reduced output. (hypertools fills missing values in + from every row it is given, and the summaries and two graph measures raise + for them, so NaN in later rows would change earlier rows or stop the + call.) + - A model must be a linear map applied to each row by itself. The guarantee + covers `"PCA"`, `"IncrementalPCA"`, `"TruncatedSVD"`, `"FastICA"` and + `"FactorAnalysis"` (scikit-learn's classes of those names, by exact + class: a subclass is not one). Any other model whose fitted estimator has + `components_`, reproduces its training rows to 1e-9 and reduces rows one + at a time as it reduces them together is used with one `UserWarning` per + call that the guarantee does not cover what its transform does. A model + without `components_`, or that fails a check, raises `ValueError` + (`"UMAP"`, `"KernelPCA"`, `"Isomap"`, `"MDS"`, `"TSNE"`, + `"SpectralEmbedding"`, `"LocallyLinearEmbedding"`). + - `"PCA"` is fitted with `svd_solver="full"` in causal mode unless a model + dict gives a solver (the randomized solver that scikit-learn chooses for + large inputs failed the check that a model reproduces its training rows, + by 0.225 in the case measured). + - An output column of a model that is constant on the training rows up to + round-off (for example a principal component along which those rows do + not vary) is frozen: a value within that tolerance of the column's + training mean is returned as exactly that mean (without this, a null PCA + component changed order 2 by 2.8 under removal in the case measured). + - Output columns of a summary that are constant up to round-off are not set + to their means in causal mode, and no constant-output warning is issued; + `"constant_columns"` of `return_info` still lists constant columns. +- `refit_every=m` (keyword-only; `features`; needs `fit_timepoints=n`): the + reducers are fitted again at rows `s_j = n + j * m`, each time on rows + `0..s_j - 1`; rows `s_j` to `s_{j+1} - 1` of every output are those of the + same call with `fit_timepoints=s_j` and no refit, and rows before `n` are + those of the first fit. The output columns are those of the first fit: the + choice of an automatic feeding step (the shift null runs in the first fit + only), the number of components of a model, and the number of output + columns of a communities step, which is its number of communities of 2 or + more nodes. The number of clusters is not fixed: a later fit clusters its + rows with the first fit's number of clusters `n0` and then, while it has + not that many communities of 2 or more nodes, with `n0 + 1`, `n0 - 1`, + `n0 + 2`, `n0 - 2`, ... up to `n0 + 5` and `n0 - 5` (between 2 and the + number of features), and takes the first clustering that has them. A later + fit that cannot have the columns of the first is not used: the fit before + stays for its rows (at every order), `return_info` lists the row + (`"refit_kept_previous"`), and one `UserWarning` per call names the rows + left out and the step (order and path) that could not be fitted. The + components of a model are matched to those of the fit before (largest sum of + absolute cosines; a component is negated when its cosine is negative), and + the communities of `tc.Communities` by the most shared nodes. Each fit is a + pass over its rows and one over all rows. +- `tc.FeaturesModel` (`timecorr/model.py`) and `return_model=True` in + `features` (needs `causal=True`): the call also returns the fitted pipeline + (the order, kernels, `cfun`, `combine`, `include_zero`, `min_samples`, + `ndims`, `max_memory_gb`, and the reducers of every order and path as + fitted). `model.transform(data, return_delta=False, return_info=False, *, + events=None)` computes the features of other data with the same number of + columns and any number of rows, causally and without fitting anything; + `transform` of the data of the call returns what the call returned. With + `refit_every` the model holds the last fit. Attributes include + `fit_timepoints`, `refits`, `fits` and `info`. A model can be pickled when + the arguments of the call can (not with a lambda or a local function); + unpickling needs the same versions of timecorr, hypertools and + scikit-learn. A pipeline with a fitted summary takes the number of subjects + it was fitted with. +- `tc.features(..., causal=True, return_info=True)`: every entry also has + `"weights_params"` (the kernel parameters of the step) and `"warmup_rows"` + (the number of rows of the step's output that are entirely NaN; one number + per subject for list outputs); the entry of a step whose reducer was fitted + has `"fit_timepoints"`, `"refit_rows"` and `"refit_kept_previous"`. With + `refit_every`, what describes a fit is that of the last fit; when that fit + took another number of clusters than the `n` of a `tc.Communities` object, + `"effective"` shows the object with the number taken (for example + `Communities(n=5, ...)` for `tc.Communities(n=6)`). Entries of calls without + `causal=True` are unchanged. +- Timings recorded during development, on 5,033 timepoints of 49 features: + `timecorr` with `causal=True` 0.32 s (0.2 s for the same backward kernel + without `causal`; 1.77 s with 0.1% of the samples NaN); `features` at order + 3 with `"strength"` 1.85 s (1.15 s with a backward kernel and without + `causal`); `features` at order 3 with the default reducers and + `fit_timepoints=2500` 7.97 s and, in a later measurement, 9.8 s, + `model.transform` 1.80 s, and `refit_every=250` (11 fits) 68.9 s. On 2,700 timepoints of 500 features, + order 2 with the default reducers took 161 s. +- Tutorial `docs/tutorial/causal.ipynb` ("Causal features: no look-ahead"), on + the daily returns of the 49 Industry Portfolios + (`tc.datasets.industry_returns`): the look-ahead of a call without `causal`, + reducers fitted on a training span and applied to later days with + `model.transform`, warm-up rows and `min_samples`, refits with the default + reducers (it prints the rows of the fits, the fits left out and the warning + about them), and what causal mode does not accept. Its Colab cell installs `timecorr>=0.4.0`. +- `tests/test_packaging.py`: the declared hypertools requirement is at least + 1.1, and the installed `hypertools.reduce` has `random_state`, + `return_model` and `model`. + +### Changed + +- Calls without `causal=True` return what they returned in 0.3.1: the + stored-output tests (`tests/test_legacy_pipeline.py`, + `tests/test_legacy_timecorr.py`, `tests/test_kernels_reference.py`, + `tests/test_chunked_kernels.py`) pass unchanged. `min_samples`, + `fit_timepoints`, `refit_every` or `return_model=True` given without + `causal=True` raise `ValueError`. +- `install_requires`: `hypertools>=1.1` (was `hypertools>=0.8`; see Fixed). + The `tutorials` extra keeps `hypertools>=1.2`. + +### Fixed + +- Versions 0.3.0 and 0.3.1 declared `hypertools>=0.8`, but + `timecorr.helpers.reduce` calls `hypertools.reduce(..., random_state=0)`, + an argument that hypertools has from version 1.0 on. With hypertools 0.8.x + installed, every call that reduces with a model, the default `tc.features` + call included, raised `TypeError: reduce() got an unexpected keyword + argument 'random_state'`. The declared floor (`setup.py`, + `requirements.txt`) is now 1.1, the oldest version the test suite runs + with. + ## [0.3.1] - 2026-11-23 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 9da98637..660c71f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## About This Project -timecorr is a Python toolbox for computing and exploring correlational structure in timeseries data. The `timecorr` function computes kernel-weighted dynamic correlations from timeseries observations, and `features` computes higher-order dynamic correlations through the two-path pipeline of Owen, Chang & Manning (2021), Fig. 10 (by default with Gaussian kernels whose widths are set from each order's input and squared-correlation summaries at orders >= 2; the original pipeline is selected with `rfun="PCA", delta_rfun=None, delta_weights_function=tc.eye_weights`). +timecorr is a Python toolbox for computing and exploring correlational structure in timeseries data. The `timecorr` function computes kernel-weighted dynamic correlations from timeseries observations, and `features` computes higher-order dynamic correlations through the two-path pipeline of Owen, Chang & Manning (2021), Fig. 10 (by default with Gaussian kernels whose widths are set from each order's input and squared-correlation summaries at orders >= 2; the original pipeline is selected with `rfun="PCA", delta_rfun=None, delta_weights_function=tc.eye_weights`). With `causal=True` (version 0.4.0) both compute row `t` from rows `0..t` only, with reducers fitted on the first `fit_timepoints` rows and returned as a `tc.FeaturesModel`. ## Development Commands @@ -48,15 +48,17 @@ python setup.py sdist bdist_wheel ### Core Components -- **`timecorr/timecorr.py`**: the `timecorr()` function, the primary entry point for computing dynamic correlations (or, with `cfun=None`, kernel-weighted smoothing). +- **`timecorr/timecorr.py`**: the `timecorr()` function, the primary entry point for computing dynamic correlations (or, with `cfun=None`, kernel-weighted smoothing). Keyword-only `causal`, `min_samples`, `fit_timepoints` (see "Causal mode" under Key Concepts): `_causal_arguments` checks what has no causal form, `_causal_smooth` is the smoothing of `cfun=None` with NaN warm-up entries per feature (each chunk's samples centered on the weighted mean of its first row, which is added back), `_needs_fit` says whether an `rfun` is fitted to data, `_check_fit_timepoints` validates `fit_timepoints`, and `_fit_reducer` fits a reducer on the rows without any NaN or infinite value and returns what is applied frozen (a `summaries._FittedSummary`, a `helpers._FittedModel`, or the reducer itself when nothing is fitted). - **`timecorr/_kernels.py`**: `LagKernel`, the kernels of `timecorr`, `features`, `two_path_step`, the streamed summaries and the decoders for the built-in kernel functions: the lag profile (length T; the kernel functions in `helpers` build their T x T matrices from the same profile functions), `include_timepoints`/`include_zero`/`exclude_timepoints` and the event labels (`events.mask_kernel` accepts it), with `block(t0, t1, c0, c1)`, `span(t0, t1)` and `key(t0, t1)` (chunks away from edges and event boundaries share one block; `with_events` intersects the events it already has, `with_events(None)` keeps them; labels are runs of consecutive values, a single block stored as None; a non-finite `exclude` raises `ValueError`, as `exclude_timepoints` does for every kernel function); no T x T array is built (`uniform_weights` and `eye_weights` build their dense output directly). A kernel function of the user's gives T x T arrays (`helpers._lag_kernel` returns None for it), wrapped in `ArrayKernel` (the same `shape`/`chunks`/`block` interface; every chunk spans all columns; blocks are read-only views); `as_kernel` wraps either, and `blocks(kernel, size, transform, full)` is the one chunk iterator (blocks computed once per key), used by the estimator, the smoothing of `timecorr` and the row statistics. A custom `cfun` receives T x T arrays (counted by the memory guards and by `estimate_memory_gb(..., cfun=)`; a feeding kernel of the user's counts only at the orders whose feeding path runs). - **`timecorr/helpers.py`**: - Kernel functions (`gaussian_weights`, `laplace_weights`, `eye_weights`, `mexican_hat_weights`, `t_weights`, `uniform_weights`, `boxcar_weights`) and `one_sided` - - The estimator `wcorr` and correlation functions (`isfc`, `wisfc`, `autofc`) + - The estimator `wcorr` and correlation functions (`isfc`, `wisfc`, `autofc`), each with keyword-only `causal=False, min_samples=None`; the causal branch is `_causal_setup` / `_causal_block` (see "Causal mode" under Key Concepts) + - Frozen hypertools models of causal mode: `_model_reduce(..., return_model=True)` gives a `_FittedModel` (the model, its padding and its frozen constant columns); `_COMPONENT_MODELS` names the models with `components_`; `_FitUnusable` is raised for a fit a refit cannot use - Combine functions (`null_combine`, `corrmean_combine`, `mean_combine`, `tstat_combine`) - `reduce` (dimensionality reduction), `format_data` (input formatting via pydata-wrangler), `mat2vec`/`vec2mat`, `smooth`, `plot_weights` - Re-exports of the decoders from `decoding.py` -- **`timecorr/higher_order.py`**: the two-path pipeline: `features`, `two_path_step`, `estimate_memory_gb` (`streamed=True` for the peak of a streamed step; `combine=` counts the temporaries of the built-in combine functions, not of a function of your own). Keyword-only `delta_weights_function` / `delta_weights_params` set the kernel of the delta (feeding) path (default None: `gaussian_weights`, giving `autofc` correlations; `eye_weights` gives co-fluctuations). Kernel parameters of None (the defaults `weights_params=None`, `delta_weights_params=None`) with Gaussian kernels on both paths are automatic (`_auto_sd`, `_auto_params`): at each order the feeding kernel's standard deviation is 5 autocorrelation widths of that order's input, at least 5 rows and at most a hundredth of its rows or 5 rows, whichever is larger (so 5 below 500 rows), and the analysis kernel's is that or 10 rows, whichever is larger (white data: 10 and 5 at order 1, the fixed kernels of earlier versions, which are requested with `weights_params={"var": 100}, delta_weights_params={"var": 25}`; recordings of up to 1000 timepoints: at most 10 samples at every order). With no kernel parameters and no events given and two-sided kernels (`include_timepoints="all"`), `features` passes each order's feeding features on at every `floor(sd / 2)`-th row while at least 1000 rows remain and returns every output at all timepoints by linear interpolation (`return_info` entries of automatic kernels have `kernel_sd` and `sampling`). With another kernel function, or `eye_weights` on the feeding path, None is that function's own defaults. `weights_params` / `delta_weights_params` also accept order maps (dicts whose keys are all integers in 1..order; missing orders use the default; `two_path_step`, exported as `tc.two_path_step`, raises for one). `rfun` / `delta_rfun` accept `"auto"` (the defaults; analysis: PCA at order 1, `WeightedStrength(signed=True)` above; feeding: `Communities()`, which needs >= 4 features and T >= 40 (with more features than distinct shift-null lags in `[L, T - L]`, each lag is used for several features, balanced, and features sharing a lag keep their dependence in that surrogate; for a built-in kernel without events, one-sided restriction or `exclude_timepoints` (`summaries._stationary`) the null's squared correlations are averaged over every s-th timepoint, s the kernel's standard deviation rounded down for a Gaussian: `summaries._null_row_stride`; for any other kernel (arrays, kernel functions of your own, restricted kernels), over every timepoint); when its communities would emit fewer than 4 columns, the step emits `WeightedStrength(split=False, signed=False, center=False)` instead, one column per input feature, warning only when the shift null found no structure) and dicts keyed by order. `return_info=True` returns `(result, info)` with one dict per step and path (reducers requested and used, widths, community counts, fallback reason; no arrays, but lists of ints: `"constant_columns"` in every entry, the output columns with `np.ptp(x, axis=0) == 0` in the returned arrays (after the interpolation to all timepoints; one list per subject for list outputs; for feeding features that are not returned, in the rows computed), and `"labels"` in feeding entries, the community of each input column when the step's output columns are the communities of a `Communities` object (the default's included), None after a fallback, for other reducers and for the name `"communities"`, whose fit is not kept; `tests/test_features_info.py`). Summary columns constant up to round-off (range <= 1e-9 * max|column|, or <= 1e-12 of the largest absolute value of the unit's output) are set to their means and reported by the constant-output warning. Steps with a summary reducer, `null_combine` and `autofc`/`isfc`/`wisfc` are streamed in blocks of nodes. The original two-path pipeline of the paper is `rfun="PCA", delta_rfun=None, delta_weights_function=tc.eye_weights` (pinned by `tests/test_legacy_pipeline.py`); the decoders always use co-fluctuations on the feeding path. +- **`timecorr/higher_order.py`**: the two-path pipeline: `features`, `two_path_step`, `estimate_memory_gb` (`streamed=True` for the peak of a streamed step; `combine=` counts the temporaries of the built-in combine functions, not of a function of your own). Keyword-only `delta_weights_function` / `delta_weights_params` set the kernel of the delta (feeding) path (default None: `gaussian_weights`, giving `autofc` correlations; `eye_weights` gives co-fluctuations). Kernel parameters of None (the defaults `weights_params=None`, `delta_weights_params=None`) with Gaussian kernels on both paths are automatic (`_auto_sd`, `_auto_params`): at each order the feeding kernel's standard deviation is 5 autocorrelation widths of that order's input, at least 5 rows and at most a hundredth of its rows or 5 rows, whichever is larger (so 5 below 500 rows), and the analysis kernel's is that or 10 rows, whichever is larger (white data: 10 and 5 at order 1, the fixed kernels of earlier versions, which are requested with `weights_params={"var": 100}, delta_weights_params={"var": 25}`; recordings of up to 1000 timepoints: at most 10 samples at every order). With no kernel parameters and no events given and two-sided kernels (`include_timepoints="all"`), `features` passes each order's feeding features on at every `floor(sd / 2)`-th row while at least 1000 rows remain and returns every output at all timepoints by linear interpolation (`return_info` entries of automatic kernels have `kernel_sd` and `sampling`). With another kernel function, or `eye_weights` on the feeding path, None is that function's own defaults. `weights_params` / `delta_weights_params` also accept order maps (dicts whose keys are all integers in 1..order; missing orders use the default; `two_path_step`, exported as `tc.two_path_step`, raises for one). `rfun` / `delta_rfun` accept `"auto"` (the defaults; analysis: PCA at order 1, `WeightedStrength(signed=True)` above; feeding: `Communities()`, which needs >= 4 features and T >= 40 (with more features than distinct shift-null lags in `[L, T - L]`, each lag is used for several features, balanced, and features sharing a lag keep their dependence in that surrogate; for a built-in kernel without events, one-sided restriction or `exclude_timepoints` (`summaries._stationary`) the null's squared correlations are averaged over every s-th timepoint, s the kernel's standard deviation rounded down for a Gaussian: `summaries._null_row_stride`; for any other kernel (arrays, kernel functions of your own, restricted kernels), over every timepoint); when its communities would emit fewer than 4 columns, the step emits `WeightedStrength(split=False, signed=False, center=False)` instead, one column per input feature, warning only when the shift null found no structure) and dicts keyed by order. `return_info=True` returns `(result, info)` with one dict per step and path (reducers requested and used, widths, community counts, fallback reason; no arrays, but lists of ints: `"constant_columns"` in every entry, the output columns with `np.ptp(x, axis=0) == 0` in the returned arrays (after the interpolation to all timepoints; one list per subject for list outputs; for feeding features that are not returned, in the rows computed), and `"labels"` in feeding entries, the community of each input column when the step's output columns are the communities of a `Communities` object (the default's included), None after a fallback, for other reducers and for the name `"communities"`, whose fit is not kept; `tests/test_features_info.py`). Summary columns constant up to round-off (range <= 1e-9 * max|column|, or <= 1e-12 of the largest absolute value of the unit's output) are set to their means and reported by the constant-output warning. Steps with a summary reducer, `null_combine` and `autofc`/`isfc`/`wisfc` are streamed in blocks of nodes. The original two-path pipeline of the paper is `rfun="PCA", delta_rfun=None, delta_weights_function=tc.eye_weights` (pinned by `tests/test_legacy_pipeline.py`); the decoders always use co-fluctuations on the feeding path. Causal mode (keyword-only `causal`, `min_samples`, `fit_timepoints` in `features` and `two_path_step`; `refit_every`, `return_model` in `features` only; all but `causal` raise `ValueError` without `causal=True`): `_check_causal` raises before anything is computed for what has no causal form (missing kernel parameters on either path or order, `eye_weights`, forward kernels, `cfun=tc.wisfc` without fixed weights, events given as features, a `min_samples` no kernel reaches), `_check_refit_every` validates `refit_every`; `_check_streamed_steps(..., causal=True)` also checks the steps streamed with fixed-weight `wisfc` before order 1 runs; every causal `features` call is run by `model._causal_features` (reducers that need no fit, None and graph measures, have nothing to fit there; a fitted reducer, the defaults included, requires `fit_timepoints`), with `_causal_step` passing the estimator's causal arguments to each step's `timecorr` call and `_fit_pass` silencing the estimator's row warnings during the fit. Causal `return_info` entries add `"weights_params"` and `"warmup_rows"` (`_warmup_rows`: rows entirely NaN; per subject for lists), fitted steps `"fit_timepoints"`, `"refit_rows"`, `"refit_kept_previous"`; `_constant_columns(out, causal=True)` ignores NaN rows; summary columns are not set to their means and no constant-output warning is issued; non-causal entries keep their exact key sets. +- **`timecorr/model.py`**: causal features with fitted reducers: `FeaturesModel` (exported as `tc.FeaturesModel`; returned by `features(..., causal=True, return_model=True)`; attributes `order`, `fit_timepoints`, `refits`, `fits` (`{(order, path): fit}`), `info`, `n_features`, `n_subjects`, the kernels, `cfun`, `combine`, `include_zero`, `min_samples`, `ndims`, settable `max_memory_gb`; `transform(data, return_delta=False, return_info=False, *, events=None)` runs the pipeline on other data with the fits frozen; picklable unless the call had a lambda or local function; a pipeline with a fitted summary needs the number of subjects of the fit). `features` with `causal=True` calls `_causal_features`; with a fitted reducer `_single_fit` runs the pipeline on the first `fit_timepoints` rows alone, order by order (pass 1: every reducer fitted on those rows, each order's fit reading the feeding features of those rows), and `_causal_pass` runs it on every row with the fits frozen (pass 2), so the fits of a series and of a longer one with the same first rows are bit-identical. `refit_every=m` (`_refit`) repeats both passes for the fits at rows `n + j*m` and stitches rows `[s_j, s_{j+1})` from pass 2 of fit `j` (rows before `n` from fit 0); the structure is that of fit 0 (`_refit_settings`: the automatic feeding step's choice, number of components, and the output columns of a communities step, its communities of 2 or more nodes; `_same_width`: a refit clusters with fit 0's number of clusters n0, then n0 + 1, n0 - 1, ... up to n0 +- 5 (`_REFIT_CLUSTER_RANGE`; between 2 and the number of nodes), and takes the first clustering with that many such communities; `_effective`: the `"effective"` entry of a `Communities(n=...)` step shows the number of clusters of the fit the entry describes), each reducer's fit is matched to the fit before as soon as it is made (`_Matched`, `_match_model`: assignment by largest sum of absolute cosines of `components_`, signs set to agree; `_match_labels`: communities by most shared nodes), and a fit that cannot have the structure (`helpers._FitUnusable`) is left out for every order (the fit before stays; its row is in `"refit_kept_previous"`, and one `UserWarning` per call names the rows left out and the step). The model holds the last fit; summary objects passed as reducers keep fit 0's records in `fits_`. - **`timecorr/summaries.py`**: squared-correlation summaries `WeightedStrength` (weighted sums of squared correlations per node; `signed`, `split`; `center`: pair weights centered on the mean of their lower cluster (default), `"median"`, or `False`) and `Communities` (mean squared correlation within communities found by spectral k-means; `n=None` in `features` uses a shift null), with `fit`/`transform`/`fits_` (`transform(..., fit_index=...)` names the fitted unit of each unit), and the streaming engine used by `features`. - **`timecorr/decoding.py`**: timepoint decoders (`timepoint_decoder`, `weighted_timepoint_decoder`, `weighted_timepoint_decoder_ec`, `pca_decoder`) and their helpers. All four accept `events` / `events_params`, resolved once on the full subject list before the folds (per-subject entries follow their subject through the folds; segmentation does not advance NumPy's global random state): the correlation decoders restrict the analysis kernel at levels >= 1 and leave level 0 unchanged; `pca_decoder` restricts its level-0 smoothing kernel and takes one specification, not a dict by order. - **`timecorr/events.py`**: event-restricted kernels: parsing of `events` specifications into boundary sets (`resolve_events`, `resolve_events_by_order`, `check_boundaries`, `block_labels`), `mask_kernel` (zero weight between timepoints in different blocks), `distinct_event_sets`, and `segment` (hidden Markov model segmentation with hmmlearn: `kind="ordered"`, with `n` given or chosen automatically, or `kind="recurring"`). @@ -72,6 +74,7 @@ The `timecorr` function accepts: - `data`: numpy array, pandas DataFrame or polars DataFrame (timepoints x features), or a list of them (one per subject) - `weights_function` / `weights_params`: the kernel; row `t` of the kernel matrix (`weights[t, :]`) is the kernel used at timepoint `t` - `include_timepoints` (`'all'`, `'backward'`/`'pre'`, `'forward'`/`'post'`), `include_zero`, `exclude_timepoints`: restrict the kernel +- `causal` / `min_samples` / `fit_timepoints` (keyword-only): the causal mode (below) - `events` / `events_params`: restrict the kernel to blocks of consecutive timepoints (boundaries, features segmented with `segment`, or a per-subject list; in `features` and the correlation decoders also a dict keyed by order); also accepted by the decoders - `cfun`: correlation function: `isfc` (each subject versus the others), `wisfc` (weighted), `autofc` (within subject), or `None` (smoothing) - `combine`: how per-subject results are combined (`null_combine` keeps them separate) @@ -79,6 +82,8 @@ The `timecorr` function accepts: The estimator (`wcorr`) is a kernel-weighted Pearson correlation; a true delta kernel (`eye_weights`) gives co-fluctuations (products of z-scored series). It reads every kernel (a T x T array or a `LagKernel`) through `helpers._KernelRows`, in chunks of 128 rows (`_kernels.CHUNK`), each a contiguous block over its columns, with one span finder (`_time_slices`, which also reads the prepared rows of `_KernelRows`) and one rescaling of extreme rows, so an array and the equal `LagKernel` give identical results (`tests/test_chunked_kernels.py`; `tests/test_kernels_reference.py` compares with stored outputs of commit 6b3d23a, written by `tests/fixtures/make_chunked_kernels_reference.py`); blocks are kept up to `_KERNEL_CACHE_ELEMENTS` (32 MB) and computed again beyond it, and the kernel memory of a `LagKernel` is at most that plus about 4 blocks of 128 x T (`_kernel_work_elements`, used by `estimate_memory_gb`, whose keyword `weights_function` counts a user's kernel function as T x T arrays). Its kernel products are time sliced: each chunk is multiplied only with the span of columns where it has non-zero weight, unless the spans cover more than half the kernel or the samples, their squares or cross products are not all finite; then each chunk spans every column (`helpers._TIME_SLICING = False` forces that; `tests/test_time_sliced_estimation.py` compares both). The two differ only in the order of floating-point summation, but entries whose kernel-weighted variance nearly cancels are sensitive to that order in either path, so the tests compare those entries by a conditioning measure computed from the data and kernel. A kernel-weighted variance counts as zero (correlations 0, counted in the zero-variance warning) when it is at most 1e-10 of the mean square of the globally centered column or at the round-off level of the raw column (`helpers._zero_variance` and `_round_off_variance`, also used by the delta kernel's and `segment`'s z-scores). Columns are centered on their overall means, so with a one-sided kernel only well-conditioned estimates are independent of the excluded timepoints; estimates near the 1e-10 threshold can differ (`tests/test_estimator_causality.py`). Fisher z averaging and `tstat_combine` treat values at most `helpers._UNIT_TOLERANCE` (128 eps, 2.8e-14) below +-1 or at most 1e-12 above as +-1 (`helpers._correlation_z`). +Causal mode (`causal=True`; `tests/test_causal_*.py`). The guarantee as documented: row `t` is unchanged bit for bit when rows after `t` are replaced by any values (finite, NaN, inf), and to 1e-9 when they are removed, for outputs continuous in the correlations (no reduction, `"strength"`, the summaries, linear models once fitted); the eigenvector-based graph measures (`"eigenvector_centrality"`, the PageRank measures) can differ by more under removal where leading eigenvalues coincide, and the t statistics of `tstat_combine` where the subjects' correlations nearly coincide (always with two subjects and `isfc`; to about 1e-9 of their magnitude); smoothed values (`cfun=None`) agree under removal to round-off relative to the data's magnitude (1e-9 or 8 units in the last place of the largest magnitude); with `include_zero=False` row `t` is also unchanged when row `t` changes; with a fitted reducer the guarantee is for rows `t >= fit_timepoints`, and a row before is unchanged when rows from `fit_timepoints` on change. The kernel is backward (`'forward'`/`'post'` raise) and its parameters must be given (`weights_params=None` raises for every kernel; `{}` for one without parameters); `eye_weights`, `cfun=tc.wisfc` (but not `functools.partial(tc.wisfc, subject_weights=...)`, recognized as the built-in with fixed weights), events given as features, and a kernel array or user kernel function with weight above the diagonal (`_check_causal_kernel`) raise `ValueError`; a callable `cfun`/`combine`/`rfun` of the user's runs with one `UserWarning` that the guarantee does not cover it (`timecorr._builtin_combine` names the built-in combine functions); `timecorr(causal=True, cfun=None)` ignores `rfun` as without `causal`; event boundaries at or beyond the end of the data are ignored, so a prefix runs with the events of the whole series, and every prefix from T = 1 runs. The estimator (`helpers._causal_setup`, `_causal_block`): `_causal_clean` turns inf and `|x| > 1e150` (`_CAUSAL_MAX`) into NaN; a timepoint without any sample gets zero kernel columns; a row is defined (`_causal_defined`) with at least 3 observed timepoints of non-zero weight and, with `min_samples` (default None), an effective sample size `(sum |w|)**2 / sum w**2` over them of at least `min_samples` (relative tolerance 1e-12; smoothing uses the effective size only, per feature; a number no built-in kernel row can reach raises, decided from the lag profile by `_kernel_reach` / `_check_reachable`, independent of T; for a Mexican hat wider than about 2 million samples the reach is an upper bound about 1% above, `_strided_reach` with `_STRIDED_MARGIN` 1.01), and undefined rows are NaN, the diagonal included (zero-variance entries stay 0); chunks are always time sliced and computed a group of 16 rows at a time (`_CAUSAL_GROUP`, larger for chunks weighting more than `_CAUSAL_SPAN` = 512 columns), each group centered on the kernel-weighted mean of the observed samples at its first row (`_group_reference`; without one, `_causal_reference`: the mean of the earlier observed samples in the span, else the first observed sample), never on the overall mean; a row uses the sums for complete data exactly when no timepoint it weights has a NaN sample and the pairwise sums otherwise, so later values change no bit; the zero-variance rule (`_causal_zero_variance`) is `_zero_variance` about the group's reference or a kernel-weighted standard deviation below 1e-9 (`_CAUSAL_CONSTANT`) of `|kernel-weighted mean|` (a column constant up to round-off, which causal mode does not set to its mean). `mat2vec` zeroes NaN above the diagonal, so code that vectorizes causal correlations has to put the NaN rows back. Reducers in causal mode skip NaN rows (fits use defined rows; transforms return NaN rows as NaN; a defined row is one without any NaN or infinite value, `timecorr._defined_rows`, for models, summaries and graph measures alike: hypertools imputes from every row it is given and the summaries raise for NaN, so a partly NaN row, as of smoothing in `features`, is left out of fits and is a row of NaN in the output; streamed steps without `max_memory_gb` use the block size of data with NaN samples for every recording (`summaries._Units.has_nan`), so later NaN samples change no bit; a model needs 2 defined training rows, a summary 1, the shift null 40 rows) and combine functions give NaN on the union of the subjects' NaN rows; at orders >= 2 the NaN rows of the feeding features are missing data, so warm-up accumulates over orders. Hypertools models: the guarantee covers `_GUARANTEED_MODELS` of `timecorr.py` (scikit-learn's PCA, IncrementalPCA, TruncatedSVD, FastICA, FactorAnalysis, by exact class); any other model whose fitted estimator has `components_`, reproduces its training rows to 1e-9 and reduces rows one at a time as together is used with one `UserWarning` per call (`_uncovered_model`, `_warn_uncovered_models`); a model without `components_` or failing a check raises `ValueError` (UMAP, KernelPCA, Isomap, MDS, TSNE, SpectralEmbedding, LocallyLinearEmbedding); `"PCA"` is fitted with `svd_solver="full"` unless a model dict gives a solver; a model output column constant on the training rows up to round-off (`_FROZEN_RTOL` 1e-9, `_FROZEN_ZERO_RTOL` 1e-12) is frozen: a value within that tolerance of the column's training mean is returned as that mean, other values as computed; a model asked for at least as many components as columns changes nothing (zero columns appended). The warning text about undefined timepoints counts rows of the whole output (ruled not part of the guarantee, which is about returned values). + ### Data Flow 1. Inputs are formatted as float timepoints x features matrices (`format_data`) @@ -89,7 +94,7 @@ The estimator (`wcorr`) is a kernel-weighted Pearson correlation; a true delta k ## Testing Framework -- Uses `pytest`; tests are in `tests/` (one file per area: estimator, kernels, formatting, reduce, features, decoders, simulate, higher-order recovery, events (`test_events.py`), segmentation and on-demand installation (`test_segment.py`), recovery with event-restricted kernels (`test_events_recovery.py`), summaries and their streaming (`test_summaries.py`, `test_summaries_streaming.py`), the feeding path and reducer grammar in `features` (`test_features_summaries.py`), the defaults of `features` and `two_path_step` (`test_features_defaults.py`), their automatic kernels and the lower rate between orders (`test_features_auto_kernels.py`), the timepoints of the shift null (`test_shift_null_rows.py`), outputs and warnings of the original pipeline frozen at commit d4bb5ba (`test_legacy_pipeline.py`, `test_legacy_timecorr.py`), time-sliced versus full estimator products (`test_time_sliced_estimation.py`), features constant up to round-off (`test_round_off_variance.py`), what one-sided kernels guarantee (`test_estimator_causality.py`), kernels read in chunks of rows (`LagKernel`) versus T x T arrays, allocation and memory estimates at T up to 50,000 (`test_chunked_kernels.py`), outputs compared with those of commit 6b3d23a (`test_kernels_reference.py`; `tests/fixtures/chunked_kernels_reference.npz`), order-2 recovery on `simulate_nested` data (`test_nested_recovery.py`; its T 3000, isfc and K 702 cases are slow), kernels by order in `features` (`test_features_kernels_by_order.py`), `simulate_hierarchy` (`test_simulate_hierarchy.py`; reference values of the pre-`signs` output in `tests/fixtures/private_signs_reference.npz`, written by `tests/fixtures/make_private_signs_reference.py` at commit 012f5e0^), the example datasets (`test_datasets.py`: `fetch` on `file://` URLs, a real download of the French library archive (4 MB) and, slow, the story-listening data, read from the cache or downloaded (460 MB); a failed download fails the test), the video helpers, really drawn, encoded and decoded (`test_video.py`), the tutorial style (`test_tutorial_style.py`), the labels and constant columns of `return_info` (`test_features_info.py`), plus coverage files) +- Uses `pytest`; tests are in `tests/` (one file per area: estimator, kernels, formatting, reduce, features, decoders, simulate, higher-order recovery, events (`test_events.py`), segmentation and on-demand installation (`test_segment.py`), recovery with event-restricted kernels (`test_events_recovery.py`), summaries and their streaming (`test_summaries.py`, `test_summaries_streaming.py`), the feeding path and reducer grammar in `features` (`test_features_summaries.py`), the defaults of `features` and `two_path_step` (`test_features_defaults.py`), their automatic kernels and the lower rate between orders (`test_features_auto_kernels.py`), the timepoints of the shift null (`test_shift_null_rows.py`), outputs and warnings of the original pipeline frozen at commit d4bb5ba (`test_legacy_pipeline.py`, `test_legacy_timecorr.py`), time-sliced versus full estimator products (`test_time_sliced_estimation.py`), features constant up to round-off (`test_round_off_variance.py`), what one-sided kernels guarantee (`test_estimator_causality.py`), kernels read in chunks of rows (`LagKernel`) versus T x T arrays, allocation and memory estimates at T up to 50,000 (`test_chunked_kernels.py`), outputs compared with those of commit 6b3d23a (`test_kernels_reference.py`; `tests/fixtures/chunked_kernels_reference.npz`), the causal mode (`test_causal_estimator.py`: `causal`/`min_samples` in `timecorr`, `wcorr`, `autofc`, `isfc`, `wisfc`, replacement and removal at every row before several cuts of series with an offset column, a round-off-constant column, a random walk and NaN samples; `test_causal_features.py`: `features` and `two_path_step` with reducers that need no fit, NaN rows through the orders, argument errors, `return_info` entries; `test_causal_fit.py`: `fit_timepoints`, frozen reducers, `tc.FeaturesModel`, `transform`, pickling, equal outputs in two processes; `test_causal_refit.py`: `refit_every`, rows of segment j equal to a call with that fit alone, structure of fit 0, column matching; their exhaustive grids are marked slow, a covering subset runs in every run), the declared hypertools floor and the arguments of `hypertools.reduce` that are used (`test_packaging.py`), order-2 recovery on `simulate_nested` data (`test_nested_recovery.py`; its T 3000, isfc and K 702 cases are slow), kernels by order in `features` (`test_features_kernels_by_order.py`), `simulate_hierarchy` (`test_simulate_hierarchy.py`; reference values of the pre-`signs` output in `tests/fixtures/private_signs_reference.npz`, written by `tests/fixtures/make_private_signs_reference.py` at commit 012f5e0^), the example datasets (`test_datasets.py`: `fetch` on `file://` URLs, a real download of the French library archive (4 MB) and, slow, the story-listening data, read from the cache or downloaded (460 MB); a failed download fails the test), the video helpers, really drawn, encoded and decoded (`test_video.py`), the tutorial style (`test_tutorial_style.py`), the labels and constant columns of `return_info` (`test_features_info.py`), plus coverage files) - Tests run real computations on simulated data; no mocks - `pytest.ini` registers the `slow` marker for long-running integration tests (continuous integration runs them in a separate job on Python 3.12) - Docstring examples are tested with `pytest --doctest-modules timecorr/` @@ -100,13 +105,13 @@ The estimator (`wcorr`) is a kernel-weighted Pearson correlation; a true delta k - Sphinx with numpydoc, autosummary and nbsphinx; source in `docs/`; theme: Furo with the Contextual Dynamics Lab look shared with the htfa and hypertools documentation (Nunito Sans, lowercase light headings, green brand colors set in `html_theme_options` in `docs/conf.py`, rules in `docs/_static/custom.css`) - API pages: `docs/api.rst` (autosummary stubs in `docs/generated/`) - Gallery: the tutorials are the gallery. `docs/tutorials.rst` holds an nbsphinx `nbgallery` of the notebooks in `docs/tutorial/` (quickstart first); each card shows the image output of the notebook's one code cell tagged `nbsphinx-thumbnail` (a 4:3 picture without text, drawn from the notebook's own data by a cell near its end, after a one-line caption) and opens the notebook (card styles in `docs/_static/custom.css`, light and dark). `tests/test_docs_tutorials.py` checks that the gallery and the notebooks match, the thumbnail cell, the Colab badge, no error outputs, that relative links name tutorial notebooks (links to other doc pages are absolute `https://timecorr.readthedocs.io/en/latest/...` URLs, which also work on Colab), and that every public name is used (as `tc.`, imported or called; comments and strings do not count) in a tutorial's code cell -- Tutorial notebooks: `docs/tutorial/` (`quickstart`, `kernels`, `subjects`, `reduce`, `simulate`, `higher_order`, `events`, `decoding`, `htfa_network_animations`, `stocks`, `trajectories`; rendered without execution; execute them with nbconvert (needs jupyter) before committing, except the three real-data notebooks, which take minutes to tens of minutes and download data). Each starts with a Colab badge and a title cell; its first code cell installs, on Google Colab only, what the notebook imports: `timecorr` (`timecorr[segment]` for `events`, plus named packages such as polars where imported; the real-data notebooks install `timecorr[tutorials]` and `bottleneck>=1.5`, since pandas 3 warns about Colab's older bottleneck), with one shell line, `!pip install -q "timecorr>=0.3.1" ... || pip install -q "timecorr @ git+https://github.com/ContextLab/timecorr.git@master" ...`: release 0.3.1 or later (the first with the helpers the notebooks call) from PyPI, or git master when pip cannot install that (the cell prints nothing of its own; pip's error about PyPI shows before the fallback), and every notebook must run top to bottom in a fresh Colab runtime from that cell alone (the Colab badge is the way to run a tutorial; the docs give no other run instructions); text before a code cell is at most 3 short sentences, and numbers computed by the code are printed, not typed in the text. Code shared by notebooks lives in the package, not in the notebooks: the plot style of the eight simulated-data notebooks (`plt.style.use('timecorr.tutorial')`, with `COLORS` read from its color cycle), the data of the three real-data notebooks (`tc.datasets.story_listening`, `tc.datasets.industry_returns`, `tc.datasets.fetch`), their videos (`tc.render_video` calls the notebook's function that draws a run of frames; files go to `tc.media_dir()` and are shown with `tc.show_video`), community labels and constant columns (the `"labels"` and `"constant_columns"` entries of `return_info`). A thumbnail cell sets `%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}` and shows a 4 x 3 inch figure made with `dpi=150` (600 x 450 pixels). `higher_order.ipynb` holds the PCA event-contrast measurement that `simulate_data`'s order >= 3 warning cites. `htfa_network_animations.ipynb` downloads the HTFA fit of the story-listening data of Owen, Chang & Manning (2021) (460 MB archive, cached under `$TIMECORR_DATA`, default `~/timecorr_data`) and draws the features of orders 1 to 4 on the brain with the htfa toolbox; it writes its four 1920 x 1080, 30 fps H.264 movies (each drawn by one `htfa.animate_network` call of htfa 0.2.0: per-node colors, per-frame radii and edges, two views, caption and legend rows, frames rendered in parallel, a view that comes back black redrawn by htfa; encoded at CRF 23 with x264's preset `slow` and `+faststart`; its stills by `plot_network(..., views=, legend=, caption=)`; one frame per timepoint, 300 frames, 10 s; `QUALITY = 'full'`, chosen with 4 or more usable cores; with fewer, as on Colab, `'preview'` draws 960 x 540 frames of every 8th timepoint and also shows the full-quality videos of the online docs when reachable) to `docs/_static/tutorial_media/htfa_order{1..4}.mp4` (committed; at most about 8 MB each) and links them with `