Skip to content

Rank search

Greedy AIC rank search (docs/model.md ยง 7.2, (M39)).

Starting from an initial rank vector, every round refits with each regressor's rank raised by one, scores each candidate, and accepts the one that lowers the objective most if it lowers it by more than a threshold; regressors at max_rank leave the candidate set. The reference's EstRankGreedily, with three corrections: acceptance requires a strict decrease (the reference accepts an equal score), the fit stored for an accepted step is always that step's (the reference indexes its candidate list by position in the movable set), and the history is kept in memory, including the terminal rejected round.

greedy_aic is agnostic to the estimator: it takes a fit(ranks) callable and an objective(fit_object, ranks) callable, which is also the only place where the parameter count or the selection criterion can be changed.

NEAR_TIE_AIC = 2.0 module-attribute

Default margin, in AIC units, below which RankSearchHistory.near_ties reports a round.

RankSearchHistory dataclass

Record of a greedy rank search, (M39).

Row k of ranks and entry k of aic and converged describe the fit after k accepted steps (row 0 is the initial vector); candidates[k] holds the score of every +1 move tried from row k, so the last entry is the terminal round, whose best move was rejected (empty when every regressor was already at max_rank); accepted[k] names the regressor raised from row k to row k + 1. Invariant: ranks.shape[0] == aic.shape[0] == len(candidates) == len(converged) == len(accepted) + 1. The constructor also checks that the record is a coherent search: ranks[0] == init_ranks; ranks are non-negative integers; row k + 1 is row k with accepted[k] raised by one, and aic[k + 1] == candidates[k][accepted[k]]; every name is a regressor name; converged holds bools; threshold >= 0; and the last round is empty exactly when stop_reason == "max_rank". The containers are immutable copies (tuples, read-only mappings, read-only arrays), also after unpickling, so a history cannot be changed after it was checked.

Attributes:

Name Type Description
regressor_names tuple of str

Names, in rank-vector order.

estimator str

"svd" when the fit objects were SVDFits, "mmle" when they were MMLEFits, else "custom".

init_ranks ndarray

(P,) int, the starting vector.

ranks ndarray

(n_accepted + 1, P) int, the accepted rank vectors.

aic ndarray

(n_accepted + 1,) objective value at each accepted vector.

candidates tuple of Mapping of str to float

Per round, the objective value of each tried move, keyed by the name of the regressor raised (read-only mappings).

accepted tuple of str

Per accepted step, the regressor raised.

converged tuple of bool

Per accepted vector, the converged attribute of its fit object (True when the object has none, as for the closed-form SVD fit).

threshold float

The improvement threshold \(\delta\) used.

stop_reason str

"no_improvement" or "max_rank" (every regressor capped).

svd_stage RankSearchHistory or None

The SVD-estimator search that seeded this one, when MTDR runs the two-stage search; None from greedy_aic.

n_fits property

Number of fits this search made: the start plus every candidate.

One fit at init_ranks and one per candidate of every round of (M39), the terminal rejected round included: \(1+\sum_k\) len(candidates[k]). It counts this stage's top-level fits only: the preceding SVD stage has its own (svd_stage.n_fits), and the work inside a fit (an MMLE fit's SVD initialiser, its ECME and L-BFGS-B iterations) is not counted.

Examples:

>>> from mtdr.rank_search import greedy_aic
>>> _, h = greedy_aic(lambda r: None, lambda f, r: (r[0] - 2.0) ** 2, [1], 3)
>>> [len(c) for c in h.candidates], h.n_fits
([1, 1], 3)

final_ranks()

Return the chosen ranks, the last row of ranks, keyed by name.

Returns:

Type Description
dict of str to int

{name: rank} in regressor order.

Examples:

>>> from mtdr.rank_search import greedy_aic
>>> _, h = greedy_aic(lambda r: None, lambda f, r: (r[0] - 2.0) ** 2, [1], 3)
>>> h.final_ranks()
{'x0': 2}

margins()

Return how decisive each round of the greedy search (M39) was.

For round \(k\) (the moves tried from row \(k\)), with \(F_k=\) aic[k] and the round's candidate scores \(F_{k,p}\):

  • "improvement": \(F_k-\min_pF_{k,p}\), what the best move gains (NaN for an empty round);
  • "decision": the improvement minus threshold, positive in every accepted round and at most 0 in the terminal one: its distance from zero is the margin by which the round was decided;
  • "runner_up": the second-smallest candidate score minus the smallest (NaN with fewer than two candidates), the margin by which the move taken beat the next one.

Returns:

Type Description
dict of str to numpy.ndarray

Three (n_accepted + 1,) arrays.

Examples:

>>> from mtdr.rank_search import greedy_aic
>>> _, h = greedy_aic(lambda r: None, lambda f, r: (r[0] - 2.5) ** 2, [1], 4)
>>> {k: v.round(2).tolist() for k, v in h.margins().items()}
{'improvement': [2.0, 0.0], 'decision': [2.0, 0.0], 'runner_up': [nan, nan]}

near_ties(within=NEAR_TIE_AIC)

List the rounds of the search (M39) decided by less than within.

A round is a near tie when its accepted move gained less than within beyond the threshold, when its rejected best move came within within of being accepted (the terminal round), or when the move taken beat the runner-up by less than within. With the default of 2 AIC units, a near tie is an alternative whose relative likelihood \(\exp(-\Delta\mathrm{AIC}/2)\) is above \(1/e\).

Parameters:

Name Type Description Default
within float

The margin, >= 0 (NEAR_TIE_AIC = 2 by default).

