Data utilities¶
Simulating non-simultaneously recorded sessions¶
To test a pipeline on sessions recorded one after another, simulate one
population and partition its neurons and trials into sessions, then stack them with
stack_sessions. Separate simulate calls draw separate
temporal bases, so their sessions would not share one mTDR model.
from mtdr import MTDR, simulate, split_trials, stack_sessions
# One population of 120 neurons and 360 trials, cut into three sessions of
# 40 neurons and 120 trials each.
sim = simulate(
n_neurons=120, n_bins=8, n_trials=360, ranks=[2, 1, 2], drop_prob=0.2, seed=42
)
sessions = []
for s in range(3):
trials, neurons = slice(120 * s, 120 * (s + 1)), slice(40 * s, 40 * (s + 1))
sessions.append((sim.Y[trials, neurons], sim.X[trials], sim.mask[trials, neurons]))
stacked = stack_sessions(sessions) # Y (360, 120, 8), a block-diagonal mask
train, test = split_trials(
stacked.Y.shape[0], random_state=0, stratify=stacked.session_of_trial
)
model = MTDR(ranks=[2, 1, 2]).fit(
stacked.Y[train], stacked.X[train], mask=stacked.mask[train]
)
print(model.ranks_, model.n_neurons_, stacked.mask.sum(axis=1).max())
Each neuron is then observed only on its own session's trials, and every trial sees only its session's neurons, as in the recorded data.
Reference¶
mtdr.data
¶
Input validation and data utilities.
Everything the MTDR estimator reads goes through
validate_inputs first: the layout
Y[k, i, t], X[k, p], mask[k, i] (docs/model.md § 1.2), NaN-to-mask
inference, and the fit-only checks on neurons and designs that the
estimators cannot fit. The other functions here prepare data for the
estimator and never fit anything:
check_designreports, without raising, whatfitwould reject or warn about in a design;condition_averageaverages trials within conditions under the mask (a masked mean; for pseudo-trial resampling see the Nature Neuroscience supplement, §6.1);stack_sessionsassembles sequentially recorded sessions into one union-trial tensor with a block-diagonal mask, the observation model (M3), (M9) the estimators are written for;split_trialsdraws a trial split for held-out comparisons.
The package never centres or rescales X or Y.
DesignReport
dataclass
¶
What check_design found.
Attributes:
| Name | Type | Description |
|---|---|---|
n_trials |
int
|
Rows of |
n_regressors |
int
|
Columns of |
regressor_names |
tuple of str
|
Names of the columns. |
means |
ndarray
|
|
stds |
ndarray
|
|
constant |
ndarray
|
|
rank |
int
|
Rank of |
augmented_rank |
int
|
Rank of |
duplicate_columns |
list of tuple of int
|
Pairs |
condition_number |
float
|
2-norm condition number of the design the per-neuron solves see: the
columns centred when |
max_abs_correlation |
float
|
Largest absolute correlation between two non-constant columns (0 with fewer than two). |
few_trial_neurons |
ndarray
|
|
rank_deficient_neurons |
ndarray
|
|
empty_trials |
ndarray
|
|
problems |
list of str
|
What |
warnings |
list of str
|
What |
notes |
list of str
|
What |
ConditionAverage
dataclass
¶
Condition-averaged data from condition_average.
Attributes:
| Name | Type | Description |
|---|---|---|
Y |
ndarray
|
|
X |
ndarray
|
|
mask |
ndarray
|
|
counts |
ndarray
|
|
condition_of_trial |
ndarray
|
|
StackedSessions
dataclass
¶
Sessions assembled by stack_sessions.
Attributes:
| Name | Type | Description |
|---|---|---|
Y |
ndarray
|
|
X |
ndarray
|
|
mask |
ndarray
|
|
session_of_trial |
ndarray
|
|
session_of_neuron |
ndarray
|
|
trial_index_in_session |
ndarray
|
|
neuron_index_in_session |
ndarray
|
|
validate_inputs(Y, X=None, mask=None, *, for_fit=False, condition_independent=True, min_observations=2)
¶
Validate (Y, X, mask) and return them as float64, float64, bool.
What MTDR.fit (with for_fit=True) and every
evaluation method run first. It never drops or reorders trials: the
returned arrays have the input's trial count, and the returned mask is the
observation pattern \(h_{ki}\) of (M3).
Ymust be 3-D(n_trials, n_neurons, n_bins)with non-empty axes and a real dtype; it is converted tofloat64(a copy only if needed).- Without a
mask, a neuron-trial with anyNaNbin is unobserved:mask[k, i] = not np.isnan(Y[k, i, :]).any(). With amask(boolean or exactly 0/1), aNaNorInfunderTrueis an error; values underFalseare ignored. X, when given, must be 2-D(n_trials, n_regressors), real, finite, with at least one column.
With for_fit=True it also applies the fit-only checks: a neuron
observed on fewer than min_observations trials (never observed
included), a neuron whose observed entries are all equal, a pooled X
whose rank is below its column count, and, with
condition_independent=True, a constant column of X or a combination
of columns that is constant (collinear with the intercept), are
ValidationErrors; a trial with no observed neuron is kept with one
DesignWarning. The pooled design checks use
the trials with at least one observed neuron, and every rank test is
scale- and shift-invariant: a set of columns is rank-deficient when an
eigenvalue of its unit-diagonal Gram is at most svd_fit.RANK_TOLERANCE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
X
|
array_like
|
|
None
|
mask
|
array_like
|
|
None
|
for_fit
|
bool
|
Apply the fit-only checks. |
False
|
condition_independent
|
bool
|
Whether the model has the intercept; with |
True
|
min_observations
|
int
|
The per-neuron observation floor, positive ( |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
Y |
ndarray
|
|
X |
ndarray or None
|
|
mask |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
For any of the data errors above (the message names the offending shape, neurons or columns and states the expected layout). |
ParameterError
|
For a bad |
Warns:
| Type | Description |
|---|---|
DesignWarning
|
With |
Examples:
>>> import numpy as np
>>> from mtdr import validate_inputs
>>> Y = np.zeros((3, 2, 4))
>>> Y[1, 0, 2] = np.nan # neuron 0 unobserved on trial 1
>>> Y_out, X_out, mask = validate_inputs(Y, np.array([[1.0], [-1.0], [0.0]]))
>>> mask
array([[ True, True],
[False, True],
[ True, True]])
check_design(X, mask=None, regressor_names=None, condition_independent=True, basis_ridge=0.0, *, min_observations=2, ridge=0.0, estimator=None)
¶
Report what fit would reject or warn about in a design, without raising.
Runs the hard checks fit applies to the pooled design (a pooled X of
rank below its column count; with condition_independent=True a constant
column, or a combination of columns that is constant, collinear with the
intercept of docs/model.md § 2) and adds soft diagnostics. With a
mask it also runs the per-neuron checks: neurons below the observation
floor, neurons whose observed design [X_i, 1] is rank-deficient (the
per-neuron Gram \(A_i\) of (M6) by fit_svd's scale-invariant test, at the
given ridge), and trials with no observed neuron. warnings lists what
fit would warn about with the same basis_ridge and ridge; notes
what it stays silent about, so the two never disagree with fit.
Zero-variance neurons need Y and are reported by
validate_inputs.
The observation floor is min_observations when estimator is None.
With estimator, it is the floor MTDR.fit
applies for that estimator, by the same calculation: min_observations
for "svd", and
\(\max(\texttt{min\_observations},\,P+1+\mathbf 1_{\rm intercept})\) for
"mmle", below which a neuron keeps no residual degree of freedom and its
marginal likelihood (M24) is unbounded. Pass the same
condition_independent and min_observations as to MTDR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array_like
|
|
required |
mask
|
array_like
|
|
None
|
regressor_names
|
sequence of str
|
Column names, |
None
|
condition_independent
|
bool
|
Whether the model has the intercept. |
True
|
basis_ridge
|
float
|
|
0.0
|
min_observations
|
int
|
The per-neuron observation floor (keyword-only), raised as |
2
|
ridge
|
float
|
|
0.0
|
estimator
|
('mmle', 'svd')
|
The estimator whose observation floor to apply (keyword-only); |
"mmle"
|
Returns:
| Type | Description |
|---|---|
DesignReport
|
The findings; |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
ParameterError
|
For bad names, |
Examples:
>>> import numpy as np
>>> from mtdr import check_design
>>> rng = np.random.default_rng(0)
>>> X = np.column_stack([rng.normal(size=50), np.ones(50)])
>>> report = check_design(X, regressor_names=["coherence", "bias"])
>>> report.constant.tolist(), report.rank, report.augmented_rank
([False, True], 2, 2)
>>> print(report.problems[0])
column(s) ['bias'] constant: collinear with the intercept; drop it or pass
condition_independent=False
The "mmle" floor, with three regressors and the intercept, is 5 trials:
>>> mask = np.ones((50, 3), dtype=bool)
>>> mask[4:, 0] = False # neuron 0 seen on 4 trials
>>> X3 = rng.normal(size=(50, 3))
>>> check_design(X3, mask).few_trial_neurons.tolist()
[]
>>> report = check_design(X3, mask, estimator="mmle")
>>> report.few_trial_neurons.tolist()
[0]
>>> print(report.problems[0])
neurons [0] are observed on fewer than 5 trials, the "mmle" floor
n_regressors + 2 (above min_observations = 2)
condition_average(Y, X, mask=None, by=None, regressor_names=None, min_trials=1)
¶
Average trials within conditions, per neuron, over its observed trials.
Conditions are the unique rows of X[:, by], ordered as
numpy.unique(X[:, by], axis=0) orders them (lexicographic); for neuron
\(i\) and condition \(c\) the average is
\(\bar Y_{ci}=\frac1{n_{ci}}\sum_{k\in c}h_{ki}Y_{ki\cdot}\) with
\(n_{ci}=\sum_{k\in c}h_{ki}\) its observed trials there, \(h\) the mask of
(M3). A neuron with fewer than min_trials trials in a condition has
mask False and Y NaN there; every condition row is kept, so
conditions line up across neurons and calls. The result plugs into
MTDR.project with its mask. This is a masked
mean; pseudo-trial resampling is described in the
Nature Neuroscience supplement, §6.1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
X
|
array_like
|
|
required |
mask
|
array_like
|
|
None
|
by
|
sequence of int or of str
|
Columns of |
None
|
regressor_names
|
sequence of str
|
Names of the columns of |
None
|
min_trials
|
int
|
Positive; the per-neuron, per-condition trial floor. |
1
|
Returns:
| Type | Description |
|---|---|
ConditionAverage
|
The averaged arrays, read-only. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
As |
ParameterError
|
For unknown or repeated |
Examples:
>>> import numpy as np
>>> from mtdr import condition_average
>>> Y = np.arange(4.0).reshape(4, 1, 1) # 4 trials, 1 neuron, 1 bin
>>> X = np.array([[1.0], [-1.0], [1.0], [-1.0]])
>>> avg = condition_average(Y, X)
>>> avg.X.ravel().tolist(), avg.Y.ravel().tolist(), avg.condition_of_trial.tolist()
([-1.0, 1.0], [2.0, 1.0], [1, 0, 1, 0])
stack_sessions(sessions)
¶
Stack sequentially recorded sessions into one block-diagonal dataset.
Session \(s\) contributes its trials and its neurons; a neuron of session
\(s\) is observed only on session \(s\)'s trials, so the mask is
block-diagonal and every neuron has its own trial set and its own
\(X_i^\top X_i\): exactly the observation model (M3), (M9) the estimators
are written for. Each session's mask is the given one or inferred from
NaN. The trial axis of the result is the union of the sessions' trials,
so memory grows as \(8\,\sum_sK_s\,\sum_sn_s\,T\) bytes. The regressors must
mean the same thing in every session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sessions
|
sequence of tuples
|
Each |
required |
Returns:
| Type | Description |
|---|---|
StackedSessions
|
The stacked arrays and the index maps back to the sessions. |
Raises:
| Type | Description |
|---|---|
ParameterError
|
If |
ValidationError
|
If a session's arrays are invalid (as |
Examples:
>>> import numpy as np
>>> from mtdr import stack_sessions
>>> a = (np.ones((3, 2, 5)), np.array([[1.0], [-1.0], [1.0]]))
>>> b = (np.zeros((2, 1, 5)), np.array([[-1.0], [1.0]]))
>>> st = stack_sessions([a, b])
>>> st.Y.shape, st.mask.astype(int).tolist()
((5, 3, 5), [[1, 1, 0], [1, 1, 0], [1, 1, 0], [0, 0, 1], [0, 0, 1]])
>>> st.session_of_neuron.tolist(), st.trial_index_in_session.tolist()
([0, 0, 1], [0, 1, 2, 0, 1])
split_trials(n_trials, test_fraction=0.2, random_state=None, stratify=None)
¶
Split trial indices into a training and a test set.
Without stratify, round(test_fraction * n_trials) trials (at least one
in each half) go to the test set at random. With stratify, each label's
trials are split the same way, so each label's proportion is
approximately preserved in both halves: a label with a single trial goes
to the training half (one DesignWarning
lists such labels), a label with two trials goes one each way. The
function sees no mask, so it cannot promise that every neuron is observed
in both halves; check mask[train].any(0) and mask[test].any(0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_trials
|
int
|
Number of trials, at least 2. |
required |
test_fraction
|
float
|
In |
0.2
|
random_state
|
(int, Generator or None)
|
Seed (non-negative) or generator ( |
None
|
stratify
|
array_like
|
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
train |
ndarray
|
Sorted |
test |
ndarray
|
Sorted |
Raises:
| Type | Description |
|---|---|
ParameterError
|
For a bad |
Warns:
| Type | Description |
|---|---|
DesignWarning
|
When a stratification label has a single trial. |
Examples:
>>> import numpy as np
>>> from mtdr import split_trials
>>> train, test = split_trials(10, test_fraction=0.3, random_state=0)
>>> both = np.concatenate([train, test])
>>> len(train), len(test), sorted(both.tolist()) == list(range(10))
(7, 3, True)