Skip to content

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_design reports, without raising, what fit would reject or warn about in a design;
  • condition_average averages trials within conditions under the mask (a masked mean; for pseudo-trial resampling see the Nature Neuroscience supplement, §6.1);
  • stack_sessions assembles sequentially recorded sessions into one union-trial tensor with a block-diagonal mask, the observation model (M3), (M9) the estimators are written for;
  • split_trials draws 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 X.

n_regressors int

Columns of X.

regressor_names tuple of str

Names of the columns.

means ndarray

(P,) column means over the design rows (the trials with an observed neuron when a mask is given).

stds ndarray

(P,) population standard deviations of the columns over the same rows.

constant ndarray

(P,) bool, columns that take one value.

rank int

Rank of X by the scale-invariant test of validate_inputs.

augmented_rank int

Rank of [X, 1] (shift-invariant: one plus the rank of the centred columns).

duplicate_columns list of tuple of int

Pairs (a, b), a < b, of exactly collinear columns.

condition_number float

2-norm condition number of the design the per-neuron solves see: the columns centred when condition_independent=True, each scaled to unit norm (inf when singular). Scale-free, so it measures collinearity, not column scale.

max_abs_correlation float

Largest absolute correlation between two non-constant columns (0 with fewer than two).

few_trial_neurons ndarray

(n_flagged,) int, neurons observed on fewer than min_observations trials (empty without a mask).

rank_deficient_neurons ndarray

(n_flagged,) int, observed neurons whose own design [X_i, 1] (X_i without the intercept) is rank-deficient by fit_svd's test, at the given ridge (empty without a mask).

empty_trials ndarray

(n_flagged,) int, trials with no observed neuron (empty without a mask).

problems list of str

What fit would raise on.

warnings list of str

What fit would warn about with the same basis_ridge and ridge.

notes list of str

What fit stays silent about: uncentred continuous columns and, at basis_ridge == 0, scale disparities.

ConditionAverage dataclass

Condition-averaged data from condition_average.

Attributes:

Name Type Description
Y ndarray

(n_conditions, n_neurons, n_bins) masked means; NaN where the neuron has fewer than min_trials trials in the condition.

X ndarray

(n_conditions, n_regressors): each condition's regressor values (the by columns), and the unweighted mean over its trials for the others.

mask ndarray

(n_conditions, n_neurons) bool, the neuron has at least min_trials trials in the condition.

counts ndarray

(n_conditions, n_neurons) int, observed trials per neuron and condition (informational; project does not weight by it).

condition_of_trial ndarray

(n_trials,) int, the row of each input trial.

StackedSessions dataclass

Sessions assembled by stack_sessions.

Attributes:

Name Type Description
Y ndarray

(sum K_s, sum n_s, T); NaN off the block diagonal.

X ndarray

(sum K_s, P), the sessions' designs stacked.

mask ndarray

(sum K_s, sum n_s) bool, block-diagonal (each block AND-ed with the session's own mask).

session_of_trial ndarray

(sum K_s,) int, the session of each trial (row).

session_of_neuron ndarray

(sum n_s,) int, the session of each neuron (column).

trial_index_in_session ndarray

(sum K_s,) int, each trial's position within its session.

neuron_index_in_session ndarray

(sum n_s,) int, each neuron's position within its session.

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).

  • Y must be 3-D (n_trials, n_neurons, n_bins) with non-empty axes and a real dtype; it is converted to float64 (a copy only if needed).
  • Without a mask, a neuron-trial with any NaN bin is unobserved: mask[k, i] = not np.isnan(Y[k, i, :]).any(). With a mask (boolean or exactly 0/1), a NaN or Inf under True is an error; values under False are 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

(n_trials, n_neurons, n_bins) responses; NaN allowed as above.

required
X array_like

(n_trials, n_regressors) design, no constant column; None where a method has no design (project).

None
mask array_like

(n_trials, n_neurons) observation mask; None infers it from NaN.

None
for_fit bool

Apply the fit-only checks.

False
condition_independent bool

Whether the model has the intercept; with False constant columns are allowed.

True
min_observations int

The per-neuron observation floor, positive (MTDR passes max(min_observations, n_regressors + 2) for "mmle").

2

Returns:

Name Type Description
Y ndarray

float64, the input's shape.

X ndarray or None

float64, or None when not given.

mask ndarray

bool, (n_trials, n_neurons).

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 for_fit, condition_independent or min_observations.

Warns:

Type Description
DesignWarning

With for_fit=True, once, listing the trials with no observed neuron.

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

(n_trials, n_regressors) design, finite.

required
mask array_like

(n_trials, n_neurons) observation mask, boolean or 0/1.

None
regressor_names sequence of str

Column names, ("x0", "x1", ...) by default.

None
condition_independent bool

Whether the model has the intercept.

True
basis_ridge float

>= 0; scale disparities are warnings only when positive.

0.0
min_observations int

The per-neuron observation floor (keyword-only), raised as fit raises it when estimator="mmle".

2
ridge float

>= 0, the least-squares ridge, which removes per-neuron rank deficiency (keyword-only).

0.0
estimator ('mmle', 'svd')

The estimator whose observation floor to apply (keyword-only); None applies min_observations as given.

"mmle"

Returns:

Type Description
DesignReport

The findings; str(report) prints a table.

Raises:

Type Description
ValidationError

If X is not a finite 2-D real array, or the mask has the wrong shape or values.

ParameterError

For bad names, basis_ridge, ridge, min_observations or estimator.

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

(n_trials, n_neurons, n_bins), as validate_inputs (NaN allowed).

required
X array_like

(n_trials, n_regressors).

required
mask array_like

(n_trials, n_neurons); None infers it from NaN.

None
by sequence of int or of str

Columns of X that define a condition, by index or by name; None uses every column. Continuous regressors should be binned first.

None
regressor_names sequence of str

Names of the columns of X, needed when by holds names (("x0", ...) by default).

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 validate_inputs.

ParameterError

For unknown or repeated by columns, bad names or min_trials.

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 (Y_s, X_s) or (Y_s, X_s, mask_s), Y_s of shape (K_s, n_s, T) and X_s (K_s, P), with the same T and P.

required

Returns:

Type Description
StackedSessions

The stacked arrays and the index maps back to the sessions.

Raises:

Type Description
ParameterError

If sessions is not a non-empty sequence of 2- or 3-tuples.

ValidationError

If a session's arrays are invalid (as validate_inputs) or the sessions disagree on T or P.

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, 1).

0.2
random_state (int, Generator or None)

Seed (non-negative) or generator (numpy.random.default_rng).

None
stratify array_like

(n_trials,) labels, e.g. condition_of_trial or session_of_trial (for a joint stratification pass a combined label).

None

Returns:

Name Type Description
train ndarray

Sorted int64 training-trial indices.

test ndarray

Sorted int64 test-trial indices; with train a partition of range(n_trials).

Raises:

Type Description
ParameterError

For a bad n_trials, test_fraction, random_state or stratify.

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)