NEAR_TIE_AIC

Returns:

Type Description
list of str

One readable line per near tie, in round order; empty if none.

Raises:

Type Description
ParameterError

For a negative or non-finite within.

Examples:

>>> from mtdr.rank_search import greedy_aic
>>> _, h = greedy_aic(lambda r: None, lambda f, r: (r[0] - 2.4) ** 2, [1], 4)
>>> for line in h.near_ties():
...     print(line)
round 0 (accepted x0+1): gained 1.8 beyond the threshold
round 1 (rejected): best move x0+1 missed acceptance by 0.2

to_frame()

Return the history as a pandas.DataFrame, one row per accepted vector.

Columns: rank[<name>] (int) per regressor, aic, converged, candidate[<name>] (the score of raising that regressor from this row; NaN when it was capped), accepted (the regressor raised from this row; missing on the last row), and the round margins improvement, decision and runner_up of margins. The index is the step number.

Returns:

Type Description
DataFrame

The table.

Raises:

Type Description
ImportError

If pandas is not installed (it is an optional dependency, part of the xarray extra).

Examples:

>>> from mtdr.rank_search import greedy_aic
>>> _, h = greedy_aic(lambda r: None, lambda f, r: (r[0] - 2.0) ** 2, [1], 3)
>>> h.to_frame()[["rank[x0]", "aic", "candidate[x0]"]].to_numpy().tolist()
[[1.0, 1.0, 0.0], [2.0, 0.0, 1.0]]

greedy_aic(fit, objective, init_ranks, max_rank, threshold=0.0, regressor_names=None, verbose=0, callback=None, fit_many=None)

Choose ranks by greedy coordinate search on an objective, (M39).

With \(F(r)=\) objective(fit(r), r) and \(r^{(0)}=\) init_ranks, each round evaluates \(F(r+e_p)\) for every regressor \(p\) with \(r_p<\) max_rank (in regressor order), takes \(p^*\), the candidate with the smallest score (the lowest index on ties), and accepts it iff

\[ F(r)-F(r+e_{p^*})>\delta , \]

the decrease exceeding the threshold \(\delta=\) threshold \(\ge0\); with the default \(\delta=0\) an accepted step strictly lowers the score (the reference also accepts a tie). The search stops at the first round with no accepted move ("no_improvement") or with no movable regressor ("max_rank"). Ties go to the lowest index; there is no random state.

Parameters:

Name Type Description Default
fit callable

fit(ranks) with ranks a fresh (P,) int64 array; returns any fit object. Typically functools.partial(svd_fit.fit_svd, stats).

required
objective callable

objective(fit_object, ranks) returns the score to minimise, a real number (AIC for MTDR, lambda f, r: f.aic). +inf marks an infeasible candidate; NaN and -inf (an unbounded likelihood, which would win every round and freeze the search) are errors.

required
init_ranks sequence of int or 1-D integer array

Positive starting ranks, each at most max_rank.

required
max_rank int

Largest rank any regressor may reach, positive. For the SVD estimator it may not exceed min(n_neurons, n_bins), which fit_svd enforces when the search reaches it, part-way through (MTDR bounds it up front).

required
threshold float

\(\delta\ge0\), finite.

0.0
regressor_names sequence of str

Names for the history, ("x0", "x1", ...) by default; unique, "intercept" and "total" reserved.

None
verbose int

0 silent; 1 prints the initial vector and every accepted step (rank vector and score), so the last line is the chosen vector; 2 also prints every round's candidate scores.

0
callback callable

callback(step, ranks, score) after each accepted step, step counting accepted steps from 1, ranks a copy.

None
fit_many callable

fit_many(trials) fits one round's candidates, trials a list of fresh (P,) int64 arrays in regressor order, and returns their fit objects in the same order; for example, fitting them concurrently. The default calls fit on each in turn. The initial fit always uses fit. The search depends only on the returned fits, so the result is the same either way when fit_many returns what fit would.

None

Returns:

Name Type Description
fit_object

The fit at the chosen ranks, as returned by fit.

history RankSearchHistory

The full trace.

Raises:

Type Description
ParameterError

For a non-callable fit, objective, callback or fit_many; a fit_many that returns the wrong number of fits; init_ranks not a sequence of positive integers or above max_rank; a non-positive max_rank; a negative or non-finite threshold; bad names; verbose not 0, 1 or 2; or an objective that returns NaN, -inf or a non-number. Errors raised by fit, objective or fit_many propagate.

Notes

Cost: each round costs one fit per movable regressor, so a search that accepts \(s\) steps over \(P\) regressors costs about \((s+1)P\) fits plus the initial one. Only the current round's fits are held in memory.

Examples:

>>> import functools
>>> from mtdr import simulate
>>> from mtdr.rank_search import greedy_aic
>>> from mtdr.stats import sufficient_statistics
>>> from mtdr.svd_fit import fit_svd
>>> sim = simulate(n_neurons=60, n_bins=8, n_trials=300, ranks=[2, 1],
...                noise_precision=1.0, seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> best, history = greedy_aic(functools.partial(fit_svd, stats),
...                            lambda f, r: f.aic, init_ranks=[1, 1],
...                            max_rank=8, regressor_names=["sa", "choice"])
>>> history.final_ranks()
{'sa': 2, 'choice': 1}
>>> history.ranks.tolist(), history.stop_reason
([[1, 1], [2, 1]], 'no_improvement')
>>> sorted(history.candidates[-1])
['choice', 'sa']
>>> best.ranks
(2, 1)