Skip to content

The MTDR estimator

converged_=False: what it means and what to do

For MMLE, converged_=False means that at least one optimisation step did not pass the package's convergence checks. The fitted parameters are still returned, but inspect the ConvergenceWarning and check the fit before interpreting the results. The flag stays False if an earlier step failed, even when later steps finish normally. True means the checks passed; it does not guarantee a global optimum.

The warning identifies the step and the reason. Start with the corresponding action:

Warning mentions Meaning and action
An iteration cap Raise the named limit: ecme_max_iter, refine_max_iter or optimizer_max_iter, then refit.
ABNORMAL or L-BFGS-B status 2 The optimiser could not find an acceptable next step. Check input conditioning with check_design, then assess a refit as below.
A result was not finite or raised the objective That inner optimiser result was discarded and the previous parameters kept. Check input scales and design conditioning before refitting.
A neuron ended on the precision step bound Its estimated noise precision reached the step limit. Inspect the named neurons for very small residual variation.
ECME raised the marginal NLL An ECME update worsened the fit beyond the rounding allowance. Assess a refit; this warning is not covered by the inner optimiser's rule for discarding steps.

Line searches that stop because further improvement is below numerical precision can pass the convergence checks without a warning. The criteria are in model §E.3.

In a rank search, converged_ describes the selected fit. The warning also lists other candidate fits that failed. Their failures can affect rank selection even when the selected fit converged.

To assess the result, fit again at the selected ranks with a tighter stopping tolerance and more refinement iterations. Use the same data and mask, and preserve the original settings, including regularisation and preconditioning:

params = model.get_params()
params.update(
    ranks=model.ranks_,
    refine_tol=min(model.refine_tol, 1e-8),
    refine_max_iter=max(model.refine_max_iter, 50),
)
refit = MTDR(**params).fit(Y, X, mask, regressor_names=model.regressor_names_)
print(model.objective_, refit.objective_)  # higher is better

Also raise any limit named in the warning. Compare objective_ and the coefficient matrices B_, and inspect any new warnings. At basis_ridge=0, objective_ equals the marginal training log_likelihood_; otherwise it includes the penalty. A substantial objective gain shows that the original fit could be improved. Similar objectives and coefficients provide evidence of stability, rather than proof of an optimum.

This is a new fit, not a continuation. A fixed-rank fit starts from its own SVD estimate, whereas the default rank search starts candidates from the preceding accepted fit. The refit can therefore reach a different result, including a lower objective. A substantial difference warrants checking sensitivity to initialisation; rank_search_warm_start=False makes each search candidate start from its own SVD estimate too. A fixed-rank check assesses the fit at those ranks; it does not check whether failed candidates changed the rank-search outcome.

Plain per-neuron least squares

The natural baseline, ordinary least squares per neuron with the intercept, is the "svd" estimator at full rank, where the truncation removes nothing:

P = X.shape[1]
ols = MTDR(ranks=[min(n_neurons, n_bins)] * P, estimator="svd").fit(Y, X, mask)
ols.B_  # each neuron's least-squares coefficients, regressor by regressor

The full rank is min(n_neurons, n_bins), not n_bins: a rank above it is a ParameterError, so [n_bins] * P fails when there are fewer neurons than bins. Under a mask each neuron's fit uses only its observed trials; with ridge > 0 it is ridge regression.

Reference

mtdr.model

The MTDR estimator.

MTDR composes the package's functional building blocks: validate_inputs, the sufficient statistics of mtdr.stats, the SVD estimator of mtdr.svd_fit, the marginal-likelihood estimator of mtdr.mmle and the greedy AIC search of mtdr.rank_search. It fits

\[ Y[k] = \text{intercept} + \sum_p X[k,p]\,W_pS_p^\top + E_k,\qquad E_k[i,:]\sim\mathcal N\big(0,\lambda_i^{-1}I\big), \]

(M1)-(M4), under the observation mask (M3), and derives from the fit the projections (M49)-(M49a), the plug-in decoder (M46)-(M48c) and the held-out plug-in likelihood. Per-regressor results are dicts keyed by regressor name, in X column order.

MTDR

Model-based targeted dimensionality reduction.

Fits, for every regressor \(p\), a low-rank coefficient matrix \(B_p=W_pS_p^\top\) ((n_neurons, n_bins), rank \(r_p\)), a per-neuron noise precision \(\lambda_i\) and, by default, a full-rank condition-independent intercept, (M1)-(M4). estimator="mmle" (the default, the estimator of the paper) integrates the weights out under \(w_i\sim\mathcal N(0,I)\) and maximises the marginal likelihood (M24) by ECME and coordinate ascent (docs/model.md § 5), then sets W_ to the posterior mean (M36); estimator="svd" is reduced-rank regression, (M15)-(M18). ranks="aic" chooses the ranks by the greedy AIC search (M39).

