From 09f23e9c210b7dd805a66cd05e2c84d6fc7bda3b Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Tue, 24 Nov 2026 10:01:42 -0500 Subject: [PATCH 1/2] simulate_hierarchy: factors="shared" gives every subject the same module series The module series f (one per module) is drawn once for all subjects; z stays private. truth["factors"] holds each subject's series. The default output is unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- tests/test_simulate_hierarchy.py | 87 ++++++++++++++++++++++++++++++++ timecorr/simulate.py | 42 ++++++++++++--- 2 files changed, 123 insertions(+), 6 deletions(-) diff --git a/tests/test_simulate_hierarchy.py b/tests/test_simulate_hierarchy.py index 61e8e54e..6664b3d1 100644 --- a/tests/test_simulate_hierarchy.py +++ b/tests/test_simulate_hierarchy.py @@ -366,3 +366,90 @@ def test_shared_signs_change_the_private_draws_at_the_same_seed(shared): np.testing.assert_array_equal(truth_p["top"], truth_s["top"]) assert not np.array_equal(truth_p["signals"][0][0], truth_s["signals"][0][0]) assert not np.array_equal(data_p[0], data_s[0]) + + +# --- factors: module series shared across subjects --------------------------- + +@pytest.mark.parametrize("shared", ["top", "all", "none"]) +def test_private_factors_are_the_default_output(shared): + data, truth = small(S=3, shared=shared) + data_p, truth_p = small(S=3, shared=shared, factors="private") + for x, y in zip(data, data_p): + assert np.array_equal(x, y) + n_modules = truth["signals"][0][0].shape[1] + assert len(truth["factors"]) == 3 + for f in truth["factors"]: + assert f.shape == (400, n_modules) + # private: the subjects' module series differ + assert not np.array_equal(truth["factors"][0], truth["factors"][1]) + + +@pytest.mark.parametrize("shared", ["top", "all", "none"]) +@pytest.mark.parametrize("signs", ["private", "shared"]) +def test_shared_factors_are_equal_copies(shared, signs): + data, truth = small(S=3, shared=shared, signs=signs, factors="shared") + f = truth["factors"] + for other in f[1:]: + np.testing.assert_array_equal(other, f[0]) + assert other is not f[0] + # the subjects' data still differ (z is private) + assert not np.array_equal(data[0], data[1]) + # a copy: changing one subject's series leaves the others unchanged + before = f[1].copy() + f[0][:] = 0.0 + np.testing.assert_array_equal(f[1], before) + # the signals are those of the "private" call at the same seed when + # they are drawn before the shared series + if shared == "all": + _, private = small(S=3, shared=shared, signs=signs) + for x, y in zip(truth["signals"][0], private["signals"][0]): + np.testing.assert_array_equal(x, y) + + +def _across_subject_correlations(factors): + """Correlations between the nodes of subjects 0 and 1, times the sign + product, and the module mean of g, for a long series with every signal + and sign shared (so sqrt(g_a g_b) is g).""" + data, truth = small(S=2, T=20000, shared="all", signs="shared", + factors=factors) + module = truth["groups"][0] + e = truth["signs"][0] + K = len(module) + r = np.corrcoef(data[0].T, data[1].T)[:K, K:] * np.outer(e, e) + same = module[:, None] == module[None, :] + expected = np.where(same, truth["signals"][0][0].mean(axis=0)[module][:, None], 0.0) + return r, expected, same + + +def test_shared_factors_correlate_modules_across_subjects(): + # measured at seeds 0 to 3: largest deviation 0.017 within modules and + # 0.032 between modules (sampling error at T = 20000) + r, expected, same = _across_subject_correlations("shared") + assert np.abs(r - expected).max() < 0.05 + assert r[same].mean() > 0.4 + + +def test_private_factors_share_no_series(): + r, _, same = _across_subject_correlations("private") + assert np.abs(r).max() < 0.05 + + +def test_data_are_the_documented_mixture_of_the_returned_factors(): + # x = sqrt(g) e f + sqrt(1 - g) z: what is left after removing the + # factor term is sqrt(1 - g) z, uncorrelated with f and of variance 1 - g + data, truth = small(S=2, T=20000, factors="shared") + module = truth["groups"][0] + for x, signals, e, f in zip(data, truth["signals"], truth["signs"], + truth["factors"]): + g = signals[0][:, module] + rest = x - np.sqrt(g) * e * f[:, module] + np.testing.assert_allclose(rest.var(axis=0), (1 - g).mean(axis=0), + rtol=0.06) + r = [np.corrcoef(rest[:, k], f[:, module[k]])[0, 1] + for k in range(x.shape[1])] + assert np.abs(r).max() < 0.03 + + +def test_factors_validation(): + with pytest.raises(ValueError, match="factors must be 'private' or 'shared'"): + small(factors="all") diff --git a/timecorr/simulate.py b/timecorr/simulate.py index 6b5bdcd7..65413455 100644 --- a/timecorr/simulate.py +++ b/timecorr/simulate.py @@ -1243,6 +1243,7 @@ def simulate_hierarchy( shared="top", set_random_seed=None, signs="private", + factors="private", ): """ Simulate nodes in nested groups of any depth with time-varying coupling. @@ -1264,7 +1265,9 @@ def simulate_hierarchy( - ``x_i(t) = sqrt(g) e_i f_m(t) + sqrt(1 - g) z_i(t)`` for node ``i`` in module ``m``, with ``g = s_{1,m}(t)``, ``f`` and ``z`` white standard normal noise and ``e_i`` a fixed random sign per node (drawn per - subject, or once for every subject with ``signs="shared"``). + subject, or once for every subject with ``signs="shared"``). ``f`` + (one series per module) is drawn per subject, or once for every + subject with ``factors="shared"``; ``z`` is always private. Siblings at level ``l`` share ``u`` of their parent with weight ``sqrt(s_{l+1})``, so their latent series ``a`` are correlated by about @@ -1314,6 +1317,19 @@ def simulate_hierarchy( from the ``"private"`` output: only the shared signals are the same, and the two settings are not paired draws of the subjects' series. Default: ``"private"``. + factors : {"private", "shared"} + ``"private"``: each subject draws its own module series ``f``, so + no time series is shared between subjects (the output is the same + as without this option). ``"shared"``: one set of module series, + drawn after the shared signals and signs and before the subjects' + series, is used by every subject, so nodes of one module are + correlated across subjects: for node ``i`` of subject ``a`` and + node ``j`` of subject ``b`` in module ``m``, the correlation at + time ``t`` is ``e_i e_j sqrt(g_a(t) g_b(t))``, with ``g`` each + subject's ``s_{1,m}`` and ``e`` each subject's signs (use + ``signs="shared"`` for the same sign in every subject). As for + ``signs``, every draw after the shared series differs from the + ``"private"`` output at the same seed. Default: ``"private"``. Returns ------- @@ -1327,7 +1343,10 @@ def simulate_hierarchy( groups)``. ``"top"``: ``s_n`` of subject 0 (shared by every subject unless ``shared="none"``). ``"signs"``: ``(S, K)`` array; row ``s`` holds the node signs ``e`` of subject ``s`` (equal rows with - ``signs="shared"``). Every array is a separate copy, so + ``signs="shared"``). ``"factors"``: a list over subjects of + ``(T, number of modules)`` arrays, the module series ``f`` of each + subject (equal arrays with ``factors="shared"``). Every array is a + separate copy, so changing one subject's signals (or ``"top"``) leaves the others unchanged. ``"taus"`` and ``"branching"``: tuples. @@ -1337,7 +1356,7 @@ def simulate_hierarchy( For a size that is not a positive integer, ``taus`` or ``branching`` that is not a sequence of positive integers, an empty ``taus``, ``len(branching) != len(taus) - 1``, ``T < 8 * max(taus)``, - or an unknown ``shared`` or ``signs``. + or an unknown ``shared``, ``signs`` or ``factors``. TypeError For a ``set_random_seed`` that is not None, a bool or an integer. @@ -1377,6 +1396,10 @@ def simulate_hierarchy( raise ValueError(f"shared must be 'top', 'all' or 'none'; got {shared!r}.") if signs not in ("private", "shared"): raise ValueError(f"signs must be 'private' or 'shared'; got {signs!r}.") + if factors not in ("private", "shared"): + raise ValueError( + f"factors must be 'private' or 'shared'; got {factors!r}." + ) rng = _make_rng(set_random_seed) counts = [n_top] # counts[l-1]: number of level-l groups @@ -1395,8 +1418,10 @@ def simulate_hierarchy( top = _hierarchy_signals(rng, T, counts[n - 1:], (), taus[n - 1:])[0] if signs == "shared": common_signs = rng.choice([-1.0, 1.0], K) + if factors == "shared": + common_f = rng.standard_normal((T, counts[0])) - data, signals, node_signs = [], [], [] + data, signals, node_signs, series = [], [], [], [] for _ in range(S): if shared == "all": s = [x.copy() for x in common] @@ -1407,11 +1432,15 @@ def simulate_hierarchy( ) g = s[0][:, module] e = rng.choice([-1.0, 1.0], K) if signs == "private" else common_signs - f = rng.standard_normal((T, counts[0]))[:, module] + if factors == "private": + f = rng.standard_normal((T, counts[0])) + else: + f = common_f.copy() z = rng.standard_normal((T, K)) - data.append(np.sqrt(g) * e * f + np.sqrt(1 - g) * z) + data.append(np.sqrt(g) * e * f[:, module] + np.sqrt(1 - g) * z) signals.append(s) node_signs.append(e.copy()) + series.append(f) truth = { "groups": groups, "signals": signals, @@ -1419,5 +1448,6 @@ def simulate_hierarchy( "taus": taus, "branching": branching, "signs": np.array(node_signs), + "factors": series, } return data, truth From bc206a785031ac351cb4998a42fe474b7960bd08 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Tue, 24 Nov 2026 11:05:05 -0500 Subject: [PATCH 2/2] Subject weights per feature for wisfc; distinct_subject_weights wisfc(subject_weights=W) accepts W of shape (subjects, subjects, features): the weight of each subject in each subject's reference at each feature, in wisfc, the streamed summaries and causal mode. A feature of a subject without reference keeps the one defined orientation of its entries; its diagonal entry and its entries with other such features are 0, with one warning. tc.distinct_subject_weights(labels) builds the weights that leave out subjects holding one of a subject's own series. Also: docstrings of wcorr, isfc, wisfc and autofc no longer say that causal rows are unchanged "to 1e-9" (bit for bit since 0.4.0); new section in the subjects tutorial; API page, changelog and CLAUDE.md. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtyroRyyp5UK7L9zwqxL --- CHANGELOG.md | 33 ++ CLAUDE.md | 3 +- docs/api.rst | 31 ++ .../timecorr.distinct_subject_weights.rst | 6 + docs/tutorial/subjects.ipynb | 141 +++++--- tests/test_node_subject_weights.py | 325 ++++++++++++++++++ tests/test_simulate_hierarchy.py | 4 +- timecorr/__init__.py | 1 + timecorr/helpers.py | 231 ++++++++++++- timecorr/higher_order.py | 7 + timecorr/summaries.py | 22 +- 11 files changed, 746 insertions(+), 58 deletions(-) create mode 100644 docs/generated/timecorr.distinct_subject_weights.rst create mode 100644 tests/test_node_subject_weights.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d50467e..2d6aeb29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,39 @@ 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). +## [Unreleased] + +### Added + +- `tc.simulate_hierarchy(..., factors="shared")`: one set of module series + `f` for every subject (the noise `z` stays private), so nodes of one module + are correlated across subjects, by `e_i e_j sqrt(g_a g_b)` for nodes `i`, + `j` of subjects `a`, `b`. `truth["factors"]` holds each subject's module + series. The default (`"private"`) output is unchanged. +- Subject weights per feature: `tc.wisfc(subject_weights=W)` accepts `W` of + shape (subjects, subjects, features), the weight of each subject in each + subject's reference at each feature; in `tc.timecorr` and `tc.features` as + `cfun=functools.partial(tc.wisfc, subject_weights=W)`, also with + `causal=True` and in streamed steps. A feature of a subject where no + subject has weight has no reference: its entries with the other features + are the correlations of the subject's series there with the references of + those features, its diagonal entry and its entries with other such + features are 0, and one `UserWarning` counts the (subject, feature) pairs. + Matrix weights are unchanged. +- `tc.distinct_subject_weights(labels)`: the weights per feature that leave + out of each subject's reference the subjects holding one of its own series + (labels of shape (subjects, features)), for subjects that can hold the same + series; with two or more subjects and no repeated label the result is + `tc.isfc`. New section in the + "Several subjects" tutorial. + +### Fixed + +- Docstrings of `tc.wcorr`, `tc.isfc`, `tc.wisfc` and `tc.autofc` still said + that causal rows are unchanged "to 1e-9" when later samples are replaced or + removed; since 0.4.0 they are unchanged bit for bit (removal: with the + built-in kernel functions). No change in behavior. + ## [0.4.0] - 2026-11-24 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 5d074399..a514ce19 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,6 +53,7 @@ python setup.py sdist bdist_wheel - **`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`), each with keyword-only `causal=False, min_samples=None`; the causal branch is `_causal_setup` / `_causal_block` (see "Causal mode" under Key Concepts) + - Subject weights of `wisfc`: a matrix (S, S), or per feature (S, S, K) (`_subject_weight_matrix` checks the shape; `_subject_reference` gives a subject's reference and the mask of its features without reference, `_node_weighted_mean` the mean per feature, a column of zeros where no subject has weight; `_no_reference_entries` sets the entries of such a feature before the symmetrization, in `wisfc` and in the streamed blocks of `summaries._unit_row_blocks`: the defined orientation `C[k, i]` for both, 0 between two such features; `_no_reference_message` is the warning, issued by `wisfc` and by the streamed step in `higher_order`); `distinct_subject_weights(labels)` (exported) builds the per-feature weights that leave out subjects holding one of a subject's own series (`tests/test_node_subject_weights.py`) - 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` @@ -66,7 +67,7 @@ python setup.py sdist bdist_wheel - **`timecorr/datasets.py`** (used as `tc.datasets`; its functions are not top-level names): `fetch(url, path, sha256=None, member=None)` (cached download through uniquely named `.part` files next to the target and an atomic replace, so concurrent calls for one target are safe; a relative path is under the cache root `cache_dir()`: `$TIMECORR_DATA`, default `~/timecorr_data`; a cached file is checked against `sha256` on every call), `story_listening(n_nodes=100, return_nodes=False)` (HTFA node weights of the story-listening data, `pieman/pieman_posterior_K700.mat`; intact participants, nodes varying in every participant, farthest-point selection; `n_nodes` outside 1..679, the nodes that vary in every participant, raises `ValueError`; `return_nodes=True` adds a dict with `centers`, `widths`, `index`, `varying`, `total`) and `industry_returns(start, end)` (log returns of the 49 Industry Portfolios, `french/49_Industry_Portfolios_daily_CSV.zip`; `attrs` has the file's first line, `"header"`, and the count of missing returns, `"missing"`). `tests/test_datasets.py` holds the loading code the tutorial notebooks had at commit f9db4af and requires equal arrays. Only runtime dependencies. - **`timecorr/video.py`**: `render_video(draw, n_frames, path, fps=30, crf=23, hold=0, n_jobs=None, chunk_size=25, retries=0)` (`draw(frames, paths)` is called once per run of at most `chunk_size` consecutive frames in joblib worker processes, 3 or the usable cores by default; PNG frames in a temporary folder; `hold` appends copies of the last frame; with `retries`, workers are stopped after an error and new ones draw the frames whose files do not exist, again in runs of consecutive frames; the video is encoded under a temporary name next to the target and replaces it only on success; encoded with imageio-ffmpeg's ffmpeg, `-c:v libx264 -preset slow -crf -pix_fmt yuv420p -movflags +faststart`, byte for byte what the notebooks' own command gave: `tests/test_video.py`), `show_video(path, width=960)` (an HTML `