Skip to content

Sufficient statistics

mtdr.stats

Per-neuron sufficient statistics under the observation mask.

Every estimator and likelihood in mtdr reads the data only through the statistics (M6), (M10)-(M12): for neuron \(i\), with \(\mathcal K_i\) the trials on which it was observed and \(n_i=|\mathcal K_i|\), the means

\[ \bar x_i=\frac1{n_i}\sum_{k\in\mathcal K_i}x_k,\qquad \bar y_i=\frac1{n_i}\sum_{k\in\mathcal K_i}Y_{ki\cdot}, \]

and the moments about them,

\[ \tilde A_i=\sum_{k\in\mathcal K_i}(x_k-\bar x_i)(x_k-\bar x_i)^\top,\quad \tilde\xi_i=\sum_{k\in\mathcal K_i}(x_k-\bar x_i)(Y_{ki\cdot}-\bar y_i)^\top,\quad \tilde\upsilon_i=\sum_{k\in\mathcal K_i}\lVert Y_{ki\cdot}-\bar y_i\rVert^2 . \]

The raw moments of (M6), (M10)-(M11) follow from them without cancellation, \(A_i=\tilde A_i+n_i\bar x_i\bar x_i^\top\), \(\xi_i=\tilde\xi_i+n_i\bar x_i\bar y_i^\top\) and \(\upsilon_i=\tilde\upsilon_i+n_i\lVert\bar y_i\rVert^2\), and are kept as read-only views, XtX, XtY_raw and YtY_raw.