The constructor only stores and checks hyper-parameters (sklearn style); fit learns, and fitted attributes end in _. Fitting is deterministic: there is no random state.

Parameters:

Name Type Description Default
ranks "aic", sequence of int or mapping of str to int

"aic" chooses every rank by AIC (positive ranks only); a sequence (one per column of X) or a mapping naming every regressor fixes them; 0 removes a regressor's term.

'aic'
estimator ('mmle', 'svd')

The marginal-likelihood estimator (default) or reduced-rank regression.

"mmle"
condition_independent bool

Fit the full-rank intercept. False only for Y already mean-subtracted per neuron and bin.

True
max_rank int

Largest rank the search may assign (and a bound on fixed ranks); None is min(n_neurons, n_bins).

None
min_observations int

A neuron observed on fewer trials is a ValidationError in fit; under "mmle" the floor applied is at least n_regressors + 2 (n_regressors + 1 without the intercept), below which a neuron has no residual degree of freedom and its marginal likelihood is unbounded.

2
ridge float

L2 penalty on every neuron's \(X_i^\top X_i\) in the least-squares stage.

0.0
basis_ridge float

L2 penalty \(\tfrac g2\lVert S\rVert^2\) on the bases ("mmle" only).

0.0
rank_search_init ('svd_weighted', 'svd', 'ones')

Where the search starts: "svd_weighted" runs the AIC search of the precision-weighted SVD fit (M18w) from ones and starts the MMLE search at its ranks; "svd" the same with the unweighted fit, as the reference does; "ones" a single MMLE search from ones; a sequence of positive ints starts there. With estimator="svd" the strings coincide (one unweighted SVD search from ones).

"svd_weighted"
rank_search_threshold float

\(\delta\ge0\): a step is accepted only if it lowers the AIC by more.

0.0
rank_search_warm_start bool

Start each candidate of the MMLE search from the accepted fit instead of from its own SVD fit: the accepted bases, noise precisions and intercept, plus, for the raised regressor, the last component of the unweighted SVD fit at the candidate's ranks. The search's first fit stays cold. About 6x fewer basis-step evaluations per candidate at the paper's scale and no change in any selected rank vector measured, so the default; False is the reference's procedure, an SVD start per candidate (M29). No effect with estimator="svd" or fixed ranks.

True
ecme_max_iter int

ECME's iteration cap (docs/model.md § C.6).

100
ecme_tol float

ECME's threshold on the largest squared relative change of a parameter in an iteration, (M34) with convergence_eps added to each denominator (docs/model.md § C.6).

1.0
refine_max_iter int

The coordinate ascent's iteration cap (docs/model.md § C.7).

10
refine_tol float

The coordinate ascent's threshold on the same change (docs/model.md § C.7).

0.0001
convergence_eps float

The term added to each \(\theta_j^2\) in that change, in both loops, so that a parameter that is exactly zero does not make it infinite.

1e-12
optimizer_max_iter int

maxiter of the inner L-BFGS-B runs (default 2000: the first basis step at the paper's scale needs 582-909 iterations).

2000
optimizer_tol float

Their projected-gradient test gtol, minFunc's optTol (the reference's is \(10^{-5}\)). With basis_preconditioning=True the basis step tests it on the rescaled gradient.

1e-06
optimizer_progtol float

The absolute function change at which the inner basis step stops, minFunc's progTol (default \(10^{-9}\)).

1e-09
canonicalize bool

Rotate each \((W_p,S_p)\) into the PC orientation after fitting (docs/model.md § 10.1): W_[p] orthonormal, ordered by singular value, largest entry of each column positive; S_[p] carries the scale. Likelihoods and AIC are computed in the raw frame before the rotation.

True
verbose int

0 silent; 1 one line per accepted rank-search step; 2 also per ECME and refinement iteration.

0
n_jobs int or None

