From dfe024b2531cf1e8a5f9c241eb495065cf6c8064 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 10:44:29 -0500 Subject: [PATCH 01/26] Causal estimator: causal= and min_samples= in timecorr, wcorr, autofc, 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 646 ++++++++++++++++++++++++++++++++ timecorr/helpers.py | 665 ++++++++++++++++++++++++++++++--- timecorr/timecorr.py | 282 +++++++++++++- 3 files changed, 1541 insertions(+), 52 deletions(-) create mode 100644 tests/test_causal_estimator.py diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py new file mode 100644 index 00000000..293ac02e --- /dev/null +++ b/tests/test_causal_estimator.py @@ -0,0 +1,646 @@ +""" +The causal estimator: ``causal=True`` in ``timecorr``, ``wcorr``, ``autofc``, +``isfc`` and ``wisfc``. + +The guarantee: output row t is unchanged (to 1e-9, NaN rows included) when +the input rows after t are replaced by other finite values, by NaN, by inf, +or removed; with ``include_zero=False`` also when row t itself changes. The +tests check every row before several cut points of series of 300 +timepoints, with an offset column, a column constant up to round-off, a +random walk and NaN samples. Real computations; nothing is mocked. +""" + +import functools +import warnings + +import numpy as np +import pytest + +import timecorr as tc +from timecorr import helpers + +from .test_estimator_causality import _data as _conditioned_data +from .test_estimator_causality import _good + +ATOL = 1e-9 +T = 300 +CUTS = (3, 40, 127, 128, 129, 200, 257, 299) + +# name: (kernel function, parameters, min_samples). The t kernel has weight +# at every lag but is narrow whatever its df: a backward row has at most 2.6 +# effective samples (2.1 without the diagonal), so it is tested with +# min_samples=2 (with the default of 3 every row is NaN). +KERNELS = { + "gaussian": (tc.gaussian_weights, {"var": 25}, 3), + "laplace": (tc.laplace_weights, {"scale": 8}, 3), + "boxcar": (tc.boxcar_weights, {"width": 30}, 3), + "t": (tc.t_weights, {"df": 3}, 2), +} +SUBJECT_WEIGHTS = np.array([[0.0, 1.0, 0.5], [0.3, 0.0, 1.0], [1.0, 2.0, 0.0]]) +WISFC = functools.partial(tc.wisfc, subject_weights=SUBJECT_WEIGHTS) +# name: (cfun, number of subjects, combine) +CASES = { + "autofc": (tc.autofc, 1, tc.null_combine), + "isfc-null": (tc.isfc, 3, tc.null_combine), + "isfc-corrmean": (tc.isfc, 3, tc.corrmean_combine), + "wisfc-null": (WISFC, 3, tc.null_combine), + "wisfc-corrmean": (WISFC, 3, tc.corrmean_combine), + "smooth": (None, 1, tc.null_combine), + "smooth-subjects": (None, 3, tc.null_combine), +} +MODES = ("finite", "nan", "inf", "remove") + + +def _quiet(f, *args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return f(*args, **kwargs) + + +def _series(seed, n=T, K=5, missing=0.02): + rng = np.random.default_rng(seed) + x = rng.standard_normal((n, K)) + x[:, 0] += 1e6 # an offset + x[:, 2] = 2.0 * (1 + 1e-16 * rng.standard_normal(n)) # constant up to round-off + x[:, 3] = np.cumsum(rng.standard_normal(n)) # a random walk + x[rng.random((n, K)) < missing] = np.nan + return x + + +def _subjects(n_subjects, seed=0, missing=0.02): + return [_series(seed + s, missing=missing) for s in range(n_subjects)] + + +def _perturb(x, n, mode, rng): + """``x`` with rows ``n:`` replaced (finite values, NaN, inf) or removed.""" + if mode == "remove": + return x[:n].copy() + y = x.copy() + if mode == "finite": + y[n:] = rng.standard_normal(y[n:].shape) * 50 - 20 + elif mode == "nan": + y[n:] = np.nan + else: + y[n:] = np.where(rng.random(y[n:].shape) < 0.5, np.inf, -np.inf) + y[n:, 1] = 1e200 # squares overflow + return y + + +def _call(data, case, kernel, include_zero=True, **kwargs): + cfun, n_subjects, combine = CASES[case] + weights_function, weights_params, min_samples = KERNELS[kernel] + x = data[0] if n_subjects == 1 else data + return _quiet(tc.timecorr, x, causal=True, cfun=cfun, combine=combine, + weights_function=weights_function, weights_params=weights_params, + include_zero=include_zero, min_samples=min_samples, **kwargs) + + +def _as_list(out): + return out if isinstance(out, list) else [out] + + +def _max_difference(full, part, rows): + """Largest absolute difference over rows ``:rows``; NaN must match NaN.""" + worst = 0.0 + for f, p in zip(_as_list(full), _as_list(part)): + f, p = np.asarray(f)[:rows], np.asarray(p)[:rows] + assert f.shape == p.shape + assert np.array_equal(np.isnan(f), np.isnan(p)) + both = ~np.isnan(f) + if both.any(): + worst = max(worst, float(np.max(np.abs(f[both] - p[both])))) + return worst + + +# ---------------------------------------------------------------------------- +# the guarantee +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_rows_do_not_depend_on_later_rows(case, include_zero, kernel, mode): + data = _subjects(CASES[case][1]) + full = _call(data, case, kernel, include_zero) + rng = np.random.default_rng(7) + defined = 0 + for n in CUTS: + part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, + include_zero) + assert _max_difference(full, part, n) <= ATOL + defined += int(np.sum(~np.isnan(np.asarray(_as_list(part)[0])[:n]))) + assert defined > 0 # the comparison is not between NaN rows only + + +@pytest.mark.parametrize("missing", [0, 0.002]) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("case", ["autofc", "isfc-corrmean", "wisfc-null", "smooth"]) +def test_rows_do_not_depend_on_later_rows_with_few_missing_samples( + case, include_zero, kernel, mode, missing): + # without NaN samples (and with NaN samples in some chunks of kernel rows + # only) the estimator takes its path for complete data, and later NaN or + # inf rows change the path of the chunk they are in + data = _subjects(CASES[case][1], seed=30, missing=missing) + assert bool(missing) == any(np.isnan(x).any() for x in data) + full = _call(data, case, kernel, include_zero) + rng = np.random.default_rng(17) + for n in CUTS: + part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, + include_zero) + rows = n if include_zero or mode == "remove" else n + 1 + assert _max_difference(full, part, rows) <= ATOL + # (with the narrow t kernel, a missing sample leaves a feature of the + # smoothed data below min_samples for a row or two) + assert np.isnan(np.asarray(_as_list(full)[0])[20:]).mean() < 0.01 + + +@pytest.mark.parametrize("mode", ["finite", "nan", "inf"]) +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_without_the_diagonal_row_t_does_not_depend_on_row_t(case, kernel, mode): + data = _subjects(CASES[case][1]) + full = _call(data, case, kernel, include_zero=False) + rng = np.random.default_rng(8) + for n in CUTS: + # rows n: change; rows :n + 1 (row n included) must not + part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, + include_zero=False) + assert _max_difference(full, part, n + 1) <= ATOL + + +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_replacing_later_rows_with_finite_values_changes_no_bit(case, include_zero, + kernel): + data = _subjects(CASES[case][1]) + full = _call(data, case, kernel, include_zero) + rng = np.random.default_rng(9) + for n in CUTS: + part = _call([_perturb(x, n, "finite", rng) for x in data], case, kernel, + include_zero) + rows = n if include_zero else n + 1 + for f, p in zip(_as_list(full), _as_list(part)): + assert np.array_equal(np.asarray(f)[:rows], np.asarray(p)[:rows], + equal_nan=True) + + +def test_rows_do_not_depend_on_later_rows_with_event_boundaries(): + x = _series(3) + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}, + events=[90, 210]) + full = _quiet(tc.timecorr, x, **kw) + rng = np.random.default_rng(10) + for mode in ("finite", "nan", "inf"): + for n in CUTS: + part = _quiet(tc.timecorr, _perturb(x, n, mode, rng), **kw) + assert _max_difference(full, part, n) <= ATOL + # warm-up starts again at each block + nan_rows = np.flatnonzero(np.isnan(full).all(axis=1)) + assert {0, 1, 90, 91, 210, 211} <= set(nan_rows.tolist()) + assert not np.isnan(full[[89, 209, 299]]).any() + + +@pytest.mark.parametrize("mode", MODES) +def test_wcorr_rows_do_not_depend_on_later_rows(mode): + a, b = _series(11), _series(12) + rng = np.random.default_rng(13) + + def run(a, b): + w = tc.gaussian_weights(len(a), {"var": 25}, direction="backward") + return _quiet(tc.wcorr, a, b, w, causal=True) + + full = run(a, b) + for n in CUTS: + part = run(_perturb(a, n, mode, rng), _perturb(b, n, mode, rng)) + f, p = full[:, :, :n], part[:, :, :n] + assert np.array_equal(np.isnan(f), np.isnan(p)) + assert np.allclose(f, p, atol=ATOL, rtol=0, equal_nan=True) + assert np.sum(~np.isnan(full)) > 0 + + +def test_non_finite_and_overflowing_samples_are_missing(): + x = np.random.default_rng(0).standard_normal((120, 4)) + holes = [(5, 0), (40, 1), (41, 1), (90, 3), (119, 2)] + values = [np.inf, -np.inf, 1e200, -1e151, np.inf] + y, z = x.copy(), x.copy() + for (t, k), v in zip(holes, values): + y[t, k] = v + z[t, k] = np.nan + for cfun in (tc.autofc, None): + kw = dict(causal=True, cfun=cfun, weights_params={"var": 20}) + out = _quiet(tc.timecorr, y, **kw) + assert np.array_equal(out, _quiet(tc.timecorr, z, **kw), equal_nan=True) + assert not np.isnan(out[10:]).any() + + +# ---------------------------------------------------------------------------- +# agreement with the estimator of causal=False +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("cfun", ["autofc", "isfc", "wisfc"]) +def test_agrees_with_the_backward_kernel_of_causal_false(cfun): + subjects = [_conditioned_data(seed=s) for s in range(3)] + function = {"autofc": tc.autofc, "isfc": tc.isfc, + "wisfc": functools.partial(tc.wisfc, subject_weights=1.0)}[cfun] + kw = dict(cfun=function, combine=tc.null_combine, weights_params={"var": 30}) + causal = _quiet(tc.timecorr, subjects, causal=True, **kw) + plain = _quiet(tc.timecorr, subjects, include_timepoints="backward", **kw) + for s in range(3): + # entries that are well conditioned for the estimator of causal=False + # (the measure of test_estimator_causality.py) + good = _good(subjects, s, cfun, "backward") + defined = ~np.isnan(causal[s]).all(axis=1) + assert not np.isnan(causal[s][defined]).any() + assert defined.sum() >= 147 + good &= defined[:, np.newaxis] + assert good.mean() > 0.5 + assert np.max(np.abs(causal[s][good] - plain[s][good])) <= ATOL + + +def test_smoothing_agrees_with_the_backward_kernel_of_causal_false(): + x = np.random.default_rng(1).standard_normal((200, 4)) + x[30:33, 1] = np.nan + kw = dict(cfun=None, weights_params={"var": 30}) + causal = _quiet(tc.timecorr, x, causal=True, **kw) + plain = _quiet(tc.timecorr, x, include_timepoints="backward", **kw) + defined = ~np.isnan(causal) + assert defined[5:].all() and not defined[:2].any() + assert np.max(np.abs(causal[defined] - plain[defined])) <= 1e-12 + + +def test_default_is_not_causal(): + x = np.random.default_rng(2).standard_normal((80, 4)) + kw = dict(cfun=tc.autofc, weights_params={"var": 20}) + assert np.array_equal(_quiet(tc.timecorr, x, **kw), + _quiet(tc.timecorr, x, causal=False, min_samples=3, **kw)) + w = tc.gaussian_weights(80, {"var": 20}) + assert np.array_equal(_quiet(tc.wcorr, x, x, w), + _quiet(tc.wcorr, x, x, w, causal=False)) + + +# ---------------------------------------------------------------------------- +# warm-up rows +# ---------------------------------------------------------------------------- + + +def _expected_undefined(w, observed, min_samples, min_count=3): + """Rows of the kernel ``w`` below the rules, from the observed timepoints.""" + a = np.abs(w) * observed + count = (a != 0).sum(axis=1) + with np.errstate(invalid="ignore", divide="ignore"): + ess = a.sum(axis=1) ** 2 / (a**2).sum(axis=1) + ess = np.nan_to_num(ess) + return (count < min_count) | (ess < min_samples * (1 - 1e-12)) + + +def test_three_equal_weights_are_three_samples(): + x = np.random.default_rng(3).standard_normal((60, 4)) + # a backward boxcar over the lags 0, 1, 2: three weights of 1 from row 2 on + kw = dict(causal=True, cfun=tc.autofc, weights_function=tc.boxcar_weights, + weights_params={"width": 5}) + out = _quiet(tc.timecorr, x, min_samples=3, **kw) + nan_rows = np.isnan(out).all(axis=1) + assert np.array_equal(np.flatnonzero(nan_rows), [0, 1]) + assert not np.isnan(out[2:]).any() + # the default is 3 + assert np.array_equal(out, _quiet(tc.timecorr, x, **kw), equal_nan=True) + # a little more than 3 samples asks for more than the window has + assert np.isnan(_quiet(tc.timecorr, x, min_samples=3.001, **kw)).all() + # the same kernel as an array, in wcorr + w = np.tril(np.ones((60, 60))) - np.tril(np.ones((60, 60)), -3) + r = _quiet(tc.wcorr, x, x, w, causal=True) + assert np.array_equal(np.flatnonzero(np.isnan(r).all(axis=(0, 1))), [0, 1]) + assert not np.isnan(r[:, :, 2:]).any() + assert np.allclose(tc.mat2vec(r)[2:], out[2:], atol=1e-12, rtol=0) + + +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("var, min_samples", [(25, 3), (25, 8), (25, 10), (100, 10), + (25, 0)]) +def test_warm_up_rows_are_those_below_the_rules(include_zero, var, min_samples): + n = 150 + x = np.random.default_rng(4).standard_normal((n, 4)) + out = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, min_samples=min_samples, + weights_params={"var": var}, include_zero=include_zero) + w = tc.gaussian_weights(n, {"var": var}, direction="backward", + include_zero=include_zero) + expected = _expected_undefined(w, np.ones(n), min_samples) + assert np.array_equal(np.isnan(out).all(axis=1), expected) + assert not np.isnan(out[~expected]).any() + if (var, min_samples) == (25, 10): + # a backward Gaussian of variance 25 has fewer than 10 effective + # samples (9.4 with the diagonal) in every row + ess = w[-1].sum() ** 2 / (w[-1] ** 2).sum() + assert 8 < ess < 10 and expected.all() + return + first = int(np.flatnonzero(~expected)[0]) + assert np.array_equal(np.flatnonzero(expected), np.arange(first)) + if min_samples >= 8: + assert first > 5 # more leading rows than the three-sample rule gives + if min_samples == 3: + # three unequal weights are fewer than 3 effective samples + assert first == (3 if include_zero else 4) + if min_samples == 0: + assert first == (2 if include_zero else 3) # fewer than 3 samples + + +def test_rows_without_samples_do_not_count_as_observed(): + n = 120 + x = np.random.default_rng(5).standard_normal((n, 4)) + x[40:52] = np.nan # whole rows missing + x[80, 2] = np.nan # a single sample: the row is observed + out = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, min_samples=6, + weights_params={"var": 25}) + w = tc.gaussian_weights(n, {"var": 25}, direction="backward") + observed = (~np.isnan(x)).any(axis=1).astype(float) + expected = _expected_undefined(w, observed, 6) + assert np.array_equal(np.isnan(out).all(axis=1), expected) + assert not np.isnan(out[~expected]).any() + assert expected[45:55].all() and not expected[70:].any() + + +def test_a_kernel_too_narrow_for_min_samples_gives_no_defined_row(): + x = np.random.default_rng(3).standard_normal((80, 3)) + kw = dict(causal=True, weights_function=tc.t_weights, weights_params={"df": 3}) + for cfun in (tc.autofc, None): + with pytest.warns(UserWarning, match="80"): + out = tc.timecorr(x, cfun=cfun, **kw) + assert np.isnan(out).all() + assert not np.isnan(_quiet(tc.timecorr, x, cfun=cfun, min_samples=2, + **kw)[10:]).any() + + +def test_zero_variance_entries_stay_zero(): + x = np.random.default_rng(6).standard_normal((100, 4)) + x[:, 1] = 7.0 + out = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, + weights_params={"var": 25}) + assert np.isnan(out[:3]).all() and not np.isnan(out[3:]).any() + full = tc.vec2mat(out[3:]) # (K, K, T - 3) + assert np.all(full[1, :, :] == 0) and np.all(full[:, 1, :] == 0) + assert np.all(full[[0, 2, 3], [0, 2, 3], :] == 1) + assert np.any(full[0, 2, :] != 0) + + +def test_warning_names_the_undefined_rows(): + x = np.random.default_rng(7).standard_normal((90, 3)) + w = tc.gaussian_weights(90, {"var": 25}, direction="backward") + n8 = int(_expected_undefined(w, np.ones(90), 8).sum()) + assert n8 > 5 + with pytest.warns(UserWarning, match=rf"^{n8} of 90 timepoints .* NaN"): + out = tc.timecorr(x, causal=True, cfun=tc.autofc, min_samples=8, + weights_params={"var": 25}) + assert np.array_equal(np.flatnonzero(np.isnan(out).all(axis=1)), np.arange(n8)) + with pytest.warns(UserWarning, match=r"^3 of 90 timepoints .* NaN"): + tc.wcorr(x, x, w, causal=True) + with pytest.warns(UserWarning, match=r"^2 of 90 timepoints .* NaN"): + tc.autofc(x, w, causal=True, min_samples=0) + with pytest.warns(UserWarning, match=r"[Ss]moothing .* 3 timepoint"): + tc.timecorr(x, causal=True, cfun=None, weights_params={"var": 25}) + # one warning per call + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + tc.timecorr([x, x + 1, x * 2], causal=True, weights_params={"var": 25}) + assert len(caught) == 1 + + +def test_smoothing_warm_up_is_per_feature(): + n = 80 + x = np.random.default_rng(8).standard_normal((n, 3)) + x[20:40, 1] = np.nan + out = _quiet(tc.timecorr, x, causal=True, cfun=None, min_samples=4, + weights_params={"var": 25}) + w = tc.gaussian_weights(n, {"var": 25}, direction="backward") + for k in range(3): + observed = (~np.isnan(x[:, k])).astype(float) + expected = _expected_undefined(w, observed, 4, min_count=0) + assert np.array_equal(np.isnan(out[:, k]), expected) + assert np.isnan(out[30, 1]) and not np.isnan(out[30, [0, 2]]).any() + + +# ---------------------------------------------------------------------------- +# the correlation functions, called directly +# ---------------------------------------------------------------------------- + + +def test_correlation_functions_called_directly(): + data = [np.random.default_rng(s).standard_normal((100, 4)) for s in range(3)] + w = tc.gaussian_weights(100, {"var": 16}, direction="backward") + kw = dict(causal=True, weights_params={"var": 16}, combine=tc.null_combine) + for cfun, direct in ( + (tc.autofc, lambda: tc.autofc(data, w, causal=True)), + (tc.isfc, lambda: tc.isfc(data, w, causal=True)), + (WISFC, lambda: tc.wisfc(data, w, subject_weights=SUBJECT_WEIGHTS, + causal=True)), + ): + expected = _quiet(tc.timecorr, data, cfun=cfun, **kw) + got = _quiet(direct) + for e, g in zip(expected, got): + assert np.isnan(g[:3]).all() and not np.isnan(g[3:]).any() + assert np.allclose(e, g, atol=1e-12, rtol=0, equal_nan=True) + # a single array, and wcorr + one = _quiet(tc.autofc, data[0], w, causal=True, min_samples=6) + r = _quiet(tc.wcorr, data[0], data[0], w, causal=True, min_samples=6) + assert one.shape == (100, 10) and r.shape == (4, 4, 100) + undefined = np.isnan(r).all(axis=(0, 1)) + assert 3 < undefined.sum() < 50 and not np.isnan(r[:, :, ~undefined]).any() + assert np.array_equal(np.isnan(one).all(axis=1), undefined) + # (mat2vec itself sets NaN above the diagonal to 0) + assert np.array_equal(one[~undefined], tc.mat2vec(r)[~undefined]) + assert np.all(r[[0, 1, 2, 3], [0, 1, 2, 3], 50] == 1) + + +def test_streamed_rows_equal_wcorr(): + x = _series(20, n=200, K=6) + w = helpers._lag_kernel(200, tc.gaussian_weights, {"var": 25}, "backward") + for a, b, symmetric in ((x, x, True), (x, _series(21, n=200, K=6), False)): + full = _quiet(helpers._wcorr, a, b, w, warn=False, causal=True, min_samples=5, + autocorrelation=symmetric) + got = np.empty_like(full) + for i0, i1, R, _, _ in helpers._corr_row_blocks(a, b, w, symmetric, 2, + causal=True, min_samples=5): + got[i0:i1] = R + assert np.array_equal(np.isnan(full), np.isnan(got)) + assert np.isnan(full[:, :, 0]).all() and not np.isnan(full[:, :, 20:]).any() + assert np.allclose(full, got, atol=1e-12, rtol=0, equal_nan=True) + + +# ---------------------------------------------------------------------------- +# arguments +# ---------------------------------------------------------------------------- + +X = np.random.default_rng(0).standard_normal((60, 4)) +OK = dict(causal=True, cfun=tc.autofc, weights_params={"var": 9}) + + +def test_backward_kernel_is_implied(): + out = _quiet(tc.timecorr, X, **OK) + for side in ("backward", "pre", "BACKWARD"): + assert np.array_equal(out, _quiet(tc.timecorr, X, include_timepoints=side, **OK), + equal_nan=True) + + +@pytest.mark.parametrize("side", ["forward", "post", "Forward"]) +def test_forward_kernels_raise(side): + with pytest.raises(ValueError, match="backward"): + tc.timecorr(X, include_timepoints=side, **OK) + + +def test_kernel_parameters_are_required(): + with pytest.raises(ValueError, match="weights_params"): + tc.timecorr(X, causal=True, cfun=tc.autofc) + + +def test_delta_kernel_raises(): + with pytest.raises(ValueError, match="eye_weights"): + tc.timecorr(X, causal=True, cfun=tc.autofc, weights_function=tc.eye_weights, + weights_params={}) + with pytest.raises(ValueError, match="delta"): + tc.wcorr(X, X, np.eye(60), causal=True) + with pytest.raises(ValueError, match="delta"): + tc.autofc(X, np.eye(60), causal=True) + + +def test_wisfc_needs_fixed_subject_weights(): + data = [X, X[::-1].copy(), X**2] + with pytest.raises(ValueError, match="subject_weights"): + tc.timecorr(data, causal=True, cfun=tc.wisfc, weights_params={"var": 9}) + with pytest.raises(ValueError, match="subject_weights"): + tc.timecorr(data, causal=True, cfun=functools.partial(tc.wisfc), + weights_params={"var": 9}) + w = tc.gaussian_weights(60, {"var": 9}, direction="backward") + with pytest.raises(ValueError, match="subject_weights"): + tc.wisfc(data, w, causal=True) + # fixed weights: the built-in function, without the warning of a callable + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + out = tc.timecorr(data, causal=True, weights_params={"var": 9}, + cfun=functools.partial(tc.wisfc, subject_weights=1.0)) + assert not [c for c in caught if "guarantee" in str(c.message)] + direct = _quiet(tc.wisfc, data, w, subject_weights=1.0, causal=True) + for o, d in zip(out, direct): + assert np.allclose(o, d, atol=1e-12, rtol=0, equal_nan=True) + + +def test_events_must_be_boundaries(): + features = np.random.default_rng(1).standard_normal((60, 3)) + with pytest.raises(ValueError, match="boundaries"): + tc.timecorr(X, events=features, **OK) + with pytest.raises(ValueError, match="boundaries"): + tc.timecorr([X, X + 1], events=[[30], features], **OK) + out = _quiet(tc.timecorr, X, events=[30], **OK) + assert out.shape == (60, 10) + out = _quiet(tc.timecorr, [X, X + 1], events=[[30], None], **OK) + assert len(out) == 2 + + +def test_kernels_with_weight_on_later_timepoints_raise(): + two_sided = tc.gaussian_weights(60, {"var": 9}) + with pytest.raises(ValueError, match="later timepoints"): + tc.wcorr(X, X, two_sided, causal=True) + with pytest.raises(ValueError, match="later timepoints"): + tc.autofc(X, two_sided, causal=True) + with pytest.raises(ValueError, match="later timepoints"): + tc.isfc([X, X + 1], two_sided, causal=True) + with pytest.raises(ValueError, match="later timepoints"): + tc.wcorr(X, X, helpers._lag_kernel(60, tc.gaussian_weights, {"var": 9}), + causal=True) + for cfun in (tc.autofc, None): + with pytest.raises(ValueError, match="later timepoints"): + tc.timecorr(X, causal=True, cfun=cfun, weights_params={}, + weights_function=lambda T, p: tc.gaussian_weights(T, {"var": 9})) + # a function of the user's that returns a backward kernel is accepted + out = _quiet( + tc.timecorr, X, causal=True, cfun=tc.autofc, weights_params={"var": 9}, + weights_function=lambda T, p: tc.gaussian_weights(T, p, direction="backward")) + assert np.allclose(out, _quiet(tc.timecorr, X, **OK), atol=1e-12, rtol=0, + equal_nan=True) + + +def test_a_correlation_function_of_the_users_warns_once(): + def mine(data, weights): + return tc.autofc(data, weights) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + out = tc.timecorr(X, causal=True, cfun=mine, weights_params={"var": 9}) + messages = [str(c.message) for c in caught if "guarantee" in str(c.message)] + assert len(messages) == 1 and "cfun" in messages[0] + assert issubclass( + [c for c in caught if "guarantee" in str(c.message)][0].category, UserWarning) + # it received the backward kernel as a T x T array + plain = _quiet(tc.timecorr, X, cfun=tc.autofc, weights_params={"var": 9}, + include_timepoints="backward") + assert np.array_equal(out, plain) + + +def test_a_reducer_of_the_users_warns_once(): + def mine(arrays): + return [np.nan_to_num(a[:, :2]) for a in arrays] + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + out = tc.timecorr(X, rfun=mine, **OK) + messages = [str(c.message) for c in caught if "guarantee" in str(c.message)] + assert len(messages) == 1 and "rfun" in messages[0] + assert out.shape == (60, 2) + + +@pytest.mark.parametrize("rfun", [ + "PCA", {"model": "PCA"}, "weighted_strength", "weighted_strength_split", + "communities", tc.WeightedStrength(), tc.Communities(n=2), +], ids=str) +def test_fitted_reducers_are_not_implemented_yet(rfun): + with pytest.raises(NotImplementedError, match="fit_timepoints"): + tc.timecorr(X, rfun=rfun, **OK) + + +@pytest.mark.parametrize("rfun", ["strength", "eigenvector_centrality", + "pagerank_centrality_abs"]) +def test_graph_measures_run_on_the_defined_rows(rfun): + out = _quiet(tc.timecorr, X, rfun=rfun, **OK) + corrs = _quiet(tc.timecorr, X, **OK) + defined = ~np.isnan(corrs).all(axis=1) + assert out.shape == (60, 4) + assert np.array_equal(np.isnan(out).all(axis=1), ~defined) + assert not np.isnan(out[defined]).any() + assert np.allclose(out[defined], _quiet(tc.reduce, corrs[defined], rfun=rfun), + atol=1e-12, rtol=0) + # and in a list of subjects + outs = _quiet(tc.timecorr, [X, X[::-1].copy()], rfun=rfun, **OK) + assert len(outs) == 2 and np.isnan(outs[1][:3]).all() + assert not np.isnan(outs[1][3:]).any() + + +@pytest.mark.parametrize("bad", [-1, np.nan, np.inf, "3", None, True]) +def test_min_samples_must_be_a_number(bad): + with pytest.raises(ValueError, match="min_samples"): + tc.timecorr(X, min_samples=bad, **OK) + w = tc.gaussian_weights(60, {"var": 9}, direction="backward") + with pytest.raises(ValueError, match="min_samples"): + tc.wcorr(X, X, w, causal=True, min_samples=bad) + + +def test_min_samples_needs_causal(): + with pytest.raises(ValueError, match="causal=True"): + tc.timecorr(X, cfun=tc.autofc, weights_params={"var": 9}, min_samples=5) + with pytest.raises(ValueError, match="causal=True"): + tc.wcorr(X, X, tc.gaussian_weights(60, {"var": 9}), min_samples=5) + + +def test_new_arguments_are_keyword_only(): + w = tc.gaussian_weights(60, {"var": 9}, direction="backward") + with pytest.raises(TypeError): + tc.wcorr(X, X, w, True) + with pytest.raises(TypeError): + tc.autofc(X, w, True) + with pytest.raises(TypeError): + tc.isfc(X, w, True) + with pytest.raises(TypeError): + tc.wisfc(X, w, 1.0, True) diff --git a/timecorr/helpers.py b/timecorr/helpers.py index 8e90fc7b..93b663d6 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -556,7 +556,8 @@ def _kernel_row_problems(weights): return undefined, ~undefined & (ess < 2) -def _estimator_message(weights, cancelled=None, sparse=None): +def _estimator_message(weights, cancelled=None, sparse=None, warmup=None, + min_samples=None): """ The one warning of a correlation call, or None. @@ -567,11 +568,31 @@ def _estimator_message(weights, cancelled=None, sparse=None): (undefined, set to 0), and the timepoints (``cancelled``, a boolean mask) where every correlation was set to 0 because the kernel-weighted variances there are zero. + + ``warmup`` (the causal estimator: a boolean mask of its undefined rows, + with ``min_samples``) replaces the first of these: the message names how + many rows are undefined and returned as NaN. """ T = _kernel_shape(weights)[0] parts = [] problems = _kernel_row_problems(weights) - if problems is not None: + if warmup is not None: + if np.any(warmup): + parts.append( + f"{int(np.sum(warmup))} of {T} timepoints have fewer than 3 " + "weighted, observed samples or an effective sample size " + "((sum |w|)**2 / sum w**2 over the kernel row) below " + f"min_samples={min_samples:g}; their correlations are undefined " + "and returned as NaN (causal=True)." + ) + low = None if problems is None else problems[1] & ~warmup + if low is not None and low.any(): + parts.append( + f"{int(low.sum())} of {T} timepoints have an effective sample size " + "((sum |w|)**2 / sum w**2 over the kernel row) below 2; the kernel " + "is too narrow to estimate correlations reliably there." + ) + elif problems is not None: undefined, low = problems if undefined.any(): parts.append( @@ -1025,8 +1046,12 @@ def zero_rows(self, mask): """Set the rows in ``mask`` to 0 (before ``prepare``).""" self.zero = np.asarray(mask, dtype=bool) - def prepare(self, finite): - """Rescale the extreme rows and choose each chunk's columns.""" + def prepare(self, finite, always=False): + """ + Rescale the extreme rows and choose each chunk's columns + (``always``: the columns where the chunk has weight, however much of + the kernel they cover, as the causal estimator needs). + """ T_out = self.shape[0] T = self.shape[1] if len(self.shape) == 2 else 0 peak = self._peak if self.zero is None else np.where(self.zero, 0.0, self._peak) @@ -1040,7 +1065,10 @@ def prepare(self, finite): self._cache = {} self._cached = 0 self._kept = set() - slices = _time_slices(self, finite) if len(self.shape) == 2 else None + slices = None + if len(self.shape) == 2: + slices = (_time_slices(self, finite, True) if always + else _time_slices(self, finite)) if slices is None: slices = [(t0, t1, 0, T) for t0, t1, _, _, _ in self._chunks] self.spans = slices @@ -1200,7 +1228,7 @@ def _wcorr_inputs(a, b, weights): return a, b, rows -def _time_slices(weights, finite=True): +def _time_slices(weights, finite=True, always=False): """ Chunks of a kernel's rows and the span of columns where each has weight, or None when slicing would not save work. @@ -1216,12 +1244,13 @@ def _time_slices(weights, finite=True): products have non-finite operands, where the full products give ``0 * inf = NaN`` that slicing would skip), when T' or T is 0, or when the spans cover more than ``_TIME_SLICE_MAX_FRACTION`` of the kernel's - entries. + entries. ``always=True`` (the causal estimator) returns the spans + whatever ``_TIME_SLICING``, ``finite`` and the fraction covered are. """ kernel = as_kernel(weights) T_out, T = kernel.shape slices = None - if _TIME_SLICING and finite and T_out and T: + if (always or (_TIME_SLICING and finite)) and T_out and T: slices, covered = [], 0 for t0, t1, c0, _, _, w in blocks(kernel, CHUNK): cols = (w != 0).any(axis=0) @@ -1232,7 +1261,7 @@ def _time_slices(weights, finite=True): s0 = s1 = 0 slices.append((t0, t1, s0, s1)) covered += (t1 - t0) * (s1 - s0) - if covered > _TIME_SLICE_MAX_FRACTION * T_out * T: + if not always and covered > _TIME_SLICE_MAX_FRACTION * T_out * T: slices = None if _time_slice_log is not None: _time_slice_log.append(slices) @@ -1319,6 +1348,8 @@ def _wcorr_block(state, i0, i1, j0): whether some pair has fewer than 3 observed samples with non-zero weight (always False without NaN samples). """ + if state.get("causal"): + return _causal_block(state, i0, i1, j0) T = state["T"] rows = state["rows"] Kb = state["b"].shape[1] @@ -1373,6 +1404,15 @@ def _wcorr_block(state, i0, i1, j0): undefined = zero | few zero_all = zero.reshape(shape[0], -1).all(axis=1) + r = _correlation_ratio(num, var_a, var_b, undefined, shape) + return r, undefined, zero_all, few_any + + +def _correlation_ratio(num, var_a, var_b, undefined, shape): + """ + ``num / sqrt(var_a * var_b)`` clipped to [-1, 1], with 0 where + ``undefined``; arrays of ``shape`` (the variances may broadcast to it). + """ with np.errstate(over="ignore", under="ignore"): product = np.where(undefined, 1.0, var_a * var_b) den = np.sqrt(product) @@ -1384,7 +1424,321 @@ def _wcorr_block(state, i0, i1, j0): np.sqrt(np.broadcast_to(var_a, shape)[extreme]) * np.sqrt(np.broadcast_to(var_b, shape)[extreme]) ) - r = np.where(undefined, 0.0, np.clip(num / den, -1.0, 1.0)) + return np.where(undefined, 0.0, np.clip(num / den, -1.0, 1.0)) + + +# ---------------------------------------------------------------------------- +# the causal estimator (``causal=True``) +# ---------------------------------------------------------------------------- + +# Samples larger than this in magnitude (their squares overflow), and +# infinite ones, are missing data for the causal estimator. +_CAUSAL_MAX = 1e150 +# Relative tolerance of the comparison of a row's effective sample size with +# ``min_samples`` (three equal weights give 3 up to round-off). +_MIN_SAMPLES_RTOL = 1e-12 + + +def _check_min_samples(min_samples, causal): + """ + ``min_samples`` as a float; ``ValueError`` unless it is a finite number + >= 0, and when it is given (not 3) without ``causal=True``. + """ + if ( + isinstance(min_samples, (bool, np.bool_)) + or not isinstance(min_samples, numbers.Real) + or not 0 <= min_samples < np.inf + ): + raise ValueError( + "min_samples must be a finite number >= 0 (the effective number of " + f"weighted samples a row needs); got {min_samples!r}." + ) + if not causal and min_samples != 3: + raise ValueError( + f"min_samples={min_samples!r} applies with causal=True only; pass " + "causal=True, or leave min_samples at its default." + ) + return float(min_samples) + + +def _causal_clean(x): + """ + ``x`` as the causal estimator reads it: infinite samples and samples + above ``_CAUSAL_MAX`` in magnitude are NaN (missing). ``x`` itself when + it has none, otherwise a copy. + """ + x = np.asarray(x, dtype=np.float64) + with np.errstate(invalid="ignore"): + bad = np.abs(x) > _CAUSAL_MAX + if bad.any(): + x = x.copy() + x[bad] = np.nan + return x + + +def _abs_weights(w): + """The absolute values of a kernel block, NaN weights as 0 (a new array).""" + w = np.abs(w) + w[np.isnan(w)] = 0 + return w + + +def _check_causal_kernel(weights, what="the kernel"): + """ + ``ValueError`` if a (T', T) kernel (an array or a ``LagKernel``) has + weight above its diagonal: row t would weight timepoints after t. + """ + kernel = as_kernel(weights) + if isinstance(kernel, LagKernel) and kernel.include == "backward": + return + if len(kernel.shape) != 2: + return + for t0, t1, c0, c1, _, w in blocks(kernel, CHUNK): + later = np.triu(w, t0 - c0 + 1) + if np.any((later != 0) & ~np.isnan(later)): + raise ValueError( + f"causal=True: {what} gives weight to later timepoints (it has " + "non-zero entries above its diagonal). Pass a kernel whose row " + "t weights only timepoints at or before t, for example " + "tc.one_sided(weights, 'backward') or a kernel function called " + "with direction='backward'." + ) + + +def _check_causal_rows(rows): + """The checks of a causal call on its kernel (a ``_KernelRows``).""" + if np.all(rows.support == 1): + raise ValueError( + "causal=True: a delta kernel (one non-zero weight in every row, as " + "eye_weights gives) yields co-fluctuations of series z-scored over " + "the whole recording, which use later timepoints. Pass a kernel " + "with at least 3 weights per row, for example " + "tc.boxcar_weights(T, {'width': 5}, direction='backward')." + ) + _check_causal_kernel(rows.kernel) + + +def _causal_defined(kernel, observed, min_samples, min_count=3): + """ + The rows of a causal kernel that are defined: at least ``min_count`` + observed timepoints with non-zero weight, and an effective sample size + ``(sum |w|)**2 / sum w**2`` over the observed timepoints of at least + ``min_samples`` (relative tolerance ``_MIN_SAMPLES_RTOL``). + + ``observed`` is a boolean vector over the T timepoints (a timepoint with + no sample at all is not observed). Each row is scaled by its largest + weight first, so tiny weights do not underflow when squared. + """ + T_out = kernel.shape[0] + count = np.zeros(T_out, dtype=np.int64) + ess = np.zeros(T_out) + everything = bool(np.all(observed)) + observed = np.asarray(observed, dtype=np.float64) + seen = {} + for t0, t1, c0, c1, key, w in blocks(kernel, CHUNK, _abs_weights): + stats = seen.get(key) if (key is not None and everything) else None + if stats is None: + if not everything: + w = w * observed[c0:c1] + n = np.count_nonzero(w, axis=1) + peak = w.max(axis=1, keepdims=True, initial=0.0) + with np.errstate(invalid="ignore"): + w = np.divide(w, peak, out=np.zeros_like(w), where=peak != 0) + total = w.sum(axis=1) + np.multiply(w, w, out=w) + stats = n, _safe_divide(total**2, w.sum(axis=1)) + if key is not None and everything: + seen[key] = stats + count[t0:t1], ess[t0:t1] = stats + with np.errstate(invalid="ignore"): + enough = ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) + return (count >= min_count) & enough + + +def _causal_reference(x, c0, t0, c1): + """ + The centering reference of the columns of ``x`` for a chunk of kernel + rows that starts at row ``t0`` and weights rows ``c0:c1``: the mean of + each column's observed samples in rows ``c0:t0`` (before every row of the + chunk); for a column without any, its first observed sample in rows + ``c0:c1`` (0 when it has none). A row of the chunk that has samples of + the column has that first sample in its past, so no row's reference + holds a sample from its future. + """ + past = x[c0:max(c0, t0)] + ok = ~np.isnan(past) + n = ok.sum(axis=0) + ref = _safe_divide(np.where(ok, past, 0.0).sum(axis=0), n) + none = n == 0 + if none.any(): + span = x[c0:c1][:, none] + ok = ~np.isnan(span) + first = span[ok.argmax(axis=0), np.arange(span.shape[1])] + ref[none] = np.where(ok.any(axis=0), first, 0.0) + return ref + + +def _causal_setup(a, b, rows, autocorrelation, min_samples): + """ + ``_wcorr_setup`` for the causal estimator (``a`` and ``b`` from + ``_causal_clean``, the kernel checked by ``_check_causal_rows``). + + Nothing computed for a kernel row uses a sample after the row: + + - the undefined rows (``_causal_defined``, from the timepoints where + both ``a`` and ``b`` have a sample) are set to 0 here and to NaN in the + output; + - every chunk of ``CHUNK`` rows is multiplied with the columns where it + has weight, whatever fraction of the kernel they cover; + - each chunk centers the data on its own reference + (``_causal_reference``), and the zero-variance rule compares a + variance with the kernel-weighted mean square about that reference; + - a chunk takes the path for NaN samples when its columns hold one, so + samples outside its columns do not choose the path. + + Returns a dict with ``"causal": True`` for ``_wcorr_block``. + """ + T_out = rows.shape[0] + Ka, Kb = a.shape[1], b.shape[1] + nan_a = np.isnan(a) + nan_b = nan_a if autocorrelation else np.isnan(b) + defined = _causal_defined( + rows.kernel, ~nan_a.all(axis=1) & ~nan_b.all(axis=1), min_samples + ) + rows.zero_rows(~defined) + rows.prepare(True, always=True) + # rows with a NaN sample before each row, to ask whether a span has one + nan_before = np.concatenate([[0], np.cumsum(nan_a.any(axis=1) | nan_b.any(axis=1))]) + del nan_a, nan_b + n = len(rows.spans) + state = { + "causal": True, "T": a.shape[0], "rows": rows, "a": a, "b": b, + "defined": defined, + "nan": np.zeros(n, dtype=bool), + "ref_a": np.zeros((n, Ka)), + "sw": np.zeros((T_out, 1)), + "ma": np.zeros((T_out, Ka)), "wa": np.zeros((T_out, Ka)), + "va": np.zeros((T_out, Ka)), "za": np.ones((T_out, Ka), dtype=bool), + } + if autocorrelation: + state.update(ref_b=state["ref_a"], mb=state["ma"], wb=state["wa"], + vb=state["va"], zb=state["za"]) + else: + state.update({ + "ref_b": np.zeros((n, Kb)), + "mb": np.zeros((T_out, Kb)), "wb": np.zeros((T_out, Kb)), + "vb": np.zeros((T_out, Kb)), "zb": np.ones((T_out, Kb), dtype=bool), + }) + active = np.zeros(T_out, dtype=bool) + + def moments(x, ref, A, W, s, t0, t1, side): + x = x - ref + mean = _safe_divide(A @ x, s) + msq = A @ x**2 + var = msq - s * mean**2 + zero = _zero_variance(var, msq, s, mean + ref) + state["m" + side][t0:t1] = mean + state["w" + side][t0:t1] = W @ x + state["v" + side][t0:t1] = np.where(zero, 0.0, var) + state["z" + side][t0:t1] = zero + + for i, (t0, t1, c0, c1) in enumerate(rows.spans): + if c1 <= c0: + continue + A = rows._block(i, "a") + s = A.sum(axis=1)[:, np.newaxis] + active[t0:t1] = s[:, 0] > 0 + state["nan"][i] = nan_before[c1] > nan_before[c0] + state["ref_a"][i] = _causal_reference(a, c0, t0, c1) + if not autocorrelation: + state["ref_b"][i] = _causal_reference(b, c0, t0, c1) + if not state["nan"][i]: + W = rows._block(i, "w") + state["sw"][t0:t1, 0] = W.sum(axis=1) + moments(a[c0:c1], state["ref_a"][i], A, W, s, t0, t1, "a") + if not autocorrelation: + moments(b[c0:c1], state["ref_b"][i], A, W, s, t0, t1, "b") + state["active"] = active + state["has_nan"] = bool(state["nan"].any()) + state["n_products"] = _WCORR_NAN_PRODUCTS if state["has_nan"] else 1 + return state + + +def _causal_block(state, i0, i1, j0): + """ + ``_wcorr_block`` for the causal estimator (``state`` from + ``_causal_setup``): the same sums, a chunk of kernel rows at a time, + each over its own columns and about its own centering reference. + """ + rows = state["rows"] + a, b = state["a"], state["b"] + shape = (rows.shape[0], i1 - i0, b.shape[1] - j0) + r = np.zeros(shape) + undefined = np.ones(shape, dtype=bool) + zero_all = np.ones(shape[0], dtype=bool) + few_any = np.zeros(shape[0], dtype=bool) + for i, (t0, t1, c0, c1) in enumerate(rows.spans): + if c1 <= c0: + continue + L = c1 - c0 + sub = (t1 - t0,) + shape[1:] + ref_a = state["ref_a"][i, i0:i1] + ref_b = state["ref_b"][i, j0:] + xa = a[c0:c1, i0:i1] - ref_a + xb = b[c0:c1, j0:] - ref_b + W = rows._block(i, "w") + if not state["nan"][i]: + prod = (xa[:, :, np.newaxis] * xb[:, np.newaxis, :]).reshape(L, -1) + cross = (W @ prod).reshape(sub) + del prod + ma_i = state["ma"][t0:t1, i0:i1, np.newaxis] + mb_j = state["mb"][t0:t1, np.newaxis, j0:] + num = ( + cross + - ma_i * state["wb"][t0:t1, np.newaxis, j0:] + - mb_j * state["wa"][t0:t1, i0:i1, np.newaxis] + + ma_i * mb_j * state["sw"][t0:t1, :, np.newaxis] + ) + var_a = state["va"][t0:t1, i0:i1, np.newaxis] + var_b = state["vb"][t0:t1, np.newaxis, j0:] + zero = (state["za"][t0:t1, i0:i1, np.newaxis] + | state["zb"][t0:t1, np.newaxis, j0:]) + und = zero + else: + A = rows._block(i, "a") + ok_a = ~np.isnan(xa) + ok_b = ~np.isnan(xb) + pair_ok = ok_a[:, :, np.newaxis] & ok_b[:, np.newaxis, :] + x = np.where(ok_a, xa, 0.0)[:, :, np.newaxis] * pair_ok + y = np.where(ok_b, xb, 0.0)[:, np.newaxis, :] * pair_ok + m = x[0].size + terms = np.concatenate( + [t.reshape(L, -1) for t in (pair_ok.astype(float), x, y, x**2, y**2)], + axis=1, + ) + s0, sx, sy, sxx, syy = np.split(A @ terms, 5, axis=1) + w0, wx, wy = np.split(W @ terms[:, : 3 * m], 3, axis=1) + wxy = W @ (x * y).reshape(L, -1) + mx = _safe_divide(sx, s0) + my = _safe_divide(sy, s0) + num = (wxy - mx * wy - my * wx + mx * my * w0).reshape(sub) + var_a = sxx - s0 * mx**2 + var_b = syy - s0 * my**2 + pairs = sub[1:] + ca = np.broadcast_to(ref_a[:, np.newaxis], pairs).reshape(-1) + cb = np.broadcast_to(ref_b[np.newaxis, :], pairs).reshape(-1) + zero = _zero_variance(var_a, sxx, s0, mx + ca) | _zero_variance( + var_b, syy, s0, my + cb + ) + var_a, var_b, zero = (v.reshape(sub) for v in (var_a, var_b, zero)) + # two samples always give r = +-1: fewer than 3 is undefined + few = (rows._block(i, "s") @ terms[:, :m]).reshape(sub) < 3 + del terms + few_any[t0:t1] = few.reshape(sub[0], -1).any(axis=1) + und = zero | few + zero_all[t0:t1] = zero.reshape(sub[0], -1).all(axis=1) + r[t0:t1] = _correlation_ratio(num, var_a, var_b, und, sub) + undefined[t0:t1] = und return r, undefined, zero_all, few_any @@ -1402,7 +1756,7 @@ def _symmetrize_block(r, undefined, offset): r[:, :, offset : offset + c] = (square + square.transpose(0, 2, 1)) / 2 -def _wcorr_blocks(a, b, rows, autocorrelation): +def _wcorr_blocks(a, b, rows, autocorrelation, min_samples=None): """ Kernel-weighted correlations, computed with matrix products over blocks of feature pairs. NaN samples are excluded pairwise (they carry no weight). @@ -1414,10 +1768,18 @@ def _wcorr_blocks(a, b, rows, autocorrelation): with non-zero weight (NaN samples; those correlations are set to 0, the diagonal of an autocorrelation included). Without NaN samples ``sparse`` is all False. + + ``min_samples`` (not None) selects the causal estimator + (``_causal_setup``): the rows it leaves undefined are NaN in ``out``, and + their mask is returned as a fourth item (None otherwise). """ T, Ka = a.shape Kb = b.shape[1] - state = _wcorr_setup(a, b, rows, autocorrelation) + causal = min_samples is not None + if causal: + state = _causal_setup(a, b, rows, autocorrelation, min_samples) + else: + state = _wcorr_setup(a, b, rows, autocorrelation) out = np.zeros([Ka, Kb, rows.shape[0]]) cancelled = state["active"].copy() sparse = np.zeros_like(cancelled) @@ -1439,10 +1801,15 @@ def _wcorr_blocks(a, b, rows, autocorrelation): # rows without weight (undefined kernel rows) are reported as such sparse &= state["active"] - return out, cancelled, sparse + if causal: + warmup = ~state["defined"] + out[:, :, warmup] = np.nan + return out, cancelled, sparse, warmup + return out, cancelled, sparse, None -def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None): +def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None, *, + causal=False, min_samples=3): """ The rows of ``_wcorr(a, b, weights)`` in blocks, without the full array. @@ -1471,10 +1838,20 @@ def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None): masks ``_wcorr(..., return_cancelled=True)`` returns (all False for the delta case). + With ``causal=True`` the rows are those of ``_wcorr(..., causal=True, + min_samples=min_samples, autocorrelation=symmetric)``: the undefined + (warm-up) rows are NaN in every block. + Raises ``ValueError`` as ``_wcorr`` does, and if ``symmetric`` is True but ``a`` and ``b`` differ in shape. """ + same = a is b a, b, rows = _wcorr_inputs(a, b, weights) + if causal: + min_samples = _check_min_samples(min_samples, True) + _check_causal_rows(rows) + a = _causal_clean(a) + b = a if same else _causal_clean(b) if symmetric and a.shape != b.shape: raise ValueError( "symmetric=True requires a and b of the same shape; " @@ -1498,8 +1875,13 @@ def delta_blocks(): return delta_blocks() - rows.zero_rows(rows.support < 3) - state = _wcorr_setup(a, b, rows, symmetric) + if causal: + state = _causal_setup(a, b, rows, symmetric, min_samples) + warmup = ~state["defined"] + else: + rows.zero_rows(rows.support < 3) + state = _wcorr_setup(a, b, rows, symmetric) + warmup = None step = int(rows_per_block or _wcorr_block_rows(T, Kb, state["n_products"])) active = state["active"] @@ -1509,12 +1891,14 @@ def blocks(): r, undefined, zero_all, few_any = _wcorr_block(state, i0, i1, 0) if symmetric: _symmetrize_block(r, undefined, i0) + if warmup is not None: + r[warmup] = np.nan yield i0, i1, r.transpose(1, 2, 0), active & zero_all, active & few_any return blocks() -def wcorr(a, b, weights): +def wcorr(a, b, weights, *, causal=False, min_samples=3): """ Compute kernel-weighted correlations between two sets of observations. @@ -1598,6 +1982,35 @@ def wcorr(a, b, weights): kernel also weights the covariance and variance sums. Numerical results therefore differ from 0.2.0. + With ``causal=True`` nothing computed for timepoint ``t`` reads a sample + after ``t``: the correlations at ``t`` are unchanged (to 1e-9) when the + samples after ``t`` are replaced by any values, NaN and inf included, or + removed (and, when the kernel gives ``t`` itself no weight, when the + samples at ``t`` change). The kernel must give no weight to later + timepoints. The estimate is the same formula, with these differences: + + - Data are centered, a chunk of 128 kernel rows at a time, on the mean + of each feature's samples in the rows that the chunk weights and that + come before the chunk (its first observed sample when there are + none), not on the mean over all timepoints; the 1e-10 rule above + compares the variance with the kernel-weighted mean square about that + reference. A correlation does not depend on the reference; it only + conditions the sums. + - Infinite samples and samples above 1e150 in magnitude are missing + data, like NaN. + - A timepoint with fewer than 3 observed samples with non-zero weight, + or whose effective sample size ``(sum |w|)**2 / sum w**2`` over the + observed timepoints of its kernel row is below ``min_samples``, is + undefined: all its correlations are NaN (the diagonal included), not + 0. A timepoint counts as observed when ``a`` and ``b`` each have at + least one sample there. Other undefined entries are 0, as without + ``causal``: constant features, and pairs of features with fewer than + 3 common samples. + - ``a`` and ``b`` are an autocorrelation (diagonal set to 1) only when + they are the same object; equal values in two arrays are not compared. + - A delta kernel raises ``ValueError`` (its z-scores use every + timepoint). + Parameters ---------- a : numpy.ndarray @@ -1607,12 +2020,23 @@ def wcorr(a, b, weights): weights : numpy.ndarray Kernel matrix with T columns; row ``t`` holds the weights used to estimate at timepoint ``t``. Usually T x T. + causal : bool, optional + True: the causal estimator described above. ``weights`` must have + no non-zero entry above its diagonal (for example a kernel function + called with ``direction='backward'``). Keyword only. Default: + False. + min_samples : float, optional + With ``causal=True``, the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs (compared with a + relative tolerance of 1e-12, so three equal weights are 3 samples); + timepoints below it are NaN. Keyword only. Default: 3. Returns ------- numpy.ndarray Array of shape (Ka, Kb, weights.shape[0]); entry ``[i, j, t]`` is the correlation between ``a[:, i]`` and ``b[:, j]`` at timepoint ``t``. + With ``causal=True`` the undefined timepoints are NaN. Warns ----- @@ -1625,13 +2049,18 @@ def wcorr(a, b, weights): samples, some pairs of features have fewer than 3 observed samples with non-zero kernel weight (those correlations are undefined and set to 0); and timepoints with zero kernel-weighted variance in every feature - (their correlations are set to 0). Never for a delta kernel. + (their correlations are set to 0). Never for a delta kernel. With + ``causal=True`` the first of these names the undefined timepoints + (returned as NaN). Raises ------ ValueError If the inputs do not have T rows / T kernel columns, or if every row of - the kernel is zero. + the kernel is zero. With ``causal=True``: if the kernel has weight + above its diagonal or is a delta kernel, or if ``min_samples`` is + not a finite number >= 0. If ``min_samples`` is given without + ``causal=True``. Examples -------- @@ -1646,19 +2075,59 @@ def wcorr(a, b, weights): >>> uniform = tc.wcorr(x, x, tc.uniform_weights(100)) >>> bool(np.allclose(uniform[:, :, 10], np.corrcoef(x.T))) True + + The causal estimator: timepoint 60 does not depend on later samples. + + The first 3 timepoints have fewer than 3 effective samples and are NaN + (a ``UserWarning`` says so). + + >>> past = tc.gaussian_weights(100, {"var": 50}, direction="backward") + >>> r = tc.wcorr(x, x, past, causal=True) + >>> bool(np.isnan(r[:, :, :3]).all()), bool(np.isnan(r[:, :, 3:]).any()) + (True, False) + >>> y = x.copy() + >>> y[61:] = 1000.0 + >>> bool(np.array_equal(tc.wcorr(y, y, past, causal=True)[:, :, 60], r[:, :, 60])) + True """ - return _wcorr(a, b, weights) + min_samples = _check_min_samples(min_samples, causal) + return _wcorr(a, b, weights, causal=causal, min_samples=min_samples) -def _wcorr(a, b, weights, warn=True, return_cancelled=False): +def _wcorr(a, b, weights, warn=True, return_cancelled=False, causal=False, + min_samples=3, autocorrelation=None): """ ``wcorr``. With ``warn=False`` the warning is left to the caller; with ``return_cancelled=True`` the masks ``(cancelled, sparse)`` of the timepoints whose correlations all cancelled and of those where some pair has fewer than 3 observed samples (see ``_wcorr_blocks``) are returned too: ``(out, (cancelled, sparse))``. + + ``causal=True`` is the causal estimator (see ``wcorr``): the masks are + then ``(cancelled, sparse, warmup)``, ``warmup`` marking the undefined + rows (NaN in ``out``). ``autocorrelation`` says whether ``b`` is ``a`` + (None: whether they are the same object; comparing their values would + read every timepoint). """ + same = a is b a, b, rows = _wcorr_inputs(a, b, weights) + if causal: + min_samples = _check_min_samples(min_samples, True) + _check_causal_rows(rows) + a = _causal_clean(a) + b = a if same else _causal_clean(b) + if autocorrelation is None: + autocorrelation = same + out, cancelled, sparse, warmup = _wcorr_blocks( + a, b, rows, autocorrelation, min_samples + ) + del rows + if warn: + message = _estimator_message(weights, cancelled, sparse, warmup, + min_samples) + if message is not None: + _warn_user(message) + return (out, (cancelled, sparse, warmup)) if return_cancelled else out if np.all(rows.support == 1): out = _delta_wcorr(a, b, rows) none = np.zeros(rows.shape[0], dtype=bool) @@ -1668,7 +2137,7 @@ def _wcorr(a, b, weights, warn=True, return_cancelled=False): autocorrelation = a is b or ( a.shape == b.shape and np.array_equal(a, b, equal_nan=True) ) - out, cancelled, sparse = _wcorr_blocks(a, b, rows, autocorrelation) + out, cancelled, sparse, _ = _wcorr_blocks(a, b, rows, autocorrelation) del rows if warn: message = _estimator_message(weights, cancelled, sparse) @@ -1797,7 +2266,8 @@ def _fisher_mean(r, axis): return np.where(nan, np.nan, out) -def wisfc(data, timepoint_weights, subject_weights=None): +def wisfc(data, timepoint_weights, subject_weights=None, *, causal=False, + min_samples=3): """ Compute weighted inter-subject functional connectivity (ISFC). @@ -1829,6 +2299,22 @@ def wisfc(data, timepoint_weights, subject_weights=None): defined (``K <= 2`` features give fewer than 3 matrix entries) or is at most 1e-5 in magnitude for every other subject, the other subjects are weighted equally. + causal : bool, optional + True: the causal estimator (see ``wcorr``): row ``t`` of the output + is unchanged (to 1e-9) when the samples after ``t`` are replaced by + any values, NaN and inf included, or removed. Every kernel must + give no weight to later timepoints (for example a kernel function + called with ``direction='backward'``); infinite samples and samples + above 1e150 in magnitude are missing data; undefined (warm-up) + timepoints are rows of NaN, not 0. ``subject_weights`` + must be given: the default weights are computed from every + timepoint. Keyword only. Default: False. + min_samples : float, optional + With ``causal=True``, the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs, over the timepoints of + its kernel row where the subject and its reference each have a + sample; a timepoint below it, or with fewer than 3 such timepoints, + is a row of NaN. Keyword only. Default: 3. Returns ------- @@ -1836,6 +2322,7 @@ def wisfc(data, timepoint_weights, subject_weights=None): One (T, K * (K + 1) / 2) array of vectorized correlation matrices per subject (see ``mat2vec``); a single array if ``data`` is an array. Row ``t`` is estimated with the kernel ``timepoint_weights[t, :]``. + With ``causal=True`` the undefined timepoints are rows of NaN. Warns ----- @@ -1854,14 +2341,18 @@ def wisfc(data, timepoint_weights, subject_weights=None): an undefined entry ``C[i, j]`` is averaged (in Fisher z space) with ``C[j, i]``, which can be defined, so the returned value need not be 0; a feature with zero kernel-weighted variance on one side only (subject - or reference) is treated the same way. + or reference) is treated the same way. With ``causal=True`` the + first of these names the undefined timepoints (returned as NaN). Raises ------ ValueError If the subjects differ in shape, the kernel does not have T columns, every row of the kernel is zero, or a list of kernels does not have - one kernel per subject. + one kernel per subject. With ``causal=True``: if a + kernel has weight above its diagonal or is a delta kernel, if ``subject_weights`` is None, or if + ``min_samples`` is not a finite number >= 0. If ``min_samples`` is + given without ``causal=True``. Notes ----- @@ -1894,8 +2385,18 @@ def wisfc(data, timepoint_weights, subject_weights=None): (3, (50, 10)) """ if type(data) != list: - return wisfc([data], timepoint_weights, subject_weights=subject_weights)[0] + return wisfc([data], timepoint_weights, subject_weights=subject_weights, + causal=causal, min_samples=min_samples)[0] + min_samples = _check_min_samples(min_samples, causal) + if causal: + if subject_weights is None: + raise ValueError( + "causal=True: the default subject_weights of wisfc are computed " + "from every timepoint of the recording. Pass subject_weights (a " + "number, or one row of weights per subject), or use isfc." + ) + data = [_causal_clean(d) for d in data] S = len(data) subject_weights = _subject_weight_matrix(data, subject_weights) @@ -1904,25 +2405,57 @@ def wisfc(data, timepoint_weights, subject_weights=None): corrs = [] cancelled = [False] * len(kernels) sparse = [False] * len(kernels) + warmup = [False] * len(kernels) if causal else None for s, a in enumerate(data): g = group_of[s] b = _nan_weighted_mean(stacked, subject_weights[s, :]) - wc, (c, few) = _wcorr(a, b, kernels[g], warn=False, return_cancelled=True) + if causal: + # whether the reference is the subject's own data is read from + # the weights; comparing the samples would read every timepoint + own = _own_reference(subject_weights[s, :], s) + wc, (c, few, undefined) = _wcorr( + a, a if own else b, kernels[g], warn=False, return_cancelled=True, + causal=True, min_samples=min_samples, autocorrelation=own, + ) + warmup[g] = warmup[g] | undefined + symmetrize = not own + else: + wc, (c, few) = _wcorr(a, b, kernels[g], warn=False, return_cancelled=True) + symmetrize = not np.array_equal(a, b, equal_nan=True) cancelled[g] = cancelled[g] | c sparse[g] = sparse[g] | few - if not np.array_equal(a, b, equal_nan=True): + if symmetrize: wc = _fisher_symmetrize(wc) corrs.append(mat2vec(wc)) + if causal: + # mat2vec sets NaN above the diagonal to 0: undefined rows are NaN + corrs[-1][undefined] = np.nan # free the (K, K, T) array before the next subject's is allocated del wc # one warning per call, covering every kernel - message = _kernels_message(kernels, group_of, cancelled, sparse) + message = _kernels_message(kernels, group_of, cancelled, sparse, warmup, + min_samples) if message is not None: _warn_user(message) return corrs +def _own_reference(weights, s, tol=1e-5): + """ + True when ``_nan_weighted_mean`` with these subject weights returns + subject ``s``'s own data: after its rules (NaN weights 0, weights that + sum to 0 replaced by ones, magnitudes at most ``tol`` dropped) only + subject ``s`` has weight. + """ + w = np.array(weights, dtype=np.float64, copy=True) + w[np.isnan(w)] = 0 + if np.sum(w) == 0: + w = np.ones_like(w) + keep = np.abs(w) > tol + return bool(keep[s] and keep.sum() == 1) + + def _static_connectome(d, iu, rows_per_block): """ The upper triangle (``iu``) of the static correlation matrix of ``d`` @@ -2028,20 +2561,26 @@ def _subject_kernels(timepoint_weights, S): return kernels, group_of -def _kernels_message(kernels, group_of, cancelled, sparse=None): +def _kernels_message(kernels, group_of, cancelled, sparse=None, warmup=None, + min_samples=None): """ The one warning of a correlation call with one or several kernels, or None. With one kernel it is ``_estimator_message``; with several, each kernel's message is prefixed by the subjects that use it. ``cancelled`` and ``sparse`` - hold one mask (see ``_wcorr_blocks``) per kernel. + hold one mask (see ``_wcorr_blocks``) per kernel, as does ``warmup`` (the + causal estimator's undefined rows, see ``_estimator_message``). """ if sparse is None: sparse = [None] * len(kernels) + if warmup is None: + warmup = [None] * len(kernels) if len(kernels) == 1: - return _estimator_message(kernels[0], cancelled[0], sparse[0]) + return _estimator_message(kernels[0], cancelled[0], sparse[0], warmup[0], + min_samples) parts = [] for g, kernel in enumerate(kernels): - message = _estimator_message(kernel, cancelled[g], sparse[g]) + message = _estimator_message(kernel, cancelled[g], sparse[g], warmup[g], + min_samples) if message is not None: subjects = [s for s, k in enumerate(group_of) if k == g] label = "Subject" if len(subjects) == 1 else "Subjects" @@ -2049,7 +2588,7 @@ def _kernels_message(kernels, group_of, cancelled, sparse=None): return " ".join(parts) if parts else None -def isfc(data, timepoint_weights): +def isfc(data, timepoint_weights, *, causal=False, min_samples=3): """ Compute Inter-Subject Functional Connectivity (ISFC). @@ -2075,6 +2614,20 @@ def isfc(data, timepoint_weights): data and to the reference it is correlated with (see ``timecorr(..., events=...)``). Equal kernels in the list are grouped. + causal : bool, optional + True: the causal estimator (see ``wcorr``): row ``t`` of the output + is unchanged (to 1e-9) when the samples after ``t`` are replaced by + any values, NaN and inf included, or removed. Every kernel must + give no weight to later timepoints (for example a kernel function + called with ``direction='backward'``); infinite samples and samples + above 1e150 in magnitude are missing data; undefined (warm-up) + timepoints are rows of NaN, not 0. Keyword only. Default: False. + min_samples : float, optional + With ``causal=True``, the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs, over the timepoints of + its kernel row where the subject and its reference each have a + sample; a timepoint below it, or with fewer than 3 such timepoints, + is a row of NaN. Keyword only. Default: 3. Returns ------- @@ -2083,7 +2636,8 @@ def isfc(data, timepoint_weights): array per subject, see ``mat2vec``), each showing correlations between that subject and the average of all others; a single array if ``data`` is an array. Row ``t`` is estimated with the kernel - ``timepoint_weights[t, :]``. + ``timepoint_weights[t, :]``. With ``causal=True`` the undefined + timepoints are rows of NaN. Warns ----- @@ -2109,7 +2663,10 @@ def isfc(data, timepoint_weights): ValueError If the subjects differ in shape, the kernel does not have T columns, every row of the kernel is zero, or a list of kernels does not have - one kernel per subject. + one kernel per subject. With ``causal=True``: if a + kernel has weight above its diagonal or is a delta kernel, or if + ``min_samples`` is not a finite number >= 0. If ``min_samples`` is + given without ``causal=True``. Notes ----- @@ -2133,12 +2690,14 @@ def isfc(data, timepoint_weights): (5, (100, 55)) """ if type(data) != list: - return isfc([data], timepoint_weights)[0] + return isfc([data], timepoint_weights, causal=causal, + min_samples=min_samples)[0] - return wisfc(data, timepoint_weights, subject_weights=1 - np.eye(len(data))) + return wisfc(data, timepoint_weights, subject_weights=1 - np.eye(len(data)), + causal=causal, min_samples=min_samples) -def autofc(data, timepoint_weights): +def autofc(data, timepoint_weights, *, causal=False, min_samples=3): """ Compute auto-correlations within each subject's data. @@ -2158,6 +2717,20 @@ def autofc(data, timepoint_weights): data and to the reference it is correlated with (see ``timecorr(..., events=...)``). Equal kernels in the list are grouped. + causal : bool, optional + True: the causal estimator (see ``wcorr``): row ``t`` of the output + is unchanged (to 1e-9) when the samples after ``t`` are replaced by + any values, NaN and inf included, or removed. Every kernel must + give no weight to later timepoints (for example a kernel function + called with ``direction='backward'``); infinite samples and samples + above 1e150 in magnitude are missing data; undefined (warm-up) + timepoints are rows of NaN, not 0. Keyword only. Default: False. + min_samples : float, optional + With ``causal=True``, the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs, over the timepoints of + its kernel row where the subject and its reference each have a + sample; a timepoint below it, or with fewer than 3 such timepoints, + is a row of NaN. Keyword only. Default: 3. Returns ------- @@ -2165,7 +2738,8 @@ def autofc(data, timepoint_weights): List of vectorized correlation matrices (one (T, K * (K + 1) / 2) array per subject, see ``mat2vec``), each showing within-subject correlations; a single array if ``data`` is an array. Row ``t`` is - estimated with the kernel ``timepoint_weights[t, :]``. + estimated with the kernel ``timepoint_weights[t, :]``. With + ``causal=True`` the undefined timepoints are rows of NaN. Warns ----- @@ -2187,7 +2761,10 @@ def autofc(data, timepoint_weights): ValueError If the subjects differ in shape, the kernel does not have T columns, every row of the kernel is zero, or a list of kernels does not have - one kernel per subject. + one kernel per subject. With ``causal=True``: if a + kernel has weight above its diagonal or is a delta kernel, or if + ``min_samples`` is not a finite number >= 0. If ``min_samples`` is + given without ``causal=True``. Examples -------- @@ -2200,9 +2777,11 @@ def autofc(data, timepoint_weights): (3, (100, 55)) """ if type(data) != list: - return autofc([data], timepoint_weights)[0] + return autofc([data], timepoint_weights, causal=causal, + min_samples=min_samples)[0] - return wisfc(data, timepoint_weights, subject_weights=np.eye(len(data))) + return wisfc(data, timepoint_weights, subject_weights=np.eye(len(data)), + causal=causal, min_samples=min_samples) def apply_by_row(corrs, f): diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 8cdfaa76..2db2536c 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -1,15 +1,31 @@ # coding: utf-8 +import functools import warnings import numpy as np from ._kernels import CHUNK, as_kernel, blocks, check_exclude -from .events import distinct_event_sets, mask_kernel, resolve_events +from .events import ( + _has_features, + _parse_spec, + distinct_event_sets, + mask_kernel, + resolve_events, +) from .helpers import ( + _GRAPH_MEASURES, + _MIN_SAMPLES_RTOL, + _abs_weights, _as_kernel_array, + _causal_clean, + _check_causal_kernel, + _check_min_samples, + _check_rfun, _lag_kernel, + _warn_user, autofc, + eye_weights, format_data, gaussian_weights, isfc, @@ -23,6 +39,45 @@ _KERNEL_LIST_CFUNS = (wisfc, isfc, autofc) +def _causal_smooth(x, weights, min_samples): + """ + ``_kernel_smooth`` for ``causal=True``: the same kernel-weighted means of + a kernel without weight on later timepoints, each chunk of rows over the + columns where it has weight. Infinite samples and samples above 1e150 + in magnitude are missing, like NaN. An entry whose feature has an + effective sample size ``(sum |w|)**2 / sum w**2`` (over the feature's + observed samples in the kernel row) below ``min_samples``, or no weighted + sample, is NaN; one warning reports how many timepoints have one. + """ + x = _causal_clean(x) + valid = ~np.isnan(x) + observed = np.where(valid, x, 0.0) + valid = valid.astype(np.float64) + out = np.full(observed.shape, np.nan) + for t0, t1, c0, c1, _, w in blocks(as_kernel(weights), CHUNK, _abs_weights): + if c1 <= c0: + continue + # each row scaled by its largest weight, so squares do not underflow + peak = w.max(axis=1, keepdims=True, initial=0.0) + with np.errstate(invalid="ignore"): + w = np.divide(w, peak, out=np.zeros_like(w), where=peak != 0) + den = w @ valid[c0:c1] + num = w @ observed[c0:c1] + ess = np.divide(den**2, (w * w) @ valid[c0:c1], out=np.zeros_like(den), + where=den > 0) + defined = (den > 0) & (ess >= min_samples * (1 - _MIN_SAMPLES_RTOL)) + np.divide(num, den, out=out[t0:t1], where=defined) + undefined = np.isnan(out).any(axis=1) + if undefined.any(): + warnings.warn( + f"Smoothing is undefined at {int(undefined.sum())} timepoint(s) (for " + "some feature, no weighted, observed sample or an effective sample " + f"size below min_samples={min_samples:g}); those values are NaN " + "(causal=True)." + ) + return out + + def _kernel_smooth(x, weights): """ Kernel-weighted mean of the rows of x: out[t] = sum_j |w[t, j]| x[j] / sum_j |w[t, j]|. @@ -97,13 +152,16 @@ def _shaped_kernel( include_timepoints="all", include_zero=True, exclude_timepoints=None, + causal=False, ): """ The T x T kernel of ``timecorr`` before the events restriction: ``weights_function(T, weights_params)`` shaped by ``include_timepoints``, ``include_zero`` and ``exclude_timepoints``. For a built-in kernel function it is a ``LagKernel``, whose rows are computed when they are - read (no T x T array); for any other function, the array it returns. + read (no T x T array); for any other function, the array it returns + (with ``causal=True`` that array must have no weight above its + diagonal: ``ValueError``). """ exclude_timepoints = check_exclude(exclude_timepoints) include_timepoints = include_timepoints.lower() @@ -120,6 +178,8 @@ def _shaped_kernel( return lazy weights = weights_function(T, weights_params) + if causal: + _check_causal_kernel(weights, "the kernel that weights_function returned") if include_timepoints == "all": if not include_zero: weights = weights.copy() @@ -184,6 +244,121 @@ def _per_subject_cfun(cfun, data, kernels, groups): return out +def _fixed_weights_wisfc(cfun): + """ + True for ``functools.partial(wisfc, subject_weights=...)`` with weights + given (and nothing else bound): the built-in ``wisfc`` with fixed + subject weights. + """ + return ( + isinstance(cfun, functools.partial) + and cfun.func is wisfc + and not cfun.args + and set(cfun.keywords) == {"subject_weights"} + and cfun.keywords["subject_weights"] is not None + ) + + +def _needs_fit(rfun): + """True for a reducer that is fitted to data: a model or a summary.""" + from .summaries import _Summary # timecorr.summaries imports helpers + + if isinstance(rfun, (dict, _Summary)): + return True + return isinstance(rfun, str) and rfun not in _GRAPH_MEASURES + + +def _causal_arguments(weights_function, weights_params, include_timepoints, cfun, + rfun, events, T, n_subjects): + """ + The checks of ``timecorr(..., causal=True)``. Returns + ``(include_timepoints, cfun)``: ``'backward'``, and the correlation + function to call (a built-in one is called with ``causal=True``). + Raises ``ValueError`` for what has no causal form, and warns once when + ``cfun`` or ``rfun`` is a function of the user's. + """ + side = str(include_timepoints).lower() + if side in ("forward", "post"): + raise ValueError( + f"causal=True: include_timepoints={include_timepoints!r} weights " + "later timepoints. Leave include_timepoints out (causal=True uses " + "'backward'), or pass causal=False." + ) + if side in ("all", "backward", "pre"): + include_timepoints = "backward" + if weights_function is eye_weights: + raise ValueError( + "causal=True: eye_weights gives co-fluctuations of series z-scored " + "over the whole recording, which use later timepoints. Pass a " + "kernel with a width, for example weights_function=" + "tc.gaussian_weights, weights_params={'var': 25}." + ) + if weights_params is None: + raise ValueError( + "causal=True: weights_params must be given (the kernel's width is " + "not chosen for you), for example weights_params={'var': 25} for " + "gaussian_weights; pass {} for a kernel without parameters." + ) + if cfun is wisfc or ( + isinstance(cfun, functools.partial) and cfun.func is wisfc + and not _fixed_weights_wisfc(cfun) + ): + raise ValueError( + "causal=True: the default subject_weights of wisfc are computed " + "from every timepoint of the recording. Pass cfun=" + "functools.partial(tc.wisfc, subject_weights=...) with weights of " + "your own and nothing else bound, or cfun=tc.isfc." + ) + if _has_features(_parse_spec(events, T, n_subjects)): + raise ValueError( + "causal=True: events given as features are segmented from the whole " + "recording. Pass the boundaries (the timepoints where a new block " + "starts), for example events=[100, 250]." + ) + _check_rfun(rfun) + if _needs_fit(rfun): + raise NotImplementedError( + f"causal=True: rfun={rfun!r} is fitted to data and needs " + "fit_timepoints (the rows it is fitted on), which timecorr does not " + "accept yet. Use rfun=None or a graph measure such as 'strength'." + ) + builtin = cfun is None or cfun in (isfc, autofc) or _fixed_weights_wisfc(cfun) + theirs = [name for name, f, ours in (("cfun", cfun, builtin), + ("rfun", rfun, not callable(rfun))) + if not ours] + if theirs: + _warn_user( + f"causal=True: {' and '.join(theirs)} " + f"{'is a function' if len(theirs) == 1 else 'are functions'} of your " + "own; the guarantee that row t does not depend on later rows does " + "not cover what " + f"{'it does' if len(theirs) == 1 else 'they do'}." + ) + return include_timepoints, cfun + + +def _reduce_defined(corrs, rfun): + """ + ``reduce(corrs, rfun)`` for a graph measure on the output of the causal + estimator: the measure is computed for the defined rows; rows of NaN + stay rows of NaN. + """ + arrays = corrs if isinstance(corrs, list) else [corrs] + out = [] + for c in arrays: + c = np.asarray(c) + defined = ~np.isnan(c).all(axis=1) + if not defined.any(): + width = np.asarray(reduce(np.nan_to_num(c[:1]), rfun=rfun)).shape[1] + out.append(np.full((c.shape[0], width), np.nan)) + continue + reduced = np.asarray(reduce(c[defined], rfun=rfun)) + full = np.full((c.shape[0], reduced.shape[1]), np.nan) + full[defined] = reduced + out.append(full) + return out if isinstance(corrs, list) else out[0] + + def timecorr( data, weights_function=gaussian_weights, @@ -197,6 +372,8 @@ def timecorr( *, events=None, events_params=None, + causal=False, + min_samples=3, ): """ Compute dynamic (moment-by-moment) correlations in one or more datasets. @@ -317,6 +494,55 @@ def timecorr( ``events`` (keys ``n``, ``kind``, ``max_events``, ``random_state``). Unknown keys, or giving it when no entry of ``events`` holds features, raise ``ValueError``. Default: None. + causal : bool + True: row ``t`` of the output uses no sample after timepoint ``t``. + It is unchanged (to 1e-9) when the rows after ``t`` are replaced by + any values, NaN and inf included, or removed; with + ``include_zero=False`` also when row ``t`` itself changes. Keyword + only. Default: False. With ``causal=True``: + + - the kernel is backward: ``include_timepoints`` 'all' (the + default) means 'backward', and 'forward' / 'post' raise + ``ValueError``; + - ``weights_params`` must be given, and ``weights_function`` cannot + be ``eye_weights`` (its z-scores use every timepoint); a kernel + function of your own must return a matrix without weight above + its diagonal (for example ``tc.one_sided(w, 'backward')``), and + removing rows is covered only if its weights do not depend on T; + - ``cfun`` is ``isfc``, ``autofc``, None, or + ``functools.partial(tc.wisfc, subject_weights=...)`` with weights + of your own (the default weights of ``wisfc`` use every + timepoint, so ``cfun=tc.wisfc`` raises ``ValueError``). Any + other function is called as without ``causal``, with a + ``UserWarning`` that the guarantee does not cover it; the same + holds for a callable ``rfun``; + - ``events`` must be boundaries; features to segment raise + ``ValueError``. That the boundaries themselves were chosen + without later data is the caller's responsibility. The warm-up + below starts again at each boundary; + - ``rfun`` is None, a graph measure (computed for the defined rows) + or a callable; a reducer that is fitted to data (a model name, a + summary) raises ``NotImplementedError``; + - infinite samples and samples above 1e150 in magnitude are missing + data, like NaN; + - the estimator centers each feature, a chunk of 128 timepoints at + a time, on the mean of its earlier samples that the chunk + weights, and its zero-variance rule is relative to that reference + (see ``wcorr``); + - timepoints with too few samples are rows of NaN, not 0 (see + ``min_samples``). + min_samples : float + With ``causal=True``, the effective sample size + ``(sum |w|)**2 / sum w**2`` that a timepoint needs, summed over the + observed timepoints of its kernel row (those where the data, and + for ``isfc`` and ``wisfc`` the reference, have at least one sample); + compared with a relative tolerance of 1e-12, so three equal weights + are 3 samples. A timepoint below it, or with fewer than 3 observed + timepoints with non-zero weight, is a row of NaN. With + ``cfun=None`` only the effective sample size applies, to each + feature's own observed samples: values below it are NaN. Features + with zero variance still give correlations of 0. Keyword only. + Default: 3. Returns ------- @@ -327,7 +553,9 @@ def timecorr( reduced features when ``rfun`` is given ((T, K) for model-based reduction and graph measures); or the smoothed (T, K) data when ``cfun`` is None. A list (one entry per subject) - when ``combine`` returns one; a single array otherwise. + when ``combine`` returns one; a single array otherwise. With + ``causal=True`` the timepoints with too few samples (the first ones, + and those after long gaps or event boundaries) are rows of NaN. Warns ----- @@ -360,7 +588,12 @@ def timecorr( row with fewer than 3 non-zero weights (no block is long enough to estimate a correlation); and, with per-subject events, when a custom ``cfun`` does not return a list with one array per subject; and as - raised by ``segment`` for features entries of ``events``. + raised by ``segment`` for features entries of ``events``. With + ``causal=True``, for the arguments listed under ``causal`` that have + no causal form, and for a ``min_samples`` that is not a finite number + >= 0; for ``min_samples`` given without ``causal=True``. + NotImplementedError + With ``causal=True``, for an ``rfun`` that is fitted to data. RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. @@ -449,6 +682,19 @@ def timecorr( >>> per_subject = tc.timecorr(subjects, cfun=tc.autofc, events=[[40], [50, 80], None]) >>> len(per_subject), per_subject[0].shape (3, (100, 15)) + + Causal estimates: row 60 does not change when later rows do. The first + 3 rows have fewer than 3 effective samples and are NaN (a + ``UserWarning`` says so). + + >>> past = tc.timecorr(data, causal=True, weights_params={"var": 50}) + >>> bool(np.isnan(past[:3]).all()), bool(np.isnan(past[3:]).any()) + (True, False) + >>> later = data.copy() + >>> later[61:] = 1000.0 + >>> changed = tc.timecorr(later, causal=True, weights_params={"var": 50}) + >>> bool(np.array_equal(changed[60], past[60])) + True """ # NaN samples are kept; both the correlation functions and the smoothing @@ -456,6 +702,16 @@ def timecorr( data = format_data(data, fill_nan=False) T = data[0].shape[0] + min_samples = _check_min_samples(min_samples, causal) + if causal: + include_timepoints, cfun = _causal_arguments( + weights_function, weights_params, include_timepoints, cfun, rfun, + events, T, len(data), + ) + # the built-in correlation functions: one kernel per subject, never T x T + builtin = cfun in _KERNEL_LIST_CFUNS or (causal and _fixed_weights_wisfc(cfun)) + estimator = {"causal": True, "min_samples": min_samples} if causal and builtin else {} + weights = _shaped_kernel( T, weights_function, @@ -463,6 +719,7 @@ def timecorr( include_timepoints, include_zero, exclude_timepoints, + causal, ) # event restriction: applied after the include/exclude options; subjects that @@ -472,7 +729,7 @@ def timecorr( per_subject = isinstance(kernels, list) if cfun: - if cfun not in _KERNEL_LIST_CFUNS: + if not builtin: # a correlation function of the user's receives T x T arrays if per_subject: arrays = {} @@ -482,18 +739,25 @@ def timecorr( kernels = [arrays[id(k)] for k in kernels] else: kernels = _as_kernel_array(kernels) - if not per_subject or cfun in _KERNEL_LIST_CFUNS: - corrs = cfun(data, kernels) + if not per_subject or builtin: + corrs = cfun(data, kernels, **estimator) else: groups = distinct_event_sets(_restricted(resolved), len(data)) corrs = _per_subject_cfun(cfun, data, kernels, groups) - corrs = reduce(combine(corrs), rfun=rfun) + if causal and isinstance(rfun, str): + corrs = _reduce_defined(combine(corrs), rfun) + else: + corrs = reduce(combine(corrs), rfun=rfun) else: # smoothing path: kernel-weighted mean of the samples, using the same # kernel rows (after include_timepoints, include_zero, exclude_timepoints # and events) as the correlation path - if per_subject: + if causal: + subject_kernels = kernels if per_subject else [kernels] * len(data) + smoothed = [_causal_smooth(x, k, min_samples) + for x, k in zip(data, subject_kernels)] + elif per_subject: smoothed = [_kernel_smooth(x, k) for x, k in zip(data, kernels)] else: smoothed = [_kernel_smooth(x, kernels) for x in data] From 3893ebdc04e5ffd822b3237316f204f3cbacadeb Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 11:03:14 -0500 Subject: [PATCH 02/26] Causal estimator: min_samples defaults to None; a number no kernel row 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 159 ++++++++++++++++++-------- tests/test_estimator.py | 5 +- timecorr/helpers.py | 202 ++++++++++++++++++++------------- timecorr/timecorr.py | 71 +++++++----- 4 files changed, 281 insertions(+), 156 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 293ac02e..37a53481 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -11,6 +11,7 @@ """ import functools +import re import warnings import numpy as np @@ -26,14 +27,13 @@ T = 300 CUTS = (3, 40, 127, 128, 129, 200, 257, 299) -# name: (kernel function, parameters, min_samples). The t kernel has weight -# at every lag but is narrow whatever its df: a backward row has at most 2.6 -# effective samples (2.1 without the diagonal), so it is tested with -# min_samples=2 (with the default of 3 every row is NaN). +# name: (kernel function, parameters, a min_samples that its rows reach). +# The t kernel has weight at every lag but is narrow whatever its df: a +# backward row has at most 2.6 effective samples (2.1 without the diagonal). KERNELS = { - "gaussian": (tc.gaussian_weights, {"var": 25}, 3), - "laplace": (tc.laplace_weights, {"scale": 8}, 3), - "boxcar": (tc.boxcar_weights, {"width": 30}, 3), + "gaussian": (tc.gaussian_weights, {"var": 25}, 6), + "laplace": (tc.laplace_weights, {"scale": 8}, 6), + "boxcar": (tc.boxcar_weights, {"width": 30}, 6), "t": (tc.t_weights, {"df": 3}, 2), } SUBJECT_WEIGHTS = np.array([[0.0, 1.0, 0.5], [0.3, 0.0, 1.0], [1.0, 2.0, 0.0]]) @@ -88,11 +88,11 @@ def _perturb(x, n, mode, rng): def _call(data, case, kernel, include_zero=True, **kwargs): cfun, n_subjects, combine = CASES[case] - weights_function, weights_params, min_samples = KERNELS[kernel] + weights_function, weights_params, _ = KERNELS[kernel] x = data[0] if n_subjects == 1 else data return _quiet(tc.timecorr, x, causal=True, cfun=cfun, combine=combine, weights_function=weights_function, weights_params=weights_params, - include_zero=include_zero, min_samples=min_samples, **kwargs) + include_zero=include_zero, **kwargs) def _as_list(out): @@ -134,6 +134,30 @@ def test_rows_do_not_depend_on_later_rows(case, include_zero, kernel, mode): assert defined > 0 # the comparison is not between NaN rows only +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("case", ["autofc", "isfc-null", "wisfc-corrmean", "smooth"]) +def test_rows_do_not_depend_on_later_rows_with_min_samples(case, include_zero, kernel, + mode): + min_samples = KERNELS[kernel][2] + data = _subjects(CASES[case][1], seed=40) + full = _call(data, case, kernel, include_zero, min_samples=min_samples) + plain = _call(data, case, kernel, include_zero) + nan_rows = np.isnan(np.asarray(_as_list(full)[0])).all(axis=1) + # the number asks for more than the default rule (except for the narrow + # t kernel, whose third row already has 2 effective samples), and rows + # reach it + default = np.isnan(np.asarray(_as_list(plain)[0])).all(axis=1).sum() + assert nan_rows.sum() > default or (kernel == "t" and nan_rows.sum() == default) + assert not nan_rows[30:].all() + rng = np.random.default_rng(27) + for n in CUTS[1:]: # (a series of 3 rows cannot reach the number: ValueError) + part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, + include_zero, min_samples=min_samples) + assert _max_difference(full, part, n) <= ATOL + + @pytest.mark.parametrize("missing", [0, 0.002]) @pytest.mark.parametrize("mode", MODES) @pytest.mark.parametrize("kernel", sorted(KERNELS)) @@ -153,9 +177,7 @@ def test_rows_do_not_depend_on_later_rows_with_few_missing_samples( include_zero) rows = n if include_zero or mode == "remove" else n + 1 assert _max_difference(full, part, rows) <= ATOL - # (with the narrow t kernel, a missing sample leaves a feature of the - # smoothed data below min_samples for a row or two) - assert np.isnan(np.asarray(_as_list(full)[0])[20:]).mean() < 0.01 + assert not np.isnan(np.asarray(_as_list(full)[0])[20:]).any() @pytest.mark.parametrize("mode", ["finite", "nan", "inf"]) @@ -270,7 +292,7 @@ def test_smoothing_agrees_with_the_backward_kernel_of_causal_false(): causal = _quiet(tc.timecorr, x, causal=True, **kw) plain = _quiet(tc.timecorr, x, include_timepoints="backward", **kw) defined = ~np.isnan(causal) - assert defined[5:].all() and not defined[:2].any() + assert defined.all() # one weighted sample defines a smoothed value assert np.max(np.abs(causal[defined] - plain[defined])) <= 1e-12 @@ -278,7 +300,7 @@ def test_default_is_not_causal(): x = np.random.default_rng(2).standard_normal((80, 4)) kw = dict(cfun=tc.autofc, weights_params={"var": 20}) assert np.array_equal(_quiet(tc.timecorr, x, **kw), - _quiet(tc.timecorr, x, causal=False, min_samples=3, **kw)) + _quiet(tc.timecorr, x, causal=False, min_samples=None, **kw)) w = tc.gaussian_weights(80, {"var": 20}) assert np.array_equal(_quiet(tc.wcorr, x, x, w), _quiet(tc.wcorr, x, x, w, causal=False)) @@ -296,9 +318,59 @@ def _expected_undefined(w, observed, min_samples, min_count=3): with np.errstate(invalid="ignore", divide="ignore"): ess = a.sum(axis=1) ** 2 / (a**2).sum(axis=1) ess = np.nan_to_num(ess) + if min_samples is None: + return count < min_count return (count < min_count) | (ess < min_samples * (1 - 1e-12)) +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +def test_default_nan_rows_are_the_zero_rows_of_causal_false(kernel, include_zero): + x = np.random.default_rng(14).standard_normal((120, 4)) + weights_function, weights_params, _ = KERNELS[kernel] + kw = dict(cfun=tc.autofc, weights_function=weights_function, + weights_params=weights_params, include_zero=include_zero) + causal = _quiet(tc.timecorr, x, causal=True, **kw) + plain = _quiet(tc.timecorr, x, include_timepoints="backward", **kw) + nan_rows = np.isnan(causal).all(axis=1) + assert np.array_equal(nan_rows, (plain == 0).all(axis=1)) + assert np.array_equal(np.flatnonzero(nan_rows), + np.arange(2 if include_zero else 3)) + assert not np.isnan(causal[~nan_rows]).any() + assert np.max(np.abs(causal[~nan_rows] - plain[~nan_rows])) <= ATOL + # smoothing: a value is undefined only without any weighted sample + smooth = _quiet(tc.timecorr, x, causal=True, **{**kw, "cfun": None}) + assert np.array_equal(np.flatnonzero(np.isnan(smooth).all(axis=1)), + np.arange(0 if include_zero else 1)) + assert not np.isnan(smooth[1:]).any() + + +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +def test_a_min_samples_that_no_row_reaches_raises(kernel): + n = 120 + x = np.random.default_rng(15).standard_normal((n, 4)) + weights_function, weights_params, reached = KERNELS[kernel] + w = weights_function(n, weights_params, direction="backward") + most = float(np.max(w.sum(axis=1) ** 2 / (w**2).sum(axis=1))) + kw = dict(causal=True, weights_function=weights_function, + weights_params=weights_params) + shown = re.escape(f"{most:.4g}") + for cfun in (tc.autofc, tc.isfc, None): + with pytest.raises(ValueError, match=rf"min_samples.*{shown}"): + tc.timecorr(x, cfun=cfun, min_samples=most * 1.01, **kw) + out = _quiet(tc.timecorr, x, cfun=cfun, min_samples=most, **kw) + assert not np.isnan(out[-1]).any() # the tolerance: the maximum is reached + assert not np.isnan(_quiet(tc.timecorr, x, cfun=cfun, min_samples=reached, + **kw)[-1]).any() + with pytest.raises(ValueError, match=rf"min_samples.*{shown}"): + tc.wcorr(x, x, w, causal=True, min_samples=most + 1) + # missing data may leave every row below a number the kernel reaches + y = x.copy() + y[::2] = np.nan + assert np.isnan(_quiet(tc.timecorr, y, cfun=tc.autofc, min_samples=most, + **kw)).all() + + def test_three_equal_weights_are_three_samples(): x = np.random.default_rng(3).standard_normal((60, 4)) # a backward boxcar over the lags 0, 1, 2: three weights of 1 from row 2 on @@ -311,7 +383,8 @@ def test_three_equal_weights_are_three_samples(): # the default is 3 assert np.array_equal(out, _quiet(tc.timecorr, x, **kw), equal_nan=True) # a little more than 3 samples asks for more than the window has - assert np.isnan(_quiet(tc.timecorr, x, min_samples=3.001, **kw)).all() + with pytest.raises(ValueError, match="min_samples"): + tc.timecorr(x, min_samples=3.001, **kw) # the same kernel as an array, in wcorr w = np.tril(np.ones((60, 60))) - np.tril(np.ones((60, 60)), -3) r = _quiet(tc.wcorr, x, x, w, causal=True) @@ -321,8 +394,8 @@ def test_three_equal_weights_are_three_samples(): @pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("var, min_samples", [(25, 3), (25, 8), (25, 10), (100, 10), - (25, 0)]) +@pytest.mark.parametrize("var, min_samples", [(25, None), (25, 1), (25, 3), (25, 8), + (100, 10)]) def test_warm_up_rows_are_those_below_the_rules(include_zero, var, min_samples): n = 150 x = np.random.default_rng(4).standard_normal((n, 4)) @@ -333,21 +406,15 @@ def test_warm_up_rows_are_those_below_the_rules(include_zero, var, min_samples): expected = _expected_undefined(w, np.ones(n), min_samples) assert np.array_equal(np.isnan(out).all(axis=1), expected) assert not np.isnan(out[~expected]).any() - if (var, min_samples) == (25, 10): - # a backward Gaussian of variance 25 has fewer than 10 effective - # samples (9.4 with the diagonal) in every row - ess = w[-1].sum() ** 2 / (w[-1] ** 2).sum() - assert 8 < ess < 10 and expected.all() - return first = int(np.flatnonzero(~expected)[0]) assert np.array_equal(np.flatnonzero(expected), np.arange(first)) - if min_samples >= 8: - assert first > 5 # more leading rows than the three-sample rule gives - if min_samples == 3: + if min_samples in (None, 1): + assert first == (2 if include_zero else 3) # fewer than 3 samples + elif min_samples == 3: # three unequal weights are fewer than 3 effective samples assert first == (3 if include_zero else 4) - if min_samples == 0: - assert first == (2 if include_zero else 3) # fewer than 3 samples + else: + assert first > 5 # more leading rows than the three-sample rule gives def test_rows_without_samples_do_not_count_as_observed(): @@ -365,24 +432,13 @@ def test_rows_without_samples_do_not_count_as_observed(): assert expected[45:55].all() and not expected[70:].any() -def test_a_kernel_too_narrow_for_min_samples_gives_no_defined_row(): - x = np.random.default_rng(3).standard_normal((80, 3)) - kw = dict(causal=True, weights_function=tc.t_weights, weights_params={"df": 3}) - for cfun in (tc.autofc, None): - with pytest.warns(UserWarning, match="80"): - out = tc.timecorr(x, cfun=cfun, **kw) - assert np.isnan(out).all() - assert not np.isnan(_quiet(tc.timecorr, x, cfun=cfun, min_samples=2, - **kw)[10:]).any() - - def test_zero_variance_entries_stay_zero(): x = np.random.default_rng(6).standard_normal((100, 4)) x[:, 1] = 7.0 out = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, weights_params={"var": 25}) - assert np.isnan(out[:3]).all() and not np.isnan(out[3:]).any() - full = tc.vec2mat(out[3:]) # (K, K, T - 3) + assert np.isnan(out[:2]).all() and not np.isnan(out[2:]).any() + full = tc.vec2mat(out[2:]) # (K, K, T - 2) assert np.all(full[1, :, :] == 0) and np.all(full[:, 1, :] == 0) assert np.all(full[[0, 2, 3], [0, 2, 3], :] == 1) assert np.any(full[0, 2, :] != 0) @@ -397,11 +453,16 @@ def test_warning_names_the_undefined_rows(): out = tc.timecorr(x, causal=True, cfun=tc.autofc, min_samples=8, weights_params={"var": 25}) assert np.array_equal(np.flatnonzero(np.isnan(out).all(axis=1)), np.arange(n8)) - with pytest.warns(UserWarning, match=r"^3 of 90 timepoints .* NaN"): + with pytest.warns(UserWarning, match=r"^2 of 90 timepoints .* NaN") as record: tc.wcorr(x, x, w, causal=True) - with pytest.warns(UserWarning, match=r"^2 of 90 timepoints .* NaN"): - tc.autofc(x, w, causal=True, min_samples=0) + assert "min_samples" not in str(record[0].message) + with pytest.warns(UserWarning, match=r"^3 of 90 timepoints .*min_samples=3.* NaN"): + tc.autofc(x, w, causal=True, min_samples=3) with pytest.warns(UserWarning, match=r"[Ss]moothing .* 3 timepoint"): + tc.timecorr(x, causal=True, cfun=None, weights_params={"var": 25}, + min_samples=3) + with warnings.catch_warnings(): + warnings.simplefilter("error") # every smoothed value is defined tc.timecorr(x, causal=True, cfun=None, weights_params={"var": 25}) # one warning per call with warnings.catch_warnings(record=True) as caught: @@ -442,7 +503,7 @@ def test_correlation_functions_called_directly(): expected = _quiet(tc.timecorr, data, cfun=cfun, **kw) got = _quiet(direct) for e, g in zip(expected, got): - assert np.isnan(g[:3]).all() and not np.isnan(g[3:]).any() + assert np.isnan(g[:2]).all() and not np.isnan(g[2:]).any() assert np.allclose(e, g, atol=1e-12, rtol=0, equal_nan=True) # a single array, and wcorr one = _quiet(tc.autofc, data[0], w, causal=True, min_samples=6) @@ -614,12 +675,12 @@ def test_graph_measures_run_on_the_defined_rows(rfun): atol=1e-12, rtol=0) # and in a list of subjects outs = _quiet(tc.timecorr, [X, X[::-1].copy()], rfun=rfun, **OK) - assert len(outs) == 2 and np.isnan(outs[1][:3]).all() - assert not np.isnan(outs[1][3:]).any() + assert len(outs) == 2 and np.isnan(outs[1][:2]).all() + assert not np.isnan(outs[1][2:]).any() -@pytest.mark.parametrize("bad", [-1, np.nan, np.inf, "3", None, True]) -def test_min_samples_must_be_a_number(bad): +@pytest.mark.parametrize("bad", [-1, 0, 0.5, np.nan, np.inf, "3", True]) +def test_min_samples_must_be_none_or_a_number_from_1(bad): with pytest.raises(ValueError, match="min_samples"): tc.timecorr(X, min_samples=bad, **OK) w = tc.gaussian_weights(60, {"var": 9}, direction="backward") diff --git a/tests/test_estimator.py b/tests/test_estimator.py index 64b39ed0..2fdc94d8 100644 --- a/tests/test_estimator.py +++ b/tests/test_estimator.py @@ -732,9 +732,10 @@ def test_timecorr_positional_order(): "rfun", "include_zero", ] - assert list(params) == positional + ["events", "events_params"] + keyword_only = ["events", "events_params", "causal", "min_samples"] + assert list(params) == positional + keyword_only assert all( - params[n].kind == inspect.Parameter.KEYWORD_ONLY for n in ("events", "events_params") + params[n].kind == inspect.Parameter.KEYWORD_ONLY for n in keyword_only ) diff --git a/timecorr/helpers.py b/timecorr/helpers.py index 93b663d6..5e44b3db 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -578,12 +578,14 @@ def _estimator_message(weights, cancelled=None, sparse=None, warmup=None, problems = _kernel_row_problems(weights) if warmup is not None: if np.any(warmup): + rule = "" if min_samples is None else ( + " or an effective sample size ((sum |w|)**2 / sum w**2 over the " + f"kernel row) below min_samples={min_samples:g}" + ) parts.append( f"{int(np.sum(warmup))} of {T} timepoints have fewer than 3 " - "weighted, observed samples or an effective sample size " - "((sum |w|)**2 / sum w**2 over the kernel row) below " - f"min_samples={min_samples:g}; their correlations are undefined " - "and returned as NaN (causal=True)." + f"weighted, observed samples{rule}; their correlations are " + "undefined and returned as NaN (causal=True)." ) low = None if problems is None else problems[1] & ~warmup if low is not None and low.any(): @@ -1441,26 +1443,46 @@ def _correlation_ratio(num, var_a, var_b, undefined, shape): def _check_min_samples(min_samples, causal): """ - ``min_samples`` as a float; ``ValueError`` unless it is a finite number - >= 0, and when it is given (not 3) without ``causal=True``. + ``min_samples`` as None or a float; ``ValueError`` unless it is None or + a finite number >= 1, and when it is given without ``causal=True``. """ + if min_samples is None: + return None if ( isinstance(min_samples, (bool, np.bool_)) or not isinstance(min_samples, numbers.Real) - or not 0 <= min_samples < np.inf + or not 1 <= min_samples < np.inf ): raise ValueError( - "min_samples must be a finite number >= 0 (the effective number of " - f"weighted samples a row needs); got {min_samples!r}." + "min_samples must be None or a finite number >= 1 (the effective " + f"number of weighted samples a row needs); got {min_samples!r}." ) - if not causal and min_samples != 3: + if not causal: raise ValueError( f"min_samples={min_samples!r} applies with causal=True only; pass " - "causal=True, or leave min_samples at its default." + "causal=True, or leave min_samples out." ) return float(min_samples) +def _check_reachable(ess, min_samples): + """ + ``ValueError`` when no row of a fully observed kernel, with effective + sample sizes ``ess``, reaches ``min_samples``. + """ + with np.errstate(invalid="ignore"): + reached = np.any(ess >= min_samples * (1 - _MIN_SAMPLES_RTOL)) + if not reached: + finite = ess[np.isfinite(ess)] + most = float(finite.max()) if finite.size else 0.0 + raise ValueError( + f"min_samples={min_samples:g} is more than any row of the kernel " + f"has: its largest effective sample size ((sum |w|)**2 / sum w**2 " + f"over a row) is {most:.4g}. Pass a min_samples of at most that, a " + "wider kernel, or leave min_samples out." + ) + + def _causal_clean(x): """ ``x`` as the causal estimator reads it: infinite samples and samples @@ -1518,22 +1540,22 @@ def _check_causal_rows(rows): _check_causal_kernel(rows.kernel) -def _causal_defined(kernel, observed, min_samples, min_count=3): +def _kernel_samples(kernel, observed=None): """ - The rows of a causal kernel that are defined: at least ``min_count`` - observed timepoints with non-zero weight, and an effective sample size - ``(sum |w|)**2 / sum w**2`` over the observed timepoints of at least - ``min_samples`` (relative tolerance ``_MIN_SAMPLES_RTOL``). + ``(count, ess)`` per row of a kernel: the number of observed timepoints + with non-zero weight, and the effective sample size + ``(sum |w|)**2 / sum w**2`` over them (0 for a row without any). - ``observed`` is a boolean vector over the T timepoints (a timepoint with - no sample at all is not observed). Each row is scaled by its largest - weight first, so tiny weights do not underflow when squared. + ``observed`` is a boolean vector over the T timepoints (None: all). + Each row is scaled by its largest weight first, so tiny weights do not + underflow when squared. """ T_out = kernel.shape[0] count = np.zeros(T_out, dtype=np.int64) ess = np.zeros(T_out) - everything = bool(np.all(observed)) - observed = np.asarray(observed, dtype=np.float64) + everything = observed is None or bool(np.all(observed)) + if not everything: + observed = np.asarray(observed, dtype=np.float64) seen = {} for t0, t1, c0, c1, key, w in blocks(kernel, CHUNK, _abs_weights): stats = seen.get(key) if (key is not None and everything) else None @@ -1550,9 +1572,29 @@ def _causal_defined(kernel, observed, min_samples, min_count=3): if key is not None and everything: seen[key] = stats count[t0:t1], ess[t0:t1] = stats - with np.errstate(invalid="ignore"): - enough = ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) - return (count >= min_count) & enough + return count, ess + + +def _causal_defined(kernel, observed, min_samples, min_count=3): + """ + The rows of a causal kernel that are defined: at least ``min_count`` + observed timepoints with non-zero weight and, with ``min_samples`` (not + None), an effective sample size over the observed timepoints of at + least ``min_samples`` (relative tolerance ``_MIN_SAMPLES_RTOL``). + + ``observed`` is a boolean vector over the T timepoints (a timepoint with + no sample at all is not observed). ``ValueError`` when no row of the + fully observed kernel reaches ``min_samples``. + """ + count, ess = _kernel_samples(kernel, observed) + defined = count >= min_count + if min_samples is not None: + _check_reachable( + ess if np.all(observed) else _kernel_samples(kernel)[1], min_samples + ) + with np.errstate(invalid="ignore"): + defined &= ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) + return defined def _causal_reference(x, c0, t0, c1): @@ -1756,7 +1798,7 @@ def _symmetrize_block(r, undefined, offset): r[:, :, offset : offset + c] = (square + square.transpose(0, 2, 1)) / 2 -def _wcorr_blocks(a, b, rows, autocorrelation, min_samples=None): +def _wcorr_blocks(a, b, rows, autocorrelation, causal=False, min_samples=None): """ Kernel-weighted correlations, computed with matrix products over blocks of feature pairs. NaN samples are excluded pairwise (they carry no weight). @@ -1769,13 +1811,12 @@ def _wcorr_blocks(a, b, rows, autocorrelation, min_samples=None): diagonal of an autocorrelation included). Without NaN samples ``sparse`` is all False. - ``min_samples`` (not None) selects the causal estimator - (``_causal_setup``): the rows it leaves undefined are NaN in ``out``, and + ``causal=True`` selects the causal estimator (``_causal_setup``, with + ``min_samples``): the rows it leaves undefined are NaN in ``out``, and their mask is returned as a fourth item (None otherwise). """ T, Ka = a.shape Kb = b.shape[1] - causal = min_samples is not None if causal: state = _causal_setup(a, b, rows, autocorrelation, min_samples) else: @@ -1809,7 +1850,7 @@ def _wcorr_blocks(a, b, rows, autocorrelation, min_samples=None): def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None, *, - causal=False, min_samples=3): + causal=False, min_samples=None): """ The rows of ``_wcorr(a, b, weights)`` in blocks, without the full array. @@ -1898,7 +1939,7 @@ def blocks(): return blocks() -def wcorr(a, b, weights, *, causal=False, min_samples=3): +def wcorr(a, b, weights, *, causal=False, min_samples=None): """ Compute kernel-weighted correlations between two sets of observations. @@ -1998,14 +2039,14 @@ def wcorr(a, b, weights, *, causal=False, min_samples=3): conditions the sums. - Infinite samples and samples above 1e150 in magnitude are missing data, like NaN. - - A timepoint with fewer than 3 observed samples with non-zero weight, - or whose effective sample size ``(sum |w|)**2 / sum w**2`` over the - observed timepoints of its kernel row is below ``min_samples``, is - undefined: all its correlations are NaN (the diagonal included), not - 0. A timepoint counts as observed when ``a`` and ``b`` each have at - least one sample there. Other undefined entries are 0, as without - ``causal``: constant features, and pairs of features with fewer than - 3 common samples. + - A timepoint with fewer than 3 observed samples with non-zero weight + is undefined: all its correlations are NaN (the diagonal included), + not 0; so is, with ``min_samples``, a timepoint whose effective + sample size ``(sum |w|)**2 / sum w**2`` over the observed timepoints + of its kernel row is below it. A timepoint counts as observed when + ``a`` and ``b`` each have at least one sample there. Other undefined + entries are 0, as without ``causal``: constant features, and pairs of + features with fewer than 3 common samples. - ``a`` and ``b`` are an autocorrelation (diagonal set to 1) only when they are the same object; equal values in two arrays are not compared. - A delta kernel raises ``ValueError`` (its z-scores use every @@ -2025,11 +2066,13 @@ def wcorr(a, b, weights, *, causal=False, min_samples=3): no non-zero entry above its diagonal (for example a kernel function called with ``direction='backward'``). Keyword only. Default: False. - min_samples : float, optional + min_samples : float or None, optional With ``causal=True``, the effective sample size - ``(sum |w|)**2 / sum w**2`` a timepoint needs (compared with a - relative tolerance of 1e-12, so three equal weights are 3 samples); - timepoints below it are NaN. Keyword only. Default: 3. + ``(sum |w|)**2 / sum w**2`` a timepoint needs (a number >= 1, + compared with a relative tolerance of 1e-12, so three equal weights + are 3 samples); timepoints below it are NaN too. A number that no + row of the kernel reaches raises ``ValueError``. Keyword only. + Default: None (only the rule of 3 samples). Returns ------- @@ -2059,8 +2102,9 @@ def wcorr(a, b, weights, *, causal=False, min_samples=3): If the inputs do not have T rows / T kernel columns, or if every row of the kernel is zero. With ``causal=True``: if the kernel has weight above its diagonal or is a delta kernel, or if ``min_samples`` is - not a finite number >= 0. If ``min_samples`` is given without - ``causal=True``. + not None or a finite number >= 1, or is more than the largest + effective sample size of the kernel's rows. If ``min_samples`` is + given without ``causal=True``. Examples -------- @@ -2078,12 +2122,12 @@ def wcorr(a, b, weights, *, causal=False, min_samples=3): The causal estimator: timepoint 60 does not depend on later samples. - The first 3 timepoints have fewer than 3 effective samples and are NaN - (a ``UserWarning`` says so). + The first 2 timepoints have fewer than 3 samples and are NaN (a + ``UserWarning`` says so). >>> past = tc.gaussian_weights(100, {"var": 50}, direction="backward") >>> r = tc.wcorr(x, x, past, causal=True) - >>> bool(np.isnan(r[:, :, :3]).all()), bool(np.isnan(r[:, :, 3:]).any()) + >>> bool(np.isnan(r[:, :, :2]).all()), bool(np.isnan(r[:, :, 2:]).any()) (True, False) >>> y = x.copy() >>> y[61:] = 1000.0 @@ -2095,7 +2139,7 @@ def wcorr(a, b, weights, *, causal=False, min_samples=3): def _wcorr(a, b, weights, warn=True, return_cancelled=False, causal=False, - min_samples=3, autocorrelation=None): + min_samples=None, autocorrelation=None): """ ``wcorr``. With ``warn=False`` the warning is left to the caller; with ``return_cancelled=True`` the masks ``(cancelled, sparse)`` of the @@ -2119,7 +2163,7 @@ def _wcorr(a, b, weights, warn=True, return_cancelled=False, causal=False, if autocorrelation is None: autocorrelation = same out, cancelled, sparse, warmup = _wcorr_blocks( - a, b, rows, autocorrelation, min_samples + a, b, rows, autocorrelation, True, min_samples ) del rows if warn: @@ -2267,7 +2311,7 @@ def _fisher_mean(r, axis): def wisfc(data, timepoint_weights, subject_weights=None, *, causal=False, - min_samples=3): + min_samples=None): """ Compute weighted inter-subject functional connectivity (ISFC). @@ -2309,12 +2353,13 @@ def wisfc(data, timepoint_weights, subject_weights=None, *, causal=False, timepoints are rows of NaN, not 0. ``subject_weights`` must be given: the default weights are computed from every timepoint. Keyword only. Default: False. - min_samples : float, optional - With ``causal=True``, the effective sample size - ``(sum |w|)**2 / sum w**2`` a timepoint needs, over the timepoints of - its kernel row where the subject and its reference each have a - sample; a timepoint below it, or with fewer than 3 such timepoints, - is a row of NaN. Keyword only. Default: 3. + min_samples : float or None, optional + With ``causal=True``, a timepoint with fewer than 3 weighted + timepoints where the subject and its reference each have a sample + is a row of NaN. A number (>= 1) is also the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints + (rows below it are NaN); one that no row of a kernel reaches raises + ``ValueError``. Keyword only. Default: None. Returns ------- @@ -2351,8 +2396,9 @@ def wisfc(data, timepoint_weights, subject_weights=None, *, causal=False, every row of the kernel is zero, or a list of kernels does not have one kernel per subject. With ``causal=True``: if a kernel has weight above its diagonal or is a delta kernel, if ``subject_weights`` is None, or if - ``min_samples`` is not a finite number >= 0. If ``min_samples`` is - given without ``causal=True``. + ``min_samples`` is not None or a finite number >= 1, or is more + than any row of a kernel reaches. If ``min_samples`` is given + without ``causal=True``. Notes ----- @@ -2588,7 +2634,7 @@ def _kernels_message(kernels, group_of, cancelled, sparse=None, warmup=None, return " ".join(parts) if parts else None -def isfc(data, timepoint_weights, *, causal=False, min_samples=3): +def isfc(data, timepoint_weights, *, causal=False, min_samples=None): """ Compute Inter-Subject Functional Connectivity (ISFC). @@ -2622,12 +2668,13 @@ def isfc(data, timepoint_weights, *, causal=False, min_samples=3): called with ``direction='backward'``); infinite samples and samples above 1e150 in magnitude are missing data; undefined (warm-up) timepoints are rows of NaN, not 0. Keyword only. Default: False. - min_samples : float, optional - With ``causal=True``, the effective sample size - ``(sum |w|)**2 / sum w**2`` a timepoint needs, over the timepoints of - its kernel row where the subject and its reference each have a - sample; a timepoint below it, or with fewer than 3 such timepoints, - is a row of NaN. Keyword only. Default: 3. + min_samples : float or None, optional + With ``causal=True``, a timepoint with fewer than 3 weighted + timepoints where the subject and its reference each have a sample + is a row of NaN. A number (>= 1) is also the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints + (rows below it are NaN); one that no row of a kernel reaches raises + ``ValueError``. Keyword only. Default: None. Returns ------- @@ -2665,8 +2712,9 @@ def isfc(data, timepoint_weights, *, causal=False, min_samples=3): every row of the kernel is zero, or a list of kernels does not have one kernel per subject. With ``causal=True``: if a kernel has weight above its diagonal or is a delta kernel, or if - ``min_samples`` is not a finite number >= 0. If ``min_samples`` is - given without ``causal=True``. + ``min_samples`` is not None or a finite number >= 1, or is more + than any row of a kernel reaches. If ``min_samples`` is given + without ``causal=True``. Notes ----- @@ -2697,7 +2745,7 @@ def isfc(data, timepoint_weights, *, causal=False, min_samples=3): causal=causal, min_samples=min_samples) -def autofc(data, timepoint_weights, *, causal=False, min_samples=3): +def autofc(data, timepoint_weights, *, causal=False, min_samples=None): """ Compute auto-correlations within each subject's data. @@ -2725,12 +2773,13 @@ def autofc(data, timepoint_weights, *, causal=False, min_samples=3): called with ``direction='backward'``); infinite samples and samples above 1e150 in magnitude are missing data; undefined (warm-up) timepoints are rows of NaN, not 0. Keyword only. Default: False. - min_samples : float, optional - With ``causal=True``, the effective sample size - ``(sum |w|)**2 / sum w**2`` a timepoint needs, over the timepoints of - its kernel row where the subject and its reference each have a - sample; a timepoint below it, or with fewer than 3 such timepoints, - is a row of NaN. Keyword only. Default: 3. + min_samples : float or None, optional + With ``causal=True``, a timepoint with fewer than 3 weighted + timepoints where the subject and its reference each have a sample + is a row of NaN. A number (>= 1) is also the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints + (rows below it are NaN); one that no row of a kernel reaches raises + ``ValueError``. Keyword only. Default: None. Returns ------- @@ -2763,8 +2812,9 @@ def autofc(data, timepoint_weights, *, causal=False, min_samples=3): every row of the kernel is zero, or a list of kernels does not have one kernel per subject. With ``causal=True``: if a kernel has weight above its diagonal or is a delta kernel, or if - ``min_samples`` is not a finite number >= 0. If ``min_samples`` is - given without ``causal=True``. + ``min_samples`` is not None or a finite number >= 1, or is more + than any row of a kernel reaches. If ``min_samples`` is given + without ``causal=True``. Examples -------- diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 2db2536c..86b53fb0 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -19,9 +19,11 @@ _abs_weights, _as_kernel_array, _causal_clean, + _check_reachable, _check_causal_kernel, _check_min_samples, _check_rfun, + _kernel_samples, _lag_kernel, _warn_user, autofc, @@ -44,11 +46,15 @@ def _causal_smooth(x, weights, min_samples): ``_kernel_smooth`` for ``causal=True``: the same kernel-weighted means of a kernel without weight on later timepoints, each chunk of rows over the columns where it has weight. Infinite samples and samples above 1e150 - in magnitude are missing, like NaN. An entry whose feature has an - effective sample size ``(sum |w|)**2 / sum w**2`` (over the feature's - observed samples in the kernel row) below ``min_samples``, or no weighted - sample, is NaN; one warning reports how many timepoints have one. + in magnitude are missing, like NaN. An entry whose feature has no + weighted sample or, with ``min_samples`` (not None), an effective sample + size ``(sum |w|)**2 / sum w**2`` (over the feature's observed samples in + the kernel row) below it is NaN; one warning reports how many timepoints + have one. ``ValueError`` when no row of the kernel reaches + ``min_samples``. """ + if min_samples is not None: + _check_reachable(_kernel_samples(as_kernel(weights))[1], min_samples) x = _causal_clean(x) valid = ~np.isnan(x) observed = np.where(valid, x, 0.0) @@ -63,17 +69,20 @@ def _causal_smooth(x, weights, min_samples): w = np.divide(w, peak, out=np.zeros_like(w), where=peak != 0) den = w @ valid[c0:c1] num = w @ observed[c0:c1] - ess = np.divide(den**2, (w * w) @ valid[c0:c1], out=np.zeros_like(den), - where=den > 0) - defined = (den > 0) & (ess >= min_samples * (1 - _MIN_SAMPLES_RTOL)) + defined = den > 0 + if min_samples is not None: + ess = np.divide(den**2, (w * w) @ valid[c0:c1], + out=np.zeros_like(den), where=defined) + defined &= ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) np.divide(num, den, out=out[t0:t1], where=defined) undefined = np.isnan(out).any(axis=1) if undefined.any(): warnings.warn( f"Smoothing is undefined at {int(undefined.sum())} timepoint(s) (for " - "some feature, no weighted, observed sample or an effective sample " - f"size below min_samples={min_samples:g}); those values are NaN " - "(causal=True)." + "some feature, no weighted, observed sample" + + ("" if min_samples is None else + f" or an effective sample size below min_samples={min_samples:g}") + + "); those values are NaN (causal=True)." ) return out @@ -373,7 +382,7 @@ def timecorr( events=None, events_params=None, causal=False, - min_samples=3, + min_samples=None, ): """ Compute dynamic (moment-by-moment) correlations in one or more datasets. @@ -529,20 +538,23 @@ def timecorr( a time, on the mean of its earlier samples that the chunk weights, and its zero-variance rule is relative to that reference (see ``wcorr``); - - timepoints with too few samples are rows of NaN, not 0 (see + - timepoints with fewer than 3 samples are rows of NaN, not 0 (see ``min_samples``). - min_samples : float - With ``causal=True``, the effective sample size - ``(sum |w|)**2 / sum w**2`` that a timepoint needs, summed over the - observed timepoints of its kernel row (those where the data, and - for ``isfc`` and ``wisfc`` the reference, have at least one sample); - compared with a relative tolerance of 1e-12, so three equal weights - are 3 samples. A timepoint below it, or with fewer than 3 observed - timepoints with non-zero weight, is a row of NaN. With - ``cfun=None`` only the effective sample size applies, to each - feature's own observed samples: values below it are NaN. Features - with zero variance still give correlations of 0. Keyword only. - Default: 3. + min_samples : float or None + With ``causal=True``, a timepoint with fewer than 3 observed + timepoints with non-zero weight in its kernel row is a row of NaN + (observed: the data, and for ``isfc`` and ``wisfc`` the reference, + have at least one sample there): the rows that are 0 without + ``causal``. A number (>= 1) is also the effective sample size + ``(sum |w|)**2 / sum w**2`` a timepoint needs over those + timepoints, compared with a relative tolerance of 1e-12 (three + equal weights are 3 samples); rows below it are NaN too. A number + that no row of the kernel reaches raises ``ValueError`` (a backward + Gaussian of variance 25 has at most 9.4 effective samples). With + ``cfun=None`` a value is NaN when its feature has no weighted + sample, or fewer effective samples than the number. Features with + zero variance still give correlations of 0. Keyword only. + Default: None. Returns ------- @@ -590,8 +602,9 @@ def timecorr( ``cfun`` does not return a list with one array per subject; and as raised by ``segment`` for features entries of ``events``. With ``causal=True``, for the arguments listed under ``causal`` that have - no causal form, and for a ``min_samples`` that is not a finite number - >= 0; for ``min_samples`` given without ``causal=True``. + no causal form, and for a ``min_samples`` that is not None or a + finite number >= 1, or that no row of the kernel reaches; for + ``min_samples`` given without ``causal=True``. NotImplementedError With ``causal=True``, for an ``rfun`` that is fitted to data. RuntimeError, ImportError @@ -684,11 +697,11 @@ def timecorr( (3, (100, 15)) Causal estimates: row 60 does not change when later rows do. The first - 3 rows have fewer than 3 effective samples and are NaN (a - ``UserWarning`` says so). + 2 rows have fewer than 3 samples and are NaN (a ``UserWarning`` says + so). >>> past = tc.timecorr(data, causal=True, weights_params={"var": 50}) - >>> bool(np.isnan(past[:3]).all()), bool(np.isnan(past[3:]).any()) + >>> bool(np.isnan(past[:2]).all()), bool(np.isnan(past[2:]).any()) (True, False) >>> later = data.copy() >>> later[61:] = 1000.0 From 798d4fccef68a80b834891f868d2305993c881d1 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 11:11:03 -0500 Subject: [PATCH 03/26] Causal estimator: whether min_samples raises does not depend on the length 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 112 ++++++++++++++++++++++++--- timecorr/_kernels.py | 9 ++- timecorr/helpers.py | 135 +++++++++++++++++++++++---------- timecorr/timecorr.py | 17 +++-- 4 files changed, 213 insertions(+), 60 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 37a53481..c60050ad 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -152,7 +152,7 @@ def test_rows_do_not_depend_on_later_rows_with_min_samples(case, include_zero, k assert nan_rows.sum() > default or (kernel == "t" and nan_rows.sum() == default) assert not nan_rows[30:].all() rng = np.random.default_rng(27) - for n in CUTS[1:]: # (a series of 3 rows cannot reach the number: ValueError) + for n in CUTS: # (the first 3 rows alone cannot reach the number: NaN rows) part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, include_zero, min_samples=min_samples) assert _max_difference(full, part, n) <= ATOL @@ -345,32 +345,122 @@ def test_default_nan_rows_are_the_zero_rows_of_causal_false(kernel, include_zero assert not np.isnan(smooth[1:]).any() +def _reach(weights_function, weights_params, include_zero=True, n=4000): + """The largest effective sample size of a row with ``n`` earlier timepoints.""" + w = weights_function(n, weights_params, direction="backward", + include_zero=include_zero)[-1] + return float(np.abs(w).sum() ** 2 / (w**2).sum()) + + +@pytest.mark.parametrize("include_zero", [True, False]) @pytest.mark.parametrize("kernel", sorted(KERNELS)) -def test_a_min_samples_that_no_row_reaches_raises(kernel): +def test_a_min_samples_that_no_row_reaches_raises(kernel, include_zero): n = 120 x = np.random.default_rng(15).standard_normal((n, 4)) weights_function, weights_params, reached = KERNELS[kernel] - w = weights_function(n, weights_params, direction="backward") - most = float(np.max(w.sum(axis=1) ** 2 / (w**2).sum(axis=1))) + # what a row reaches with any number of earlier timepoints + most = _reach(weights_function, weights_params, include_zero) + assert helpers._kernel_reach(helpers._lag_kernel( + 7, weights_function, weights_params, "backward", include_zero + )) == pytest.approx(most, rel=1e-9) kw = dict(causal=True, weights_function=weights_function, - weights_params=weights_params) + weights_params=weights_params, include_zero=include_zero) shown = re.escape(f"{most:.4g}") for cfun in (tc.autofc, tc.isfc, None): with pytest.raises(ValueError, match=rf"min_samples.*{shown}"): tc.timecorr(x, cfun=cfun, min_samples=most * 1.01, **kw) - out = _quiet(tc.timecorr, x, cfun=cfun, min_samples=most, **kw) - assert not np.isnan(out[-1]).any() # the tolerance: the maximum is reached - assert not np.isnan(_quiet(tc.timecorr, x, cfun=cfun, min_samples=reached, + low = min(reached, most * 0.99) + assert not np.isnan(_quiet(tc.timecorr, x, cfun=cfun, min_samples=low, **kw)[-1]).any() - with pytest.raises(ValueError, match=rf"min_samples.*{shown}"): - tc.wcorr(x, x, w, causal=True, min_samples=most + 1) # missing data may leave every row below a number the kernel reaches y = x.copy() y[::2] = np.nan - assert np.isnan(_quiet(tc.timecorr, y, cfun=tc.autofc, min_samples=most, + assert np.isnan(_quiet(tc.timecorr, y, cfun=tc.autofc, min_samples=most * 0.99, **kw)).all() +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("cfun", [tc.autofc, None]) +def test_whether_min_samples_raises_does_not_depend_on_the_length(kernel, cfun): + weights_function, weights_params, reached = KERNELS[kernel] + most = _reach(weights_function, weights_params) + kw = dict(causal=True, cfun=cfun, weights_function=weights_function, + weights_params=weights_params) + x = np.random.default_rng(16).standard_normal((400, 3)) + for n in (3, 4, 10, 60, 400): + # a number the kernel reaches, though not within n rows: no error, and + # the rows that do not reach it are NaN + out = _quiet(tc.timecorr, x[:n], min_samples=most * 0.999, **kw) + assert out.shape[0] == n + if n <= 10 and kernel != "t": + assert np.isnan(out).all() + # a number no row of any series reaches: the same error at every length + with pytest.raises(ValueError, match="min_samples"): + tc.timecorr(x[:n], min_samples=most * 1.001, **kw) + + +def test_three_rows_cannot_reach_six_samples_and_are_nan(): + x = np.random.default_rng(17).standard_normal((300, 4)) + kw = dict(causal=True, weights_params={"var": 25}, min_samples=6) + for cfun in (tc.autofc, None): + full = _quiet(tc.timecorr, x, cfun=cfun, **kw) + short = _quiet(tc.timecorr, x[:3], cfun=cfun, **kw) + assert np.isnan(short).all() and np.isnan(full[:3]).all() + assert not np.isnan(full[100:]).any() + w = tc.gaussian_weights(3, {"var": 25}, direction="backward") + assert np.isnan(_quiet(tc.wcorr, x[:3], x[:3], w, causal=True, min_samples=6)).all() + + +def test_kernels_without_a_lag_profile_never_raise_for_min_samples(): + n = 60 + x = np.random.default_rng(18).standard_normal((n, 4)) + w = tc.gaussian_weights(n, {"var": 9}, direction="backward") + most = float(np.max(w.sum(axis=1) ** 2 / (w**2).sum(axis=1))) + # an array: every row is below the number, so every row is NaN + assert np.isnan(_quiet(tc.wcorr, x, x, w, causal=True, min_samples=most + 1)).all() + assert np.isnan(_quiet(tc.autofc, x, w, causal=True, min_samples=most + 1)).all() + assert helpers._kernel_reach(helpers.as_kernel(w)) is None + # a kernel function of the user's + for cfun in (tc.autofc, None): + out = _quiet( + tc.timecorr, x, causal=True, cfun=cfun, weights_params={"var": 9}, + min_samples=most + 1, + weights_function=lambda T, p: tc.gaussian_weights(T, p, direction="backward")) + assert np.isnan(out).all() + # the same kernel, built in: the error + with pytest.raises(ValueError, match="min_samples"): + tc.timecorr(x, causal=True, cfun=tc.autofc, weights_params={"var": 9}, + min_samples=most + 1) + + +def test_reach_of_the_built_in_kernels(): + def reach(function, params, **kwargs): + return helpers._kernel_reach( + helpers._lag_kernel(5, function, params, "backward", **kwargs)) + + # equal weights at every lag: no limit + assert reach(tc.uniform_weights, None) is None + x = np.random.default_rng(19).standard_normal((40, 3)) + out = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, min_samples=30, + weights_function=tc.uniform_weights, weights_params={}) + assert np.array_equal(np.flatnonzero(np.isnan(out).all(axis=1)), np.arange(29)) + # a boxcar over the lags 0..14, and without the diagonal + assert reach(tc.boxcar_weights, {"width": 30}) == pytest.approx(15) + assert reach(tc.boxcar_weights, {"width": 30}, include_zero=False) == pytest.approx(14) + # exclude_timepoints: the lags 0..4, and the lags from 5 on + assert reach(tc.boxcar_weights, {"width": 30}, exclude=4) == pytest.approx(5) + assert reach(tc.boxcar_weights, {"width": 30}, exclude=-4) == pytest.approx(10) + # a wide Gaussian: sd * 2 * sqrt(pi) / 2 of a half kernel, about 1.77 sd + wide = reach(tc.gaussian_weights, {"var": 1e6}) + assert wide == pytest.approx(_reach(tc.gaussian_weights, {"var": 1e6}, n=9000), + rel=1e-9) + assert 1700 < wide < 1800 + # event boundaries do not change what a kernel can reach + kernel = helpers._lag_kernel(50, tc.gaussian_weights, {"var": 25}, "backward") + labels = np.repeat([0, 1], 25) + assert helpers._kernel_reach(kernel.with_events(labels)) == helpers._kernel_reach(kernel) + + def test_three_equal_weights_are_three_samples(): x = np.random.default_rng(3).standard_normal((60, 4)) # a backward boxcar over the lags 0, 1, 2: three weights of 1 from row 2 on diff --git a/timecorr/_kernels.py b/timecorr/_kernels.py index b78e06da..b1f13160 100644 --- a/timecorr/_kernels.py +++ b/timecorr/_kernels.py @@ -147,14 +147,19 @@ class LagKernel: between timepoints in different blocks are 0. The blocks are the runs of consecutive equal labels (a label that returns after another starts a new block); labels with a single block are stored as None. + lag_profile : callable or None + The function that gives the weights at any absolute lags (an integer + array), beyond ``T - 1`` too, when it is known (the built-in kernel + functions); ``helpers._kernel_reach`` reads it. The values equal those of the T x T matrix that ``timecorr`` builds from the kernel function and the same restrictions, entry for entry. """ def __init__(self, profile, include="all", include_zero=True, exclude=None, - labels=None): + labels=None, lag_profile=None): self.profile = np.asarray(profile, dtype=np.float64) + self.lag_profile = lag_profile self.T = int(self.profile.shape[0]) self.shape = (self.T, self.T) if include not in ("all", "backward", "forward"): @@ -216,7 +221,7 @@ def with_events(self, labels): else: labels = self.labels return LagKernel(self.profile, self.include, self.include_zero, self.exclude, - labels) + labels, self.lag_profile) def same_as(self, other): """True when ``other`` is a LagKernel with the same weights.""" diff --git a/timecorr/helpers.py b/timecorr/helpers.py index 5e44b3db..c5f3f2ab 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -1,4 +1,5 @@ # coding: utf-8 +import functools import inspect import numbers import os @@ -501,7 +502,8 @@ def _lag_kernel(T, weights_function, weights_params, include="all", include_zero return None params = defaults if weights_params is None else weights_params return LagKernel(profile(np.arange(int(T), dtype=np.int64), params), include, - include_zero, exclude) + include_zero, exclude, + lag_profile=functools.partial(profile, params=params)) def _as_kernel_array(weights): @@ -1465,22 +1467,80 @@ def _check_min_samples(min_samples, causal): return float(min_samples) -def _check_reachable(ess, min_samples): +# ``_kernel_reach`` evaluates a lag profile at up to this many lags. +_REACH_LAGS = 2 ** 22 + + +def _kernel_reach(kernel): """ - ``ValueError`` when no row of a fully observed kernel, with effective - sample sizes ``ess``, reaches ``min_samples``. + The largest effective sample size ``(sum |w|)**2 / sum w**2`` a row of a + backward kernel can have with any number of earlier timepoints: the + largest over the lags ``0..n`` (from 1 without the diagonal, within + ``exclude_timepoints``), for every n. It does not depend on the length + of the series. + + None when it is not known or has no limit: a kernel without a lag + profile function (an array, a kernel function of the user's), and a + profile whose sums have not converged within ``_REACH_LAGS`` lags + (``uniform_weights``). The result is kept on the kernel. """ - with np.errstate(invalid="ignore"): - reached = np.any(ess >= min_samples * (1 - _MIN_SAMPLES_RTOL)) - if not reached: - finite = ess[np.isfinite(ess)] - most = float(finite.max()) if finite.size else 0.0 - raise ValueError( - f"min_samples={min_samples:g} is more than any row of the kernel " - f"has: its largest effective sample size ((sum |w|)**2 / sum w**2 " - f"over a row) is {most:.4g}. Pass a min_samples of at most that, a " - "wider kernel, or leave min_samples out." - ) + profile = getattr(kernel, "lag_profile", None) + if profile is None or kernel.include != "backward": + return None + cached = getattr(kernel, "_reach", None) + if cached is not None: + return cached[0] + reach = None + n = 1024 + while n <= _REACH_LAGS: + with np.errstate(over="ignore", invalid="ignore"): + a = np.abs(np.asarray(profile(np.arange(n, dtype=np.int64)), dtype=np.float64)) + a[~np.isfinite(a)] = 0 + if not kernel.include_zero: + a[0] = 0 + if kernel.exclude is not None: + x = int(min(abs(kernel.exclude), n)) + if kernel.exclude >= 0: + a[x + 1:] = 0 + else: + a[:x + 1] = 0 + peak = a.max() + if peak > 0: + a /= peak # so that tiny weights do not underflow when squared + total = np.cumsum(a) + squares = np.cumsum(a * a) + # converged: the later half of the lags adds nothing to the sums + if total[-1] - total[n // 2 - 1] <= 1e-15 * total[-1]: + with np.errstate(invalid="ignore", divide="ignore"): + ess = total**2 / squares + reach = float(np.nanmax(ess)) + break + n *= 2 + else: + if peak == 0: + reach = 0.0 + kernel._reach = (reach,) + return reach + + +def _check_reachable(kernel, min_samples): + """ + ``ValueError`` when no row of ``kernel``, however many timepoints come + before it, reaches ``min_samples`` (``_kernel_reach``; never for a kernel + without a lag profile function). The decision does not depend on the + length of the series: rows of a short series that do not reach + ``min_samples`` are undefined, not an error. + """ + most = _kernel_reach(as_kernel(kernel)) + if most is None or most >= min_samples * (1 - _MIN_SAMPLES_RTOL): + return + raise ValueError( + f"min_samples={min_samples:g} is more than a row of the kernel can " + "have: with any number of earlier timepoints its largest effective " + f"sample size ((sum |w|)**2 / sum w**2 over a row) is {most:.4g}. " + "Pass a min_samples of at most that, a wider kernel, or leave " + "min_samples out." + ) def _causal_clean(x): @@ -1583,15 +1643,14 @@ def _causal_defined(kernel, observed, min_samples, min_count=3): least ``min_samples`` (relative tolerance ``_MIN_SAMPLES_RTOL``). ``observed`` is a boolean vector over the T timepoints (a timepoint with - no sample at all is not observed). ``ValueError`` when no row of the - fully observed kernel reaches ``min_samples``. + no sample at all is not observed). ``ValueError`` when the kernel + cannot reach ``min_samples`` at any length (``_check_reachable``). """ + if min_samples is not None: + _check_reachable(kernel, min_samples) count, ess = _kernel_samples(kernel, observed) defined = count >= min_count if min_samples is not None: - _check_reachable( - ess if np.all(observed) else _kernel_samples(kernel)[1], min_samples - ) with np.errstate(invalid="ignore"): defined &= ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) return defined @@ -2070,8 +2129,8 @@ def wcorr(a, b, weights, *, causal=False, min_samples=None): With ``causal=True``, the effective sample size ``(sum |w|)**2 / sum w**2`` a timepoint needs (a number >= 1, compared with a relative tolerance of 1e-12, so three equal weights - are 3 samples); timepoints below it are NaN too. A number that no - row of the kernel reaches raises ``ValueError``. Keyword only. + are 3 samples); timepoints below it are NaN too (every timepoint, + when no row of the array reaches the number). Keyword only. Default: None (only the rule of 3 samples). Returns @@ -2102,9 +2161,8 @@ def wcorr(a, b, weights, *, causal=False, min_samples=None): If the inputs do not have T rows / T kernel columns, or if every row of the kernel is zero. With ``causal=True``: if the kernel has weight above its diagonal or is a delta kernel, or if ``min_samples`` is - not None or a finite number >= 1, or is more than the largest - effective sample size of the kernel's rows. If ``min_samples`` is - given without ``causal=True``. + not None or a finite number >= 1. If ``min_samples`` is given + without ``causal=True``. Examples -------- @@ -2358,8 +2416,8 @@ def wisfc(data, timepoint_weights, subject_weights=None, *, causal=False, timepoints where the subject and its reference each have a sample is a row of NaN. A number (>= 1) is also the effective sample size ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints - (rows below it are NaN); one that no row of a kernel reaches raises - ``ValueError``. Keyword only. Default: None. + (rows below it are NaN; every row, when no row of the array reaches + the number). Keyword only. Default: None. Returns ------- @@ -2396,9 +2454,8 @@ def wisfc(data, timepoint_weights, subject_weights=None, *, causal=False, every row of the kernel is zero, or a list of kernels does not have one kernel per subject. With ``causal=True``: if a kernel has weight above its diagonal or is a delta kernel, if ``subject_weights`` is None, or if - ``min_samples`` is not None or a finite number >= 1, or is more - than any row of a kernel reaches. If ``min_samples`` is given - without ``causal=True``. + ``min_samples`` is not None or a finite number >= 1. If + ``min_samples`` is given without ``causal=True``. Notes ----- @@ -2673,8 +2730,8 @@ def isfc(data, timepoint_weights, *, causal=False, min_samples=None): timepoints where the subject and its reference each have a sample is a row of NaN. A number (>= 1) is also the effective sample size ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints - (rows below it are NaN); one that no row of a kernel reaches raises - ``ValueError``. Keyword only. Default: None. + (rows below it are NaN; every row, when no row of the array reaches + the number). Keyword only. Default: None. Returns ------- @@ -2712,9 +2769,8 @@ def isfc(data, timepoint_weights, *, causal=False, min_samples=None): every row of the kernel is zero, or a list of kernels does not have one kernel per subject. With ``causal=True``: if a kernel has weight above its diagonal or is a delta kernel, or if - ``min_samples`` is not None or a finite number >= 1, or is more - than any row of a kernel reaches. If ``min_samples`` is given - without ``causal=True``. + ``min_samples`` is not None or a finite number >= 1. If + ``min_samples`` is given without ``causal=True``. Notes ----- @@ -2778,8 +2834,8 @@ def autofc(data, timepoint_weights, *, causal=False, min_samples=None): timepoints where the subject and its reference each have a sample is a row of NaN. A number (>= 1) is also the effective sample size ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints - (rows below it are NaN); one that no row of a kernel reaches raises - ``ValueError``. Keyword only. Default: None. + (rows below it are NaN; every row, when no row of the array reaches + the number). Keyword only. Default: None. Returns ------- @@ -2812,9 +2868,8 @@ def autofc(data, timepoint_weights, *, causal=False, min_samples=None): every row of the kernel is zero, or a list of kernels does not have one kernel per subject. With ``causal=True``: if a kernel has weight above its diagonal or is a delta kernel, or if - ``min_samples`` is not None or a finite number >= 1, or is more - than any row of a kernel reaches. If ``min_samples`` is given - without ``causal=True``. + ``min_samples`` is not None or a finite number >= 1. If + ``min_samples`` is given without ``causal=True``. Examples -------- diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 86b53fb0..1a6393bd 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -23,7 +23,6 @@ _check_causal_kernel, _check_min_samples, _check_rfun, - _kernel_samples, _lag_kernel, _warn_user, autofc, @@ -50,11 +49,11 @@ def _causal_smooth(x, weights, min_samples): weighted sample or, with ``min_samples`` (not None), an effective sample size ``(sum |w|)**2 / sum w**2`` (over the feature's observed samples in the kernel row) below it is NaN; one warning reports how many timepoints - have one. ``ValueError`` when no row of the kernel reaches - ``min_samples``. + have one. ``ValueError`` when the kernel cannot reach ``min_samples`` + with any number of earlier timepoints (``_check_reachable``). """ if min_samples is not None: - _check_reachable(_kernel_samples(as_kernel(weights))[1], min_samples) + _check_reachable(weights, min_samples) x = _causal_clean(x) valid = ~np.isnan(x) observed = np.where(valid, x, 0.0) @@ -549,8 +548,12 @@ def timecorr( ``(sum |w|)**2 / sum w**2`` a timepoint needs over those timepoints, compared with a relative tolerance of 1e-12 (three equal weights are 3 samples); rows below it are NaN too. A number - that no row of the kernel reaches raises ``ValueError`` (a backward - Gaussian of variance 25 has at most 9.4 effective samples). With + that a built-in kernel cannot reach with any number of earlier + timepoints raises ``ValueError`` (a backward Gaussian of variance + 25 has at most 9.4 effective samples), whatever the length of the + data; the rows of a short recording that do not reach a number the + kernel can reach are NaN, as are all rows when a kernel function + of your own never reaches it. With ``cfun=None`` a value is NaN when its feature has no weighted sample, or fewer effective samples than the number. Features with zero variance still give correlations of 0. Keyword only. @@ -603,7 +606,7 @@ def timecorr( raised by ``segment`` for features entries of ``events``. With ``causal=True``, for the arguments listed under ``causal`` that have no causal form, and for a ``min_samples`` that is not None or a - finite number >= 1, or that no row of the kernel reaches; for + finite number >= 1, or that a built-in kernel cannot reach; for ``min_samples`` given without ``causal=True``. NotImplementedError With ``causal=True``, for an ``rfun`` that is fitted to data. From 581154115768f9227e53c2560347aebb4aff0682 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 11:22:40 -0500 Subject: [PATCH 04/26] Causal estimator: a row's arithmetic does not depend on later rows; every 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 132 ++++++++++++++++++ timecorr/helpers.py | 242 +++++++++++++++++++++++---------- 2 files changed, 300 insertions(+), 74 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index c60050ad..6da2d120 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -795,3 +795,135 @@ def test_new_arguments_are_keyword_only(): tc.isfc(X, w, True) with pytest.raises(TypeError): tc.wisfc(X, w, 1.0, True) + + +# ---------------------------------------------------------------------------- +# the arithmetic of row t does not depend on later rows +# ---------------------------------------------------------------------------- + + +def _level_step(where, seed=0, n=120, K=3, step=1e4): + """Rows before ``where`` (at least the first) near 0, the others near ``step``.""" + x = np.random.default_rng(seed).normal(size=(n, K)) + if where == 0: + x[0] = 0 + x[1:] += step + else: + x[where:] += step + return x + + +# Removing later rows changes the shapes of the estimator's sums, so their +# round-off: an entry then moves by about eps times its condition number, +# (distance of the samples from the centering reference of the chunk of +# kernel rows / their spread)**2. After a step of 1e4 standard deviations +# inside a chunk that is 1e8 eps (measured: up to 1.6e-7); after a step of +# 100, 1e4 eps (measured: 2.5e-11). Replacing later rows changes no shape and no bit. +REMOVE_ATOL = {1e2: ATOL, 1e4: 1e-6} + + +def test_a_later_nan_does_not_change_an_ill_conditioned_row(): + # the case that showed two arithmetic paths: a chunk of kernel rows took + # the path for NaN samples when any of its rows had one + x = _level_step(0) + y = x.copy() + y[100:] = np.nan + w = tc.gaussian_weights(120, {"var": 25}, direction="backward") + a = _quiet(tc.wcorr, x, x, w, causal=True) + b = _quiet(tc.wcorr, y, y, w, causal=True) + assert np.array_equal(a[:, :, :100], b[:, :, :100], equal_nan=True) + # without the diagonal, row 40 as NaN changes no row up to 40 + y = x.copy() + y[40] = np.nan + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}, + include_zero=False) + assert np.array_equal(_quiet(tc.timecorr, x, **kw)[:41], + _quiet(tc.timecorr, y, **kw)[:41], equal_nan=True) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("where", [0, 60, 150]) +@pytest.mark.parametrize("case", ["autofc", "isfc-null", "wisfc-corrmean", "smooth"]) +@pytest.mark.parametrize("missing", [False, True]) +@pytest.mark.parametrize("step", [1e2, 1e4]) +def test_rows_of_a_level_step_do_not_depend_on_later_rows(case, where, include_zero, + mode, missing, step): + data = [_level_step(where, seed=s, n=T, K=4, step=step) + for s in range(CASES[case][1])] + if missing: + for s, x in enumerate(data): + x[np.random.default_rng(50 + s).random(x.shape) < 0.01] = np.nan + full = _call(data, case, "gaussian", include_zero) + rng = np.random.default_rng(31) + for n in (1, 2, 3, 40, 61, 100, 127, 128, 129, 151, 200, 257, 299): + part = _call([_perturb(x, n, mode, rng) for x in data], case, "gaussian", + include_zero) + rows = n if include_zero or mode == "remove" else n + 1 + if mode == "remove": + worst = _max_difference(full, part, rows) + assert worst <= REMOVE_ATOL[step] + else: + # replacement changes no bit of an earlier row + for f, p in zip(_as_list(full), _as_list(part)): + assert np.array_equal(np.asarray(f)[:rows], np.asarray(p)[:rows], + equal_nan=True) + + +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_replacing_later_rows_with_nan_or_inf_changes_no_bit(case, include_zero, kernel): + data = _subjects(CASES[case][1]) + full = _call(data, case, kernel, include_zero) + rng = np.random.default_rng(19) + for mode in ("nan", "inf"): + for n in CUTS: + part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, + include_zero) + rows = n if include_zero else n + 1 + for f, p in zip(_as_list(full), _as_list(part)): + assert np.array_equal(np.asarray(f)[:rows], np.asarray(p)[:rows], + equal_nan=True) + + +# ---------------------------------------------------------------------------- +# every prefix of a series runs +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("kernel", sorted(KERNELS)) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_every_prefix_runs_and_equals_the_first_rows(case, include_zero, kernel): + data = _subjects(CASES[case][1], seed=60) + full = _call(data, case, kernel, include_zero) + for n in list(range(1, 13)) + [40, 128, 129, 200]: + part = _call([x[:n] for x in data], case, kernel, include_zero) + assert all(np.asarray(p).shape[0] == n for p in _as_list(part)) + assert _max_difference(full, part, n) <= ATOL + one = _as_list(_call([x[:1] for x in data], case, kernel, include_zero)) + if CASES[case][0] is not None: + assert all(np.isnan(p).all() for p in one) + + +def test_one_row_of_a_wide_kernel_is_not_a_delta_kernel(): + x = np.random.default_rng(70).standard_normal((30, 3)) + # as arrays and through the correlation functions + for n in (1, 2, 3): + w = tc.gaussian_weights(n, {"var": 25}, direction="backward") + assert np.isnan(_quiet(tc.wcorr, x[:n], x[:n], w, causal=True)[:, :, :2]).all() + assert np.isnan(_quiet(tc.autofc, x[:n], w, causal=True)[:2]).all() + assert np.isnan(_quiet(tc.isfc, [x[:n], x[:n] + 1], w, causal=True)[0][:2]).all() + w0 = tc.gaussian_weights(n, {"var": 25}, direction="backward", + include_zero=False) + assert np.isnan(_quiet(tc.wcorr, x[:n], x[:n], w0, causal=True)).all() + # kernels that are delta kernels at every length still raise + with pytest.raises(ValueError, match="delta"): + tc.timecorr(x, causal=True, cfun=tc.autofc, weights_function=tc.boxcar_weights, + weights_params={"width": 1}) + with pytest.raises(ValueError, match="delta"): + tc.timecorr(x[:1], causal=True, cfun=tc.autofc, + weights_function=tc.boxcar_weights, weights_params={"width": 1}) + with pytest.raises(ValueError, match="delta"): + tc.wcorr(x[:2], x[:2], np.eye(2), causal=True) diff --git a/timecorr/helpers.py b/timecorr/helpers.py index c5f3f2ab..ceedb89d 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -1203,14 +1203,14 @@ def _delta_wcorr(a, b, rows): return np.einsum("ti,tj->ijt", za, zb) -def _wcorr_inputs(a, b, weights): +def _wcorr_inputs(a, b, weights, causal=False): """ The estimator's inputs: ``a`` and ``b`` as float (T, K) matrices and the kernel as a ``_KernelRows`` (NaN weights count as 0). Returns ``(a, b, rows)``. Raises ``ValueError`` if the shapes do not match (T rows in ``a`` and - ``b``, T columns in ``weights``) or if every row of the kernel is zero. + ``b``, T columns in ``weights``) or, unless ``causal``, if every row of the kernel is zero. """ a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) @@ -1225,7 +1225,9 @@ def _wcorr_inputs(a, b, weights): f"must have T columns; got a {a.shape}, b {b.shape}, weights {rows.shape}." ) - if np.all(rows.support == 0): + # (the causal estimator returns rows without weight as NaN: a series of + # one timepoint has such a kernel when the diagonal is left out) + if np.all(rows.support == 0) and not causal: raise ValueError( "Every row of the kernel is zero; no correlation can be estimated." ) @@ -1588,8 +1590,20 @@ def _check_causal_kernel(weights, what="the kernel"): def _check_causal_rows(rows): - """The checks of a causal call on its kernel (a ``_KernelRows``).""" - if np.all(rows.support == 1): + """ + The checks of a causal call on its kernel (a ``_KernelRows``). + + A delta kernel is one with a single non-zero weight in every row at any + length of the series. The one row of a series of one timepoint has a + single weight whatever the kernel: it is a delta kernel only when the + kernel's lag profile says so (``_kernel_reach`` of at most 1), so a + prefix of a series is never refused where the series is not. + """ + delta = bool(rows.support.size) and bool(np.all(rows.support == 1)) + if delta and rows.shape[0] == 1: + reach = _kernel_reach(rows.kernel) + delta = reach is not None and reach <= 1 + _MIN_SAMPLES_RTOL + if delta: raise ValueError( "causal=True: a delta kernel (one non-zero weight in every row, as " "eye_weights gives) yields co-fluctuations of series z-scored over " @@ -1656,6 +1670,29 @@ def _causal_defined(kernel, observed, min_samples, min_count=3): return defined +# The causal estimator also counts a kernel-weighted standard deviation below +# this fraction of the magnitude of the kernel-weighted mean as zero: a column +# that is constant up to the round-off of the computation that produced it +# (an output of an earlier order; such columns are not set to their mean in +# causal mode, which would read later rows). +_CAUSAL_CONSTANT = 1e-9 + + +def _causal_zero_variance(var, msq, s, mean): + """ + The zero-variance rule of the causal estimator: ``_zero_variance`` (with + ``msq`` the kernel-weighted mean square about the chunk's reference), or + a kernel-weighted standard deviation ``sqrt(var / s)`` below + ``_CAUSAL_CONSTANT`` times ``|mean|``, the kernel-weighted mean of the + raw column. Every quantity is a kernel-weighted sum of the row, so the + rule reads no later sample. + """ + sd = np.sqrt(np.maximum(var, 0.0)) + return _zero_variance(var, msq, s, mean) | ( + sd < _CAUSAL_CONSTANT * np.sqrt(s) * np.abs(mean) + ) + + def _causal_reference(x, c0, t0, c1): """ The centering reference of the columns of ``x`` for a chunk of kernel @@ -1684,7 +1721,9 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): ``_wcorr_setup`` for the causal estimator (``a`` and ``b`` from ``_causal_clean``, the kernel checked by ``_check_causal_rows``). - Nothing computed for a kernel row uses a sample after the row: + Nothing computed for a kernel row uses a sample after the row, and the + floating-point operations that give a row do not depend on the samples + it does not weight: - the undefined rows (``_causal_defined``, from the timepoints where both ``a`` and ``b`` have a sample) are set to 0 here and to NaN in the @@ -1693,9 +1732,14 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): has weight, whatever fraction of the kernel they cover; - each chunk centers the data on its own reference (``_causal_reference``), and the zero-variance rule compares a - variance with the kernel-weighted mean square about that reference; - - a chunk takes the path for NaN samples when its columns hold one, so - samples outside its columns do not choose the path. + variance with the kernel-weighted mean square about that reference + and with the kernel-weighted mean (``_causal_zero_variance``); + - a row is computed with the sums for complete data exactly when no + timepoint it weights has a NaN sample (``"plain"``), and with the + pairwise sums otherwise. NaN samples are set to 0 after centering, so + the sums for complete data of such a row hold only exact zeros from + the timepoints it does not weight: a NaN (or any other value) after a + row changes no bit of the row. Returns a dict with ``"causal": True`` for ``_wcorr_block``. """ @@ -1708,14 +1752,19 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): ) rows.zero_rows(~defined) rows.prepare(True, always=True) - # rows with a NaN sample before each row, to ask whether a span has one - nan_before = np.concatenate([[0], np.cumsum(nan_a.any(axis=1) | nan_b.any(axis=1))]) + # the timepoints with a NaN sample, and their number before each row + with_nan = (nan_a.any(axis=1) | nan_b.any(axis=1)).astype(np.float64) + nan_before = np.concatenate([[0], np.cumsum(with_nan)]) del nan_a, nan_b n = len(rows.spans) state = { "causal": True, "T": a.shape[0], "rows": rows, "a": a, "b": b, "defined": defined, + # chunks whose columns hold a NaN sample; chunks with a row that + # weights one; the rows that weight none + "dirty": np.zeros(n, dtype=bool), "nan": np.zeros(n, dtype=bool), + "plain": np.ones(T_out, dtype=bool), "ref_a": np.zeros((n, Ka)), "sw": np.zeros((T_out, 1)), "ma": np.zeros((T_out, Ka)), "wa": np.zeros((T_out, Ka)), @@ -1732,12 +1781,14 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): }) active = np.zeros(T_out, dtype=bool) - def moments(x, ref, A, W, s, t0, t1, side): + def moments(x, ref, dirty, A, W, s, t0, t1, side): x = x - ref + if dirty: + x[np.isnan(x)] = 0 mean = _safe_divide(A @ x, s) msq = A @ x**2 var = msq - s * mean**2 - zero = _zero_variance(var, msq, s, mean + ref) + zero = _causal_zero_variance(var, msq, s, mean + ref) state["m" + side][t0:t1] = mean state["w" + side][t0:t1] = W @ x state["v" + side][t0:t1] = np.where(zero, 0.0, var) @@ -1749,27 +1800,78 @@ def moments(x, ref, A, W, s, t0, t1, side): A = rows._block(i, "a") s = A.sum(axis=1)[:, np.newaxis] active[t0:t1] = s[:, 0] > 0 - state["nan"][i] = nan_before[c1] > nan_before[c0] + dirty = state["dirty"][i] = nan_before[c1] > nan_before[c0] + if dirty: + plain = (rows._block(i, "s") @ with_nan[c0:c1]) == 0 + state["plain"][t0:t1] = plain + state["nan"][i] = not plain.all() state["ref_a"][i] = _causal_reference(a, c0, t0, c1) if not autocorrelation: state["ref_b"][i] = _causal_reference(b, c0, t0, c1) - if not state["nan"][i]: - W = rows._block(i, "w") - state["sw"][t0:t1, 0] = W.sum(axis=1) - moments(a[c0:c1], state["ref_a"][i], A, W, s, t0, t1, "a") - if not autocorrelation: - moments(b[c0:c1], state["ref_b"][i], A, W, s, t0, t1, "b") + W = rows._block(i, "w") + state["sw"][t0:t1, 0] = W.sum(axis=1) + moments(a[c0:c1], state["ref_a"][i], dirty, A, W, s, t0, t1, "a") + if not autocorrelation: + moments(b[c0:c1], state["ref_b"][i], dirty, A, W, s, t0, t1, "b") state["active"] = active - state["has_nan"] = bool(state["nan"].any()) - state["n_products"] = _WCORR_NAN_PRODUCTS if state["has_nan"] else 1 + # the sums for complete data set the block size; the pairwise sums of + # the rows that need them are computed in blocks of their own + # (``_causal_block``), so the blocks of the first do not depend on + # whether the data hold NaN samples + state["n_products"] = 1 return state +def _causal_pairwise(state, i, xa, ok_a, xb, ok_b, ref_a, ref_b): + """ + The pairwise sums of chunk ``i`` of the causal estimator for the + centered, zero-filled columns ``xa`` and ``xb`` (``ok_a``, ``ok_b``: + their observed samples): ``(r, undefined, zero, few)``, each of shape + (rows of the chunk, columns of ``xa``, columns of ``xb``). + """ + rows = state["rows"] + t0, t1, c0, c1 = rows.spans[i] + L = c1 - c0 + sub = (t1 - t0, xa.shape[1], xb.shape[1]) + A = rows._block(i, "a") + W = rows._block(i, "w") + pair_ok = ok_a[:, :, np.newaxis] & ok_b[:, np.newaxis, :] + x = xa[:, :, np.newaxis] * pair_ok + y = xb[:, np.newaxis, :] * pair_ok + m = x[0].size + terms = np.concatenate( + [t.reshape(L, -1) for t in (pair_ok.astype(float), x, y, x**2, y**2)], + axis=1, + ) + s0, sx, sy, sxx, syy = np.split(A @ terms, 5, axis=1) + w0, wx, wy = np.split(W @ terms[:, : 3 * m], 3, axis=1) + wxy = W @ (x * y).reshape(L, -1) + mx = _safe_divide(sx, s0) + my = _safe_divide(sy, s0) + num = (wxy - mx * wy - my * wx + mx * my * w0).reshape(sub) + var_a = sxx - s0 * mx**2 + var_b = syy - s0 * my**2 + pairs = sub[1:] + ca = np.broadcast_to(ref_a[:, np.newaxis], pairs).reshape(-1) + cb = np.broadcast_to(ref_b[np.newaxis, :], pairs).reshape(-1) + zero = _causal_zero_variance(var_a, sxx, s0, mx + ca) | ( + _causal_zero_variance(var_b, syy, s0, my + cb) + ) + var_a, var_b, zero = (v.reshape(sub) for v in (var_a, var_b, zero)) + # two samples always give r = +-1: fewer than 3 is undefined + few = (rows._block(i, "s") @ terms[:, :m]).reshape(sub) < 3 + und = zero | few + return _correlation_ratio(num, var_a, var_b, und, sub), und, zero, few + + def _causal_block(state, i0, i1, j0): """ ``_wcorr_block`` for the causal estimator (``state`` from ``_causal_setup``): the same sums, a chunk of kernel rows at a time, - each over its own columns and about its own centering reference. + each over its own columns and about its own centering reference. Every + chunk computes the sums for complete data, on the data with NaN samples + set to 0; a chunk with rows that weight a NaN sample also computes the + pairwise sums, which those rows take. """ rows = state["rows"] a, b = state["a"], state["b"] @@ -1778,6 +1880,8 @@ def _causal_block(state, i0, i1, j0): undefined = np.ones(shape, dtype=bool) zero_all = np.ones(shape[0], dtype=bool) few_any = np.zeros(shape[0], dtype=bool) + # rows of ``a`` per block of pairwise sums + step = _wcorr_block_rows(state["T"], shape[2], _WCORR_NAN_PRODUCTS) for i, (t0, t1, c0, c1) in enumerate(rows.spans): if c1 <= c0: continue @@ -1787,58 +1891,48 @@ def _causal_block(state, i0, i1, j0): ref_b = state["ref_b"][i, j0:] xa = a[c0:c1, i0:i1] - ref_a xb = b[c0:c1, j0:] - ref_b - W = rows._block(i, "w") - if not state["nan"][i]: - prod = (xa[:, :, np.newaxis] * xb[:, np.newaxis, :]).reshape(L, -1) - cross = (W @ prod).reshape(sub) - del prod - ma_i = state["ma"][t0:t1, i0:i1, np.newaxis] - mb_j = state["mb"][t0:t1, np.newaxis, j0:] - num = ( - cross - - ma_i * state["wb"][t0:t1, np.newaxis, j0:] - - mb_j * state["wa"][t0:t1, i0:i1, np.newaxis] - + ma_i * mb_j * state["sw"][t0:t1, :, np.newaxis] - ) - var_a = state["va"][t0:t1, i0:i1, np.newaxis] - var_b = state["vb"][t0:t1, np.newaxis, j0:] - zero = (state["za"][t0:t1, i0:i1, np.newaxis] - | state["zb"][t0:t1, np.newaxis, j0:]) - und = zero - else: - A = rows._block(i, "a") + if state["dirty"][i]: ok_a = ~np.isnan(xa) ok_b = ~np.isnan(xb) - pair_ok = ok_a[:, :, np.newaxis] & ok_b[:, np.newaxis, :] - x = np.where(ok_a, xa, 0.0)[:, :, np.newaxis] * pair_ok - y = np.where(ok_b, xb, 0.0)[:, np.newaxis, :] * pair_ok - m = x[0].size - terms = np.concatenate( - [t.reshape(L, -1) for t in (pair_ok.astype(float), x, y, x**2, y**2)], - axis=1, - ) - s0, sx, sy, sxx, syy = np.split(A @ terms, 5, axis=1) - w0, wx, wy = np.split(W @ terms[:, : 3 * m], 3, axis=1) - wxy = W @ (x * y).reshape(L, -1) - mx = _safe_divide(sx, s0) - my = _safe_divide(sy, s0) - num = (wxy - mx * wy - my * wx + mx * my * w0).reshape(sub) - var_a = sxx - s0 * mx**2 - var_b = syy - s0 * my**2 - pairs = sub[1:] - ca = np.broadcast_to(ref_a[:, np.newaxis], pairs).reshape(-1) - cb = np.broadcast_to(ref_b[np.newaxis, :], pairs).reshape(-1) - zero = _zero_variance(var_a, sxx, s0, mx + ca) | _zero_variance( - var_b, syy, s0, my + cb - ) - var_a, var_b, zero = (v.reshape(sub) for v in (var_a, var_b, zero)) - # two samples always give r = +-1: fewer than 3 is undefined - few = (rows._block(i, "s") @ terms[:, :m]).reshape(sub) < 3 - del terms + xa[~ok_a] = 0 + xb[~ok_b] = 0 + W = rows._block(i, "w") + prod = (xa[:, :, np.newaxis] * xb[:, np.newaxis, :]).reshape(L, -1) + cross = (W @ prod).reshape(sub) + del prod + ma_i = state["ma"][t0:t1, i0:i1, np.newaxis] + mb_j = state["mb"][t0:t1, np.newaxis, j0:] + num = ( + cross + - ma_i * state["wb"][t0:t1, np.newaxis, j0:] + - mb_j * state["wa"][t0:t1, i0:i1, np.newaxis] + + ma_i * mb_j * state["sw"][t0:t1, :, np.newaxis] + ) + var_a = state["va"][t0:t1, i0:i1, np.newaxis] + var_b = state["vb"][t0:t1, np.newaxis, j0:] + zero = (state["za"][t0:t1, i0:i1, np.newaxis] + | state["zb"][t0:t1, np.newaxis, j0:]) + r_chunk = _correlation_ratio(num, var_a, var_b, zero, sub) + und = zero + if state["nan"][i]: + # the rows that weight a NaN sample take the pairwise sums + need = ~state["plain"][t0:t1] + und = zero.copy() + zero = zero.copy() + few = np.zeros(sub, dtype=bool) + for k0 in range(0, sub[1], step): + k1 = min(sub[1], k0 + step) + pr, pu, pz, pf = _causal_pairwise( + state, i, xa[:, k0:k1], ok_a[:, k0:k1], xb, ok_b, + ref_a[k0:k1], ref_b, + ) + r_chunk[need, k0:k1] = pr[need] + und[need, k0:k1] = pu[need] + zero[need, k0:k1] = pz[need] + few[need, k0:k1] = pf[need] few_any[t0:t1] = few.reshape(sub[0], -1).any(axis=1) - und = zero | few zero_all[t0:t1] = zero.reshape(sub[0], -1).all(axis=1) - r[t0:t1] = _correlation_ratio(num, var_a, var_b, und, sub) + r[t0:t1] = r_chunk undefined[t0:t1] = und return r, undefined, zero_all, few_any @@ -1946,7 +2040,7 @@ def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None, *, ``a`` and ``b`` differ in shape. """ same = a is b - a, b, rows = _wcorr_inputs(a, b, weights) + a, b, rows = _wcorr_inputs(a, b, weights, causal) if causal: min_samples = _check_min_samples(min_samples, True) _check_causal_rows(rows) @@ -1962,7 +2056,7 @@ def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None, *, T, Ka = a.shape Kb = b.shape[1] - if np.all(rows.support == 1): + if np.all(rows.support == 1) and not causal: za, zb = _delta_zscores(a, b, rows) step = int(rows_per_block or _wcorr_block_rows(T, Kb)) @@ -2212,7 +2306,7 @@ def _wcorr(a, b, weights, warn=True, return_cancelled=False, causal=False, read every timepoint). """ same = a is b - a, b, rows = _wcorr_inputs(a, b, weights) + a, b, rows = _wcorr_inputs(a, b, weights, causal) if causal: min_samples = _check_min_samples(min_samples, True) _check_causal_rows(rows) From c8cb365957264977f80d96c255e3d1e561fc7185 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 12:01:44 -0500 Subject: [PATCH 05/26] features, two_path_step: causal= and min_samples= for reducers that need 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 25 +- tests/test_causal_features.py | 716 +++++++++++++++++++++++++++++++++ timecorr/helpers.py | 317 ++++++++++----- timecorr/higher_order.py | 477 ++++++++++++++++++++-- 4 files changed, 1379 insertions(+), 156 deletions(-) create mode 100644 tests/test_causal_features.py diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 6da2d120..9b2424c4 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -156,6 +156,12 @@ def test_rows_do_not_depend_on_later_rows_with_min_samples(case, include_zero, k part = _call([_perturb(x, n, mode, rng) for x in data], case, kernel, include_zero, min_samples=min_samples) assert _max_difference(full, part, n) <= ATOL + if mode != "remove": + # (rows a later NaN leaves undefined do not change the columns, + # and so the sums, of the chunk of kernel rows they are in) + for f, p in zip(_as_list(full), _as_list(part)): + assert np.array_equal(np.asarray(f)[:n], np.asarray(p)[:n], + equal_nan=True) @pytest.mark.parametrize("missing", [0, 0.002]) @@ -813,13 +819,11 @@ def _level_step(where, seed=0, n=120, K=3, step=1e4): return x -# Removing later rows changes the shapes of the estimator's sums, so their -# round-off: an entry then moves by about eps times its condition number, -# (distance of the samples from the centering reference of the chunk of -# kernel rows / their spread)**2. After a step of 1e4 standard deviations -# inside a chunk that is 1e8 eps (measured: up to 1.6e-7); after a step of -# 100, 1e4 eps (measured: 2.5e-11). Replacing later rows changes no shape and no bit. -REMOVE_ATOL = {1e2: ATOL, 1e4: 1e-6} +# The estimator centers the data anew for every group of 16 kernel rows, on +# the kernel-weighted mean at the group's first row, so rows long after a +# step are as well conditioned as rows before it (centered once per chunk of +# 128 rows, removing later rows moved a row after a step of 1e4 standard +# deviations by up to 1.6e-7; now at most 6e-13 up to steps of 1e8). def test_a_later_nan_does_not_change_an_ill_conditioned_row(): @@ -846,7 +850,7 @@ def test_a_later_nan_does_not_change_an_ill_conditioned_row(): @pytest.mark.parametrize("where", [0, 60, 150]) @pytest.mark.parametrize("case", ["autofc", "isfc-null", "wisfc-corrmean", "smooth"]) @pytest.mark.parametrize("missing", [False, True]) -@pytest.mark.parametrize("step", [1e2, 1e4]) +@pytest.mark.parametrize("step", [1e4, 1e8]) def test_rows_of_a_level_step_do_not_depend_on_later_rows(case, where, include_zero, mode, missing, step): data = [_level_step(where, seed=s, n=T, K=4, step=step) @@ -861,8 +865,9 @@ def test_rows_of_a_level_step_do_not_depend_on_later_rows(case, where, include_z include_zero) rows = n if include_zero or mode == "remove" else n + 1 if mode == "remove": - worst = _max_difference(full, part, rows) - assert worst <= REMOVE_ATOL[step] + # (smoothed values are as large as the step: a few of their ulps) + atol = max(ATOL, 8 * np.spacing(step)) if case == "smooth" else ATOL + assert _max_difference(full, part, rows) <= atol else: # replacement changes no bit of an earlier row for f, p in zip(_as_list(full), _as_list(part)): diff --git a/tests/test_causal_features.py b/tests/test_causal_features.py new file mode 100644 index 00000000..25efa30d --- /dev/null +++ b/tests/test_causal_features.py @@ -0,0 +1,716 @@ +""" +``causal=True`` in ``features`` and ``two_path_step``, with reducers that +need no fit (None and graph measures). + +The guarantee: row t of every ``X[k]`` and ``D[k]`` is unchanged (to 1e-9, +NaN rows included) when the input rows after t are replaced by other finite +values, by NaN, by inf, or removed; with ``include_zero=False`` also when +row t itself changes. Warm-up rows are NaN and are missing data for the +next order, so they accumulate over the orders. Real computations; nothing +is mocked. +""" + +import functools +import time +import warnings + +import numpy as np +import pytest + +import timecorr as tc +from timecorr.higher_order import estimate_memory_gb + +from .test_causal_estimator import ( + SUBJECT_WEIGHTS, + _as_list, + _expected_undefined, + _max_difference, + _perturb, + _quiet, + _series, +) +from .test_estimator_causality import _data as _conditioned_data + +ATOL = 1e-9 +WISFC = functools.partial(tc.wisfc, subject_weights=SUBJECT_WEIGHTS) + + +# ---------------------------------------------------------------------------- +# the estimator's rule for columns that are constant up to round-off +# ---------------------------------------------------------------------------- + + +def _nearly_constant(mean, relative, n=300, seed=0): + rng = np.random.default_rng(seed) + x = rng.standard_normal((n, 4)) + noise = rng.standard_normal(n) + x[:, 1] = mean * (1 + relative * noise) + return x, noise + + +@pytest.mark.parametrize("mean", [1.0, 1e6, -3.0, 2e-5]) +def test_a_column_constant_to_relative_round_off_has_zero_variance(mean): + x, _ = _nearly_constant(mean, 1e-12) + kw = dict(cfun=tc.autofc, weights_params={"var": 25}) + out = _quiet(tc.timecorr, x, causal=True, **kw) + assert np.isnan(out[:2]).all() and not np.isnan(out[2:]).any() + full = tc.vec2mat(out[2:]) + # 0, not correlations of round-off noise; the other features keep theirs + assert np.all(full[1, :, :] == 0) and np.all(full[:, 1, :] == 0) + assert np.all(full[[0, 2, 3], [0, 2, 3], :] == 1) + assert np.all(np.abs(full[0, 2, 5:]) > 0) + # identically when later rows are removed + for n in (3, 40, 128, 129, 257): + part = _quiet(tc.timecorr, x[:n], causal=True, **kw) + assert _max_difference(out, part, n) <= ATOL + assert np.all(tc.vec2mat(part[2:])[1] == 0) + # the rule is the causal estimator's: without causal=True the column's + # round-off noise is correlated like any signal + plain = tc.vec2mat(_quiet(tc.timecorr, x, include_timepoints="backward", **kw)[2:]) + assert np.mean(plain[1, 0, :] != 0) > 0.9 + + +@pytest.mark.parametrize("mean", [1.0, 1e6]) +def test_a_column_with_relative_variation_1e_6_is_not_constant(mean): + x, noise = _nearly_constant(mean, 1e-6) + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}) + out = tc.vec2mat(_quiet(tc.timecorr, x, **kw)[2:]) + # a correlation does not depend on offset and scale: those of the noise + y = x.copy() + y[:, 1] = noise + expected = tc.vec2mat(_quiet(tc.timecorr, y, **kw)[2:]) + assert np.all(out[1, 1, :] == 1) + assert np.mean(out[1, 0, :] != 0) == 1 + assert np.max(np.abs(out - expected)) < 1e-6 + + +def test_the_rule_applies_to_the_next_order_of_features(): + # a feeding column that is constant up to round-off (strength of a node + # whose correlations are all 0 or 1) gives zeros at the next order + x, _ = _nearly_constant(1.0, 1e-12, n=200) + kw = dict(causal=True, cfun=tc.autofc, rfun=None, delta_rfun=None, + weights_params={"var": 25}, delta_weights_params={"var": 25}) + X = _quiet(tc.features, x, order=1, **kw) + full = tc.vec2mat(X[1][2:]) + assert np.all(full[1, :, :] == 0) + for n in (40, 129): + part = _quiet(tc.features, x[:n], order=1, **kw) + assert _max_difference(X[1], part[1], n) <= ATOL + + +# ---------------------------------------------------------------------------- +# the guarantee +# ---------------------------------------------------------------------------- + +T = 300 +CUTS = (3, 40, 128, 129, 200, 299) +PARAMS = dict(weights_params={"var": 25}, delta_weights_params={"var": 16}) +UNREDUCED = dict(rfun=None, delta_rfun=None) +STRENGTH = dict(rfun="strength", delta_rfun="strength") + +# name: (number of subjects, features, highest order, arguments) +CONFIGS = { + "unreduced": (1, 4, 3, dict(cfun=tc.autofc, **UNREDUCED, **PARAMS)), + "strength": (1, 6, 4, dict(cfun=tc.autofc, **STRENGTH, **PARAMS)), + "eigenvector": (1, 6, 3, dict(cfun=tc.autofc, rfun="eigenvector_centrality", + delta_rfun="strength", **PARAMS)), + "mixed": (1, 5, 3, dict(cfun=tc.autofc, rfun={1: None, 2: "strength", 3: None}, + delta_rfun={1: "strength", 2: None, 3: "strength"}, + **PARAMS)), + "laplace": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, + weights_function=tc.laplace_weights, + weights_params={"scale": 6}, + delta_weights_function=tc.laplace_weights, + delta_weights_params={"scale": 4})), + "boxcar": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, + weights_function=tc.boxcar_weights, + weights_params={"width": 30}, + delta_weights_function=tc.boxcar_weights, + delta_weights_params={"width": 16})), + "order-maps": (1, 5, 3, dict( + cfun=tc.autofc, **STRENGTH, + weights_params={1: {"var": 25}, 2: {"var": 49}, 3: {"var": 9}}, + delta_weights_params={1: {"var": 16}, 2: {"var": 36}, 3: {"var": 16}})), + "events": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS, events=[90, 210])), + "events-by-order": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS, + events={1: [150], 3: [60, 100]})), + "min-samples": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS, min_samples=6)), + "isfc": (3, 5, 3, dict(cfun=tc.isfc, **STRENGTH, **PARAMS)), + "isfc-unreduced": (3, 4, 2, dict(cfun=tc.isfc, **UNREDUCED, **PARAMS)), + "isfc-corrmean": (3, 5, 3, dict(cfun=tc.isfc, combine=tc.corrmean_combine, + **STRENGTH, **PARAMS)), + "isfc-mean": (3, 5, 3, dict(cfun=tc.isfc, combine=tc.mean_combine, **STRENGTH, + **PARAMS)), + "isfc-tstat": (3, 4, 2, dict(cfun=tc.isfc, combine=tc.tstat_combine, + **UNREDUCED, **PARAMS)), + "wisfc": (3, 5, 3, dict(cfun=WISFC, **STRENGTH, **PARAMS)), + "wisfc-corrmean": (3, 5, 2, dict(cfun=WISFC, combine=tc.corrmean_combine, + **UNREDUCED, **PARAMS)), + "autofc-subjects": (3, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS)), +} +MODES = ("finite", "nan", "inf", "remove") +# Removing rows changes the shapes of the estimator's last sums and so their +# round-off (replacement changes no shape and no bit). A t statistic over 3 +# subjects divides by their spread, which amplifies it (measured: 7.8e-12). +REMOVE_ATOL = {} + + +def _data(config, seed=0, n=T): + n_subjects, K = CONFIGS[config][:2] + data = [_series(seed + s, n=n, K=K) for s in range(n_subjects)] + return data[0] if n_subjects == 1 else data + + +def _map(data, f): + return [f(x) for x in data] if isinstance(data, list) else f(data) + + +def _within(events, n): + """Boundaries of a series cut to ``n`` rows (the later ones are not in it).""" + if isinstance(events, dict): + return {k: _within(v, n) for k, v in events.items()} + kept = [b for b in events if b < n] + return kept or None + + +def _run(data, config, order=None, **kwargs): + highest, kw = CONFIGS[config][2:] + if "events" in kw: + kw = {**kw, "events": _within(kw["events"], len(_as_list(data)[0]))} + return _quiet(tc.features, data, order=highest if order is None else order, + causal=True, return_delta=True, **{**kw, **kwargs}) + + +def _worst(full, part, rows, orders): + """Largest difference over ``X[k]`` and ``D[k]``, k in ``orders``, rows ``:rows``.""" + return max(_max_difference(f[k], p[k], rows) + for f, p in zip(full, part) for k in orders) + + +def _defined_rows(out): + return int(np.sum(~np.isnan(np.asarray(_as_list(out)[0])).all(axis=1))) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("config", sorted(CONFIGS)) +def test_rows_do_not_depend_on_later_rows(config, include_zero, mode): + data = _data(config) + highest = CONFIGS[config][2] + orders = range(1, highest + 1) + full = _run(data, config, include_zero=include_zero) + assert len(full[0]) == highest + 1 and len(full[1]) == highest + 1 + # the highest order has defined rows before the last cut + assert _defined_rows(full[0][highest]) > T - CUTS[-2] + rng = np.random.default_rng(7) + atol = REMOVE_ATOL.get(config, ATOL) if mode == "remove" else ATOL + for n in CUTS: + part = _run(_map(data, lambda x: _perturb(x, n, mode, rng)), config, + include_zero=include_zero) + # without the diagonal, row n itself may change too + rows = n if include_zero or mode == "remove" else n + 1 + assert _worst(full, part, rows, orders) <= atol + + +@pytest.mark.parametrize("mode", ["finite", "nan", "inf"]) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("config", ["unreduced", "strength", "eigenvector", "isfc", + "wisfc", "events", "min-samples"]) +def test_replacing_later_rows_changes_no_bit(config, include_zero, mode): + data = _data(config, seed=20) + full = _run(data, config, include_zero=include_zero) + rng = np.random.default_rng(8) + for n in CUTS: + part = _run(_map(data, lambda x: _perturb(x, n, mode, rng)), config, + include_zero=include_zero) + rows = n if include_zero else n + 1 + for f, p in zip(full, part): + for fk, pk in zip(f[1:], p[1:]): + for a, b in zip(_as_list(fk), _as_list(pk)): + assert np.array_equal(a[:rows], b[:rows], equal_nan=True) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("include_zero", [True, False]) +def test_order_four_unreduced(include_zero, mode): + # 3 features: 6, 21, 231 and 26,796 columns at orders 1 to 4 + n = 150 + rng = np.random.default_rng(5) + x = rng.standard_normal((n, 3)) + x[:, 0] += 1e3 + x[:, 1] = np.cumsum(x[:, 1]) + x[rng.random(x.shape) < 0.02] = np.nan + kw = dict(order=4, causal=True, cfun=tc.autofc, include_zero=include_zero, + **UNREDUCED, **PARAMS) + full = _quiet(tc.features, x, **kw) + assert [f.shape[1] for f in full] == [3, 6, 21, 231, 26796] + assert _defined_rows(full[4]) > 100 + for cut in (60, 129): + part = _quiet(tc.features, _perturb(x, cut, mode, rng), **kw) + rows = cut if include_zero or mode == "remove" else cut + 1 + assert max(_max_difference(full[k], part[k], rows) for k in range(1, 5)) <= ATOL + + +@pytest.mark.parametrize("config", ["unreduced", "strength", "eigenvector", "laplace", + "boxcar", "isfc", "isfc-corrmean", "wisfc", + "min-samples"]) +@pytest.mark.parametrize("include_zero", [True, False]) +def test_every_prefix_runs_and_equals_the_first_rows(config, include_zero): + data = _data(config, seed=30) + orders = range(1, 4) if CONFIGS[config][2] >= 3 else range(1, 3) + full = _run(data, config, order=orders[-1], include_zero=include_zero) + atol = REMOVE_ATOL.get(config, ATOL) + for n in list(range(1, 13)) + [20, 64, 130, 257]: + part = _run(_map(data, lambda x: x[:n]), config, order=orders[-1], + include_zero=include_zero) + for out in part: + assert all(a.shape[0] == n for k in orders for a in _as_list(out[k])) + assert _worst(full, part, n, orders) <= atol + + +def test_two_path_step(): + x = _series(40, K=5) + kw = dict(causal=True, cfun=tc.autofc, **STRENGTH, **PARAMS) + X, D = _quiet(tc.features, x, order=2, return_delta=True, **kw) + X1, D1 = _quiet(tc.two_path_step, x, **kw) + assert np.array_equal(X1, X[1], equal_nan=True) + assert np.array_equal(D1, D[1], equal_nan=True) + X2, D2 = _quiet(tc.two_path_step, D1, order=2, **kw) + assert np.array_equal(X2, X[2], equal_nan=True) + assert np.array_equal(D2, D[2], equal_nan=True) + assert np.isnan(X2[:4]).all() and not np.isnan(X2[4:]).any() + # rows do not depend on later rows, with min_samples too + rng = np.random.default_rng(41) + full = _quiet(tc.two_path_step, x, min_samples=5, **kw) + assert 5 < _defined_rows(full[0]) < T - 2 + for mode in MODES: + for n in (3, 129, 200): + part = _quiet(tc.two_path_step, _perturb(x, n, mode, rng), min_samples=5, + **kw) + assert max(_max_difference(f, p, n) for f, p in zip(full, part)) <= ATOL + # list input + X1s, D1s = _quiet(tc.two_path_step, [x, x[::-1].copy()], **kw) + assert len(X1s) == 2 and len(D1s) == 2 + assert np.array_equal(D1s[0], D1, equal_nan=True) + + +# ---------------------------------------------------------------------------- +# warm-up rows accumulate over the orders +# ---------------------------------------------------------------------------- + + +def _kernel(function, params, n, include_zero, boundaries=()): + w = function(n, params, direction="backward", include_zero=include_zero) + block = np.searchsorted(np.asarray(boundaries), np.arange(n), side="right") + return w * (block[:, np.newaxis] == block[np.newaxis, :]) + + +@pytest.mark.parametrize("config", ["unreduced", "strength", "laplace", "boxcar", + "order-maps", "events", "events-by-order", "isfc", + "isfc-corrmean", "wisfc", "autofc-subjects"]) +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("min_samples", [None, 3, 4.5]) +def test_warm_up_rows_accumulate_over_the_orders(config, include_zero, min_samples): + data = _data(config, seed=50) + highest, kw = CONFIGS[config][2:] + (X, D), info = _run(data, config, include_zero=include_zero, + min_samples=min_samples, return_info=True) + analysis = kw.get("weights_function", tc.gaussian_weights) + feeding = kw.get("delta_weights_function", tc.gaussian_weights) + events = kw.get("events") + observed = np.ones(T) # no row of the data is missing altogether + for k in range(1, highest + 1): + boundaries = events.get(k, ()) if isinstance(events, dict) else (events or ()) + params = [kw[name][k] if 1 in kw[name] else kw[name] + for name in ("weights_params", "delta_weights_params")] + expected = [ + _expected_undefined(_kernel(f, p, T, include_zero, boundaries), observed, + min_samples) + for f, p in zip((analysis, feeding), params) + ] + for out, exp, path in zip((X[k], D[k]), expected, ("analysis", "feeding")): + for a in _as_list(out): + assert np.array_equal(np.isnan(a).all(axis=1), exp) + assert not np.isnan(a[~exp]).any() + entry = [e for e in info if e["order"] == k and e["path"] == path][0] + count = int(exp.sum()) + if isinstance(out, list): + assert entry["warmup_rows"] == [count] * len(out) + else: + assert entry["warmup_rows"] == count + assert entry["weights_params"] == params[path == "feeding"] + # the next order reads the feeding features: their NaN rows are missing + observed = (~expected[1]).astype(float) + counts = [e["warmup_rows"] for e in info if e["path"] == "analysis"] + counts = [c[0] if isinstance(c, list) else c for c in counts] + assert counts[0] >= (2 if include_zero else 3) + if not isinstance(events, dict) and 1 not in kw["weights_params"]: + # the same kernels and events at every order: more undefined rows at each + assert all(b > a for a, b in zip(counts, counts[1:])) + + +def test_missing_rows_of_the_data_are_missing_at_every_order(): + x = _series(60, K=5) + x[100:112] = np.nan + kw = dict(causal=True, cfun=tc.autofc, return_delta=True, **STRENGTH, **PARAMS) + X, D = _quiet(tc.features, x, order=2, min_samples=4, **kw) + observed = (~np.isnan(x)).any(axis=1).astype(float) + wa = _kernel(tc.gaussian_weights, {"var": 25}, T, True) + wf = _kernel(tc.gaussian_weights, {"var": 16}, T, True) + assert np.array_equal(np.isnan(X[1]).all(axis=1), _expected_undefined(wa, observed, 4)) + d1 = _expected_undefined(wf, observed, 4) + assert np.array_equal(np.isnan(D[1]).all(axis=1), d1) + # the first missing rows still have 4 effective samples before them + assert not d1[100] and d1[106:112].all() and not d1[130:].any() + x2 = _expected_undefined(wa, (~d1).astype(float), 4) + assert np.array_equal(np.isnan(X[2]).all(axis=1), x2) + assert np.flatnonzero(~x2)[0] > np.flatnonzero(~d1)[0] + + +# ---------------------------------------------------------------------------- +# agreement with causal=False +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("reducers", ["unreduced", "strength", "eigenvector"]) +@pytest.mark.parametrize("cfun", ["autofc", "isfc"]) +def test_agrees_with_backward_kernels_of_causal_false(reducers, cfun): + # boxcar kernels over the lags 0..14 (analysis) and 0..7 (feeding). + # causal=False returns undefined rows as rows of 0 and reads them as data + # at the next order, where causal=True reads them as missing: the two + # agree on the rows that weight none of them, at any order before + subjects = [_conditioned_data(seed=s)[:, :4] for s in range(3)] + n = subjects[0].shape[0] + kw = dict(order=3, cfun={"autofc": tc.autofc, "isfc": tc.isfc}[cfun], + return_delta=True, + weights_function=tc.boxcar_weights, weights_params={"width": 30}, + delta_weights_function=tc.boxcar_weights, + delta_weights_params={"width": 16}, + **{"unreduced": UNREDUCED, "strength": STRENGTH, + "eigenvector": dict(rfun="eigenvector_centrality", + delta_rfun="strength")}[reducers]) + causal = _quiet(tc.features, subjects, causal=True, **kw) + plain = _quiet(tc.features, subjects, include_timepoints="backward", **kw) + clean = 0 # the feeding features of the previous order agree from this row on + for k in range(1, 4): + starts = (max(2, clean + 14), max(2, clean + 7)) + for c_out, p_out, start in zip(causal, plain, starts): + for c, p in zip(c_out[k], p_out[k]): + assert c.shape == p.shape + assert not np.isnan(c[start:]).any() + assert np.max(np.abs(c[start:] - p[start:])) <= ATOL + clean = starts[1] + assert starts[0] < n // 4 + + +# ---------------------------------------------------------------------------- +# return_info, constant columns, memory +# ---------------------------------------------------------------------------- + + +def test_return_info_of_a_causal_call(): + x = _series(70, K=5) + (X, D), info = _quiet( + tc.features, x, order=2, causal=True, cfun=tc.autofc, return_delta=True, + return_info=True, **STRENGTH, + weights_params={1: {"var": 25}, 2: {"var": 49}}, + delta_weights_params={"var": 16}) + assert [(e["order"], e["path"]) for e in info] == [ + (1, "analysis"), (1, "feeding"), (2, "analysis"), (2, "feeding")] + assert [e["weights_params"] for e in info] == [ + {"var": 25}, {"var": 16}, {"var": 49}, {"var": 16}] + assert [e["warmup_rows"] for e in info] == [2, 2, 4, 4] + assert all(type(e["warmup_rows"]) is int for e in info) + for e in info: + out = (X if e["path"] == "analysis" else D)[e["order"]] + assert e["warmup_rows"] == int(np.isnan(out).all(axis=1).sum()) + assert e["requested"] == "strength" and e["effective"] == "strength" + # the dicts are copies: changing them does not change the caller's + info[0]["weights_params"]["var"] = 1 + # without return_delta the last feeding step is not computed + _, info = _quiet(tc.features, [x, x + 1], order=1, causal=True, return_info=True, + **UNREDUCED, **PARAMS) + assert len(info) == 1 and info[0]["warmup_rows"] == [2, 2] + + +def test_constant_columns_ignore_the_warm_up_rows(): + rng = np.random.default_rng(71) + x = rng.standard_normal((120, 5)) + x[:, 2] = 4.0 # zero variance: correlations 0, strength 0 at every defined row + (X, D), info = _quiet(tc.features, x, order=2, causal=True, cfun=tc.autofc, + return_delta=True, return_info=True, **STRENGTH, **PARAMS) + for e in info: + out = (X if e["path"] == "analysis" else D)[e["order"]] + defined = ~np.isnan(out).all(axis=1) + assert 0 < (~defined).sum() < 10 + expected = np.flatnonzero(np.ptp(out[defined], axis=0) == 0).tolist() + assert e["constant_columns"] == expected + assert 2 in expected + # an output without a defined row has no constant column + _, info = _quiet(tc.features, x[:2], order=1, causal=True, cfun=tc.autofc, + return_info=True, **STRENGTH, **PARAMS) + assert info[0]["constant_columns"] == [] and info[0]["warmup_rows"] == 2 + + +def test_info_of_calls_without_causal_is_unchanged(): + x = np.random.default_rng(72).standard_normal((80, 4)) + _, info = _quiet(tc.features, x, order=1, rfun=None, delta_rfun=None, + return_info=True, **PARAMS) + assert set(info[0]) == {"order", "path", "requested", "effective", "input_width", + "output_width", "constant_columns"} + + +def test_memory_limit_applies(): + x = np.random.default_rng(73).standard_normal((400, 30)) + kw = dict(order=2, causal=True, cfun=tc.autofc, **PARAMS) + with pytest.raises(MemoryError, match="max_memory_gb"): + tc.features(x, max_memory_gb=0.01, **UNREDUCED, **kw) + with pytest.raises(MemoryError, match="max_memory_gb"): + tc.features(x, max_memory_gb=0.001, **STRENGTH, **kw) + with pytest.raises(MemoryError, match="max_memory_gb"): + tc.two_path_step(x, causal=True, max_memory_gb=0.001, **STRENGTH, **PARAMS) + needed = estimate_memory_gb(30, 1, 400)[1] + X = _quiet(tc.features, x, max_memory_gb=needed * 1.5, **STRENGTH, + **{**kw, "order": 1}) + assert X[1].shape == (400, 30) + # wisfc with fixed weights is read like the built-in function (kernels in + # chunks of rows, not T x T arrays) + data = [np.random.default_rng(s).standard_normal((3000, 6)) for s in range(3)] + limit = estimate_memory_gb(6, 1, 3000, n_subjects=3, cfun=tc.wisfc)[1] * 1.2 + assert limit < estimate_memory_gb(6, 1, 3000, n_subjects=3, cfun=WISFC)[1] / 2 + X = _quiet(tc.features, data, order=1, causal=True, cfun=WISFC, + max_memory_gb=limit, **STRENGTH, **PARAMS) + assert len(X[1]) == 3 + + +# ---------------------------------------------------------------------------- +# arguments +# ---------------------------------------------------------------------------- + +X0 = np.random.default_rng(0).standard_normal((60, 5)) +OK = dict(causal=True, cfun=tc.autofc, **STRENGTH, **PARAMS) +FUNCTIONS = { + "features": lambda x, **kw: tc.features(x, order=2, **kw), + "two_path_step": tc.two_path_step, +} +both = pytest.mark.parametrize("function", sorted(FUNCTIONS)) + + +@both +def test_backward_kernels_are_implied(function): + f = FUNCTIONS[function] + out = _quiet(f, X0, **OK) + for side in ("all", "backward", "pre", "BACKWARD"): + other = _quiet(f, X0, include_timepoints=side, **OK) + for a, b in zip(out, other): + assert np.array_equal(a, b, equal_nan=True) + + +@both +@pytest.mark.parametrize("side", ["forward", "post", "Forward"]) +def test_forward_kernels_raise(function, side): + with pytest.raises(ValueError, match="backward"): + FUNCTIONS[function](X0, include_timepoints=side, **OK) + + +@both +@pytest.mark.parametrize("missing", ["weights_params", "delta_weights_params"]) +def test_kernel_parameters_are_required_on_both_paths(function, missing): + kw = {k: v for k, v in OK.items() if k != missing} + with pytest.raises(ValueError, match=rf"causal=True.*\b{missing}"): + FUNCTIONS[function](X0, **kw) + # also when another kernel function is given + names = {"weights_params": "weights_function", + "delta_weights_params": "delta_weights_function"} + with pytest.raises(ValueError, match=rf"causal=True.*\b{missing}"): + FUNCTIONS[function](X0, **{names[missing]: tc.laplace_weights}, **kw) + + +@pytest.mark.parametrize("name", ["weights_params", "delta_weights_params"]) +def test_order_maps_of_kernel_parameters_must_cover_every_order(name): + kw = {**OK, name: {1: {"var": 25}, 3: {"var": 25}}} + with pytest.raises(ValueError, match=rf"causal=True.*{name}.*order 2"): + tc.features(X0, order=3, **kw) + kw = {**OK, name: {1: {"var": 25}, 2: None}} + with pytest.raises(ValueError, match=rf"causal=True.*{name}.*order 2"): + tc.features(X0, order=2, **kw) + kw = {**OK, name: {1: {"var": 25}, 2: {"var": 9}}} + assert len(_quiet(tc.features, X0, order=2, **kw)) == 3 + + +@both +def test_delta_kernels_raise(function): + f = FUNCTIONS[function] + kw = {k: v for k, v in OK.items() if k != "delta_weights_params"} + with pytest.raises(ValueError, match="causal=True.*eye_weights"): + f(X0, delta_weights_function=tc.eye_weights, **kw) + kw = {k: v for k, v in OK.items() if k != "weights_params"} + with pytest.raises(ValueError, match="causal=True.*eye_weights"): + f(X0, weights_function=tc.eye_weights, **kw) + with pytest.raises(ValueError, match="causal=True.*eye_weights"): + f(X0, weights_function=tc.eye_weights, weights_params={}, **kw) + + +@both +def test_wisfc_needs_fixed_subject_weights(function): + f = FUNCTIONS[function] + data = [X0, X0[::-1].copy(), X0**2] + kw = {**OK} + for cfun in (tc.wisfc, functools.partial(tc.wisfc), + functools.partial(tc.wisfc, subject_weights=None)): + kw["cfun"] = cfun + with pytest.raises(ValueError, match="causal=True.*subject_weights"): + f(data, **kw) + kw["cfun"] = WISFC + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + out = f(data, **kw) + assert not [c for c in caught if "guarantee" in str(c.message)] + assert len(out[-1]) == 3 + + +@both +def test_events_must_be_boundaries(function): + f = FUNCTIONS[function] + feats = np.random.default_rng(1).standard_normal((60, 3)) + with pytest.raises(ValueError, match="causal=True.*boundaries"): + f(X0, events=feats, **OK) + with pytest.raises(ValueError, match="causal=True.*boundaries"): + f([X0, X0 + 1], events=[[30], feats], **OK) + out = _quiet(f, X0, events=[30], **OK) + assert np.isnan(np.asarray(out[-1])[30:32]).all() + if function == "features": + with pytest.raises(ValueError, match="causal=True.*boundaries"): + tc.features(X0, order=2, events={2: feats}, **OK) + with pytest.raises(ValueError, match="causal=True.*boundaries"): + tc.features(X0, order=2, events={1: [30], 2: feats}, **OK) + assert len(_quiet(tc.features, X0, order=2, events={2: [30]}, **OK)) == 3 + + +FITTED = ["auto", "PCA", {"model": "PCA"}, "weighted_strength", + "weighted_strength_split", "communities", tc.WeightedStrength(), + tc.Communities(n=2)] + + +@both +@pytest.mark.parametrize("rfun", FITTED, ids=str) +@pytest.mark.parametrize("name", ["rfun", "delta_rfun"]) +def test_fitted_reducers_are_not_implemented_yet(function, name, rfun): + kw = {**OK, name: rfun} + with pytest.raises(NotImplementedError, match=rf"{name}.*fit_timepoints"): + FUNCTIONS[function](X0, **kw) + + +@both +def test_the_default_reducers_are_fitted(function): + kw = {k: v for k, v in OK.items() if k not in ("rfun", "delta_rfun")} + with pytest.raises(NotImplementedError, match="fit_timepoints"): + FUNCTIONS[function](X0, **kw) + with pytest.raises(NotImplementedError, match="fit_timepoints"): + FUNCTIONS[function](X0, rfun="strength", **kw) + with pytest.raises(NotImplementedError, match="fit_timepoints"): + FUNCTIONS[function](X0, delta_rfun="strength", **kw) + + +def test_fitted_reducers_in_order_maps_are_not_implemented_yet(): + kw = {**OK, "rfun": {1: "strength", 2: "PCA"}} + with pytest.raises(NotImplementedError, match=r"rfun.*order 2.*fit_timepoints"): + tc.features(X0, order=2, **kw) + # an order missing from a map is "auto" + kw = {**OK, "delta_rfun": {1: "strength"}} + with pytest.raises(NotImplementedError, match=r"delta_rfun.*order 2.*fit_timepoints"): + tc.features(X0, order=2, **kw) + kw = {**OK, "rfun": {1: "strength", 2: None}, "delta_rfun": {1: None, 2: "strength"}} + assert len(_quiet(tc.features, X0, order=2, **kw)) == 3 + + +@both +def test_functions_of_the_users_warn_once(function): + f = FUNCTIONS[function] + + def my_cfun(data, weights): + return tc.autofc(data, weights) + + def my_rfun(arrays): + return [np.nan_to_num(a[:, :3]) for a in arrays] + + for kw, names in (({"cfun": my_cfun}, ["cfun"]), ({"rfun": my_rfun}, ["rfun"]), + ({"delta_rfun": my_rfun}, ["delta_rfun"]), + ({"cfun": my_cfun, "rfun": my_rfun}, ["cfun", "rfun"])): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + f(X0, **{**OK, **kw}) + messages = [str(c.message) for c in caught if "guarantee" in str(c.message)] + assert len(messages) == 1 + assert all(name in messages[0] for name in names) + + +@both +@pytest.mark.parametrize("bad", [-1, 0, 0.5, np.nan, np.inf, "3", True]) +def test_min_samples_must_be_none_or_a_number_from_1(function, bad): + with pytest.raises(ValueError, match="min_samples"): + FUNCTIONS[function](X0, min_samples=bad, **OK) + + +@both +def test_min_samples_needs_causal_and_a_kernel_that_reaches_it(function): + f = FUNCTIONS[function] + kw = {k: v for k, v in OK.items() if k != "causal"} + with pytest.raises(ValueError, match="causal=True"): + f(X0, min_samples=5, **kw) + # the feeding kernel (variance 16) has at most 7.6 effective samples: the + # error comes before anything is computed, whatever the length + for x in (X0, X0[:3]): + with pytest.raises(ValueError, match="min_samples=8.*7.5"): + f(x, min_samples=8, **OK) + assert np.isnan(np.asarray(_quiet(f, X0[:3], min_samples=7, **OK)[-1])).all() + + +@both +def test_new_arguments_are_keyword_only_and_documented(function): + import inspect + + f = getattr(tc, function) + parameters = inspect.signature(f).parameters + for name in ("causal", "min_samples"): + assert parameters[name].kind is inspect.Parameter.KEYWORD_ONLY + assert f"\n {name} : " in f.__doc__ + assert parameters["causal"].default is False + assert parameters["min_samples"].default is None + assert "NotImplementedError" in f.__doc__ + + +def test_default_is_not_causal(): + x = np.random.default_rng(2).standard_normal((80, 4)) + kw = dict(order=2, cfun=tc.autofc, return_delta=True, **STRENGTH, **PARAMS) + a = _quiet(tc.features, x, **kw) + b = _quiet(tc.features, x, causal=False, min_samples=None, **kw) + for p, q in zip(a, b): + for u, v in zip(p, q): + assert np.array_equal(u, v) + assert not np.isnan(a[0][2]).any() + + +# ---------------------------------------------------------------------------- +# speed +# ---------------------------------------------------------------------------- + + +def test_order_three_of_5033_by_49_takes_seconds(): + x = np.random.default_rng(0).standard_normal((5033, 49)) + kw = dict(order=3, rfun="strength", delta_rfun="strength", + weights_params={"var": 25}, delta_weights_params={"var": 25}) + start = time.perf_counter() + X = _quiet(tc.features, x, causal=True, **kw) + causal = time.perf_counter() - start + start = time.perf_counter() + P = _quiet(tc.features, x, include_timepoints="backward", **kw) + plain = time.perf_counter() - start + print(f"\n5033 x 49, order 3: causal {causal:.2f} s, causal=False backward " + f"{plain:.2f} s") + assert X[3].shape == (5033, 49) + assert np.array_equal(np.flatnonzero(np.isnan(X[3]).all(axis=1)), np.arange(6)) + assert not np.isnan(X[3][6:]).any() + # the rows far from the start agree with the kernels of causal=False + assert np.max(np.abs(X[3][800:] - P[3][800:])) <= ATOL + assert causal < 15 diff --git a/timecorr/helpers.py b/timecorr/helpers.py index ceedb89d..70c62d62 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -1036,6 +1036,7 @@ def __init__(self, weights): self._peak[t0:t1] = np.maximum(w.max(axis=1), -w.min(axis=1)) self._first[t0:t1] = c0 + np.argmax(w != 0, axis=1) self.zero = None + self.zero_cols = None self._scale = None self.spans = None self._cache = {} @@ -1050,11 +1051,21 @@ def zero_rows(self, mask): """Set the rows in ``mask`` to 0 (before ``prepare``).""" self.zero = np.asarray(mask, dtype=bool) + def zero_columns(self, mask): + """ + Set the columns in ``mask`` to 0 (before ``prepare``): timepoints + that no row weights (the causal estimator's timepoints without a + sample). + """ + mask = np.asarray(mask, dtype=bool) + self.zero_cols = mask if mask.any() else None + def prepare(self, finite, always=False): """ Rescale the extreme rows and choose each chunk's columns - (``always``: the columns where the chunk has weight, however much of - the kernel they cover, as the causal estimator needs). + (``always``: the columns where the chunk has weight before + ``zero_rows``, however much of the kernel they cover, as the causal + estimator needs). """ T_out = self.shape[0] T = self.shape[1] if len(self.shape) == 2 else 0 @@ -1071,8 +1082,17 @@ def prepare(self, finite, always=False): self._kept = set() slices = None if len(self.shape) == 2: - slices = (_time_slices(self, finite, True) if always - else _time_slices(self, finite)) + if always: + # from the kernel before any row or column is set to 0: + # which rows the causal estimator leaves undefined and which + # timepoints have no sample depends on the data, and the + # columns of a chunk (the shapes of its sums) must not + zero, cols = self.zero, self.zero_cols + self.zero = self.zero_cols = None + slices = _time_slices(self, finite, True) + self.zero, self.zero_cols = zero, cols + else: + slices = _time_slices(self, finite) if slices is None: slices = [(t0, t1, 0, T) for t0, t1, _, _, _ in self._chunks] self.spans = slices @@ -1101,24 +1121,32 @@ def _keep(self, key, block, shared=False): self._kept.add(id(block)) # cached arrays are never dropped return block - def _row_state(self, t0, t1): - """The zeroed rows and scales of rows t0:t1, as part of a cache key.""" + def _row_state(self, t0, t1, c0=0, c1=0): + """ + The zeroed rows and scales of rows t0:t1 and the zeroed columns + among c0:c1, as part of a cache key. + """ zero = None if self.zero is None else self.zero[t0:t1].tobytes() scale = None if self._scale is None else self._scale[t0:t1].tobytes() - return zero, scale + cols = None + if self.zero_cols is not None and self.zero_cols[c0:c1].any(): + cols = self.zero_cols[c0:c1].tobytes() + return zero, scale, cols def _final(self, i): """ - Chunk i over its columns: NaN weights 0, the zeroed rows 0, the - extreme rows rescaled. Chunks with equal blocks, equal zeroed rows - and equal scales share one array (do not modify it). + Chunk i over its columns: NaN weights 0, the zeroed rows and + columns 0, the extreme rows rescaled. Chunks with equal blocks, + equal zeroed rows and columns and equal scales share one array (do + not modify it). """ t0, t1, c0, c1, key = self._chunks[i] zero = None if self.zero is None else self.zero[t0:t1] scale = None if self._scale is None else self._scale[t0:t1] # a chunk without a shared key (at an edge or an event boundary) is # kept under its own index - key = ("final", ("chunk", i) if key is None else key) + self._row_state(t0, t1) + key = (("final", ("chunk", i) if key is None else key) + + self._row_state(t0, t1, c0, c1)) hit = self._cache.get(key) if hit is not None: return hit @@ -1128,6 +1156,8 @@ def _final(self, i): w[np.isnan(w)] = 0 if zero is not None: w[zero] = 0 + if key[-1] is not None: + w[:, self.zero_cols[c0:c1]] = 0 if scale is not None: rows = scale != 1.0 if rows.any(): @@ -1140,7 +1170,8 @@ def _block(self, i, kind): # chunks with equal blocks, equal rows zeroed and rescaled (as in # _final) and the same span relative to t0 have equal blocks key = (("chunk", i) if key is None - else (key, c0 - t0, c1 - t0) + self._row_state(t0, t1)) + else (key, c0 - t0, c1 - t0) + + self._row_state(t0, t1, *self._chunks[i][2:4])) hit = self._cache.get((key, kind)) if hit is not None: return hit @@ -1693,15 +1724,25 @@ def _causal_zero_variance(var, msq, s, mean): ) +# The causal estimator centers the data anew for every group of this many +# kernel rows (see ``_group_reference``): a few standard deviations of a +# kernel as narrow as a Gaussian of variance 25. Each group multiplies the +# centered columns over all the columns its chunk weights, so a chunk that +# weights more than ``_CAUSAL_SPAN`` columns (a kernel with weight at every +# lag, such as ``laplace_weights``) has proportionally larger groups, up to +# the whole chunk. +_CAUSAL_GROUP = 16 +_CAUSAL_SPAN = 512 + + def _causal_reference(x, c0, t0, c1): """ - The centering reference of the columns of ``x`` for a chunk of kernel - rows that starts at row ``t0`` and weights rows ``c0:c1``: the mean of - each column's observed samples in rows ``c0:t0`` (before every row of the - chunk); for a column without any, its first observed sample in rows - ``c0:c1`` (0 when it has none). A row of the chunk that has samples of - the column has that first sample in its past, so no row's reference - holds a sample from its future. + A centering reference of the columns of ``x`` for kernel rows from + ``t0`` on that weight rows ``c0:c1``: the mean of each column's observed + samples in rows ``c0:t0`` (before every such row); for a column without + any, its first observed sample in rows ``c0:c1`` (0 when it has none). + A kernel row that has samples of the column has that first sample in + its past, so no row's reference holds a sample from its future. """ past = x[c0:max(c0, t0)] ok = ~np.isnan(past) @@ -1716,6 +1757,57 @@ def _causal_reference(x, c0, t0, c1): return ref +def _group_reference(x, weights, c0, g0, c1): + """ + The centering reference of the columns of ``x`` for a group of kernel + rows that starts at row ``g0`` and weights rows ``c0:c1``: the + kernel-weighted mean of each column's observed samples at row ``g0`` + (``weights``: the absolute weights of that row over ``c0:c1``), which + every row of the group may read and which lies within the samples the + group weights. For a column without a weighted sample at row ``g0`` + (the first rows of a series or of an event, a row left undefined): + ``_causal_reference``. + + A correlation does not depend on the reference; a reference close to + the samples a row weights keeps its sums well conditioned. + """ + span = x[c0:c1] + ok = ~np.isnan(span) + num = weights @ np.where(ok, span, 0.0) + den = weights @ ok.astype(np.float64) + ref = _safe_divide(num, den) + none = den == 0 + if none.any(): + ref[none] = _causal_reference(x[:, none], c0, g0, c1) + return ref + + +def _causal_groups(rows): + """ + ``(i, g0, g1, c0, c1)`` for the groups of consecutive rows ``g0:g1`` of + each chunk ``i`` of a prepared ``_KernelRows`` whose kernel has no + weight above its diagonal: the group's weights lie in columns ``c0:c1`` + (the chunk's columns before row ``g1``). A group has ``_CAUSAL_GROUP`` + rows, times the number of ``_CAUSAL_SPAN`` columns the chunk weights + (rounded up), at most the chunk. + """ + groups = [] + for i, (t0, t1, c0, c1) in enumerate(rows.spans): + size = _CAUSAL_GROUP * max(1, -(-(c1 - c0) // _CAUSAL_SPAN)) + for g0 in range(t0, t1, size): + g1 = min(t1, g0 + size) + if min(c1, g1) > c0: + groups.append((i, g0, g1, c0, min(c1, g1))) + return groups + + +def _group_block(rows, group, kind): + """The rows and columns of a group of ``_causal_groups`` (a new array).""" + i, g0, g1, c0, c1 = group + t0 = rows.spans[i][0] + return np.ascontiguousarray(rows._block(i, kind)[g0 - t0 : g1 - t0, : c1 - c0]) + + def _causal_setup(a, b, rows, autocorrelation, min_samples): """ ``_wcorr_setup`` for the causal estimator (``a`` and ``b`` from @@ -1729,11 +1821,15 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): both ``a`` and ``b`` have a sample) are set to 0 here and to NaN in the output; - every chunk of ``CHUNK`` rows is multiplied with the columns where it - has weight, whatever fraction of the kernel they cover; - - each chunk centers the data on its own reference - (``_causal_reference``), and the zero-variance rule compares a + has weight, whatever fraction of the kernel they cover, a group of + ``_CAUSAL_GROUP`` rows at a time (``_causal_groups``); + - each group centers the data on its own reference + (``_group_reference``), and the zero-variance rule compares a variance with the kernel-weighted mean square about that reference and with the kernel-weighted mean (``_causal_zero_variance``); + - a timepoint where ``a`` or ``b`` has no sample at all (a row of NaN, + as the undefined rows of an earlier order are) has weight 0 in every + row; - a row is computed with the sums for complete data exactly when no timepoint it weights has a NaN sample (``"plain"``), and with the pairwise sums otherwise. NaN samples are set to 0 after centering, so @@ -1747,20 +1843,25 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): Ka, Kb = a.shape[1], b.shape[1] nan_a = np.isnan(a) nan_b = nan_a if autocorrelation else np.isnan(b) - defined = _causal_defined( - rows.kernel, ~nan_a.all(axis=1) & ~nan_b.all(axis=1), min_samples - ) + # timepoints without a sample of ``a`` or of ``b``: no pair of features + # has one there, so no row weights them (their kernel columns are 0) + missing = nan_a.all(axis=1) | nan_b.all(axis=1) + defined = _causal_defined(rows.kernel, ~missing, min_samples) rows.zero_rows(~defined) + rows.zero_columns(missing) rows.prepare(True, always=True) - # the timepoints with a NaN sample, and their number before each row - with_nan = (nan_a.any(axis=1) | nan_b.any(axis=1)).astype(np.float64) + # the timepoints with a NaN sample, their number before each row, and + # those among them that rows can weight + with_nan = nan_a.any(axis=1) | nan_b.any(axis=1) nan_before = np.concatenate([[0], np.cumsum(with_nan)]) + with_nan = (with_nan & ~missing).astype(np.float64) del nan_a, nan_b - n = len(rows.spans) + groups = _causal_groups(rows) + n = len(groups) state = { "causal": True, "T": a.shape[0], "rows": rows, "a": a, "b": b, - "defined": defined, - # chunks whose columns hold a NaN sample; chunks with a row that + "defined": defined, "groups": groups, + # groups whose columns hold a NaN sample; groups with a row that # weights one; the rows that weight none "dirty": np.zeros(n, dtype=bool), "nan": np.zeros(n, dtype=bool), @@ -1781,7 +1882,7 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): }) active = np.zeros(T_out, dtype=bool) - def moments(x, ref, dirty, A, W, s, t0, t1, side): + def moments(x, ref, dirty, A, W, s, g0, g1, side): x = x - ref if dirty: x[np.isnan(x)] = 0 @@ -1789,30 +1890,29 @@ def moments(x, ref, dirty, A, W, s, t0, t1, side): msq = A @ x**2 var = msq - s * mean**2 zero = _causal_zero_variance(var, msq, s, mean + ref) - state["m" + side][t0:t1] = mean - state["w" + side][t0:t1] = W @ x - state["v" + side][t0:t1] = np.where(zero, 0.0, var) - state["z" + side][t0:t1] = zero - - for i, (t0, t1, c0, c1) in enumerate(rows.spans): - if c1 <= c0: - continue - A = rows._block(i, "a") + state["m" + side][g0:g1] = mean + state["w" + side][g0:g1] = W @ x + state["v" + side][g0:g1] = np.where(zero, 0.0, var) + state["z" + side][g0:g1] = zero + + for g, group in enumerate(groups): + _, g0, g1, c0, c1 = group + A = _group_block(rows, group, "a") s = A.sum(axis=1)[:, np.newaxis] - active[t0:t1] = s[:, 0] > 0 - dirty = state["dirty"][i] = nan_before[c1] > nan_before[c0] + active[g0:g1] = s[:, 0] > 0 + dirty = state["dirty"][g] = nan_before[c1] > nan_before[c0] if dirty: - plain = (rows._block(i, "s") @ with_nan[c0:c1]) == 0 - state["plain"][t0:t1] = plain - state["nan"][i] = not plain.all() - state["ref_a"][i] = _causal_reference(a, c0, t0, c1) + plain = (_group_block(rows, group, "s") @ with_nan[c0:c1]) == 0 + state["plain"][g0:g1] = plain + state["nan"][g] = not plain.all() + state["ref_a"][g] = _group_reference(a, A[0], c0, g0, c1) if not autocorrelation: - state["ref_b"][i] = _causal_reference(b, c0, t0, c1) - W = rows._block(i, "w") - state["sw"][t0:t1, 0] = W.sum(axis=1) - moments(a[c0:c1], state["ref_a"][i], dirty, A, W, s, t0, t1, "a") + state["ref_b"][g] = _group_reference(b, A[0], c0, g0, c1) + W = _group_block(rows, group, "w") + state["sw"][g0:g1, 0] = W.sum(axis=1) + moments(a[c0:c1], state["ref_a"][g], dirty, A, W, s, g0, g1, "a") if not autocorrelation: - moments(b[c0:c1], state["ref_b"][i], dirty, A, W, s, t0, t1, "b") + moments(b[c0:c1], state["ref_b"][g], dirty, A, W, s, g0, g1, "b") state["active"] = active # the sums for complete data set the block size; the pairwise sums of # the rows that need them are computed in blocks of their own @@ -1822,19 +1922,16 @@ def moments(x, ref, dirty, A, W, s, t0, t1, side): return state -def _causal_pairwise(state, i, xa, ok_a, xb, ok_b, ref_a, ref_b): +def _causal_pairwise(A, W, S, xa, ok_a, xb, ok_b, ref_a, ref_b): """ - The pairwise sums of chunk ``i`` of the causal estimator for the - centered, zero-filled columns ``xa`` and ``xb`` (``ok_a``, ``ok_b``: - their observed samples): ``(r, undefined, zero, few)``, each of shape - (rows of the chunk, columns of ``xa``, columns of ``xb``). + The pairwise sums of a group of rows of the causal estimator (``A``, + ``W``, ``S``: the group's absolute weights, weights and support) for + the centered, zero-filled columns ``xa`` and ``xb`` (``ok_a``, + ``ok_b``: their observed samples): ``(r, undefined, zero, few)``, each + of shape (rows of the group, columns of ``xa``, columns of ``xb``). """ - rows = state["rows"] - t0, t1, c0, c1 = rows.spans[i] - L = c1 - c0 - sub = (t1 - t0, xa.shape[1], xb.shape[1]) - A = rows._block(i, "a") - W = rows._block(i, "w") + L = xa.shape[0] + sub = (A.shape[0], xa.shape[1], xb.shape[1]) pair_ok = ok_a[:, :, np.newaxis] & ok_b[:, np.newaxis, :] x = xa[:, :, np.newaxis] * pair_ok y = xb[:, np.newaxis, :] * pair_ok @@ -1859,7 +1956,7 @@ def _causal_pairwise(state, i, xa, ok_a, xb, ok_b, ref_a, ref_b): ) var_a, var_b, zero = (v.reshape(sub) for v in (var_a, var_b, zero)) # two samples always give r = +-1: fewer than 3 is undefined - few = (rows._block(i, "s") @ terms[:, :m]).reshape(sub) < 3 + few = (S @ terms[:, :m]).reshape(sub) < 3 und = zero | few return _correlation_ratio(num, var_a, var_b, und, sub), und, zero, few @@ -1867,10 +1964,10 @@ def _causal_pairwise(state, i, xa, ok_a, xb, ok_b, ref_a, ref_b): def _causal_block(state, i0, i1, j0): """ ``_wcorr_block`` for the causal estimator (``state`` from - ``_causal_setup``): the same sums, a chunk of kernel rows at a time, + ``_causal_setup``): the same sums, a group of kernel rows at a time, each over its own columns and about its own centering reference. Every - chunk computes the sums for complete data, on the data with NaN samples - set to 0; a chunk with rows that weight a NaN sample also computes the + group computes the sums for complete data, on the data with NaN samples + set to 0; a group with rows that weight a NaN sample also computes the pairwise sums, which those rows take. """ rows = state["rows"] @@ -1882,58 +1979,59 @@ def _causal_block(state, i0, i1, j0): few_any = np.zeros(shape[0], dtype=bool) # rows of ``a`` per block of pairwise sums step = _wcorr_block_rows(state["T"], shape[2], _WCORR_NAN_PRODUCTS) - for i, (t0, t1, c0, c1) in enumerate(rows.spans): - if c1 <= c0: - continue + for g, group in enumerate(state["groups"]): + _, g0, g1, c0, c1 = group L = c1 - c0 - sub = (t1 - t0,) + shape[1:] - ref_a = state["ref_a"][i, i0:i1] - ref_b = state["ref_b"][i, j0:] + sub = (g1 - g0,) + shape[1:] + ref_a = state["ref_a"][g, i0:i1] + ref_b = state["ref_b"][g, j0:] xa = a[c0:c1, i0:i1] - ref_a xb = b[c0:c1, j0:] - ref_b - if state["dirty"][i]: + if state["dirty"][g]: ok_a = ~np.isnan(xa) ok_b = ~np.isnan(xb) xa[~ok_a] = 0 xb[~ok_b] = 0 - W = rows._block(i, "w") + W = _group_block(rows, group, "w") prod = (xa[:, :, np.newaxis] * xb[:, np.newaxis, :]).reshape(L, -1) cross = (W @ prod).reshape(sub) del prod - ma_i = state["ma"][t0:t1, i0:i1, np.newaxis] - mb_j = state["mb"][t0:t1, np.newaxis, j0:] + ma_i = state["ma"][g0:g1, i0:i1, np.newaxis] + mb_j = state["mb"][g0:g1, np.newaxis, j0:] num = ( cross - - ma_i * state["wb"][t0:t1, np.newaxis, j0:] - - mb_j * state["wa"][t0:t1, i0:i1, np.newaxis] - + ma_i * mb_j * state["sw"][t0:t1, :, np.newaxis] + - ma_i * state["wb"][g0:g1, np.newaxis, j0:] + - mb_j * state["wa"][g0:g1, i0:i1, np.newaxis] + + ma_i * mb_j * state["sw"][g0:g1, :, np.newaxis] ) - var_a = state["va"][t0:t1, i0:i1, np.newaxis] - var_b = state["vb"][t0:t1, np.newaxis, j0:] - zero = (state["za"][t0:t1, i0:i1, np.newaxis] - | state["zb"][t0:t1, np.newaxis, j0:]) - r_chunk = _correlation_ratio(num, var_a, var_b, zero, sub) + var_a = state["va"][g0:g1, i0:i1, np.newaxis] + var_b = state["vb"][g0:g1, np.newaxis, j0:] + zero = (state["za"][g0:g1, i0:i1, np.newaxis] + | state["zb"][g0:g1, np.newaxis, j0:]) + r_group = _correlation_ratio(num, var_a, var_b, zero, sub) und = zero - if state["nan"][i]: + if state["nan"][g]: # the rows that weight a NaN sample take the pairwise sums - need = ~state["plain"][t0:t1] + need = ~state["plain"][g0:g1] + A = _group_block(rows, group, "a") + S = _group_block(rows, group, "s") und = zero.copy() zero = zero.copy() few = np.zeros(sub, dtype=bool) for k0 in range(0, sub[1], step): k1 = min(sub[1], k0 + step) pr, pu, pz, pf = _causal_pairwise( - state, i, xa[:, k0:k1], ok_a[:, k0:k1], xb, ok_b, + A, W, S, xa[:, k0:k1], ok_a[:, k0:k1], xb, ok_b, ref_a[k0:k1], ref_b, ) - r_chunk[need, k0:k1] = pr[need] + r_group[need, k0:k1] = pr[need] und[need, k0:k1] = pu[need] zero[need, k0:k1] = pz[need] few[need, k0:k1] = pf[need] - few_any[t0:t1] = few.reshape(sub[0], -1).any(axis=1) - zero_all[t0:t1] = zero.reshape(sub[0], -1).all(axis=1) - r[t0:t1] = r_chunk - undefined[t0:t1] = und + few_any[g0:g1] = few.reshape(sub[0], -1).any(axis=1) + zero_all[g0:g1] = zero.reshape(sub[0], -1).all(axis=1) + r[g0:g1] = r_group + undefined[g0:g1] = und return r, undefined, zero_all, few_any @@ -2180,16 +2278,29 @@ def wcorr(a, b, weights, *, causal=False, min_samples=None): after ``t``: the correlations at ``t`` are unchanged (to 1e-9) when the samples after ``t`` are replaced by any values, NaN and inf included, or removed (and, when the kernel gives ``t`` itself no weight, when the - samples at ``t`` change). The kernel must give no weight to later - timepoints. The estimate is the same formula, with these differences: - - - Data are centered, a chunk of 128 kernel rows at a time, on the mean - of each feature's samples in the rows that the chunk weights and that - come before the chunk (its first observed sample when there are - none), not on the mean over all timepoints; the 1e-10 rule above + samples at ``t`` change). Replacing later samples changes no bit of + an earlier timepoint; removing them changes the shapes of the last + sums and so their round-off (measured: at most 6e-13, on series with + an offset, a random walk, and steps of up to 1e8 standard + deviations). The kernel must give no weight to later timepoints. The estimate is the same formula, with these differences: + + - Data are centered, a group of 16 timepoints at a time (more for a + kernel that weights more than 512 timepoints), on the kernel-weighted + mean of each feature at the group's first timepoint (where that + timepoint has no weighted sample of the feature: the mean of its + samples before the group among those the group weights, or its first + sample), not on the mean over all timepoints; the 1e-10 rule above compares the variance with the kernel-weighted mean square about that reference. A correlation does not depend on the reference; it only conditions the sums. + - A feature whose kernel-weighted standard deviation at a timepoint is + below 1e-9 times the magnitude of its kernel-weighted mean also + counts as having zero variance there: a feature that is constant up + to the round-off of whatever computed it. + - A timepoint is computed with the sums for complete data when none of the + timepoints it weights has a NaN sample, and with pairwise sums + otherwise, whatever the later samples are. A timepoint where ``a`` + or ``b`` has no sample at all has no weight in any row. - Infinite samples and samples above 1e150 in magnitude are missing data, like NaN. - A timepoint with fewer than 3 observed samples with non-zero weight @@ -2203,7 +2314,9 @@ def wcorr(a, b, weights, *, causal=False, min_samples=None): - ``a`` and ``b`` are an autocorrelation (diagonal set to 1) only when they are the same object; equal values in two arrays are not compared. - A delta kernel raises ``ValueError`` (its z-scores use every - timepoint). + timepoint). A series of one timepoint is not a delta kernel, and a + kernel row without weight is an undefined timepoint (NaN), not an + error: every prefix of a series can be computed. Parameters ---------- @@ -2252,8 +2365,8 @@ def wcorr(a, b, weights, *, causal=False, min_samples=None): Raises ------ ValueError - If the inputs do not have T rows / T kernel columns, or if every row of - the kernel is zero. With ``causal=True``: if the kernel has weight + If the inputs do not have T rows / T kernel columns, or (without + ``causal``) if every row of the kernel is zero. With ``causal=True``: if the kernel has weight above its diagonal or is a delta kernel, or if ``min_samples`` is not None or a finite number >= 1. If ``min_samples`` is given without ``causal=True``. diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index cbac1528..4c19c48c 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -54,14 +54,18 @@ block holds all d rows. """ +import functools import inspect import numbers +import warnings import numpy as np from .helpers import ( _SUMMARY_NAMES, + _check_min_samples, _check_ndims, + _check_reachable, _check_rfun, _LAG_PROFILES, _is_model, @@ -103,7 +107,15 @@ _auto_emitter, _auto_fallback, ) -from .timecorr import _event_kernels, _restricted, _shaped_kernel, timecorr +from .timecorr import ( + _event_kernels, + _fixed_weights_wisfc, + _needs_fit, + _reduce_defined, + _restricted, + _shaped_kernel, + timecorr, +) _BYTES_PER_GB = 1e9 # outputs computed at fewer timepoints are interpolated to all T timepoints @@ -139,16 +151,20 @@ def _builtin_kernel(weights_function): return False -def _dense_analysis(weights_function, cfun=isfc): +def _dense_analysis(weights_function, cfun=isfc, causal=False): """ True when an analysis step holds T x T kernel arrays: for a kernel function of your own, and for a correlation function of your own, which ``timecorr`` passes T x T arrays (only ``autofc``, ``isfc``, ``wisfc`` and the smoothing of ``cfun=None`` read a built-in kernel in chunks of - rows). + rows; with ``causal``, also ``functools.partial(wisfc, + subject_weights=...)``, which ``timecorr`` then calls as ``wisfc``). """ # cfun=None smooths the data with the kernel, also in chunks of rows - builtin_cfun = cfun is None or any(cfun is f for f in _STREAMED_CFUNS) + builtin_cfun = ( + cfun is None or any(cfun is f for f in _STREAMED_CFUNS) + or (causal and _fixed_weights_wisfc(cfun)) + ) return not (_builtin_kernel(weights_function) and builtin_cfun) @@ -586,14 +602,18 @@ def _as_summary(rfun): def _apply_reducer(corrs, rfun, ndims, order=None, path=None, null_threshold=None, - append_fit=False): + append_fit=False, causal=False): """ ``_reduce``; a summary is fit (recording ``order`` and ``path`` in its ``fits_``) and then transforms the same correlations. With ``append_fit`` False, ``fits_`` keeps only the new fit (as a direct call of the summary does); True appends it (the steps of ``features`` and - ``two_path_step``). + ``two_path_step``). ``causal``: the correlations are those of the + causal estimator, whose undefined rows are NaN; a graph measure is + computed for the defined rows and the others stay NaN. """ + if causal and isinstance(rfun, str): + return _reduce_defined(corrs, rfun) summary = _as_summary(rfun) if summary is None: return _reduce(corrs, rfun, ndims) @@ -609,6 +629,35 @@ def _apply_reducer(corrs, rfun, ndims, order=None, path=None, null_threshold=Non return out +class _causal_step: + """ + Context of one ``timecorr`` call of a step: the keyword arguments of the + causal estimator (none without ``causal``). ``timecorr``'s warning about + a correlation function of the user's is not repeated at every step + (``_check_causal`` issued it once for the call). + """ + + def __init__(self, causal, min_samples): + self.causal = causal + self.min_samples = min_samples + self._caught = None + + def __enter__(self): + if not self.causal: + return {} + self._caught = warnings.catch_warnings() + self._caught.__enter__() + warnings.filterwarnings( + "ignore", message=r"causal=True: cfun is a function of your own" + ) + return {"causal": True, "min_samples": self.min_samples} + + def __exit__(self, *exc): + if self._caught is not None: + self._caught.__exit__(*exc) + return False + + def _streams(rfun, cfun, combine, groups=None): """Whether an analysis step is streamed (see the module docstring).""" return ( @@ -707,10 +756,16 @@ def _analysis_path( held_elements=0, reducers=(), input_elements=0, + causal=False, + min_samples=None, ): """ Analysis path of one order: ``reduce(combine(timecorr(subjects, kernel, cfun)))``. + ``causal`` and ``min_samples`` are ``timecorr``'s (the arguments were + checked by ``_check_causal``; the reducer is None, a graph measure or a + callable). + ``held_elements``: float64 values the caller retains (earlier outputs of a ``features`` run), counted against ``max_memory_gb``; ``reducers``: the reducer objects the caller holds, whose ``fits_`` arrays are counted too. @@ -744,7 +799,7 @@ def _analysis_path( ``append_fit``, otherwise the only entry; see ``_apply_reducer``). """ T, d = subjects[0].shape - dense = _dense_analysis(weights_function, cfun) + dense = _dense_analysis(weights_function, cfun, causal) if _streams(rfun, cfun, combine, groups): summary = _as_summary(rfun) # the distinct event kernels and earlier fits are held while the step @@ -778,26 +833,28 @@ def _analysis_path( dense=dense, combine=combine) def analyze(members, member_events): - return combine( - _as_list( - timecorr( - members, - weights_function=weights_function, - weights_params=weights_params, - include_timepoints=include_timepoints, - combine=null_combine, - cfun=cfun, - rfun=None, - include_zero=include_zero, - events=member_events, + with _causal_step(causal, min_samples) as estimator: + return combine( + _as_list( + timecorr( + members, + weights_function=weights_function, + weights_params=weights_params, + include_timepoints=include_timepoints, + combine=null_combine, + cfun=cfun, + rfun=None, + include_zero=include_zero, + events=member_events, + **estimator, + ) ) ) - ) if groups is None: return _apply_reducer( analyze(subjects, events), rfun, ndims, order, "analysis", - append_fit=append_fit, + append_fit=append_fit, causal=causal, ) def group_events(g): @@ -867,6 +924,8 @@ def _delta_path( held_elements=0, append_fit=False, retained_elements=0, + causal=False, + min_samples=None, ): """ Feeding (delta) path of one order: per-subject correlations with the @@ -929,21 +988,24 @@ def _delta_path( ) _check_step_memory(d, T, S, n_outputs, max_memory_gb, order, True, retained_elements, dense=dense) - corrs = _as_list( - timecorr( - subjects, - weights_function=weights_function, - weights_params=weights_params, - include_timepoints=include_timepoints, - include_zero=include_zero, - combine=null_combine, - cfun=autofc, - rfun=None, - events=events, + with _causal_step(causal, min_samples) as estimator: + corrs = _as_list( + timecorr( + subjects, + weights_function=weights_function, + weights_params=weights_params, + include_timepoints=include_timepoints, + include_zero=include_zero, + combine=null_combine, + cfun=autofc, + rfun=None, + events=events, + **estimator, + ) ) - ) return _as_list( - _apply_reducer(corrs, rfun, ndims, order, "feeding", append_fit=append_fit) + _apply_reducer(corrs, rfun, ndims, order, "feeding", + append_fit=append_fit, causal=causal) ) _check_step_memory(d, T, S, n_outputs, max_memory_gb, order, @@ -1581,6 +1643,8 @@ def two_path_step( delta_weights_function=None, delta_weights_params=None, order=1, + causal=False, + min_samples=None, ): """ Compute one order of the two-path pipeline from the previous feeding features. @@ -1682,6 +1746,59 @@ def two_path_step( The order this step computes (keyword-only), used to resolve ``"auto"`` and order maps (whose keys may be any positive integers here) and recorded in summaries' ``fits_``. Default: 1. + causal : bool + If True (keyword-only), row ``t`` of every output is computed from + rows ``0..t`` of the data only: it is unchanged (to 1e-9; bit for + bit when later rows are replaced) when later rows are replaced by + any values, NaN and inf included, or removed, and with + ``include_zero=False`` also when row ``t`` itself changes. + Default: False. With ``causal=True``: + + - both paths use backward kernels (``include_timepoints`` may be + left out; ``"forward"``/``"post"`` raises ``ValueError``), and + the correlations are those of the causal estimator (see + ``timecorr`` and ``wcorr``): infinite samples and samples above + 1e150 in magnitude are missing, like NaN; + - the kernel parameters of both paths must be given + (``weights_params`` and ``delta_weights_params``): + widths are not chosen from the data. ``eye_weights`` on either + path raises ``ValueError`` (co-fluctuations use series z-scored + over the whole recording); + - ``rfun`` and ``delta_rfun`` must be given as None or a graph + measure (``"strength"``, ``"eigenvector_centrality"``, + ``"pagerank_centrality"``, ``"pagerank_centrality_abs"``): a reducer that is fitted to data (a model such + as ``"PCA"``, a summary, and ``"auto"``, the default) raises + ``NotImplementedError``. A function of your own (as ``cfun``, + ``rfun`` or ``delta_rfun``) is called as without ``causal``, with + one ``UserWarning`` that the guarantee does not cover what it + does; + - ``cfun=tc.wisfc`` raises ``ValueError`` (its default subject + weights use the whole recording); + ``functools.partial(tc.wisfc, subject_weights=...)`` is accepted; + - ``events`` must be boundaries (features to segment raise + ``ValueError``); that the boundaries are known at their own time + is the caller's responsibility, and the warm-up starts again at + each boundary; + - a row with too few earlier samples (see ``min_samples``) is NaN + in every column, not 0. The NaN rows of an order's feeding + features are missing data for the next order, so each order has + more of them than the one before; graph measures are computed + for the other rows. A series of any length runs, and its output + is the first rows of the output of a longer series; + - 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 that is constant + up to round-off; see ``wcorr``). + min_samples : float or None + With ``causal=True`` (keyword-only), a timepoint with fewer than 3 + observed timepoints in its kernel row is undefined (NaN). A number + (>= 1) is also the effective sample size ``(sum |w|)**2 / sum + w**2`` a row needs over the observed timepoints it weights, on both + paths (see ``timecorr``); a number that a built-in + kernel of the call cannot reach with any number of earlier + timepoints raises ``ValueError`` before anything is computed. + Given without ``causal=True``, it raises ``ValueError``. Default: + None. Returns ------- @@ -1750,6 +1867,16 @@ def two_path_step( specification, a dict ``events``, or events that leave no kernel row with 3 or more non-zero weights). The events are resolved (and features segmented) before any correlations are computed. + ValueError + With ``causal=True``, before anything is computed: for the + arguments listed under ``causal`` that have no causal form, and + for a ``min_samples`` that is not None or a finite number >= 1 or + that a built-in kernel of the call cannot reach; for + ``min_samples`` given without ``causal=True``. + NotImplementedError + With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is + fitted to data (the defaults included); it would need + ``fit_timepoints``, the rows it is fitted on. RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. TypeError @@ -1788,6 +1915,17 @@ def two_path_step( ... delta_weights_function=tc.eye_weights) >>> X1[0].shape, D1[0].shape ((300, 24), (300, 24)) + + A causal step (row ``t`` uses rows ``0..t`` only; the first 2 rows have + fewer than 3 samples and are NaN): + + >>> import numpy as np + >>> X1, D1 = two_path_step(data[0], causal=True, cfun=tc.autofc, + ... rfun="strength", delta_rfun="strength", + ... weights_params={"var": 100}, + ... delta_weights_params={"var": 25}) + >>> X1.shape, D1.shape, int(np.isnan(D1).all(axis=1).sum()) + ((300, 24), (300, 24), 2) """ if ( not isinstance(order, numbers.Integral) @@ -1796,6 +1934,7 @@ def two_path_step( ): raise ValueError(f"order must be a positive integer; got {order!r}.") order = int(order) + min_samples = _check_min_samples(min_samples, causal) _refuse_params_map(weights_params, "weights_params") _refuse_params_map(delta_weights_params, "delta_weights_params") analysis, feeding = _resolve_reducers(rfun, delta_rfun, [order], None) @@ -1809,6 +1948,20 @@ def two_path_step( ) single = not isinstance(data, (list, tuple)) subjects = format_data(data, fill_nan=False) + estimator = {} + if causal: + _check_causal( + function="two_path_step", include_timepoints=include_timepoints, + weights_function=weights_function, + delta_weights_function=delta_weights_function, cfun=cfun, rfun=rfun, + delta_rfun=delta_rfun, analysis_rfun=analysis, feeding_rfun=feeding, + analysis_params={order: weights_params}, + feeding_params={order: delta_weights_params}, events=[events], + T=subjects[0].shape[0], n_subjects=len(subjects), + include_zero=include_zero, min_samples=min_samples, + ) + include_timepoints = "backward" + estimator = {"causal": True, "min_samples": min_samples} analysis_auto, feeding_auto = _auto_params( subjects, auto_analysis and weights_params is None, @@ -1838,6 +1991,7 @@ def two_path_step( include_zero=include_zero, max_memory_gb=max_memory_gb, events=resolved, + **estimator, ) if single: if isinstance(X_next, list): @@ -1895,8 +2049,9 @@ def _two_path_step( feeding_streamed = feeding_function is not eye_weights and _is_summary(delta_rfun) n_outputs = 2 if feed and not (analysis_streamed or feeding_streamed) else 1 kernel_feeding = feed and feeding_function is not eye_weights + causal = analysis.get("causal", False) dense_analysis = _dense_analysis(analysis.get("weights_function"), - analysis.get("cfun", isfc)) + analysis.get("cfun", isfc), causal) dense_feeding = feed and not _builtin_kernel(feeding_function) dense = dense_analysis or dense_feeding S = len(subjects) @@ -1990,10 +2145,113 @@ def _two_path_step( held_elements=retained + _output_elements(X_next) + fits, append_fit=True, retained_elements=retained_m + fits, + causal=causal, + min_samples=analysis.get("min_samples"), ) return X_next, D_next +def _check_causal(*, function, include_timepoints, weights_function, + delta_weights_function, cfun, rfun, delta_rfun, analysis_rfun, + feeding_rfun, analysis_params, feeding_params, events, T, + n_subjects, include_zero, min_samples): + """ + The checks of ``features`` and ``two_path_step`` with ``causal=True`` + (``function``: the name of the caller, for the messages), before + anything is computed. ``analysis_rfun`` and ``feeding_rfun`` are the + resolved reducers by order, ``analysis_params`` and ``feeding_params`` + the kernel parameters GIVEN for each order (None: not given), + ``events`` the specifications to check (one per order that has one). + + Raises ``ValueError`` for what has no causal form (a forward kernel, + ``eye_weights``, kernel parameters that are not given, the default + subject weights of ``wisfc``, events given as features, a + ``min_samples`` no row of a built-in kernel can reach) and + ``NotImplementedError`` for a reducer that is fitted to data; warns once + when ``cfun`` or a reducer is a function of the user's. + """ + side = str(include_timepoints).lower() + if side in ("forward", "post"): + raise ValueError( + f"causal=True: include_timepoints={include_timepoints!r} weights " + "later timepoints. Leave include_timepoints out (causal=True uses " + "'backward' on both paths), or pass causal=False." + ) + for name, kernel in (("weights_function", weights_function), + ("delta_weights_function", delta_weights_function)): + if kernel is eye_weights: + raise ValueError( + f"causal=True: {name}=eye_weights gives co-fluctuations of series " + "z-scored over the whole recording, which use later timepoints. " + f"Pass a kernel with a width, for example {name}=" + f"tc.gaussian_weights with {name.replace('function', 'params')}=" + "{'var': 25}." + ) + for name, params in (("weights_params", analysis_params), + ("delta_weights_params", feeding_params)): + for k in sorted(params): + if params[k] is None: + raise ValueError( + f"causal=True: {name} must be given for every order (kernel " + "widths are not chosen from the data, which would read later " + f"timepoints); order {k} has none. Pass for example " + f"{name}={{'var': 25}} for a Gaussian kernel, {{}} for a " + "kernel without parameters, or in features an order map " + "that names every order." + ) + if cfun is wisfc or ( + isinstance(cfun, functools.partial) and cfun.func is wisfc + and not _fixed_weights_wisfc(cfun) + ): + raise ValueError( + "causal=True: the default subject_weights of wisfc are computed " + "from every timepoint of the recording. Pass cfun=" + "functools.partial(tc.wisfc, subject_weights=...) with weights of " + "your own and nothing else bound, or cfun=tc.isfc." + ) + for spec in events: + if _has_features(_parse_spec(spec, T, n_subjects)): + raise ValueError( + "causal=True: events given as features are segmented from the " + "whole recording. Pass the boundaries (the timepoints where a " + "new block starts), for example events=[100, 250]." + ) + for name, given, resolved in (("rfun", rfun, analysis_rfun), + ("delta_rfun", delta_rfun, feeding_rfun)): + for k in sorted(resolved): + if _needs_fit(resolved[k]): + raise NotImplementedError( + f"causal=True: {name}={_requested(given, k)!r} (order {k}) is " + "fitted to data and needs fit_timepoints (the rows it is " + f"fitted on), which {function} does not accept yet. Pass " + "rfun and delta_rfun as None or a graph measure such as " + "'strength' (the defaults are fitted)." + ) + if min_samples is not None: + # a number no kernel row can reach, whatever the length of the data + for kernel, params in ((weights_function, analysis_params), + (delta_weights_function, feeding_params)): + kernel = gaussian_weights if kernel is None else kernel + for k in sorted(params): + lag_kernel = _lag_kernel(2, kernel, params[k], "backward", include_zero) + if lag_kernel is not None: + _check_reachable(lag_kernel, min_samples) + builtin = cfun is None or cfun in (isfc, autofc) or _fixed_weights_wisfc(cfun) + theirs = [name for name, ours in ( + ("cfun", builtin), + ("rfun", not any(callable(r) for r in analysis_rfun.values())), + ("delta_rfun", not any(callable(r) for r in feeding_rfun.values())), + ) if not ours] + if theirs: + one = len(theirs) == 1 + _warn_user( + f"causal=True: {', '.join(theirs[:-1])}{'' if one else ' and '}" + f"{theirs[-1]} {'is a function' if one else 'are functions'} of your " + "own; the guarantee that row t does not depend on later rows does " + f"not cover what {'it does' if one else 'they do'}." + ) + + def _requested(value, k): """The reducer given for order ``k`` (an order map's value, or ``"auto"``).""" if isinstance(value, dict) and "model" not in value: @@ -2057,15 +2315,33 @@ def _step_info(k, inputs, x, delta, analysis_rfun, feeding_rfun, requested, return entries -def _constant_columns(out): +def _constant_columns(out, causal=False): """ The columns of an output that are constant over time (``np.ptp(x, axis=0) == 0``), as a list of ints; for a list of arrays, - one such list per array. + one such list per array. ``causal``: over the rows that are not + entirely NaN (the warm-up rows of the causal estimator are left out; an + output without any other row has no constant column). + """ + if isinstance(out, list): + return [_constant_columns(x, causal) for x in out] + x = np.asarray(out) + if causal: + x = x[~np.isnan(x).all(axis=1)] + if not x.shape[0]: + return [] + return np.flatnonzero(np.ptp(x, axis=0) == 0).tolist() + + +def _warmup_rows(out): + """ + The number of rows of an output that are entirely NaN (the rows the + causal estimator leaves undefined), as an int; for a list of arrays, + one int per array. """ if isinstance(out, list): - return [_constant_columns(x) for x in out] - return np.flatnonzero(np.ptp(np.asarray(out), axis=0) == 0).tolist() + return [_warmup_rows(x) for x in out] + return int(np.isnan(np.asarray(out)).all(axis=1).sum()) def _check_events_order_zero(events, T, n_subjects, events_params): @@ -2107,6 +2383,8 @@ def features( delta_weights_function=None, delta_weights_params=None, return_info=False, + causal=False, + min_samples=None, ): """ Compute features of every order from 0 to ``order`` with the two-path pipeline. @@ -2406,7 +2684,66 @@ def features( list per subject when the output is a list; for feeding features that are not returned (``return_delta=False``), in the rows computed. No arrays: numbers, strings, None and lists of ints. + With ``causal=True`` every entry also has ``"weights_params"`` (a + dict: the kernel parameters of that step) and ``"warmup_rows"`` (the + number of rows of the step's output that are entirely NaN, an int, + or one int per subject when the output is a list), and + ``"constant_columns"`` is taken over the other rows. Default: False. + causal : bool + If True (keyword-only), row ``t`` of every output is computed from + rows ``0..t`` of the data only: it is unchanged (to 1e-9; bit for + bit when later rows are replaced) when later rows are replaced by + any values, NaN and inf included, or removed, and with + ``include_zero=False`` also when row ``t`` itself changes. + Default: False. With ``causal=True``: + + - both paths use backward kernels (``include_timepoints`` may be + left out; ``"forward"``/``"post"`` raises ``ValueError``), and + the correlations are those of the causal estimator (see + ``timecorr`` and ``wcorr``): infinite samples and samples above + 1e150 in magnitude are missing, like NaN; + - the kernel parameters of both paths must be given + (``weights_params`` and ``delta_weights_params``, for every order when they are order maps): + widths are not chosen from the data. ``eye_weights`` on either + path raises ``ValueError`` (co-fluctuations use series z-scored + over the whole recording); + - ``rfun`` and ``delta_rfun`` must be given as None or a graph + measure (``"strength"``, ``"eigenvector_centrality"``, + ``"pagerank_centrality"``, ``"pagerank_centrality_abs"``), + also in order maps: a reducer that is fitted to data (a model such + as ``"PCA"``, a summary, and ``"auto"``, the default) raises + ``NotImplementedError``. A function of your own (as ``cfun``, + ``rfun`` or ``delta_rfun``) is called as without ``causal``, with + one ``UserWarning`` that the guarantee does not cover what it + does; + - ``cfun=tc.wisfc`` raises ``ValueError`` (its default subject + weights use the whole recording); + ``functools.partial(tc.wisfc, subject_weights=...)`` is accepted; + - ``events`` must be boundaries (features to segment raise + ``ValueError``); that the boundaries are known at their own time + is the caller's responsibility, and the warm-up starts again at + each boundary; + - a row with too few earlier samples (see ``min_samples``) is NaN + in every column, not 0. The NaN rows of an order's feeding + features are missing data for the next order, so each order has + more of them than the one before; graph measures are computed + for the other rows. A series of any length runs, and its output + is the first rows of the output of a longer series; + - 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 that is constant + up to round-off; see ``wcorr``). + min_samples : float or None + With ``causal=True`` (keyword-only), a timepoint with fewer than 3 + observed timepoints in its kernel row is undefined (NaN). A number + (>= 1) is also the effective sample size ``(sum |w|)**2 / sum + w**2`` a row needs over the observed timepoints it weights, on both + paths and at every order (see ``timecorr``); a number that a built-in + kernel of the call cannot reach with any number of earlier + timepoints raises ``ValueError`` before anything is computed. + Given without ``causal=True``, it raises ``ValueError``. Default: + None. Returns ------- @@ -2481,6 +2818,16 @@ def features( segmented) before anything is computed. RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. + ValueError + With ``causal=True``, before anything is computed: for the + arguments listed under ``causal`` that have no causal form, and + for a ``min_samples`` that is not None or a finite number >= 1 or + that a built-in kernel of the call cannot reach; for + ``min_samples`` given without ``causal=True``. + NotImplementedError + With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is + fitted to data (the defaults included); it would need + ``fit_timepoints``, the rows it is fitted on. TypeError If ``rfun`` or ``delta_rfun`` is not None, a string, a dict or a callable, or ``delta_weights_function`` is not None or callable. @@ -2680,6 +3027,24 @@ def features( ... delta_weights_function=tc.eye_weights, return_delta=True) >>> X[1].shape, D[1].shape ((50, 6), (50, 6)) + + Causal features: row ``t`` uses rows ``0..t`` of the data only. The + kernel parameters of both paths and reducers that are not fitted are + given; the first rows have too few earlier samples and are NaN, more of + them at each order (a ``UserWarning`` per step says so): + + >>> x = np.random.RandomState(1).randn(200, 5) + >>> kw = dict(order=2, causal=True, cfun=tc.autofc, rfun="strength", + ... delta_rfun="strength", weights_params={"var": 25}, + ... delta_weights_params={"var": 25}) + >>> X, info = tc.features(x, return_info=True, **kw) + >>> [(e["order"], e["path"], e["warmup_rows"]) for e in info] + [(1, 'analysis', 2), (1, 'feeding', 2), (2, 'analysis', 4)] + >>> later = x.copy() + >>> later[101:] = 1000.0 + >>> changed = tc.features(later, **kw) + >>> bool(np.array_equal(changed[2][:101], X[2][:101], equal_nan=True)) + True """ if ( not isinstance(order, numbers.Integral) @@ -2688,6 +3053,7 @@ def features( ): raise ValueError(f"order must be a non-negative integer; got {order!r}.") order = int(order) + min_samples = _check_min_samples(min_samples, causal) # every reducer is checked and resolved here, including ones a short run # never calls orders = range(1, order + 1) @@ -2736,6 +3102,20 @@ def features( delta_unreduced = all(feeding_rfun[k] is None for k in orders) S = len(subjects) + estimator = {} + if causal: + _check_causal( + function="features", include_timepoints=include_timepoints, + weights_function=weights_function, + delta_weights_function=delta_weights_function, cfun=cfun, rfun=rfun, + delta_rfun=delta_rfun, analysis_rfun=analysis_rfun, + feeding_rfun=feeding_rfun, analysis_params=analysis_params, + feeding_params=given_feeding, + events=list(events.values()) if isinstance(events, dict) else [events], + T=T, n_subjects=S, include_zero=include_zero, min_samples=min_samples, + ) + include_timepoints = "backward" + estimator = {"causal": True, "min_samples": min_samples} # events are resolved (and features segmented) once, before anything is computed if order == 0: _check_events_order_zero(events, T, S, events_params) @@ -2759,7 +3139,7 @@ def features( # widths are known in advance: refuse before computing anything kernels = dict( kernel_feeding=feeding_function is not eye_weights, - dense=_dense_analysis(weights_function, cfun), + dense=_dense_analysis(weights_function, cfun, causal), combine=combine, dense_feeding=not _builtin_kernel(feeding_function), ) @@ -2852,6 +3232,7 @@ def features( input_elements=0 if k == 1 else _output_elements(fed_by), reducers=held_reducers, previous_communities=previous_communities, + **estimator, ) X.append(x) computed_at.append(rows) @@ -2874,11 +3255,17 @@ def features( if params is not None: entry["kernel_sd"] = _bandwidth(gaussian_weights, params) entry["sampling"] = int(rows[1] - rows[0]) if len(rows) > 1 else 1 + if causal: + # the kernel parameters of the step (copies) + for entry, params in zip(entries, (analysis_params[k], + feeding_params[k])): + entry["weights_params"] = dict(params) if delta is not None and not return_delta: # feeding features that are not returned: as computed - entries[-1]["constant_columns"] = _constant_columns( - delta[0] if single else delta - ) + computed = delta[0] if single else delta + entries[-1]["constant_columns"] = _constant_columns(computed, causal) + if causal: + entries[-1]["warmup_rows"] = _warmup_rows(computed) info.extend(entries) if delta is not None: fed_by = delta @@ -2913,6 +3300,8 @@ def features( for entry in info: if entry["path"] == "analysis" or return_delta: out = (X if entry["path"] == "analysis" else D)[entry["order"]] - entry["constant_columns"] = _constant_columns(out) + entry["constant_columns"] = _constant_columns(out, causal) + if causal: + entry["warmup_rows"] = _warmup_rows(out) return result, info return result From 9f02d23f98711161b33d34c383cc1c6a38b860b8 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 12:26:49 -0500 Subject: [PATCH 06/26] Tests: the keyword-only names of features and two_path_step include the 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_features.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_features.py b/tests/test_features.py index ae8c83b5..cecf5c00 100644 --- a/tests/test_features.py +++ b/tests/test_features.py @@ -721,10 +721,12 @@ def test_events_signatures_keep_positional_order(): # keyword-only arguments added later follow events and events_params later = ["delta_weights_function", "delta_weights_params"] + ( ["order"] if f is two_path_step else ["return_info"]) + # the arguments of the causal mode (0.4.0), keyword-only, come last + later += ["causal", "min_samples"] assert list(params) == positional + ["events", "events_params"] + later, ( f.__name__) assert all(params[n].kind == inspect.Parameter.KEYWORD_ONLY - for n in ("events", "events_params")), f.__name__ + for n in ["events", "events_params"] + later), f.__name__ assert params["events"].default is None assert params["events_params"].default is None From 77a2bb0ab77fbc4401bd6a2bdaff773f5e242388 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 12:48:47 -0500 Subject: [PATCH 07/26] Causal mode: prefixes run with the events of the whole series; reach 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 144 +++++++++++++++++++++++++++++++++ tests/test_causal_features.py | 83 +++++++++++++++++-- timecorr/events.py | 67 +++++++++++---- timecorr/helpers.py | 123 +++++++++++++++++++++++++--- timecorr/higher_order.py | 55 +++++++++---- timecorr/timecorr.py | 39 ++++++--- 6 files changed, 453 insertions(+), 58 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 9b2424c4..f0771173 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -467,6 +467,98 @@ def reach(function, params, **kwargs): assert helpers._kernel_reach(kernel.with_events(labels)) == helpers._kernel_reach(kernel) +def _t_sums(df, start, n=4_000_000): + """Sums of the t density and of its square over the lags ``start..n``.""" + d = np.arange(start, n, dtype=np.float64) + w = (1 + d * d / df) ** (-(df + 1) / 2) + return w.sum(), (w * w).sum() + + +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("df", [1, 2, 5, 30]) +def test_heavy_tails_have_a_known_reach(df, include_zero): + kernel = helpers._lag_kernel(2, tc.t_weights, {"df": df}, "backward", include_zero) + limit = helpers._kernel_reach(kernel) + start = 0 if include_zero else 1 + if df == 1: + # the Cauchy sums in closed form: sum 1 / (1 + d**2) and + # sum 1 / (1 + d**2)**2 over d >= 0 + first = (1 + np.pi / np.tanh(np.pi)) / 2 + second = (1 + np.pi / 2 * (1 / np.tanh(np.pi) + np.pi / np.sinh(np.pi) ** 2)) / 2 + expected = (first - start) ** 2 / (second - start) + assert limit == pytest.approx(expected, rel=1e-12) + else: + # added up: the lags from 4 million on hold less than 1e-12 of the sums + first, second = _t_sums(df, start) + assert limit == pytest.approx(first**2 / second, rel=1e-10) + # decisive on both sides of the limit, in timecorr and in features, + # whatever the length of the series + for n in (20, 3): + x = np.random.default_rng(21).standard_normal((n, 3)) + calls = ( + lambda m: tc.timecorr( + x, causal=True, cfun=tc.autofc, weights_function=tc.t_weights, + weights_params={"df": df}, include_zero=include_zero, min_samples=m), + lambda m: tc.features( + x, order=1, causal=True, cfun=tc.autofc, rfun=None, delta_rfun=None, + weights_function=tc.t_weights, weights_params={"df": df}, + delta_weights_params={"var": 400}, include_zero=include_zero, + min_samples=m), + ) + for call in calls: + if limit * (1 - 1e-6) >= 1: + _quiet(call, limit * (1 - 1e-6)) + with pytest.raises(ValueError, match="min_samples.*more than a row"): + call(max(1.0, limit) * (1 + 1e-6)) + + +def test_an_unreachable_min_samples_never_gives_silent_nan_rows(): + # the case of a Cauchy kernel (at most 3.3 effective samples) + x = np.random.default_rng(22).standard_normal((20, 3)) + with pytest.raises(ValueError, match=r"min_samples=4 .*is 3\.3"): + tc.features(x, order=1, causal=True, cfun=tc.autofc, rfun=None, + delta_rfun=None, weights_function=tc.t_weights, + weights_params={"df": 1}, delta_weights_params={"var": 25}, + min_samples=4) + + def reach(function, params, include_zero=True): + return helpers._kernel_reach( + helpers._lag_kernel(5, function, params, "backward", include_zero)) + + # kernels far wider than the lags that are added up + assert reach(tc.boxcar_weights, {"width": 1e9}) == 5e8 + assert reach(tc.boxcar_weights, {"width": 1e9}, False) == 5e8 - 1 + for scale in (3.0, 3000.0, 1e9): # (1 + q) / (1 - q), q = exp(-1 / scale) + q = np.exp(-1 / scale) + assert reach(tc.laplace_weights, {"scale": scale}) == pytest.approx( + (1 + q) / -np.expm1(-1 / scale), rel=1e-9) + # sqrt(pi var) for the half of a wide Gaussian (plus half the lag-0 term) + assert reach(tc.gaussian_weights, {"var": 1e14}) == pytest.approx( + np.sqrt(np.pi * 1e14), rel=1e-6) + # an upper bound for a wide Mexican hat + a = np.abs(helpers.mexican_hat_profile(np.arange(100_000), {"sigma": 5000.0})) + most = np.nanmax(np.cumsum(a) ** 2 / np.cumsum(a * a)) + assert most <= reach(tc.mexican_hat_weights, {"sigma": 5000.0}) <= most * 1.01 + # every one of these decides: more than the reach raises + for function, params in ((tc.boxcar_weights, {"width": 1e9}), + (tc.laplace_weights, {"scale": 1e9}), + (tc.gaussian_weights, {"var": 1e14}), + (tc.mexican_hat_weights, {"sigma": 5000.0}), + (tc.t_weights, {"df": 0.5})): + most = reach(function, params) + kw = dict(causal=True, cfun=tc.autofc, weights_function=function, + weights_params=params) + with pytest.raises(ValueError, match="min_samples"): + tc.timecorr(x, min_samples=most * 1.02, **kw) + assert _quiet(tc.timecorr, x, min_samples=min(5, most * 0.9), + **kw).shape == (20, 6) + # equal weights at every lag have no limit: never an error + for m in (5, 1e6, 1e300): + out = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, min_samples=m, + weights_function=tc.uniform_weights, weights_params={}) + assert np.isnan(out[:4]).all() and np.isnan(out[5:]).all() == (m > 20) + + def test_three_equal_weights_are_three_samples(): x = np.random.default_rng(3).standard_normal((60, 4)) # a backward boxcar over the lags 0, 1, 2: three weights of 1 from row 2 on @@ -912,6 +1004,58 @@ def test_every_prefix_runs_and_equals_the_first_rows(case, include_zero, kernel) assert all(np.isnan(p).all() for p in one) +# name: (number of subjects, events). Boundaries at or beyond the end of a +# prefix are times it has not seen: the same ``events`` are passed to every +# prefix. +EVENTS = { + "shared": (1, [1, 5, 90, 210]), + "short-blocks": (1, [1, 2, 4, 7, 8, 150]), + "per-subject": (3, [[1, 60], None, [130, 131, 250]]), +} + + +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("cfun", ["autofc", "isfc", "smooth"]) +@pytest.mark.parametrize("events", sorted(EVENTS)) +def test_every_prefix_runs_with_the_events_of_the_whole_series(events, cfun, + include_zero): + n_subjects, spec = EVENTS[events] + data = _subjects(n_subjects, seed=61) + data = data[0] if n_subjects == 1 else data + kw = dict(causal=True, cfun={"autofc": tc.autofc, "isfc": tc.isfc, + "smooth": None}[cfun], + weights_params={"var": 25}, include_zero=include_zero, events=spec) + full = _quiet(tc.timecorr, data, **kw) + for n in list(range(1, 13)) + [60, 91, 131, 211, 251]: + part = _quiet(tc.timecorr, [x[:n] for x in _as_list(data)] + if n_subjects > 1 else data[:n], **kw) + assert all(np.asarray(p).shape[0] == n for p in _as_list(part)) + assert _max_difference(full, part, n) <= ATOL + # the boundaries the series has reached restrict its kernel + last = np.asarray(_as_list(full)[0]) + if cfun != "smooth": + assert np.isnan(last[1:3]).all() + + +def test_events_beyond_the_series_are_an_error_without_causal(): + x = np.random.default_rng(62).standard_normal((40, 3)) + with pytest.raises(ValueError, match=r"boundaries must lie in \[0, 40\)"): + tc.timecorr(x, events=[10, 40], weights_params={"var": 25}) + with pytest.raises(ValueError, match="no block is long enough"): + tc.timecorr(x[:2], events=[1], weights_params={"var": 25}, + include_timepoints="backward") + # with causal=True: ignored, and rows without 3 samples are NaN + out = _quiet(tc.timecorr, x, causal=True, events=[10, 40, 4000], + weights_params={"var": 25}) + same = _quiet(tc.timecorr, x, causal=True, events=[10], weights_params={"var": 25}) + assert np.array_equal(out, same, equal_nan=True) + assert np.isnan(_quiet(tc.timecorr, x[:2], causal=True, events=[1], + weights_params={"var": 25})).all() + # negative boundaries are an error either way + with pytest.raises(ValueError, match="boundaries must lie in"): + tc.timecorr(x, causal=True, events=[-1, 10], weights_params={"var": 25}) + + def test_one_row_of_a_wide_kernel_is_not_a_delta_kernel(): x = np.random.default_rng(70).standard_normal((30, 3)) # as arrays and through the correlation functions diff --git a/tests/test_causal_features.py b/tests/test_causal_features.py index 25efa30d..bf662f4a 100644 --- a/tests/test_causal_features.py +++ b/tests/test_causal_features.py @@ -98,6 +98,70 @@ def test_the_rule_applies_to_the_next_order_of_features(): assert _max_difference(X[1], part[1], n) <= ATOL +def _constant_feeding_column(relative, seed=3): + """A feeding reducer whose last output column is 3 to ``relative``.""" + noise = np.random.default_rng(seed).standard_normal(400) + + def reducer(arrays): + return [np.column_stack([a[:, 4:7], 3.0 * (1 + relative * noise[:len(a)])]) + for a in arrays] + + return reducer + + +@pytest.mark.parametrize("mode", ["finite", "nan", "inf", "remove"]) +def test_a_feeding_column_constant_to_round_off_is_zero_at_the_next_order(mode): + # the order-1 feeding features: three correlations and a column that is + # 3 up to a relative 1e-12 (the round-off of a summary that is not set to + # its mean in causal mode). At order 2 its correlations are 0, not + # correlations of that noise (which they are when the estimator's rule, + # helpers._causal_zero_variance, is taken out: 27% of them non-zero, up + # to 0.28), whatever comes later. + x = np.random.default_rng(4).standard_normal((200, 4)) + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun=None, + delta_rfun=_constant_feeding_column(1e-12), return_delta=True, + weights_params={"var": 25}, delta_weights_params={"var": 25}) + X, D = _quiet(tc.features, x, **kw) + column = D[1][2:, 3] + assert 0 < np.ptp(column) < 1e-10 and np.all(np.abs(column - 3) < 1e-10) + second = tc.vec2mat(X[2][4:]) + assert np.all(second[3, :, :] == 0) and np.all(second[:, 3, :] == 0) + # the other feeding features keep their correlations + assert np.all(second[[0, 1, 2], [0, 1, 2], :] == 1) + assert np.mean(second[0, 1, :] != 0) > 0.99 + rng = np.random.default_rng(5) + for n in (5, 40, 129, 199): + part = _quiet(tc.features, _perturb(x, n, mode, rng), **kw) + assert _worst((X, D), part, n, (1, 2)) <= ATOL + if n > 5: + assert np.all(tc.vec2mat(part[0][2][4:n])[3] == 0) + # a column that varies by a relative 1e-6 is a signal: correlated + kw["delta_rfun"] = _constant_feeding_column(1e-6) + varying = tc.vec2mat(_quiet(tc.features, x, **kw)[0][2][4:]) + assert np.mean(varying[3, 0, :] != 0) > 0.99 + + +def test_duplicated_features_give_a_constant_feeding_column(): + # a real case: feature 1 is an affine function of feature 0, so their + # order-1 correlation is 1 up to round-off at every timepoint; at order + # 2 that feeding column has no correlation with any other + x = np.random.default_rng(6).standard_normal((200, 4)) + x[:, 1] = 2 * x[:, 0] + 3 + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun=None, delta_rfun=None, + return_delta=True, weights_params={"var": 25}, + delta_weights_params={"var": 25}) + X, D = _quiet(tc.features, x, **kw) + pair = 4 # mat2vec: the 4 diagonal entries, then the pair (0, 1) + assert np.max(np.abs(D[1][2:, pair] - 1)) < 1e-12 + second = tc.vec2mat(X[2][4:]) + assert np.all(np.delete(second[pair], pair, axis=0) == 0) + rng = np.random.default_rng(7) + for mode in MODES: + for n in (40, 129): + part = _quiet(tc.features, _perturb(x, n, mode, rng), **kw) + assert _worst((X, D), part, n, (1, 2)) <= ATOL + + # ---------------------------------------------------------------------------- # the guarantee # ---------------------------------------------------------------------------- @@ -135,6 +199,10 @@ def test_the_rule_applies_to_the_next_order_of_features(): "events-by-order": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS, events={1: [150], 3: [60, 100]})), "min-samples": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS, min_samples=6)), + "events-short": (1, 5, 3, dict(cfun=tc.autofc, **STRENGTH, **PARAMS, + events={1: [1, 2, 4, 7, 8, 150], 2: [1, 100]})), + "events-per-subject": (3, 5, 3, dict(cfun=tc.isfc, **STRENGTH, **PARAMS, + events=[[1, 60], None, [130, 131, 250]])), "isfc": (3, 5, 3, dict(cfun=tc.isfc, **STRENGTH, **PARAMS)), "isfc-unreduced": (3, 4, 2, dict(cfun=tc.isfc, **UNREDUCED, **PARAMS)), "isfc-corrmean": (3, 5, 3, dict(cfun=tc.isfc, combine=tc.corrmean_combine, @@ -169,13 +237,15 @@ def _within(events, n): """Boundaries of a series cut to ``n`` rows (the later ones are not in it).""" if isinstance(events, dict): return {k: _within(v, n) for k, v in events.items()} + if any(e is None or isinstance(e, list) for e in events): # one entry per subject + return [None if e is None else _within(e, n) for e in events] kept = [b for b in events if b < n] return kept or None -def _run(data, config, order=None, **kwargs): +def _run(data, config, order=None, all_events=False, **kwargs): highest, kw = CONFIGS[config][2:] - if "events" in kw: + if "events" in kw and not all_events: kw = {**kw, "events": _within(kw["events"], len(_as_list(data)[0]))} return _quiet(tc.features, data, order=highest if order is None else order, causal=True, return_delta=True, **{**kw, **kwargs}) @@ -253,16 +323,19 @@ def test_order_four_unreduced(include_zero, mode): @pytest.mark.parametrize("config", ["unreduced", "strength", "eigenvector", "laplace", "boxcar", "isfc", "isfc-corrmean", "wisfc", - "min-samples"]) + "min-samples", "events", "events-by-order", + "events-short", "events-per-subject"]) @pytest.mark.parametrize("include_zero", [True, False]) def test_every_prefix_runs_and_equals_the_first_rows(config, include_zero): data = _data(config, seed=30) orders = range(1, 4) if CONFIGS[config][2] >= 3 else range(1, 3) full = _run(data, config, order=orders[-1], include_zero=include_zero) atol = REMOVE_ATOL.get(config, ATOL) - for n in list(range(1, 13)) + [20, 64, 130, 257]: + for n in list(range(1, 13)) + [20, 64, 91, 130, 211, 257]: + # every prefix gets the events of the whole series: the boundaries + # it has not reached are ignored part = _run(_map(data, lambda x: x[:n]), config, order=orders[-1], - include_zero=include_zero) + include_zero=include_zero, all_events=True) for out in part: assert all(a.shape[0] == n for k in orders for a in _as_list(out[k])) assert _worst(full, part, n, orders) <= atol diff --git a/timecorr/events.py b/timecorr/events.py index e2cd0179..168d9594 100644 --- a/timecorr/events.py +++ b/timecorr/events.py @@ -82,6 +82,16 @@ def check_boundaries(b, T): >>> check_boundaries([7, 3, 3, 5], 10) array([0, 3, 5, 7]) """ + return _boundaries(b, T) + + +def _boundaries(b, T, causal=False): + """ + ``check_boundaries``; with ``causal`` (the causal mode of ``timecorr`` + and ``features``), boundaries at or beyond ``T`` are left out instead of + raising: they are times the series has not reached, so a prefix of a + series takes the events of the whole series. + """ T = _check_T(T) if pl is not None and isinstance(b, pl.Series): arr = b.to_numpy() @@ -102,6 +112,10 @@ def check_boundaries(b, T): return np.zeros(1, dtype=np.int64) if not np.issubdtype(arr.dtype, np.integer): raise ValueError(f"boundaries must have an integer dtype, got {arr.dtype}") + if causal and arr.min() >= 0: + arr = arr[arr < T] + if arr.size == 0: + return np.zeros(1, dtype=np.int64) if arr.min() < 0 or arr.max() >= T: raise ValueError( f"boundaries must lie in [0, {T}), got values from {arr.min()} to {arr.max()}" @@ -158,8 +172,9 @@ def _is_single_entry(x): return pl is not None and isinstance(x, (pl.DataFrame, pl.Series)) -def _parse_entry(x, T): - """Parse one entry: None, boundaries, or features. Returns array, None or _Features.""" +def _parse_entry(x, T, causal=False): + """Parse one entry: None, boundaries, or features. Returns array, None or _Features. + ``causal``: see ``_boundaries``.""" if x is None: return None if _is_features_array(x): @@ -171,10 +186,10 @@ def _parse_entry(x, T): ) return _Features(x) if _is_single_entry(x): - return check_boundaries(x, T) # 1-D (or an error for other shapes) + return _boundaries(x, T, causal) # 1-D (or an error for other shapes) if isinstance(x, (list, tuple)): if all(_is_int_scalar(e) for e in x): - return check_boundaries(list(x), T) + return _boundaries(list(x), T, causal) raise ValueError( "an events entry that is a list must hold only integer boundaries; " "pass features as an array or DataFrame" @@ -185,8 +200,9 @@ def _parse_entry(x, T): ) -def _parse_spec(events, T, n_subjects): - """Parse a specification for one order into array, None, list, or _Features entries.""" +def _parse_spec(events, T, n_subjects, causal=False): + """Parse a specification for one order into array, None, list, or _Features entries. + ``causal``: see ``_boundaries``.""" if events is None: return None if isinstance(events, dict): @@ -196,10 +212,10 @@ def _parse_spec(events, T, n_subjects): "weighted_timepoint_decoder_ec); here, pass one events specification" ) if _is_single_entry(events): - return _parse_entry(events, T) + return _parse_entry(events, T, causal) if isinstance(events, (list, tuple)): if all(_is_int_scalar(e) for e in events): - return check_boundaries(list(events), T) + return _boundaries(list(events), T, causal) # scalars are checked before the length, so that a list of non-integer # scalars gets this message whatever its length for i, e in enumerate(events): @@ -215,7 +231,7 @@ def _parse_spec(events, T, n_subjects): f"per-subject events must have one entry per subject: got {len(events)} " f"entries for {n_subjects} subjects" ) - return [_parse_entry(e, T) for e in events] + return [_parse_entry(e, T, causal) for e in events] raise ValueError( f"events must be None, boundaries, features, or a per-subject list; " f"got {type(events).__name__}" @@ -287,7 +303,7 @@ def one(p): return one(parsed) -def resolve_events(events, T, n_subjects, events_params=None): +def resolve_events(events, T, n_subjects, events_params=None, *, causal=False): """ Parse the event specification for one order. @@ -310,6 +326,11 @@ def resolve_events(events, T, n_subjects, events_params=None): Keyword arguments for :func:`segment` when an entry holds features. Allowed keys are ``n``, ``kind``, ``max_events`` and ``random_state``. Unknown keys, or giving this when no entry holds features, raise ``ValueError``. + causal : bool + If True (keyword-only; the causal mode of ``timecorr`` and ``features``), boundaries + at or beyond ``T`` are left out instead of raising ``ValueError``: they are times the + series has not reached, so a prefix of a series takes the events of the whole + series. Default: False. Returns ------- @@ -337,7 +358,7 @@ def resolve_events(events, T, n_subjects, events_params=None): """ params = events_params _check_params_keys(params) - parsed = _parse_spec(events, _check_T(T), _check_n_subjects(n_subjects)) + parsed = _parse_spec(events, _check_T(T), _check_n_subjects(n_subjects), causal) if params and not _has_features(parsed): raise ValueError("events_params was given but no events entry holds features") return _finish(parsed, params, {}) @@ -349,7 +370,8 @@ def _order_key(k, order): return int(k) -def resolve_events_by_order(events, T, n_subjects, order, events_params=None): +def resolve_events_by_order(events, T, n_subjects, order, events_params=None, *, + causal=False): """ Parse the event specification for orders ``1..order``. @@ -367,6 +389,8 @@ def resolve_events_by_order(events, T, n_subjects, order, events_params=None): As in :func:`resolve_events`. When ``events`` is a dict, ``events_params`` may instead be a dict keyed by order whose values are dicts of segmentation parameters; each such order must hold features. + causal : bool + As in :func:`resolve_events` (keyword-only). Default: False. Returns ------- @@ -394,7 +418,8 @@ def resolve_events_by_order(events, T, n_subjects, order, events_params=None): specs[_order_key(k, order)] = v else: specs = {k: events for k in range(1, order + 1)} - parsed = {k: _parse_spec(specs.get(k), T, n_subjects) for k in range(1, order + 1)} + parsed = {k: _parse_spec(specs.get(k), T, n_subjects, causal) + for k in range(1, order + 1)} flat, by_order = None, None if events_params is not None: @@ -475,13 +500,24 @@ def mask_kernel(weights, boundaries): >>> masked[0].astype(int), masked[5].astype(int) (array([1, 1, 1, 0, 0, 0]), array([0, 0, 0, 1, 1, 1])) """ + return _mask_kernel(weights, boundaries) + + +def _mask_kernel(weights, boundaries, check=True): + """ + ``mask_kernel``. ``check=False`` (the causal mode of ``timecorr`` and + ``features``): a kernel whose blocks are all too short for a correlation + is returned, not refused; its rows are undefined (NaN) there, as the + first rows of every block are. + """ if boundaries is None: return weights if isinstance(weights, LagKernel): # the kernels of timecorr, features and the decoders: rows computed # when read, so no T x T array is built here either out = weights.with_events(block_labels(boundaries, weights.T)) - if weights.max_row_support(CHUNK) >= 2 and out.max_row_support(CHUNK) < 3: + if (check and weights.max_row_support(CHUNK) >= 2 + and out.max_row_support(CHUNK) < 3): raise ValueError(_TOO_SHORT) return out w = np.asarray(weights) @@ -491,7 +527,8 @@ def mask_kernel(weights, boundaries): labels = block_labels(boundaries, T) same = labels[:, None] == labels[None, :] out = np.where(same, w, np.zeros((), dtype=w.dtype)) - if np.sum(w != 0, axis=1).max() >= 2 and np.sum(out != 0, axis=1).max() < 3: + if (check and np.sum(w != 0, axis=1).max() >= 2 + and np.sum(out != 0, axis=1).max() < 3): raise ValueError(_TOO_SHORT) return out diff --git a/timecorr/helpers.py b/timecorr/helpers.py index 70c62d62..d1690eb8 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -1504,6 +1504,83 @@ def _check_min_samples(min_samples, causal): _REACH_LAGS = 2 ** 22 +def _profile_tails(profile, n): + """ + ``(sum of |w|, sum of w**2)`` over the lags ``n, n + 1, ...`` of the lag + profile of a built-in kernel function, from the profile's formula (the + sums over a heavy or very wide tail converge too slowly to be added + up), or None when there is no formula (or the tail has no end: + ``uniform_weights``). + + - ``laplace_weights``: the two geometric series, exactly. + - ``boxcar_weights``: the number of lags below ``width / 2``, exactly. + - ``t_weights`` and ``gaussian_weights`` (densities): the integral of + the tail from the survival function, with the first two terms of the + Euler-Maclaurin formula (``f(n) / 2 - f'(n) / 12``); the square of + either density is a multiple of a density of the same family. + - ``mexican_hat_weights``, for ``n >= 2 sigma`` (where ``|w|`` + decreases): an upper bound of the sum of ``|w|``, and 0 for the sum + of squares, so that the reach computed from them is an upper bound. + """ + from scipy.stats import norm, t as student + + family = getattr(profile, "func", None) + params = (getattr(profile, "keywords", None) or {}).get("params") + if params is None: + return None + n = int(n) + + def value(x): + return float(profile(np.array([float(x)]))[0]) + + with np.errstate(all="ignore"): + if family is boxcar_profile: + last = float(params["width"]) / 2.0 # lags d < last have weight 1 + if np.isnan(last): + return None + count = np.inf if np.isinf(last) and last > 0 else max( + 0.0, float(np.ceil(last)) - n) + return count, count + if family is laplace_profile: + scale = float(params["scale"]) + if not (np.isfinite(scale) and scale > 0): + return None + f = abs(value(n)) + return f / -np.expm1(-1.0 / scale), f * f / -np.expm1(-2.0 / scale) + if family is gaussian_profile: + var = float(params["var"]) + if not (np.isfinite(var) and var > 0): + return None + f = value(n) + slope = -n / var * f + first = norm.sf(n / np.sqrt(var)) + f / 2 - slope / 12 + second = (norm.sf(n / np.sqrt(var / 2)) / (2 * np.sqrt(np.pi * var)) + + f * f / 2 - 2 * f * slope / 12) + return float(first), float(second) + if family is t_profile: + df = float(params["df"]) + f, peak = value(n), value(0) + if not (np.isfinite(df) and df > 0 and np.isfinite(peak) and peak > 0): + return None + slope = f * (-(df + 1) * n / df) / (1 + n * n / df) + first = student.sf(n, df) + f / 2 - slope / 12 + # the squared density is a t density of 2 df + 1 degrees of + # freedom on a rescaled axis + df2 = 2 * df + 1 + second = (peak * peak * np.sqrt(df / df2) + * student.sf(n * np.sqrt(df2 / df), df2) / student.pdf(0, df2) + + f * f / 2 - 2 * f * slope / 12) + return float(first), float(second) + if family is mexican_hat_profile: + sigma = abs(float(params["sigma"])) + if not (np.isfinite(sigma) and sigma > 0) or n < 2 * sigma: + return None + # the integral of |w| from n on is n |w(n)| / (n**2 / sigma**2 - 1) + f = abs(value(n)) + return f + n * f / (n * n / (sigma * sigma) - 1), 0.0 + return None + + def _kernel_reach(kernel): """ The largest effective sample size ``(sum |w|)**2 / sum w**2`` a row of a @@ -1512,10 +1589,21 @@ def _kernel_reach(kernel): ``exclude_timepoints``), for every n. It does not depend on the length of the series. - None when it is not known or has no limit: a kernel without a lag - profile function (an array, a kernel function of the user's), and a - profile whose sums have not converged within ``_REACH_LAGS`` lags - (``uniform_weights``). The result is kept on the kernel. + The sums are added up over the first lags; when they have not converged + there (a heavy tail, as of ``t_weights`` with few degrees of freedom, or + a very wide kernel), the rest comes from the profile's formula + (``_profile_tails``), so the result is known for every built-in kernel + function and parameter value: exactly for ``boxcar_weights`` and + ``laplace_weights``, to round-off of the tail formula for + ``gaussian_weights`` and ``t_weights``, and as an upper bound for a + ``mexican_hat_weights`` wider than about 1000 samples. + + None when it has no limit (``uniform_weights``: the effective sample + size grows with the number of earlier timepoints) or is not known: a + kernel without a lag profile function (an array, a kernel function of + the user's), a ``mexican_hat_weights`` with sigma above 2 million + samples, and a kernel that is both wider than the lags added up and + restricted by ``exclude_timepoints``. The result is kept on the kernel. """ profile = getattr(kernel, "lag_profile", None) if profile is None or kernel.include != "backward": @@ -1525,7 +1613,8 @@ def _kernel_reach(kernel): return cached[0] reach = None n = 1024 - while n <= _REACH_LAGS: + unbounded = getattr(profile, "func", None) is uniform_profile + while n <= _REACH_LAGS and not unbounded: with np.errstate(over="ignore", invalid="ignore"): a = np.abs(np.asarray(profile(np.arange(n, dtype=np.int64)), dtype=np.float64)) a[~np.isfinite(a)] = 0 @@ -1542,16 +1631,27 @@ def _kernel_reach(kernel): a /= peak # so that tiny weights do not underflow when squared total = np.cumsum(a) squares = np.cumsum(a * a) + with np.errstate(invalid="ignore", divide="ignore"): + ess = total**2 / squares # converged: the later half of the lags adds nothing to the sums if total[-1] - total[n // 2 - 1] <= 1e-15 * total[-1]: - with np.errstate(invalid="ignore", divide="ignore"): - ess = total**2 / squares reach = float(np.nanmax(ess)) break + # not converged: the rest of the sums from the profile's formula + # (not with exclude_timepoints, which cuts the tail) + tails = _profile_tails(profile, n) if kernel.exclude is None else None + if tails is not None: + first, second = tails[0] / peak, tails[1] / peak**2 + with np.errstate(invalid="ignore", divide="ignore"): + limit = (total[-1] + first) ** 2 / (squares[-1] + second) + reach = float(np.nanmax([np.nanmax(ess), limit])) + break n *= 2 else: - if peak == 0: + if not unbounded and peak == 0: reach = 0.0 + if reach is not None and np.isinf(reach): + reach = None # no limit (a boxcar of infinite width) kernel._reach = (reach,) return reach @@ -1628,10 +1728,13 @@ def _check_causal_rows(rows): length of the series. The one row of a series of one timepoint has a single weight whatever the kernel: it is a delta kernel only when the kernel's lag profile says so (``_kernel_reach`` of at most 1), so a - prefix of a series is never refused where the series is not. + prefix of a series is never refused where the series is not; the same + holds for a built-in kernel whose rows are cut by events. """ delta = bool(rows.support.size) and bool(np.all(rows.support == 1)) - if delta and rows.shape[0] == 1: + if delta and (rows.shape[0] == 1 or getattr(rows.kernel, "labels", None) is not None): + # one row, or rows cut by events (blocks of one timepoint): the + # kernel's own lag profile decides reach = _kernel_reach(rows.kernel) delta = reach is not None and reach <= 1 + _MIN_SAMPLES_RTOL if delta: diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index 4c19c48c..a1e920b4 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -688,18 +688,20 @@ def _bandwidth(weights_function, weights_params): def _step_kernels(T, n_subjects, weights_function, weights_params, - include_timepoints="all", include_zero=True, events=None): + include_timepoints="all", include_zero=True, events=None, + causal=False): """ The kernel(s) ``timecorr`` builds for these arguments and RESOLVED events: one kernel, or one per subject when the subjects' events differ (``LagKernel`` objects for a built-in kernel function, T x T arrays - otherwise). + otherwise). ``causal``: as ``timecorr(..., causal=True)`` builds them. """ weights = _shaped_kernel( - T, weights_function, weights_params, include_timepoints, include_zero + T, weights_function, weights_params, include_timepoints, include_zero, + causal=causal, ) - resolved = resolve_events(events, T, n_subjects, None) - return _event_kernels(weights, resolved, n_subjects) + resolved = resolve_events(events, T, n_subjects, None, causal=causal) + return _event_kernels(weights, resolved, n_subjects, causal) def _run_streamed(subjects, summary, cfun, kernels, *, max_memory_gb, order, path, @@ -1752,7 +1754,14 @@ def two_path_step( bit when later rows are replaced) when later rows are replaced by any values, NaN and inf included, or removed, and with ``include_zero=False`` also when row ``t`` itself changes. - Default: False. With ``causal=True``: + Replacing later rows changes no bit, with every supported reducer. + Removing them changes the correlations by round-off, so the + outputs agree to 1e-9 where they depend continuously on the + correlations (no reduction, ``"strength"``, the summaries, and + linear models such as PCA once fitted); the eigenvector-based + graph measures (``"eigenvector_centrality"``, the PageRank + measures) can differ by more at a correlation matrix whose leading + eigenvalues coincide. Default: False. With ``causal=True``: - both paths use backward kernels (``include_timepoints`` may be left out; ``"forward"``/``"post"`` raises ``ValueError``), and @@ -1778,7 +1787,11 @@ def two_path_step( - ``events`` must be boundaries (features to segment raise ``ValueError``); that the boundaries are known at their own time is the caller's responsibility, and the warm-up starts again at - each boundary; + each boundary. Boundaries at or beyond the end of the data are + ignored (times the series has not reached), and events that + leave no timepoint with 3 samples give rows of NaN, not an + error, so a prefix of a series runs with the events of the whole + series; - a row with too few earlier samples (see ``min_samples``) is NaN in every column, not 0. The NaN rows of an order's feeding features are missing data for the next order, so each order has @@ -1972,7 +1985,7 @@ def two_path_step( if feeding_auto is not None: feeding_params = feeding_auto resolved = resolve_events( - events, subjects[0].shape[0], len(subjects), events_params + events, subjects[0].shape[0], len(subjects), events_params, causal=causal ) X_next, D_next = _two_path_step( subjects, @@ -2210,7 +2223,7 @@ def _check_causal(*, function, include_timepoints, weights_function, "your own and nothing else bound, or cfun=tc.isfc." ) for spec in events: - if _has_features(_parse_spec(spec, T, n_subjects)): + if _has_features(_parse_spec(spec, T, n_subjects, True)): raise ValueError( "causal=True: events given as features are segmented from the " "whole recording. Pass the boundaries (the timepoints where a " @@ -2344,7 +2357,7 @@ def _warmup_rows(out): return int(np.isnan(np.asarray(out)).all(axis=1).sum()) -def _check_events_order_zero(events, T, n_subjects, events_params): +def _check_events_order_zero(events, T, n_subjects, events_params, causal=False): """ Check ``events`` / ``events_params`` for ``features(order=0)``, which has no kernel to restrict: a dict with any key raises, and a non-dict @@ -2358,7 +2371,7 @@ def _check_events_order_zero(events, T, n_subjects, events_params): ) events = None _check_params_keys(events_params) - parsed = _parse_spec(events, T, n_subjects) + parsed = _parse_spec(events, T, n_subjects, causal) if events_params and not _has_features(parsed): raise ValueError("events_params was given but no events entry holds features") @@ -2696,7 +2709,14 @@ def features( bit when later rows are replaced) when later rows are replaced by any values, NaN and inf included, or removed, and with ``include_zero=False`` also when row ``t`` itself changes. - Default: False. With ``causal=True``: + Replacing later rows changes no bit, with every supported reducer. + Removing them changes the correlations by round-off, so the + outputs agree to 1e-9 where they depend continuously on the + correlations (no reduction, ``"strength"``, the summaries, and + linear models such as PCA once fitted); the eigenvector-based + graph measures (``"eigenvector_centrality"``, the PageRank + measures) can differ by more at a correlation matrix whose leading + eigenvalues coincide. Default: False. With ``causal=True``: - both paths use backward kernels (``include_timepoints`` may be left out; ``"forward"``/``"post"`` raises ``ValueError``), and @@ -2723,7 +2743,11 @@ def features( - ``events`` must be boundaries (features to segment raise ``ValueError``); that the boundaries are known at their own time is the caller's responsibility, and the warm-up starts again at - each boundary; + each boundary. Boundaries at or beyond the end of the data are + ignored (times the series has not reached), and events that + leave no timepoint with 3 samples give rows of NaN, not an + error, so a prefix of a series runs with the events of the whole + series; - a row with too few earlier samples (see ``min_samples``) is NaN in every column, not 0. The NaN rows of an order's feeding features are missing data for the next order, so each order has @@ -3118,10 +3142,11 @@ def features( estimator = {"causal": True, "min_samples": min_samples} # events are resolved (and features segmented) once, before anything is computed if order == 0: - _check_events_order_zero(events, T, S, events_params) + _check_events_order_zero(events, T, S, events_params, causal) resolved = {} else: - resolved = resolve_events_by_order(events, T, S, order, events_params) + resolved = resolve_events_by_order(events, T, S, order, events_params, + causal=causal) # with both kernels automatic at every order, no events and two-sided # kernels, each order's feeding features are passed on at a lower rate diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 1a6393bd..36de0238 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -10,7 +10,7 @@ _has_features, _parse_spec, distinct_event_sets, - mask_kernel, + _mask_kernel, resolve_events, ) from .helpers import ( @@ -130,10 +130,10 @@ def one(b): return one(resolved) -def _mask_for_subjects(weights, boundaries, subjects): +def _mask_for_subjects(weights, boundaries, subjects, causal=False): """``mask_kernel`` for one event set; an error names the subjects that use it.""" try: - return mask_kernel(weights, boundaries) + return _mask_kernel(weights, boundaries, not causal) except ValueError as err: raise ValueError(f"per-subject events of subjects {subjects}: {err}") from err @@ -202,19 +202,20 @@ def _shaped_kernel( return weights -def _event_kernels(weights, resolved, n_subjects): +def _event_kernels(weights, resolved, n_subjects, causal=False): """ ``weights`` restricted to the RESOLVED events as ``timecorr`` restricts it: one masked kernel when every subject has the same events, otherwise a list of ``n_subjects`` kernels (subjects that share events share one - array). + array). ``causal``: events that leave no row with 3 weights are not an + error (a short prefix of a series; its rows are undefined). """ groups = distinct_event_sets(_restricted(resolved), n_subjects) if len(groups) == 1: - return mask_kernel(weights, groups[0][0]) + return _mask_kernel(weights, groups[0][0], not causal) kernels = [None] * n_subjects for boundaries, subjects in groups: - masked = _mask_for_subjects(weights, boundaries, subjects) + masked = _mask_for_subjects(weights, boundaries, subjects, causal) for s in subjects: kernels[s] = masked return kernels @@ -317,7 +318,7 @@ def _causal_arguments(weights_function, weights_params, include_timepoints, cfun "functools.partial(tc.wisfc, subject_weights=...) with weights of " "your own and nothing else bound, or cfun=tc.isfc." ) - if _has_features(_parse_spec(events, T, n_subjects)): + if _has_features(_parse_spec(events, T, n_subjects, True)): raise ValueError( "causal=True: events given as features are segmented from the whole " "recording. Pass the boundaries (the timepoints where a new block " @@ -506,8 +507,16 @@ def timecorr( True: row ``t`` of the output uses no sample after timepoint ``t``. It is unchanged (to 1e-9) when the rows after ``t`` are replaced by any values, NaN and inf included, or removed; with - ``include_zero=False`` also when row ``t`` itself changes. Keyword - only. Default: False. With ``causal=True``: + ``include_zero=False`` also when row ``t`` itself changes. + Replacing later rows changes no bit, with every supported ``rfun``. + Removing them changes the correlations by round-off, so the + outputs agree to 1e-9 where they depend continuously on the + correlations (no reduction, ``"strength"``, the summaries, and + linear models such as PCA once fitted); the eigenvector-based + graph measures (``"eigenvector_centrality"``, the PageRank + measures) can differ by more at a correlation matrix whose leading + eigenvalues coincide. Keyword only. Default: False. With + ``causal=True``: - the kernel is backward: ``include_timepoints`` 'all' (the default) means 'backward', and 'forward' / 'post' raise @@ -527,7 +536,11 @@ def timecorr( - ``events`` must be boundaries; features to segment raise ``ValueError``. That the boundaries themselves were chosen without later data is the caller's responsibility. The warm-up - below starts again at each boundary; + below starts again at each boundary. Boundaries at or beyond + the end of the data are ignored (times the series has not + reached), and events that leave no timepoint with 3 samples give + rows of NaN, not an error, so a prefix of a series runs with the + events of the whole series; - ``rfun`` is None, a graph measure (computed for the defined rows) or a callable; a reducer that is fitted to data (a model name, a summary) raises ``NotImplementedError``; @@ -740,8 +753,8 @@ def timecorr( # event restriction: applied after the include/exclude options; subjects that # share events share one masked kernel (one array, or a list per subject) - resolved = resolve_events(events, T, len(data), events_params) - kernels = _event_kernels(weights, resolved, len(data)) + resolved = resolve_events(events, T, len(data), events_params, causal=causal) + kernels = _event_kernels(weights, resolved, len(data), causal) per_subject = isinstance(kernels, list) if cfun: From cbea6ec2eb1adb14281d31cb133a07ad8b46aaf4 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 13:37:58 -0500 Subject: [PATCH 08/26] Causal mode: fit_timepoints freezes the fitted reducers; tc.FeaturesModel 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_api_docs.py | 1 + tests/test_causal_fit.py | 727 +++++++++++++++++++++++++++++++++++++++ tests/test_estimator.py | 3 +- tests/test_features.py | 3 +- timecorr/__init__.py | 1 + timecorr/helpers.py | 198 ++++++++--- timecorr/higher_order.py | 432 ++++++++++++++++++----- timecorr/model.py | 455 ++++++++++++++++++++++++ timecorr/summaries.py | 281 +++++++++++++-- timecorr/timecorr.py | 296 +++++++++++++++- 10 files changed, 2202 insertions(+), 195 deletions(-) create mode 100644 tests/test_causal_fit.py create mode 100644 timecorr/model.py diff --git a/tests/test_api_docs.py b/tests/test_api_docs.py index 32c4ef16..010a8ac0 100644 --- a/tests/test_api_docs.py +++ b/tests/test_api_docs.py @@ -25,6 +25,7 @@ "timecorr.timecorr", "timecorr.helpers", "timecorr.higher_order", + "timecorr.model", "timecorr.decoding", "timecorr.simulate", "timecorr.events", diff --git a/tests/test_causal_fit.py b/tests/test_causal_fit.py new file mode 100644 index 00000000..3bbbf0a0 --- /dev/null +++ b/tests/test_causal_fit.py @@ -0,0 +1,727 @@ +""" +Reducers fitted on the first rows and then frozen: ``fit_timepoints`` in +``timecorr``, ``features`` and ``two_path_step`` with ``causal=True``, and +``tc.FeaturesModel`` (``return_model=True``, ``transform``). + +The guarantee: the reducers are fitted on rows ``[0, fit_timepoints)`` only +(a fit does not change, bit for bit, whatever follows those rows), and every +output row t is unchanged (to 1e-9, NaN rows included; bit for bit under +replacement) when the input rows after t and at or after ``fit_timepoints`` +are replaced by other finite values, by NaN, by inf, or removed. Real +computations; nothing is mocked. +""" + +import inspect +import pickle +import subprocess +import sys +import warnings + +import hypertools as hyp +import numpy as np +import pytest + +import timecorr as tc +from timecorr.higher_order import two_path_step + +from .test_causal_estimator import ( + _as_list, + _max_difference, + _perturb, + _quiet, + _series, +) +from .test_causal_features import WISFC + +ATOL = 1e-9 +T, N = 240, 140 # timepoints, and the rows the reducers are fitted on +PARAMS = dict(weights_params={"var": 25}, delta_weights_params={"var": 16}) +MODES = ("finite", "nan", "inf", "remove") + + +def _modular(seed, n=T, modules=4, per=3): + """Modules of nodes that share a signal: communities for the feeding path.""" + rng = np.random.default_rng(seed) + shared = np.repeat(rng.standard_normal((n, modules)), per, axis=1) + return shared + 0.5 * rng.standard_normal((n, modules * per)) + + +# name: (subjects, data, features, highest order, arguments) +CONFIGS = { + # the defaults: PCA, then signed weighted strength; communities counted + # with the shift null on the feeding path (found at order 1, and the + # fallback to weighted strength at order 2) + "auto": (1, _modular, 12, 3, dict(cfun=tc.autofc)), + "auto-noise": (1, _series, 6, 3, dict(cfun=tc.autofc)), + "auto-isfc": (3, _modular, 12, 2, dict()), + "pca": (1, _series, 5, 3, dict(cfun=tc.autofc, rfun="PCA", delta_rfun=None)), + "pca-order-4": (1, _series, 4, 4, dict(cfun=tc.autofc, rfun="PCA", + delta_rfun=None)), + "models": (3, _series, 5, 2, dict(rfun={"model": "IncrementalPCA"}, + delta_rfun="FactorAnalysis", ndims=3)), + "strength": (1, _series, 6, 3, dict( + cfun=tc.autofc, rfun=tc.WeightedStrength(signed=True), + delta_rfun=tc.WeightedStrength())), + "strength-split": (1, _modular, 12, 2, dict( + cfun=tc.autofc, rfun=tc.WeightedStrength(split=True, n=3, center="median"), + delta_rfun="weighted_strength")), + "communities-2": (1, _modular, 12, 2, dict( + cfun=tc.autofc, rfun="weighted_strength", + delta_rfun={1: tc.Communities(n=2, signed=True), 2: "weighted_strength"})), + "communities": (1, _modular, 12, 2, dict( + cfun=tc.autofc, rfun={1: tc.Communities(n=4), 2: "weighted_strength"}, + delta_rfun={1: tc.Communities(), 2: "weighted_strength"})), + "isfc": (3, _series, 5, 3, dict(rfun="weighted_strength", + delta_rfun="weighted_strength")), + "wisfc": (3, _series, 5, 3, dict(cfun=WISFC, rfun=tc.WeightedStrength(signed=True), + delta_rfun="weighted_strength")), + "wisfc-corrmean": (3, _series, 5, 2, dict( + cfun=WISFC, combine=tc.corrmean_combine, rfun="PCA", + delta_rfun="weighted_strength")), + "autofc-subjects": (3, _series, 5, 2, dict( + cfun=tc.autofc, rfun="weighted_strength", + delta_rfun={1: tc.Communities(n=2), 2: "weighted_strength"})), + "events": (1, _series, 6, 2, dict( + cfun=tc.autofc, rfun="PCA", delta_rfun="weighted_strength", + events=[60, 170], min_samples=5)), + "mixed": (1, _series, 5, 3, dict( + cfun=tc.autofc, rfun={1: None, 2: "PCA", 3: "strength"}, + delta_rfun={1: "strength", 2: "weighted_strength", 3: None})), +} +WITHOUT_ZERO = ["auto", "pca", "strength", "wisfc", "events", "communities"] + + +def _data(config, seed=0, n=T): + n_subjects, make, K = CONFIGS[config][:3] + kw = {} if make is _modular else {"K": K} + data = [make(seed + s, n=n, **kw) for s in range(n_subjects)] + return data[0] if n_subjects == 1 else data + + +def _map(data, f): + return [f(x) for x in data] if isinstance(data, list) else f(data) + + +def _run(data, config, **kwargs): + order, kw = CONFIGS[config][3:] + return _quiet(tc.features, data, causal=True, + **{**dict(order=order, fit_timepoints=N, return_delta=True), + **PARAMS, **kw, **kwargs}) + + +def _worst(full, part, rows): + """Largest difference over every ``X[k]`` and ``D[k]``, rows ``:rows``.""" + return max(_max_difference(f[k], p[k], rows) + for f, p in zip(full, part) for k in range(1, len(f))) + + +def _identical(full, part, rows=None): + return all(np.array_equal(np.asarray(a)[:rows], np.asarray(b)[:rows], + equal_nan=True) + for f, p in zip(full, part) for fk, pk in zip(f[1:], p[1:]) + for a, b in zip(_as_list(fk), _as_list(pk))) + + +def _same_fits(a, b): + """Whether two models hold the same fits, bit for bit.""" + assert sorted(a.fits) == sorted(b.fits) + for key in a.fits: + p, q = a.fits[key], b.fits[key] + if isinstance(p, dict): # a summary's record + assert sorted(p) == sorted(q) + for name in p: + u, v = p[name], q[name] + if isinstance(u, (list, np.ndarray)): + if not all(np.array_equal(i, j) for i, j in zip(u, v)): + return False + elif u != v: + return False + elif hasattr(p, "model_"): # a fitted hypertools model + for name, u in vars(p.model_).items(): + if isinstance(u, np.ndarray) and not np.array_equal( + u, getattr(q.model_, name), equal_nan=True): + return False + elif p is not q and p != q: + return False + return True + + +# ---------------------------------------------------------------------------- +# the guarantee +# ---------------------------------------------------------------------------- + +CASES = [(c, True) for c in sorted(CONFIGS)] + [(c, False) for c in WITHOUT_ZERO] + + +@pytest.mark.parametrize("config,include_zero", CASES) +def test_rows_do_not_depend_on_later_rows(config, include_zero): + data = _data(config) + full = _run(data, config, include_zero=include_zero) + order = CONFIGS[config][3] + assert len(full[0]) == order + 1 and len(full[1]) == order + 1 + last = np.asarray(_as_list(full[0][order])[0]) + # defined after the training rows (but for the warm-up of an event) + assert np.isnan(last[0]).all() and np.isnan(last[N:]).all(axis=1).sum() < 20 + rng = np.random.default_rng(7) + for mode in MODES: + # rows before fit_timepoints are in-sample: they change with the + # rows the reducers are fitted on, and with nothing after those + for m in (N, N + 1, 200, T - 1) if mode == "remove" else (N, 200): + part = _run(_map(data, lambda x: _perturb(x, m, mode, rng)), config, + include_zero=include_zero) + # without the diagonal, row m itself may change too + rows = m if include_zero or mode == "remove" else m + 1 + assert _worst(full, part, rows) <= ATOL + if mode != "remove": + # replacing later rows changes no bit + assert _identical(full, part, rows) + + +@pytest.mark.parametrize("config", ["auto", "pca", "communities", "wisfc", "models"]) +def test_the_fit_reads_the_first_rows_only(config): + data = _data(config, seed=10) + full, model = _run(data, config, return_model=True) + assert model.fit_timepoints == N + assert any(isinstance(f, dict) or hasattr(f, "model_") for f in model.fits.values()) + # the same fits from the first rows alone, and whatever follows them + _, alone = _run(_map(data, lambda x: x[:N]), config, return_model=True) + assert _same_fits(model, alone) + rng = np.random.default_rng(11) + for mode in ("finite", "nan", "inf"): + _, other = _run(_map(data, lambda x: _perturb(x, N, mode, rng)), config, + return_model=True) + assert _same_fits(model, other) + # another row in the training span: other fits + _, more = _run(data, config, return_model=True, fit_timepoints=N + 25) + assert not _same_fits(model, more) + + +def test_the_fit_is_made_of_the_defined_training_rows(): + x = _series(12, n=T, K=6) + kw = dict(causal=True, cfun=tc.autofc, min_samples=5, events=[40], **PARAMS) + strength = tc.WeightedStrength(signed=True) + (X, D), model = _quiet(tc.features, x, order=1, rfun="PCA", delta_rfun=strength, + fit_timepoints=N, return_delta=True, return_model=True, **kw) + corrs = [_quiet(tc.timecorr, x[:N], causal=True, cfun=tc.autofc, min_samples=5, + events=[40], weights_params=PARAMS[name]) + for name in ("weights_params", "delta_weights_params")] + defined = [~np.isnan(c).all(axis=1) for c in corrs] + assert 5 < (~defined[0]).sum() < 30 # the warm-up of both blocks is left out + # weighted strength: the mean squared (and mean) correlations of those rows + r = tc.vec2mat(corrs[1][defined[1]]) + w = np.mean(r**2, axis=2) + np.fill_diagonal(w, 0) + m = np.mean(r, axis=2) + np.fill_diagonal(m, 0) + fit = model.fits[(1, "feeding")] + assert np.allclose(fit["weights"][0], w, atol=1e-12, rtol=0) + assert np.allclose(fit["mean_r"][0], m, atol=1e-12, rtol=0) + assert strength.fits_[0]["weights"][0] is not None # the caller's object too + # PCA: hypertools' model of those rows, applied to every defined row + _, pca = hyp.reduce(corrs[0][defined[0]], reduce="PCA", ndims=6, random_state=0, + return_model=True) + every = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, min_samples=5, + events=[40], **{"weights_params": PARAMS["weights_params"]}) + rows = ~np.isnan(every).all(axis=1) + expected = np.full((T, 6), np.nan) + expected[rows] = hyp.reduce(every[rows], reduce=pca) + assert _max_difference(X[1], expected, T) <= ATOL + assert np.array_equal(np.isnan(X[1]).all(axis=1), ~rows) + + +# ---------------------------------------------------------------------------- +# the model +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("config", ["auto", "pca", "strength", "wisfc", "events", + "communities-2", "models"]) +def test_transform_of_the_fitted_data_is_the_output(config): + data = _data(config, seed=20) + full, info, model = _run(data, config, return_info=True, return_model=True) + assert isinstance(model, tc.FeaturesModel) and model.info is info + events = CONFIGS[config][4].get("events") + again, again_info = _quiet(model.transform, data, return_delta=True, + return_info=True, events=events) + assert _identical(full, again) and again_info == info + # without the feeding features: X alone, the same arrays + X = _quiet(model.transform, data, events=events) + assert _identical((full[0],), (X,)) + # a pickled model gives the same output + copy = pickle.loads(pickle.dumps(model)) + assert repr(copy) == repr(model) and _same_fits(copy, model) + assert _identical(full, _quiet(copy.transform, data, return_delta=True, + events=events)) + # rows do not depend on later rows: prefixes of every length, and + # later rows replaced + rng = np.random.default_rng(21) + for n in (1, 2, 3, 7, 30, N - 1, N, N + 1, 150, 170, 171, 199, 223, T - 1): + part = _quiet(model.transform, _map(data, lambda x: x[:n]), + return_delta=True, events=events) + assert all(np.asarray(a).shape[0] == n for a in _as_list(part[0][-1])) + assert _worst(full, part, n) <= ATOL + for mode in ("finite", "nan", "inf"): + for n in (5, 100, 200): + part = _quiet(model.transform, _map(data, lambda x: _perturb(x, n, mode, rng)), + return_delta=True, events=events) + assert _identical(full, part, n) + + +def test_transform_of_other_data(): + data = _data("auto", seed=30) + X, model = _run(data, "auto", return_model=True, return_delta=False) + other = _modular(31, n=90) + out, info = _quiet(model.transform, other, return_info=True) + assert [a.shape for a in out] == [(90,) + a.shape[1:] for a in X] + assert np.array_equal(out[0], other) + assert [e["warmup_rows"] for e in info] == [2, 2, 4, 4, 6] + assert not np.isnan(out[3][6:]).any() + # the frozen fits: the same columns as a call that fits on these rows too + # would not give (other weights), and no fit is changed by transform + before = pickle.dumps(model) + _quiet(model.transform, other) + assert pickle.dumps(model) == before + # a list of one subject, and frames + import pandas as pd + + as_list = _quiet(model.transform, [other]) + assert isinstance(as_list[1], list) and np.array_equal(as_list[3][0], out[3], + equal_nan=True) + frame = _quiet(model.transform, pd.DataFrame(other)) + assert np.array_equal(frame[3], out[3], equal_nan=True) + + +def test_transform_checks_its_data(): + data = _data("wisfc", seed=32) + X, model = _run(data, "wisfc", return_model=True, return_delta=False) + assert (model.n_features, model.n_subjects, model.order) == (5, 3, 3) + with pytest.raises(ValueError, match="5 features; got 4"): + model.transform([x[:, :4] for x in data]) + # summaries hold pair weights per subject + with pytest.raises(ValueError, match="pair weights of 3 subjects.*got 2"): + _quiet(model.transform, data[:2]) + # the last feeding step was not computed by the call that made the model + with pytest.raises(ValueError, match="return_delta=True"): + model.transform(data, return_delta=True) + with pytest.raises(ValueError, match="causal=True.*boundaries"): + model.transform(data, events=np.zeros((T, 2))) + with pytest.raises(MemoryError, match="max_memory_gb"): + model.max_memory_gb = 1e-6 + model.transform(data) + # a pipeline without summaries takes any number of subjects + x = _series(33, n=T, K=5) + _, pca = _quiet(tc.features, x, order=2, causal=True, cfun=tc.autofc, rfun="PCA", + delta_rfun="PCA", fit_timepoints=N, return_model=True, **PARAMS) + out = _quiet(pca.transform, [x[:50], x[50:100]]) + assert len(out[2]) == 2 and out[2][0].shape == (50, 5) + + +def test_a_model_without_fitted_reducers(): + x = _series(34, n=T, K=5) + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun="strength", + delta_rfun="strength", **PARAMS) + X = _quiet(tc.features, x, **kw) + same, model = _quiet(tc.features, x, return_model=True, **kw) + assert model.fit_timepoints is None and _identical((X,), (same,)) + assert model.fits == {(1, "analysis"): "strength", (1, "feeding"): "strength", + (2, "analysis"): "strength"} + assert _identical((X,), (_quiet(model.transform, x),)) + # fit_timepoints is not used by reducers that need no fit + other, info = _quiet(tc.features, x, fit_timepoints=50, return_info=True, **kw) + assert _identical((X,), (other,)) + assert all("fit_timepoints" not in e for e in info) + zero, model = _quiet(tc.features, x, order=0, causal=True, return_model=True) + assert len(zero) == 1 and model.order == 0 and model.fits == {} + assert np.array_equal(model.transform(x[:9])[0], x[:9], equal_nan=True) + + +def test_the_model_describes_the_call(): + x = _modular(35) + kw = dict(order=2, causal=True, cfun=tc.autofc, fit_timepoints=N, + weights_params={1: {"var": 25}, 2: {"var": 49}}, + delta_weights_params={"var": 16}, min_samples=4, include_zero=False) + X, model = _quiet(tc.features, x, return_model=True, **kw) + assert repr(model) == ("FeaturesModel(order=2, fit_timepoints=140, n_features=12, " + "n_subjects=1)") + assert model.weights_function is tc.gaussian_weights + assert model.delta_weights_function is tc.gaussian_weights + assert model.weights_params == {1: {"var": 25}, 2: {"var": 49}} + assert model.delta_weights_params == {1: {"var": 16}, 2: {"var": 16}} + assert model.cfun is tc.autofc and model.combine is tc.null_combine + assert (model.min_samples, model.include_zero, model.ndims) == (4.0, False, None) + assert model.max_memory_gb == 4.0 + assert sorted(model.fits) == [(1, "analysis"), (1, "feeding"), (2, "analysis")] + # a hypertools model, a record of the communities, a record of the weights + assert model.fits[(1, "analysis")].model_.components_.shape == (12, 78) + assert model.fits[(1, "feeding")]["labels"].tolist() == np.repeat( + np.arange(4), 3).tolist() + assert model.fits[(2, "analysis")]["weights"][0].shape == (4, 4) + # the caller's dictionaries are not the model's + kw["weights_params"][1]["var"] = 1 + assert model.weights_params[1] == {"var": 25} + # a model that holds a lambda cannot be pickled + _, local = _quiet(tc.features, x, order=1, causal=True, fit_timepoints=N, + cfun=lambda data, weights: tc.autofc(data, weights), + return_model=True, **PARAMS) + with pytest.raises(Exception, match="(?i)pickle|lambda"): + pickle.dumps(local) + + +SCRIPT = """ +import sys, warnings +import numpy as np +import timecorr as tc +warnings.simplefilter("ignore") +rng = np.random.default_rng(40) +shared = np.repeat(rng.standard_normal((240, 4)), 3, axis=1) +x = shared + 0.5 * rng.standard_normal((240, 12)) +(X, D), model = tc.features(x, order=3, causal=True, cfun=tc.autofc, + weights_params={"var": 25}, + delta_weights_params={"var": 16}, fit_timepoints=140, + return_delta=True, return_model=True) +Y = model.transform(x[:200]) +np.savez(sys.argv[1], *X, *D, *Y) +""" + + +def test_the_same_arrays_in_two_processes(tmp_path): + files = [str(tmp_path / f"run{i}.npz") for i in range(2)] + for path in files: + subprocess.run([sys.executable, "-c", SCRIPT, path], check=True) + first, second = (np.load(path) for path in files) + assert len(first.files) == 12 and first.files == second.files + for name in first.files: + assert np.array_equal(first[name], second[name], equal_nan=True) + assert first["arr_3"].shape == (240, 8) and not np.isnan(first["arr_3"][6:]).any() + + +# ---------------------------------------------------------------------------- +# what is fitted, and what is reported +# ---------------------------------------------------------------------------- + + +def test_return_info_names_the_fitted_steps(): + x = _modular(50) + kw = dict(order=2, causal=True, cfun=tc.autofc, return_delta=True, **PARAMS) + (X, D), info = _quiet(tc.features, x, fit_timepoints=N, return_info=True, + rfun={1: "PCA", 2: "strength"}, + delta_rfun={1: "auto", 2: None}, **kw) + assert [(e["order"], e["path"], e.get("fit_timepoints")) for e in info] == [ + (1, "analysis", N), (1, "feeding", N), (2, "analysis", None), + (2, "feeding", None)] + assert all("weights_params" in e and "warmup_rows" in e for e in info) + # the automatic feeding step: decided on the training rows + step = info[1] + assert step["fallback"] is None and step["n_communities"] == 4 + assert step["labels"] == np.repeat(np.arange(4), 3).tolist() + assert step["effective"] == "Communities(n=None, signed=False, n_null=5)" + assert D[1].shape == (T, 4) + # unstructured data: the fallback, decided on the training rows too, with + # the one warning of the fit + noise = np.random.default_rng(51).standard_normal((T, 6)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + (X, D), info = tc.features(noise, fit_timepoints=N, return_info=True, **kw) + assert info[1]["fallback"] in ("no_null_exceedance", "too_few_community_columns") + assert info[1]["effective"].startswith("WeightedStrength(") and D[1].shape == (T, 6) + fallbacks = [c for c in caught if "Automatic feeding reducer" in str(c.message)] + assert len(fallbacks) == sum(e.get("fallback") == "no_null_exceedance" for e in info) + # the estimator's warning is issued once per step, for every row + rows = [str(c.message) for c in caught if "timepoints have" in str(c.message)] + assert len(rows) == 4 and all(f"of {T} timepoints" in r for r in rows) + # calls without causal have no such keys + _, info = _quiet(tc.features, x, order=1, return_info=True, **PARAMS) + assert not {"fit_timepoints", "weights_params", "warmup_rows"} & set(info[0]) + + +def test_constant_columns_are_reported_and_not_set_to_their_mean(): + # features 0 and 1 are equal up to a factor: their summaries agree to + # round-off at every timepoint. Without causal such a column of the + # difference would be set to its mean, which reads every row. + rng = np.random.default_rng(52) + x = rng.standard_normal((T, 5)) + x[:, 4] = 3.0 # zero variance: weighted strength 0 at every row + kw = dict(order=2, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun="weighted_strength", return_delta=True, return_info=True, + **PARAMS) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + (X, D), info = tc.features(x, causal=True, fit_timepoints=N, **kw) + assert not [c for c in caught if "constant over time" in str(c.message)] + for e in info: + out = (X if e["path"] == "analysis" else D)[e["order"]] + defined = ~np.isnan(out).all(axis=1) + assert e["constant_columns"] == np.flatnonzero( + np.ptp(out[defined], axis=0) == 0).tolist() + assert 4 in e["constant_columns"] + assert np.all(X[1][2:, 4] == 0) + # values are those of the frozen weights applied to each row's + # correlations: nothing is replaced afterwards + fit = tc.WeightedStrength() + corrs = _quiet(tc.timecorr, x, causal=True, cfun=tc.autofc, + weights_params={"var": 25}) + fit.fit(corrs[2:N]) + expected = _quiet(fit.transform, corrs[2:]) + assert np.max(np.abs(X[1][2:] - expected)) <= 1e-12 + + +def test_errors_of_the_training_rows(): + x = _modular(53) + kw = dict(order=2, causal=True, cfun=tc.autofc, **PARAMS) + # the default feeding reducer: 40 rows to be fitted on + with pytest.raises(ValueError, match=r"40 timepoints.*fit_timepoints = 30"): + tc.features(x, fit_timepoints=30, **kw) + # the shift null of a later order: 40 rows of its input, which starts + # with the warm-up rows of the order before + later = {1: "weighted_strength", 2: tc.Communities()} + with pytest.raises(ValueError, match="shift null needs T >= 40.*training span"): + _quiet(tc.features, x, fit_timepoints=41, delta_rfun=later, **{**kw, "order": 3}) + assert len(_quiet(tc.features, x, fit_timepoints=42, delta_rfun=later, + **{**kw, "order": 3})) == 4 + # no defined row to fit: the first rows of every order are warm-up + for reducers in (dict(rfun="PCA", delta_rfun="strength"), + dict(rfun="weighted_strength", delta_rfun="strength"), + dict(rfun="strength", delta_rfun="weighted_strength"), + dict(rfun="strength", delta_rfun=tc.Communities(n=2))): + with pytest.raises(ValueError, match="fit_timepoints.*Raise fit_timepoints"): + _quiet(tc.features, x, fit_timepoints=2, **reducers, **kw) + with pytest.raises(ValueError, match="fit_timepoints.*Raise fit_timepoints"): + _quiet(tc.features, x, fit_timepoints=4, rfun={1: "strength", 2: "PCA"}, + delta_rfun="strength", **kw) + assert len(_quiet(tc.features, x, fit_timepoints=8, rfun="PCA", + delta_rfun="weighted_strength", **kw)) == 3 + + +@pytest.mark.parametrize("model", ["MDS", "SpectralEmbedding", "LocallyLinearEmbedding"]) +def test_models_that_cannot_embed_later_rows_raise(model): + x = np.random.default_rng(54).standard_normal((80, 5)) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=50, + weights_params={"var": 25}) + with pytest.raises(ValueError, match=f"causal=True: the model '{model}'"): + _quiet(tc.timecorr, x, rfun={"model": model}, **kw) + with pytest.raises(ValueError, match=f"causal=True: the model '{model}'.*order 1"): + _quiet(tc.features, x, order=1, rfun=model, delta_weights_params={"var": 16}, + **kw) + # without causal they reduce the recording as before + assert _quiet(tc.timecorr, x, cfun=tc.autofc, rfun=model).shape == (80, 5) + + +def test_model_columns_constant_on_the_training_rows_are_frozen(): + # a feature that is constant has correlation 0 with every other, so the + # correlations of the training rows span fewer dimensions than PCA has + # components: the last component's output is round-off (1e-16). The + # next order would correlate that noise, which is not reproducible when + # rows are removed; the values are returned as the column's training + # mean, exactly. + x = _series(56, n=T, K=4) # its feature 2 is 2 up to round-off + kw = dict(causal=True, cfun=tc.autofc, rfun="PCA", delta_rfun="PCA", + fit_timepoints=N, return_delta=True, **PARAMS) + (X, D), info = _quiet(tc.features, x, order=1, return_info=True, **kw) + assert info[1]["constant_columns"] == [3] and info[0]["constant_columns"] == [3] + assert np.ptp(D[1][2:, 3]) == 0 and abs(D[1][2, 3]) < 1e-12 + assert np.all(np.ptp(D[1][2:, :3], axis=0) > 1) + # at the next orders that column has zero variance at every row, and + # the outputs do not depend on later rows + full = _quiet(tc.features, x, order=3, **kw) + rng = np.random.default_rng(57) + for mode in MODES: + for m in (N, 141, 200): + part = _quiet(tc.features, _perturb(x, m, mode, rng), order=3, **kw) + assert _worst(full, part, m) <= ATOL + # the rule itself: values within round-off of the training mean are that + # mean; any other value is the model's + from timecorr.helpers import _model_reduce + + rng = np.random.default_rng(58) + rows = rng.standard_normal((50, 3)) @ rng.standard_normal((3, 6)) # rank 3 + _, fitted = _quiet(_model_reduce, rows, "PCA", 5, return_model=True) + plain = hyp.reduce(rows, reduce=fitted.model) + assert 0 < np.ptp(plain[:, 3:], axis=0).max() < 1e-12 + fitted.freeze_constants([plain]) + frozen = fitted.apply([rows])[0] + assert np.all(np.ptp(frozen[:, 3:], axis=0) == 0) + assert np.array_equal(frozen[:, :3], plain[:, :3]) + other = rng.standard_normal((10, 6)) # rows outside that subspace + assert np.array_equal(fitted.apply([other])[0], hyp.reduce(other, reduce=fitted.model)) + assert np.ptp(fitted.apply([other])[0][:, 3:], axis=0).min() > 0.1 + + +def test_pca_is_fitted_with_an_exact_solver(): + # 520 training rows of 55 correlations: scikit-learn's default solver for + # 10 components is the randomized one, whose fit_transform is not the + # projection that transform computes + x = np.random.default_rng(55).standard_normal((600, 10)) + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}, + fit_timepoints=522) + out = _quiet(tc.timecorr, x, rfun="PCA", **kw) + corrs = _quiet(tc.timecorr, x, **{**kw, "fit_timepoints": None}) + rows = corrs[2:522] + centered = rows - rows.mean(axis=0) + # the principal components of the training rows: decreasing variances + # that are the eigenvalues of their covariance + variances = np.var(out[2:522], axis=0, ddof=1) + expected = np.linalg.eigvalsh(centered.T @ centered / 519)[::-1][:10] + assert np.allclose(variances, expected, rtol=1e-9, atol=0) + same = _quiet(tc.timecorr, x, rfun={"model": "PCA", "kwargs": {"whiten": False}}, + **kw) + assert np.array_equal(out, same, equal_nan=True) + with pytest.raises(ValueError, match="does not reproduce the rows"): + _quiet(tc.timecorr, x, **kw, + rfun={"model": "PCA", "kwargs": {"svd_solver": "randomized", + "iterated_power": 0}}) + + +# ---------------------------------------------------------------------------- +# two_path_step and timecorr +# ---------------------------------------------------------------------------- + + +def test_two_path_step_fits_on_the_first_rows(): + x = _modular(60) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=N, **PARAMS) + X, D = _quiet(tc.features, x, order=2, return_delta=True, **kw) + X1, D1 = _quiet(tc.two_path_step, x, **kw) + assert np.array_equal(X1, X[1], equal_nan=True) + assert np.array_equal(D1, D[1], equal_nan=True) + # the next order: the fit skips the warm-up rows of its input (features + # fits it on the feeding features of the first rows alone, which equal + # these to round-off) + X2, D2 = _quiet(tc.two_path_step, D1, order=2, **kw) + assert np.isnan(X2[:4]).all() and not np.isnan(X2[4:]).any() + assert _max_difference(X2, X[2], T) <= ATOL + assert _max_difference(D2, D[2], T) <= ATOL + rng = np.random.default_rng(61) + for mode in MODES: + for m in (N, 200): + part = _quiet(tc.two_path_step, _perturb(x, m, mode, rng), **kw) + assert max(_max_difference(f, p, m) for f, p in zip((X1, D1), part)) <= ATOL + with pytest.raises(ValueError, match="more than the 240 timepoints"): + tc.two_path_step(x, **{**kw, "fit_timepoints": T + 1}) + + +TIMECORR_REDUCERS = { + "PCA": lambda: "PCA", + "model-dict": lambda: {"model": "FactorAnalysis", "params": {"n_components": 3}}, + "strength": lambda: tc.WeightedStrength(signed=True), + "split": lambda: tc.WeightedStrength(split=True, n=2), + "communities": lambda: tc.Communities(n=2), + "name": lambda: "weighted_strength", +} + + +@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("reducer", sorted(TIMECORR_REDUCERS)) +@pytest.mark.parametrize("subjects", [1, 3]) +def test_timecorr_fits_its_reducer_on_the_first_rows(subjects, reducer, include_zero): + data = [_series(70 + s, n=T, K=5) for s in range(subjects)] + data = data[0] if subjects == 1 else data + rfun = TIMECORR_REDUCERS[reducer]() + kw = dict(causal=True, weights_params={"var": 25}, rfun=rfun, fit_timepoints=N, + include_zero=include_zero, + cfun=tc.autofc if subjects == 1 else tc.isfc) + full = _quiet(tc.timecorr, data, **kw) + assert all(np.isnan(f[0]).all() and not np.isnan(f[N:]).any() + for f in _as_list(full)) + rng = np.random.default_rng(71) + for mode in MODES: + for m in (N, 200) if mode != "remove" else (N, N + 1, T - 1): + part = _quiet(tc.timecorr, _map(data, lambda x: _perturb(x, m, mode, rng)), + **kw) + rows = m if include_zero or mode == "remove" else m + 1 + assert _max_difference(full, part, rows) <= ATOL + if isinstance(rfun, tc.WeightedStrength) and subjects == 1: + # the caller's object holds the fit of the training rows, to use again + corrs = _quiet(tc.timecorr, data, **{**kw, "rfun": None}) + assert len(rfun.fits_) == 1 + again = _quiet(rfun.transform, corrs[5:]) + assert np.max(np.abs(again - full[5:])) <= ATOL + + +def test_timecorr_with_every_row_in_the_training_span(): + x = _series(72, n=T, K=5) + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}, rfun="PCA") + out = _quiet(tc.timecorr, x, fit_timepoints=T, **kw) + assert out.shape == (T, 5) and np.isnan(out[:2]).all() + # the fit of every row is not causal for the rows before the last + assert _max_difference(out, _quiet(tc.timecorr, x[:200], fit_timepoints=200, **kw), + 200) > 1e-3 + # smoothing has no reducer: fit_timepoints is not used + kw = dict(causal=True, cfun=None, weights_params={"var": 25}) + assert np.array_equal(_quiet(tc.timecorr, x, fit_timepoints=9, **kw), + _quiet(tc.timecorr, x, **kw), equal_nan=True) + + +# ---------------------------------------------------------------------------- +# arguments +# ---------------------------------------------------------------------------- + +X0 = np.random.default_rng(0).standard_normal((60, 5)) +CALLS = { + "timecorr": lambda **kw: tc.timecorr(X0, cfun=tc.autofc, rfun="PCA", + weights_params={"var": 25}, **kw), + "features": lambda **kw: tc.features(X0, order=2, cfun=tc.autofc, **PARAMS, **kw), + "two_path_step": lambda **kw: tc.two_path_step(X0, cfun=tc.autofc, **PARAMS, **kw), +} +each = pytest.mark.parametrize("function", sorted(CALLS)) + + +def _rows(out): + """Rows of the last output (an array, or the highest order of a list).""" + return (out if isinstance(out, np.ndarray) else np.asarray(out[-1])).shape[0] + + +@each +def test_fitted_reducers_need_fit_timepoints(function): + with pytest.raises(ValueError, match="causal=True.*needs fit_timepoints=n"): + CALLS[function](causal=True) + assert _rows(_quiet(CALLS[function], causal=True, fit_timepoints=50)) == 60 + # every row in the rows the reducers are fitted on + assert _rows(_quiet(CALLS[function], causal=True, fit_timepoints=60)) == 60 + + +@each +@pytest.mark.parametrize("bad", [0, -3, 2.0, "10", True, np.nan]) +def test_fit_timepoints_is_a_positive_integer(function, bad): + with pytest.raises(ValueError, match="fit_timepoints must be None or a positive"): + CALLS[function](causal=True, fit_timepoints=bad) + + +@each +def test_fit_timepoints_needs_causal_and_rows(function): + with pytest.raises(ValueError, match="fit_timepoints=30 applies with causal=True"): + CALLS[function](fit_timepoints=30) + with pytest.raises(ValueError, match="fit_timepoints=61 is more than the 60"): + CALLS[function](causal=True, fit_timepoints=61) + assert _rows(_quiet(CALLS[function], causal=True, + fit_timepoints=np.int64(50))) == 60 + + +def test_return_model_needs_causal(): + with pytest.raises(ValueError, match="return_model=True applies with causal=True"): + tc.features(X0, order=1, return_model=True) + out = _quiet(tc.features, X0, order=1, causal=True, cfun=tc.autofc, + fit_timepoints=50, return_delta=True, return_info=True, + return_model=True, **PARAMS) + (X, D), info, model = out + assert len(X) == 2 and len(D) == 2 and len(info) == 2 + assert isinstance(model, tc.FeaturesModel) + assert np.array_equal(_quiet(model.transform, X0, return_delta=True)[1][1], D[1], + equal_nan=True) + + +@pytest.mark.parametrize("function,names", [ + (tc.timecorr, ["fit_timepoints"]), + (tc.features, ["fit_timepoints", "return_model"]), + (two_path_step, ["fit_timepoints"]), +]) +def test_new_arguments_are_keyword_only_and_documented(function, names): + parameters = inspect.signature(function).parameters + for name in names: + assert parameters[name].kind is inspect.Parameter.KEYWORD_ONLY + assert f"\n {name} : " in function.__doc__ + assert parameters["fit_timepoints"].default is None + assert list(parameters)[-len(names):] == names + for section in ("Parameters", "Returns", "Examples"): + assert section in tc.FeaturesModel.transform.__doc__ + assert "Examples" in tc.FeaturesModel.__doc__ + assert tc.FeaturesModel.__module__ == "timecorr.model" diff --git a/tests/test_estimator.py b/tests/test_estimator.py index 2fdc94d8..dee8cb12 100644 --- a/tests/test_estimator.py +++ b/tests/test_estimator.py @@ -732,7 +732,8 @@ def test_timecorr_positional_order(): "rfun", "include_zero", ] - keyword_only = ["events", "events_params", "causal", "min_samples"] + keyword_only = ["events", "events_params", "causal", "min_samples", + "fit_timepoints"] assert list(params) == positional + keyword_only assert all( params[n].kind == inspect.Parameter.KEYWORD_ONLY for n in keyword_only diff --git a/tests/test_features.py b/tests/test_features.py index cecf5c00..5c1db4aa 100644 --- a/tests/test_features.py +++ b/tests/test_features.py @@ -722,7 +722,8 @@ def test_events_signatures_keep_positional_order(): later = ["delta_weights_function", "delta_weights_params"] + ( ["order"] if f is two_path_step else ["return_info"]) # the arguments of the causal mode (0.4.0), keyword-only, come last - later += ["causal", "min_samples"] + later += ["causal", "min_samples", "fit_timepoints"] + ( + [] if f is two_path_step else ["return_model"]) assert list(params) == positional + ["events", "events_params"] + later, ( f.__name__) assert all(params[n].kind == inspect.Parameter.KEYWORD_ONLY diff --git a/timecorr/__init__.py b/timecorr/__init__.py index d8bb7e35..12554b51 100644 --- a/timecorr/__init__.py +++ b/timecorr/__init__.py @@ -39,6 +39,7 @@ ) from .events import segment from .higher_order import features, two_path_step +from .model import FeaturesModel from .summaries import Communities, WeightedStrength from .simulate import ( carrier_columns, diff --git a/timecorr/helpers.py b/timecorr/helpers.py index d1690eb8..93129cef 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -3,6 +3,7 @@ import inspect import numbers import os +import pickle import sys import warnings @@ -1067,7 +1068,6 @@ def prepare(self, finite, always=False): ``zero_rows``, however much of the kernel they cover, as the causal estimator needs). """ - T_out = self.shape[0] T = self.shape[1] if len(self.shape) == 2 else 0 peak = self._peak if self.zero is None else np.where(self.zero, 0.0, self._peak) extreme = ( @@ -3570,6 +3570,151 @@ def _pagerank_solve(B, b): return r +def _model_reduce(corrs, rfun, ndims, return_model=False): + """ + The model-based reduction of ``reduce`` (``rfun`` a model name or dict, + ``ndims`` checked). ``return_model=True`` returns ``(reduced, fitted)``, + ``fitted`` a ``_FittedModel`` that reduces other rows with the model + fitted here. + """ + arrays = corrs if isinstance(corrs, list) else [corrs] + n_features = arrays[0].shape[1] + if ndims is None: + # K(K+1)/2 features back to K columns + ndims = int(np.divide(np.sqrt(8 * n_features + 1) - 1, 2)) + + # a model cannot return more components than there are features or samples + n_samples = sum(a.shape[0] for a in arrays) + n_fit = min(ndims, n_features, n_samples) + + if isinstance(rfun, dict) and "params" in rfun: + # hypertools deprecated 'params' in favor of 'kwargs': merge both + params = dict(rfun["params"] or {}) + kwargs = dict(rfun.get("kwargs") or {}) + clash = sorted( + k for k in set(params) & set(kwargs) if params[k] is not kwargs[k] + and params[k] != kwargs[k] + ) + if clash: + raise ValueError( + f"rfun gives different values for {clash} in 'params' and " + "'kwargs'; give each model argument once." + ) + rfun = { + **{k: v for k, v in rfun.items() if k not in ("params", "kwargs")}, + "kwargs": {**kwargs, **params}, + } + + rfun = _umap_defaults(rfun) + model = None + if return_model: + red_corrs, model = hyp.reduce(corrs, reduce=rfun, ndims=n_fit, + random_state=0, return_model=True) + else: + red_corrs = hyp.reduce(corrs, reduce=rfun, ndims=n_fit, random_state=0) + if isinstance(corrs, list) and not isinstance(red_corrs, list): + # hypertools returns a bare array for a one-element list + red_corrs = [red_corrs] + + if n_fit < ndims: + # Pad with zeros to match the requested output width + pad = ndims - n_fit + _warn_user( + f"reduce: the data supply at most {n_fit} components ({n_features} " + f"features, {n_samples} samples) but {ndims} were requested; the " + f"output is padded with {pad} zero column{'s' if pad > 1 else ''}." + ) + if isinstance(red_corrs, list): + red_corrs = [ + np.hstack((arr, np.zeros((arr.shape[0], pad)))) for arr in red_corrs + ] + else: + red_corrs = np.hstack((red_corrs, np.zeros((red_corrs.shape[0], pad)))) + + if return_model: + return red_corrs, _FittedModel(model, n_features, max(0, ndims - n_fit)) + return red_corrs + + +# an output column of a fitted model is constant on its training rows when +# its range there is at most this fraction of its largest magnitude, or +# _FROZEN_ZERO_RTOL of the largest magnitude of the whole output (the +# tolerances of summaries._Summary._warn_constant) +_FROZEN_RTOL = 1e-9 +_FROZEN_ZERO_RTOL = 1e-12 + + +class _FittedModel: + """ + A hypertools model fitted by ``_model_reduce``: ``model`` (the fitted + ``hypertools`` reducer; None when hypertools fitted none, as for a + single row), the number of input columns ``n_features`` and the number + of zero columns ``pad`` that ``reduce`` appends when the data supplied + fewer components than requested. ``apply`` reduces other rows with it. + + ``freeze_constants(outputs)`` (the model's outputs for its training + rows) records the output columns that are constant there up to + round-off: a range of at most ``_FROZEN_RTOL`` of the column's largest + magnitude, or ``_FROZEN_ZERO_RTOL`` of the largest magnitude of the + whole output (a component along which the training rows do not vary, + for example: its values are round-off of the others). ``apply`` then + returns a value of such a column that lies within that tolerance of + the column's training mean as exactly that mean; other values are + returned as computed. The rule reads the training rows and the row it + is applied to, nothing else, so it is causal; without it the next + order would correlate that round-off, which is not reproducible to + 1e-9 when later rows are removed. + """ + + def __init__(self, model, n_features, pad=0): + # the model as a pickle restores it: a fitted model's arrays can be + # laid out differently in memory after pickling, which changes the + # round-off of its products, so a model and its unpickled copy + # would differ in the last bit + try: + model = pickle.loads(pickle.dumps(model)) + except Exception: # a model that cannot be pickled is used as it is + pass + self.model = model + self.n_features = int(n_features) + self.pad = int(pad) + self.constants = None # (columns, their training means, tolerances) + + def freeze_constants(self, outputs): + stacked = np.vstack([np.asarray(o, dtype=np.float64) for o in outputs]) + if not stacked.shape[0]: + return + largest = np.max(np.abs(stacked), axis=0) + tol = np.maximum(_FROZEN_RTOL * largest, + _FROZEN_ZERO_RTOL * np.max(largest, initial=0.0)) + columns = np.flatnonzero(np.ptp(stacked, axis=0) <= tol) + if columns.size: + self.constants = (columns, np.mean(stacked[:, columns], axis=0), + tol[columns]) + + def apply(self, arrays): + """The rows of a list of (rows, n_features) arrays, reduced with the + fitted model (a list of arrays).""" + arrays = [np.asarray(a, dtype=np.float64) for a in arrays] + for a in arrays: + if a.ndim != 2 or a.shape[1] != self.n_features: + raise ValueError( + f"the fitted model takes {self.n_features} columns; got an " + f"array of shape {a.shape}." + ) + out = hyp.reduce(arrays, reduce=self.model) + out = out if isinstance(out, list) else [out] + out = [np.asarray(o, dtype=np.float64) for o in out] + if self.pad: + out = [np.hstack((o, np.zeros((o.shape[0], self.pad)))) for o in out] + if self.constants is not None: + columns, means, tol = self.constants + for o in out: + values = o[:, columns] + o[:, columns] = np.where(np.abs(values - means) <= tol, means, values) + return out + + def reduce(corrs, rfun=None, ndims=None): """ Reduce vectorized correlation matrices back to a (timepoints by features) matrix. @@ -3881,56 +4026,7 @@ def strengths_und(W): ) return out - arrays = corrs if isinstance(corrs, list) else [corrs] - n_features = arrays[0].shape[1] - if ndims is None: - # K(K+1)/2 features back to K columns - ndims = int(np.divide(np.sqrt(8 * n_features + 1) - 1, 2)) - - # a model cannot return more components than there are features or samples - n_samples = sum(a.shape[0] for a in arrays) - n_fit = min(ndims, n_features, n_samples) - - if isinstance(rfun, dict) and "params" in rfun: - # hypertools deprecated 'params' in favor of 'kwargs': merge both - params = dict(rfun["params"] or {}) - kwargs = dict(rfun.get("kwargs") or {}) - clash = sorted( - k for k in set(params) & set(kwargs) if params[k] is not kwargs[k] - and params[k] != kwargs[k] - ) - if clash: - raise ValueError( - f"rfun gives different values for {clash} in 'params' and " - "'kwargs'; give each model argument once." - ) - rfun = { - **{k: v for k, v in rfun.items() if k not in ("params", "kwargs")}, - "kwargs": {**kwargs, **params}, - } - - rfun = _umap_defaults(rfun) - red_corrs = hyp.reduce(corrs, reduce=rfun, ndims=n_fit, random_state=0) - if isinstance(corrs, list) and not isinstance(red_corrs, list): - # hypertools returns a bare array for a one-element list - red_corrs = [red_corrs] - - if n_fit < ndims: - # Pad with zeros to match the requested output width - pad = ndims - n_fit - _warn_user( - f"reduce: the data supply at most {n_fit} components ({n_features} " - f"features, {n_samples} samples) but {ndims} were requested; the " - f"output is padded with {pad} zero column{'s' if pad > 1 else ''}." - ) - if isinstance(red_corrs, list): - red_corrs = [ - np.hstack((arr, np.zeros((arr.shape[0], pad)))) for arr in red_corrs - ] - else: - red_corrs = np.hstack((red_corrs, np.zeros((red_corrs.shape[0], pad)))) - - return red_corrs + return _model_reduce(corrs, rfun, ndims) def smooth( diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index a1e920b4..742afa42 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -54,6 +54,7 @@ block holds all d rows. """ +import contextlib import functools import inspect import numbers @@ -106,12 +107,16 @@ _Summary, _auto_emitter, _auto_fallback, + _FittedSummary, ) from .timecorr import ( + _apply_frozen, + _check_fit_timepoints, _event_kernels, + _fit_reducer, + _FitTimepointsMissing, _fixed_weights_wisfc, _needs_fit, - _reduce_defined, _restricted, _shaped_kernel, timecorr, @@ -602,18 +607,32 @@ def _as_summary(rfun): def _apply_reducer(corrs, rfun, ndims, order=None, path=None, null_threshold=None, - append_fit=False, causal=False): + append_fit=False, causal=False, frozen=None, record=None): """ ``_reduce``; a summary is fit (recording ``order`` and ``path`` in its ``fits_``) and then transforms the same correlations. With ``append_fit`` False, ``fits_`` keeps only the new fit (as a direct call of the summary does); True appends it (the steps of ``features`` and - ``two_path_step``). ``causal``: the correlations are those of the - causal estimator, whose undefined rows are NaN; a graph measure is - computed for the defined rows and the others stay NaN. + ``two_path_step``). + + ``causal``: the correlations are those of the causal estimator, whose + undefined rows are NaN: they are left out of every fit and stay rows of + NaN in the output (see ``timecorr._fit_reducer`` and + ``timecorr._apply_frozen``). The reducer is fitted to ``corrs`` (the + training rows of a causal fit) unless ``frozen`` holds a fit made + earlier (a ``_FittedSummary`` or ``_FittedModel``), which then reduces + ``corrs``. ``record`` (a dict): ``record[path]`` is set to what + reduced the step (the fit, or the reducer itself when it has none). """ - if causal and isinstance(rfun, str): - return _reduce_defined(corrs, rfun) + if causal: + if frozen is None: + frozen = _fit_reducer( + corrs, rfun, ndims, order=order, path=path, append_fit=append_fit, + name="rfun" if path == "analysis" else "delta_rfun", + ) + if record is not None: + record[path] = frozen + return _apply_frozen(corrs, frozen) summary = _as_summary(rfun) if summary is None: return _reduce(corrs, rfun, ndims) @@ -658,12 +677,14 @@ def __exit__(self, *exc): return False -def _streams(rfun, cfun, combine, groups=None): - """Whether an analysis step is streamed (see the module docstring).""" +def _streams(rfun, cfun, combine, groups=None, causal=False): + """Whether an analysis step is streamed (see the module docstring); + with ``causal``, ``wisfc`` with fixed subject weights is streamed too.""" return ( groups is None and combine is null_combine - and any(cfun is f for f in _STREAMED_CFUNS) + and (any(cfun is f for f in _STREAMED_CFUNS) + or (causal and _fixed_weights_wisfc(cfun))) and _is_summary(rfun) ) @@ -705,10 +726,13 @@ def _step_kernels(T, n_subjects, weights_function, weights_params, def _run_streamed(subjects, summary, cfun, kernels, *, max_memory_gb, order, path, - auto_n, bandwidth, append_fit=False, dense=False): + auto_n, bandwidth, append_fit=False, dense=False, estimator=None, + frozen=None, record=None): """ ``summaries._streamed_summary`` under a memory budget; issues the estimator's warning. ``append_fit`` as in ``_apply_reducer``. + ``estimator``: the keyword arguments of the causal estimator (None + without ``causal``); ``frozen`` and ``record`` as in ``_apply_reducer``. """ # C-ordered float copies: the blocked arithmetic's round-off then does not # depend on the memory layout of the inputs (reducers can return views) @@ -730,9 +754,16 @@ def _run_streamed(subjects, summary, cfun, kernels, *, max_memory_gb, order, pat # the shift null (when it runs) chooses its timepoints: every s-th # for a stationary built-in kernel, every timepoint otherwise null_row_stride=None, + estimator=estimator, + fitted=frozen, ) - if not append_fit: - del summary.fits_[:-1] + if frozen is None: + if record is not None: + record[path] = _FittedSummary(summary, summary.fits_[-1]) + if not append_fit: + del summary.fits_[:-1] + elif record is not None: + record[path] = frozen if message is not None: _warn_user(message) return out @@ -760,13 +791,16 @@ def _analysis_path( input_elements=0, causal=False, min_samples=None, + frozen=None, + record=None, ): """ Analysis path of one order: ``reduce(combine(timecorr(subjects, kernel, cfun)))``. ``causal`` and ``min_samples`` are ``timecorr``'s (the arguments were - checked by ``_check_causal``; the reducer is None, a graph measure or a - callable). + checked by ``_check_causal``); ``frozen`` and ``record`` as in + ``_apply_reducer`` (with ``causal`` a reducer is fitted to the rows + given, the training rows of a causal fit, or ``frozen`` is applied). ``held_elements``: float64 values the caller retains (earlier outputs of a ``features`` run), counted against ``max_memory_gb``; ``reducers``: the @@ -802,7 +836,8 @@ def _analysis_path( """ T, d = subjects[0].shape dense = _dense_analysis(weights_function, cfun, causal) - if _streams(rfun, cfun, combine, groups): + estimator = {"causal": True, "min_samples": min_samples} if causal else None + if _streams(rfun, cfun, combine, groups, causal): summary = _as_summary(rfun) # the distinct event kernels and earlier fits are held while the step # runs: checked before the kernels are built @@ -814,7 +849,7 @@ def _analysis_path( ) kernels = _step_kernels( T, len(subjects), weights_function, weights_params, - include_timepoints, include_zero, events, + include_timepoints, include_zero, events, causal, ) return _run_streamed( subjects, @@ -828,6 +863,9 @@ def _analysis_path( bandwidth=_bandwidth(weights_function, weights_params), append_fit=append_fit, dense=dense, + estimator=estimator, + frozen=frozen, + record=record, ) _check_step_memory(d, T, len(subjects), n_outputs, max_memory_gb, order, kernel_feeding, @@ -856,7 +894,7 @@ def analyze(members, member_events): if groups is None: return _apply_reducer( analyze(subjects, events), rfun, ndims, order, "analysis", - append_fit=append_fit, causal=causal, + append_fit=append_fit, causal=causal, frozen=frozen, record=record, ) def group_events(g): @@ -928,6 +966,8 @@ def _delta_path( retained_elements=0, causal=False, min_samples=None, + frozen=None, + record=None, ): """ Feeding (delta) path of one order: per-subject correlations with the @@ -955,7 +995,8 @@ def _delta_path( (``include_timepoints``, ``include_zero``, and the RESOLVED ``events`` entry), NaN samples are left out pairwise by the estimator, and the estimator's warning is issued at most once. A summary reducer is - streamed. + streamed. ``causal``, ``min_samples``, ``frozen`` and ``record`` as in + ``_analysis_path``. """ T, d = subjects[0].shape S = len(subjects) @@ -973,7 +1014,7 @@ def _delta_path( ) kernels = _step_kernels( T, S, weights_function, weights_params, include_timepoints, - include_zero, events, + include_zero, events, causal, ) return _run_streamed( subjects, @@ -987,6 +1028,10 @@ def _delta_path( bandwidth=_bandwidth(weights_function, weights_params), append_fit=append_fit, dense=dense, + estimator=({"causal": True, "min_samples": min_samples} + if causal else None), + frozen=frozen, + record=record, ) _check_step_memory(d, T, S, n_outputs, max_memory_gb, order, True, retained_elements, dense=dense) @@ -1007,7 +1052,8 @@ def _delta_path( ) return _as_list( _apply_reducer(corrs, rfun, ndims, order, "feeding", - append_fit=append_fit, causal=causal) + append_fit=append_fit, causal=causal, frozen=frozen, + record=record) ) _check_step_memory(d, T, S, n_outputs, max_memory_gb, order, @@ -1147,7 +1193,7 @@ def _resolve_auto(value, k, path): _AUTO_FEEDING_MIN_T = 40 -def _check_auto_feeding(delta_rfun, d, T, order, previous=None): +def _check_auto_feeding(delta_rfun, d, T, order, previous=None, training=False): """ Raise ``ValueError`` naming the alternatives when the feeding reducer resolved from ``delta_rfun="auto"`` (communities) cannot be fitted to @@ -1157,7 +1203,8 @@ def _check_auto_feeding(delta_rfun, d, T, order, previous=None): ``previous``: the number of communities found at the previous order when the d inputs are the community columns of an explicit ``Communities`` there (the automatic reducer keeps at least 4 - columns; see ``summaries._auto_emitter``). + columns; see ``summaries._auto_emitter``). ``training``: the T rows + are the rows a causal call fits its reducers on (``fit_timepoints``). """ if not getattr(delta_rfun, "_from_auto", False): return @@ -1178,8 +1225,10 @@ def _check_auto_feeding(delta_rfun, d, T, order, previous=None): raise ValueError( f'The default feeding reducer (delta_rfun="auto": communities, counted ' f"with a shift null){at} needs at least {_AUTO_FEEDING_MIN_K} features " - f"and {_AUTO_FEEDING_MIN_T} timepoints; got {d} feature" - f"{'' if d == 1 else 's'}{source} and T = {T}. " + alternatives + f"and {_AUTO_FEEDING_MIN_T} timepoints" + f"{' to be fitted on (fit_timepoints)' if training else ''}; got " + f"{d} feature{'' if d == 1 else 's'}{source} and " + f"{'fit_timepoints' if training else 'T'} = {T}. " + alternatives ) @@ -1647,6 +1696,7 @@ def two_path_step( order=1, causal=False, min_samples=None, + fit_timepoints=None, ): """ Compute one order of the two-path pipeline from the previous feeding features. @@ -1773,14 +1823,16 @@ def two_path_step( widths are not chosen from the data. ``eye_weights`` on either path raises ``ValueError`` (co-fluctuations use series z-scored over the whole recording); - - ``rfun`` and ``delta_rfun`` must be given as None or a graph - measure (``"strength"``, ``"eigenvector_centrality"``, - ``"pagerank_centrality"``, ``"pagerank_centrality_abs"``): a reducer that is fitted to data (a model such - as ``"PCA"``, a summary, and ``"auto"``, the default) raises - ``NotImplementedError``. A function of your own (as ``cfun``, - ``rfun`` or ``delta_rfun``) is called as without ``causal``, with - one ``UserWarning`` that the guarantee does not cover what it - does; + - a reducer that is fitted to data (a model such as ``"PCA"``, a + summary, and ``"auto"``, the default of ``rfun`` and + ``delta_rfun``) needs ``fit_timepoints``: it is fitted on the + first ``fit_timepoints`` rows and then applied, unchanged, to + every row. None and the graph measures (``"strength"``, + ``"eigenvector_centrality"``, ``"pagerank_centrality"``, + ``"pagerank_centrality_abs"``) need no fit. A function of your + own (as ``cfun``, ``rfun`` or ``delta_rfun``) is called as + without ``causal``, with one ``UserWarning`` that the guarantee + does not cover what it does; - ``cfun=tc.wisfc`` raises ``ValueError`` (its default subject weights use the whole recording); ``functools.partial(tc.wisfc, subject_weights=...)`` is accepted; @@ -1812,6 +1864,44 @@ def two_path_step( timepoints raises ``ValueError`` before anything is computed. Given without ``causal=True``, it raises ``ValueError``. Default: None. + fit_timepoints : int or None + With ``causal=True`` (keyword-only), the number ``n`` of first rows + that the reducers are fitted on: an integer from 1 to the number + of timepoints. Every reducer that is fitted to data is fitted to + the correlations of rows ``0..n-1`` alone and then frozen: + hypertools models (the components of ``"PCA"``), the pair weights + and communities of ``WeightedStrength`` and ``Communities`` (with + ``n=None``, the shift null runs on those rows), and the automatic + reducers (``"auto"``), whose feeding step chooses between + communities and weighted strength on those rows. The rows + without defined correlations (the warm-up, see ``min_samples``) are + left out of the fits; a model needs 2 rows with defined + correlations there, a summary 1, the shift null 40 rows of + input. The fits do not change, bit for bit, whatever follows row + ``n-1``. Every row is then reduced with them: row ``t >= n`` is + unchanged (to 1e-9; bit for bit under replacement) when rows after + ``t`` are replaced or removed, and a row ``t < n`` (in sample: the + fits have read rows after it) when rows from ``n`` on are replaced + or removed. ``n`` equal to the number of timepoints fits on every + row. A model must reduce rows it was not fitted on and reproduce + its training rows to 1e-9 (``"PCA"``, ``"IncrementalPCA"``, + ``"FactorAnalysis"``, ``"FastICA"``, ...; ``"MDS"``, ``"TSNE"``, + ``"SpectralEmbedding"`` and ``"LocallyLinearEmbedding"`` raise + ``ValueError``); ``"PCA"`` is fitted with ``svd_solver="full"`` + unless a model dict gives a solver, because the randomized solver + scikit-learn chooses for large inputs does not reproduce its + rows. An output column of a model that is constant on the + training rows up to round-off (a range of at most 1e-9 of its + largest magnitude, or 1e-12 of the largest magnitude of the + output: for example a principal component along which those rows + do not vary) is frozen: at every row, a value within that + tolerance of the column's training mean is returned as exactly + that mean, so the next order does not correlate round-off. Output + columns of a summary that are constant up to round-off + are not set to their mean (see ``WeightedStrength``), and no + warning reports them. Not used by reducers that need no fit; + required (``ValueError``) when a reducer is fitted. Given without + ``causal=True``, it raises ``ValueError``. Default: None. Returns ------- @@ -1886,10 +1976,16 @@ def two_path_step( for a ``min_samples`` that is not None or a finite number >= 1 or that a built-in kernel of the call cannot reach; for ``min_samples`` given without ``causal=True``. - NotImplementedError + ValueError With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is - fitted to data (the defaults included); it would need - ``fit_timepoints``, the rows it is fitted on. + fitted to data (the defaults included) when ``fit_timepoints`` is + not given (this error is also a ``NotImplementedError``); for a + ``fit_timepoints`` that is not an integer from 1 to the number of + timepoints, or given without ``causal=True``; when the first + ``fit_timepoints`` rows hold no row with defined correlations for + a fit (2 for a model), or fewer than 40 rows for the default + feeding reducer or a shift null; and for a model that cannot + reduce rows it was not fitted on. RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. TypeError @@ -1939,6 +2035,16 @@ def two_path_step( ... delta_weights_params={"var": 25}) >>> X1.shape, D1.shape, int(np.isnan(D1).all(axis=1).sum()) ((300, 24), (300, 24), 2) + + With the default reducers, fitted on the first 200 rows and applied to + every row: + + >>> X1, D1 = two_path_step(data[0], causal=True, cfun=tc.autofc, + ... weights_params={"var": 100}, + ... delta_weights_params={"var": 25}, + ... fit_timepoints=200) + >>> X1.shape, D1.shape + ((300, 24), (300, 6)) """ if ( not isinstance(order, numbers.Integral) @@ -1961,6 +2067,8 @@ def two_path_step( ) single = not isinstance(data, (list, tuple)) subjects = format_data(data, fill_nan=False) + fit_timepoints = _check_fit_timepoints(fit_timepoints, causal, + subjects[0].shape[0]) estimator = {} if causal: _check_causal( @@ -1972,6 +2080,7 @@ def two_path_step( feeding_params={order: delta_weights_params}, events=[events], T=subjects[0].shape[0], n_subjects=len(subjects), include_zero=include_zero, min_samples=min_samples, + fit_timepoints=fit_timepoints, ) include_timepoints = "backward" estimator = {"causal": True, "min_samples": min_samples} @@ -1987,8 +2096,7 @@ def two_path_step( resolved = resolve_events( events, subjects[0].shape[0], len(subjects), events_params, causal=causal ) - X_next, D_next = _two_path_step( - subjects, + step = dict( weights_function=weights_function, weights_params=weights_params, cfun=cfun, @@ -2003,9 +2111,21 @@ def two_path_step( include_timepoints=include_timepoints, include_zero=include_zero, max_memory_gb=max_memory_gb, - events=resolved, **estimator, ) + frozen = None + if causal and (_needs_fit(analysis[order]) or _needs_fit(feeding[order])): + # the reducers are fitted on the first fit_timepoints rows alone, + # then applied to every row + frozen = {} + with _fit_pass(): + _two_path_step( + [x[:fit_timepoints] for x in subjects], + events=resolve_events(events, fit_timepoints, len(subjects), None, + causal=True), + record=frozen, **step, + ) + X_next, D_next = _two_path_step(subjects, events=resolved, frozen=frozen, **step) if single: if isinstance(X_next, list): X_next = X_next[0] @@ -2028,6 +2148,8 @@ def _two_path_step( previous_communities=None, input_elements=0, auto_analysis=False, + frozen=None, + record=None, **analysis ): """ @@ -2049,20 +2171,28 @@ def _two_path_step( ``auto_analysis``: the analysis reducer comes from ``rfun="auto"``; only then may a MemoryError of the analysis step carry the streamed-reducer hint. + + With ``causal`` (in ``analysis``): the reducers are fitted to the rows + given, which are the training rows of a causal fit, and ``record`` (a + dict) receives what reduced each path (``record["analysis"]``, + ``record["feeding"]``: see ``_apply_reducer``); or ``frozen``, such a + dict of an earlier call, reduces these rows without any fit. """ if delta_rfun is None: delta_rfun = analysis.get("rfun", "PCA") T, d = subjects[0].shape - if feed: - _check_auto_feeding(delta_rfun, d, T, order, previous_communities) + causal = analysis.get("causal", False) + frozen = frozen or {} + if feed and "feeding" not in frozen: + _check_auto_feeding(delta_rfun, d, T, order, previous_communities, + training=causal) analysis_streamed = _streams( analysis.get("rfun", "PCA"), analysis.get("cfun", isfc), - analysis.get("combine", null_combine), + analysis.get("combine", null_combine), causal=causal, ) feeding_streamed = feeding_function is not eye_weights and _is_summary(delta_rfun) n_outputs = 2 if feed and not (analysis_streamed or feeding_streamed) else 1 kernel_feeding = feed and feeding_function is not eye_weights - causal = analysis.get("causal", False) dense_analysis = _dense_analysis(analysis.get("weights_function"), analysis.get("cfun", isfc), causal) dense_feeding = feed and not _builtin_kernel(feeding_function) @@ -2137,6 +2267,7 @@ def _two_path_step( subjects, max_memory_gb=max_memory_gb, n_outputs=n_outputs, order=order, append_fit=True, kernel_feeding=kernel_feeding, held_elements=retained, reducers=(delta_rfun,) + reducers, input_elements=int(input_elements), + frozen=frozen.get("analysis"), record=record, **analysis ) if not feed: @@ -2160,14 +2291,31 @@ def _two_path_step( retained_elements=retained_m + fits, causal=causal, min_samples=analysis.get("min_samples"), + frozen=frozen.get("feeding"), + record=record, ) return X_next, D_next +@contextlib.contextmanager +def _fit_pass(): + """ + The pass of a causal call that fits the reducers on the first + ``fit_timepoints`` rows: the estimator's warnings about its rows are + not issued (the pass over every row, which follows, issues them). + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=r"(Subjects? [0-9, ]+: )?[0-9]+ of [0-9]+ timepoints have", + ) + yield + + def _check_causal(*, function, include_timepoints, weights_function, delta_weights_function, cfun, rfun, delta_rfun, analysis_rfun, feeding_rfun, analysis_params, feeding_params, events, T, - n_subjects, include_zero, min_samples): + n_subjects, include_zero, min_samples, fit_timepoints=None): """ The checks of ``features`` and ``two_path_step`` with ``causal=True`` (``function``: the name of the caller, for the messages), before @@ -2179,9 +2327,9 @@ def _check_causal(*, function, include_timepoints, weights_function, Raises ``ValueError`` for what has no causal form (a forward kernel, ``eye_weights``, kernel parameters that are not given, the default subject weights of ``wisfc``, events given as features, a - ``min_samples`` no row of a built-in kernel can reach) and - ``NotImplementedError`` for a reducer that is fitted to data; warns once - when ``cfun`` or a reducer is a function of the user's. + ``min_samples`` no row of a built-in kernel can reach, a reducer that + is fitted to data without ``fit_timepoints``); warns once when ``cfun`` + or a reducer is a function of the user's. """ side = str(include_timepoints).lower() if side in ("forward", "post"): @@ -2232,13 +2380,14 @@ def _check_causal(*, function, include_timepoints, weights_function, for name, given, resolved in (("rfun", rfun, analysis_rfun), ("delta_rfun", delta_rfun, feeding_rfun)): for k in sorted(resolved): - if _needs_fit(resolved[k]): - raise NotImplementedError( + if _needs_fit(resolved[k]) and fit_timepoints is None: + raise _FitTimepointsMissing( f"causal=True: {name}={_requested(given, k)!r} (order {k}) is " - "fitted to data and needs fit_timepoints (the rows it is " - f"fitted on), which {function} does not accept yet. Pass " - "rfun and delta_rfun as None or a graph measure such as " - "'strength' (the defaults are fitted)." + "fitted to data and needs fit_timepoints=n: the reducers " + "are then fitted on the first n rows and applied to every " + "row. Or pass rfun and delta_rfun as None or a graph " + "measure such as 'strength', which need no fit (the " + "defaults are fitted)." ) if min_samples is not None: # a number no kernel row can reach, whatever the length of the data @@ -2252,8 +2401,8 @@ def _check_causal(*, function, include_timepoints, weights_function, builtin = cfun is None or cfun in (isfc, autofc) or _fixed_weights_wisfc(cfun) theirs = [name for name, ours in ( ("cfun", builtin), - ("rfun", not any(callable(r) for r in analysis_rfun.values())), - ("delta_rfun", not any(callable(r) for r in feeding_rfun.values())), + ("rfun", not any(_theirs(r) for r in analysis_rfun.values())), + ("delta_rfun", not any(_theirs(r) for r in feeding_rfun.values())), ) if not ours] if theirs: one = len(theirs) == 1 @@ -2265,6 +2414,11 @@ def _check_causal(*, function, include_timepoints, weights_function, ) +def _theirs(reducer): + """True for a reducer that is a function of the user's (not a summary).""" + return callable(reducer) and not isinstance(reducer, _Summary) + + def _requested(value, k): """The reducer given for order ``k`` (an order map's value, or ``"auto"``).""" if isinstance(value, dict) and "model" not in value: @@ -2289,10 +2443,12 @@ def _width(out): def _step_info(k, inputs, x, delta, analysis_rfun, feeding_rfun, requested, - requested_delta): + requested_delta, feeding_fit=None): """ The ``return_info`` entries of order ``k`` of ``features``: one dict for the analysis path and, when it was computed, one for the feeding path. + ``feeding_fit``: the fit record of the feeding step when it is not the + last of ``feeding_rfun.fits_`` for this order (a frozen fit). """ d = _width(inputs) entries = [{ @@ -2307,11 +2463,12 @@ def _step_info(k, inputs, x, delta, analysis_rfun, feeding_rfun, requested, "effective": _describe(feeding_rfun), "input_width": d, "output_width": _width(delta), "labels": None, } - fit = None + fit = feeding_fit if isinstance(feeding_rfun, Communities): # this step's fit (the same object may also reduce the analysis path) - fit = next(f for f in reversed(feeding_rfun.fits_) - if f["order"] == k and f["path"] == "feeding") + if fit is None: + fit = next(f for f in reversed(feeding_rfun.fits_) + if f["order"] == k and f["path"] == "feeding") if fit.get("fallback") is None: entry["labels"] = fit["labels"].tolist() if getattr(feeding_rfun, "_from_auto", False): @@ -2398,6 +2555,8 @@ def features( return_info=False, causal=False, min_samples=None, + fit_timepoints=None, + return_model=False, ): """ Compute features of every order from 0 to ``order`` with the two-path pipeline. @@ -2463,7 +2622,12 @@ def features( The summaries' weights and communities are fitted on all timepoints and all events of a step (the fit is not causal, also with ``include_timepoints="backward"``); ``fit`` and ``transform`` of an - instance allow fitting on other data. + instance allow fitting on other data. With ``causal=True`` and + ``fit_timepoints=n`` every reducer is fitted on the first ``n`` rows + only: the pipeline first runs on those rows alone, order by order (each + order's fit reads the feeding features of those rows), and then on + every row with the fits frozen (see ``fit_timepoints`` and + ``FeaturesModel``). Parameters ---------- @@ -2701,7 +2865,11 @@ def features( dict: the kernel parameters of that step) and ``"warmup_rows"`` (the number of rows of the step's output that are entirely NaN, an int, or one int per subject when the output is a list), and - ``"constant_columns"`` is taken over the other rows. + ``"constant_columns"`` is taken over the other rows; the entry of + a step whose reducer was fitted has ``"fit_timepoints"`` (the + number of rows it was fitted on), and what describes a fit + (``"labels"``, ``"n_communities"``, ``"fallback"``, ...) is that + of the fit on those rows. Default: False. causal : bool If True (keyword-only), row ``t`` of every output is computed from @@ -2728,15 +2896,16 @@ def features( widths are not chosen from the data. ``eye_weights`` on either path raises ``ValueError`` (co-fluctuations use series z-scored over the whole recording); - - ``rfun`` and ``delta_rfun`` must be given as None or a graph - measure (``"strength"``, ``"eigenvector_centrality"``, - ``"pagerank_centrality"``, ``"pagerank_centrality_abs"``), - also in order maps: a reducer that is fitted to data (a model such - as ``"PCA"``, a summary, and ``"auto"``, the default) raises - ``NotImplementedError``. A function of your own (as ``cfun``, - ``rfun`` or ``delta_rfun``) is called as without ``causal``, with - one ``UserWarning`` that the guarantee does not cover what it - does; + - a reducer that is fitted to data (a model such as ``"PCA"``, a + summary, and ``"auto"``, the default of ``rfun`` and + ``delta_rfun``) needs ``fit_timepoints``: it is fitted on the + first ``fit_timepoints`` rows and then applied, unchanged, to + every row. None and the graph measures (``"strength"``, + ``"eigenvector_centrality"``, ``"pagerank_centrality"``, + ``"pagerank_centrality_abs"``) need no fit. A function of your + own (as ``cfun``, ``rfun`` or ``delta_rfun``) is called as + without ``causal``, with one ``UserWarning`` that the guarantee + does not cover what it does; - ``cfun=tc.wisfc`` raises ``ValueError`` (its default subject weights use the whole recording); ``functools.partial(tc.wisfc, subject_weights=...)`` is accepted; @@ -2768,6 +2937,53 @@ def features( timepoints raises ``ValueError`` before anything is computed. Given without ``causal=True``, it raises ``ValueError``. Default: None. + fit_timepoints : int or None + With ``causal=True`` (keyword-only), the number ``n`` of first rows + that the reducers are fitted on: an integer from 1 to the number + of timepoints. Every reducer that is fitted to data is fitted to + the correlations of rows ``0..n-1`` alone and then frozen: + hypertools models (the components of ``"PCA"``), the pair weights + and communities of ``WeightedStrength`` and ``Communities`` (with + ``n=None``, the shift null runs on those rows), and the automatic + reducers (``"auto"``), whose feeding step chooses between + communities and weighted strength on those rows. The rows + without defined correlations (the warm-up, see ``min_samples``) are + left out of the fits; a model needs 2 rows with defined + correlations there, a summary 1, the shift null 40 rows of + input. The fits do not change, bit for bit, whatever follows row + ``n-1``. Every row is then reduced with them: row ``t >= n`` is + unchanged (to 1e-9; bit for bit under replacement) when rows after + ``t`` are replaced or removed, and a row ``t < n`` (in sample: the + fits have read rows after it) when rows from ``n`` on are replaced + or removed. ``n`` equal to the number of timepoints fits on every + row. A model must reduce rows it was not fitted on and reproduce + its training rows to 1e-9 (``"PCA"``, ``"IncrementalPCA"``, + ``"FactorAnalysis"``, ``"FastICA"``, ...; ``"MDS"``, ``"TSNE"``, + ``"SpectralEmbedding"`` and ``"LocallyLinearEmbedding"`` raise + ``ValueError``); ``"PCA"`` is fitted with ``svd_solver="full"`` + unless a model dict gives a solver, because the randomized solver + scikit-learn chooses for large inputs does not reproduce its + rows. An output column of a model that is constant on the + training rows up to round-off (a range of at most 1e-9 of its + largest magnitude, or 1e-12 of the largest magnitude of the + output: for example a principal component along which those rows + do not vary) is frozen: at every row, a value within that + tolerance of the column's training mean is returned as exactly + that mean, so the next order does not correlate round-off. Output + columns of a summary that are constant up to round-off + are not set to their mean (see ``WeightedStrength``), and no + warning reports them. Not used by reducers that need no fit; + required (``ValueError``) when a reducer is fitted. Given without + ``causal=True``, it raises ``ValueError``. Default: None. + return_model : bool + If True (keyword-only; needs ``causal=True``), also return the + fitted pipeline as a ``tc.FeaturesModel``, last: ``(X, model)``, + ``((X, D), model)``, ``(X, info, model)`` or ``((X, D), info, + model)``. ``model.transform(data)`` computes the features of + other data (the same series with later rows, for example) with the + reducers as fitted here, causally and without fitting anything; + ``model.transform`` of this data returns these outputs. The model + can be pickled (see ``FeaturesModel``). Default: False. Returns ------- @@ -2781,6 +2997,9 @@ def features( info : list of dict Only with ``return_info=True`` (see ``return_info``); the call then returns ``(X, info)`` or ``((X, D), info)``. + model : FeaturesModel + Only with ``return_model=True`` (see ``return_model``), after the + other items. Warns ----- @@ -2848,10 +3067,16 @@ def features( for a ``min_samples`` that is not None or a finite number >= 1 or that a built-in kernel of the call cannot reach; for ``min_samples`` given without ``causal=True``. - NotImplementedError + ValueError With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is - fitted to data (the defaults included); it would need - ``fit_timepoints``, the rows it is fitted on. + fitted to data (the defaults included) when ``fit_timepoints`` is + not given (this error is also a ``NotImplementedError``); for a + ``fit_timepoints`` that is not an integer from 1 to the number of + timepoints, or given without ``causal=True``; when the first + ``fit_timepoints`` rows hold no row with defined correlations for + a fit (2 for a model), or fewer than 40 rows for the default + feeding reducer or a shift null; and for a model that cannot + reduce rows it was not fitted on. TypeError If ``rfun`` or ``delta_rfun`` is not None, a string, a dict or a callable, or ``delta_weights_function`` is not None or callable. @@ -3069,6 +3294,22 @@ def features( >>> changed = tc.features(later, **kw) >>> bool(np.array_equal(changed[2][:101], X[2][:101], equal_nan=True)) True + + Reducers that are fitted (here PCA and weighted strength) are fitted + on the first ``fit_timepoints`` rows and then frozen; the model applies + them to other data, such as the same series with more rows: + + >>> kw = dict(order=2, causal=True, cfun=tc.autofc, rfun="PCA", + ... delta_rfun="weighted_strength", weights_params={"var": 25}, + ... delta_weights_params={"var": 25}, fit_timepoints=120) + >>> X, model = tc.features(x[:150], return_model=True, **kw) + >>> model + FeaturesModel(order=2, fit_timepoints=120, n_features=5, n_subjects=1) + >>> longer = model.transform(x) + >>> longer[2].shape + (200, 5) + >>> bool(np.allclose(longer[2][:150], X[2], atol=1e-9, equal_nan=True)) + True """ if ( not isinstance(order, numbers.Integral) @@ -3078,6 +3319,12 @@ def features( raise ValueError(f"order must be a non-negative integer; got {order!r}.") order = int(order) min_samples = _check_min_samples(min_samples, causal) + if return_model and not causal: + raise ValueError( + "return_model=True applies with causal=True only (the model holds " + "the reducers fitted on the first fit_timepoints rows); pass " + "causal=True, or leave return_model out." + ) # every reducer is checked and resolved here, including ones a short run # never calls orders = range(1, order + 1) @@ -3126,7 +3373,7 @@ def features( delta_unreduced = all(feeding_rfun[k] is None for k in orders) S = len(subjects) - estimator = {} + fit_timepoints = _check_fit_timepoints(fit_timepoints, causal, T) if causal: _check_causal( function="features", include_timepoints=include_timepoints, @@ -3137,9 +3384,9 @@ def features( feeding_params=given_feeding, events=list(events.values()) if isinstance(events, dict) else [events], T=T, n_subjects=S, include_zero=include_zero, min_samples=min_samples, + fit_timepoints=fit_timepoints, ) include_timepoints = "backward" - estimator = {"causal": True, "min_samples": min_samples} # events are resolved (and features segmented) once, before anything is computed if order == 0: _check_events_order_zero(events, T, S, events_params, causal) @@ -3205,6 +3452,27 @@ def features( weights_function=weights_function, later_T=later_T, ) + if causal: + from .model import _causal_features # timecorr.model imports this module + + return _causal_features( + subjects, single, events, + dict( + order=order, weights_function=weights_function, + weights_params=analysis_params, cfun=cfun, combine=combine, + rfun=analysis_rfun, delta_rfun=feeding_rfun, ndims=ndims, + delta_weights_function=feeding_function, + delta_weights_params=feeding_params, include_zero=include_zero, + min_samples=min_samples, max_memory_gb=max_memory_gb, + requested={k: (_describe(_requested(rfun, k)), + _describe(_requested(delta_rfun, k))) for k in orders}, + auto={k: _auto_at(rfun, k) for k in orders}, + fed=list(fed), + ), + fit_timepoints=fit_timepoints, return_delta=return_delta, + return_info=return_info, return_model=return_model, + ) + X = [subjects] D = [subjects] fed_by = subjects # the feeding features the next order reads @@ -3257,7 +3525,6 @@ def features( input_elements=0 if k == 1 else _output_elements(fed_by), reducers=held_reducers, previous_communities=previous_communities, - **estimator, ) X.append(x) computed_at.append(rows) @@ -3280,17 +3547,10 @@ def features( if params is not None: entry["kernel_sd"] = _bandwidth(gaussian_weights, params) entry["sampling"] = int(rows[1] - rows[0]) if len(rows) > 1 else 1 - if causal: - # the kernel parameters of the step (copies) - for entry, params in zip(entries, (analysis_params[k], - feeding_params[k])): - entry["weights_params"] = dict(params) if delta is not None and not return_delta: # feeding features that are not returned: as computed computed = delta[0] if single else delta - entries[-1]["constant_columns"] = _constant_columns(computed, causal) - if causal: - entries[-1]["warmup_rows"] = _warmup_rows(computed) + entries[-1]["constant_columns"] = _constant_columns(computed) info.extend(entries) if delta is not None: fed_by = delta @@ -3325,8 +3585,6 @@ def features( for entry in info: if entry["path"] == "analysis" or return_delta: out = (X if entry["path"] == "analysis" else D)[entry["order"]] - entry["constant_columns"] = _constant_columns(out, causal) - if causal: - entry["warmup_rows"] = _warmup_rows(out) + entry["constant_columns"] = _constant_columns(out) return result, info return result diff --git a/timecorr/model.py b/timecorr/model.py new file mode 100644 index 00000000..3f7ede49 --- /dev/null +++ b/timecorr/model.py @@ -0,0 +1,455 @@ +""" +Causal features whose reducers are fitted once and then frozen. + +``features(..., causal=True, fit_timepoints=n)`` runs two passes of the +two-path pipeline, both with the causal estimator: + +1. the fit: the pipeline on the first ``n`` rows alone, every order. Each + reducer that is fitted to data (a hypertools model, ``WeightedStrength``, + ``Communities`` with its shift null, the automatic feeding reducer and its + fallback) is fitted to the correlations of those rows, and each order's + feeding features of those rows, reduced with the new fit, are the input + of the next order's fit. Later rows are not read, so the fits of a + series and of any longer series with the same first ``n`` rows are equal + bit for bit. +2. the output: the pipeline on every row, with the fits frozen. + +``FeaturesModel`` holds the settings and the fits of pass 1; +``FeaturesModel.transform`` is pass 2 on other data. ``_single_fit`` is +pass 1 and ``_causal_pass`` either pass. +""" + +import copy + +from .events import _has_features, _parse_spec, resolve_events_by_order +from .helpers import _FittedModel, format_data, gaussian_weights +from .higher_order import ( + _constant_columns, + _fit_pass, + _output_elements, + _step_info, + _two_path_step, + _warmup_rows, +) +from .summaries import Communities, _FittedSummary, _Summary +from .timecorr import _needs_fit + +__all__ = ["FeaturesModel"] + + +def _is_fit(frozen): + """True for what a fitted reducer leaves (a frozen summary or model).""" + return isinstance(frozen, (_FittedSummary, _FittedModel)) + + +def _events_by_order(events, T, n_subjects, order): + """The boundaries of each order for a causal pass over T rows (those at + or beyond T are left out); ``ValueError`` for events given as features.""" + if order == 0: + return {} + specs = list(events.values()) if isinstance(events, dict) else [events] + for spec in specs: + if _has_features(_parse_spec(spec, T, n_subjects, True)): + raise ValueError( + "causal=True: events given as features are segmented from the " + "whole recording. Pass the boundaries (the timepoints where a " + "new block starts), for example events=[100, 250]." + ) + return resolve_events_by_order(events, T, n_subjects, order, None, causal=True) + + +def _causal_pass(settings, subjects, events, *, steps=None, record=None, + keep_delta=True, single=False): + """ + One causal pass of the two-path pipeline over ``subjects`` (a list of + (T, K) arrays): ``(X, D, info)``, the lists of outputs by order + (``D[k]`` None for a feeding step that is not computed) and the + ``return_info`` entries. + + ``steps`` None: every reducer is fitted to the rows given (pass 1 of the + module docstring when they are the training rows; reducers without a + fit are simply applied), and ``record`` (a dict) receives, by order, + what reduced each path (``{"analysis": ..., "feeding": ...}``: a + ``_FittedSummary``, a ``_FittedModel``, or the reducer itself). With + ``steps`` (such a dict), nothing is fitted: pass 2. ``events``: the + specification, resolved for these rows. ``keep_delta``: whether the + feeding features of every order are kept (counted against + ``max_memory_gb``); ``single``: the data were one array (the entries of + ``info`` then describe arrays, not lists). + """ + s = settings + order = s["order"] + T = subjects[0].shape[0] + resolved = _events_by_order(events, T, len(subjects), order) + held = tuple({id(r): r for r in list(s["rfun"].values()) + + list(s["delta_rfun"].values()) if isinstance(r, _Summary)}.values()) + X, D, info = [subjects], [subjects], [] + fed_by = subjects + previous_communities = None + for k in range(1, order + 1): + kept = X[1:] + ([d for d in D[1:] if d is not None] if keep_delta + else ([] if k == 1 else [fed_by])) + used = {} + x, delta = _two_path_step( + fed_by, + delta_rfun=s["delta_rfun"][k], + auto_analysis=s["auto"][k], + max_memory_gb=s["max_memory_gb"], + order=k, + feed=k in s["fed"], + feeding_function=s["delta_weights_function"], + feeding_params=s["delta_weights_params"][k], + weights_function=s["weights_function"], + weights_params=s["weights_params"][k], + cfun=s["cfun"], + rfun=s["rfun"][k], + ndims=s["ndims"], + combine=s["combine"], + include_timepoints="backward", + include_zero=s["include_zero"], + events=resolved[k], + retained_elements=_output_elements(*kept), + input_elements=0 if k == 1 else _output_elements(fed_by), + reducers=held, + previous_communities=previous_communities, + causal=True, + min_samples=s["min_samples"], + frozen=None if steps is None else steps[k], + record=used, + ) + if record is not None: + record[k] = used + X.append(x) + D.append(delta) + feeding = used.get("feeding") + feeding_fit = feeding.fit if isinstance(feeding, _FittedSummary) else None + # explicit Communities only (see features) + previous_communities = ( + feeding_fit["n"] if feeding_fit is not None + and isinstance(s["delta_rfun"][k], Communities) + and not getattr(s["delta_rfun"][k], "_from_auto", False) else None + ) + entries = _step_info(k, fed_by, x, delta, s["rfun"][k], s["delta_rfun"][k], + *s["requested"][k], feeding_fit=feeding_fit) + for entry, params in zip(entries, (s["weights_params"][k], + s["delta_weights_params"][k])): + out = x if entry["path"] == "analysis" else delta + if single and isinstance(out, list): + out = out[0] + entry["weights_params"] = dict(params) # a copy + entry["constant_columns"] = _constant_columns(out, True) + entry["warmup_rows"] = _warmup_rows(out) + if _is_fit(used.get(entry["path"])): + entry["fit_timepoints"] = s["fit_timepoints"] + info.extend(entries) + if delta is not None: + fed_by = delta + return X, D, info + + +def _single_fit(settings, subjects, events): + """ + Pass 1: the fits of every order from the first ``fit_timepoints`` rows + of ``subjects`` alone, as ``{order: {"analysis": ..., "feeding": ...}}`` + (see ``_causal_pass``), or None when no reducer of a computed step is + fitted to data. The estimator's warnings about these rows are not + issued (pass 2 issues them for every row). + """ + s = settings + orders = range(1, s["order"] + 1) + needed = any(_needs_fit(s["rfun"][k]) for k in orders) or any( + _needs_fit(s["delta_rfun"][k]) for k in s["fed"]) + if not needed: + return None + n = s["fit_timepoints"] + steps = {} + with _fit_pass(): + _causal_pass(s, [x[:n] for x in subjects], events, record=steps, + keep_delta=False) + return steps + + +def _causal_features(subjects, single, events, settings, *, fit_timepoints, + return_delta, return_info, return_model): + """``features(..., causal=True)`` on formatted subjects, after its checks.""" + settings = dict(settings, fit_timepoints=fit_timepoints) + steps = _single_fit(settings, subjects, events) + model = FeaturesModel(settings, steps, n_features=subjects[0].shape[1], + n_subjects=len(subjects)) + result, info = model._transform(subjects, single, events, return_delta) + model.info = info + out = (result,) + ((info,) if return_info else ()) + ( + (model,) if return_model else ()) + return out[0] if len(out) == 1 else out + + +class FeaturesModel: + """ + The fitted two-path pipeline of a causal ``features`` call. + + Returned by ``features(..., causal=True, return_model=True)``; not made + directly. It holds what the call computed with: the order, the kernel + function and parameters of both paths at every order, ``cfun``, + ``combine``, ``include_zero``, ``min_samples``, ``ndims``, + ``max_memory_gb``, and the reducers of every order and path as they + were fitted on the first ``fit_timepoints`` rows (the components of a + model, the pair weights and communities of a summary, the choice an + automatic feeding step made). ``transform`` applies that pipeline to + other data without fitting anything. Events are not kept: ``transform`` + takes its own. + + Parameters + ---------- + settings : dict + The resolved arguments of the ``features`` call. + steps : dict or None + The fits by order and path (None: no reducer is fitted to data). + n_features : int + The number of columns of the data. + n_subjects : int + The number of subjects of the data. + + Attributes + ---------- + order : int + The highest order. + fit_timepoints : int or None + The number of first rows the reducers were fitted on (None: the + call gave none, and no reducer needed a fit). + n_features, n_subjects : int + The numbers of columns and of subjects of the data of the fit. + info : list of dict + The ``return_info`` entries of the ``features`` call. + fits : dict + ``{(order, path): fit}`` for every computed step, ``path`` being + ``"analysis"`` or ``"feeding"``: for a summary its record (a dict + as in ``fits_``, with the pair weights ``"weights"``, one (K, K) + array per subject, ``"mean_r"``, ``"labels"``, ...), for a model + the fitted hypertools model, and for a reducer without a fit the + reducer itself (None, a graph measure, a function). + weights_function, delta_weights_function : function + The kernel functions of the analysis and feeding paths. + weights_params, delta_weights_params : dict + The kernel parameters of each path, by order. + cfun, combine : function + The correlation and combine functions of the analysis path. + include_zero : bool + min_samples : float or None + ndims : int or None + max_memory_gb : float or None + As given to ``features``; ``transform`` uses them (assign another + ``max_memory_gb`` to change the limit of ``transform``). + + Notes + ----- + A model can be pickled when the arguments of the call can: a ``cfun``, + reducer or kernel function that is a lambda or a local function cannot. + Unpickling needs the same versions of timecorr, hypertools and + scikit-learn. + + Examples + -------- + >>> import numpy as np + >>> import timecorr as tc + >>> x = np.random.RandomState(0).randn(150, 6) + >>> X, model = tc.features(x, order=2, causal=True, cfun=tc.autofc, + ... weights_params={"var": 25}, + ... delta_weights_params={"var": 25}, + ... delta_rfun="weighted_strength", + ... fit_timepoints=100, return_model=True) + >>> model + FeaturesModel(order=2, fit_timepoints=100, n_features=6, n_subjects=1) + >>> sorted(model.fits) + [(1, 'analysis'), (1, 'feeding'), (2, 'analysis')] + >>> later = model.transform(x[:120]) + >>> bool(np.allclose(later[2], X[2][:120], atol=1e-9, equal_nan=True)) + True + """ + + def __init__(self, settings, steps, *, n_features, n_subjects): + self._settings = self._detached(settings) + self._steps = steps + self.n_features = int(n_features) + self.n_subjects = int(n_subjects) + self.info = [] + + @staticmethod + def _detached(settings): + """The settings with copies of the summary objects among the + reducers, without their fits: they only say how a step is computed + (the fits are in ``steps``), and the caller's objects are fitted + again by later calls.""" + copies = {} + + def detach(reducer): + if not isinstance(reducer, _Summary): + return reducer + if id(reducer) not in copies: + clone = copy.copy(reducer) + clone.fits_ = [] + copies[id(reducer)] = clone + return copies[id(reducer)] + + settings = dict(settings) + for name in ("rfun", "delta_rfun"): + settings[name] = {k: detach(r) for k, r in settings[name].items()} + for name in ("weights_params", "delta_weights_params"): + settings[name] = {k: copy.deepcopy(p) for k, p in settings[name].items()} + return settings + + # -- what the call computed with ----------------------------------------- + + order = property(lambda self: self._settings["order"]) + fit_timepoints = property(lambda self: self._settings["fit_timepoints"]) + weights_function = property(lambda self: self._settings["weights_function"]) + weights_params = property(lambda self: self._settings["weights_params"]) + delta_weights_function = property( + lambda self: self._settings["delta_weights_function"] or gaussian_weights) + delta_weights_params = property( + lambda self: self._settings["delta_weights_params"]) + cfun = property(lambda self: self._settings["cfun"]) + combine = property(lambda self: self._settings["combine"]) + include_zero = property(lambda self: self._settings["include_zero"]) + min_samples = property(lambda self: self._settings["min_samples"]) + ndims = property(lambda self: self._settings["ndims"]) + + @property + def max_memory_gb(self): + return self._settings["max_memory_gb"] + + @max_memory_gb.setter + def max_memory_gb(self, value): + self._settings["max_memory_gb"] = value + + @property + def fits(self): + s = self._settings + out = {} + for k in range(1, s["order"] + 1): + for path, reducers in (("analysis", s["rfun"]), ("feeding", s["delta_rfun"])): + if path == "feeding" and k not in s["fed"]: + continue + step = reducers[k] if self._steps is None else self._steps[k][path] + if isinstance(step, _FittedSummary): + step = step.fit + elif isinstance(step, _FittedModel): + step = step.model + out[(k, path)] = step + return out + + def __repr__(self): + return ( + f"FeaturesModel(order={self.order}, fit_timepoints={self.fit_timepoints}, " + f"n_features={self.n_features}, n_subjects={self.n_subjects})" + ) + + # -- applying it ----------------------------------------------------------- + + def transform(self, data, return_delta=False, return_info=False, *, events=None): + """ + Features of ``data`` from the fitted pipeline, without fitting. + + Every row is computed causally, as by the ``features`` call that + made the model: row ``t`` of every output uses rows ``0..t`` of + ``data`` and the frozen fits only, so it is unchanged (to 1e-9; see + ``features``) when later rows are replaced or removed, and + ``transform`` of the data of the fit returns what that call + returned. + + Parameters + ---------- + data : numpy.ndarray, pandas.DataFrame, polars.DataFrame, or list of these + One timepoints-by-features matrix per subject, with the number + of features of the fit (``n_features``) and any number of + timepoints (one or more). The number of subjects must be that + of the fit (``n_subjects``) when a summary was fitted (each + subject is summarized with the pair weights fitted to the + subject at its position); a pipeline without summaries takes + any number. + return_delta : bool + If True, also return the feeding features ``[D_0, ..., + D_order]``; the ``features`` call must have computed the last + of them (``return_delta=True`` there). Default: False. + return_info : bool + If True, also return the list of dicts ``features`` returns + with ``return_info=True`` and ``causal=True``, for this data. + Default: False. + events : None, dict, array-like, or list + Event boundaries that restrict the kernels (keyword-only), as + in ``features`` with ``causal=True`` (boundaries only; a dict + by order; boundaries at or beyond the end of ``data`` are + ignored). The events of the ``features`` call are not kept: + give them again, extended to this data, if the fit used any. + Default: None (no restriction). + + Returns + ------- + X : list + ``[X_0, ..., X_order]``, as ``features`` returns it (arrays for + array input, lists of arrays for list input unless ``combine`` + returns one array). The first rows of every order are NaN + (see ``min_samples`` of ``features``). + D : list + Only with ``return_delta=True``: ``[D_0, ..., D_order]``; the + call then returns ``(X, D)``. + info : list of dict + Only with ``return_info=True``; the call then returns ``(X, + info)`` or ``((X, D), info)``. + + Raises + ------ + ValueError + If the data have another number of features than the fit, or + another number of subjects when a summary was fitted; if + ``return_delta=True`` and the fit did not compute the last + feeding step; for events given as features or malformed. + MemoryError + As ``features``, with ``max_memory_gb`` of the model. + + Examples + -------- + >>> import numpy as np + >>> import timecorr as tc + >>> rng = np.random.RandomState(0) + >>> x = rng.randn(150, 6) + >>> X, model = tc.features(x, order=2, causal=True, cfun=tc.autofc, + ... weights_params={"var": 25}, + ... delta_weights_params={"var": 25}, + ... delta_rfun="weighted_strength", + ... fit_timepoints=100, return_model=True) + >>> same = model.transform(x) + >>> bool(np.array_equal(same[2], X[2], equal_nan=True)) + True + + Other data with 6 features, of any length: + + >>> new = model.transform(rng.randn(40, 6)) + >>> new[1].shape, new[2].shape + ((40, 6), (40, 12)) + """ + single = not isinstance(data, (list, tuple)) + subjects = format_data(data, fill_nan=False) + K = subjects[0].shape[1] + if K != self.n_features: + raise ValueError( + f"the model was fitted to data with {self.n_features} features; " + f"got {K}." + ) + if return_delta and self.order and self.order not in self._settings["fed"]: + raise ValueError( + f"return_delta=True: the feeding features of order {self.order} " + "were not computed by the features call that made this model; " + "call features with return_delta=True." + ) + result, info = self._transform(subjects, single, events, return_delta) + return (result, info) if return_info else result + + def _transform(self, subjects, single, events, return_delta): + """Pass 2 on formatted subjects: ``(result, info)``.""" + X, D, info = _causal_pass(self._settings, subjects, events, + steps=self._steps, keep_delta=return_delta, + single=single) + if single: + X = [x[0] if isinstance(x, list) else x for x in X] + D = [d if d is None else d[0] for d in D] + return ((X, D) if return_delta else X), info diff --git a/timecorr/summaries.py b/timecorr/summaries.py index cf2bec1b..8cfa2563 100644 --- a/timecorr/summaries.py +++ b/timecorr/summaries.py @@ -18,6 +18,8 @@ the threshold of the automatic number of communities. """ +import copy +import functools import numbers import warnings from fractions import Fraction @@ -28,11 +30,13 @@ from ._kernels import LagKernel from .helpers import ( _WCORR_NAN_PRODUCTS, + _causal_clean, _corr_row_blocks, _fisher_mean, _kernel_work_elements, _kernels_message, _nan_weighted_mean, + _own_reference, _subject_kernels, _subject_weight_matrix, _warn_user, @@ -618,8 +622,10 @@ def check(i, label): ) return [check(i, f"fit_index[{u}]") for u, i in enumerate(indices)] - def _transform_fit(self, fit, corrs, fit_index=None): - """``transform`` with the fit record ``fit`` (see ``_auto_emitter``).""" + def _transform_fit(self, fit, corrs, fit_index=None, constant=True): + """``transform`` with the fit record ``fit`` (see ``_auto_emitter``). + ``constant=False`` leaves out ``_warn_constant`` (the causal mode: + no column is set to its mean, which would read every row).""" name = type(self).__name__ units, K, single = _as_units(corrs, name) K_fit = fit["weights"][0].shape[0] @@ -636,7 +642,8 @@ def _transform_fit(self, fit, corrs, fit_index=None): out = np.zeros((R.shape[2], c)) self._emit(fit, unit, 0, K, R, out) outs.append(out) - self._warn_constant(outs) + if constant: + self._warn_constant(outs) return outs[0] if single else outs def _warn_constant(self, outs): @@ -1152,6 +1159,54 @@ def _auto_emitter(summary, fit, K, order=None): return _auto_fallback() +class _FittedSummary: + """ + One fit of a summary, frozen (the causal mode of ``timecorr`` and + ``features``): ``summary``, a copy of the summary that emits the output + (the fallback of an automatic feeding step included) and ``fit``, its + record (as in ``fits_``). ``apply`` summarizes other correlations with + it; neither changes when the summary it came from is fitted again. + """ + + def __init__(self, summary, fit): + fit = dict(fit) + emitter = _auto_fallback() if fit.get("fallback") else copy.copy(summary) + emitter.fits_ = [fit] + self.summary = emitter + self.fit = fit + + @property + def n_units(self): + return len(self.fit["weights"]) + + def check_units(self, n_units, K): + """``ValueError`` unless the correlations are those of ``n_units`` + units of the fit's number of nodes: each unit uses the pair weights + fitted to the unit at its position.""" + name = type(self.summary).__name__ + K_fit = self.fit["weights"][0].shape[0] + if K != K_fit: + raise ValueError( + f"{name}: the fit has {K_fit} nodes but the correlations have " + f"{K} nodes." + ) + if n_units != self.n_units: + raise ValueError( + f"{name}: the fit holds pair weights of {self.n_units} " + f"subject{'s' if self.n_units != 1 else ''} (each subject is " + f"summarized with its own); got {n_units}. Pass the same " + "number of subjects, in the order of the fit." + ) + + def apply(self, arrays): + """The summary of a list of (rows, K(K+1)/2) arrays of finite + correlations (a list of arrays), unit u with fitted unit u; no + column is set to its mean.""" + units, K, _ = _as_units(arrays, type(self.summary).__name__) + self.check_units(len(units), K) + return self.summary._transform_fit(self.fit, units, constant=False) + + # ---------------------------------------------------------------------------- # streaming: correlations in row blocks # ---------------------------------------------------------------------------- @@ -1219,7 +1274,10 @@ def _block_rows_for(T, K, S, max_bytes, dense=False): def _correlation_kind(cfun): - """``"auto"``, ``"isfc"`` or ``"wisfc"`` for the supported correlation functions.""" + """``"auto"``, ``"isfc"`` or ``"wisfc"`` for the supported correlation + functions (``functools.partial(wisfc, subject_weights=...)`` is ``wisfc``).""" + if isinstance(cfun, functools.partial) and cfun.func is wisfc: + return "wisfc" for kind, f in (("auto", autofc), ("isfc", isfc), ("wisfc", wisfc)): if cfun is f: return kind @@ -1277,7 +1335,7 @@ def _fisher_rows(R, Rt): flat[k0:k1] = _fisher_mean(np.stack([flat[k0:k1], flat_t[k0:k1]]), axis=0) -def _unit_row_blocks(a, ref, kernel, symmetric, b): +def _unit_row_blocks(a, ref, kernel, symmetric, b, estimator=None): """ Rows of one subject's (K, K, T') correlations as ``wisfc`` returns them (before ``mat2vec``), in blocks of b rows: ``(i0, i1, R, cancelled_all, @@ -1286,18 +1344,31 @@ def _unit_row_blocks(a, ref, kernel, symmetric, b): autocorrelation; otherwise each block holds rows of ``C`` (subject versus reference) and of ``C.T`` (reference versus subject), averaged in Fisher z space as ``_fisher_symmetrize`` does. + + ``estimator``: the keyword arguments of the causal estimator + (``causal=True``, ``min_samples``), or None. The timepoints it leaves + undefined are NaN in every block. """ + estimator = estimator or {} if symmetric: - for i0, i1, R, cancelled, sparse in _corr_row_blocks(a, ref, kernel, True, b): + for i0, i1, R, cancelled, sparse in _corr_row_blocks(a, ref, kernel, True, b, + **estimator): yield i0, i1, R, cancelled, sparse return - forward = _corr_row_blocks(a, ref, kernel, False, b) - backward = _corr_row_blocks(ref, a, kernel, False, b) + forward = _corr_row_blocks(a, ref, kernel, False, b, **estimator) + backward = _corr_row_blocks(ref, a, kernel, False, b, **estimator) for (i0, i1, R, cancelled, sparse), (_, _, Rt, _, _) in zip(forward, backward): R = np.ascontiguousarray(R) Rt = np.ascontiguousarray(Rt) + undefined = None + if estimator: + undefined = np.isnan(R[0, 0]) | np.isnan(Rt[0, 0]) + R[:, :, undefined] = 0 + Rt[:, :, undefined] = 0 _fisher_rows(R, Rt) del Rt + if undefined is not None: + R[:, :, undefined] = np.nan yield i0, i1, R, cancelled, sparse @@ -1306,11 +1377,20 @@ class _Units: The fitting units of a streamed step: each subject, its kernel and its reference (the subject's own data for ``autofc``; otherwise the weighted mean of the subjects that ``wisfc`` correlates it with). + + ``estimator``: the keyword arguments of the causal estimator + (``causal=True``, ``min_samples``) or None. With it, the blocks hold 0 + at the timepoints the estimator leaves undefined, and ``undefined[s]`` + is their mask (set when subject s's blocks are read). """ - def __init__(self, subjects, kernels, cfun, grouping=None): + def __init__(self, subjects, kernels, cfun, grouping=None, estimator=None): self.kind = _correlation_kind(cfun) + self.estimator = dict(estimator or {}) self.subjects = _as_subjects(subjects) + if self.estimator: + self.subjects = [_causal_clean(x) for x in self.subjects] + self.undefined = [None] * len(self.subjects) self.has_nan = any(bool(np.isnan(x).any()) for x in self.subjects) S = len(self.subjects) if grouping is None: @@ -1333,6 +1413,11 @@ def __init__(self, subjects, kernels, cfun, grouping=None): _subject_weight_matrix(self.subjects, 1 - np.eye(S)) if self.kind == "isfc" else None ) + if isinstance(cfun, functools.partial): + # wisfc with subject weights of the caller's + self.weights = _subject_weight_matrix( + self.subjects, cfun.keywords["subject_weights"] + ) self.stacked = np.stack(self.subjects, axis=2) self._mean = _nan_weighted_mean @@ -1344,6 +1429,8 @@ def kernel(self, s): def blocks(self, s, b): a = self.subjects[s] + if self.estimator: + return self._defined_blocks(s, b) if self.kind == "auto": return _unit_row_blocks(a, a, self.kernel(s), True, b) if self.weights is None: @@ -1352,30 +1439,61 @@ def blocks(self, s, b): symmetric = bool(np.array_equal(a, ref, equal_nan=True)) return _unit_row_blocks(a, ref, self.kernel(s), symmetric, b) + def _defined_blocks(self, s, b): + """``blocks`` of the causal estimator, as ``wisfc(..., causal=True)`` + computes subject s's correlations: whether the reference is the + subject's own data is read from the subject weights (comparing the + samples would read every timepoint).""" + a = self.subjects[s] + own = self.kind == "auto" or _own_reference(self.weights[s, :], s) + ref = a if own else self._mean(self.stacked, self.weights[s, :]) + for i0, i1, R, cancelled, sparse in _unit_row_blocks( + a, ref, self.kernel(s), own, b, self.estimator): + undefined = np.isnan(R[0, 0]) + if undefined.any(): + R[:, :, undefined] = 0 + self.undefined[s] = undefined + yield i0, i1, R, cancelled, sparse + def _accumulate_units(units, K, T_out, signed, b, masks=None): """ Pass 1: one fitting state per unit; with ``masks`` (a pair of lists, one - entry per distinct kernel), the estimator's cancelled and sparse masks - are merged into it as ``wisfc`` merges them. + entry per distinct kernel; three with the causal estimator), the + estimator's cancelled and sparse (and undefined) masks are merged into + it as ``wisfc`` merges them. With the causal estimator, a state's + ``"T"`` is the number of defined timepoints (the others add nothing to + the sums). """ states = [] for s in range(len(units)): state = _new_state(K, T_out, signed) - cancelled = np.ones(T_out, dtype=bool) - sparse = np.zeros(T_out, dtype=bool) - for i0, i1, R, c, f in units.blocks(s, b): - _accumulate(state, i0, i1, R) - cancelled &= c - sparse |= f - if masks is not None: - g = units.group_of[s] - masks[0][g] = masks[0][g] | cancelled - masks[1][g] = masks[1][g] | sparse + _read_blocks(units, s, b, T_out, masks, + lambda i0, i1, R: _accumulate(state, i0, i1, R)) + if units.undefined[s] is not None: + state["T"] = int(T_out - np.sum(units.undefined[s])) states.append(state) return states +def _read_blocks(units, s, b, T_out, masks, use): + """Call ``use(i0, i1, R)`` for every block of unit ``s`` and merge the + estimator's masks into ``masks`` (see ``_accumulate_units``; None: not + merged).""" + cancelled = np.ones(T_out, dtype=bool) + sparse = np.zeros(T_out, dtype=bool) + for i0, i1, R, c, f in units.blocks(s, b): + use(i0, i1, R) + cancelled &= c + sparse |= f + if masks is not None: + g = units.group_of[s] + masks[0][g] = masks[0][g] | cancelled + masks[1][g] = masks[1][g] | sparse + if len(masks) > 2 and units.undefined[s] is not None: + masks[2][g] = masks[2][g] | units.undefined[s] + + def _shift_lags(rng, T, K, L): """ K circular lags from the n integers in ``[L, T - L]``, drawn with the @@ -1549,7 +1667,7 @@ def block(self, i0, i1, c0, c1): def _shift_null_threshold( subjects, kernels, n_null=5, bandwidth=5.0, max_block_elements=None, - row_stride=None, + row_stride=None, estimator=None, ): """ Threshold of the automatic number of communities (``autofc`` steps). @@ -1585,6 +1703,15 @@ def _shift_null_threshold( (event-masked kernels), whole columns are shifted across event boundaries while the event masks stay fixed. + ``estimator``: the keyword arguments of the causal estimator + (``causal=True``, ``min_samples``) or None. With it, the subjects are + the training rows of a causal fit: the correlations are the causal + estimator's (averaged over its defined timepoints), and the rows of a + subject that are entirely missing (the warm-up rows of an earlier + order) stay where they are while each column is shifted circularly + among the subject's other rows (``T`` above is then the smallest number + of such rows of a subject). + Raises ------ ValueError @@ -1592,10 +1719,16 @@ def _shift_null_threshold( """ subjects = _as_subjects(subjects) T, K = subjects[0].shape + present = None + if estimator: + subjects = [_causal_clean(x) for x in subjects] + present = [np.flatnonzero(~np.isnan(x).all(axis=1)) for x in subjects] + T = min(len(rows) for rows in present) if T < 40: raise ValueError( - f"the shift null needs T >= 40 timepoints (got T = {T}); give the " - "number of communities n." + f"the shift null needs T >= 40 timepoints (got T = {T}" + f"{' with data in the training span' if estimator else ''}); give " + "the number of communities n." ) L = int(min(T // 4, max(10, 10 * float(bandwidth)))) n_null = _check_n_null(n_null) @@ -1614,26 +1747,37 @@ def _shift_null_threshold( stacklevel=2, ) rng = np.random.default_rng(0) - probe = _Units(subjects, kernels, autofc) + probe = _Units(subjects, kernels, autofc, estimator=estimator) null_kernels = probe.kernels if row_stride is None: row_stride = _null_stride(null_kernels) if row_stride > 1: null_kernels = [_every_nth_row(k, int(row_stride)) for k in null_kernels] T_out = null_kernels[0].shape[0] - b = _rows_per_block(max_block_elements, T_out, K, T, probe.has_nan) + b = _rows_per_block(max_block_elements, T_out, K, subjects[0].shape[0], + probe.has_nan) rows = np.arange(T)[:, None] cols = np.arange(K) top = [] for _ in range(n_null): shifted = [] - for x in subjects: + for s, x in enumerate(subjects): lags = _shift_lags(rng, T, K, L) - shifted.append(x[(rows - lags[None, :]) % T, cols]) + if present is None: + shifted.append(x[(rows - lags[None, :]) % T, cols]) + continue + # among the subject's rows with data (all of them at order 1) + kept = present[s] + moved = np.full_like(x, np.nan) + moved[kept] = x[kept][ + (np.arange(len(kept))[:, None] - lags[None, :]) % len(kept), cols] + shifted.append(moved) units = _Units( - shifted, kernels, autofc, grouping=(null_kernels, probe.group_of) + shifted, kernels, autofc, grouping=(null_kernels, probe.group_of), + estimator=estimator, ) states = _accumulate_units(units, K, T_out, False, b) + _check_defined(states) del units, shifted wbar = np.mean([_pair_weights(s["sum_r2"], s["T"]) for s in states], axis=0) top.append(float(np.linalg.eigvalsh(_centered(wbar))[-1])) @@ -1652,6 +1796,8 @@ def _streamed_summary( auto_n=False, bandwidth=5.0, null_row_stride=None, + estimator=None, + fitted=None, ): """ A summary of the subjects' correlations, computed in row blocks. @@ -1695,6 +1841,19 @@ def _streamed_summary( ``row_stride`` of ``_shift_null_threshold`` (None: every s-th timepoint for stationary built-in kernels, every timepoint otherwise, chosen only when the null runs). Default: None. + estimator : dict or None + The keyword arguments of the causal estimator (``causal=True``, + ``min_samples``): the correlations are ``cfun(subjects, kernels, + **estimator)`` (``cfun`` may then be ``functools.partial(wisfc, + subject_weights=...)``), the timepoints the estimator leaves + undefined are left out of the fit and are rows of NaN in the + output, and no output column is set to its mean (no warning about + constant columns either). Default: None. + fitted : _FittedSummary or None + A frozen fit: the summary is not fitted (no pass 1, ``fits_`` + unchanged) and the output is that fit's summary of these + subjects' correlations, subject s with fitted unit s. Default: + None. Returns ------- @@ -1709,15 +1868,26 @@ def _streamed_summary( ------ ValueError For an unsupported ``cfun``, the summary's fitting errors, or - ``auto_n`` with a ``cfun`` other than ``autofc``. + ``auto_n`` with a ``cfun`` other than ``autofc``; with + ``estimator``, when a subject has no defined timepoint to fit; + with ``fitted``, when the number of nodes or of subjects differs + from the fit's. MemoryError If one row of correlations (``K * T'`` elements) exceeds ``max_block_elements``. """ - units = _Units(subjects, kernels, cfun) + units = _Units(subjects, kernels, cfun, estimator=estimator) T, K = units.subjects[0].shape T_out = units.kernels[0].shape[0] b = _rows_per_block(max_block_elements, T_out, K, T, units.has_nan) + n_kernels = len(units.kernels) + masks = ([False] * n_kernels, [False] * n_kernels) + if estimator: + masks += ([False] * n_kernels,) + if fitted is not None: + fitted.check_units(len(units), K) + outs = _emit_units(units, fitted.summary, fitted.fit, K, T_out, b, masks) + return outs, _units_message(units, masks) null_threshold = None if auto_n and summary._needs_communities and summary.n is None: @@ -1736,13 +1906,13 @@ def _streamed_summary( bandwidth=bandwidth, max_block_elements=max_block_elements, row_stride=null_row_stride, + estimator=estimator, ) summary._check_fit(K, null_threshold) - n_kernels = len(units.kernels) - masks = ([False] * n_kernels, [False] * n_kernels) states = _accumulate_units(units, K, T_out, summary.signed, b, masks) - message = _kernels_message(units.kernels, units.group_of, masks[0], masks[1]) + _check_defined(states) + message = _units_message(units, masks) summary._fit_states( states, K, order=order, path=path, null_threshold=null_threshold, n_null=None if null_threshold is None else summary.n_null, @@ -1751,13 +1921,48 @@ def _streamed_summary( fit = summary.fits_[-1] emitter = _auto_emitter(summary, fit, K, order) + outs = _emit_units(units, emitter, fit, K, T_out, b, None) + if not estimator: + emitter._warn_constant(outs) + return outs, message + + +def _check_defined(states): + """``ValueError`` when a unit of a causal fit has no defined timepoint.""" + for s, state in enumerate(states): + if state["T"] < 1: + raise ValueError( + "causal=True: the rows the reducers are fitted on " + f"(fit_timepoints) hold no timepoint with defined correlations" + f"{'' if len(states) == 1 else f' for subject {s}'} (the first " + "rows of every order are undefined: see min_samples). Raise " + "fit_timepoints." + ) + + +def _units_message(units, masks): + """The estimator's warning of a streamed step (see ``_kernels_message``).""" + if len(masks) > 2: + return _kernels_message(units.kernels, units.group_of, masks[0], masks[1], + masks[2], units.estimator.get("min_samples")) + return _kernels_message(units.kernels, units.group_of, masks[0], masks[1]) + + +def _emit_units(units, emitter, fit, K, T_out, b, masks): + """ + Pass 2: one (T_out, c) output per unit, unit s with fitted unit s of + ``fit``, emitted by ``emitter``. With the causal estimator, the + timepoints it leaves undefined are rows of NaN. ``masks``: as in + ``_accumulate_units`` (None: the masks are not merged). + """ c = emitter._n_columns(fit, K) outs = [] for s in range(len(units)): unit = emitter._unit_params(fit, s) out = np.zeros((T_out, c)) - for i0, i1, R, _, _ in units.blocks(s, b): - emitter._emit(fit, unit, i0, i1, R, out) + _read_blocks(units, s, b, T_out, masks, + lambda i0, i1, R: emitter._emit(fit, unit, i0, i1, R, out)) + if units.undefined[s] is not None: + out[units.undefined[s]] = np.nan outs.append(out) - emitter._warn_constant(outs) - return outs, message + return outs diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 36de0238..a781a32a 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -1,6 +1,7 @@ # coding: utf-8 import functools +import numbers import warnings import numpy as np @@ -16,6 +17,10 @@ from .helpers import ( _GRAPH_MEASURES, _MIN_SAMPLES_RTOL, + _SUMMARY_NAMES, + _FittedModel, + _is_model, + _model_reduce, _abs_weights, _as_kernel_array, _causal_clean, @@ -277,8 +282,207 @@ def _needs_fit(rfun): return isinstance(rfun, str) and rfun not in _GRAPH_MEASURES +class _FitTimepointsMissing(ValueError, NotImplementedError): + """ + ``causal=True`` with a reducer that is fitted to data and no + ``fit_timepoints``. A ``ValueError``; also a ``NotImplementedError``, + which these calls raised before ``fit_timepoints`` existed. + """ + + +def _check_fit_timepoints(fit_timepoints, causal, T=None): + """ + ``fit_timepoints`` as None or an int: ``ValueError`` unless it is None + or an integer in ``1..T`` (``T`` None: any integer >= 1), and when it is + given without ``causal=True``. + """ + if fit_timepoints is None: + return None + if ( + isinstance(fit_timepoints, (bool, np.bool_)) + or not isinstance(fit_timepoints, numbers.Integral) + or fit_timepoints < 1 + ): + raise ValueError( + "fit_timepoints must be None or a positive integer (the number of " + f"first rows the reducers are fitted on); got {fit_timepoints!r}." + ) + if not causal: + raise ValueError( + f"fit_timepoints={fit_timepoints!r} applies with causal=True only; " + "pass causal=True, or leave fit_timepoints out." + ) + if T is not None and fit_timepoints > T: + raise ValueError( + f"fit_timepoints={fit_timepoints} is more than the {T} " + f"timepoint{'s' if T != 1 else ''} of the data; pass at most {T} " + "(every row is then in the rows the reducers are fitted on)." + ) + return int(fit_timepoints) + + +def _defined_rows(arrays): + """For each array, the mask of its rows that are not entirely NaN.""" + return [~np.isnan(np.asarray(a)).all(axis=1) for a in arrays] + + +def _on_defined(arrays, f, width): + """ + ``f`` (a list of arrays in, a list of arrays out, row by row) applied to + the rows of ``arrays`` that are not entirely NaN; the other rows stay + rows of NaN. ``width``: the number of output columns when no array has + such a row (None: found by reducing a row of zeros). + """ + arrays = [np.asarray(a, dtype=np.float64) for a in arrays] + defined = _defined_rows(arrays) + kept = [k for k, d in enumerate(defined) if d.any()] + # every row is passed, the undefined ones as rows of zeros: a row is then + # reduced at the same position of an array of the same shape whatever + # the later rows hold, so replacing later rows (by NaN too) changes no + # bit of it (the round-off of a matrix product can depend on its shape) + filled = [np.where(defined[k][:, None], arrays[k], 0.0) for k in kept] + reduced = f(filled) if kept else [] + if reduced: + width = np.asarray(reduced[0]).shape[1] + elif width is None: + # no row to reduce: the width of the reduction of a row of zeros + width = np.asarray(f([np.zeros((1, arrays[0].shape[1]))])[0]).shape[1] + out = [np.full((a.shape[0], width), np.nan) for a in arrays] + for k, r in zip(kept, reduced): + out[k][defined[k]] = np.asarray(r)[defined[k]] + return out + + +# a fitted model must reproduce its own training rows to this (relative to +# the largest of them, at least 1) to be used on other rows +_REFIT_ATOL = 1e-9 + + +def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=False, + name="rfun"): + """ + ``rfun`` fitted to the rows of ``corrs`` (an array or a list of arrays + of vectorized correlations) that are not entirely NaN, for + ``causal=True``: what ``_apply_frozen`` applies to these or other rows. + + A summary (object or name) gives a ``_FittedSummary`` (the object's + ``fits_`` gains the fit, with ``order`` and ``path``; ``append_fit`` as + in ``higher_order._apply_reducer``), a model a ``helpers._FittedModel``; + None, a graph measure and a function of the user's are returned as they + are (nothing to fit). + + ``ValueError`` when the rows hold no defined row to fit (a model: fewer + than 2), and for a model that cannot reduce rows it was not fitted on + or does not reproduce its training rows (to ``_REFIT_ATOL``). + """ + from .summaries import _auto_emitter, _FittedSummary, _from_name, _Summary + + summary = rfun + if isinstance(rfun, str) and rfun in _SUMMARY_NAMES: + summary = _from_name(rfun) + is_summary = isinstance(summary, _Summary) + if not is_summary and not _is_model(rfun): + return rfun + arrays = corrs if isinstance(corrs, list) else [corrs] + arrays = [np.asarray(a, dtype=np.float64) for a in arrays] + rows = [a[d] for a, d in zip(arrays, _defined_rows(arrays))] + at = "" if order is None else f" at order {order}" + fewest = min(len(r) for r in rows) if is_summary else sum(len(r) for r in rows) + if fewest < (1 if is_summary else 2): + raise ValueError( + f"causal=True: the rows {name} is fitted on (fit_timepoints){at} " + f"hold {'no row' if is_summary else 'fewer than 2 rows'} with " + "defined correlations (the first rows of every order are " + "undefined: see min_samples). Raise fit_timepoints." + ) + if is_summary: + summary.fit(rows, order=order, path=path) + fit = summary.fits_[-1] + K = fit["weights"][0].shape[0] + _auto_emitter(summary, fit, K, order) + if not append_fit: + del summary.fits_[:-1] + return _FittedSummary(summary, fit) + rfun = _exact_pca(rfun) + reduced, fitted = _model_reduce(rows, rfun, ndims, return_model=True) + label = rfun.get("model") if isinstance(rfun, dict) else rfun + label = getattr(label, "__name__", None) or str(label) + try: + if fitted.model is None: + raise NotImplementedError("hypertools returned no fitted model") + again = fitted.apply(rows) + except (NotImplementedError, AttributeError, TypeError) as err: + raise ValueError( + f"causal=True: the model {label!r} ({name}{at}) cannot reduce rows it " + f"was not fitted on ({err}), so it cannot be fitted on the first " + "rows and applied to later ones. Use a model with an out-of-sample " + "transform, such as 'PCA', 'IncrementalPCA' or 'FactorAnalysis'." + ) from err + worst = max(float(np.max(np.abs(np.asarray(r) - a), initial=0.0)) + for r, a in zip(reduced, again)) + scale = max(1.0, max(float(np.max(np.abs(a), initial=0.0)) for a in again)) + if not worst <= _REFIT_ATOL * scale: + raise ValueError( + f"causal=True: the model {label!r} ({name}{at}) does not reproduce " + f"the rows it was fitted on when it reduces them again (they differ " + f"by up to {worst:.3g}), so the rows it is fitted on and later rows " + "would not be comparable. Use a model with an exact out-of-sample " + "transform, such as 'PCA', 'IncrementalPCA' or 'FactorAnalysis', " + "with an exact solver (a randomized one, as svd_solver='randomized' " + "of PCA, does not reproduce its rows)." + ) + fitted.freeze_constants(again) + return fitted + + +def _exact_pca(rfun): + """ + ``"PCA"`` (a name, or a dict that gives no ``svd_solver``) with + ``svd_solver="full"``; any other reducer unchanged. scikit-learn's + default chooses a randomized solver for large inputs, whose + ``fit_transform`` is not the projection ``transform`` computes, so the + rows of the fit would not be reproduced. + """ + if isinstance(rfun, str): + rfun = {"model": rfun} + if not (isinstance(rfun, dict) and isinstance(rfun.get("model"), str) + and rfun["model"] == "PCA"): + return rfun + given = {**(rfun.get("kwargs") or {}), **(rfun.get("params") or {})} + if "svd_solver" in given: + return rfun + return {**rfun, "kwargs": {**(rfun.get("kwargs") or {}), "svd_solver": "full"}} + + +def _apply_frozen(corrs, frozen): + """ + The reduction of ``corrs`` (an array or a list of arrays of vectorized + correlations of the causal estimator) by ``frozen``, a result of + ``_fit_reducer``: a fitted summary or model and a graph measure reduce + the rows that are not entirely NaN (the others stay rows of NaN); None + returns ``corrs``; a function of the user's is called as ``reduce`` + calls it. The same container type as ``corrs``. + """ + from .summaries import _FittedSummary + + if isinstance(frozen, str): + return _reduce_defined(corrs, frozen) + if not isinstance(frozen, (_FittedModel, _FittedSummary)): + return reduce(corrs, rfun=frozen) + arrays = corrs if isinstance(corrs, list) else [corrs] + if isinstance(frozen, _FittedSummary): + K = frozen.fit["weights"][0].shape[0] + if arrays and np.asarray(arrays[0]).shape[1] == K * (K + 1) // 2: + frozen.check_units(len(arrays), K) + width = frozen.summary._n_columns(frozen.fit, K) + else: + width = None + out = _on_defined(arrays, frozen.apply, width) + return out if isinstance(corrs, list) else out[0] + + def _causal_arguments(weights_function, weights_params, include_timepoints, cfun, - rfun, events, T, n_subjects): + rfun, events, T, n_subjects, fit_timepoints=None): """ The checks of ``timecorr(..., causal=True)``. Returns ``(include_timepoints, cfun)``: ``'backward'``, and the correlation @@ -325,16 +529,20 @@ def _causal_arguments(weights_function, weights_params, include_timepoints, cfun "starts), for example events=[100, 250]." ) _check_rfun(rfun) - if _needs_fit(rfun): - raise NotImplementedError( + if _needs_fit(rfun) and fit_timepoints is None: + raise _FitTimepointsMissing( f"causal=True: rfun={rfun!r} is fitted to data and needs " - "fit_timepoints (the rows it is fitted on), which timecorr does not " - "accept yet. Use rfun=None or a graph measure such as 'strength'." + "fit_timepoints=n: it is then fitted on the first n rows and applied " + "to every row. Or use rfun=None or a graph measure such as " + "'strength', which need no fit." ) builtin = cfun is None or cfun in (isfc, autofc) or _fixed_weights_wisfc(cfun) - theirs = [name for name, f, ours in (("cfun", cfun, builtin), - ("rfun", rfun, not callable(rfun))) - if not ours] + from .summaries import _Summary # timecorr.summaries imports helpers + + theirs = [name for name, f, ours in ( + ("cfun", cfun, builtin), + ("rfun", rfun, not callable(rfun) or isinstance(rfun, _Summary)), + ) if not ours] if theirs: _warn_user( f"causal=True: {' and '.join(theirs)} " @@ -383,6 +591,7 @@ def timecorr( events_params=None, causal=False, min_samples=None, + fit_timepoints=None, ): """ Compute dynamic (moment-by-moment) correlations in one or more datasets. @@ -541,9 +750,11 @@ def timecorr( reached), and events that leave no timepoint with 3 samples give rows of NaN, not an error, so a prefix of a series runs with the events of the whole series; - - ``rfun`` is None, a graph measure (computed for the defined rows) - or a callable; a reducer that is fitted to data (a model name, a - summary) raises ``NotImplementedError``; + - an ``rfun`` that is fitted to data (a model name or dict, a + summary) needs ``fit_timepoints``: it is fitted on the first + ``fit_timepoints`` rows and then applied, unchanged, to every + row. None, a graph measure (computed for the defined rows) and + a callable need no fit; - infinite samples and samples above 1e150 in magnitude are missing data, like NaN; - the estimator centers each feature, a chunk of 128 timepoints at @@ -571,6 +782,37 @@ def timecorr( sample, or fewer effective samples than the number. Features with zero variance still give correlations of 0. Keyword only. Default: None. + fit_timepoints : int or None + With ``causal=True``, the number ``n`` of first rows that ``rfun`` + is fitted on (an integer from 1 to the number of timepoints), for + an ``rfun`` that is fitted to data: a hypertools model (the + components of ``"PCA"``) or a summary (the pair weights and + communities of ``tc.WeightedStrength`` and ``tc.Communities``; an + object given as ``rfun`` holds that fit in ``fits_`` afterwards). + It is fitted to the correlations of rows ``0..n-1`` that are + defined (not NaN: see ``min_samples``; a model needs 2 such rows, + a summary 1) and then reduces every row, so row ``t >= n`` is + unchanged (to 1e-9; bit for bit under replacement) when rows after + ``t`` are replaced or removed, and a row ``t < n`` when rows from + ``n`` on are. ``n`` equal to the number of timepoints fits on + every row. A model must reduce rows it was not fitted on and + reproduce its training rows to 1e-9 (``"PCA"``, + ``"IncrementalPCA"``, ``"FactorAnalysis"``, ...; ``"MDS"``, + ``"TSNE"``, ``"SpectralEmbedding"`` and + ``"LocallyLinearEmbedding"`` raise ``ValueError``); ``"PCA"`` is + fitted with ``svd_solver="full"`` unless a model dict gives a + solver, because the randomized solver scikit-learn chooses for + large inputs does not reproduce its rows. An output column of + a model that is constant on the training rows up to round-off (a + range of at most 1e-9 of its largest magnitude, or 1e-12 of the + largest magnitude of the output) is frozen: at every row, a value + within that tolerance of the column's training mean is returned as + exactly that mean. Output columns + of a summary that are constant up to round-off are not set to + their mean, and no warning reports them. Required + (``ValueError``) for such an ``rfun``; not used by any other, nor + with ``cfun=None``. Given without ``causal=True``, it raises + ``ValueError``. Keyword only. Default: None. Returns ------- @@ -620,9 +862,13 @@ def timecorr( ``causal=True``, for the arguments listed under ``causal`` that have no causal form, and for a ``min_samples`` that is not None or a finite number >= 1, or that a built-in kernel cannot reach; for - ``min_samples`` given without ``causal=True``. - NotImplementedError - With ``causal=True``, for an ``rfun`` that is fitted to data. + ``min_samples`` given without ``causal=True``; for an ``rfun`` + that is fitted to data without ``fit_timepoints`` (this error is + also a ``NotImplementedError``); for a ``fit_timepoints`` that is + not an integer from 1 to the number of timepoints, or given + without ``causal=True``; when the first ``fit_timepoints`` rows + hold no row with defined correlations to fit (2 for a model); and + for a model that cannot reduce rows it was not fitted on. RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. @@ -724,6 +970,17 @@ def timecorr( >>> changed = tc.timecorr(later, causal=True, weights_params={"var": 50}) >>> bool(np.array_equal(changed[60], past[60])) True + + A reducer that is fitted (here PCA) is fitted on the first + ``fit_timepoints`` rows and applied to every row: + + >>> kw = dict(causal=True, weights_params={"var": 50}, rfun="PCA", + ... fit_timepoints=50) + >>> reduced = tc.timecorr(data, **kw) + >>> reduced.shape + (100, 5) + >>> bool(np.array_equal(tc.timecorr(later, **kw)[60], reduced[60])) + True """ # NaN samples are kept; both the correlation functions and the smoothing @@ -732,10 +989,11 @@ def timecorr( T = data[0].shape[0] min_samples = _check_min_samples(min_samples, causal) + fit_timepoints = _check_fit_timepoints(fit_timepoints, causal, T) if causal: include_timepoints, cfun = _causal_arguments( weights_function, weights_params, include_timepoints, cfun, rfun, - events, T, len(data), + events, T, len(data), fit_timepoints, ) # the built-in correlation functions: one kernel per subject, never T x T builtin = cfun in _KERNEL_LIST_CFUNS or (causal and _fixed_weights_wisfc(cfun)) @@ -773,8 +1031,12 @@ def timecorr( else: groups = distinct_event_sets(_restricted(resolved), len(data)) corrs = _per_subject_cfun(cfun, data, kernels, groups) - if causal and isinstance(rfun, str): - corrs = _reduce_defined(combine(corrs), rfun) + if causal: + # a reducer that is fitted: on the first fit_timepoints rows only + corrs = combine(corrs) + first = ([c[:fit_timepoints] for c in corrs] if isinstance(corrs, list) + else corrs[:fit_timepoints]) + corrs = _apply_frozen(corrs, _fit_reducer(first, rfun)) else: corrs = reduce(combine(corrs), rfun=rfun) From 1c1fed09231a576b35d03f7689f23ee6943ff30f Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 13:47:59 -0500 Subject: [PATCH 09/26] Causal mode: a fitted reducer without fit_timepoints raises a plain ValueError 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 4 ++-- tests/test_causal_features.py | 18 +++++++++--------- timecorr/higher_order.py | 9 +++------ timecorr/timecorr.py | 14 +++----------- 4 files changed, 17 insertions(+), 28 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index f0771173..14ac837d 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -845,8 +845,8 @@ def mine(arrays): "PCA", {"model": "PCA"}, "weighted_strength", "weighted_strength_split", "communities", tc.WeightedStrength(), tc.Communities(n=2), ], ids=str) -def test_fitted_reducers_are_not_implemented_yet(rfun): - with pytest.raises(NotImplementedError, match="fit_timepoints"): +def test_fitted_reducers_need_fit_timepoints(rfun): + with pytest.raises(ValueError, match="fit_timepoints"): tc.timecorr(X, rfun=rfun, **OK) diff --git a/tests/test_causal_features.py b/tests/test_causal_features.py index bf662f4a..9b92d749 100644 --- a/tests/test_causal_features.py +++ b/tests/test_causal_features.py @@ -668,30 +668,30 @@ def test_events_must_be_boundaries(function): @both @pytest.mark.parametrize("rfun", FITTED, ids=str) @pytest.mark.parametrize("name", ["rfun", "delta_rfun"]) -def test_fitted_reducers_are_not_implemented_yet(function, name, rfun): +def test_fitted_reducers_need_fit_timepoints(function, name, rfun): kw = {**OK, name: rfun} - with pytest.raises(NotImplementedError, match=rf"{name}.*fit_timepoints"): + with pytest.raises(ValueError, match=rf"{name}.*fit_timepoints"): FUNCTIONS[function](X0, **kw) @both def test_the_default_reducers_are_fitted(function): kw = {k: v for k, v in OK.items() if k not in ("rfun", "delta_rfun")} - with pytest.raises(NotImplementedError, match="fit_timepoints"): + with pytest.raises(ValueError, match="fit_timepoints"): FUNCTIONS[function](X0, **kw) - with pytest.raises(NotImplementedError, match="fit_timepoints"): + with pytest.raises(ValueError, match="fit_timepoints"): FUNCTIONS[function](X0, rfun="strength", **kw) - with pytest.raises(NotImplementedError, match="fit_timepoints"): + with pytest.raises(ValueError, match="fit_timepoints"): FUNCTIONS[function](X0, delta_rfun="strength", **kw) -def test_fitted_reducers_in_order_maps_are_not_implemented_yet(): +def test_fitted_reducers_in_order_maps_need_fit_timepoints(): kw = {**OK, "rfun": {1: "strength", 2: "PCA"}} - with pytest.raises(NotImplementedError, match=r"rfun.*order 2.*fit_timepoints"): + with pytest.raises(ValueError, match=r"rfun.*order 2.*fit_timepoints"): tc.features(X0, order=2, **kw) # an order missing from a map is "auto" kw = {**OK, "delta_rfun": {1: "strength"}} - with pytest.raises(NotImplementedError, match=r"delta_rfun.*order 2.*fit_timepoints"): + with pytest.raises(ValueError, match=r"delta_rfun.*order 2.*fit_timepoints"): tc.features(X0, order=2, **kw) kw = {**OK, "rfun": {1: "strength", 2: None}, "delta_rfun": {1: None, 2: "strength"}} assert len(_quiet(tc.features, X0, order=2, **kw)) == 3 @@ -750,7 +750,7 @@ def test_new_arguments_are_keyword_only_and_documented(function): assert f"\n {name} : " in f.__doc__ assert parameters["causal"].default is False assert parameters["min_samples"].default is None - assert "NotImplementedError" in f.__doc__ + assert "fit_timepoints" in f.__doc__ def test_default_is_not_causal(): diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index 742afa42..b43bae95 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -114,7 +114,6 @@ _check_fit_timepoints, _event_kernels, _fit_reducer, - _FitTimepointsMissing, _fixed_weights_wisfc, _needs_fit, _restricted, @@ -1979,8 +1978,7 @@ def two_path_step( ValueError With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is fitted to data (the defaults included) when ``fit_timepoints`` is - not given (this error is also a ``NotImplementedError``); for a - ``fit_timepoints`` that is not an integer from 1 to the number of + not given; for a ``fit_timepoints`` that is not an integer from 1 to the number of timepoints, or given without ``causal=True``; when the first ``fit_timepoints`` rows hold no row with defined correlations for a fit (2 for a model), or fewer than 40 rows for the default @@ -2381,7 +2379,7 @@ def _check_causal(*, function, include_timepoints, weights_function, ("delta_rfun", delta_rfun, feeding_rfun)): for k in sorted(resolved): if _needs_fit(resolved[k]) and fit_timepoints is None: - raise _FitTimepointsMissing( + raise ValueError( f"causal=True: {name}={_requested(given, k)!r} (order {k}) is " "fitted to data and needs fit_timepoints=n: the reducers " "are then fitted on the first n rows and applied to every " @@ -3070,8 +3068,7 @@ def features( ValueError With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is fitted to data (the defaults included) when ``fit_timepoints`` is - not given (this error is also a ``NotImplementedError``); for a - ``fit_timepoints`` that is not an integer from 1 to the number of + not given; for a ``fit_timepoints`` that is not an integer from 1 to the number of timepoints, or given without ``causal=True``; when the first ``fit_timepoints`` rows hold no row with defined correlations for a fit (2 for a model), or fewer than 40 rows for the default diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index a781a32a..777cfc84 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -282,14 +282,6 @@ def _needs_fit(rfun): return isinstance(rfun, str) and rfun not in _GRAPH_MEASURES -class _FitTimepointsMissing(ValueError, NotImplementedError): - """ - ``causal=True`` with a reducer that is fitted to data and no - ``fit_timepoints``. A ``ValueError``; also a ``NotImplementedError``, - which these calls raised before ``fit_timepoints`` existed. - """ - - def _check_fit_timepoints(fit_timepoints, causal, T=None): """ ``fit_timepoints`` as None or an int: ``ValueError`` unless it is None @@ -530,7 +522,7 @@ def _causal_arguments(weights_function, weights_params, include_timepoints, cfun ) _check_rfun(rfun) if _needs_fit(rfun) and fit_timepoints is None: - raise _FitTimepointsMissing( + raise ValueError( f"causal=True: rfun={rfun!r} is fitted to data and needs " "fit_timepoints=n: it is then fitted on the first n rows and applied " "to every row. Or use rfun=None or a graph measure such as " @@ -863,8 +855,8 @@ def timecorr( no causal form, and for a ``min_samples`` that is not None or a finite number >= 1, or that a built-in kernel cannot reach; for ``min_samples`` given without ``causal=True``; for an ``rfun`` - that is fitted to data without ``fit_timepoints`` (this error is - also a ``NotImplementedError``); for a ``fit_timepoints`` that is + that is fitted to data without ``fit_timepoints``; for a + ``fit_timepoints`` that is not an integer from 1 to the number of timepoints, or given without ``causal=True``; when the first ``fit_timepoints`` rows hold no row with defined correlations to fit (2 for a model); and From e7254ccf552c5bf3ddf0c103168338e73611cd19 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 14:00:31 -0500 Subject: [PATCH 10/26] Causal mode: refit_every fits the reducers again on an expanding window 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_fit.py | 2 +- tests/test_causal_refit.py | 599 +++++++++++++++++++++++++++++++++++++ tests/test_features.py | 2 +- timecorr/helpers.py | 20 ++ timecorr/higher_order.py | 181 +++++++++-- timecorr/model.py | 367 ++++++++++++++++++++++- timecorr/summaries.py | 5 +- timecorr/timecorr.py | 7 +- 8 files changed, 1136 insertions(+), 47 deletions(-) create mode 100644 tests/test_causal_refit.py diff --git a/tests/test_causal_fit.py b/tests/test_causal_fit.py index 3bbbf0a0..adade6fa 100644 --- a/tests/test_causal_fit.py +++ b/tests/test_causal_fit.py @@ -711,7 +711,7 @@ def test_return_model_needs_causal(): @pytest.mark.parametrize("function,names", [ (tc.timecorr, ["fit_timepoints"]), - (tc.features, ["fit_timepoints", "return_model"]), + (tc.features, ["fit_timepoints", "refit_every", "return_model"]), (two_path_step, ["fit_timepoints"]), ]) def test_new_arguments_are_keyword_only_and_documented(function, names): diff --git a/tests/test_causal_refit.py b/tests/test_causal_refit.py new file mode 100644 index 00000000..25c17f6e --- /dev/null +++ b/tests/test_causal_refit.py @@ -0,0 +1,599 @@ +""" +``refit_every`` of ``features`` with ``causal=True``: the reducers are fitted +on the first ``fit_timepoints`` rows and again every ``refit_every`` rows, +each time on every row before. + +What is checked: rows ``[s_j, s_{j+1})`` of the output are those of a call +with ``fit_timepoints=s_j`` alone (exactly, where no rule changes a fit; up +to the matching of columns otherwise); the structure of the first fit is +kept; the columns of a fit are matched to those of the fit before; and the +guarantee of the causal mode holds (a row is unchanged when later rows are +replaced or removed). Real computations; nothing is mocked. +""" + +import pickle +import warnings + +import numpy as np +import pytest + +import timecorr as tc +from timecorr.helpers import _FittedModel, _FitUnusable +from timecorr.higher_order import two_path_step +from timecorr.model import _assignment, _match_labels, _match_model + +from .test_causal_estimator import _as_list, _max_difference, _perturb, _quiet, _series +from .test_causal_fit import _identical, _map, _modular, _worst + +ATOL = 1e-9 +T, N, M = 200, 100, 40 +ROWS = [100, 140, 180] # the fits: N + j * M below T +SEGMENTS = [(100, 140), (140, 180), (180, 200)] +PARAMS = dict(causal=True, weights_params={"var": 25}, + delta_weights_params={"var": 16}) + +# name: (subjects, data, features, highest order, arguments) +CONFIGS = { + # the defaults: PCA, then signed weighted strength; communities counted + # with the shift null on the feeding path + "auto": (1, _modular, 12, 3, dict(cfun=tc.autofc)), + "auto-isfc": (3, _modular, 12, 2, dict()), + "pca": (1, _series, 5, 3, dict(cfun=tc.autofc, rfun="PCA", delta_rfun="PCA")), + "pca-subjects": (3, _series, 5, 2, dict(rfun="PCA", delta_rfun="PCA", ndims=3)), + "strength": (1, _series, 6, 3, dict( + cfun=tc.autofc, rfun=tc.WeightedStrength(signed=True), + delta_rfun=tc.WeightedStrength())), + "strength-isfc": (3, _series, 5, 2, dict(rfun="weighted_strength", + delta_rfun="weighted_strength")), + "split": (1, _modular, 12, 2, dict( + cfun=tc.autofc, rfun=tc.WeightedStrength(split=True, n=3, center="median"), + delta_rfun="weighted_strength")), + "mixed": (1, _series, 5, 3, dict( + cfun=tc.autofc, rfun={1: None, 2: "weighted_strength", 3: "strength"}, + delta_rfun={1: "strength", 2: "weighted_strength", 3: None})), + "communities": (1, _modular, 12, 2, dict( + cfun=tc.autofc, rfun={1: tc.Communities(n=4), 2: "weighted_strength"}, + delta_rfun={1: tc.Communities(), 2: "weighted_strength"})), +} +# no rule changes a fit: nothing is matched, no structure is carried over +EXACT = ["strength", "strength-isfc", "split", "mixed"] +GUARANTEED = [("auto", True), ("auto", False), ("auto-isfc", True), + ("pca", True), ("pca", False), ("pca-subjects", True), + ("strength", True), ("strength", False), ("strength-isfc", False)] + + +def _data(config, seed=0, n=T): + n_subjects, make, K = CONFIGS[config][:3] + kw = {} if make is _modular else {"K": K} + data = [make(seed + s, n=n, **kw) for s in range(n_subjects)] + return data[0] if n_subjects == 1 else data + + +def _run(data, config, **kwargs): + order, kw = CONFIGS[config][3:] + return _quiet(tc.features, data, **{ + **dict(order=order, fit_timepoints=N, refit_every=M, return_delta=True), + **PARAMS, **kw, **kwargs}) + + +def _rows(out, start, stop): + """Rows ``start:stop`` of every ``X[k]`` and ``D[k]``, k >= 1.""" + return [[[np.asarray(a)[start:stop] for a in _as_list(o)] for o in part[1:]] + for part in out] + + +def _same_rows(a, b, start, stop): + return all(np.array_equal(u, v, equal_nan=True) + for p, q in zip(_rows(a, start, stop), _rows(b, start, stop)) + for x, y in zip(p, q) for u, v in zip(x, y)) + + +def _rows_difference(a, b, start, stop): + return max(_max_difference(u, v, None) + for p, q in zip(_rows(a, start, stop), _rows(b, start, stop)) + for x, y in zip(p, q) for u, v in zip(x, y)) + + +def _cosines(a, b): + return (a @ b.T) / np.outer(np.linalg.norm(a, axis=1), np.linalg.norm(b, axis=1)) + + +# ---------------------------------------------------------------------------- +# the definition: each segment is a call with that fit alone +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("config", EXACT) +def test_each_segment_is_the_call_with_that_fit_alone(config): + """Exactly: these reducers are neither matched nor given a structure.""" + data = _data(config) + out, info = _run(data, config, return_info=True) + fitted = [e for e in info if "fit_timepoints" in e] + assert fitted + for entry in fitted: + assert entry["fit_timepoints"] == N + assert entry["refit_rows"] == ROWS + assert entry["refit_kept_previous"] == [] + for j, (start, stop) in enumerate(SEGMENTS): + alone = _run(data, config, fit_timepoints=start, refit_every=None) + assert _same_rows(out, alone, start, stop) + if j == 0: + # the rows before the first fit's row are the first fit's + assert _same_rows(out, alone, 0, N) + else: + assert not _same_rows(out, alone, 0, start) + + +@pytest.mark.parametrize("config", ["pca", "auto", "communities", "auto-isfc"]) +def test_each_segment_is_the_model_of_the_fits_so_far(config): + """ + With matched columns a call with one fit is not the reference (its + columns are in its own order). The model of the call on the rows before + ``s_{j+1}`` holds fit ``j`` as matched to the fits before it: its + transform of all the data gives rows ``[s_j, s_{j+1})`` (to 1e-9: the + rows after were removed for that call). + """ + data = _data(config) + out, model = _run(data, config, return_model=True) + assert model.refits == ROWS + for start, stop in SEGMENTS: + _, prefix = _run(_map(data, lambda x: x[:stop]), config, return_model=True) + assert prefix.refits == [r for r in ROWS if r < stop] + applied = _quiet(prefix.transform, data, return_delta=True) + assert _rows_difference(out, applied, start, stop) <= ATOL + # the model of the whole call holds the last fit: the same arrays + applied = _quiet(model.transform, data, return_delta=True) + assert _same_rows(out, applied, ROWS[-1], T) + + +def test_model_columns_are_those_of_single_fits_up_to_order_and_sign(): + """PCA of the correlations of unmatched feeding features (weighted + strength): at every order, each column of a segment is a column of the + call with that fit alone, or its negative.""" + x = _series(3, n=T, K=5, missing=0.0) + kw = dict(order=2, cfun=tc.autofc, rfun="PCA", delta_rfun="weighted_strength", + fit_timepoints=N, **PARAMS) + X = _quiet(tc.features, x, refit_every=M, **kw) + moved = 0 + for start, stop in SEGMENTS: + alone = _quiet(tc.features, x, **{**kw, "fit_timepoints": start}) + for k in (1, 2): + a, b = X[k][start:stop], alone[k][start:stop] + assert not np.isnan(a).any() + # which column of the single fit each column is + distance = np.minimum( + np.abs(a[:, :, None] - b[:, None, :]).max(axis=0), + np.abs(a[:, :, None] + b[:, None, :]).max(axis=0)) + source = distance.argmin(axis=1) + assert sorted(source) == list(range(a.shape[1])) + assert distance[np.arange(a.shape[1]), source].max() <= ATOL + moved += not np.array_equal(a, b) + assert moved # the matching did something in this data + + +# ---------------------------------------------------------------------------- +# matching +# ---------------------------------------------------------------------------- + + +def _swapping(seed=2, n=T): + """Two pairs of columns whose correlations vary; the second pair's vary + most after row 100, so the leading components of later fits change.""" + rng = np.random.default_rng(seed) + t = np.arange(n) + a = 0.6 * np.sin(t / 9.0) + b = np.where(t < 100, 0.15 * np.sin(t / 7.0), 0.95 * np.sign(np.sin(t / 6.0))) + z, e = rng.standard_normal((n, 2)), rng.standard_normal((n, 2)) + return np.column_stack([ + z[:, 0], a * z[:, 0] + np.sqrt(1 - a ** 2) * e[:, 0], + z[:, 1], b * z[:, 1] + np.sqrt(1 - b ** 2) * e[:, 1]]) + + +def test_components_keep_their_columns_and_signs_across_refits(): + x = _swapping() + kw = dict(order=1, cfun=tc.autofc, rfun="PCA", delta_rfun="weighted_strength", + ndims=2, **PARAMS) + key = (1, "analysis") + + def components(n, **more): + _, model = _quiet(tc.features, x[:n + 1], return_model=True, + **{**kw, "fit_timepoints": n, **more}) + return model.fits[key].model_.components_ + + # the fits alone: the second fit's components are the first's in the + # other order, one of them negated + alone = _cosines(components(140), components(100)) + assert list(_assignment(np.abs(alone))) == [1, 0] + assert alone[0, 1] > 0.5 and alone[1, 0] < -0.5 + # matched: each stays where it was, with its sign + first = components(100) + second = components(140, **{"fit_timepoints": 100, "refit_every": 40}) + matched = _cosines(second, first) + assert list(_assignment(np.abs(matched))) == [0, 1] + assert matched[0, 0] > 0.5 and matched[1, 1] > 0.5 + # the same vectors as the fit alone, reordered and negated + assert np.allclose(np.abs(_cosines(second, components(140))), + [[0, 1], [1, 0]], atol=1e-12) + # so each column goes on measuring what it measured: over the second + # fit's rows it follows the first fit's column, which the second column + # of the fit alone does not + X = _quiet(tc.features, x, fit_timepoints=100, refit_every=40, **kw)[1] + before = _quiet(tc.features, x, fit_timepoints=100, **kw)[1] + unmatched = _quiet(tc.features, x, fit_timepoints=140, **kw)[1] + + def follows(a, column): + return np.corrcoef(a[140:180, column], before[140:180, column])[0, 1] + + assert follows(X, 0) > 0.6 and follows(X, 1) > 0.6 + assert follows(unmatched, 1) < 0.3 + + +@pytest.mark.parametrize("rfun", [ + "PCA", {"model": "PCA", "kwargs": {"whiten": True}}, "IncrementalPCA", + "FactorAnalysis", "TruncatedSVD", "FastICA"], ids=str) +def test_a_matched_model_gives_the_reordered_columns(rfun): + from timecorr.timecorr import _fit_reducer + + rng = np.random.default_rng(0) + rows = rng.standard_normal((60, 6)) * np.array([5, 4, 3, 2, 1, 0.5]) + new = _quiet(_fit_reducer, rows, rfun, 3) + assert isinstance(new, _FittedModel) + # an earlier fit with these components in another order, one negated + previous = pickle.loads(pickle.dumps(new)) + estimator = previous.model.model_ + estimator.components_ = estimator.components_[[2, 0, 1]] * np.array([[1], [-1], [1]]) + matched = _match_model(new, previous, 1, "analysis") + assert matched is not new + assert np.allclose(np.diag(_cosines(matched.model.model_.components_, + estimator.components_)), 1, atol=1e-12) + other = rng.standard_normal((20, 6)) + before, after = new.apply([other])[0], matched.apply([other])[0] + assert np.allclose(after, before[:, [2, 0, 1]] * np.array([1, -1, 1]), + rtol=0, atol=1e-9 * np.abs(before).max()) + # nothing to move: the fit itself + assert _match_model(new, pickle.loads(pickle.dumps(new)), 1, "analysis") is new + + +def test_frozen_constant_columns_follow_their_components(): + from timecorr.timecorr import _fit_reducer + + rng = np.random.default_rng(1) + rows = rng.standard_normal((40, 6)) + rows[:, 4] = rows[:, 5] = rows[:, 3] # rank 4: the fifth component is round-off + new = _quiet(_fit_reducer, rows, "PCA", 5) + assert list(new.constants[0]) == [4] + previous = pickle.loads(pickle.dumps(new)) + estimator = previous.model.model_ + estimator.components_ = estimator.components_[[4, 1, 2, 3, 0]] + matched = _match_model(new, previous, 1, "analysis") + assert list(matched.constants[0]) == [0] + assert np.array_equal(matched.apply([rows])[0][:, 0], new.apply([rows])[0][:, 4]) + # padded columns stay last; another number of them is another structure + padded = _quiet(_fit_reducer, rows[:3], "PCA", 5) + assert padded.pad == 2 + with pytest.raises(_FitUnusable): + _match_model(new, padded, 1, "analysis") + + +def test_labels_take_the_columns_of_the_communities_they_share_most_nodes_with(): + previous = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) + # node 0 moved: numbered by smallest member, every community has another label + new = np.array([0, 1, 1, 2, 2, 2, 0, 0, 0]) + assert list(_match_labels(new, previous)) == [2, 0, 0, 1, 1, 1, 2, 2, 2] + assert list(_match_labels(previous, previous)) == list(previous) + # single-node communities have no column and keep their labels + assert list(_match_labels(np.array([0, 1, 1, 2, 3, 3]), + np.array([4, 3, 3, 2, 0, 0]))) == [0, 3, 3, 2, 1, 1] + with pytest.raises(_FitUnusable, match="communities of 2 or more"): + _match_labels(np.array([0, 0, 0, 0, 1, 2]), np.array([0, 0, 1, 1, 2, 2])) + + +def _moving_node(n=T): + """Three modules of three nodes; from row 100 node 0 follows the third.""" + rng = np.random.default_rng(1) + signals = rng.standard_normal((n, 3)) + x = np.repeat(signals, 3, axis=1) + 0.5 * rng.standard_normal((n, 9)) + x[100:, 0] = 3 * (signals[100:, 2] + 0.2 * rng.standard_normal(n - 100)) + return x + + +def test_communities_keep_their_columns_across_refits(): + x = _moving_node() + kw = dict(order=2, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun={1: tc.Communities(n=3), 2: "weighted_strength"}, + return_delta=True, return_info=True, **PARAMS) + + def run(**more): + (X, D), info = _quiet(tc.features, x, **kw, **more) + return X, D, info[1] + + _, D100, first = run(fit_timepoints=100) + _, D180, alone = run(fit_timepoints=180) + assert first["labels"] == [0, 0, 0, 1, 1, 1, 2, 2, 2] + # alone, the fit at row 180 numbers the communities in another order + assert alone["labels"] == [0, 1, 1, 2, 2, 2, 0, 0, 0] + X, D, entry = run(fit_timepoints=100, refit_every=40) + assert entry["refit_rows"] == ROWS and entry["refit_kept_previous"] == [] + # the labels of the last fit: node 0 with the third module, in its column + assert entry["labels"] == [2, 0, 0, 1, 1, 1, 2, 2, 2] + # the same columns as the fit alone, reordered, at order 1 ... + assert np.array_equal(D[1][180:], D180[1][180:][:, [1, 2, 0]]) + assert np.array_equal(D[1][:140], D100[1][:140], equal_nan=True) + # ... and order 2 was fitted on the reordered columns + alone2 = _quiet(tc.features, x, **{**kw, "fit_timepoints": 180})[0][0][2] + assert _max_difference(X[2][180:], alone2[180:][:, [1, 2, 0]], None) <= ATOL + + +# ---------------------------------------------------------------------------- +# the structure is the first fit's +# ---------------------------------------------------------------------------- + + +def _feeding(x, **kwargs): + (X, D), info = _quiet(tc.features, x, order=1, cfun=tc.autofc, return_delta=True, + return_info=True, **PARAMS, **kwargs) + return D[1], info[1] + + +def test_a_fallback_of_the_first_fit_stays(): + # noise, then modules: later fits alone would emit their communities + x = np.vstack([np.random.default_rng(2).standard_normal((100, 12)), + _modular(3, n=200)]) + D0, first = _feeding(x, fit_timepoints=100) + assert first["fallback"] == "no_null_exceedance" and D0.shape[1] == 12 + D200, alone = _feeding(x, fit_timepoints=200) + assert alone["fallback"] is None and D200.shape[1] == 4 + D, entry = _feeding(x, fit_timepoints=100, refit_every=100) + assert entry["refit_rows"] == [100, 200] and entry["refit_kept_previous"] == [] + assert entry["fallback"] == "no_null_exceedance" and entry["labels"] is None + assert entry["effective"] == first["effective"] and D.shape == (300, 12) + assert np.array_equal(D[:200], D0[:200], equal_nan=True) + # from row 200: weighted strength with the pair weights of rows 0..199 + again, _ = _feeding(x, fit_timepoints=200, delta_rfun=tc.WeightedStrength( + split=False, signed=False, center=False)) + assert np.array_equal(D[200:], again[200:]) + assert not np.array_equal(D[200:], D0[200:]) + + +def test_communities_of_the_first_fit_stay(): + # weak modules, then noise: later fits alone fall back to weighted strength + rng = np.random.default_rng(0) + modules = np.repeat(rng.standard_normal((100, 4)), 3, axis=1) + x = np.vstack([modules + rng.standard_normal((100, 12)), + np.random.default_rng(9).standard_normal((200, 12))]) + D0, first = _feeding(x, fit_timepoints=100) + assert first["fallback"] is None and first["n_communities"] == 4 + D200, alone = _feeding(x, fit_timepoints=200) + assert alone["fallback"] == "too_few_community_columns" and D200.shape[1] == 12 + D, entry = _feeding(x, fit_timepoints=100, refit_every=100) + assert entry["fallback"] is None and entry["n_communities"] == 4 + assert D.shape == (300, 4) and len(set(entry["labels"])) >= 4 + assert entry["null_threshold"] == first["null_threshold"] # no second null + assert np.array_equal(D[:200], D0[:200], equal_nan=True) + + +def _merging(n=T): + """Three pairs of nodes; from row 100 four nodes share one signal and + two are noise, and three clusters leave fewer than three pairs.""" + rng = np.random.default_rng(5) + x = np.repeat(rng.standard_normal((n, 3)), 2, axis=1) + x = x + rng.standard_normal((n, 6)) + common = rng.standard_normal(n) + x[100:, :4] = 4 * common[100:, None] + 0.3 * rng.standard_normal((n - 100, 4)) + x[100:, 4:] = rng.standard_normal((n - 100, 2)) + return x + + +def test_a_refit_without_the_structure_keeps_the_fit_before(): + x = _merging() + kw = dict(order=2, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun={1: tc.Communities(n=3), 2: "weighted_strength"}, + return_delta=True, return_info=True, **PARAMS) + first, info0 = _quiet(tc.features, x, fit_timepoints=100, **kw) + _, alone = _quiet(tc.features, x, fit_timepoints=140, **kw) + assert info0[1]["output_width"] == 3 and alone[1]["output_width"] == 2 + out, info, model = _quiet(tc.features, x, fit_timepoints=100, refit_every=40, + return_model=True, **kw) + for entry in info: + assert entry["refit_rows"] == ROWS + # of every order: the whole fit is left out + assert entry["refit_kept_previous"] == [140, 180] + assert entry["fit_timepoints"] == 100 + assert info[1]["labels"] == info0[1]["labels"] == [0, 0, 1, 1, 2, 2] + assert _same_rows(out, first, 0, T) + assert model.refits == ROWS + assert _same_rows(_quiet(model.transform, x, return_delta=True), first, 0, T) + # whether a fit is kept is decided by the rows before it + cut, cut_info = _quiet(tc.features, x[:150], fit_timepoints=100, refit_every=40, + **kw) + assert cut_info[0]["refit_kept_previous"] == [140] + assert _rows_difference(out, cut, 0, 150) <= ATOL + + +# ---------------------------------------------------------------------------- +# the guarantee +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("config,include_zero", GUARANTEED) +def test_rows_do_not_depend_on_later_rows(config, include_zero): + data = _data(config) + full = _run(data, config, include_zero=include_zero) + order = CONFIGS[config][3] + last = np.asarray(_as_list(full[0][order])[0]) + assert np.isnan(last[0]).all() and not np.isnan(last[N:]).any() + rng = np.random.default_rng(7) + # replaced from the first fit's row (the rows before it depend on + # nothing after them), at a refit row and inside segments; removed also + # just before and just after a refit row + cuts = {"finite": (N, 140, 185), "nan": (140,), "inf": (120,), + "remove": (N, 139, 140, 141, 181, T - 1)} + for mode in cuts: + for m in cuts[mode]: + part = _run(_map(data, lambda x: _perturb(x, m, mode, rng)), config, + include_zero=include_zero) + # without the diagonal, row m itself may change too + rows = m if include_zero or mode == "remove" else m + 1 + assert _worst(full, part, rows) <= ATOL + if mode != "remove": + # replacing later rows changes no bit + assert _identical(full, part, rows) + + +def test_the_fits_made_depend_on_the_length_only_through_their_rows(): + data = _data("pca") + kw = dict(return_info=True, return_model=True) + for n, rows in ((140, [100]), (141, [100, 140]), (180, [100, 140]), + (181, [100, 140, 180])): + _, info, model = _run(data[:n], "pca", **kw) + assert model.refits == rows and info[0]["refit_rows"] == rows + assert model.fit_timepoints == N + # no row for a second fit: the call with one fit + one = _run(data[:140], "pca") + assert _same_rows(one, _run(data[:140], "pca", refit_every=None), 0, 140) + assert _same_rows(one, _run(data[:140], "pca", refit_every=1000), 0, 140) + + +def test_refit_every_row(): + x = _series(4, n=70, K=4, missing=0.0) + kw = dict(order=2, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun="weighted_strength", **PARAMS) + X, info = _quiet(tc.features, x, fit_timepoints=60, refit_every=1, + return_info=True, **kw) + assert info[0]["refit_rows"] == list(range(60, 70)) + for t in (60, 64, 69): + alone = _quiet(tc.features, x, fit_timepoints=t, **kw) + assert np.array_equal(X[2][t], alone[2][t]) + + +# ---------------------------------------------------------------------------- +# the model +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("config", ["auto", "pca", "strength"]) +def test_the_model_holds_the_last_fit(config): + data = _data(config) + out, info, model = _run(data, config, return_info=True, return_model=True) + assert isinstance(model, tc.FeaturesModel) + assert model.fit_timepoints == N and model.refits == ROWS + assert model.info is info + applied, applied_info = _quiet(model.transform, data, return_delta=True, + return_info=True) + # from the last fit's row on: what features returned + assert _same_rows(out, applied, ROWS[-1], T) + # before it, features returned the rows of earlier fits ... + assert not _same_rows(out, applied, N, ROWS[-1]) + assert not _same_rows(out, applied, 0, N) + # ... which differ only through the fit: the last fit's are those of the + # model of that fit alone, up to the matching of its columns (none for + # weighted strength) + if config == "strength": + alone = _run(data, config, fit_timepoints=ROWS[-1], refit_every=None) + assert _same_rows(applied, alone, 0, T) + fitted = [e for e in applied_info if "fit_timepoints" in e] + assert fitted and all(e["refit_rows"] == ROWS for e in fitted) + # other data, causally + longer = _data(config, seed=20, n=T + 30) + more = _quiet(model.transform, longer, return_delta=True) + part = _quiet(model.transform, longer[:T], return_delta=True) + assert _rows_difference(more, part, 0, T) <= ATOL + # a pickled model gives the same arrays + copy = pickle.loads(pickle.dumps(model)) + assert copy.refits == ROWS and copy.fit_timepoints == N + assert _same_rows(_quiet(copy.transform, longer, return_delta=True), more, 0, T + 30) + + +def test_info_and_model_without_refits(): + x = _series(5, n=T, K=5) + kw = dict(order=2, cfun=tc.autofc, rfun={1: "PCA", 2: "strength"}, + delta_rfun="strength", **PARAMS) + X, info, model = _quiet(tc.features, x, fit_timepoints=N, return_info=True, + return_model=True, **kw) + assert info[0]["refit_rows"] == [N] and info[0]["refit_kept_previous"] == [] + assert all("refit_rows" not in e for e in info[1:]) # nothing fitted there + assert model.refits == [N] + # reducers without a fit: nothing to fit again + kw["rfun"] = "strength" + X, info, model = _quiet(tc.features, x, fit_timepoints=N, refit_every=M, + return_info=True, return_model=True, **kw) + assert model.refits == [] and all("refit_rows" not in e for e in info) + alone = _quiet(tc.features, x, **kw) + assert np.array_equal(X[2], alone[2], equal_nan=True) + + +def test_reducer_objects_keep_the_first_fit(): + x = _series(6, n=T, K=5, missing=0.0) + strength = tc.WeightedStrength() + kw = dict(order=1, cfun=tc.autofc, rfun=strength, delta_rfun="strength", + fit_timepoints=N, **PARAMS) + _, model = _quiet(tc.features, x, refit_every=M, return_model=True, **kw) + assert len(strength.fits_) == 1 + refitted = strength.fits_[0]["weights"][0].copy() + _quiet(tc.features, x, **kw) + assert np.array_equal(strength.fits_[0]["weights"][0], refitted) + assert not np.array_equal(model.fits[(1, "analysis")]["weights"][0], refitted) + + +# ---------------------------------------------------------------------------- +# arguments +# ---------------------------------------------------------------------------- + +OK = dict(order=1, cfun=tc.autofc, rfun="weighted_strength", delta_rfun="strength", + **PARAMS) +X0 = np.random.default_rng(0).standard_normal((80, 4)) + + +def test_refit_every_needs_causal_and_fit_timepoints(): + with pytest.raises(ValueError, match=r"refit_every=10.*fit_timepoints"): + tc.features(X0, refit_every=10, **OK) + plain = {k: v for k, v in OK.items() if k != "causal"} + with pytest.raises(ValueError, match=r"refit_every=10.*causal=True"): + tc.features(X0, refit_every=10, **plain) + with pytest.raises(TypeError): + two_path_step(X0, refit_every=10, fit_timepoints=40, **{ + k: v for k, v in OK.items() if k != "order"}) + with pytest.raises(TypeError): + tc.timecorr(X0, causal=True, weights_params={"var": 25}, fit_timepoints=40, + rfun="weighted_strength", refit_every=10) + + +@pytest.mark.parametrize("value", [0, -3, 2.5, 10.0, "10", True, [10], np.nan]) +def test_refit_every_is_a_positive_integer(value): + with pytest.raises(ValueError, match="refit_every must be None or a positive"): + tc.features(X0, fit_timepoints=40, refit_every=value, **OK) + + +def test_refit_every_takes_numpy_integers_and_none(): + a = _quiet(tc.features, X0, fit_timepoints=40, refit_every=np.int64(20), **OK) + b = _quiet(tc.features, X0, fit_timepoints=40, refit_every=20, **OK) + assert np.array_equal(a[1], b[1], equal_nan=True) + c = _quiet(tc.features, X0, fit_timepoints=40, refit_every=None, **OK) + assert not np.array_equal(a[1], c[1], equal_nan=True) + + +def test_new_argument_is_keyword_only_and_documented(): + import inspect + + parameter = inspect.signature(tc.features).parameters["refit_every"] + assert parameter.kind is inspect.Parameter.KEYWORD_ONLY + assert parameter.default is None + assert "\n refit_every : " in tc.features.__doc__ + assert "refit_every" not in inspect.signature(two_path_step).parameters + assert "refit_every" not in inspect.signature(tc.timecorr).parameters + for name in ("refit_rows", "refit_kept_previous"): + assert name in tc.features.__doc__ + assert "refits" in tc.FeaturesModel.__doc__ + + +def test_warnings_are_not_repeated_for_every_fit(): + x = _series(8, n=T, K=5) + kw = dict(order=2, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun="weighted_strength", fit_timepoints=N, **PARAMS) + counts = [] + for more in ({}, {"refit_every": M}): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + tc.features(x, **kw, **more) + counts.append(len(caught)) + assert counts[0] == counts[1] diff --git a/tests/test_features.py b/tests/test_features.py index 5c1db4aa..fe5773e5 100644 --- a/tests/test_features.py +++ b/tests/test_features.py @@ -723,7 +723,7 @@ def test_events_signatures_keep_positional_order(): ["order"] if f is two_path_step else ["return_info"]) # the arguments of the causal mode (0.4.0), keyword-only, come last later += ["causal", "min_samples", "fit_timepoints"] + ( - [] if f is two_path_step else ["return_model"]) + [] if f is two_path_step else ["refit_every", "return_model"]) assert list(params) == positional + ["events", "events_params"] + later, ( f.__name__) assert all(params[n].kind == inspect.Parameter.KEYWORD_ONLY diff --git a/timecorr/helpers.py b/timecorr/helpers.py index 93129cef..b1c9928b 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -3636,6 +3636,26 @@ def _model_reduce(corrs, rfun, ndims, return_model=False): return red_corrs +class _FitUnusable(ValueError): + """ + A reducer could not be fitted to the training rows of a causal fit, or + its fit cannot be used on other rows (no defined row, a clustering + without a community of 2 members, a model that does not reproduce its + rows). A ``ValueError`` for the caller; a refit of ``features`` that + raises it keeps the previous fit (``refit_every``). + """ + + +# the hypertools model names whose fitted estimator has ``components_`` (one +# vector per output column): the models a refit can match to the fit before +# (``features(..., refit_every=...)``) +_COMPONENT_MODELS = ( + "PCA", "IncrementalPCA", "SparsePCA", "MiniBatchSparsePCA", "FastICA", + "FactorAnalysis", "TruncatedSVD", "DictionaryLearning", + "MiniBatchDictionaryLearning", +) + + # an output column of a fitted model is constant on its training rows when # its range there is at most this fraction of its largest magnitude, or # _FROZEN_ZERO_RTOL of the largest magnitude of the whole output (the diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index b43bae95..e3d6dcc1 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -63,6 +63,7 @@ import numpy as np from .helpers import ( + _COMPONENT_MODELS, _SUMMARY_NAMES, _check_min_samples, _check_ndims, @@ -631,6 +632,9 @@ def _apply_reducer(corrs, rfun, ndims, order=None, path=None, null_threshold=Non ) if record is not None: record[path] = frozen + # a record of a refit matches the fit to the one before + # (model._Matched): what it holds reduces the step + frozen = record[path] return _apply_frozen(corrs, frozen) summary = _as_summary(rfun) if summary is None: @@ -740,11 +744,7 @@ def _run_streamed(subjects, summary, cfun, kernels, *, max_memory_gb, order, pat max_block = _streamed_block_elements( d, T, len(subjects), max_memory_gb, order, path, dense ) - out, message = _streamed_summary( - subjects, - kernels, - summary, - cfun, + step = dict( max_block_elements=max_block, order=order, path=path, @@ -754,11 +754,18 @@ def _run_streamed(subjects, summary, cfun, kernels, *, max_memory_gb, order, pat # for a stationary built-in kernel, every timepoint otherwise null_row_stride=None, estimator=estimator, - fitted=frozen, ) + out, message = _streamed_summary(subjects, kernels, summary, cfun, + fitted=frozen, **step) if frozen is None: if record is not None: - record[path] = _FittedSummary(summary, summary.fits_[-1]) + made = _FittedSummary(summary, summary.fits_[-1]) + record[path] = made + if record[path] is not made: + # a refit, matched to the fit before (model._Matched): the + # matched fit summarizes the step + out, _ = _streamed_summary(subjects, kernels, summary, cfun, + fitted=record[path], **step) if not append_fit: del summary.fits_[:-1] elif record is not None: @@ -1978,12 +1985,12 @@ def two_path_step( ValueError With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is fitted to data (the defaults included) when ``fit_timepoints`` is - not given; for a ``fit_timepoints`` that is not an integer from 1 to the number of - timepoints, or given without ``causal=True``; when the first - ``fit_timepoints`` rows hold no row with defined correlations for - a fit (2 for a model), or fewer than 40 rows for the default - feeding reducer or a shift null; and for a model that cannot - reduce rows it was not fitted on. + not given; for a ``fit_timepoints`` that is not an integer from 1 + to the number of timepoints, or given without ``causal=True``; + when the first ``fit_timepoints`` rows hold no row with defined + correlations for a fit (2 for a model), or fewer than 40 rows for + the default feeding reducer or a shift null; and for a model that + cannot reduce rows it was not fitted on. RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. TypeError @@ -2412,6 +2419,57 @@ def _check_causal(*, function, include_timepoints, weights_function, ) +def _no_components_message(label, name, k): + """The error of ``refit_every`` for a model a refit cannot match.""" + return ( + f"refit_every: the model {label!r} ({name}, order {k}) has no " + "components_ (one vector per output column), so the columns of a " + "refit cannot be matched to those of the fit before. Use a model " + "that has them ('PCA', 'IncrementalPCA', 'FactorAnalysis', 'FastICA', " + "'TruncatedSVD', ...), a summary such as 'weighted_strength', or " + "leave refit_every out." + ) + + +def _check_refit_every(refit_every, causal, fit_timepoints, analysis_rfun, + feeding_rfun, fed): + """ + ``refit_every`` as None or an int: ``ValueError`` unless it is None or + an integer >= 1 given with ``causal=True`` and ``fit_timepoints``, and + for a model of a computed step that is named and known to have no + ``components_`` (a model given as an object is checked when it has been + fitted: ``model._refit``). + """ + if refit_every is None: + return None + if ( + isinstance(refit_every, (bool, np.bool_)) + or not isinstance(refit_every, numbers.Integral) + or refit_every < 1 + ): + raise ValueError( + "refit_every must be None or a positive integer (the number of " + f"rows between two fits of the reducers); got {refit_every!r}." + ) + if not causal or fit_timepoints is None: + raise ValueError( + f"refit_every={refit_every!r} applies with causal=True and " + "fit_timepoints=n only (the reducers are fitted on the first n " + f"rows, then again every {refit_every} rows, each time on all " + "rows before); pass both, or leave refit_every out." + ) + for name, reducers, orders in (("rfun", analysis_rfun, sorted(analysis_rfun)), + ("delta_rfun", feeding_rfun, fed)): + for k in orders: + label = reducers[k] + if isinstance(label, dict): + label = label.get("model") + if (isinstance(label, str) and _is_model(label) + and label not in _COMPONENT_MODELS): + raise ValueError(_no_components_message(label, name, k)) + return int(refit_every) + + def _theirs(reducer): """True for a reducer that is a function of the user's (not a summary).""" return callable(reducer) and not isinstance(reducer, _Summary) @@ -2554,6 +2612,7 @@ def features( causal=False, min_samples=None, fit_timepoints=None, + refit_every=None, return_model=False, ): """ @@ -2865,9 +2924,14 @@ def features( or one int per subject when the output is a list), and ``"constant_columns"`` is taken over the other rows; the entry of a step whose reducer was fitted has ``"fit_timepoints"`` (the - number of rows it was fitted on), and what describes a fit - (``"labels"``, ``"n_communities"``, ``"fallback"``, ...) is that - of the fit on those rows. + number of rows it was fitted on), ``"refit_rows"`` (the rows of + the fits: ``[fit_timepoints]``, and with ``refit_every`` every + row at which the reducers were fitted again) and + ``"refit_kept_previous"`` (those of them whose fit could not be + used, so that the fit before was kept; see ``refit_every``), and + what describes a fit (``"labels"``, ``"n_communities"``, + ``"fallback"``, ...) is that of the fit on those rows (with + ``refit_every``: of the last fit). Default: False. causal : bool If True (keyword-only), row ``t`` of every output is computed from @@ -2973,6 +3037,49 @@ def features( warning reports them. Not used by reducers that need no fit; required (``ValueError``) when a reducer is fitted. Given without ``causal=True``, it raises ``ValueError``. Default: None. + refit_every : int or None + With ``causal=True`` and ``fit_timepoints=n`` (keyword-only): the + number of rows ``m >= 1`` after which the reducers are fitted + again, each time on every row before. The fits are at rows + ``s_j = n + j * m`` for ``j = 0, 1, ...`` while ``s_j`` is less + than the number of timepoints; fit ``j`` reads rows ``0..s_j - 1`` + only. Rows ``s_j`` to ``s_{j+1} - 1`` of every output (to the + last row for the last fit) are the rows that this call returns + with ``fit_timepoints=s_j`` and no ``refit_every``, up to the two + rules below; rows before ``n`` are those of fit 0. So the + guarantee of ``fit_timepoints`` holds: a row ``t >= n`` is + unchanged when rows after ``t`` are replaced or removed, and a + row ``t < n`` when rows from ``n`` on are. Every fit is a pass + over its rows and one over all rows, so the time grows with the + number of fits. + + - The structure is that of fit 0, so that every output has the + same columns at every row: the number of communities of a + summary that counts them with the shift null (the null runs in + fit 0 only), what an automatic feeding step chose (communities + or weighted strength), and the number of components of a + model. A later fit that cannot have it (its clustering gives + another number of communities of 2 or more nodes, its model + another number of components, or does not reproduce its rows) + is not used: the fit before, of every order, stays for its + rows, and the row is listed in ``"refit_kept_previous"`` of + ``return_info``. + - The columns of a fit are matched to those of the fit before, + order by order, before the next order of that fit is fitted: + the components of a model (the one-to-one assignment with the + largest sum of absolute cosines between component vectors; + a component is negated when its cosine is negative), and the + communities of ``Communities`` (the assignment with the most + shared nodes). Models need ``components_`` (``"PCA"``, + ``"IncrementalPCA"``, ``"FactorAnalysis"``, ``"FastICA"``, + ``"TruncatedSVD"``, ...); others raise ``ValueError``. The + columns of ``WeightedStrength`` belong to the nodes and are not + matched; with ``split=True`` a node that changes community + changes which pairs its own and other columns sum. + + Summary objects passed as reducers keep the records of fit 0 in + ``fits_``; the last fit is in the model (``return_model``). + Default: None (one fit). return_model : bool If True (keyword-only; needs ``causal=True``), also return the fitted pipeline as a ``tc.FeaturesModel``, last: ``(X, model)``, @@ -2980,7 +3087,12 @@ def features( model)``. ``model.transform(data)`` computes the features of other data (the same series with later rows, for example) with the reducers as fitted here, causally and without fitting anything; - ``model.transform`` of this data returns these outputs. The model + ``model.transform`` of this data returns these outputs. With + ``refit_every`` the model holds the last fit, which + ``model.transform`` applies to every row: it returns these + outputs from the last row of ``model.refits`` on, and the rows + before as the last fit gives them, not as returned here (they + came from earlier fits). The model can be pickled (see ``FeaturesModel``). Default: False. Returns @@ -3068,12 +3180,15 @@ def features( ValueError With ``causal=True``, for an ``rfun`` or ``delta_rfun`` that is fitted to data (the defaults included) when ``fit_timepoints`` is - not given; for a ``fit_timepoints`` that is not an integer from 1 to the number of - timepoints, or given without ``causal=True``; when the first - ``fit_timepoints`` rows hold no row with defined correlations for - a fit (2 for a model), or fewer than 40 rows for the default - feeding reducer or a shift null; and for a model that cannot - reduce rows it was not fitted on. + not given; for a ``fit_timepoints`` that is not an integer from 1 + to the number of timepoints, or given without ``causal=True``; + when the first ``fit_timepoints`` rows hold no row with defined + correlations for a fit (2 for a model), or fewer than 40 rows for + the default feeding reducer or a shift null; for a model that + cannot reduce rows it was not fitted on; and for a + ``refit_every`` that is not None or an integer >= 1, that is + given without ``causal=True`` and ``fit_timepoints``, or given + with a model that has no ``components_``. TypeError If ``rfun`` or ``delta_rfun`` is not None, a string, a dict or a callable, or ``delta_weights_function`` is not None or callable. @@ -3307,6 +3422,19 @@ def features( (200, 5) >>> bool(np.allclose(longer[2][:150], X[2], atol=1e-9, equal_nan=True)) True + + With ``refit_every`` the reducers are fitted again every so many rows, + each time on all rows before; the rows from a fit to the next are those + of a call with that fit alone (the columns of a model or of + communities are also matched to those of the fit before): + + >>> kw["rfun"] = "weighted_strength" + >>> X, info = tc.features(x, refit_every=40, return_info=True, **kw) + >>> info[0]["refit_rows"], info[0]["refit_kept_previous"] + ([120, 160], []) + >>> alone = tc.features(x, **{**kw, "fit_timepoints": 160}) + >>> bool(np.array_equal(X[2][160:], alone[2][160:])) + True """ if ( not isinstance(order, numbers.Integral) @@ -3371,6 +3499,8 @@ def features( S = len(subjects) fit_timepoints = _check_fit_timepoints(fit_timepoints, causal, T) + refit_every = _check_refit_every(refit_every, causal, fit_timepoints, + analysis_rfun, feeding_rfun, fed) if causal: _check_causal( function="features", include_timepoints=include_timepoints, @@ -3466,8 +3596,9 @@ def features( auto={k: _auto_at(rfun, k) for k in orders}, fed=list(fed), ), - fit_timepoints=fit_timepoints, return_delta=return_delta, - return_info=return_info, return_model=return_model, + fit_timepoints=fit_timepoints, refit_every=refit_every, + return_delta=return_delta, return_info=return_info, + return_model=return_model, ) X = [subjects] diff --git a/timecorr/model.py b/timecorr/model.py index 3f7ede49..c7b11fe0 100644 --- a/timecorr/model.py +++ b/timecorr/model.py @@ -17,21 +17,46 @@ ``FeaturesModel`` holds the settings and the fits of pass 1; ``FeaturesModel.transform`` is pass 2 on other data. ``_single_fit`` is pass 1 and ``_causal_pass`` either pass. + +``refit_every=m`` repeats both passes for the fits at rows ``s_j = n + j m`` +(``_refit``): fit ``j`` is pass 1 on the first ``s_j`` rows, with the +structure of the first fit (``_refit_settings``) and every reducer's fit +matched to the fit before as soon as it is made (``_Matched``), so that +the next order of that fit is fitted on the matched columns; rows +``[s_j, s_{j+1})`` of the output are those of pass 2 on every row with fit +``j``. A fit that cannot have the structure of the first one +(``helpers._FitUnusable``) is left out: the fit before stays for its rows. """ import copy +import numpy as np +from scipy.optimize import linear_sum_assignment + from .events import _has_features, _parse_spec, resolve_events_by_order -from .helpers import _FittedModel, format_data, gaussian_weights +from .helpers import ( + _SUMMARY_NAMES, + _FittedModel, + _FitUnusable, + format_data, + gaussian_weights, +) from .higher_order import ( _constant_columns, _fit_pass, + _no_components_message, _output_elements, _step_info, _two_path_step, _warmup_rows, ) -from .summaries import Communities, _FittedSummary, _Summary +from .summaries import ( + Communities, + _auto_fallback, + _FittedSummary, + _from_name, + _Summary, +) from .timecorr import _needs_fit __all__ = ["FeaturesModel"] @@ -59,7 +84,7 @@ def _events_by_order(events, T, n_subjects, order): def _causal_pass(settings, subjects, events, *, steps=None, record=None, - keep_delta=True, single=False): + keep_delta=True, single=False, match=None): """ One causal pass of the two-path pipeline over ``subjects`` (a list of (T, K) arrays): ``(X, D, info)``, the lists of outputs by order @@ -75,7 +100,9 @@ def _causal_pass(settings, subjects, events, *, steps=None, record=None, specification, resolved for these rows. ``keep_delta``: whether the feeding features of every order are kept (counted against ``max_memory_gb``); ``single``: the data were one array (the entries of - ``info`` then describe arrays, not lists). + ``info`` then describe arrays, not lists). ``match`` (with + ``record``): the fits of the fit before, to which each new fit is + matched when it is made (a refit; see ``_Matched``). """ s = settings order = s["order"] @@ -89,7 +116,7 @@ def _causal_pass(settings, subjects, events, *, steps=None, record=None, for k in range(1, order + 1): kept = X[1:] + ([d for d in D[1:] if d is not None] if keep_delta else ([] if k == 1 else [fed_by])) - used = {} + used = {} if match is None else _Matched(match[k], k) x, delta = _two_path_step( fed_by, delta_rfun=s["delta_rfun"][k], @@ -118,7 +145,7 @@ def _causal_pass(settings, subjects, events, *, steps=None, record=None, record=used, ) if record is not None: - record[k] = used + record[k] = dict(used) X.append(x) D.append(delta) feeding = used.get("feeding") @@ -141,6 +168,8 @@ def _causal_pass(settings, subjects, events, *, steps=None, record=None, entry["warmup_rows"] = _warmup_rows(out) if _is_fit(used.get(entry["path"])): entry["fit_timepoints"] = s["fit_timepoints"] + entry["refit_rows"] = list(s.get("refits", [s["fit_timepoints"]])) + entry["refit_kept_previous"] = list(s.get("refit_kept_previous", [])) info.extend(entries) if delta is not None: fed_by = delta @@ -169,14 +198,298 @@ def _single_fit(settings, subjects, events): return steps +# -- refits ------------------------------------------------------------------ + +# the attributes of a fitted scikit-learn model that hold one value per +# component (reordered with ``components_``), and the one with one column +# per component +_PER_COMPONENT = ("explained_variance_", "explained_variance_ratio_", + "singular_values_") +_COLUMN_PER_COMPONENT = "mixing_" +# a model with reordered components must give the reordered outputs of the +# model as fitted to this (relative to the largest of them, at least 1) +_MATCH_RTOL = 1e-9 + + +def _components(fitted): + """``components_`` of a ``_FittedModel`` as a 2-D array, or None.""" + estimator = getattr(fitted.model, "model_", fitted.model) + components = getattr(estimator, "components_", None) + if components is None: + return None + components = np.asarray(components, dtype=np.float64) + return components if components.ndim == 2 else None + + +def _assignment(score): + """For each row of a square score matrix, the column of the one-to-one + assignment with the largest total score.""" + rows, columns = linear_sum_assignment(-np.asarray(score, dtype=np.float64)) + out = np.empty(len(rows), dtype=int) + out[rows] = columns + return out + + +def _match_model(new, previous, order, path): + """ + ``new`` (a ``_FittedModel``) with its components in the order and with + the signs of those of ``previous``: each component is assigned to one + of ``previous`` (the one-to-one assignment with the largest sum of + |cosine| between component vectors), takes its place, and is negated + when the cosine is negative; the columns frozen as constant + (``constants``) follow, and the padding stays last. ``new`` itself + when nothing moves. ``_FitUnusable`` when the numbers of components or + of padded columns differ; ``ValueError`` when the reordered model does + not give the reordered outputs. + """ + a, b = _components(new), _components(previous) + if a is None or b is None: + label = type(getattr(new.model, "model_", new.model)).__name__ + raise ValueError(_no_components_message( + label, "rfun" if path == "analysis" else "delta_rfun", order)) + if a.shape != b.shape or new.pad != previous.pad: + raise _FitUnusable( + f"refit at order {order} ({path}): the model has {a.shape[0]} " + f"components and {new.pad} padded columns; the fit before " + f"{b.shape[0]} and {previous.pad}." + ) + c = a.shape[0] + norms = np.linalg.norm(a, axis=1)[:, None] * np.linalg.norm(b, axis=1)[None, :] + with np.errstate(divide="ignore", invalid="ignore"): + cosine = np.where(norms > 0, (a @ b.T) / norms, 0.0) + cosine = np.nan_to_num(cosine, nan=0.0, posinf=0.0, neginf=0.0) + place = _assignment(np.abs(cosine)) # place[q]: where component q goes + source = np.empty(c, dtype=int) + source[place] = np.arange(c) # source[p]: the component that comes to p + signs = np.where(cosine[source, np.arange(c)] < 0, -1.0, 1.0) + if np.array_equal(source, np.arange(c)) and np.all(signs > 0): + return new + model = copy.deepcopy(new.model) + estimator = getattr(model, "model_", model) + fitted = np.asarray(estimator.components_) + estimator.components_ = np.ascontiguousarray(signs[:, None] * fitted[source]) + for name in _PER_COMPONENT: + value = getattr(estimator, name, None) + if isinstance(value, np.ndarray) and value.shape[:1] == (c,): + setattr(estimator, name, np.ascontiguousarray(value[source])) + value = getattr(estimator, _COLUMN_PER_COMPONENT, None) + if isinstance(value, np.ndarray) and value.ndim == 2 and value.shape[1] == c: + setattr(estimator, _COLUMN_PER_COMPONENT, + np.ascontiguousarray(value[:, source] * signs)) + matched = _FittedModel(model, new.n_features, new.pad) + if new.constants is not None: + columns, means, tol = (np.array(v) for v in new.constants) + real = columns < c + columns[real] = place[columns[real]] + means[real] = means[real] * signs[columns[real]] + at = np.argsort(columns) + matched.constants = (columns[at], means[at], tol[at]) + # the reordered model on rows of its own: the reordered outputs + probe = np.random.RandomState(0).standard_normal((4, new.n_features)) + probe = probe * np.max(np.abs(fitted), initial=1.0) + before, after = new.apply([probe])[0], matched.apply([probe])[0] + expected = before.copy() + expected[:, :c] = before[:, source] * signs + scale = max(1.0, float(np.max(np.abs(expected), initial=0.0))) + if not np.max(np.abs(after - expected), initial=0.0) <= _MATCH_RTOL * scale: + raise ValueError( + f"refit_every: the components of the model at order {order} ({path}) " + "could not be put in the order of the fit before (the reordered " + "model does not give the reordered outputs). Use 'PCA', " + "'IncrementalPCA', 'FactorAnalysis' or 'TruncatedSVD', or a summary." + ) + return matched + + +def _match_labels(labels, previous): + """ + The community labels of a refit with the communities of 2 or more + members (one output column each, in the order of their labels) in the + order of those of the fit before: each is assigned to one of the + earlier ones (the one-to-one assignment with the largest number of + shared nodes) and takes the label that puts its column at that one's + place. Single-node communities keep their labels. ``_FitUnusable`` + when the numbers of such communities differ. + """ + labels, previous = np.asarray(labels), np.asarray(previous) + kept = np.flatnonzero(np.bincount(labels) >= 2) + kept_before = np.flatnonzero(np.bincount(previous) >= 2) + if len(kept) != len(kept_before) or len(labels) != len(previous): + raise _FitUnusable( + f"refit: {len(kept)} communities of 2 or more nodes; the fit " + f"before has {len(kept_before)}." + ) + shared = np.array([[np.sum((labels == q) & (previous == p)) for p in kept_before] + for q in kept]).reshape(len(kept), len(kept)) + place = _assignment(shared) # place[q]: the column community kept[q] takes + out = labels.copy() + for q, label in enumerate(kept): + out[labels == label] = kept[place[q]] + return out + + +# what an automatic feeding step records about its choice (made by the first fit) +_AUTO_KEYS = ("n_columns", "fallback", "n_exceed", "null_threshold", "n_null") + + +def _match(new, previous, order, path): + """ + The fit ``new`` of a refit, matched to ``previous``, the fit before of + the same step (see ``_match_model`` and ``_match_labels``; the fits of + ``WeightedStrength`` have nothing to match); ``new`` itself when + nothing changes. ``_FitUnusable`` when ``new`` has not the structure + of ``previous``. + """ + if isinstance(new, _FittedModel) and isinstance(previous, _FittedModel): + return _match_model(new, previous, order, path) + if not (isinstance(new, _FittedSummary) and isinstance(previous, _FittedSummary)): + return new + if "fallback" in previous.fit: + # the choice of the automatic feeding reducer is the first fit's + new.fit.update({key: previous.fit[key] for key in _AUTO_KEYS}) + if not (isinstance(new.summary, Communities) + and isinstance(previous.summary, Communities)): + return new + labels = _match_labels(new.fit["labels"], previous.fit["labels"]) + if np.array_equal(labels, new.fit["labels"]): + return new + return _FittedSummary(new.summary, {**new.fit, "labels": labels}) + + +class _Matched(dict): + """ + The record of one order of a refit (``record`` of ``_two_path_step``): + a fit stored under its path is replaced by that fit matched to the fit + before (``previous``: that order's record of the fit before), and the + step is then reduced with what the record holds + (``higher_order._apply_reducer`` and ``_run_streamed`` read it back). + """ + + def __init__(self, previous, order): + super().__init__() + self.previous = previous + self.order = order + + def __setitem__(self, path, fit): + super().__setitem__(path, _match(fit, self.previous[path], self.order, path)) + + +def _refit_settings(settings, steps): + """ + The settings of the fits after the first, whose fits are ``steps``: + the structure is the first fit's. A summary that chose its number of + communities with the shift null gets that number (no null runs again); + an automatic feeding step is what it chose, those communities or the + weighted strength it fell back to. The summaries are copies, so the + objects of the caller keep the records of the first fit. + """ + s = FeaturesModel._detached(settings) + for name, path in (("rfun", "analysis"), ("delta_rfun", "feeding")): + reducers = dict(s[name]) + for k, step in steps.items(): + fitted = step.get(path) + if not isinstance(fitted, _FittedSummary): + continue + reducer = reducers[k] + if isinstance(reducer, str) and reducer in _SUMMARY_NAMES: + reducer = _from_name(reducer) + if fitted.fit.get("fallback"): + reducers[k] = _auto_fallback() + elif reducer._needs_communities and reducer.n is None: + reducer = copy.copy(reducer) + reducer.n = int(fitted.fit["n"]) + reducer._from_auto = False + reducers[k] = reducer + s[name] = reducers + return s + + +def _summaries(settings): + return {id(r): r for name in ("rfun", "delta_rfun") + for r in settings[name].values() if isinstance(r, _Summary)}.values() + + +def _stitch(into, part, start): + """Rows ``start:`` of the outputs ``part`` (arrays, lists of arrays or + None, by order) copied into ``into``.""" + for a, b in zip(into[1:], part[1:]): + if a is None: + continue + for u, v in zip(a if isinstance(a, list) else [a], + b if isinstance(b, list) else [b]): + u[start:] = v[start:] + + +def _refit(model, settings, subjects, single, events, return_delta, refit_every, + X, D, info): + """ + The fits after the first of ``refit_every`` (module docstring): the + outputs ``X`` and ``D`` of pass 2 with the first fit get, from each row + ``s_j`` on, the rows of pass 2 with fit ``j``; ``model`` gets the last + fit. Returns the ``return_info`` entries (those of the last fit's + pass, with the constant columns and warm-up rows of the outputs as + returned, the rows of the fits and those whose fit was left out). + """ + steps = model._steps + for k, step in steps.items(): + for path, fitted in step.items(): + if isinstance(fitted, _FittedModel) and _components(fitted) is None: + label = type(getattr(fitted.model, "model_", fitted.model)).__name__ + raise ValueError(_no_components_message( + label, "rfun" if path == "analysis" else "delta_rfun", k)) + n, T = settings["fit_timepoints"], subjects[0].shape[0] + rows = [n] + list(range(n + refit_every, T, refit_every)) + fit_settings = _refit_settings(settings, steps) + kept = [] + for s_j in rows[1:]: + for summary in _summaries(fit_settings): + summary.fits_ = [] + new = {} + try: + with _fit_pass(): + _causal_pass(dict(fit_settings, fit_timepoints=s_j), + [x[:s_j] for x in subjects], events, record=new, + keep_delta=False, match=steps) + except _FitUnusable: + # not the structure of the first fit: the fit before stays, and + # with it the rows already there + kept.append(s_j) + continue + steps = new + with _fit_pass(): + X_j, D_j, info = _causal_pass(model._settings, subjects, events, + steps=steps, keep_delta=return_delta, + single=single) + _stitch(X, X_j, s_j) + _stitch(D, D_j, s_j) + del X_j, D_j + model._steps = steps + model._settings["refits"] = rows + model._settings["refit_kept_previous"] = kept + for entry in info: + out = (X if entry["path"] == "analysis" else D)[entry["order"]] + if single and isinstance(out, list): + out = out[0] + entry["constant_columns"] = _constant_columns(out, True) + entry["warmup_rows"] = _warmup_rows(out) + if "refit_rows" in entry: + entry["refit_rows"] = list(rows) + entry["refit_kept_previous"] = list(kept) + return info + + def _causal_features(subjects, single, events, settings, *, fit_timepoints, - return_delta, return_info, return_model): + refit_every, return_delta, return_info, return_model): """``features(..., causal=True)`` on formatted subjects, after its checks.""" settings = dict(settings, fit_timepoints=fit_timepoints) steps = _single_fit(settings, subjects, events) model = FeaturesModel(settings, steps, n_features=subjects[0].shape[1], n_subjects=len(subjects)) - result, info = model._transform(subjects, single, events, return_delta) + X, D, info = model._pass(subjects, single, events, return_delta) + if refit_every is not None and steps is not None: + info = _refit(model, settings, subjects, single, events, return_delta, + refit_every, X, D, info) + result = model._returned(X, D, single, return_delta) model.info = info out = (result,) + ((info,) if return_info else ()) + ( (model,) if return_model else ()) @@ -216,6 +529,11 @@ class FeaturesModel: fit_timepoints : int or None The number of first rows the reducers were fitted on (None: the call gave none, and no reducer needed a fit). + refits : list of int + The rows of the fits: ``[fit_timepoints]``, and with + ``refit_every`` every row at which the reducers were fitted again + (each fit read the rows before its row only); empty when no + reducer was fitted. The model holds the last fit. n_features, n_subjects : int The numbers of columns and of subjects of the data of the fit. info : list of dict @@ -242,6 +560,14 @@ class FeaturesModel: Notes ----- + With ``refit_every`` the model holds the last fit (its columns matched + to those of the fits before), and ``transform`` applies it to every + row. The ``features`` call returned, before the last row of + ``refits``, rows made with earlier fits: ``transform`` of the same + data equals that output from ``refits[-1]`` on (and on every row + when that fit is the only one) and, before it, differs from it as the + fits differ. + A model can be pickled when the arguments of the call can: a ``cfun``, reducer or kernel function that is a lambda or a local function cannot. Unpickling needs the same versions of timecorr, hypertools and @@ -301,6 +627,13 @@ def detach(reducer): order = property(lambda self: self._settings["order"]) fit_timepoints = property(lambda self: self._settings["fit_timepoints"]) + + @property + def refits(self): + if self._steps is None or not any( + _is_fit(f) for step in self._steps.values() for f in step.values()): + return [] + return list(self._settings.get("refits", [self.fit_timepoints])) weights_function = property(lambda self: self._settings["weights_function"]) weights_params = property(lambda self: self._settings["weights_params"]) delta_weights_function = property( @@ -441,15 +774,19 @@ def transform(self, data, return_delta=False, return_info=False, *, events=None) "were not computed by the features call that made this model; " "call features with return_delta=True." ) - result, info = self._transform(subjects, single, events, return_delta) + X, D, info = self._pass(subjects, single, events, return_delta) + result = self._returned(X, D, single, return_delta) return (result, info) if return_info else result - def _transform(self, subjects, single, events, return_delta): - """Pass 2 on formatted subjects: ``(result, info)``.""" - X, D, info = _causal_pass(self._settings, subjects, events, - steps=self._steps, keep_delta=return_delta, - single=single) + def _pass(self, subjects, single, events, return_delta): + """Pass 2 on formatted subjects: ``(X, D, info)`` of ``_causal_pass``.""" + return _causal_pass(self._settings, subjects, events, steps=self._steps, + keep_delta=return_delta, single=single) + + @staticmethod + def _returned(X, D, single, return_delta): + """The outputs of a pass as ``features`` returns them.""" if single: X = [x[0] if isinstance(x, list) else x for x in X] D = [d if d is None else d[0] for d in D] - return ((X, D) if return_delta else X), info + return (X, D) if return_delta else X diff --git a/timecorr/summaries.py b/timecorr/summaries.py index 8cfa2563..5c97c862 100644 --- a/timecorr/summaries.py +++ b/timecorr/summaries.py @@ -30,6 +30,7 @@ from ._kernels import LagKernel from .helpers import ( _WCORR_NAN_PRODUCTS, + _FitUnusable, _causal_clean, _corr_row_blocks, _fisher_mean, @@ -262,7 +263,7 @@ def _find_communities(wbar, n): def _check_labels(labels, what): """Raise ``ValueError`` unless some community has at least 2 members.""" if not np.any(np.bincount(labels) >= 2): - raise ValueError( + raise _FitUnusable( f"{what}: the clustering left no community with at least 2 members " f"({len(labels)} nodes in {len(np.unique(labels))} communities); " "use a smaller n." @@ -1931,7 +1932,7 @@ def _check_defined(states): """``ValueError`` when a unit of a causal fit has no defined timepoint.""" for s, state in enumerate(states): if state["T"] < 1: - raise ValueError( + raise _FitUnusable( "causal=True: the rows the reducers are fitted on " f"(fit_timepoints) hold no timepoint with defined correlations" f"{'' if len(states) == 1 else f' for subject {s}'} (the first " diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 777cfc84..11b59a09 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -19,6 +19,7 @@ _MIN_SAMPLES_RTOL, _SUMMARY_NAMES, _FittedModel, + _FitUnusable, _is_model, _model_reduce, _abs_weights, @@ -381,7 +382,7 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F at = "" if order is None else f" at order {order}" fewest = min(len(r) for r in rows) if is_summary else sum(len(r) for r in rows) if fewest < (1 if is_summary else 2): - raise ValueError( + raise _FitUnusable( f"causal=True: the rows {name} is fitted on (fit_timepoints){at} " f"hold {'no row' if is_summary else 'fewer than 2 rows'} with " "defined correlations (the first rows of every order are " @@ -404,7 +405,7 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F raise NotImplementedError("hypertools returned no fitted model") again = fitted.apply(rows) except (NotImplementedError, AttributeError, TypeError) as err: - raise ValueError( + raise _FitUnusable( f"causal=True: the model {label!r} ({name}{at}) cannot reduce rows it " f"was not fitted on ({err}), so it cannot be fitted on the first " "rows and applied to later ones. Use a model with an out-of-sample " @@ -414,7 +415,7 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F for r, a in zip(reduced, again)) scale = max(1.0, max(float(np.max(np.abs(a), initial=0.0)) for a in again)) if not worst <= _REFIT_ATOL * scale: - raise ValueError( + raise _FitUnusable( f"causal=True: the model {label!r} ({name}{at}) does not reproduce " f"the rows it was fitted on when it reduces them again (they differ " f"by up to {worst:.3g}), so the rows it is fitted on and later rows " From f4625f6ed3bb5e8ee9289be62a83a2bafc368814 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 14:25:37 -0500 Subject: [PATCH 11/26] Causal mode: five defects found in review of the fitted reducers - 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 155 ++++++++++++++++++ tests/test_causal_fit.py | 287 +++++++++++++++++++++++++++++++++ timecorr/helpers.py | 229 +++++++++++++++++++------- timecorr/higher_order.py | 84 +++++----- timecorr/model.py | 47 ++---- timecorr/summaries.py | 9 +- timecorr/timecorr.py | 162 ++++++++++++++----- 7 files changed, 792 insertions(+), 181 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 14ac837d..18b84b7b 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -1076,3 +1076,158 @@ def test_one_row_of_a_wide_kernel_is_not_a_delta_kernel(): weights_function=tc.boxcar_weights, weights_params={"width": 1}) with pytest.raises(ValueError, match="delta"): tc.wcorr(x[:2], x[:2], np.eye(2), causal=True) + + +# ---------------------------------------------------------------------------- +# the reach of a restricted kernel, and of kernels without a limit +# ---------------------------------------------------------------------------- + + +def _restricted_reach(function, params, exclude, include_zero=True, n=4000): + """The largest effective sample size a row of the restricted kernel has + with up to ``n - 1`` earlier timepoints.""" + kernel = helpers._lag_kernel(n, function, params, "backward", include_zero, exclude) + # the last row, by lag: over the lags up to each one + w = np.abs(kernel.block(n - 1, n, 0, n))[0][::-1] + with np.errstate(invalid="ignore", divide="ignore"): + ess = np.cumsum(w) ** 2 / np.cumsum(w * w) + return float(np.nanmax(ess)) if not np.isnan(ess).all() else float("nan") + + +def _kernel_reach(function, params, include_zero=True, exclude=None): + return helpers._kernel_reach( + helpers._lag_kernel(5, function, params, "backward", include_zero, exclude)) + + +def test_a_kernel_of_infinite_width_has_no_limit(): + for include_zero in (True, False): + assert _kernel_reach(tc.boxcar_weights, {"width": np.inf}, include_zero) is None + assert _kernel_reach(tc.uniform_weights, None, include_zero) is None + # the lags from 4 on: still without a limit + assert _kernel_reach(tc.uniform_weights, None, include_zero, -3) is None + assert _kernel_reach(tc.boxcar_weights, {"width": np.inf}, include_zero, + -3) is None + x = np.random.default_rng(30).standard_normal((50, 3)) + kw = dict(causal=True, cfun=tc.autofc, weights_function=tc.boxcar_weights, + weights_params={"width": np.inf}) + # more than these 50 rows hold, not more than a row can have: NaN rows + assert np.isnan(_quiet(tc.timecorr, x, min_samples=2000, **kw)).all() + out = _quiet(tc.timecorr, x, min_samples=30, **kw) + assert np.array_equal(np.flatnonzero(np.isnan(out).all(axis=1)), np.arange(29)) + feats = _quiet(tc.features, x, order=1, rfun=None, delta_rfun=None, + delta_weights_function=tc.boxcar_weights, + delta_weights_params={"width": np.inf}, min_samples=2000, **kw) + assert np.isnan(feats[1]).all() + + +@pytest.mark.parametrize("function,params", [ + (tc.uniform_weights, None), (tc.boxcar_weights, {"width": np.inf}), + (tc.boxcar_weights, {"width": 30}), (tc.gaussian_weights, {"var": 25}), + (tc.laplace_weights, {"scale": 4.0}), (tc.t_weights, {"df": 2}), + (tc.mexican_hat_weights, {"sigma": 6.0}), +], ids=lambda v: getattr(v, "__name__", str(v))) +@pytest.mark.parametrize("exclude", [3, 0, -3, 40, -40]) +@pytest.mark.parametrize("include_zero", [True, False]) +def test_reach_of_a_kernel_restricted_by_exclude_timepoints(function, params, exclude, + include_zero): + reach = _kernel_reach(function, params, include_zero, exclude) + flat = function is tc.uniform_weights or params == {"width": np.inf} + if flat and exclude < 0: + assert reach is None # every lag beyond: no limit + return + heavy = function is tc.t_weights and exclude < 0 + most = _restricted_reach(function, params, exclude, include_zero, + n=200_000 if heavy else 4000) + if np.isnan(most): + most = 0.0 # no lag with weight (the lag 0 alone, without the diagonal) + assert reach == pytest.approx(most, rel=1e-3 if heavy else 1e-9, abs=1e-12) + if flat and exclude >= 0: + assert reach == exclude + 1 - (not include_zero) + if exclude == 0: + return # the lag 0 alone: a delta kernel, which causal mode refuses + # the decision of timecorr: a number above it raises, one below does not + x = np.random.default_rng(31).standard_normal((60, 3)) + kw = dict(causal=True, cfun=tc.autofc, weights_function=function, + weights_params={} if params is None else params, + include_zero=include_zero, exclude_timepoints=exclude) + with pytest.raises(ValueError, match="min_samples.*more than a row"): + tc.timecorr(x, min_samples=max(1.0, reach) * (1 + 1e-6) + 1e-9, **kw) + with pytest.raises(ValueError, match="min_samples.*more than a row"): + tc.timecorr(x, cfun=None, causal=True, weights_function=function, + weights_params={} if params is None else params, + include_zero=include_zero, exclude_timepoints=exclude, + min_samples=max(1.0, reach) * (1 + 1e-6) + 1e-9) + if reach >= 1: + _quiet(tc.timecorr, x, min_samples=reach * (1 - 1e-6), **kw) + + +def test_the_uniform_kernel_restricted_to_four_lags_cannot_reach_five(): + x = np.random.default_rng(32).standard_normal((40, 3)) + kw = dict(causal=True, cfun=tc.autofc, weights_function=tc.uniform_weights, + weights_params={}, exclude_timepoints=3) + with pytest.raises(ValueError, match=r"min_samples=5 .*is 4\b"): + tc.timecorr(x, min_samples=5, **kw) + out = _quiet(tc.timecorr, x, min_samples=4, **kw) + assert np.array_equal(np.flatnonzero(np.isnan(out).all(axis=1)), np.arange(3)) + + +def test_reach_of_wide_kernels_with_exclude_timepoints(): + # wider than the lags that are added up, and restricted + assert _kernel_reach(tc.uniform_weights, None, exclude=1e8) == 1e8 + 1 + assert _kernel_reach(tc.uniform_weights, None, False, 1e8) == 1e8 + assert _kernel_reach(tc.boxcar_weights, {"width": np.inf}, exclude=1e8) == 1e8 + 1 + # the lags from 6 on of the 5e8 of a boxcar + assert _kernel_reach(tc.boxcar_weights, {"width": 1e9}, exclude=-5) == 5e8 - 6 + # the first 11 lags of a kernel that is flat over them + assert _kernel_reach(tc.gaussian_weights, {"var": 1e14}, exclude=10) == pytest.approx( + 11, rel=1e-9) + assert _kernel_reach(tc.laplace_weights, {"scale": 1e9}, exclude=10) == pytest.approx( + 11, rel=1e-6) + # without its first lags a wide kernel reaches nearly what it reaches whole + whole = _kernel_reach(tc.gaussian_weights, {"var": 1e14}) + assert _kernel_reach(tc.gaussian_weights, {"var": 1e14}, exclude=-10) == pytest.approx( + whole, rel=1e-5) + assert _kernel_reach(tc.gaussian_weights, {"var": 1e14}, exclude=-10) < whole + # restricted beyond the lags added up: at most the kernel's own reach, + # at least the reach of the lags added up + for function, params in ((tc.boxcar_weights, {"width": 1e9}), + (tc.gaussian_weights, {"var": 1e18}), + (tc.t_weights, {"df": 1})): + bound = _kernel_reach(function, params, exclude=1e8) + assert bound is not None and bound <= _kernel_reach(function, params) + assert bound >= _kernel_reach(function, params, exclude=1e5) * (1 - 1e-9) + assert _kernel_reach(tc.boxcar_weights, {"width": 1e9}, exclude=1e8) == pytest.approx( + 1e8 + 1, rel=1e-13) + # only lags beyond those added up + assert _kernel_reach(tc.boxcar_weights, {"width": 1e9}, exclude=-1e8) == 4e8 - 1 + assert _kernel_reach(tc.boxcar_weights, {"width": 100}, exclude=-1e8) == 0 + far = _kernel_reach(tc.gaussian_weights, {"var": 1e18}, exclude=-1e8) + assert far == pytest.approx(_kernel_reach(tc.gaussian_weights, {"var": 1e18}), + rel=0.2) + assert _kernel_reach(tc.gaussian_weights, {"var": 25}, exclude=-1e8) == 0 + assert _kernel_reach(tc.t_weights, {"df": 1}, exclude=-1e8) > 1e8 + + +def test_reach_of_a_very_wide_mexican_hat_is_known(): + # the profile depends on lag / sigma: the reach grows in proportion + narrow = _kernel_reach(tc.mexican_hat_weights, {"sigma": 5000.0}) + for sigma in (5e6, 5e9, 5e15): + wide = _kernel_reach(tc.mexican_hat_weights, {"sigma": sigma}) + assert wide is not None + assert narrow * sigma / 5000 * 0.98 <= wide <= narrow * sigma / 5000 * 1.03 + + +@pytest.mark.parametrize("function,params", [ + (tc.gaussian_weights, {"var": np.inf}), (tc.laplace_weights, {"scale": np.inf}), + (tc.t_weights, {"df": np.inf}), (tc.gaussian_weights, {"var": np.nan}), + (tc.mexican_hat_weights, {"sigma": np.inf}), +], ids=str) +def test_reach_with_parameters_that_are_not_finite_never_fails(function, params): + with np.errstate(all="ignore"): + w = np.asarray(helpers._lag_kernel(50, function, params, "backward") + .block(0, 50, 0, 50)) + reach = _kernel_reach(function, params) + if not np.any(np.nan_to_num(w, nan=0.0, posinf=0.0)): + assert reach == 0 # a kernel without weight reaches nothing + else: + assert reach is None or reach > 0 diff --git a/tests/test_causal_fit.py b/tests/test_causal_fit.py index adade6fa..48811af4 100644 --- a/tests/test_causal_fit.py +++ b/tests/test_causal_fit.py @@ -725,3 +725,290 @@ def test_new_arguments_are_keyword_only_and_documented(function, names): assert section in tc.FeaturesModel.transform.__doc__ assert "Examples" in tc.FeaturesModel.__doc__ assert tc.FeaturesModel.__module__ == "timecorr.model" + + +# ---------------------------------------------------------------------------- +# models: only linear maps applied row by row +# ---------------------------------------------------------------------------- + +LINEAR = ["PCA", "IncrementalPCA", "TruncatedSVD", "FastICA"] + + +@pytest.mark.parametrize("model", ["UMAP", "KernelPCA", "Isomap"]) +def test_models_without_components_raise(model): + # reproducing its training rows does not make a model's transform one + # of each row alone (UMAP's depends on the number of rows it is given): + # only models with components_, a linear map, are taken + x = np.random.default_rng(60).standard_normal((100, 4)) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=40, + weights_params={"var": 25}) + rfun = {"model": model, "kwargs": {"n_neighbors": 5}} if model != "KernelPCA" else model + with pytest.raises(ValueError, match=f"causal=True: the model '{model}'.*components_"): + tc.timecorr(x, rfun=rfun, **kw) + kw["ndims"] = 2 + for name in ("rfun", "delta_rfun"): + other = "delta_rfun" if name == "rfun" else "rfun" + with pytest.raises(ValueError, match=f"causal=True: the model '{model}' " + rf"\({name}.*order 1.*components_"): + tc.features(x, order=1, delta_weights_params={"var": 16}, + **{name: rfun, other: "strength"}, **kw) + with pytest.raises(ValueError, match=f"causal=True: the model '{model}'"): + two_path_step(x, delta_weights_params={"var": 16}, + **{name: rfun, other: "strength"}, **kw) + with pytest.raises(ValueError, match="components_"): + tc.features(x, order=1, delta_weights_params={"var": 16}, rfun=rfun, + delta_rfun="strength", refit_every=20, **kw) + + +def test_a_model_whose_transform_is_not_row_by_row_raises(): + from sklearn.decomposition import PCA + + class BatchCentered(PCA): + """Components, but an output that depends on the other rows given.""" + + def transform(self, X): + out = super().transform(X) + return out - out.mean(axis=0) + + class Unfitted(PCA): + """No components_ once fitted.""" + + def fit(self, X, y=None): + super().fit(X, y) + self.axes_ = self.components_ + del self.components_ + return self + + def fit_transform(self, X, y=None): + return self.fit(X).transform(X) + + def transform(self, X): + return (X - self.mean_) @ self.axes_.T + + x = np.random.default_rng(61).standard_normal((100, 4)) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=40, + weights_params={"var": 25}) + with pytest.raises(ValueError, match="row by row"): + _quiet(tc.timecorr, x, rfun={"model": BatchCentered}, **kw) + with pytest.raises(ValueError, match=r"order 1.*row by row"): + _quiet(tc.features, x, order=1, rfun={"model": BatchCentered}, ndims=2, + delta_rfun="strength", delta_weights_params={"var": 16}, **kw) + with pytest.raises(ValueError, match="components_"): + _quiet(tc.timecorr, x, rfun={"model": Unfitted}, **kw) + # without causal they reduce the recording + assert _quiet(tc.timecorr, x, cfun=tc.autofc, + rfun={"model": BatchCentered}).shape == (100, 4) + + +@pytest.mark.parametrize("model", LINEAR) +def test_linear_models_are_taken_and_guaranteed(model): + x = np.random.default_rng(62).standard_normal((T, 5)) + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun=model, delta_rfun=model, + ndims=3, fit_timepoints=N, return_delta=True, **PARAMS) + full, fitted = _quiet(tc.features, x, return_model=True, **kw) + assert hasattr(fitted.fits[(1, "analysis")].model_, "components_") + rng = np.random.default_rng(63) + worst = 0.0 + for mode in MODES: + for m in (N, 190): + part = _quiet(tc.features, _perturb(x, m, mode, rng), **kw) + worst = max(worst, _worst(full, part, m)) + if mode != "remove": + assert _identical(full, part, m) + assert worst <= ATOL + # the model on a series and on its first rows + z = np.random.default_rng(64).standard_normal((300, 5)) + whole = _quiet(fitted.transform, z, return_delta=True) + part = _quiet(fitted.transform, z[:120], return_delta=True) + assert _worst(whole, part, 120) <= ATOL + + +# ---------------------------------------------------------------------------- +# a subject without a defined row keeps its place +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("rfun", [tc.WeightedStrength(), "PCA", "strength"], ids=str) +def test_a_subject_without_defined_rows_keeps_its_place(rfun): + import functools + + x = np.random.default_rng(3).normal(size=(80, 4)) + # a combine function of the user's: the step is not streamed + kw = dict(order=1, causal=True, cfun=tc.autofc, rfun=rfun, delta_rfun=rfun, + combine=functools.partial(tc.null_combine), fit_timepoints=40, + return_delta=True, **PARAMS) + _, model = _quiet(tc.features, [x, 2 * x], return_model=True, **kw) + y = x.copy() + y[:60] = np.nan + some = _quiet(model.transform, [y, x], return_delta=True) + gone = y.copy() + gone[60:] = np.nan # later rows missing too: no defined row is left + none = _quiet(model.transform, [gone, x], return_delta=True) + for a, b in zip(some, none): + assert len(b[1]) == 2 and b[1][0].shape == a[1][0].shape + assert np.isnan(b[1][0]).all() + # replacing later rows by NaN changes no bit of the rows before + assert np.array_equal(a[1][0][:60], b[1][0][:60], equal_nan=True) + assert np.array_equal(a[1][1], b[1][1], equal_nan=True) + assert not np.isnan(a[1][1][5:]).any() + + +def test_features_with_a_subject_without_defined_rows(): + x = np.random.default_rng(3).normal(size=(80, 4)) + y = x.copy() + y[:60] = np.nan + gone = np.full_like(x, np.nan) + # a model is fitted to the rows of all subjects: one of them suffices + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun="PCA", delta_rfun="PCA", + ndims=3, fit_timepoints=40, return_delta=True, **PARAMS) + some = _quiet(tc.features, [y, x], **kw) + none = _quiet(tc.features, [gone, x], **kw) + for a, b in zip(some, none): + for k in (1, 2): + assert np.isnan(b[k][0]).all() and b[k][0].shape == a[k][0].shape + assert np.array_equal(a[k][0][:60], b[k][0][:60], equal_nan=True) + assert np.array_equal(a[k][1], b[k][1], equal_nan=True) + # a summary is fitted to each subject: no defined row, no fit + kw.update(rfun="weighted_strength", delta_rfun="weighted_strength", ndims=None) + with pytest.raises(ValueError, match="fit_timepoints"): + _quiet(tc.features, [gone, x], **kw) + kw["combine"] = __import__("functools").partial(tc.null_combine) + with pytest.raises(ValueError, match="fit_timepoints"): + _quiet(tc.features, [gone, x], **kw) + + +# ---------------------------------------------------------------------------- +# a model and the reducer objects of the caller are independent +# ---------------------------------------------------------------------------- + + +def _snapshot(summary): + import copy + + return copy.deepcopy(summary.fits_) + + +def _same_records(a, b): + assert len(a) == len(b) + for p, q in zip(a, b): + assert sorted(p) == sorted(q) + for name in p: + u, v = p[name], q[name] + if isinstance(u, (list, np.ndarray)): + if not all(np.array_equal(i, j) for i, j in zip(u, v)): + return False + elif u != v: + return False + return True + + +@pytest.mark.parametrize("streamed", [True, False]) +@pytest.mark.parametrize("refit", [None, 50]) +def test_a_model_does_not_share_its_fits_with_the_reducer_objects(streamed, refit): + import copy + import functools + + x = _modular(70) + strength, communities = tc.WeightedStrength(signed=True), tc.Communities(n=3) + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun=strength, + delta_rfun={1: communities, 2: "weighted_strength"}, + fit_timepoints=N, refit_every=refit, return_delta=True, **PARAMS) + if not streamed: + kw["combine"] = functools.partial(tc.null_combine) + out, info, model = _quiet(tc.features, x, return_info=True, return_model=True, **kw) + assert model.info is info + kept_info = copy.deepcopy(info) + before = _quiet(model.transform, x, return_delta=True) + # transforming with the model does not touch the objects + records = _snapshot(strength), _snapshot(communities) + _quiet(model.transform, x[:150], return_delta=True) + assert _same_records(strength.fits_, records[0]) + assert _same_records(communities.fits_, records[1]) + # changing the objects' records changes nothing in the model + for record in strength.fits_: + record["weights"][0][:] = 0 + record["mean_r"][0][:] = -1 + for record in communities.fits_: + record["weights"][0][:] = 0 + record["labels"][:] = 0 + assert _identical(before, _quiet(model.transform, x, return_delta=True)) + # nor does fitting them again, here or in another call + strength.fit(_quiet(tc.timecorr, _modular(71), cfun=tc.autofc, rfun=None, + weights_params={"var": 9})) + _quiet(tc.features, _modular(72), **{**kw, "fit_timepoints": 60}) + assert _identical(before, _quiet(model.transform, x, return_delta=True)) + assert model.info == kept_info and info == kept_info + assert _identical(before, _quiet(pickle.loads(pickle.dumps(model)).transform, x, + return_delta=True)) + + +def test_timecorr_does_not_share_a_fit_with_the_reducer_object(): + x = _modular(73) + strength = tc.WeightedStrength() + kw = dict(causal=True, cfun=tc.autofc, rfun=strength, fit_timepoints=N, + weights_params={"var": 25}) + out = _quiet(tc.timecorr, x, **kw) + record = _snapshot(strength) + assert np.array_equal(_quiet(tc.timecorr, x, **kw), out, equal_nan=True) + assert _same_records(strength.fits_, record) + + +# ---------------------------------------------------------------------------- +# reductions that change nothing +# ---------------------------------------------------------------------------- + + +def test_a_model_with_as_many_components_as_columns_is_the_identity(): + # hypertools returns such data as they are, and fits no model + x = np.random.default_rng(80).standard_normal((120, 4)) + one = dict(causal=True, cfun=tc.autofc, fit_timepoints=60, + weights_params={"var": 25}) + plain = _quiet(tc.timecorr, x, rfun=None, **one) + assert plain.shape == (120, 10) + two = dict(order=1, delta_rfun="strength", delta_weights_params={"var": 16}, **one) + assert np.array_equal(_quiet(tc.features, x, rfun="PCA", ndims=10, **two)[1], plain, + equal_nan=True) + # more components than columns: zero columns are appended, as without causal + padded = _quiet(tc.features, x, rfun="PCA", ndims=12, **two)[1] + assert padded.shape == (120, 12) + assert np.array_equal(padded[:, :10], plain, equal_nan=True) + defined = ~np.isnan(plain).all(axis=1) + assert np.all(padded[defined, 10:] == 0) and np.isnan(padded[~defined]).all() + usual = _quiet(tc.features, x, order=1, cfun=tc.autofc, rfun="PCA", ndims=12, + delta_rfun="strength", weights_params={"var": 25})[1] + assert usual.shape == (120, 12) and np.all(usual[:, 10:] == 0) + # one column: one correlation, itself + single = _quiet(tc.timecorr, x[:, :1], rfun="PCA", **one) + assert np.array_equal(single, _quiet(tc.timecorr, x[:, :1], rfun=None, **one), + equal_nan=True) + assert single.shape == (120, 1) + + +@pytest.mark.parametrize("refit", [None, 20]) +@pytest.mark.parametrize("columns,ndims", [(4, 10), (1, None)]) +def test_identity_reductions_through_the_orders(columns, ndims, refit): + x = np.random.default_rng(81).standard_normal((120, columns)) + kw = dict(order=2, causal=True, cfun=tc.autofc, ndims=ndims, fit_timepoints=60, + refit_every=refit, return_delta=True, return_info=True, + return_model=True, **PARAMS) + out, info, model = _quiet(tc.features, x, rfun="PCA", delta_rfun="PCA", **kw) + # order 1 reduces 10 columns to 10 (1 to 1): nothing; order 2 reduces 55 + # columns to 10 with a fitted model (1 to 1: nothing again) + same, same_info, _ = _quiet(tc.features, x, **kw, **( + dict(rfun={1: None, 2: "PCA"}, delta_rfun={1: None, 2: "PCA"}) + if columns == 4 else dict(rfun=None, delta_rfun=None))) + assert _identical(out, same) + assert [e["output_width"] for e in info] == [e["output_width"] for e in same_info] + assert info[0]["output_width"] == (10 if columns == 4 else 1) + rows = [60] if refit is None else [60, 80, 100] + assert info[0]["fit_timepoints"] == 60 and info[0]["refit_rows"] == rows + assert info[0]["refit_kept_previous"] == [] + assert model.refits == rows + assert _identical(_quiet(model.transform, x, return_delta=True), + _quiet(pickle.loads(pickle.dumps(model)).transform, x, + return_delta=True)) + if refit is None: + assert _identical(out, _quiet(model.transform, x, return_delta=True)) + # the guarantee + cut = _quiet(tc.features, x[:90], rfun="PCA", delta_rfun="PCA", **kw)[0] + assert _worst(out, cut, 90) <= ATOL diff --git a/timecorr/helpers.py b/timecorr/helpers.py index b1c9928b..93d7ba49 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -1581,51 +1581,80 @@ def value(x): return None -def _kernel_reach(kernel): +# ``_strided_reach`` evaluates a lag profile at this many lags, a stride apart +_STRIDED_LAGS = 2 ** 16 +# and returns its estimate times this, so that it is an upper bound +_STRIDED_MARGIN = 1.01 + + +def _flat_profile(profile): + """Whether a lag profile is the same weight at every lag + (``uniform_weights``; ``boxcar_weights`` of infinite width).""" + family = getattr(profile, "func", None) + if family is uniform_profile: + return True + if family is boxcar_profile: + params = (getattr(profile, "keywords", None) or {}).get("params") or {} + try: + return float(params.get("width")) == np.inf + except (TypeError, ValueError): + return False + return False + + +def _strided_reach(profile, lo): """ - The largest effective sample size ``(sum |w|)**2 / sum w**2`` a row of a - backward kernel can have with any number of earlier timepoints: the - largest over the lags ``0..n`` (from 1 without the diagonal, within - ``exclude_timepoints``), for every n. It does not depend on the length - of the series. - - The sums are added up over the first lags; when they have not converged - there (a heavy tail, as of ``t_weights`` with few degrees of freedom, or - a very wide kernel), the rest comes from the profile's formula - (``_profile_tails``), so the result is known for every built-in kernel - function and parameter value: exactly for ``boxcar_weights`` and - ``laplace_weights``, to round-off of the tail formula for - ``gaussian_weights`` and ``t_weights``, and as an upper bound for a - ``mexican_hat_weights`` wider than about 1000 samples. - - None when it has no limit (``uniform_weights``: the effective sample - size grows with the number of earlier timepoints) or is not known: a - kernel without a lag profile function (an array, a kernel function of - the user's), a ``mexican_hat_weights`` with sigma above 2 million - samples, and a kernel that is both wider than the lags added up and - restricted by ``exclude_timepoints``. The result is kept on the kernel. + An upper bound of the largest effective sample size over the lags + ``lo..n``, for every n, of a profile too wide for its lags to be added + up one by one: the profile is read at every ``s``-th lag, for the + smallest stride ``s`` (a power of 16) at which the sums converge within + ``_STRIDED_LAGS`` lags, and the result is ``s`` times the effective + sample size of those lags (the profile varies little within a stride; + there are at least ``_STRIDED_LAGS / 16`` lags in its extent), times + ``_STRIDED_MARGIN``. None when the sums converge at no stride. """ - profile = getattr(kernel, "lag_profile", None) - if profile is None or kernel.include != "backward": - return None - cached = getattr(kernel, "_reach", None) - if cached is not None: - return cached[0] - reach = None + k = np.arange(_STRIDED_LAGS, dtype=np.float64) + half = _STRIDED_LAGS // 2 + stride = 16.0 + while np.isfinite(lo + stride * _STRIDED_LAGS): + with np.errstate(all="ignore"): + a = np.abs(np.asarray(profile(lo + stride * k), dtype=np.float64)) + a[~np.isfinite(a)] = 0 + peak = a.max() + if peak > 0: + a /= peak + total, squares = np.cumsum(a), np.cumsum(a * a) + if total[-1] - total[half - 1] <= 1e-12 * total[-1]: + with np.errstate(invalid="ignore", divide="ignore"): + ess = total**2 / squares + return float(_STRIDED_MARGIN * stride * np.nanmax(ess)) + stride *= 16.0 + return None + + +def _profile_reach(profile, include_zero, exclude): + """``_kernel_reach`` from the lag profile function and the restrictions + of a backward kernel (``exclude``: ``exclude_timepoints`` or None).""" + lo, hi = (0 if include_zero else 1), np.inf # the lags lo..hi are kept + if exclude is not None: + x = int(abs(exclude)) + if exclude >= 0: + hi = x + else: + lo = max(lo, x + 1) + if lo > hi: + return 0.0 + if _flat_profile(profile): + # equal weights: the number of lags + return None if np.isinf(hi) else float(hi - lo + 1) n = 1024 - unbounded = getattr(profile, "func", None) is uniform_profile - while n <= _REACH_LAGS and not unbounded: + while n <= _REACH_LAGS: with np.errstate(over="ignore", invalid="ignore"): a = np.abs(np.asarray(profile(np.arange(n, dtype=np.int64)), dtype=np.float64)) a[~np.isfinite(a)] = 0 - if not kernel.include_zero: - a[0] = 0 - if kernel.exclude is not None: - x = int(min(abs(kernel.exclude), n)) - if kernel.exclude >= 0: - a[x + 1:] = 0 - else: - a[:x + 1] = 0 + a[:lo] = 0 + if hi < n: + a[hi + 1:] = 0 peak = a.max() if peak > 0: a /= peak # so that tiny weights do not underflow when squared @@ -1635,23 +1664,89 @@ def _kernel_reach(kernel): ess = total**2 / squares # converged: the later half of the lags adds nothing to the sums if total[-1] - total[n // 2 - 1] <= 1e-15 * total[-1]: - reach = float(np.nanmax(ess)) - break + return float(np.nanmax(ess)) # not converged: the rest of the sums from the profile's formula - # (not with exclude_timepoints, which cuts the tail) - tails = _profile_tails(profile, n) if kernel.exclude is None else None - if tails is not None: + # (the lags from n on: all kept when no lag ends them) + tails = _profile_tails(profile, n) if np.isinf(hi) else None + if tails is not None and np.isfinite(tails[0]): first, second = tails[0] / peak, tails[1] / peak**2 with np.errstate(invalid="ignore", divide="ignore"): limit = (total[-1] + first) ** 2 / (squares[-1] + second) - reach = float(np.nanmax([np.nanmax(ess), limit])) - break + return float(np.nanmax([np.nanmax(ess), limit])) + elif hi < n: + return 0.0 # every lag kept was read, and none has weight n *= 2 - else: - if not unbounded and peak == 0: - reach = 0.0 - if reach is not None and np.isinf(reach): - reach = None # no limit (a boxcar of infinite width) + n //= 2 # the lags 0..n-1 were read + if np.isfinite(hi): + # kept up to a lag beyond those read + if peak == 0: + return 0.0 # no weight at any lag read + near, far = _profile_tails(profile, n), _profile_tails(profile, hi + 1) + if near is not None and far is not None and near[1] > 0 and np.isfinite(near[0]): + # weights that fall with the lag: the sums over the lags n..hi + # from the formula, and the largest value at the last lag + first = (near[0] - far[0]) / peak + second = (near[1] - far[1]) / peak**2 + with np.errstate(invalid="ignore", divide="ignore"): + limit = (total[-1] + first) ** 2 / (squares[-1] + second) + return float(np.nanmax([np.nanmax(ess), limit])) + # no formula: at most what the kernel reaches without that end + return _profile_reach(profile, lo == 0, None) + if lo >= n: + # only lags beyond those read. The four families whose weights + # fall with the lag: the effective sample size grows with every + # lag added, to the limit of the formula's sums + tails = _profile_tails(profile, lo) + if tails is not None and tails[1] > 0: + return float(tails[0] ** 2 / tails[1]) if np.isfinite(tails[0]) else None + if tails is not None and tails[0] == 0: + return 0.0 + elif peak == 0: + return 0.0 # no weight at any lag read (parameters that are not finite) + return _strided_reach(profile, lo) + + +def _kernel_reach(kernel): + """ + The largest effective sample size ``(sum |w|)**2 / sum w**2`` a row of a + backward kernel can have with any number of earlier timepoints: the + largest over the lags kept up to lag n, for every n. The lags kept are + those the kernel's restrictions leave: from 1 without the diagonal + (``include_zero=False``); up to ``x`` with ``exclude_timepoints=x >= + 0``, from ``x + 1`` with ``exclude_timepoints=-x``. It does not depend + on the length of the series (nor on events: the last block of a series + grows with it). + + For a kernel with the same weight at every lag (``uniform_weights``, a + ``boxcar_weights`` of infinite width) it is the number of lags kept. + Otherwise the sums are added up over the first lags; when they have not + converged there (a heavy tail, as of ``t_weights`` with few degrees of + freedom, or a very wide kernel), the rest comes from the profile's + formula (``_profile_tails``). So the result is known for every + built-in kernel function and parameter value: exactly for + ``boxcar_weights``, ``laplace_weights`` and ``uniform_weights``, to + round-off of the tail formula for ``gaussian_weights`` and + ``t_weights``, and as an upper bound (so that a ``min_samples`` is + never refused wrongly) for a ``mexican_hat_weights`` wider than about + 1000 samples (beyond 2 million samples from ``_strided_reach``; one + that ``exclude_timepoints`` ends beyond the 4 million lags added up + has what it reaches without that end). 0 for a kernel without weight + at the lags kept. + + None when it has no limit (equal weights at lags without end: the + effective sample size grows with the number of earlier timepoints) and + for a kernel without a lag profile function (an array, a kernel + function of the user's). The result is kept on the kernel. + """ + profile = getattr(kernel, "lag_profile", None) + if profile is None or kernel.include != "backward": + return None + cached = getattr(kernel, "_reach", None) + if cached is not None: + return cached[0] + reach = _profile_reach(profile, kernel.include_zero, kernel.exclude) + if reach is not None and not np.isfinite(reach): + reach = None kernel._reach = (reach,) return reach @@ -3667,8 +3762,10 @@ class _FitUnusable(ValueError): class _FittedModel: """ A hypertools model fitted by ``_model_reduce``: ``model`` (the fitted - ``hypertools`` reducer; None when hypertools fitted none, as for a - single row), the number of input columns ``n_features`` and the number + ``hypertools`` reducer; None when hypertools fitted none: it returns + data with no more columns than the components asked for as they are, + and ``apply`` is then the identity), the number of input columns + ``n_features`` and the number of zero columns ``pad`` that ``reduce`` appends when the data supplied fewer components than requested. ``apply`` reduces other rows with it. @@ -3700,6 +3797,23 @@ def __init__(self, model, n_features, pad=0): self.pad = int(pad) self.constants = None # (columns, their training means, tolerances) + @property + def estimator(self): + """The fitted scikit-learn model (None for the identity).""" + return getattr(self.model, "model_", self.model) + + @property + def components(self): + """``components_`` of the fitted model, one vector per output + column, as a 2-D array; None when it has none.""" + components = getattr(self.estimator, "components_", None) + if components is None: + return None + components = np.asarray(components, dtype=np.float64) + if components.ndim != 2 or components.shape[1] != self.n_features: + return None + return components + def freeze_constants(self, outputs): stacked = np.vstack([np.asarray(o, dtype=np.float64) for o in outputs]) if not stacked.shape[0]: @@ -3722,9 +3836,12 @@ def apply(self, arrays): f"the fitted model takes {self.n_features} columns; got an " f"array of shape {a.shape}." ) - out = hyp.reduce(arrays, reduce=self.model) - out = out if isinstance(out, list) else [out] - out = [np.asarray(o, dtype=np.float64) for o in out] + if self.model is None: + out = [a.copy() for a in arrays] # the identity + else: + out = hyp.reduce(arrays, reduce=self.model) + out = out if isinstance(out, list) else [out] + out = [np.asarray(o, dtype=np.float64) for o in out] if self.pad: out = [np.hstack((o, np.zeros((o.shape[0], self.pad)))) for o in out] if self.constants is not None: diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index e3d6dcc1..c1c0dd76 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -63,7 +63,6 @@ import numpy as np from .helpers import ( - _COMPONENT_MODELS, _SUMMARY_NAMES, _check_min_samples, _check_ndims, @@ -113,6 +112,7 @@ from .timecorr import ( _apply_frozen, _check_fit_timepoints, + _check_linear_model, _event_kernels, _fit_reducer, _fixed_weights_wisfc, @@ -1889,11 +1889,19 @@ def two_path_step( ``t`` are replaced or removed, and a row ``t < n`` (in sample: the fits have read rows after it) when rows from ``n`` on are replaced or removed. ``n`` equal to the number of timepoints fits on every - row. A model must reduce rows it was not fitted on and reproduce - its training rows to 1e-9 (``"PCA"``, ``"IncrementalPCA"``, - ``"FactorAnalysis"``, ``"FastICA"``, ...; ``"MDS"``, ``"TSNE"``, - ``"SpectralEmbedding"`` and ``"LocallyLinearEmbedding"`` raise - ``ValueError``); ``"PCA"`` is fitted with ``svd_solver="full"`` + row. A model must be a linear map applied to each row by itself: + its fitted estimator has ``components_`` (``"PCA"``, + ``"IncrementalPCA"``, ``"TruncatedSVD"``, ``"FastICA"``, + ``"FactorAnalysis"``, ...), it reproduces its training rows to + 1e-9, and it reduces rows one at a time as it reduces them + together; any other model raises ``ValueError`` (``"UMAP"``, + ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, + ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the + transform of some of them depends on the rows it is given + together). A model asked for as many components as its input + has columns, or more, changes nothing (zero columns are appended + for the components beyond them), as without ``causal``. + ``"PCA"`` is fitted with ``svd_solver="full"`` unless a model dict gives a solver, because the randomized solver scikit-learn chooses for large inputs does not reproduce its rows. An output column of a model that is constant on the @@ -1990,7 +1998,7 @@ def two_path_step( when the first ``fit_timepoints`` rows hold no row with defined correlations for a fit (2 for a model), or fewer than 40 rows for the default feeding reducer or a shift null; and for a model that - cannot reduce rows it was not fitted on. + is not a linear map applied row by row (see ``fit_timepoints``). RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. TypeError @@ -2385,6 +2393,7 @@ def _check_causal(*, function, include_timepoints, weights_function, for name, given, resolved in (("rfun", rfun, analysis_rfun), ("delta_rfun", delta_rfun, feeding_rfun)): for k in sorted(resolved): + _check_linear_model(resolved[k], f"{name} at order {k}") if _needs_fit(resolved[k]) and fit_timepoints is None: raise ValueError( f"causal=True: {name}={_requested(given, k)!r} (order {k}) is " @@ -2419,26 +2428,10 @@ def _check_causal(*, function, include_timepoints, weights_function, ) -def _no_components_message(label, name, k): - """The error of ``refit_every`` for a model a refit cannot match.""" - return ( - f"refit_every: the model {label!r} ({name}, order {k}) has no " - "components_ (one vector per output column), so the columns of a " - "refit cannot be matched to those of the fit before. Use a model " - "that has them ('PCA', 'IncrementalPCA', 'FactorAnalysis', 'FastICA', " - "'TruncatedSVD', ...), a summary such as 'weighted_strength', or " - "leave refit_every out." - ) - - -def _check_refit_every(refit_every, causal, fit_timepoints, analysis_rfun, - feeding_rfun, fed): +def _check_refit_every(refit_every, causal, fit_timepoints): """ ``refit_every`` as None or an int: ``ValueError`` unless it is None or - an integer >= 1 given with ``causal=True`` and ``fit_timepoints``, and - for a model of a computed step that is named and known to have no - ``components_`` (a model given as an object is checked when it has been - fitted: ``model._refit``). + an integer >= 1 given with ``causal=True`` and ``fit_timepoints``. """ if refit_every is None: return None @@ -2458,15 +2451,6 @@ def _check_refit_every(refit_every, causal, fit_timepoints, analysis_rfun, f"rows, then again every {refit_every} rows, each time on all " "rows before); pass both, or leave refit_every out." ) - for name, reducers, orders in (("rfun", analysis_rfun, sorted(analysis_rfun)), - ("delta_rfun", feeding_rfun, fed)): - for k in orders: - label = reducers[k] - if isinstance(label, dict): - label = label.get("model") - if (isinstance(label, str) and _is_model(label) - and label not in _COMPONENT_MODELS): - raise ValueError(_no_components_message(label, name, k)) return int(refit_every) @@ -3018,11 +3002,19 @@ def features( ``t`` are replaced or removed, and a row ``t < n`` (in sample: the fits have read rows after it) when rows from ``n`` on are replaced or removed. ``n`` equal to the number of timepoints fits on every - row. A model must reduce rows it was not fitted on and reproduce - its training rows to 1e-9 (``"PCA"``, ``"IncrementalPCA"``, - ``"FactorAnalysis"``, ``"FastICA"``, ...; ``"MDS"``, ``"TSNE"``, - ``"SpectralEmbedding"`` and ``"LocallyLinearEmbedding"`` raise - ``ValueError``); ``"PCA"`` is fitted with ``svd_solver="full"`` + row. A model must be a linear map applied to each row by itself: + its fitted estimator has ``components_`` (``"PCA"``, + ``"IncrementalPCA"``, ``"TruncatedSVD"``, ``"FastICA"``, + ``"FactorAnalysis"``, ...), it reproduces its training rows to + 1e-9, and it reduces rows one at a time as it reduces them + together; any other model raises ``ValueError`` (``"UMAP"``, + ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, + ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the + transform of some of them depends on the rows it is given + together). A model asked for as many components as its input + has columns, or more, changes nothing (zero columns are appended + for the components beyond them), as without ``causal``. + ``"PCA"`` is fitted with ``svd_solver="full"`` unless a model dict gives a solver, because the randomized solver scikit-learn chooses for large inputs does not reproduce its rows. An output column of a model that is constant on the @@ -3070,9 +3062,7 @@ def features( largest sum of absolute cosines between component vectors; a component is negated when its cosine is negative), and the communities of ``Communities`` (the assignment with the most - shared nodes). Models need ``components_`` (``"PCA"``, - ``"IncrementalPCA"``, ``"FactorAnalysis"``, ``"FastICA"``, - ``"TruncatedSVD"``, ...); others raise ``ValueError``. The + shared nodes). The columns of ``WeightedStrength`` belong to the nodes and are not matched; with ``split=True`` a node that changes community changes which pairs its own and other columns sum. @@ -3185,10 +3175,9 @@ def features( when the first ``fit_timepoints`` rows hold no row with defined correlations for a fit (2 for a model), or fewer than 40 rows for the default feeding reducer or a shift null; for a model that - cannot reduce rows it was not fitted on; and for a - ``refit_every`` that is not None or an integer >= 1, that is - given without ``causal=True`` and ``fit_timepoints``, or given - with a model that has no ``components_``. + is not a linear map applied row by row (see ``fit_timepoints``); + and for a ``refit_every`` that is not None or an integer >= 1, + or that is given without ``causal=True`` and ``fit_timepoints``. TypeError If ``rfun`` or ``delta_rfun`` is not None, a string, a dict or a callable, or ``delta_weights_function`` is not None or callable. @@ -3499,8 +3488,7 @@ def features( S = len(subjects) fit_timepoints = _check_fit_timepoints(fit_timepoints, causal, T) - refit_every = _check_refit_every(refit_every, causal, fit_timepoints, - analysis_rfun, feeding_rfun, fed) + refit_every = _check_refit_every(refit_every, causal, fit_timepoints) if causal: _check_causal( function="features", include_timepoints=include_timepoints, diff --git a/timecorr/model.py b/timecorr/model.py index c7b11fe0..ff777d66 100644 --- a/timecorr/model.py +++ b/timecorr/model.py @@ -44,7 +44,6 @@ from .higher_order import ( _constant_columns, _fit_pass, - _no_components_message, _output_elements, _step_info, _two_path_step, @@ -211,16 +210,6 @@ def _single_fit(settings, subjects, events): _MATCH_RTOL = 1e-9 -def _components(fitted): - """``components_`` of a ``_FittedModel`` as a 2-D array, or None.""" - estimator = getattr(fitted.model, "model_", fitted.model) - components = getattr(estimator, "components_", None) - if components is None: - return None - components = np.asarray(components, dtype=np.float64) - return components if components.ndim == 2 else None - - def _assignment(score): """For each row of a square score matrix, the column of the one-to-one assignment with the largest total score.""" @@ -238,20 +227,21 @@ def _match_model(new, previous, order, path): |cosine| between component vectors), takes its place, and is negated when the cosine is negative; the columns frozen as constant (``constants``) follow, and the padding stays last. ``new`` itself - when nothing moves. ``_FitUnusable`` when the numbers of components or - of padded columns differ; ``ValueError`` when the reordered model does - not give the reordered outputs. + when nothing moves, and for the identity (a model with as many + components as columns). Every model of a causal fit has components + (``timecorr._fit_reducer``). ``_FitUnusable`` when the numbers of + components or of padded columns differ; ``ValueError`` when the + reordered model does not give the reordered outputs. """ - a, b = _components(new), _components(previous) - if a is None or b is None: - label = type(getattr(new.model, "model_", new.model)).__name__ - raise ValueError(_no_components_message( - label, "rfun" if path == "analysis" else "delta_rfun", order)) - if a.shape != b.shape or new.pad != previous.pad: + a, b = new.components, previous.components + if a is None and b is None and new.pad == previous.pad: + return new # the identity (no more columns than components) stays + if a is None or b is None or a.shape != b.shape or new.pad != previous.pad: + shapes = [None if c is None else c.shape[0] for c in (a, b)] raise _FitUnusable( - f"refit at order {order} ({path}): the model has {a.shape[0]} " + f"refit at order {order} ({path}): the model has {shapes[0]} " f"components and {new.pad} padded columns; the fit before " - f"{b.shape[0]} and {previous.pad}." + f"{shapes[1]} and {previous.pad}." ) c = a.shape[0] norms = np.linalg.norm(a, axis=1)[:, None] * np.linalg.norm(b, axis=1)[None, :] @@ -264,8 +254,8 @@ def _match_model(new, previous, order, path): signs = np.where(cosine[source, np.arange(c)] < 0, -1.0, 1.0) if np.array_equal(source, np.arange(c)) and np.all(signs > 0): return new - model = copy.deepcopy(new.model) - estimator = getattr(model, "model_", model) + matched = _FittedModel(new.model, new.n_features, new.pad) # a copy + estimator = matched.estimator fitted = np.asarray(estimator.components_) estimator.components_ = np.ascontiguousarray(signs[:, None] * fitted[source]) for name in _PER_COMPONENT: @@ -276,7 +266,8 @@ def _match_model(new, previous, order, path): if isinstance(value, np.ndarray) and value.ndim == 2 and value.shape[1] == c: setattr(estimator, _COLUMN_PER_COMPONENT, np.ascontiguousarray(value[:, source] * signs)) - matched = _FittedModel(model, new.n_features, new.pad) + # as a pickle restores it, like every fitted model (see _FittedModel) + matched = _FittedModel(matched.model, new.n_features, new.pad) if new.constants is not None: columns, means, tol = (np.array(v) for v in new.constants) real = columns < c @@ -431,12 +422,6 @@ def _refit(model, settings, subjects, single, events, return_delta, refit_every, returned, the rows of the fits and those whose fit was left out). """ steps = model._steps - for k, step in steps.items(): - for path, fitted in step.items(): - if isinstance(fitted, _FittedModel) and _components(fitted) is None: - label = type(getattr(fitted.model, "model_", fitted.model)).__name__ - raise ValueError(_no_components_message( - label, "rfun" if path == "analysis" else "delta_rfun", k)) n, T = settings["fit_timepoints"], subjects[0].shape[0] rows = [n] + list(range(n + refit_every, T, refit_every)) fit_settings = _refit_settings(settings, steps) diff --git a/timecorr/summaries.py b/timecorr/summaries.py index 5c97c862..79d39b51 100644 --- a/timecorr/summaries.py +++ b/timecorr/summaries.py @@ -1165,12 +1165,15 @@ class _FittedSummary: One fit of a summary, frozen (the causal mode of ``timecorr`` and ``features``): ``summary``, a copy of the summary that emits the output (the fallback of an automatic feeding step included) and ``fit``, its - record (as in ``fits_``). ``apply`` summarizes other correlations with - it; neither changes when the summary it came from is fitted again. + record (as in ``fits_``, its arrays copied). ``apply`` summarizes + other correlations with it; neither changes when the summary it came + from is fitted again or its records are changed. """ def __init__(self, summary, fit): - fit = dict(fit) + # a copy of every array: the summary's own record (``fits_``) is the + # caller's to change + fit = copy.deepcopy(dict(fit)) emitter = _auto_fallback() if fit.get("fallback") else copy.copy(summary) emitter.fits_ = [fit] self.summary = emitter diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 11b59a09..f26297a7 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -18,6 +18,7 @@ _GRAPH_MEASURES, _MIN_SAMPLES_RTOL, _SUMMARY_NAMES, + _COMPONENT_MODELS, _FittedModel, _FitUnusable, _is_model, @@ -319,30 +320,26 @@ def _defined_rows(arrays): return [~np.isnan(np.asarray(a)).all(axis=1) for a in arrays] -def _on_defined(arrays, f, width): +def _on_defined(arrays, f): """ ``f`` (a list of arrays in, a list of arrays out, row by row) applied to the rows of ``arrays`` that are not entirely NaN; the other rows stay - rows of NaN. ``width``: the number of output columns when no array has - such a row (None: found by reducing a row of zeros). + rows of NaN. Every array is passed, at its position, also one without + such a row (a fit that holds one unit per subject is applied to the + subject at each position). """ arrays = [np.asarray(a, dtype=np.float64) for a in arrays] defined = _defined_rows(arrays) - kept = [k for k, d in enumerate(defined) if d.any()] # every row is passed, the undefined ones as rows of zeros: a row is then # reduced at the same position of an array of the same shape whatever # the later rows hold, so replacing later rows (by NaN too) changes no # bit of it (the round-off of a matrix product can depend on its shape) - filled = [np.where(defined[k][:, None], arrays[k], 0.0) for k in kept] - reduced = f(filled) if kept else [] - if reduced: - width = np.asarray(reduced[0]).shape[1] - elif width is None: - # no row to reduce: the width of the reduction of a row of zeros - width = np.asarray(f([np.zeros((1, arrays[0].shape[1]))])[0]).shape[1] - out = [np.full((a.shape[0], width), np.nan) for a in arrays] - for k, r in zip(kept, reduced): - out[k][defined[k]] = np.asarray(r)[defined[k]] + reduced = f([np.where(d[:, None], a, 0.0) for a, d in zip(arrays, defined)]) + out = [] + for r, d in zip(reduced, defined): + r = np.array(r, dtype=np.float64) + r[~d] = np.nan + out.append(r) return out @@ -360,13 +357,20 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F A summary (object or name) gives a ``_FittedSummary`` (the object's ``fits_`` gains the fit, with ``order`` and ``path``; ``append_fit`` as - in ``higher_order._apply_reducer``), a model a ``helpers._FittedModel``; - None, a graph measure and a function of the user's are returned as they - are (nothing to fit). - - ``ValueError`` when the rows hold no defined row to fit (a model: fewer - than 2), and for a model that cannot reduce rows it was not fitted on - or does not reproduce its training rows (to ``_REFIT_ATOL``). + in ``higher_order._apply_reducer``), a model a ``helpers._FittedModel`` + (the identity when hypertools returns the rows as they are: no more + columns than components); None, a graph measure and a function of the + user's are returned as they are (nothing to fit). + + A model is taken only when its fitted estimator has ``components_`` (a + linear map), reproduces its training rows (to ``_REFIT_ATOL``) and + reduces a few of them to the same values one at a time and in another + batch: together these show that it reduces a row by itself. + + ``ValueError`` otherwise, and when the rows hold no defined row to fit + (a model: fewer than 2); ``helpers._FitUnusable``, a ``ValueError``, + for what can differ from one fit to the next (no defined row, a model + that does not reproduce its rows). """ from .summaries import _auto_emitter, _FittedSummary, _from_name, _Summary @@ -397,37 +401,102 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F del summary.fits_[:-1] return _FittedSummary(summary, fit) rfun = _exact_pca(rfun) + # one model for all subjects: those without a defined row add nothing + rows = [r for r in rows if len(r)] reduced, fitted = _model_reduce(rows, rfun, ndims, return_model=True) - label = rfun.get("model") if isinstance(rfun, dict) else rfun - label = getattr(label, "__name__", None) or str(label) + label = _model_label(rfun) + where = f"{name}{at}" + if fitted.model is None: + # hypertools fits no model to data with no more columns than the + # components asked for: it returns them as they are (and reduce + # appends its zero columns), which the identity does for any row + if all(np.array_equal(np.asarray(r)[:, :fitted.n_features], a) + for r, a in zip(reduced, rows)): + return fitted + raise _FitUnusable( + f"causal=True: the model {label!r} ({where}) cannot reduce rows it " + "was not fitted on (hypertools returned no fitted model), so it " + "cannot be fitted on the first rows and applied to later ones. " + + _LINEAR_MODELS + ) + if fitted.components is None: + raise ValueError(_not_linear_message(label, where)) try: - if fitted.model is None: - raise NotImplementedError("hypertools returned no fitted model") again = fitted.apply(rows) except (NotImplementedError, AttributeError, TypeError) as err: raise _FitUnusable( - f"causal=True: the model {label!r} ({name}{at}) cannot reduce rows it " + f"causal=True: the model {label!r} ({where}) cannot reduce rows it " f"was not fitted on ({err}), so it cannot be fitted on the first " - "rows and applied to later ones. Use a model with an out-of-sample " - "transform, such as 'PCA', 'IncrementalPCA' or 'FactorAnalysis'." + "rows and applied to later ones. " + _LINEAR_MODELS ) from err worst = max(float(np.max(np.abs(np.asarray(r) - a), initial=0.0)) for r, a in zip(reduced, again)) scale = max(1.0, max(float(np.max(np.abs(a), initial=0.0)) for a in again)) if not worst <= _REFIT_ATOL * scale: raise _FitUnusable( - f"causal=True: the model {label!r} ({name}{at}) does not reproduce " + f"causal=True: the model {label!r} ({where}) does not reproduce " f"the rows it was fitted on when it reduces them again (they differ " f"by up to {worst:.3g}), so the rows it is fitted on and later rows " - "would not be comparable. Use a model with an exact out-of-sample " - "transform, such as 'PCA', 'IncrementalPCA' or 'FactorAnalysis', " - "with an exact solver (a randomized one, as svd_solver='randomized' " - "of PCA, does not reproduce its rows)." + "would not be comparable. " + _LINEAR_MODELS + " Use an exact " + "solver (a randomized one, as svd_solver='randomized' of PCA, does " + "not reproduce its rows)." + ) + # each row alone, and in other company: the same output + few, batch = np.vstack(rows)[:4], np.vstack(again)[:4] + alone = np.vstack([fitted.apply([few[i:i + 1]])[0] for i in range(len(few))]) + turned = np.vstack(fitted.apply([few[1:], few[:1]])[::-1]) + worst = max(float(np.max(np.abs(other - batch), initial=0.0)) + for other in (alone, turned)) + if not worst <= _REFIT_ATOL * scale: + raise ValueError( + f"causal=True: the model {label!r} ({where}) does not reduce its " + "rows row by row: a row reduced alone or with other rows differs " + f"(by up to {worst:.3g}) from the row as reduced with the rows of " + "the fit, so a row would depend on the rows after it. " + + _LINEAR_MODELS ) fitted.freeze_constants(again) return fitted +# what the errors about a model in causal mode recommend +_LINEAR_MODELS = ( + "Use a model that is a linear map of the correlations of a row, with " + "components_: 'PCA', 'IncrementalPCA', 'TruncatedSVD', 'FastICA' or " + "'FactorAnalysis'; or a summary such as 'weighted_strength'." +) + + +def _model_label(rfun): + """The name of a model reducer (a name or a dict), for messages.""" + label = rfun.get("model") if isinstance(rfun, dict) else rfun + return getattr(label, "__name__", None) or str(label) + + +def _not_linear_message(label, where): + return ( + f"causal=True: the model {label!r} ({where}) has no components_ (it is " + "not a linear map of the correlations of a row), so nothing shows " + "that it reduces a row in the same way whatever rows come with it " + "(reproducing the rows it was fitted on does not: the transform of " + "'UMAP' depends on the number of rows it is given). " + _LINEAR_MODELS + ) + + +def _check_linear_model(rfun, where): + """ + ``ValueError`` for a model reducer named in ``rfun`` (a name or a dict + with one) that is known to have no ``components_``, before anything is + computed (``causal=True``; a model given as an object is checked when + it has been fitted: ``_fit_reducer``). + """ + if not _is_model(rfun): + return + label = rfun.get("model") if isinstance(rfun, dict) else rfun + if isinstance(label, str) and label not in _COMPONENT_MODELS: + raise ValueError(_not_linear_message(label, where)) + + def _exact_pca(rfun): """ ``"PCA"`` (a name, or a dict that gives no ``svd_solver``) with @@ -467,10 +536,7 @@ def _apply_frozen(corrs, frozen): K = frozen.fit["weights"][0].shape[0] if arrays and np.asarray(arrays[0]).shape[1] == K * (K + 1) // 2: frozen.check_units(len(arrays), K) - width = frozen.summary._n_columns(frozen.fit, K) - else: - width = None - out = _on_defined(arrays, frozen.apply, width) + out = _on_defined(arrays, frozen.apply) return out if isinstance(corrs, list) else out[0] @@ -522,6 +588,7 @@ def _causal_arguments(weights_function, weights_params, include_timepoints, cfun "starts), for example events=[100, 250]." ) _check_rfun(rfun) + _check_linear_model(rfun, "rfun") if _needs_fit(rfun) and fit_timepoints is None: raise ValueError( f"causal=True: rfun={rfun!r} is fitted to data and needs " @@ -788,11 +855,19 @@ def timecorr( unchanged (to 1e-9; bit for bit under replacement) when rows after ``t`` are replaced or removed, and a row ``t < n`` when rows from ``n`` on are. ``n`` equal to the number of timepoints fits on - every row. A model must reduce rows it was not fitted on and - reproduce its training rows to 1e-9 (``"PCA"``, - ``"IncrementalPCA"``, ``"FactorAnalysis"``, ...; ``"MDS"``, - ``"TSNE"``, ``"SpectralEmbedding"`` and - ``"LocallyLinearEmbedding"`` raise ``ValueError``); ``"PCA"`` is + every row. A model must be a linear map applied to each row by itself: + its fitted estimator has ``components_`` (``"PCA"``, + ``"IncrementalPCA"``, ``"TruncatedSVD"``, ``"FastICA"``, + ``"FactorAnalysis"``, ...), it reproduces its training rows to + 1e-9, and it reduces rows one at a time as it reduces them + together; any other model raises ``ValueError`` (``"UMAP"``, + ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, + ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the + transform of some of them depends on the rows it is given + together). A model asked for as many components as its input + has columns, or more, changes nothing (zero columns are appended + for the components beyond them), as without ``causal``. + ``"PCA"`` is fitted with ``svd_solver="full"`` unless a model dict gives a solver, because the randomized solver scikit-learn chooses for large inputs does not reproduce its rows. An output column of @@ -861,7 +936,8 @@ def timecorr( not an integer from 1 to the number of timepoints, or given without ``causal=True``; when the first ``fit_timepoints`` rows hold no row with defined correlations to fit (2 for a model); and - for a model that cannot reduce rows it was not fitted on. + for a model that is not a linear map applied row by row (see + ``fit_timepoints``). RuntimeError, ImportError As raised by ``segment`` for features entries of ``events``. From d47efd63943dea0e498901bb8603f0fba7ad1dbc Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 15:37:08 -0500 Subject: [PATCH 12/26] Causal mode tests: exhaustive grids behind the slow marker, a covering 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 108 ++++++++++++++++++++++++--------- tests/test_causal_features.py | 19 +++--- tests/test_causal_fit.py | 11 ++-- tests/test_causal_refit.py | 11 +++- 4 files changed, 105 insertions(+), 44 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 18b84b7b..3414ba6c 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -11,6 +11,7 @@ """ import functools +import itertools import re import warnings @@ -51,6 +52,63 @@ MODES = ("finite", "nan", "inf", "remove") +def _grid(*factors, pairs=True, keep=None): + """ + One ``pytest.param`` for every combination of the levels of ``factors`` + (lists, in the order of the test's arguments), for + ``pytest.mark.parametrize``. A covering subset runs in every selection: + with ``pairs``, every pair of levels of two factors is in one of its + combinations; without, every level of every factor. So do the + combinations for which ``keep(*levels)`` is true (those that have found + a defect). The others are marked ``slow``: the whole grid runs with + ``-m slow`` added, and no combination is left out. + + The subset is chosen greedily and deterministically: the combination + that adds the most uncovered pairs (or levels), then the one whose + levels were chosen least often, then the first in the order of + ``itertools.product``. + """ + size = 2 if pairs and len(factors) > 1 else 1 + places = list(itertools.combinations(range(len(factors)), size)) + combos = list(itertools.product(*[range(len(f)) for f in factors])) + covers = [{(p, tuple(c[i] for i in p)) for p in places} for c in combos] + missing = set().union(*covers) + used = [[0] * len(f) for f in factors] + chosen = set() + while missing: + best = max( + (j for j in range(len(combos)) if j not in chosen), + key=lambda j: (len(covers[j] & missing), + -sum(used[i][level] for i, level in enumerate(combos[j])))) + chosen.add(best) + missing -= covers[best] + for i, level in enumerate(combos[best]): + used[i][level] += 1 + params = [] + for j, c in enumerate(combos): + levels = [f[i] for f, i in zip(factors, c)] + fast = j in chosen or (keep is not None and keep(*levels)) + params.append(pytest.param(*levels, marks=() if fast else pytest.mark.slow)) + return params + + +def test_grid_keeps_every_combination_and_covers_every_pair(): + factors = (["a", "b", "c"], [True, False], [1, 2, 3, 4]) + for pairs in (True, False): + params = _grid(*factors, pairs=pairs, keep=lambda x, y, z: x == "c" and z == 4) + assert [p.values for p in params] == list(itertools.product(*factors)) + fast = [p.values for p in params if not p.marks] + assert all([m.name for m in p.marks] in ([], ["slow"]) for p in params) + assert 0 < len(fast) < len(params) + assert ("c", True, 4) in fast and ("c", False, 4) in fast + for i, j in ((0, 1), (0, 2), (1, 2)) if pairs else (): + assert ({(v[i], v[j]) for v in fast} + == set(itertools.product(factors[i], factors[j]))) + for i, f in enumerate(factors): + assert {v[i] for v in fast} == set(f) + assert len([p for p in _grid(*factors, pairs=False) if not p.marks]) == 4 + + def _quiet(f, *args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") @@ -117,10 +175,8 @@ def _max_difference(full, part, rows): # ---------------------------------------------------------------------------- -@pytest.mark.parametrize("mode", MODES) -@pytest.mark.parametrize("kernel", sorted(KERNELS)) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("case", sorted(CASES)) +@pytest.mark.parametrize("case,include_zero,kernel,mode", _grid( + sorted(CASES), [True, False], sorted(KERNELS), MODES)) def test_rows_do_not_depend_on_later_rows(case, include_zero, kernel, mode): data = _subjects(CASES[case][1]) full = _call(data, case, kernel, include_zero) @@ -134,10 +190,9 @@ def test_rows_do_not_depend_on_later_rows(case, include_zero, kernel, mode): assert defined > 0 # the comparison is not between NaN rows only -@pytest.mark.parametrize("mode", MODES) -@pytest.mark.parametrize("kernel", sorted(KERNELS)) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("case", ["autofc", "isfc-null", "wisfc-corrmean", "smooth"]) +@pytest.mark.parametrize("case,include_zero,kernel,mode", _grid( + ["autofc", "isfc-null", "wisfc-corrmean", "smooth"], [True, False], + sorted(KERNELS), MODES)) def test_rows_do_not_depend_on_later_rows_with_min_samples(case, include_zero, kernel, mode): min_samples = KERNELS[kernel][2] @@ -164,11 +219,9 @@ def test_rows_do_not_depend_on_later_rows_with_min_samples(case, include_zero, k equal_nan=True) -@pytest.mark.parametrize("missing", [0, 0.002]) -@pytest.mark.parametrize("mode", MODES) -@pytest.mark.parametrize("kernel", sorted(KERNELS)) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("case", ["autofc", "isfc-corrmean", "wisfc-null", "smooth"]) +@pytest.mark.parametrize("case,include_zero,kernel,mode,missing", _grid( + ["autofc", "isfc-corrmean", "wisfc-null", "smooth"], [True, False], + sorted(KERNELS), MODES, [0, 0.002])) def test_rows_do_not_depend_on_later_rows_with_few_missing_samples( case, include_zero, kernel, mode, missing): # without NaN samples (and with NaN samples in some chunks of kernel rows @@ -186,9 +239,8 @@ def test_rows_do_not_depend_on_later_rows_with_few_missing_samples( assert not np.isnan(np.asarray(_as_list(full)[0])[20:]).any() -@pytest.mark.parametrize("mode", ["finite", "nan", "inf"]) -@pytest.mark.parametrize("kernel", sorted(KERNELS)) -@pytest.mark.parametrize("case", sorted(CASES)) +@pytest.mark.parametrize("case,kernel,mode", _grid( + sorted(CASES), sorted(KERNELS), ["finite", "nan", "inf"])) def test_without_the_diagonal_row_t_does_not_depend_on_row_t(case, kernel, mode): data = _subjects(CASES[case][1]) full = _call(data, case, kernel, include_zero=False) @@ -200,9 +252,8 @@ def test_without_the_diagonal_row_t_does_not_depend_on_row_t(case, kernel, mode) assert _max_difference(full, part, n + 1) <= ATOL -@pytest.mark.parametrize("kernel", sorted(KERNELS)) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("case", sorted(CASES)) +@pytest.mark.parametrize("case,include_zero,kernel", _grid( + sorted(CASES), [True, False], sorted(KERNELS))) def test_replacing_later_rows_with_finite_values_changes_no_bit(case, include_zero, kernel): data = _subjects(CASES[case][1]) @@ -937,12 +988,14 @@ def test_a_later_nan_does_not_change_an_ill_conditioned_row(): _quiet(tc.timecorr, y, **kw)[:41], equal_nan=True) -@pytest.mark.parametrize("mode", MODES) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("where", [0, 60, 150]) -@pytest.mark.parametrize("case", ["autofc", "isfc-null", "wisfc-corrmean", "smooth"]) -@pytest.mark.parametrize("missing", [False, True]) -@pytest.mark.parametrize("step", [1e4, 1e8]) +# (the cases that showed the defects, a step of 1e4 at the first row and +# mid-series under every perturbation, with and without the diagonal, run in +# every selection) +@pytest.mark.parametrize("case,where,include_zero,mode,missing,step", _grid( + ["autofc", "isfc-null", "wisfc-corrmean", "smooth"], [0, 60, 150], [True, False], + MODES, [False, True], [1e4, 1e8], + keep=lambda case, where, include_zero, mode, missing, step: ( + step == 1e4 and not missing and case in ("autofc", "smooth")))) def test_rows_of_a_level_step_do_not_depend_on_later_rows(case, where, include_zero, mode, missing, step): data = [_level_step(where, seed=s, n=T, K=4, step=step) @@ -967,9 +1020,8 @@ def test_rows_of_a_level_step_do_not_depend_on_later_rows(case, where, include_z equal_nan=True) -@pytest.mark.parametrize("kernel", sorted(KERNELS)) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("case", sorted(CASES)) +@pytest.mark.parametrize("case,include_zero,kernel", _grid( + sorted(CASES), [True, False], sorted(KERNELS))) def test_replacing_later_rows_with_nan_or_inf_changes_no_bit(case, include_zero, kernel): data = _subjects(CASES[case][1]) full = _call(data, case, kernel, include_zero) diff --git a/tests/test_causal_features.py b/tests/test_causal_features.py index 9b92d749..4c75c484 100644 --- a/tests/test_causal_features.py +++ b/tests/test_causal_features.py @@ -24,6 +24,7 @@ SUBJECT_WEIGHTS, _as_list, _expected_undefined, + _grid, _max_difference, _perturb, _quiet, @@ -261,9 +262,9 @@ def _defined_rows(out): return int(np.sum(~np.isnan(np.asarray(_as_list(out)[0])).all(axis=1))) -@pytest.mark.parametrize("mode", MODES) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("config", sorted(CONFIGS)) +@pytest.mark.parametrize("config,include_zero,mode", _grid( + sorted(CONFIGS), [True, False], MODES, pairs=False, + keep=lambda config, include_zero, mode: config == "strength")) def test_rows_do_not_depend_on_later_rows(config, include_zero, mode): data = _data(config) highest = CONFIGS[config][2] @@ -282,10 +283,10 @@ def test_rows_do_not_depend_on_later_rows(config, include_zero, mode): assert _worst(full, part, rows, orders) <= atol -@pytest.mark.parametrize("mode", ["finite", "nan", "inf"]) -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("config", ["unreduced", "strength", "eigenvector", "isfc", - "wisfc", "events", "min-samples"]) +@pytest.mark.parametrize("config,include_zero,mode", _grid( + ["unreduced", "strength", "eigenvector", "isfc", "wisfc", "events", "min-samples"], + [True, False], ["finite", "nan", "inf"], pairs=False, + keep=lambda config, include_zero, mode: config == "strength")) def test_replacing_later_rows_changes_no_bit(config, include_zero, mode): data = _data(config, seed=20) full = _run(data, config, include_zero=include_zero) @@ -300,8 +301,7 @@ def test_replacing_later_rows_changes_no_bit(config, include_zero, mode): assert np.array_equal(a[:rows], b[:rows], equal_nan=True) -@pytest.mark.parametrize("mode", MODES) -@pytest.mark.parametrize("include_zero", [True, False]) +@pytest.mark.parametrize("include_zero,mode", _grid([True, False], MODES, pairs=False)) def test_order_four_unreduced(include_zero, mode): # 3 features: 6, 21, 231 and 26,796 columns at orders 1 to 4 n = 150 @@ -769,6 +769,7 @@ def test_default_is_not_causal(): # ---------------------------------------------------------------------------- +@pytest.mark.slow def test_order_three_of_5033_by_49_takes_seconds(): x = np.random.default_rng(0).standard_normal((5033, 49)) kw = dict(order=3, rfun="strength", delta_rfun="strength", diff --git a/tests/test_causal_fit.py b/tests/test_causal_fit.py index 48811af4..96f25830 100644 --- a/tests/test_causal_fit.py +++ b/tests/test_causal_fit.py @@ -26,6 +26,7 @@ from .test_causal_estimator import ( _as_list, + _grid, _max_difference, _perturb, _quiet, @@ -150,7 +151,10 @@ def _same_fits(a, b): # the guarantee # ---------------------------------------------------------------------------- -CASES = [(c, True) for c in sorted(CONFIGS)] + [(c, False) for c in WITHOUT_ZERO] +# every configuration runs in every selection, those of WITHOUT_ZERO without +# the diagonal; with it they are slow (other configurations have the diagonal) +CASES = [pytest.param(c, True, marks=pytest.mark.slow if c in WITHOUT_ZERO else ()) + for c in sorted(CONFIGS)] + [(c, False) for c in WITHOUT_ZERO] @pytest.mark.parametrize("config,include_zero", CASES) @@ -609,9 +613,8 @@ def test_two_path_step_fits_on_the_first_rows(): } -@pytest.mark.parametrize("include_zero", [True, False]) -@pytest.mark.parametrize("reducer", sorted(TIMECORR_REDUCERS)) -@pytest.mark.parametrize("subjects", [1, 3]) +@pytest.mark.parametrize("subjects,reducer,include_zero", _grid( + [1, 3], sorted(TIMECORR_REDUCERS), [True, False])) def test_timecorr_fits_its_reducer_on_the_first_rows(subjects, reducer, include_zero): data = [_series(70 + s, n=T, K=5) for s in range(subjects)] data = data[0] if subjects == 1 else data diff --git a/tests/test_causal_refit.py b/tests/test_causal_refit.py index 25c17f6e..eec24dfc 100644 --- a/tests/test_causal_refit.py +++ b/tests/test_causal_refit.py @@ -57,9 +57,14 @@ } # no rule changes a fit: nothing is matched, no structure is carried over EXACT = ["strength", "strength-isfc", "split", "mixed"] -GUARANTEED = [("auto", True), ("auto", False), ("auto-isfc", True), - ("pca", True), ("pca", False), ("pca-subjects", True), - ("strength", True), ("strength", False), ("strength-isfc", False)] +# (every configuration, and both values of include_zero, run in every +# selection; the second value of three configurations is slow) +_SLOW = pytest.mark.slow +GUARANTEED = [pytest.param("auto", True, marks=_SLOW), ("auto", False), + ("auto-isfc", True), ("pca", True), + pytest.param("pca", False, marks=_SLOW), ("pca-subjects", True), + pytest.param("strength", True, marks=_SLOW), ("strength", False), + ("strength-isfc", False)] def _data(config, seed=0, n=T): From b3a2de73da2ca541da86e0230c1f1088a490c1f8 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 15:49:25 -0500 Subject: [PATCH 13/26] Version 0.4.0; hypertools floor 1.1 (reduce is called with random_state=, 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- README.md | 2 +- docs/conf.py | 4 +- requirements.txt | 2 +- setup.py | 4 +- tests/test_packaging.py | 95 +++++++++++++++++++++++++++++++++++++++++ timecorr/__init__.py | 2 +- 6 files changed, 102 insertions(+), 7 deletions(-) create mode 100644 tests/test_packaging.py diff --git a/README.md b/README.md index 2fd1c0c6..7da09776 100644 --- a/README.md +++ b/README.md @@ -213,7 +213,7 @@ pip install --upgrade git+https://github.com/ContextLab/timecorr.git Python 3.10 or later. The toolbox is currently supported on Mac and Linux. It has not been tested on Windows (and we expect key functionality not to work properly on Windows systems). -Dependencies (installed by pip): pydata-wrangler, hypertools>=0.8, numpy, scipy, scikit-learn, pandas, matplotlib. Optional: polars (for polars DataFrame input); hmmlearn, used only by `tc.segment`, which installs it on demand the first time it is needed (the `segment` extra, `pip install "timecorr[segment]"`; setting `TIMECORR_AUTO_INSTALL=0` turns automatic installation off); and the `test`, `docs` (building the documentation) and `tutorials` (what the real-data tutorial notebooks import) extras (`pip install "timecorr[test]"`, `pip install "timecorr[docs]"`, `pip install "timecorr[tutorials]"`). +Dependencies (installed by pip): pydata-wrangler, hypertools>=1.1, numpy, scipy, scikit-learn, pandas, matplotlib. Optional: polars (for polars DataFrame input); hmmlearn, used only by `tc.segment`, which installs it on demand the first time it is needed (the `segment` extra, `pip install "timecorr[segment]"`; setting `TIMECORR_AUTO_INSTALL=0` turns automatic installation off); and the `test`, `docs` (building the documentation) and `tutorials` (what the real-data tutorial notebooks import) extras (`pip install "timecorr[test]"`, `pip install "timecorr[docs]"`, `pip install "timecorr[tutorials]"`). # Citing this toolbox diff --git a/docs/conf.py b/docs/conf.py index 27a61bc2..bd519fa6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -79,9 +79,9 @@ # built documents. # # The short X.Y version. -version = "0.3" +version = "0.4" # The full version, including alpha/beta/rc tags. -release = "0.3.1" +release = "0.4.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/requirements.txt b/requirements.txt index 0d57e687..c7cf60fd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ pydata-wrangler -hypertools>=0.8 +hypertools>=1.1 numpy scipy scikit-learn diff --git a/setup.py b/setup.py index ca746bdb..b4822bf2 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,7 @@ setup( name="timecorr", - version="0.3.1", + version="0.4.0", description="Compute dynamic correlations, dynamic higher-order correlations, and dynamic graph theoretic measures in timeseries data", long_description=readme, long_description_content_type="text/markdown", @@ -24,7 +24,7 @@ python_requires=">=3.10", install_requires=[ "pydata-wrangler", - "hypertools>=0.8", + "hypertools>=1.1", "numpy", "scipy", "scikit-learn", diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 00000000..f5433815 --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,95 @@ +""" +The declared dependencies allow only versions the package runs with. + +``timecorr.helpers.reduce`` calls ``hypertools.reduce(..., random_state=0)``, +and the causal mode fits models with ``return_model=True`` and applies them +with ``model=``. hypertools 0.8 has none of these arguments (the default +``tc.features`` call raised ``TypeError: reduce() got an unexpected keyword +argument 'random_state'`` there), so the declared floor must exclude it. + +These tests read the real setup.py and requirements.txt and the installed +hypertools; nothing is mocked. +""" + +import ast +import inspect +import os + +import hypertools +import pytest +from packaging.requirements import Requirement +from packaging.version import Version + +ROOT = os.path.dirname(os.path.dirname(__file__)) +FLOOR = Version("1.1") + + +def _setup_keyword(name): + """The literal value of a keyword of the ``setup(...)`` call in setup.py.""" + with open(os.path.join(ROOT, "setup.py"), encoding="utf-8") as f: + tree = ast.parse(f.read()) + calls = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "setup" + ] + assert len(calls) == 1, "setup.py needs exactly one setup(...) call" + values = [k.value for k in calls[0].keywords if k.arg == name] + assert len(values) == 1, f"setup.py: no {name}= keyword" + return ast.literal_eval(values[0]) + + +def _requirements_txt(): + with open(os.path.join(ROOT, "requirements.txt"), encoding="utf-8") as f: + lines = [line.split("#")[0].strip() for line in f] + return [line for line in lines if line] + + +def _hypertools_floor(requirements, where): + """The lowest hypertools version that a list of requirement strings allows.""" + found = [r for r in map(Requirement, requirements) if r.name == "hypertools"] + assert len(found) == 1, f"{where}: {len(found)} hypertools requirements" + floors = [ + Version(s.version) for s in found[0].specifier if s.operator in (">=", "==", "~=") + ] + assert floors, f"{where}: hypertools has no lower bound ({found[0]})" + return max(floors) + + +@pytest.mark.parametrize( + "where,requirements", + [ + ("setup.py install_requires", _setup_keyword("install_requires")), + ("requirements.txt", _requirements_txt()), + ("setup.py extras_require['tutorials']", _setup_keyword("extras_require")["tutorials"]), + ], + ids=["install_requires", "requirements.txt", "tutorials-extra"], +) +def test_hypertools_floor_is_at_least_1_1(where, requirements): + assert _hypertools_floor(requirements, where) >= FLOOR, where + + +def test_the_floor_excludes_the_versions_without_the_arguments_used(): + # the specifier of install_requires rejects 0.8.x and 1.0.x and accepts 1.1.0 + requirement = [ + r + for r in map(Requirement, _setup_keyword("install_requires")) + if r.name == "hypertools" + ][0] + for version in ("0.8.0", "0.8.2", "1.0.0"): + assert not requirement.specifier.contains(version), version + assert requirement.specifier.contains("1.1.0") + + +def test_installed_hypertools_meets_the_floor_and_has_the_arguments(): + assert Version(hypertools.__version__) >= FLOOR, hypertools.__version__ + parameters = inspect.signature(hypertools.reduce).parameters + for name in ("random_state", "return_model", "model"): + assert name in parameters, f"hypertools.reduce has no {name}=" + + +def test_install_requires_and_requirements_txt_agree(): + def norm(requirements): + return sorted(str(Requirement(r)) for r in requirements) + + assert norm(_setup_keyword("install_requires")) == norm(_requirements_txt()) diff --git a/timecorr/__init__.py b/timecorr/__init__.py index 12554b51..673d6403 100644 --- a/timecorr/__init__.py +++ b/timecorr/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -__version__ = "0.3.1" +__version__ = "0.4.0" from . import datasets from .helpers import ( From 8a0c711eee6238571606667bf3fc7a23df0f25c2 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 15:57:19 -0500 Subject: [PATCH 14/26] Causal mode: the guarantee names its models; smoothing is centered per 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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_causal_estimator.py | 31 +++++++- tests/test_causal_fit.py | 96 +++++++++++++++++++++++- timecorr/higher_order.py | 73 ++++++++++++------ timecorr/model.py | 9 ++- timecorr/timecorr.py | 131 ++++++++++++++++++++++++++++----- 5 files changed, 294 insertions(+), 46 deletions(-) diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 3414ba6c..f47eef04 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -353,6 +353,34 @@ def test_smoothing_agrees_with_the_backward_kernel_of_causal_false(): assert np.max(np.abs(causal[defined] - plain[defined])) <= 1e-12 +def test_smoothed_values_agree_to_round_off_of_the_magnitude_of_the_data(): + # smoothing returns values on the scale of the data: at a level of 1e8 + # (values spaced 1.5e-8 apart) an absolute 1e-9 cannot hold. Each chunk + # of rows is centered on a mean of earlier samples, so the sums are + # exact to the round-off of the variation: removal changed these rows by + # 2 units in the last place before, and changes them by at most 1 now + x = np.random.default_rng(0).normal(size=(300, 2)) + 1e8 + kw = dict(causal=True, cfun=None, weights_params={"var": 25}) + full = _quiet(tc.timecorr, x, **kw) + assert np.spacing(1e8) > ATOL + for n in (1, 2, 3, 40, 61, 127, 128, 129, 200, 257, 299): + assert _max_difference(full, _quiet(tc.timecorr, x[:n], **kw), n) <= np.spacing(1e8) + rng = np.random.default_rng(1) + for mode in ("finite", "nan", "inf"): + for n in (61, 128, 200): + part = _quiet(tc.timecorr, _perturb(x, n, mode, rng), **kw) + assert np.array_equal(full[:n], part[:n], equal_nan=True) + # the smoothed variation is that of the series without its level + plain = _quiet(tc.timecorr, x - 1e8, **kw) + assert np.nanmax(np.abs((full - 1e8) - plain)) <= np.spacing(1e8) + # what the documentation of ``causal`` states is what the tests allow + # (test_rows_of_a_level_step_do_not_depend_on_later_rows: 8 units) + doc = " ".join(tc.timecorr.__doc__.split()) + assert ("to 1e-9 or 8 units in the last place of the largest magnitude of the " + "data, whichever is larger") in doc + assert 8 * np.spacing(1e8) < 1.2e-7 + + def test_default_is_not_causal(): x = np.random.default_rng(2).standard_normal((80, 4)) kw = dict(cfun=tc.autofc, weights_params={"var": 20}) @@ -1010,7 +1038,8 @@ def test_rows_of_a_level_step_do_not_depend_on_later_rows(case, where, include_z include_zero) rows = n if include_zero or mode == "remove" else n + 1 if mode == "remove": - # (smoothed values are as large as the step: a few of their ulps) + # (smoothed values are as large as the step: a few of their + # ulps, the bound that the documentation of ``causal`` states) atol = max(ATOL, 8 * np.spacing(step)) if case == "smooth" else ATOL assert _max_difference(full, part, rows) <= atol else: diff --git a/tests/test_causal_fit.py b/tests/test_causal_fit.py index 96f25830..a9404bad 100644 --- a/tests/test_causal_fit.py +++ b/tests/test_causal_fit.py @@ -13,6 +13,7 @@ import inspect import pickle +import re import subprocess import sys import warnings @@ -803,7 +804,100 @@ def transform(self, X): rfun={"model": BatchCentered}).shape == (100, 4) -@pytest.mark.parametrize("model", LINEAR) +GUARANTEED_MODELS = LINEAR + ["FactorAnalysis"] +NOT_COVERED = "causal=True: the model .* is not one of the models the guarantee covers" +SOME_NOT_COVERED = "causal=True: the models .* not among the models the guarantee covers" + + +def _model_warnings(f, *args, **kwargs): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + out = f(*args, **kwargs) + return out, [str(w.message) for w in caught + if "the models the guarantee covers" in str(w.message)] + + +def test_a_model_outside_the_list_runs_with_one_warning(): + from sklearn.decomposition import PCA + + class BatchPCA(PCA): + """Passes every probe of the fit (they reduce training rows only) + and reads the rows it is given together when there are more.""" + + def transform(self, X): + out = super().transform(X) + if len(X) > self.n_samples_: + out -= out.mean(axis=0) + return out + + class SamePCA(PCA): + """A subclass that changes nothing is still not the listed class.""" + + x = np.random.default_rng(61).standard_normal((100, 4)) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=40, + weights_params={"var": 25}) + listed = ("PCA, IncrementalPCA, TruncatedSVD, FastICA and FactorAnalysis") + for model in (BatchPCA, SamePCA, "MiniBatchDictionaryLearning"): + out, messages = _model_warnings(tc.timecorr, x, rfun={"model": model}, **kw) + # (rows of BatchPCA may depend on later rows: that is what the + # warning says, and nothing is asserted about them) + assert out.shape == (100, 4) + assert len(messages) == 1 + assert re.search(NOT_COVERED, messages[0]) and listed in messages[0] + assert getattr(model, "__name__", model) in messages[0] + assert "rfun" in messages[0] + # a model of another name that cannot reduce one row alone: no probe + # shows that it reduces rows one by one + with pytest.raises(ValueError, match="'SparsePCA'.*row by row.*one row alone"): + _quiet(tc.timecorr, x, rfun="SparsePCA", **kw) + # features and two_path_step: once for the call, whatever the number of + # orders, paths and fits + more = dict(delta_weights_params={"var": 16}, ndims=2, **kw) + # (a refit cannot match the components of BatchPCA to the fit before; + # those of SamePCA, a class that cannot be pickled, it reorders in a copy) + for first, extra in ((BatchPCA, {}), (SamePCA, {}), (SamePCA, {"refit_every": 20})): + out, messages = _model_warnings( + tc.features, x, order=2, rfun={"model": first}, + delta_rfun={"model": SamePCA}, **more, **extra) + assert out[2].shape == (100, 2) + assert len(messages) == 1 + assert re.search(SOME_NOT_COVERED if first is BatchPCA else NOT_COVERED, + messages[0]) + for name in (first.__name__, "SamePCA", "rfun at order 1", + "delta_rfun at order 2"): + assert name in messages[0] + out, messages = _model_warnings( + two_path_step, x, rfun="PCA", delta_rfun={"model": BatchPCA}, **more) + assert len(messages) == 1 and "delta_rfun" in messages[0] + assert "(rfun" not in messages[0] + # without causal: no warning + assert _model_warnings(tc.timecorr, x, cfun=tc.autofc, + rfun={"model": BatchPCA})[1] == [] + + +@pytest.mark.parametrize("model", GUARANTEED_MODELS) +def test_the_listed_models_do_not_warn(model): + import sklearn.decomposition + + cls = getattr(sklearn.decomposition, model) + x = np.random.default_rng(65).standard_normal((100, 4)) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=40, + weights_params={"var": 25}) + for rfun in (model, {"model": model}, {"model": cls}): + assert _model_warnings(tc.timecorr, x, rfun=rfun, **kw)[1] == [] + (out, fitted), messages = _model_warnings( + tc.features, x, order=2, rfun=model, delta_rfun={"model": model}, ndims=3, + delta_weights_params={"var": 16}, refit_every=30, return_model=True, **kw) + assert messages == [] + # the list is of exact classes: what hypertools fits for these names + assert type(fitted.fits[(1, "analysis")].model_) is cls + for name in ("timecorr", "features", "two_path_step"): + doc = {"timecorr": tc.timecorr, "features": tc.features, + "two_path_step": two_path_step}[name].__doc__ + assert f'``"{model}"``' in doc + + +@pytest.mark.parametrize("model", GUARANTEED_MODELS) def test_linear_models_are_taken_and_guaranteed(model): x = np.random.default_rng(62).standard_normal((T, 5)) kw = dict(order=2, causal=True, cfun=tc.autofc, rfun=model, delta_rfun=model, diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index c1c0dd76..083e8ffb 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -119,6 +119,8 @@ _needs_fit, _restricted, _shaped_kernel, + _uncovered_model, + _warn_uncovered_models, timecorr, ) @@ -1817,7 +1819,10 @@ def two_path_step( linear models such as PCA once fitted); the eigenvector-based graph measures (``"eigenvector_centrality"``, the PageRank measures) can differ by more at a correlation matrix whose leading - eigenvalues coincide. Default: False. With ``causal=True``: + eigenvalues coincide. With ``cfun=None`` the steps smooth their + input, and smoothed values agree to round-off relative to the + magnitude of the data (see ``timecorr``). Default: False. With + ``causal=True``: - both paths use backward kernels (``include_timepoints`` may be left out; ``"forward"``/``"post"`` raises ``ValueError``), and @@ -1838,7 +1843,8 @@ def two_path_step( ``"pagerank_centrality_abs"``) need no fit. A function of your own (as ``cfun``, ``rfun`` or ``delta_rfun``) is called as without ``causal``, with one ``UserWarning`` that the guarantee - does not cover what it does; + does not cover what it does; so is a model outside the list + under ``fit_timepoints``, with one ``UserWarning`` of its own; - ``cfun=tc.wisfc`` raises ``ValueError`` (its default subject weights use the whole recording); ``functools.partial(tc.wisfc, subject_weights=...)`` is accepted; @@ -1889,16 +1895,21 @@ def two_path_step( ``t`` are replaced or removed, and a row ``t < n`` (in sample: the fits have read rows after it) when rows from ``n`` on are replaced or removed. ``n`` equal to the number of timepoints fits on every - row. A model must be a linear map applied to each row by itself: - its fitted estimator has ``components_`` (``"PCA"``, - ``"IncrementalPCA"``, ``"TruncatedSVD"``, ``"FastICA"``, - ``"FactorAnalysis"``, ...), it reproduces its training rows to - 1e-9, and it reduces rows one at a time as it reduces them - together; any other model raises ``ValueError`` (``"UMAP"``, - ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, - ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the - transform of some of them depends on the rows it is given - together). A model asked for as many components as its input + row. 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 + (``"MiniBatchDictionaryLearning"``, a class of your own) is used with + one ``UserWarning`` per call that the guarantee does not cover what its + transform does: those checks read a few training rows and cannot show + how it reduces later rows. A model without ``components_``, or that + fails a check, raises ``ValueError`` (``"UMAP"``, ``"KernelPCA"``, + ``"Isomap"``, ``"MDS"``, ``"TSNE"``, ``"SpectralEmbedding"``, + ``"LocallyLinearEmbedding"``: the transform of some of them depends on + the rows it is given together). + A model asked for as many components as its input has columns, or more, changes nothing (zero columns are appended for the components beyond them), as without ``causal``. ``"PCA"`` is fitted with ``svd_solver="full"`` @@ -2426,6 +2437,11 @@ def _check_causal(*, function, include_timepoints, weights_function, "own; the guarantee that row t does not depend on later rows does " f"not cover what {'it does' if one else 'they do'}." ) + _warn_uncovered_models([ + (_uncovered_model(resolved[k]), f"{name} at order {k}") + for name, resolved in (("rfun", analysis_rfun), ("delta_rfun", feeding_rfun)) + for k in sorted(resolved) + ]) def _check_refit_every(refit_every, causal, fit_timepoints): @@ -2930,7 +2946,10 @@ def features( linear models such as PCA once fitted); the eigenvector-based graph measures (``"eigenvector_centrality"``, the PageRank measures) can differ by more at a correlation matrix whose leading - eigenvalues coincide. Default: False. With ``causal=True``: + eigenvalues coincide. With ``cfun=None`` the steps smooth their + input, and smoothed values agree to round-off relative to the + magnitude of the data (see ``timecorr``). Default: False. With + ``causal=True``: - both paths use backward kernels (``include_timepoints`` may be left out; ``"forward"``/``"post"`` raises ``ValueError``), and @@ -2951,7 +2970,8 @@ def features( ``"pagerank_centrality_abs"``) need no fit. A function of your own (as ``cfun``, ``rfun`` or ``delta_rfun``) is called as without ``causal``, with one ``UserWarning`` that the guarantee - does not cover what it does; + does not cover what it does; so is a model outside the list + under ``fit_timepoints``, with one ``UserWarning`` of its own; - ``cfun=tc.wisfc`` raises ``ValueError`` (its default subject weights use the whole recording); ``functools.partial(tc.wisfc, subject_weights=...)`` is accepted; @@ -3002,16 +3022,21 @@ def features( ``t`` are replaced or removed, and a row ``t < n`` (in sample: the fits have read rows after it) when rows from ``n`` on are replaced or removed. ``n`` equal to the number of timepoints fits on every - row. A model must be a linear map applied to each row by itself: - its fitted estimator has ``components_`` (``"PCA"``, - ``"IncrementalPCA"``, ``"TruncatedSVD"``, ``"FastICA"``, - ``"FactorAnalysis"``, ...), it reproduces its training rows to - 1e-9, and it reduces rows one at a time as it reduces them - together; any other model raises ``ValueError`` (``"UMAP"``, - ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, - ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the - transform of some of them depends on the rows it is given - together). A model asked for as many components as its input + row. 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 + (``"MiniBatchDictionaryLearning"``, a class of your own) is used with + one ``UserWarning`` per call that the guarantee does not cover what its + transform does: those checks read a few training rows and cannot show + how it reduces later rows. A model without ``components_``, or that + fails a check, raises ``ValueError`` (``"UMAP"``, ``"KernelPCA"``, + ``"Isomap"``, ``"MDS"``, ``"TSNE"``, ``"SpectralEmbedding"``, + ``"LocallyLinearEmbedding"``: the transform of some of them depends on + the rows it is given together). + A model asked for as many components as its input has columns, or more, changes nothing (zero columns are appended for the components beyond them), as without ``causal``. ``"PCA"`` is fitted with ``svd_solver="full"`` diff --git a/timecorr/model.py b/timecorr/model.py index ff777d66..1a4ed098 100644 --- a/timecorr/model.py +++ b/timecorr/model.py @@ -255,6 +255,10 @@ def _match_model(new, previous, order, path): if np.array_equal(source, np.arange(c)) and np.all(signs > 0): return new matched = _FittedModel(new.model, new.n_features, new.pad) # a copy + if matched.model is new.model: + # (a model that cannot be pickled, as one of a class defined in a + # function, was taken as it is: reorder a copy, not the fit itself) + matched.model = copy.deepcopy(new.model) estimator = matched.estimator fitted = np.asarray(estimator.components_) estimator.components_ = np.ascontiguousarray(signs[:, None] * fitted[source]) @@ -669,8 +673,9 @@ def transform(self, data, return_delta=False, return_info=False, *, events=None) Every row is computed causally, as by the ``features`` call that made the model: row ``t`` of every output uses rows ``0..t`` of - ``data`` and the frozen fits only, so it is unchanged (to 1e-9; see - ``features``) when later rows are replaced or removed, and + ``data`` and the frozen fits only, so it is unchanged (to 1e-9 for + features built from correlations; see ``features``) when later rows + are replaced or removed, and ``transform`` of the data of the fit returns what that call returned. diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index f26297a7..b8cae4e8 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -51,7 +51,11 @@ def _causal_smooth(x, weights, min_samples): """ ``_kernel_smooth`` for ``causal=True``: the same kernel-weighted means of a kernel without weight on later timepoints, each chunk of rows over the - columns where it has weight. Infinite samples and samples above 1e150 + columns where it has weight. The samples of a chunk are centered on the + weighted mean of its first row (which weights no later sample) and the + mean is added back, so the round-off of the sums is relative to the + variation of the data in the chunk, not to its level; the values + themselves are still rounded at their own magnitude. Infinite samples and samples above 1e150 in magnitude are missing, like NaN. An entry whose feature has no weighted sample or, with ``min_samples`` (not None), an effective sample size ``(sum |w|)**2 / sum w**2`` (over the feature's observed samples in @@ -74,13 +78,22 @@ def _causal_smooth(x, weights, min_samples): with np.errstate(invalid="ignore"): w = np.divide(w, peak, out=np.zeros_like(w), where=peak != 0) den = w @ valid[c0:c1] - num = w @ observed[c0:c1] defined = den > 0 + # the chunk's samples are centered on its first row's weighted + # mean (of samples that row weights: none after it), so the + # round-off of the sums is relative to the variation of the + # data, not to its level + first = np.zeros(den.shape[1]) + np.divide(w[0] @ observed[c0:c1], den[0], out=first, where=defined[0]) + centered = observed[c0:c1] - first + centered *= valid[c0:c1] + num = w @ centered if min_samples is not None: ess = np.divide(den**2, (w * w) @ valid[c0:c1], out=np.zeros_like(den), where=defined) defined &= ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) np.divide(num, den, out=out[t0:t1], where=defined) + out[t0:t1] += first undefined = np.isnan(out).any(axis=1) if undefined.any(): warnings.warn( @@ -443,8 +456,16 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F ) # each row alone, and in other company: the same output few, batch = np.vstack(rows)[:4], np.vstack(again)[:4] - alone = np.vstack([fitted.apply([few[i:i + 1]])[0] for i in range(len(few))]) - turned = np.vstack(fitted.apply([few[1:], few[:1]])[::-1]) + try: + alone = np.vstack([fitted.apply([few[i:i + 1]])[0] for i in range(len(few))]) + turned = np.vstack(fitted.apply([few[1:], few[:1]])[::-1]) + except Exception as err: + raise ValueError( + f"causal=True: the model {label!r} ({where}) does not reduce its " + f"rows row by row: it cannot reduce one row alone ({err}), so " + "nothing shows that a row does not depend on the rows after it. " + + _LINEAR_MODELS + ) from err worst = max(float(np.max(np.abs(other - batch), initial=0.0)) for other in (alone, turned)) if not worst <= _REFIT_ATOL * scale: @@ -463,10 +484,72 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F _LINEAR_MODELS = ( "Use a model that is a linear map of the correlations of a row, with " "components_: 'PCA', 'IncrementalPCA', 'TruncatedSVD', 'FastICA' or " - "'FactorAnalysis'; or a summary such as 'weighted_strength'." + "'FactorAnalysis' (the models the guarantee covers); or a summary such " + "as 'weighted_strength'." ) +# the models the causal guarantee covers: scikit-learn's classes of these +# names, which hypertools fits for them. Their ``transform`` is a fixed +# linear map of each row. A fitted estimator is one of them by its exact +# class: a subclass can pass every probe of ``_fit_reducer`` (they reduce +# training rows only) and still reduce a row differently with later rows. +_GUARANTEED_MODELS = ("PCA", "IncrementalPCA", "TruncatedSVD", "FastICA", + "FactorAnalysis") +_GUARANTEED_TEXT = ( + f"scikit-learn's {', '.join(_GUARANTEED_MODELS[:-1])} and " + f"{_GUARANTEED_MODELS[-1]}, by exact class: a subclass is not one" +) + + +def _uncovered_model(rfun): + """ + The label of a model reducer (a name or a dict) that is not one of + ``_GUARANTEED_MODELS``: another name, or a class or object that is not + exactly one of those scikit-learn classes. None for a model of the + list and for a reducer that is not a model. + """ + if not _is_model(rfun): + return None + model = rfun.get("model") if isinstance(rfun, dict) else rfun + if isinstance(model, str): + covered = model in _GUARANTEED_MODELS + else: + import sklearn.decomposition + + classes = [getattr(sklearn.decomposition, name) for name in _GUARANTEED_MODELS] + cls = model if isinstance(model, type) else type(model) + covered = any(cls is c for c in classes) + return None if covered else _model_label(rfun) + + +def _warn_uncovered_models(found): + """ + One ``UserWarning`` for the models of a causal call that are outside + ``_GUARANTEED_MODELS``: ``found`` is a list of ``(label, where)``, as + ``(_uncovered_model(rfun), "rfun at order 1")``; entries with a label + of None are models of the list. Such a model is used when it passes + the probes of ``_fit_reducer``, like a function of the user's. + """ + places = {} + for label, where in found: + if label is not None: + places.setdefault(label, []).append(where) + if not places: + return + named = [f"{label!r} ({', '.join(where)})" for label, where in places.items()] + one = len(named) == 1 + _warn_user( + f"causal=True: the model{'' if one else 's'} " + f"{', '.join(named[:-1])}{'' if one else ' and '}{named[-1]} " + f"{'is not one of' if one else 'are not among'} the models the guarantee " + f"covers ({_GUARANTEED_TEXT}). " + f"{'It is' if one else 'They are'} used as given: the guarantee that row " + "t does not depend on later rows does not cover what " + f"{'its transform does' if one else 'their transforms do'}." + ) + + def _model_label(rfun): """The name of a model reducer (a name or a dict), for messages.""" label = rfun.get("model") if isinstance(rfun, dict) else rfun @@ -611,6 +694,7 @@ def _causal_arguments(weights_function, weights_params, include_timepoints, cfun "not cover what " f"{'it does' if len(theirs) == 1 else 'they do'}." ) + _warn_uncovered_models([(_uncovered_model(rfun), "rfun")]) return include_timepoints, cfun @@ -784,8 +868,13 @@ def timecorr( linear models such as PCA once fitted); the eigenvector-based graph measures (``"eigenvector_centrality"``, the PageRank measures) can differ by more at a correlation matrix whose leading - eigenvalues coincide. Keyword only. Default: False. With - ``causal=True``: + eigenvalues coincide. Smoothed values (``cfun=None``) are on the + scale of the data, not bounded like correlations: when later rows + are removed they agree to round-off relative to the magnitude of + the data, that is to 1e-9 or 8 units in the last place of the + largest magnitude of the data, whichever is larger (1.2e-7 for + data near 1e8); replacement still changes no bit. Keyword only. + Default: False. With ``causal=True``: - the kernel is backward: ``include_timepoints`` 'all' (the default) means 'backward', and 'forward' / 'post' raise @@ -801,7 +890,8 @@ def timecorr( timepoint, so ``cfun=tc.wisfc`` raises ``ValueError``). Any other function is called as without ``causal``, with a ``UserWarning`` that the guarantee does not cover it; the same - holds for a callable ``rfun``; + holds for a callable ``rfun``, and for a model outside the list + under ``fit_timepoints``; - ``events`` must be boundaries; features to segment raise ``ValueError``. That the boundaries themselves were chosen without later data is the caller's responsibility. The warm-up @@ -855,16 +945,21 @@ def timecorr( unchanged (to 1e-9; bit for bit under replacement) when rows after ``t`` are replaced or removed, and a row ``t < n`` when rows from ``n`` on are. ``n`` equal to the number of timepoints fits on - every row. A model must be a linear map applied to each row by itself: - its fitted estimator has ``components_`` (``"PCA"``, - ``"IncrementalPCA"``, ``"TruncatedSVD"``, ``"FastICA"``, - ``"FactorAnalysis"``, ...), it reproduces its training rows to - 1e-9, and it reduces rows one at a time as it reduces them - together; any other model raises ``ValueError`` (``"UMAP"``, - ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, - ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the - transform of some of them depends on the rows it is given - together). A model asked for as many components as its input + every row. 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 (``"MiniBatchDictionaryLearning"``, a class of + your own) is used with one ``UserWarning`` per call that the guarantee + does not cover what its transform does: those checks read a few + training rows and cannot show how it reduces later rows. A model + without ``components_``, or that fails a check, raises ``ValueError`` + (``"UMAP"``, ``"KernelPCA"``, ``"Isomap"``, ``"MDS"``, ``"TSNE"``, + ``"SpectralEmbedding"``, ``"LocallyLinearEmbedding"``: the transform of + some of them depends on the rows it is given together). + A model asked for as many components as its input has columns, or more, changes nothing (zero columns are appended for the components beyond them), as without ``causal``. ``"PCA"`` is From 4f87f1dd1bc4ea3e8ed849eb43a3ca72ed59a24c Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Mon, 23 Nov 2026 15:59:22 -0500 Subject: [PATCH 15/26] Causal mode: tutorial on the industry returns, API page, CHANGELOG 0.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 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- CHANGELOG.md | 175 +++++ CLAUDE.md | 19 +- README.md | 1 + docs/api.rst | 99 +++ docs/generated/timecorr.FeaturesModel.rst | 16 + .../timecorr.FeaturesModel.transform.rst | 6 + docs/index.rst | 5 +- docs/tutorial/causal.ipynb | 669 ++++++++++++++++++ docs/tutorials.rst | 1 + 9 files changed, 982 insertions(+), 9 deletions(-) create mode 100644 docs/generated/timecorr.FeaturesModel.rst create mode 100644 docs/generated/timecorr.FeaturesModel.transform.rst create mode 100644 docs/tutorial/causal.ipynb diff --git a/CHANGELOG.md b/CHANGELOG.md index a6141fec..a9704be4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,181 @@ 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; + - 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: 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`, `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); + - 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. + - 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 widths, the number of communities and the + choice of an automatic feeding step are those of the first fit; a later fit + that cannot have them is not used, the fit before stays for its rows (at + every order), and `return_info` lists the row (`"refit_kept_previous"`). 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"`. 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, 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..b6f70f1d 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 that are not entirely NaN 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`; 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`: number of communities, the automatic feeding step's choice, number of components), 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"`). 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; 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`/`rfun` of the user's runs with one `UserWarning` that the guarantee does not cover it; 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), 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 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 returned as its training mean; 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 `