Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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.
- `tc.simulate_hierarchy(..., volatility=sd, volatility_tau=50)`: every
series of every subject is multiplied by one positive series `v(t)`
(volatility clustering common to all series). `log v` is Gaussian-smoothed
white noise (standard deviation `volatility_tau` samples) with standard
deviation `sd`, and the mean of `v**2` is 1. `v` is drawn last, so at the
same seed the data are exactly those without `volatility` times `v`.
`truth["volatility"]` holds `v` (ones by default). The default (`None`)
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
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,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 <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 `<video>` tag with a relative, percent-encoded and escaped link inside a Sphinx source tree and for a URL; `IPython.display.Video(embed=True)` elsewhere) and `media_dir(name="tutorial_media")` (`../_static/tutorial_media` when the parent of the working directory holds `conf.py` and `_static`, otherwise `name`). All three are exported from `timecorr`.
- **`timecorr/tutorial.mplstyle`**: the plot style of the tutorials (`plt.style.use('timecorr.tutorial')`; the seven rcParams the notebooks set, the Okabe-Ito color cycle included; `package_data` in `setup.py`; needs matplotlib >= 3.7; `tests/test_tutorial_style.py`). Importing timecorr does not apply it.
- **`timecorr/simulate.py`**: simulated data with known dynamic correlations (`simulate_data`, `simulate_multi_order`) and helpers for structure embedded at a chosen order (`min_features`, `carrier_reducer`, `carrier_columns`, `nested_template`), and `simulate_nested` (nodes in modules in supergroups; returns `(data, truth)` with the order-2 signal `truth["h"]`), and `simulate_hierarchy` (nested groups of any depth `len(taus)`, one signal per group per level; returns `(data, truth)` with `truth["groups"]`, `truth["signals"]`, `truth["top"]` and the node signs `truth["signs"]`; `signs="private"` (default) or `"shared"`; `factors="private"` (default) or `"shared"`: the module series `f` drawn per subject or once for all, returned in `truth["factors"]`).
- **`timecorr/simulate.py`**: simulated data with known dynamic correlations (`simulate_data`, `simulate_multi_order`) and helpers for structure embedded at a chosen order (`min_features`, `carrier_reducer`, `carrier_columns`, `nested_template`), and `simulate_nested` (nodes in modules in supergroups; returns `(data, truth)` with the order-2 signal `truth["h"]`), and `simulate_hierarchy` (nested groups of any depth `len(taus)`, one signal per group per level; returns `(data, truth)` with `truth["groups"]`, `truth["signals"]`, `truth["top"]` and the node signs `truth["signs"]`; `signs="private"` (default) or `"shared"`; `factors="private"` (default) or `"shared"`: the module series `f` drawn per subject or once for all, returned in `truth["factors"]`; `volatility=None` (default) or the standard deviation of the logarithm of one multiplier `v(t)` common to every subject and node, smoothed over `volatility_tau` samples, mean of `v**2` equal to 1, drawn last so the data are those without it times `v`, returned in `truth["volatility"]`).

### Key Concepts

Expand Down
6 changes: 5 additions & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,11 @@ Simulation
separately by default, so its subjects share coupling signals and no time
series; with ``factors="shared"`` every subject has the same module series
(``truth["factors"]``), and nodes of one module are correlated across
subjects.
subjects. ``volatility=0.5`` multiplies every series of every subject by one
positive series ``v(t)`` (``truth["volatility"]``) whose logarithm has
standard deviation 0.5 and varies over about ``volatility_tau`` samples:
volatility clustering common to all series, which leaves the correlations
between nodes at each time unchanged.

Decoders
--------
Expand Down
102 changes: 102 additions & 0 deletions tests/test_simulate_hierarchy.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,105 @@ def test_data_are_the_documented_mixture_of_the_returned_factors():
def test_factors_validation():
with pytest.raises(ValueError, match="factors must be 'private' or 'shared'"):
small(factors="all")


# --- volatility: one multiplier common to every subject and node -------------

COMBOS = [(sh, sg, fa) for sh in ("top", "all", "none")
for sg in ("private", "shared") for fa in ("private", "shared")]


def test_no_volatility_is_the_default_call():
data, truth = small(S=3)
data_n, truth_n = small(S=3, volatility=None)
for a, b in zip(data, data_n):
assert np.array_equal(a, b)
assert np.array_equal(truth["volatility"], np.ones(len(data[0])))
assert np.array_equal(truth_n["volatility"], np.ones(len(data[0])))