Worker processes for the candidate fits of each round of the MMLE rank search: None or 1 fits them in turn, -1 uses every CPU available to the process. A round has one candidate per regressor below max_rank, so no more workers than that are started, and none for one. The workers are started by spawn when the MMLE search begins, so they start up during its first fit, which they cannot share; each runs its linear algebra on one thread (the OPENBLAS_NUM_THREADS-like variables are 1 while they start), without which the workers compete and gain nothing. The search, the fit and the warnings are those of n_jobs=1 up to the rounding of the BLAS's thread count (identical bit for bit on the builds measured; a near-tie between candidates could in principle resolve differently). The workers import mtdr afresh: the caller's numpy.seterr is passed on, changes made to mtdr's modules at run time are not. At the paper's scale on 4 CPUs a round runs about 2.3-2.9x faster and a search about 1.3-1.5x. A script that uses it needs the if __name__ == "__main__": guard that multiprocessing requires; if the workers cannot start (a daemonic process) or stop (no guard, a dead worker), the candidates are fitted in turn, with a RuntimeWarning. With verbose=2, a round's iteration lines are printed together when it ends, in regressor order. No effect with estimator="svd", on the SVD stage of rank_search_init, or with fixed ranks.

None
basis_preconditioning bool

Speed up the MMLE refinement's basis step in every cold fit, one that starts from its own SVD fit: the fixed-rank fit, the MMLE search's first fit and, with rank_search_warm_start=False, every candidate. Warm- started candidates are never preconditioned. This has no MATLAB counterpart: False is the reference's basis step, minFunc on the raw bases (Estpars_CoordAscent_lambi_S_b.m). With True, L-BFGS-B works in rescaled variables in which each regressor's directions inside the span of its starting bases are stretched by a fixed factor of 30 (mtdr.mmle.BASIS_SPAN_SCALE; use fit_mmle(basis_span_scale=) for another value). The likelihood is nearly flat along those directions, where an unscaled run spends about half its evaluations. The objective is unchanged, so the fit ends at the same optimum to within the optimiser's tolerance; at the paper's scale a cold fit takes about 7x fewer basis-step evaluations and a whole search runs 1.3-1.8x faster with the same ranks. Because the path differs, results differ from False's at the optimiser's tolerance, and optimizer_tol is then tested on the rescaled gradient. Off by default. No effect with estimator="svd".

False

Attributes:

Name Type Description
regressor_names_ tuple of str

Names in X column order; the keys of every per-regressor dict.

n_trials_ int

Trials seen in fit.

n_neurons_ int

Neurons seen in fit.

n_bins_ int

Time bins seen in fit.

n_regressors_ int

Columns of X.

n_observations_ ndarray

(n_neurons,) int, the trials on which each neuron was observed (the mask's column sums).

ranks_ dict of str to int

The rank \(r_p\) of every regressor, chosen or fixed.

total_rank_ int

\(\sum_pr_p\).

W_ dict of str to numpy.ndarray

(n_neurons, r_p) neuron weights. With canonicalize=True the orthonormal encoding-subspace basis \(U_p\); otherwise the posterior mean (M36) in the estimator's frame ("mmle") or the left factor of (M17) ("svd"). (n_neurons, 0) at rank 0.

S_ dict of str to numpy.ndarray

(n_bins, r_p) temporal bases. With canonicalize=True, \(V_p\Sigma_p\): column \(j\) has norm \(\sigma_j\), the \(j\)-th singular value of \(B_p\). A display frame: never pass it to mtdr.mmle.

B_ dict of str to numpy.ndarray

(n_neurons, n_bins) coefficient matrices \(B_p=W_pS_p^\top\) (M1); frame-independent.

intercept_ ndarray or None

(n_neurons, n_bins) condition-independent term; None with condition_independent=False.

noise_precision_ ndarray

(n_neurons,) noise precisions \(\lambda_i\) (inverse variances).

weight_posterior_cov_ ndarray or None

"mmle": (n_neurons, total_rank_, total_rank_), the posterior covariance \(C_i^{-1}\) of neuron \(i\)'s stacked weights (M25), (M36), in the frame of W_ (R.T @ Cov @ R in the canonical frame). None for "svd".

log_likelihood_ float

The training log-likelihood at the fit, fully normalised, in the raw frame. Under "mmle" it is the marginal likelihood (M24), the weights integrated out, and so is to_xarray()'s log_likelihood attribute; the method log_likelihood is the plug-in likelihood (M46), which differs from it on the same data. Under "svd" the plug-in likelihood of the least-squares fit (M21a). Not comparable across estimators; excludes the basis_ridge penalty.

objective_ float

What the fit maximised: log_likelihood_ less \(\tfrac g2\sum_p\lVert S_p\rVert_F^2\) (basis_ridge \(=g\)).

n_parameters_ int

The count in aic_: (M38a) for "mmle", (M21b) for "svd".

aic_ float

2 * n_parameters_ - 2 * log_likelihood_. Under "mmle" the rank search selects with the reference count (M38) instead, so rank_search_history_.aic holds scores that exceed aic_ by \(\sum_pr_p(r_p-1)\) at the same ranks.

rank_search_history_ RankSearchHistory or None

The record of the greedy AIC search (M39); None when the ranks were fixed.

estimator_ str

The estimator that produced the parameters, "mmle" or "svd".

converged_ bool

Whether every stage of the selected MMLE fit passed its convergence checks. False after an iteration cap, an ECME increase in the NLL, or an inner optimiser failure, rejected result or precision bound. Parameters are still returned; inspect the warning and check the fit as described in the MTDR docs page. True does not guarantee a global optimum. Always True for the SVD estimator.

n_iter_ dict of str to int

Iterations of "ecme" and "refine" in the final fit, summed over its calls of each (empty for "svd").

condition_independent_ bool

Whether the model has the intercept.

Raises:

Type Description
ParameterError

For an invalid hyper-parameter (checks that need the data happen in fit).

Notes

get_params / set_params follow the sklearn contract, so sklearn.base.clone works; sklearn's cross-validation utilities do not (fit(Y, X) takes the 3-D activity first). Fitted models pickle.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=40, n_bins=8, n_trials=200, ranks=[2, 1],
...                drop_prob=0.2, seed=0)
>>> model = MTDR(ranks=[2, 1]).fit(sim.Y_masked, sim.X,
...                                regressor_names=["stim", "choice"])
>>> model.ranks_, model.W_["stim"].shape, model.B_["choice"].shape
({'stim': 2, 'choice': 1}, (40, 2), (40, 8))
>>> MTDR(ranks="aic", estimator="svd", max_rank=4)
MTDR(estimator='svd', max_rank=4)