sufficient_statistics computes them in one pass over Y; SufficientStats.centered derives the intercept-centred statistics (M13)-(M14) from them without touching Y again. The reference builds the raw quantities neuron by neuron (MkSuffStatsBTDR_IncompObs_uneqvar_S_fast, MkSuffStats_BilinReg_Sims, ECMEsuffstat, the inline xbari/Ybar loop of mTDRdemo.m); the port computes them batched over neurons with the mask applied explicitly, so values of Y at unobserved entries never enter (the reference's sums over all trials are right only because it zeroes those entries first).

SufficientStats dataclass

Per-neuron sufficient statistics, (M6), (M10)-(M12).

Returned by sufficient_statistics. The stored fields are the moments about each neuron's means and the means themselves; the raw moments (XtX, XtY_raw, YtY_raw) are derived from them once, on construction, and exposed as read-only properties. The intercept-centred views that the likelihoods need come from centered. Arrays are float64 (n_obs is int64) and read-only, also after unpickling; the constructor copies and checks them (shapes; finite values except the NaN means of a neuron never observed; XtX_c symmetric to \(10^{-12}\) of its largest entry, then symmetrised exactly; zero moments for a neuron with n_obs == 0), so a SufficientStats built by hand obeys the same contract. Statistics accumulated elsewhere as raw sums convert by \(\tilde A_i=A_i-n_i\bar x_i\bar x_i^\top\), \(\tilde\xi_i=\xi_i-n_i\bar x_i\bar y_i^\top\) and \(\tilde\upsilon_i=\upsilon_i-n_i\lVert\bar y_i\rVert^2\), which carries the cancellation that the centred accumulation avoids.

Attributes:

Name Type Description
XtX_c ndarray

(n_neurons, n_regressors, n_regressors), \(\tilde A_i\), the Gram matrix of the neuron's observed regressors about their mean \(\bar x_i\).

XtY_c ndarray

(n_neurons, n_regressors, n_bins), \(\tilde\xi_i[p,t]=\sum_{k\in\mathcal K_i} (X_{kp}-\bar x_{ip})(Y_{kit}-\bar y_{it})\).

YtY_c ndarray

(n_neurons,), \(\tilde\upsilon_i=\sum_{k\in\mathcal K_i} \lVert Y_{ki\cdot}-\bar y_i\rVert^2\), the energy about the mean.

n_obs ndarray

(n_neurons,) int, the number of observed trials \(n_i\), (M11).

X_mean ndarray

(n_neurons, n_regressors), the mean regressor vector over the neuron's observed trials, (M12); NaN for a neuron never observed.

Y_mean ndarray

(n_neurons, n_bins), the mean response over the neuron's observed trials, (M12); NaN for a neuron never observed.

n_regressors int

Number of columns of X (the intercept is not one).

n_bins int

Number of time bins.

Examples:

>>> import numpy as np
>>> from mtdr import simulate
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=4, n_bins=3, n_trials=12, ranks=[1, 1],
...                drop_prob=0.2, seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> stats
SufficientStats(n_neurons=4, n_regressors=2, n_bins=3, n_obs=[...])
>>> stats.XtX.shape, stats.XtY_raw.shape, stats.Y_mean.shape
((4, 2, 2), (4, 2, 3), (4, 3))
>>> raw = stats.XtX_c + stats.n_obs[:, None, None] * (
...     stats.X_mean[:, :, None] * stats.X_mean[:, None, :])
>>> bool(np.allclose(raw, stats.XtX))
True

XtX property

The raw Gram, (M6): \(A_i=\tilde A_i+n_i\bar x_i\bar x_i^\top\).

(n_neurons, n_regressors, n_regressors), read-only, derived once.

XtY_raw property

The raw cross-moment, (M10): \(\xi_i=\tilde\xi_i+n_i\bar x_i\bar y_i^\top\).

(n_neurons, n_regressors, n_bins), read-only, derived once.

YtY_raw property

The raw energy, (M11): \(\upsilon_i=\lVert Y_i\rVert^2\).

(n_neurons,), \(\tilde\upsilon_i+n_i\lVert\bar y_i\rVert^2\), read-only, derived once.

n_neurons property

Number of neurons, n_obs.size.

centered(intercept)

Statistics of the responses with an intercept subtracted, (M13)-(M14).

With \(\tilde Y_{ki\cdot}=Y_{ki\cdot}-b_i\) on the observed trials,

\[ \xi_i(b)=\tilde\xi_i+n_i\,\bar x_i(\bar y_i-b_i)^\top,\qquad \upsilon_i(b)=\tilde\upsilon_i+n_i\lVert\bar y_i-b_i\rVert^2, \]

which are (M13)-(M14) written about the means, in \(O(n\,P\,T)\) and without the data. They replace the reference's ECMEsuffstat, which re-reads every response. A neuron never observed contributes zeros.

Parameters:

Name Type Description Default
intercept array_like of shape (n_neurons, n_bins), or None

The condition-independent term \(b\) to subtract. None returns the raw statistics themselves (read-only).

required

Returns:

Name Type Description
XtY ndarray

(n_neurons, n_regressors, n_bins), \(\xi_i(b)\).

YtY ndarray

(n_neurons,), \(\upsilon_i(b)\).

Raises:

Type Description
ParameterError

If intercept is not a finite real array of shape (n_neurons, n_bins).

Notes

\(\upsilon_i(b)\) is a sum of non-negative terms, so there is no cancellation: a baseline far from zero costs no accuracy (the closed form (M14) on the raw moments loses about \(\log_{10}(\upsilon_i/\upsilon_i(b))\) digits).

Examples:

>>> import numpy as np
>>> from mtdr.stats import sufficient_statistics
>>> rng = np.random.default_rng(0)
>>> Y = rng.normal(size=(8, 3, 4)); X = rng.normal(size=(8, 2))
>>> mask = np.ones((8, 3), dtype=bool)
>>> b = rng.normal(size=(3, 4))
>>> XtY, YtY = sufficient_statistics(Y, X, mask).centered(b)
>>> direct = sufficient_statistics(Y - b, X, mask)
>>> bool(np.allclose(XtY, direct.XtY_raw) and np.allclose(YtY, direct.YtY_raw))
True

sufficient_statistics(Y, X, mask)

Per-neuron sufficient statistics of Y given X under mask.

Computes, for every neuron \(i\) over the trials \(\mathcal K_i\) on which mask[:, i] is True, the trial count \(n_i\) (M11), the means \(\bar x_i\), \(\bar y_i\) (M12), and the moments about the means \(\tilde A_i\), \(\tilde\xi_i\), \(\tilde\upsilon_i\), from which the raw Gram \(A_i\) (M6), cross-moment \(\xi_i\) (M10) and energy \(\upsilon_i\) (M11) follow. The reference's MkSuffStatsBTDR_IncompObs_uneqvar_S_fast plus the xbari/Ybar loop of mTDRdemo.m; the full-design statistics of MkSuffStats_BilinReg_Sims (with the constant column) are the same moments with the intercept appended.

Parameters:

Name Type Description Default
Y array_like of shape (n_trials, n_neurons, n_bins)

Responses Y[k, i, t]. Real numeric (bool and integer counts are converted to float64). Entries where mask is False are ignored entirely and may hold anything, including NaN.

required
X array_like of shape (n_trials, n_regressors)

Design X[k, p], finite, at least one column, no column of ones (the intercept is a separate term).

required
mask array_like of shape (n_trials, n_neurons)

True (or 1) where neuron i was observed on trial k; boolean or exactly 0/1. Required: this function does not infer the mask from NaN (that is validate_inputs).

required

Returns:

Type Description
SufficientStats

The statistics. A neuron that is never observed is kept, with zero statistics and NaN means (evaluation contexts allow it; fit rejects it).

Raises:

Type Description
ValidationError

For a wrong shape or layout (the message states the expected (n_trials, n_neurons, n_bins) layout), an empty axis, a non-real dtype, a mask that is not boolean or 0/1, a non-finite entry of X, a NaN/Inf in Y where mask is True (the message lists the trial-neuron pairs), or finite values of X or Y too large to square in float64 (above about \(10^{154}\)).

Notes

The moments are accumulated about the means: each neuron's responses and regressors are first shifted by their values on the neuron's first observed trial, then by the mean of the shifted values, so a regressor or response that is constant over the neuron's trials centres to exactly zero, and a large baseline or offset costs no accuracy.

Cost: one pass over Y, \(O(N\,n\,(P\,T+P^2))\) in batched matrix products, and one neuron-major working copy of Y. Never-observed or degenerate neurons, the min_observations floor, zero-variance neurons and the design checks are fit-time checks of validate_inputs and are not applied here.

Examples:

>>> import numpy as np
>>> from mtdr.stats import sufficient_statistics
>>> Y = np.arange(2 * 2 * 3, dtype=float).reshape(2, 2, 3)   # 2 trials, 2 neurons
>>> X = np.array([[1.0], [-1.0]])
>>> mask = np.array([[True, True], [True, False]])
>>> Y[1, 1] = np.nan                       # unobserved: ignored
>>> stats = sufficient_statistics(Y, X, mask)
>>> stats.n_obs
array([2, 1])
>>> stats.XtY_raw[:, 0]                    # sum_k x_k * Y[k, i, :]
array([[-6., -6., -6.],
       [ 3.,  4.,  5.]])
>>> stats.Y_mean
array([[3., 4., 5.],
       [3., 4., 5.]])
>>> stats.YtY_c                            # about the mean: 2 * 3 * 3**2
array([54.,  0.])