@pytest.mark.parametrize("shared,signs,factors", COMBOS)
def test_volatility_multiplies_the_output_without_it(shared, signs, factors):
"""Same seed: every other draw is unchanged, the data are multiplied."""
kw = dict(S=3, shared=shared, signs=signs, factors=factors)
data, truth = small(**kw)
data_v, truth_v = small(volatility=0.5, volatility_tau=10, **kw)
v = truth_v["volatility"]
assert v.shape == (len(data[0]),)
assert np.all(v > 0) and np.ptp(v) > 0
for a, b in zip(data, data_v):
assert np.array_equal(b, a * v[:, None])
assert np.array_equal(truth["signs"], truth_v["signs"])
for a, b in zip(truth["factors"], truth_v["factors"]):
assert np.array_equal(a, b)
for sa, sb in zip(truth["signals"], truth_v["signals"]):
for a, b in zip(sa, sb):
assert np.array_equal(a, b)


@pytest.mark.parametrize("sd", [0.1, 0.5, 1.5])
def test_volatility_scale(sd):
"""log v has standard deviation `volatility`; mean(v**2) is 1."""
_, truth = small(T=4000, volatility=sd, volatility_tau=25)
v = truth["volatility"]
assert abs(np.log(v).std() - sd) < 1e-12
assert abs(np.mean(v ** 2) - 1) < 1e-12