get_params(deep=True)

Return the hyper-parameters, as passed to the constructor (sklearn).

Parameters:

Name Type Description Default
deep bool

Ignored (no nested estimators); accepted for sklearn compatibility.

True

Returns:

Type Description
dict of str to object

Every constructor argument by name.

Examples:

>>> from mtdr import MTDR
>>> MTDR(ranks=[1, 2]).get_params()["ranks"]
[1, 2]

set_params(**params)

Set hyper-parameters by name and check them (sklearn).

Parameters:

Name Type Description Default
**params Any

Constructor arguments to change.

{}

Returns:

Type Description
MTDR

self.

Raises:

Type Description
ParameterError

For an unknown name or an invalid value (the previous values are kept).

Examples:

>>> from mtdr import MTDR
>>> MTDR().set_params(estimator="svd", max_rank=3)
MTDR(estimator='svd', max_rank=3)

fit(Y, X, mask=None, regressor_names=None)

Fit the model to Y given X.

In order: validate_inputs with the fit-only checks; the sufficient statistics (M6), (M10)-(M14); for ranks="aic" the greedy AIC search (M39) of the estimator(s) chosen by rank_search_init, else one fit at the fixed ranks; then the posterior weights (M36) ("mmle"), the coefficient matrices (M37), the raw-frame likelihood and AIC, and canonicalisation.

The MMLE search selects with the reference count (M38), \(n+T\sum_pr_p+nT\), and n_parameters_ / aic_ report the identifiable count (M38a); its history records the selection scores. The DesignWarnings of the candidate fits (rank-deficient neurons) are aggregated into one, and so are the ConvergenceWarnings of a search.

Parameters:

Name Type Description Default
Y array_like

(n_trials, n_neurons, n_bins); NaN allowed (see Notes).

required
X array_like

(n_trials, n_regressors), no constant column.

required
mask array_like

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

None
regressor_names sequence of str

Unique names; "intercept" and "total" are reserved. None takes the column names of an X that has string columns (a pandas DataFrame), in order, else ("x0", "x1", ...).

None

Returns:

Type Description
MTDR

self, fitted.

Raises:

Type Description
ValidationError

For invalid or degenerate data, including neurons below the observation floor, zero-variance neurons, a rank-deficient pooled X, a column collinear with the intercept, or a fitted neuron with zero residual.

ParameterError

For names of the wrong length or repeated; a ranks mapping that does not name exactly the regressors, a sequence of the wrong length, or a rank above max_rank; max_rank above min(n_neurons, n_bins).

LinAlgError

If a posterior precision \(C_i\) fails its Cholesky.

Warns:

Type Description
ConvergenceWarning

When a loop hit its cap or an inner optimiser failed.

DesignWarning

