Simulation¶
mtdr.simulation
¶
Ground-truth simulation of the mTDR generative model.
simulate draws data the way the reference demo does
(SimWeights, SimConditions, SimPopData and the mask step of mTDRdemo.m;
docs/model.md § 8, (M40)-(M45)) and returns them with the ground truth in a
SimulatedData.
Random draws and the transforms applied to them are kept apart: simulate
draws standard normals, exponentials, uniform condition indices and uniforms
for the mask from one numpy.random.Generator in a fixed order, and the
private functions below map those draws to the outputs deterministically. The
parity tests inject the draws exported from MATLAB
(tests/fixtures/matlab/make_simulation_fixture.m) both into these transforms
and, through a replaying generator, into simulate itself; the two RNG streams
are never compared.
SimulatedData
dataclass
¶
Simulated responses, design and mask, with the ground truth that made them.
Returned by simulate. Every array is float64
(the mask bool, condition_of_trial integer) and read-only, and the
per-regressor mappings are read-only too, so the ground truth cannot be
changed by accident; copy an array to modify it.
Attributes:
| Name | Type | Description |
|---|---|---|
Y |
ndarray
|
|
X |
ndarray
|
|
mask |
ndarray
|
|
W |
Mapping of str to numpy.ndarray
|
Per regressor, |
S |
Mapping of str to numpy.ndarray
|
Per regressor, |
B |
Mapping of str to numpy.ndarray
|
Per regressor, |
intercept |
ndarray or None
|
|
noise_precision |
ndarray
|
|
ranks |
Mapping of str to int
|
Per regressor, the generating rank |
regressor_names |
tuple of str
|
Names, in |
levels |
tuple of numpy.ndarray
|
Per regressor, the level set the conditions were drawn from (with a
supplied |
condition_of_trial |
ndarray
|
|
seed |
int or None
|
The integer seed, if one was given; |
Y_masked
property
¶
Y with NaN where mask is False: what a real dataset looks like.
The port's form of the reference's zeroed Z_k = diag(h_k) Y_k, (M45).
A new, writable array on every access.
simulate(n_neurons=100, n_bins=15, n_trials=100, ranks=(2, 1, 3), levels=None, length_scale=2.0, amplitude=1.0, noise_precision=None, drop_prob=0.0, condition_independent=True, regressor_names=None, seed=None, *, X=None, S=None, W=None)
¶
Simulate population responses with known low-rank structure.
The generative model (M40)-(M45), with the reference demo's choices:
- each column of
S[p]is an independent draw from a Gaussian process over bins with unit-variance squared-exponential kernel \(\exp(-(t-t')^2 / 2\ell_p^2)\), time-reversed as in the reference (M41); W[p]entries are i.i.d. \(\mathcal N(0, a_p^2)\), \(a_p\) the amplitude (M40), andB[p] = W[p] @ S[p].T;- with
condition_independent=Truethe intercept is \(W_0S_0^\top\), with \(W_0\) of shape(n_neurons, n_bins)i.i.d. \(\mathcal N(0, a_0^2)\) and \(S_0\) ann_bins-column GP draw: the reference's constant term, withn_binsgenerating columns; - each trial's regressor values are drawn uniformly, with replacement, from the grid of all level combinations (M43);
Y[k] = intercept + sum_p X[k, p] B[p] + E_k, the rows ofE_kGaussian with per-neuron precision (M44);- each neuron-trial is unobserved independently with probability
drop_prob(M45), conditioned on the validity promise (Notes).
Any of the drawn pieces can be supplied instead: a design X
replaces the condition draw of (M43), so a task's own incomplete or
correlated design can be simulated; S and W replace the GP bases of
(M41) and the weight draw of (M40), regressor by regressor set, so
prescribed time courses (epochs that are exactly zero outside a window,
say) and weight patterns can be simulated. The responses, noise and mask
are then generated by (M44)-(M45) as usual, and B[p] = W[p] @ S[p].T.
Draw order (docs/model.md § D.4): for each regressor in turn, then the
intercept, the weight normals and then the basis normals; the precisions
(only when noise_precision is None); the condition indices; the noise;
the mask uniforms, once per mask draw. A supplied piece skips its draw
(the weight normals when W is given, the basis normals when S is, the
condition indices when X is) and leaves the order of the rest
unchanged, so with none supplied the draws are exactly those above.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_neurons
|
int
|
Number of neurons, |
100
|
n_bins
|
int
|
Number of time bins, |
15
|
n_trials
|
int
|
Number of trials: at least 2, so every neuron can be observed twice,
and at least |
100
|
ranks
|
sequence of int, 1-D integer array, or mapping of str to int
|
Generating rank of each regressor's coefficient matrix, |
(2, 1, 3)
|
levels
|
sequence of array_like, or 2-D array
|
Level set per regressor (one row per regressor for a 2-D array),
distinct finite values. |
None
|
length_scale
|
float or sequence of float
|
GP length scale, in bins, of the temporal bases. A sequence has one
entry per regressor, plus optionally a last entry for the intercept
(the reference's |
2.0
|
amplitude
|
float or sequence of float
|
Standard deviation of the weight entries (the reference's |
1.0
|
noise_precision
|
float or array_like of shape (n_neurons,)
|
Noise precision (inverse variance) per neuron, |
None
|
drop_prob
|
float
|
Probability, in |
0.0
|
condition_independent
|
bool
|
Add the intercept. Must be a |
True
|
regressor_names
|
sequence of str
|
Names in |
None
|
seed
|
(int, Generator, SeedSequence or None)
|
Seed for |
None
|
X
|
array_like
|
|
None
|
S
|
sequence or mapping of array_like
|
Temporal bases to use instead of the GP draws (keyword-only): an
|
None
|
W
|
sequence or mapping of array_like
|
Neuron weights to use instead of the normal draws (keyword-only): an
|
None
|
Returns:
| Type | Description |
|---|---|
SimulatedData
|
Responses, design, mask and ground truth. |
Raises:
| Type | Description |
|---|---|
ParameterError
|
For an invalid argument: wrong types; mismatched lengths of
|
Notes
Validity promise: the mask is re-drawn until every trial has an observed
neuron and every neuron is observed on at least 2 trials (the default
min_observations). The re-draw conditions the mask, so in
sparse regimes the observed fraction exceeds 1 - drop_prob (about 0.73
rather than 0.40 for 3 neurons, 3 trials and drop_prob=0.6). Nothing is
promised about X: with few trials a sampled column can be constant, or
the columns collinear, by chance, which fit rejects; check X (or use
more trials) when simulating small designs.
Ranks: B[p] has rank r_p when its amplitude is positive and its
kernel is numerically full rank to r_p. At long length scales the
squared-exponential kernel's trailing eigenvalues fall below machine
precision (at n_bins=15, from a length scale of about 3.5), so the
trailing basis directions are rounding noise and, once the kernel is
singular in floating point, B[p] and the intercept are rank-deficient.
Keep r_p below the number of kernel eigenvalues above about 1e-12 of
the largest; the default length scale 2.0 is unaffected.
Examples:
>>> import numpy as np
>>> from mtdr import simulate
>>> sim = simulate(n_neurons=30, n_bins=10, n_trials=50,
... ranks={"sa": 2, "choice": 1},
... levels=[[-2, -1, 0, 1, 2], [-1, 1]],
... drop_prob=0.2, seed=0)
>>> sim
SimulatedData(n_trials=50, n_neurons=30, n_bins=10, ranks={'sa': 2, ...}, ...)
>>> sim.Y.shape, sim.X.shape, sim.mask.shape
((50, 30, 10), (50, 2), (50, 30))
>>> sim.W["sa"].shape, sim.S["sa"].shape
((30, 2), (10, 2))
>>> int(np.linalg.matrix_rank(sim.B["sa"]))
2
>>> bool(np.isnan(sim.Y_masked[~sim.mask]).all())
True
A design of one's own, with a prescribed time course for one regressor:
>>> X = np.column_stack([np.repeat([-1.0, 1.0], 25), np.tile([-1.0, 1.0], 25)])
>>> profile = np.where(np.arange(10) >= 4, 1.0, 0.0) # zero before bin 4
>>> sim = simulate(n_neurons=30, n_bins=10, n_trials=50,
... ranks={"sa": 1, "choice": 1}, X=X,
... S={"sa": profile, "choice": np.ones(10)}, seed=0)
>>> bool(np.array_equal(sim.X, X)), bool((sim.B["sa"][:, :4] == 0).all())
(True, True)