def test_volatility_timescale():
"""Autocorrelation of log v at lag k is exp(-k**2 / (4 tau**2))."""
tau = 20
_, truth = tc.simulate_hierarchy(
S=1, T=200000, nodes_per_module=2, branching=(), n_top=2, taus=(5,),
set_random_seed=4, volatility=0.5, volatility_tau=tau)
h = np.log(truth["volatility"])
h = h - h.mean()
for k in (tau // 2, tau, 2 * tau):
r = np.mean(h[:-k] * h[k:]) / np.mean(h * h)
assert abs(r - np.exp(-k ** 2 / (4 * tau ** 2))) < 0.05


def test_volatility_clusters_squared_values():
"""Squared values are autocorrelated with the multiplier and not without."""
kw = dict(S=2, T=40000, nodes_per_module=3, branching=(2,), n_top=2,
taus=(5, 50), set_random_seed=9)

def lag1(data):
out = []
for x in data:
q = x ** 2 - (x ** 2).mean(0)
out.append(np.mean(np.sum(q[:-1] * q[1:], 0) / np.sum(q * q, 0)))
return np.mean(out)

plain = lag1(tc.simulate_hierarchy(**kw)[0])
clustered = lag1(tc.simulate_hierarchy(volatility=0.5, volatility_tau=50, **kw)[0])
assert abs(plain) < 0.01
assert clustered > 0.2


def test_volatility_is_reproducible_and_a_copy():
a, ta = small(volatility=0.3)
b, tb = small(volatility=0.3)
assert np.array_equal(ta["volatility"], tb["volatility"])
before = a[0].copy()
ta["volatility"][:] = 7
assert np.array_equal(a[0], before)


@pytest.mark.parametrize("bad", [0, -0.5, np.nan, np.inf, True, "0.5", (0.5, 10)])
def test_volatility_validation(bad):
with pytest.raises(ValueError, match="volatility must be None or a positive"):
small(volatility=bad)


@pytest.mark.parametrize("bad", [0, -3, 2.5, "10", True])
def test_volatility_tau_validation(bad):
with pytest.raises(ValueError, match="volatility_tau"):
small(volatility=0.5, volatility_tau=bad)


def test_volatility_tau_needs_enough_timepoints():
with pytest.raises(ValueError, match="8 \\* volatility_tau"):
small(T=400, volatility=0.5, volatility_tau=51)
small(T=400, volatility=0.5, volatility_tau=50)
small(T=400, volatility_tau=51) # not used without volatility
56 changes: 53 additions & 3 deletions timecorr/simulate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,8 @@ def simulate_hierarchy(
set_random_seed=None,
signs="private",
factors="private",
volatility=None,
volatility_tau=50,
):
"""
Simulate nodes in nested groups of any depth with time-varying coupling.
Expand All @@ -1268,11 +1270,17 @@ def simulate_hierarchy(
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.
- With ``volatility`` given, every ``x_i(t)`` of every subject is
multiplied by one positive series ``v(t)``, with ``log v(t)`` a
``smooth(volatility_tau)`` series times ``volatility`` plus a constant
that makes the mean of ``v**2`` equal to 1.

Siblings at level ``l`` share ``u`` of their parent with weight
``sqrt(s_{l+1})``, so their latent series ``a`` are correlated by about
``s_{l+1}`` over windows short compared with ``s_{l+1}``'s timescale;
each node has variance 1 whatever the signals. With ``n = 2`` this is the
each node has variance 1 whatever the signals (without ``volatility``;
with it, variance ``v(t)**2`` at time ``t``, 1 on average, and the
correlations between nodes at each time are unchanged). With ``n = 2`` this is the
sustained coupling of ``simulate_nested`` (``s_2`` is ``h``, ``s_1`` is
``g``). The model assumes that higher levels vary more slowly
(increasing ``taus``); this is not checked.
Expand Down Expand Up @@ -1330,6 +1338,19 @@ def simulate_hierarchy(
``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"``.
volatility : float or None
``None``: no multiplier (the output is the same as without this
option). A positive number: the standard deviation of the
logarithm of a multiplier ``v(t)`` common to every subject and
node (volatility clustering shared by all series). ``v`` is drawn
after everything else, so at the same seed the data are exactly
those without ``volatility`` times ``v`` and every other entry of
``truth`` is the same. Default: ``None``.
volatility_tau : int
Standard deviation, in samples, of the Gaussian smoothing of
``log v``: its autocorrelation at lag ``k`` is
``exp(-k**2 / (4 * volatility_tau**2))``. With ``volatility``
given, ``T`` must be at least ``8 * volatility_tau``. Default: 50.

Returns
-------
Expand All @@ -1345,7 +1366,9 @@ def simulate_hierarchy(
``s`` holds the node signs ``e`` of subject ``s`` (equal rows with
``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
subject (equal arrays with ``factors="shared"``). ``"volatility"``:
the multiplier ``v``, shape ``(T,)`` (ones without ``volatility``).
Every array is a
separate copy, so
changing one subject's signals (or ``"top"``) leaves the others
unchanged. ``"taus"`` and ``"branching"``: tuples.
Expand All @@ -1356,7 +1379,10 @@ 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``, ``signs`` or ``factors``.
an unknown ``shared``, ``signs`` or ``factors``, a ``volatility``
that is not None or a positive finite number, a ``volatility_tau``
that is not a positive integer, or, with ``volatility`` given,
``T < 8 * volatility_tau``.
TypeError
For a ``set_random_seed`` that is not None, a bool or an integer.

Expand Down Expand Up @@ -1400,6 +1426,23 @@ def simulate_hierarchy(
raise ValueError(
f"factors must be 'private' or 'shared'; got {factors!r}."
)
volatility_tau = _check_positive_int("volatility_tau", volatility_tau)
if volatility is not None:
if (
not isinstance(volatility, numbers.Real)
or isinstance(volatility, bool)
or not np.isfinite(volatility)
or volatility <= 0
):
raise ValueError(
"volatility must be None or a positive finite number; "
f"got {volatility!r}."
)
if T < 8 * volatility_tau:
raise ValueError(
f"T must be at least 8 * volatility_tau = {8 * volatility_tau} "
f"for the smoothing; got T={T}."
)
rng = _make_rng(set_random_seed)

counts = [n_top] # counts[l-1]: number of level-l groups
Expand Down Expand Up @@ -1441,6 +1484,12 @@ def simulate_hierarchy(
signals.append(s)
node_signs.append(e.copy())
series.append(f)
if volatility is None:
v = np.ones(T)
else: # drawn last: every other draw is that of the call without it
v = np.exp(float(volatility) * _smooth(rng, T, 1, volatility_tau)[:, 0])
v /= np.sqrt(np.mean(v ** 2))
data = [x * v[:, None] for x in data]
truth = {
"groups": groups,
"signals": signals,
Expand All @@ -1449,5 +1498,6 @@ def simulate_hierarchy(
"branching": branching,
"signs": np.array(node_signs),
"factors": series,
"volatility": v,
}
return data, truth
Loading