For rank-deficient neurons, trials with no observed neuron, near-collinear columns, column-scale disparities when basis_ridge > 0, and, under "mmle", continuous columns whose mean is more than one standard deviation from zero (the marginal likelihood depends on a column's origin, docs/model.md § 10.2).

Notes

fit cannot tell the neuron axis from the bin axis: Y laid out (n_trials, n_bins, n_neurons) fits without an error, with neurons and bins swapped, so check model.n_neurons_ and model.n_bins_ after fitting. The observation unit is the neuron-trial: without a mask, one NaN bin makes the whole neuron-trial unobserved, its finite bins included; impute partial NaNs first to keep those bins (with a mask, a NaN under True is an error).

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=60, n_bins=10, n_trials=300, ranks=[2, 1],
...                drop_prob=0.2, seed=3)
>>> model = MTDR(ranks="aic", max_rank=5).fit(sim.Y_masked, sim.X)
>>> model.ranks_, model.rank_search_history_.stop_reason
({'x0': 2, 'x1': 1}, 'no_improvement')

predict(X)

Return the expected response intercept_ + sum_p X[k, p] B_[p], (M1).

Parameters:

Name Type Description Default
X array_like

(n_trials, n_regressors), finite.

required

Returns:

Type Description
ndarray

(n_trials, n_neurons, n_bins), for every neuron on every trial (no mask; slice it yourself).

Raises:

Type Description
ValidationError

If X is not finite or has the wrong number of columns.

NotFittedError

Before fit.

Examples:

>>> import numpy as np
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> model.predict(sim.X[:3]).shape
(3, 20, 6)

log_likelihood(Y, X, mask=None, per_trial=False)

log_likelihood(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., per_trial: Literal[False] = ...) -> float
log_likelihood(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., *, per_trial: Literal[True]) -> FloatArray

Plug-in Gaussian log-likelihood of Y under the fit, fully normalised.

\(\ell=\sum_{(k,i):\,h_{ki}}\sum_t\big[\tfrac12\log\lambda_i-\tfrac12\log2\pi -\tfrac{\lambda_i}2(Y_{kit}-\hat Y_{kit})^2\big]\) with \(\hat Y\) from predict: (M46) with \(x\) the trial's regressors, summed over observed entries. Comparable across estimators, unlike log_likelihood_. Neurons must be the fitted ones in the same order; a neuron never observed in Y is allowed.

Parameters:

Name Type Description Default
Y array_like

(n_trials, n_neurons, n_bins), NaN allowed; the fitted neurons in the same order, trials may be held out.

required
X array_like

(n_trials, n_regressors), in the coding used at fit.

required
mask array_like

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

None
per_trial bool

Return the (n_trials,) per-trial sums instead (NaN for a trial with no observed neuron).

False

Returns:

Type Description
float or ndarray

The log-likelihood.

Raises:

Type Description
ValidationError

On a shape mismatch with the fit, or invalid data.

NotFittedError

Before fit.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> bool(abs(model.log_likelihood(sim.Y, sim.X) - model.log_likelihood_) < 1e-6)
True

score(Y, X, mask=None)

Return the plug-in log-likelihood (M46) summed over trials.

The same number as log_likelihood, for sklearn's convention (higher is better).

Parameters:

Name Type Description Default
Y array_like

(n_trials, n_neurons, n_bins), NaN allowed; the fitted neurons in the same order, trials may be held out.

required
X array_like

(n_trials, n_regressors), in the coding used at fit.

required
mask array_like

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

None

Returns:

Type Description
float

The plug-in log-likelihood.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> model.score(sim.Y, sim.X) == model.log_likelihood(sim.Y, sim.X)
True

aic()

Return aic_, 2 * n_parameters_ - 2 * log_likelihood_.

There is no data-taking form: an "AIC" from the plug-in likelihood and the "mmle" count would not be an AIC.

Returns:

Type Description
float

The training AIC ((M21b) for "svd", (M38a) for "mmle").

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> model.aic() == model.aic_
True

project(Y, regressor, mask=None, remove_intercept=True, weighted=True, method='gls', basis=None)

project(Y: ArrayLike, regressor: str, mask: ArrayLike | None = ..., remove_intercept: bool = ..., weighted: bool = ..., method: Literal['gls', 'paper'] = ..., basis: Mapping[str, ArrayLike] | None = ...) -> FloatArray
project(Y: ArrayLike, regressor: None, mask: ArrayLike | None = ..., remove_intercept: bool = ..., weighted: bool = ..., method: Literal['gls', 'paper'] = ..., basis: Mapping[str, ArrayLike] | None = ...) -> dict[str, FloatArray]

