Skip to content

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

(n_trials, n_neurons, n_bins) noisy responses, every entry filled, including the unobserved ones, so recovery tests can look under the mask. Feed Y_masked, or Y together with mask, to a fit.

X ndarray

(n_trials, n_regressors) design. It has no column of ones (the intercept is separate), but with few trials a sampled column can be constant, or the columns collinear, by chance.

mask ndarray

(n_trials, n_neurons) bool; True = observed.

W Mapping of str to numpy.ndarray

Per regressor, (n_neurons, r_p) neuron weights.

S Mapping of str to numpy.ndarray

Per regressor, (n_bins, r_p) temporal bases (GP draws, not orthonormalised; docs/model.md § 8).

B Mapping of str to numpy.ndarray

Per regressor, (n_neurons, n_bins) coefficients W[p] @ S[p].T.

intercept ndarray or None

(n_neurons, n_bins) condition-independent term, or None when simulated with condition_independent=False.

noise_precision ndarray

(n_neurons,) noise precision (inverse variance) per neuron.

ranks Mapping of str to int

Per regressor, the generating rank r_p: the number of columns of W[p] and S[p]. B[p] has exactly this rank unless the amplitude is zero or the GP kernel is numerically singular (see simulate).

regressor_names tuple of str

Names, in X column order.

levels tuple of numpy.ndarray

Per regressor, the level set the conditions were drawn from (with a supplied X, each column's distinct values, sorted).

condition_of_trial ndarray

(n_trials,) index of each trial's condition in the grid of all level combinations, ordered with the first regressor varying fastest (MATLAB ndgrid): the condition with level indices j_0, j_1, ... has index j_0 + L_0 * (j_1 + L_1 * (j_2 + ...)), L_p the number of levels of regressor p. With a supplied X, the index of the trial's row among the distinct rows of X in numpy.unique(X, axis=0) order; either way a valid stratify argument for split_trials.

seed int or None

The integer seed, if one was given; None for a numpy.random.Generator, a numpy.random.SeedSequence or no seed.

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.

fit_kwargs()

Keyword arguments that pass the mask and names to a fit.

Returns:

Type Description
dict

{"mask": mask, "regressor_names": regressor_names}.

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), and B[p] = W[p] @ S[p].T;
  • with condition_independent=True the 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\) an n_bins-column GP draw: the reference's constant term, with n_bins generating 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 of E_k Gaussian 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, >= 1.

100
n_bins int

Number of time bins, >= 1.

15
n_trials int

Number of trials: at least 2, so every neuron can be observed twice, and at least n_regressors plus 1 for the intercept, so the design can have full column rank.

100
ranks sequence of int, 1-D integer array, or mapping of str to int

Generating rank of each regressor's coefficient matrix, 0 <= r_p <= min(n_neurons, n_bins). A mapping also names the regressors, in insertion order. At least one regressor.

(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 gives [-2, -1, 0, 1, 2] to the first two regressors and [-1, 1] to every other. A continuous regressor is a level set with many values, e.g. np.linspace(-1, 1, 101); the grid of combinations is never materialised, so many continuous regressors cost no memory. With condition_independent=True every level set needs at least two values (a constant column is collinear with the intercept).

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 len has one per regressor and the constant term); without it the intercept uses the default 2.0.

2.0
amplitude float or sequence of float

Standard deviation of the weight entries (the reference's rho), >= 0. Same per-regressor layout as length_scale; the intercept default is 1.0.

1.0
noise_precision float or array_like of shape (n_neurons,)

Noise precision (inverse variance) per neuron, > 0. None draws each from an Exponential distribution with mean 1.25, as the demo does (the reference's d; docs/model.md § D.3).

None
drop_prob float

Probability, in [0, 1), that a neuron is unobserved on a trial, before the validity conditioning (Notes).

0.0
condition_independent bool

Add the intercept. Must be a bool (NumPy booleans included).

True
regressor_names sequence of str

Names in X column order; default ("x0", "x1", ...). Not allowed when ranks is a mapping. Unique; "intercept" and "total" are reserved.

None
seed (int, Generator, SeedSequence or None)

Seed for numpy.random.default_rng, or a generator, which is advanced.

None
X array_like

(n_trials, n_regressors) design to use instead of drawing trials from the level grid (keyword-only). Real (not bool) and finite, with exactly n_trials rows and one column per entry of ranks; with condition_independent=True no column may be constant (it would be collinear with the intercept). levels must then be None: the returned levels are each column's distinct values and condition_of_trial indexes the distinct rows of X.

None
S sequence or mapping of array_like

Temporal bases to use instead of the GP draws (keyword-only): an (n_bins, r_p) array per regressor (a 1-D array is one column), either a sequence in regressor order whose None entries are drawn, or a mapping from regressor names, the unnamed ones drawn. Each width must equal its entry of ranks. A supplied regressor's length_scale entry is unused.

None
W sequence or mapping of array_like

Neuron weights to use instead of the normal draws (keyword-only): an (n_neurons, r_p) array per regressor, laid out as S. A supplied regressor's amplitude entry is unused.

None

Returns:

Type Description
SimulatedData

Responses, design, mask and ground truth.

Raises:

Type Description
ParameterError

For an invalid argument: wrong types; mismatched lengths of ranks, levels, length_scale, amplitude or regressor_names; a rank outside [0, min(n_neurons, n_bins)]; too few trials for the design; drop_prob outside [0, 1); scales so extreme that the simulated values are not finite; a mask that cannot satisfy the validity promise in 100 draws; or a supplied X, S or W of the wrong type, shape or names, non-finite, or (X) with a constant column next to the intercept, or given together with levels.

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)