Project activity onto regressor subspaces: trajectories.

method="gls" (default, (M49a)): per trial \(k\) and bin \(t\), the weighted least-squares coordinates \(z=(U^\top D_kU)^{-1}U^\top D_k(y-\hat b)\) over the neurons observed on trial \(k\), \(U\) the basis (W_[regressor] in the model's frame, or basis), \(D_k\) their precisions (identity with weighted=False). method="paper": \(U^\top D(y-\hat b)\) (M49), without normalisation, over the observed neurons (Nature Neuroscience supplement, §7). regressor=None solves jointly on the concatenated bases of every regressor ("gls" only) and returns a dict.

A trial whose observed (weighted) basis lacks full column rank, at tolerance \(\sqrt\epsilon\) relative to its largest singular value, gets NaN coordinates and one ProjectionWarning counts them ("gls" only, where the inverse is taken). A trial with no observed neuron gives NaN without a warning.

Parameters:

Name Type Description Default
Y array_like

(n_trials, n_neurons, n_bins), NaN allowed.

required
regressor str or None

A regressor name, or None for the joint projection.

required
mask array_like

(n_trials, n_neurons).

None
remove_intercept bool

Subtract intercept_ first (when the model has one).

True
weighted bool

Weight neurons by noise_precision_ (False: unit weights).

True
method ('gls', 'paper')

See above.

"gls"
basis mapping of str to array_like

(n_neurons, r) bases replacing W_[name], e.g. from orthogonalize.

None

Returns:

Type Description
numpy.ndarray or dict of str to numpy.ndarray

(n_trials, n_bins, r), or one per regressor for regressor=None.

Raises:

Type Description
ParameterError

For an unknown regressor, a rank-0 regressor without a basis, a bad basis, method, or regressor=None with method="paper".

SingularDesignError

For regressor=None when the joint basis is rank-deficient (shared directions or total_rank_ > n_neurons), naming the regressors.

ValidationError

On a shape mismatch or invalid data.

Warns:

Type Description
ProjectionWarning

Once, with the number of trials whose basis was singular.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=30, n_bins=6, n_trials=150, ranks=[2, 1], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X)
>>> model.project(sim.Y, "x0").shape
(150, 6, 2)
>>> {k: v.shape for k, v in model.project(sim.Y, None).items()}
{'x0': (150, 6, 2), 'x1': (150, 6, 1)}

decode(Y, regressor=None, mask=None, known=None, levels=None, bins=None, return_log_likelihood=False, return_llr=False)

decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., return_log_likelihood: Literal[False] = ..., return_llr: Literal[False] = ...) -> dict[str, FloatArray]
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., *, return_log_likelihood: Literal[True], return_llr: Literal[False] = ...) -> tuple[dict[str, FloatArray], FloatArray]
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., *, return_log_likelihood: Literal[False] = ..., return_llr: Literal[True]) -> tuple[dict[str, FloatArray], FloatArray]
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., *, return_log_likelihood: Literal[True], return_llr: Literal[True]) -> tuple[dict[str, FloatArray], FloatArray, FloatArray]

Model-based maximum-likelihood decoding.

Following the Nature Neuroscience supplement, §6, for each trial return the regressor values that maximise the plug-in log-likelihood (M46) of its observed activity over the selected bins, given B_, intercept_ and noise_precision_. Every regressor (of positive rank) is either decoded or known. Continuous unknowns are solved jointly in closed form, (M47), or (M47a) given the known ones. Discrete unknowns (in levels) are decoded by the profile likelihood (M48a): for every combination of their levels (in itertools.product order over the decoded regressors, each in the given level order; at most 64), the continuous unknowns are re-solved and (M46) evaluated; the first maximising combination wins. With one two-level discrete regressor [a, b], the log-likelihood ratio \(\ell(b,\hat x_-\mid b)-\ell(a,\hat x_-\mid a)\) of (M48b) is available; scipy.special.expit(llr) is the supplement's normalised profile likelihood for level b. The decoder depends only on B_, so it is frame-independent.

A trial whose continuous-unknown normal matrix \(\Xi_\mathcal U^\top\Lambda\Xi_\mathcal U\) is singular or has a condition number above \(\epsilon^{-1/2}\) gets NaN outputs, and one DecodingWarning gives the count and the bins. A trial with no observed neuron is NaN too.

Parameters:

Name Type Description Default
Y array_like

(n_trials, n_neurons, n_bins), NaN allowed.

required
regressor str, sequence of str or None

The regressors to decode; None is every regressor not in known. Rank-0 regressors are ignored.

None
mask array_like

(n_trials, n_neurons).

None
known mapping of str to array_like

{name: (n_trials,)} values held fixed, in the coding used at fit.

None
levels mapping of str to sequence of float

Candidate values of decoded discrete regressors.

None
bins int, slice, sequence of int or None

The evidence window: one bin (the paper's instantaneous decoder), a slice, a list, or None for every bin.

None
return_log_likelihood bool

Also return the maximised log-likelihood (n_trials,), or the profile log-likelihoods (n_trials, n_combinations) when there are discrete unknowns (fully normalised).

False
return_llr bool

Also return the LLR (n_trials,) (second level minus first).

False

Returns:

Type Description
dict of str to numpy.ndarray, or tuple

{name: (n_trials,)} for every decoded regressor; with either flag, the tuple (values, log_likelihood, llr) restricted to the requested parts, in that order.

Raises:

Type Description
ParameterError

If a name is both decoded and known, a regressor is in neither, levels names a regressor not decoded, there are more than 64 level combinations, return_llr lacks exactly one two-level discrete regressor, every decoded regressor has rank 0, or bins is invalid.

ValidationError

On a shape mismatch or invalid data.

Warns:

Type Description
DecodingWarning

Once, when some trials' systems are singular.

Examples:

>>> import numpy as np
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=40, n_bins=8, n_trials=300, ranks=[2, 1],
...                levels=[[-1, 0, 1], [-1, 1]], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X,
...                                                  regressor_names=["s", "c"])
>>> out, llr = model.decode(sim.Y, ["s", "c"], levels={"c": [-1, 1]},
...                         return_llr=True)
>>> bool(np.mean(out["c"] == sim.X[:, 1]) > 0.9), llr.shape
(True, (300,))

explained_variance(Y, X, mask=None, per_bin=False)

explained_variance(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., per_bin: Literal[False] = ...) -> dict[str, float]
explained_variance(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., *, per_bin: Literal[True]) -> dict[str, FloatArray]

Fraction of observed variance each term explains.

For each term, \(1-\lVert Y-\hat Y_p\rVert^2/\lVert Y-\bar Y\rVert^2\) over the observed entries, with \(\bar Y_i\) neuron \(i\)'s mean over its observed trials and all bins and \(\hat Y_p\) the prediction that keeps only term \(p\): \(\bar Y+X_{:p}B_p\) for a regressor, intercept_ alone for "intercept" (present only when the model has one), and the full prediction (M1) for "total". Terms are not orthogonal, so the regressors' values need not add up to "total". On held-out trials \(\bar Y_i\) is the held-out data's own mean, not the training one, so the baseline is the best flat prediction of those trials and a held-out "total" is not a training-mean comparison.

Parameters:

Name Type Description Default
Y array_like

(n_trials, n_neurons, n_bins), NaN allowed; the fitted neurons in the same order, trials may be held out.

required
X array_like

(n_trials, n_regressors), in the coding used at fit.

required
mask array_like

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

None
per_bin bool

Return (n_bins,) arrays, the sums restricted to each bin (the same per-neuron \(\bar Y_i\)).

False

Returns:

Type Description
dict of str to float or numpy.ndarray

Keys: the regressor names, "intercept" (with an intercept) and "total".

Raises:

Type Description
ValidationError

If an observed total variance it divides by is zero (naming the bins), on a shape mismatch, or for invalid data.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> ev = model.explained_variance(sim.Y, sim.X)
>>> sorted(ev), bool(0 < ev["total"] < 1)
(['intercept', 'total', 'x0'], True)

orthogonalize(order)

Ordered Gram-Schmidt of the PC-oriented bases, for display.

Following the Nature Neuroscience supplement, §4.2, the PC bases \(U_p\) of B_ (docs/model.md § 10.1, computed whatever frame the model holds) are concatenated in order and orthonormalised by rank-revealing modified Gram-Schmidt, column by column with re-orthogonalisation: the first regressor's basis is unchanged, and a later column whose residual after removing every earlier direction has norm at most \(\sqrt\epsilon\) (its norm before is 1) is dropped. So the width of regressor \(p\) is \(0\le r^{\rm disp}_p\le r_p\), and a subspace inside the earlier ones returns (n_neurons, 0). Not a model frame; feed it to project(..., basis=...), never to subspace_angles.

Parameters:

Name Type Description Default
order sequence of str

Regressor names, the first kept intact; others are omitted and rank-0 ones skipped.

required

Returns:

Type Description
dict of str to numpy.ndarray

{name: (n_neurons, r_display)} with orthonormal columns.

Raises:

Type Description
ParameterError

For an unknown or repeated name.

Examples:

>>> import numpy as np
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=30, n_bins=6, n_trials=150, ranks=[2, 1], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X)
>>> Q = model.orthogonalize(["x1", "x0"])
>>> Q["x1"].shape, Q["x0"].shape
((30, 1), (30, 2))
>>> bool(np.allclose(Q["x1"].T @ Q["x0"], 0))
True

subspace_angles(a, b)

Principal angles between the column spaces of W_[a] and W_[b].

scipy.linalg.subspace_angles on orthonormalised copies, so the result does not depend on canonicalize; the cosines are the canonical correlations of the Nature Neuroscience supplement, §8.2 (docs/model.md § 9.3). Do not use the output of orthogonalize here.

Parameters:

Name Type Description Default
a str

A regressor name.

required
b str

Another (or the same) regressor name.

required

Returns:

Type Description
ndarray

(min(r_a, r_b),) angles in radians, ascending; empty at rank 0.

Raises:

Type Description
ParameterError

For an unknown name.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=30, n_bins=6, n_trials=150, ranks=[2, 1], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X)
>>> model.subspace_angles("x0", "x1").shape
(1,)
>>> model.subspace_angles("x0", "x0").round(6)
array([0., 0.])

to_xarray()

Return the fit as an xarray.Dataset (optional extra).

Dims regressor, neuron, time, component; variables B, W, S (padded with NaN beyond each rank), rank, intercept (absent without one) and noise_precision; attributes estimator, aic, log_likelihood, n_parameters and mtdr_version. See mtdr.xarray_io.to_dataset.

Returns:

Type Description
Dataset

The dataset.

Raises:

Type Description
ImportError

If xarray is not installed (pip install 'mtdr[xarray]').

NotFittedError

Before fit.

Examples:

>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> ds = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X).to_xarray()
>>> dict(ds.sizes)
{'regressor': 1, 'neuron': 20, 'time': 6, 'component': 1}

canonical_factors(B, rank=None)

Factor a coefficient matrix in the paper's PC orientation.

The frame MTDR reports W_ and S_ in (canonicalize=True; docs/model.md § 10.1; Nature Neuroscience supplement, §4.1), for any (n_neurons, n_bins) matrix: with the thin SVD \(B=U\Sigma V^\top\) truncated to rank components,

\[ W=U_{:,1:r},\qquad S=V_{:,1:r}\,\Sigma_{1:r},\qquad WS^\top=B^{(r)}, \]

the columns ordered by decreasing singular value, W orthonormal, and the column norms of S the singular values. Each column's sign is fixed so that the entry of W of largest absolute value is positive; of entries exactly equal in absolute value the first (lowest neuron index) decides, but entries equal in exact arithmetic usually differ at rounding level in the computed SVD, so for such a column the sign is arbitrary. Use it to put a known coefficient matrix, such as a simulation's true B[p], into the frame of a fit before comparing time components column by column.

Parameters:

Name Type Description Default
B array_like

(n_neurons, n_bins) real, finite matrix.

required
rank int

Number of components, 0 <= rank <= min(n_neurons, n_bins). None keeps the numerical rank of B (numpy.linalg.matrix_rank's default tolerance, \(\sigma_1\max(n,T)\,\epsilon\)), so a true \(B_p\) of rank \(r_p\) gives \(r_p\) components rather than rounding noise.

None

Returns:

Name Type Description
W ndarray

(n_neurons, rank) orthonormal columns.

S ndarray

(n_bins, rank) time components, column j of norm \(\sigma_j\).

Raises:

Type Description
ParameterError

If B is not a 2-D real finite array, or rank is not an integer in [0, min(n_neurons, n_bins)].

Notes

Components whose singular values are equal, or nearly so, are determined only up to a rotation within their block, not merely up to sign: compare such components as a subspace (principal angles), not column by column. The frame is a display convention; it is not a symmetry of the marginal likelihood, so canonical factors are not inputs for mtdr.mmle (docs/model.md § 10.1).

Examples:

>>> import numpy as np
>>> from mtdr import canonical_factors
>>> B = np.outer([1.0, -3.0, 2.0], [1.0, 0.5])      # rank 1
>>> W, S = canonical_factors(B)
>>> W.shape, S.shape
((3, 1), (2, 1))
>>> bool(W[1, 0] > 0), bool(np.allclose(W @ S.T, B))
(True, True)