mixle.stats.rankings package¶

Intentional public surface for ranking and permutation probability models.

class BradleyTerryAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the K x K win-count matrix: wins[i, j] = weighted count of i beating j.

Parameters:
update(x, weight, estimate)[source]

Update the win-count matrix from one weighted comparison.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize win counts from one weighted comparison.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update win counts from encoded pairwise comparisons.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize win counts from encoded pairwise comparisons.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge observation count and win-count matrix statistics.

Return type:

BradleyTerryAccumulator

value()[source]

Return accumulated observation weight and win-count matrix.

from_value(x)[source]

Restore accumulator state from value output.

Return type:

BradleyTerryAccumulator

acc_to_encoder()[source]

Return the encoder compatible with Bradley-Terry win-count statistics.

Return type:

BradleyTerryDataEncoder

class BradleyTerryAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create accumulators for Bradley-Terry win-count statistics.

Parameters:
make()[source]

Create an empty Bradley-Terry accumulator.

Return type:

BradleyTerryAccumulator

class BradleyTerryDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of (winner, loser) pairs into an (N, 2) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode (winner, loser) pairs as an integer matrix.

Parameters:

x (Sequence[tuple[int, int]])

Return type:

ndarray

class BradleyTerryDistribution(log_w, name=None, keys=None, fit_diagnostics=None, *, _log_w_already_centered=False)[source]

Bases: SequenceEncodableProbabilityDistribution

Bradley-Terry paired-comparison model with centered log-worths log_w.

Parameters:
  • log_w (Sequence[float] | np.ndarray)

  • name (str | None)

  • keys (str | None)

  • fit_diagnostics (BradleyTerryFitDiagnostics | None)

  • _log_w_already_centered (bool)

classmethod compute_capabilities()[source]

Declare the NumPy and numba execution path used by Bradley-Terry kernels.

density(x)[source]

Return the probability of one (winner, loser) comparison.

Parameters:

x (tuple[int, int])

Return type:

float

log_density(x)[source]

Return the JOINT log-probability of one (winner, loser) comparison.

The pair is drawn uniformly from all K(K-1)/2 unordered pairs and the winner follows Bradley-Terry, so exp(log_density(...)) sums to one over all ordered pairs and exp(log_density((i, j))) + exp(log_density((j, i))) is 1/C(K, 2) – NOT one. It is not P(i beats j); that conditional is win_probability().

Parameters:

x (tuple[int, int])

Return type:

float

win_probability(i, j)[source]

Return P(i beats j | i and j are compared): sigmoid(log_w[i] - log_w[j]).

The conditional a reader of log_density expects. log_density is the joint over (which pair, uniformly) x (who won), smaller by the factor C(K, 2); this quantity satisfies win_probability(i, j) + win_probability(j, i) == 1.

Parameters:
Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for encoded pairwise comparisons.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for paired-comparison outcomes.

Parameters:

seed (int | None)

Return type:

BradleyTerrySampler

estimator(pseudo_count=None)[source]

Return an MM estimator with this distribution’s item count.

Parameters:

pseudo_count (float | None)

Return type:

BradleyTerryEstimator

dist_to_encoder()[source]

Return the pairwise-comparison encoder used by vectorized methods.

Return type:

BradleyTerryDataEncoder

class BradleyTerryEstimator(dim, pseudo_count=None, max_iter=500, tol=1e-10, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood log-worths via the Zermelo / MM fixed point (Hunter 2004).

pseudo_count adds that many fractional wins to EVERY ordered pair (symmetric smoothing). It is what lets an undefeated or winless competitor, or a disconnected comparison graph, fit at all: the unregularized maximum likelihood does not exist there (Ford 1957), and the estimator refuses rather than return a boundary worth. Choosing it: the top of the ranking is stable over a wide range, but near-tied competitors can swap order and the leader’s worth margin shrinks roughly with pseudo_count relative to the wins per pair, because the prior wins pull every worth toward equality (a 0.05 -> 2.0 sweep on one realistic dataset moved the leader’s margin by ~10x while leaving the top order alone). Start near 0.5, half a prior win per ordered pair, shrink it as the comparisons per pair grow, read fit_diagnostics.regularized and pseudo_count on the result, and compare two values before quoting a margin.

Parameters:
accumulator_factory()[source]

Return a factory for Bradley-Terry sufficient-statistic accumulators.

Return type:

BradleyTerryAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate centered log-worths from accumulated win counts.

Parameters:

nobs (float | None)

Return type:

BradleyTerryDistribution

class BradleyTerryFitDiagnostics(converged, iterations, l1_change, regularized, pseudo_count)[source]

Bases: object

Convergence and regularization evidence attached to an estimated model.

Parameters:
class BradleyTerrySampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw (winner, loser) pairs: a uniform unordered pair, then a Bradley-Terry outcome.

Parameters:
  • dist (BradleyTerryDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one comparison outcome or size iid comparison outcomes.

Parameters:
Return type:

tuple[int, int] | list[tuple[int, int]]

class DavidsonDistribution(log_w, nu=1.0, name=None, keys=None, fit_diagnostics=None)[source]

Bases: _BaseTieDistribution

Bradley-Terry with ties (Davidson 1970); tie mass nu sqrt(w_i w_j).

Parameters:
  • nu (float)

  • name (str | None)

  • keys (str | None)

  • fit_diagnostics (TieModelFitDiagnostics | None)

estimator(pseudo_count=None)[source]

Return the maximum-likelihood Davidson estimator.

Parameters:

pseudo_count (float | None)

class DavidsonEstimator(dim, pseudo_count=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood Davidson worths and tie parameter (L-BFGS on the count matrices).

pseudo_count adds that many fractional wins to every ordered pair and that many ties to every unordered pair; see BradleyTerryEstimator for how to choose it. Without it, data in which some competitor never lost (or never won) has no finite fit and the estimator raises ValueError rather than return a boundary worth.

Parameters:
  • dim (int)

  • pseudo_count (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return the accumulator factory used by this estimator.

Return type:

_TieAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate Davidson worths and tie parameter from sufficient statistics.

Parameters:

nobs (float | None)

Return type:

DavidsonDistribution

class EwensAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the total (weighted) cycle count and observation weight.

Parameters:
update(x, weight, estimate)[source]

Update cycle-count statistics from one weighted permutation.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize cycle-count statistics from one weighted permutation.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update cycle-count statistics from encoded permutations.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize cycle-count statistics from encoded permutations.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge cycle-count totals and observation weight from another accumulator.

Return type:

EwensAccumulator

value()[source]

Return total weighted cycle count and total observation weight.

from_value(x)[source]

Restore accumulator state from value output.

Return type:

EwensAccumulator

acc_to_encoder()[source]

Return the encoder compatible with Ewens cycle-count statistics.

Return type:

EwensDataEncoder

class EwensAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create accumulators for Ewens cycle-count statistics.

Parameters:
make()[source]

Create an empty Ewens accumulator.

Return type:

EwensAccumulator

class EwensDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of permutations of 0,…,n-1 into an (N, n) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode permutations as a dense integer matrix.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

class EwensDistribution(dim, theta=1.0, name=None, keys=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Ewens distribution over permutations of 0..n-1 with cycle-weight parameter theta > 0.

Parameters:
classmethod compute_capabilities()[source]

Declare the NumPy and numba execution path used by Ewens kernels.

density(x)[source]

Return the probability of one permutation.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of one permutation.

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for encoded permutations.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return an exact Ewens permutation sampler.

Parameters:

seed (int | None)

Return type:

EwensSampler

estimator(pseudo_count=None)[source]

Return a cycle-count moment estimator for this dimension.

Parameters:

pseudo_count (float | None)

Return type:

EwensEstimator

dist_to_encoder()[source]

Return the permutation encoder used by vectorized methods.

Return type:

EwensDataEncoder

class EwensEstimator(dim, theta=None, pseudo_count=None, prior_mean_cycles=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Fit theta by matching the mean cycle count E[cycles] = sum_i theta/(theta+i).

Parameters:
  • dim (int)

  • theta (float | None)

  • pseudo_count (float | None)

  • prior_mean_cycles (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for Ewens sufficient-statistic accumulators.

Return type:

EwensAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate theta by matching the accumulated mean cycle count.

Parameters:

nobs (float | None)

Return type:

EwensDistribution

class EwensSampler(dist, seed=None)[source]

Bases: DistributionSampler

Exact Ewens draws via the numba Chinese-restaurant construction.

Parameters:
  • dist (EwensDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one permutation or size iid permutations.

Parameters:
Return type:

list[int] | list[list[int]]

class GeneralizedMallowsAccumulator(dim, reservoir=10000, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the rank-count matrix, the precede matrix, and a bounded reservoir of orderings.

rank_count[item, rank] and precede[a, b] give the consensus (Borda / Copeland); the reservoir supplies the empirical mean metric-distance to the fitted center (exact when the data fit in it).

Parameters:
  • dim (int)

  • reservoir (int)

  • keys (str | None)

update(x, weight, estimate)[source]

Update rank, precedence, and reservoir statistics from one ordering.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one weighted ordering.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update rank, precedence, and reservoir statistics from encoded orderings.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded orderings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge consensus statistics and reservoir samples from another accumulator.

Return type:

GeneralizedMallowsAccumulator

value()[source]

Return count, consensus matrices, and bounded reservoir contents.

from_value(x)[source]

Restore accumulator state from value output.

Return type:

GeneralizedMallowsAccumulator

acc_to_encoder()[source]

Return the ranking encoder compatible with these sufficient statistics.

Return type:

GeneralizedMallowsDataEncoder

class GeneralizedMallowsAccumulatorFactory(dim, reservoir=10000, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create accumulators for generalized Mallows consensus statistics.

Parameters:
  • dim (int)

  • reservoir (int)

  • keys (str | None)

make()[source]

Create an empty generalized Mallows accumulator.

Return type:

GeneralizedMallowsAccumulator

class GeneralizedMallowsComputationDiagnostics(normalizer_algorithm, normalizer_exact, sampler_algorithm, sampler_exact, legacy_n_mc_ignored, legacy_seed_ignored)[source]

Bases: object

Exactness and algorithm provenance for scoring and sampling.

Parameters:
  • normalizer_algorithm (str)

  • normalizer_exact (bool)

  • sampler_algorithm (str)

  • sampler_exact (bool)

  • legacy_n_mc_ignored (int)

  • legacy_seed_ignored (int)

class GeneralizedMallowsDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of orderings (permutations of 0,…,n-1) into an (N, n) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode full orderings as a dense integer matrix.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

class GeneralizedMallowsDistribution(sigma0, theta=1.0, metric='kendall', name=None, keys=None, n_mc=20000, seed=0, max_exact=16, max_enum=9, fit_diagnostics=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Mallows distribution under a configurable distance metric (closed-form normalizer metrics).

Parameters:
  • sigma0 (Sequence[int] | np.ndarray)

  • theta (float)

  • metric (str)

  • name (str | None)

  • keys (str | None)

  • n_mc (int)

  • seed (int)

  • max_exact (int)

  • max_enum (int)

  • fit_diagnostics (GeneralizedMallowsFitDiagnostics | None)

classmethod compute_capabilities()[source]

Declare the NumPy and numba execution path used by Mallows kernels.

distance(x)[source]

Distance between ordering x and the central permutation under this metric.

Raises:

ValueError – If x is not a permutation of 0,…,n-1 (wrong length, a repeated element, a non-integer entry, or an element outside that range). A malformed x is not merely an unlikely ordering – it isn’t an ordering at all, so it is rejected here rather than silently scored (e.g. a repeated index would otherwise still produce a finite, meaningless distance, an out-of-range index can alias a valid rank via numpy’s negative-index wraparound instead of failing loudly, and a fractional entry like 0.5 would otherwise be silently truncated to 0 by the int cast before this check ever saw it).

Parameters:

x (Sequence[int])

Return type:

int

density(x)[source]

Return the probability of one ordering under the Mallows model.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of one ordering.

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for encoded orderings.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for this Mallows distribution.

Parameters:

seed (int | None)

Return type:

GeneralizedMallowsSampler

estimator(pseudo_count=None)[source]

Return a Mallows estimator with this metric and item count.

Parameters:

pseudo_count (float | None)

Return type:

GeneralizedMallowsEstimator

dist_to_encoder()[source]

Return the full-ranking encoder used by vectorized methods.

Return type:

GeneralizedMallowsDataEncoder

class GeneralizedMallowsEstimator(dim, metric='kendall', theta=None, reservoir=10000, name=None, keys=None, n_mc=20000, seed=0, max_exact=16, max_enum=9, pseudo_count=None, prior_center=None, center_exact_cap=7, allow_approximate_center=False)[source]

Bases: ParameterEstimator

Estimate the central permutation (Copeland/Borda) and dispersion theta (moment match).

Parameters:
  • dim (int)

  • metric (str)

  • theta (float | None)

  • reservoir (int)

  • name (str | None)

  • keys (str | None)

  • n_mc (int)

  • seed (int)

  • max_exact (int)

  • max_enum (int)

  • pseudo_count (float | None)

  • prior_center (Sequence[int] | np.ndarray | None)

  • center_exact_cap (int)

  • allow_approximate_center (bool)

accumulator_factory()[source]

Return a factory for Mallows sufficient-statistic accumulators.

Return type:

GeneralizedMallowsAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate the central ordering and dispersion from accumulated rankings.

Parameters:

nobs (float | None)

Return type:

GeneralizedMallowsDistribution

class GeneralizedMallowsFitDiagnostics(center_algorithm, center_exact, centers_evaluated, distance_objective, regularized, pseudo_count)[source]

Bases: object

Center-search and regularization evidence attached to a fitted model.

Parameters:
  • center_algorithm (str)

  • center_exact (bool)

  • centers_evaluated (int)

  • distance_objective (float)

  • regularized (bool)

  • pseudo_count (float)

class GeneralizedMallowsModelAccumulator(dim, reservoir=10000, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate precedence counts and an exact bounded weighted empirical support.

Parameters:
  • dim (int)

  • reservoir (int)

  • keys (str | None)

update(x, weight, estimate)[source]

Update consensus and reservoir statistics from one weighted ordering.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize consensus and reservoir statistics from one ordering.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update consensus and reservoir statistics from encoded orderings.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize statistics from encoded orderings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge observation weight, precedence counts, and reservoir samples.

Return type:

GeneralizedMallowsModelAccumulator

value()[source]

Return count, precedence matrix, and bounded reservoir contents.

from_value(x)[source]

Restore accumulator state from value output.

Return type:

GeneralizedMallowsModelAccumulator

acc_to_encoder()[source]

Return the encoder compatible with these sufficient statistics.

Return type:

GeneralizedMallowsModelDataEncoder

class GeneralizedMallowsModelAccumulatorFactory(dim, reservoir=10000, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create accumulators for stage-wise Generalized Mallows statistics.

Parameters:
  • dim (int)

  • reservoir (int)

  • keys (str | None)

make()[source]

Create an empty stage-wise Generalized Mallows accumulator.

Return type:

GeneralizedMallowsModelAccumulator

class GeneralizedMallowsModelDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of orderings (permutations of 0,…,n-1) into an (N, n) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode full orderings as a dense integer matrix.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

class GeneralizedMallowsModelDistribution(sigma0, theta=None, name=None, keys=None, fit_diagnostics=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Generalized Mallows Model: a Kendall Mallows model with a per-stage dispersion vector theta.

Parameters:
  • sigma0 (Sequence[int] | np.ndarray)

  • theta (Sequence[float] | np.ndarray | None)

  • name (str | None)

  • keys (str | None)

  • fit_diagnostics (GeneralizedMallowsModelFitDiagnostics | None)

classmethod compute_capabilities()[source]

Declare the NumPy execution path used by stage-wise Mallows kernels.

density(x)[source]

Return the probability of one ordering.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of one ordering.

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for encoded orderings.

Raises:

ValueError – If any row of x is not a permutation of 0,…,n-1 (wrong length, a repeated element, a non-integer entry, or an element outside that range). A malformed row is not merely an unlikely ordering – it isn’t an ordering at all, so it is rejected here rather than silently scored (e.g. a repeated index would otherwise still produce a finite, meaningless log-density, an out-of-range or negative index reaches the numba RIM kernel below, which has no bounds checking of its own and does not raise – it silently scores too, rather than failing loudly – and a fractional entry like 0.5 would otherwise be silently truncated to 0 by the int cast before this check ever saw it).

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return an exact repeated-insertion sampler for this model.

Parameters:

seed (int | None)

Return type:

GeneralizedMallowsModelSampler

estimator(pseudo_count=None)[source]

Return a stage-wise Mallows estimator with this item count.

Parameters:

pseudo_count (float | None)

Return type:

GeneralizedMallowsModelEstimator

dist_to_encoder()[source]

Return the full-ranking encoder used by vectorized methods.

Return type:

GeneralizedMallowsModelDataEncoder

class GeneralizedMallowsModelEstimator(dim, reservoir=10000, pseudo_count=None, prior_center=None, center_exact_cap=7, allow_approximate_center=False, name=None, keys=None)[source]

Bases: ParameterEstimator

Fit a center and per-stage dispersions from exact weighted empirical support.

Parameters:
  • dim (int)

  • reservoir (int)

  • pseudo_count (float | None)

  • prior_center (Sequence[int] | np.ndarray | None)

  • center_exact_cap (int)

  • allow_approximate_center (bool)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for stage-wise Mallows sufficient-statistic accumulators.

Return type:

GeneralizedMallowsModelAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate central ordering and per-stage dispersions from accumulated rankings.

Parameters:

nobs (float | None)

Return type:

GeneralizedMallowsModelDistribution

class GeneralizedMallowsModelFitDiagnostics(center_algorithm, center_exact, centers_evaluated, objective, regularized, pseudo_count)[source]

Bases: object

Center-search and regularization evidence attached to a fitted stage-wise model.

Parameters:
  • center_algorithm (str)

  • center_exact (bool)

  • centers_evaluated (int)

  • objective (float)

  • regularized (bool)

  • pseudo_count (float)

class GeneralizedMallowsModelSampler(dist, seed=None)[source]

Bases: DistributionSampler

Exact GMM draws via the per-stage Repeated Insertion Model.

Parameters:
  • dist (GeneralizedMallowsModelDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one ordering or size iid orderings.

Parameters:
Return type:

list[int] | list[list[int]]

class GeneralizedMallowsSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw exact iid orderings using metric-specific finite-law samplers.

Parameters:
  • dist (GeneralizedMallowsDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one ordering or size iid orderings.

Parameters:
Return type:

list[int] | list[list[int]]

class ItemOrdering(values)[source]

Bases: Sequence[int]

A permutation whose entry at each rank is the item occupying that rank.

Parameters:

values (tuple[int, ...])

to_rank_vector()[source]

Return the inverse permutation, indexed by item.

Return type:

RankVector

class LowRankPermutationAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the item-by-rank count matrix C[item, rank] – the first-order sufficient statistic.

Parameters:
update(x, weight, estimate)[source]

Update item-by-rank counts from one weighted ordering.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize item-by-rank counts from one weighted ordering.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update item-by-rank counts from encoded orderings.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize item-by-rank counts from encoded orderings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge observation weight and item-by-rank count statistics.

Return type:

LowRankPermutationAccumulator

value()[source]

Return accumulated observation weight and item-by-rank counts.

from_value(x)[source]

Restore accumulator state from value output.

Return type:

LowRankPermutationAccumulator

acc_to_encoder()[source]

Return the encoder compatible with item-by-rank sufficient statistics.

Return type:

LowRankPermutationDataEncoder

class LowRankPermutationAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create accumulators for low-rank permutation sufficient statistics.

Parameters:
make()[source]

Create an empty low-rank permutation accumulator.

Return type:

LowRankPermutationAccumulator

class LowRankPermutationComputationDiagnostics(normalizer_algorithm='exact_log_permanent', normalizer_exact=True, marginal_algorithm='exact_log_permanent_ratios', marginals_exact=True, sampler_algorithm='exact_conditional_permanent', sampler_exact=True, optional_relaxation='sinkhorn_bethe_transport')[source]

Bases: object

Exactness and algorithm provenance for the represented probability law.

Parameters:
  • normalizer_algorithm (str)

  • normalizer_exact (bool)

  • marginal_algorithm (str)

  • marginals_exact (bool)

  • sampler_algorithm (str)

  • sampler_exact (bool)

  • optional_relaxation (str)

class LowRankPermutationDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of orderings (permutations of 0,…,n-1) into an (N, n) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode full orderings as a dense integer matrix.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

class LowRankPermutationDistribution(u, v, name=None, keys=None, max_exact=12, sinkhorn_iter=200, fit_diagnostics=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Permutation Gibbs model with a low-rank item-by-rank score matrix S = U V^T.

Parameters:
  • u (np.ndarray)

  • v (np.ndarray)

  • name (str | None)

  • keys (str | None)

  • max_exact (int)

  • sinkhorn_iter (int)

  • fit_diagnostics (LowRankPermutationFitDiagnostics | None)

classmethod compute_capabilities()[source]

Declare the NumPy and numba execution path used by low-rank permutation kernels.

density(x)[source]

Return the probability of one ordering.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of one ordering.

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for encoded orderings.

Parameters:

x (ndarray)

Return type:

ndarray

marginals()[source]

Return exact model marginals P[item, rank].

Return type:

ndarray

sinkhorn_relaxation()[source]

Return an explicitly approximate doubly-stochastic transport relaxation.

Return type:

ndarray

sampler(seed=None)[source]

Return an exact conditional-permanent sampler.

Parameters:

seed (int | None)

Return type:

LowRankPermutationSampler

estimator(pseudo_count=None)[source]

Return an exact-marginal estimator with this dimension and rank.

Parameters:

pseudo_count (float | None)

Return type:

LowRankPermutationEstimator

dist_to_encoder()[source]

Return the full-ranking encoder used by vectorized methods.

Return type:

LowRankPermutationDataEncoder

class LowRankPermutationEstimator(dim, rank=2, max_exact=12, sinkhorn_iter=200, max_iter=300, lr=0.5, tol=1.0e-6, pseudo_count=None, prior_marginals=None, require_convergence=True, name=None, keys=None)[source]

Bases: ParameterEstimator

Fit U, V by Sinkhorn-marginal gradient ascent toward the empirical item-by-rank marginals.

Parameters:
  • dim (int)

  • rank (int)

  • max_exact (int)

  • sinkhorn_iter (int)

  • max_iter (int)

  • lr (float)

  • tol (float)

  • pseudo_count (float | None)

  • prior_marginals (np.ndarray | None)

  • require_convergence (bool)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for low-rank permutation sufficient-statistic accumulators.

Return type:

LowRankPermutationAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate low-rank score factors from item-by-rank marginal counts.

Parameters:

nobs (float | None)

Return type:

LowRankPermutationDistribution

class LowRankPermutationFitDiagnostics(converged, iterations, gradient_norm, regularized, pseudo_count, marginal_algorithm='exact_log_permanent')[source]

Bases: object

Optimization evidence attached to an estimated low-rank permutation law.

Parameters:
  • converged (bool)

  • iterations (int)

  • gradient_norm (float)

  • regularized (bool)

  • pseudo_count (float)

  • marginal_algorithm (str)

class LowRankPermutationSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid orderings from exact conditional permanent ratios.

Parameters:
  • dist (LowRankPermutationDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one ordering or size exact iid orderings.

Parameters:
Return type:

list[int] | list[list[int]]

class MallowsAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the weighted pairwise-precedence matrix for Mallows estimation.

precede[a, b] is the weighted number of orderings in which item a is ranked before item b; this is the sufficient statistic for both the central permutation (via Copeland scores) and the mean Kendall distance.

Parameters:
update(x, weight, estimate)[source]

Accumulate weighted pairwise-precedence counts for one ordering.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize the sufficient statistics with one weighted ordering.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted pairwise-precedence counts for encoded orderings.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize the sufficient statistics from encoded orderings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge serialized precedence-count statistics into this accumulator.

Parameters:

suff_stat (tuple[float, ndarray])

Return type:

MallowsAccumulator

value()[source]

Return the accumulated weight and pairwise-precedence matrix.

Return type:

tuple[float, ndarray]

from_value(x)[source]

Restore the accumulator from serialized precedence-count statistics.

Parameters:

x (tuple[float, ndarray])

Return type:

MallowsAccumulator

acc_to_encoder()[source]

Return an encoder compatible with the accumulated ordering dimension.

Return type:

MallowsDataEncoder

class MallowsAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for MallowsAccumulator.

Parameters:
make()[source]

Create an empty Mallows accumulator.

Return type:

MallowsAccumulator

class MallowsDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of orderings (permutations of 0,…,n-1) into an (N, n) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode orderings as a two-dimensional integer array.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

class MallowsDistribution(sigma0, theta=1.0, name=None, keys=None, fit_diagnostics=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Mallows distribution over permutations of 0,…,n-1 with central permutation sigma0 and dispersion theta.

Data type: List[int] (an ordering: a permutation of 0,…,n-1, best-ranked item first).

Parameters:
classmethod compute_capabilities()[source]

Return compute-backend metadata for the Mallows distribution.

kendall_distance(x)[source]

Return the Kendall tau distance between ordering x and the central permutation.

Raises:

ValueError – If x is not a permutation of 0,…,n-1 (wrong length, a repeated element, a non-integer entry, or an element outside that range). A malformed x is not merely an unlikely ordering – it isn’t an ordering at all, so it is rejected here rather than silently scored (e.g. a repeated index would otherwise still produce a finite, meaningless distance, an out-of-range index can alias a valid rank via numpy’s negative-index wraparound instead of failing loudly, and a fractional entry like 0.5 would otherwise be silently truncated to 0 by the int cast before this check ever saw it).

Parameters:

x (Sequence[int])

Return type:

int

density(x)[source]

Return the probability of an ordering x.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of an ordering x (a permutation of 0,…,n-1).

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for an (N, n) array of orderings.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for drawing orderings from this distribution.

Parameters:

seed (int | None)

Return type:

MallowsSampler

enumerator()[source]

Return an exact finite enumerator over all orderings in decreasing probability order.

Return type:

MallowsEnumerator

support_size()[source]

Return the number of full rankings.

Return type:

int

estimator(pseudo_count=None)[source]

Return an estimator that keeps the item count fixed at this distribution’s n.

Parameters:

pseudo_count (float | None)

Return type:

MallowsEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

MallowsDataEncoder

class MallowsEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate Mallows orderings in descending probability order, lazily.

Kendall distance is separable in the Lehmer code: an ordering’s distance is the sum of digits L_i in {0,...,n-1-i} (inversions contributed at each rank), each weighted -theta*L_i. So the support is a product over the digits and ProductEnumerator streams it in increasing distance (descending probability) without materializing the n! permutations; each digit tuple decodes (factorial number system) to a permutation of the identity, relabeled through the central permutation sigma0.

Parameters:

dist (MallowsDistribution)

class MallowsEstimator(dim, theta=None, pseudo_count=None, prior_precede=None, prior_center=None, center_exact_cap=9, allow_approximate_center=False, name=None, keys=None)[source]

Bases: ParameterEstimator

Estimator for the Mallows central permutation (Copeland aggregation) and dispersion theta.

Parameters:
accumulator_factory()[source]

Return a factory for Mallows sufficient-statistic accumulators.

Return type:

MallowsAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate the central permutation and dispersion from precedence counts.

Parameters:
Return type:

MallowsDistribution

class MallowsFitDiagnostics(center_algorithm, center_exact, centers_evaluated, kendall_objective, regularized, pseudo_count)[source]

Bases: object

Center-search and regularization evidence attached to a fitted Mallows law.

Parameters:
  • center_algorithm (str)

  • center_exact (bool)

  • centers_evaluated (int)

  • kendall_objective (float)

  • regularized (bool)

  • pseudo_count (float)

class MallowsSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid Mallows orderings via the Repeated Insertion Model.

Parameters:
  • dist (MallowsDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw orderings (permutations of 0,…,n-1); a single list when size is None.

Parameters:
Return type:

list[int] | list[list[int]]

class MatchingAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the weighted assignment-frequency matrix (the sufficient statistic for the weights).

Parameters:
update(x, weight, estimate)[source]

Accumulate weighted assignment counts for one matching.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize the sufficient statistics with one weighted matching.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted assignment counts for encoded matchings.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (MatchingDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize the sufficient statistics from encoded matchings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge serialized assignment-count statistics into this accumulator.

Parameters:

suff_stat (tuple[float, ndarray])

Return type:

MatchingAccumulator

value()[source]

Return the accumulated weight and assignment-count matrix.

Return type:

tuple[float, ndarray]

from_value(x)[source]

Restore the accumulator from serialized assignment-count statistics.

Parameters:

x (tuple[float, ndarray])

Return type:

MatchingAccumulator

acc_to_encoder()[source]

Return an encoder compatible with the accumulated matching dimension.

Return type:

MatchingDataEncoder

class MatchingAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for MatchingAccumulator.

Parameters:
make()[source]

Create an empty matching accumulator.

Return type:

MatchingAccumulator

class MatchingDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode a sequence of matchings (permutations) into an (N, n) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode matchings as a two-dimensional integer array.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

class MatchingDistribution(weights, max_nodes=_DEFAULT_MAX_NODES, name=None, keys=None, fit_diagnostics=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Weighted bipartite perfect-matching distribution over n left/right nodes (permanent-normalized).

Data type: a permutation x of 0,…,n-1 (left node i matched to right node x[i]).

Parameters:
classmethod compute_capabilities()[source]

Return compute-backend metadata for the matching distribution.

density(x)[source]

Return the probability of a matching x (a permutation).

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of a matching x (left i matched to right x[i]).

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for an (N, n) array of matchings.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for drawing matchings from this distribution.

Parameters:

seed (int | None)

Return type:

MatchingSampler

enumerator()[source]

Return an exact finite enumerator over all matchings in decreasing probability order.

Return type:

MatchingEnumerator

support_size()[source]

Return the number of perfect matchings.

Return type:

int

estimator(pseudo_count=1.0)[source]

Return an estimator that keeps the node count fixed at this distribution’s n.

Parameters:

pseudo_count (float | None)

Return type:

MatchingEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

Return type:

MatchingDataEncoder

class MatchingEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate finite-probability perfect matchings in descending probability order.

Lazily, via Murty’s k-best assignment on the edge-cost matrix -log(weights): decreasing probability is increasing assignment cost, and zero-weight edges become +inf costs (forbidden), so only positive-probability matchings are yielded. This streams the top matchings without materializing the n! permutation support.

Parameters:

dist (MatchingDistribution)

class MatchingEstimator(dim, max_nodes=_DEFAULT_MAX_NODES, pseudo_count=1.0, max_steps=5000, learning_rate=1.0, tol=1.0e-7, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood estimator for the edge weights (matches empirical and model edge marginals).

Parameters:
accumulator_factory()[source]

Return a factory for matching sufficient-statistic accumulators.

Return type:

MatchingAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a permanent-normalized matching distribution from assignment counts.

Parameters:
Return type:

MatchingDistribution

class MatchingFitDiagnostics(converged, iterations, max_marginal_error, regularized, pseudo_count)[source]

Bases: object

Convergence evidence attached to an estimated matching model.

Parameters:
class MatchingSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid matchings by sampling each left node’s match from the exact conditional permanent.

Parameters:
  • dist (MatchingDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw matchings (each a permutation); a single matching when size is None.

Parameters:
Return type:

list[int] | list[list[int]]

class PairDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode (winner, loser) pairs into an (N, 2) integer array.

Parameters:

dim (int | None)

seq_encode(x)[source]

Encode winner-loser pairs as an integer (N, 2) array.

Parameters:

x (Sequence[tuple[int, int]])

Return type:

ndarray

class PairWinAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Win-count matrix wins[i, j] for (winner, loser) pair data.

Parameters:
update(x, weight, estimate)[source]

Accumulate one weighted winner-loser observation.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize sufficient statistics from one weighted pair.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Accumulate weighted winner-loser pairs from an encoded batch.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize sufficient statistics from an encoded weighted batch.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge serialized win-count sufficient statistics.

Return type:

PairWinAccumulator

value()[source]

Return serialized win-count sufficient statistics.

from_value(x)[source]

Restore accumulator state from serialized win counts.

Return type:

PairWinAccumulator

acc_to_encoder()[source]

Return the encoder associated with this accumulator.

Return type:

PairDataEncoder

class PairWinAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for paired win-count accumulators.

Parameters:
make()[source]

Create a fresh paired-win accumulator.

Return type:

PairWinAccumulator

class PlackettLuceAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate the Minorization-Maximization sufficient statistics for Plackett-Luce estimation.

num (non-last appearance counts) is data-only; den accumulates the stage reciprocals 1 / sum_{t>=s} w_t and is evaluated at the previous estimate (uniform worths when no estimate is supplied, which seeds the fit).

Parameters:
update(x, weight, estimate)[source]

Update sufficient statistics from one full ranking and its weight.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one full ranking using the uniform-worth seed.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update MM sufficient statistics from encoded full rankings.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (PlackettLuceDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize a batch of rankings with uniform-worth denominator statistics.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge count, numerator, and denominator arrays from another accumulator.

Parameters:

suff_stat (tuple[float, ndarray, ndarray])

Return type:

PlackettLuceAccumulator

value()[source]

Return the accumulated count, numerator counts, and denominator totals.

Return type:

tuple[float, ndarray, ndarray]

from_value(x)[source]

Restore accumulator state from value output.

Parameters:

x (tuple[float, ndarray, ndarray])

Return type:

PlackettLuceAccumulator

acc_to_encoder()[source]

Return the full-ranking encoder compatible with these sufficient statistics.

Return type:

PlackettLuceDataEncoder

class PlackettLuceAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for PlackettLuceAccumulator.

Parameters:
make()[source]

Create an empty full-ranking Plackett-Luce accumulator.

Return type:

PlackettLuceAccumulator

class PlackettLuceDataEncoder(dim=None, allow_partial=False)[source]

Bases: DataSequenceEncoder

Encode a sequence of full or partial/top-m orderings over dim items.

A batch whose rows are all length dim (full rankings – permutations of 0,...,dim-1) is validated and encoded as a dense (N, dim) integer matrix, scored by PlackettLuceDistribution.seq_log_density()’s vectorized path. Any other batch (rows shorter than dim, or of mixed length – top-m partial rankings) is validated and encoded the same way PlackettLucePartialDataEncoder does, as a ragged list of 1-D integer arrays, scored by that method’s per-row fallback (which calls PlackettLuceDistribution.log_density(), already correct for partial rankings). This dual behavior lets dist_to_encoder() return one encoder that works regardless of whether the distribution was fit on full or partial rankings.

Parameters:
  • dim (int | None)

  • allow_partial (bool)

seq_encode(x)[source]

Validate and encode a batch of full rankings (dense) or partial rankings (ragged).

Raises:

ValueError – If x is empty, a full-length row has a non-integer-valued entry (e.g. 0.5, which would otherwise silently truncate to a plausible-looking index instead of being rejected) or is not a permutation of 0,...,dim-1, or (via PlackettLucePartialDataEncoder) a short/ragged row is malformed.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray | list[ndarray]

row_count(x)[source]

Return the number of dense or ragged encoded ranking rows.

Parameters:

x (ndarray | list[ndarray])

Return type:

int

class PlackettLuceDistribution(log_w, name=None, keys=None, allow_partial=False)[source]

Bases: SequenceEncodableProbabilityDistribution

Plackett-Luce distribution over orderings of K items with log-worths log_w.

Data type: List[int] (an ordering: a permutation of 0,…,K-1, best-ranked item first).

Parameters:
classmethod compute_capabilities()[source]

Declare the NumPy execution path used by Plackett-Luce ranking kernels.

density(x)[source]

Return the probability of an ordering x.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the log-probability of an ordering x.

x may be a full ranking (a permutation of 0,...,K-1) or a partial / top-m ranking (an ordered list of m <= K distinct items, best first, leaving the other K-m items unranked). For a partial ranking the sequential-choice denominator at each stage still includes the unranked items: p(x) = prod_{s=0}^{m-1} w_{x[s]} / (sum_{t>=s} w_{x[t]} + sum_{u unranked} w_u), which reduces to the full-ranking density when m = K.

Raises:

ValueError – If x is not 1-D, has a non-integer-valued entry (e.g. 0.5, which would otherwise silently truncate to a plausible-looking index instead of being rejected), or its (integer) entries are not distinct item indices in 0,...,K-1.

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for encoded orderings.

A dense (N, K) integer array (the full-ranking encoding) is scored by the vectorized path; a ragged sequence of variable-length orderings (the partial / top-m encoding) is scored per-ranking via log_density(), which includes the unranked-item denominator term.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for drawing orderings from this distribution.

Parameters:

seed (int | None)

Return type:

PlackettLuceSampler

enumerator()[source]

Return an exact finite enumerator over all orderings in decreasing probability order.

Return type:

PlackettLuceEnumerator

support_size()[source]

Return the number of full rankings.

Return type:

int

estimator(pseudo_count=None)[source]

Return an MM estimator that keeps the item count fixed at this distribution’s K.

Parameters:

pseudo_count (float | None)

Return type:

PlackettLuceEstimator

dist_to_encoder()[source]

Return the data encoder used by this distribution for vectorized methods.

The returned encoder handles both full rankings and partial/top-m rankings (see PlackettLuceDataEncoder), so this works regardless of whether self was produced by PlackettLuceEstimator or PlackettLucePartialEstimator.

Return type:

PlackettLuceDataEncoder

class PlackettLuceEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate Plackett–Luce orderings in descending probability order, lazily (A* best-first).

A ranking’s log-density is sum_k [theta_{x_k} - logsumexp(theta over the items not yet ranked at step k)]. The state is a chosen prefix with exact partial score g; the best possible completion ranks the remaining items by descending worth (which minimizes the remaining logsumexp denominators), giving an exact admissible bound h. A* on g + h streams the rankings in exact descending order without touching the n! support.

Parameters:

dist (PlackettLuceDistribution)

class PlackettLuceEstimator(dim, pseudo_count=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Minorization-Maximization estimator for the Plackett-Luce log-worths (item count K fixed).

Parameters:
  • dim (int)

  • pseudo_count (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for MM sufficient statistics at this estimator’s dimension.

Return type:

PlackettLuceAccumulatorFactory

estimate(nobs, suff_stat)[source]

Return one MM estimate from accumulated full-ranking sufficient statistics.

Parameters:
Return type:

PlackettLuceDistribution

class PlackettLucePartialAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Generalized Hunter (2004) MM statistics for partial / top-m Plackett-Luce rankings.

For each ranking, at every non-forced stage s (at least two items still available) the chosen item accrues a numerator count and all currently-available items (the unranked tail included) accrue weight / sum_{available} w to the denominator, evaluated at the previous estimate’s worths (uniform when none). On full rankings this reduces exactly to the vectorized full-ranking accumulator.

Parameters:
update(x, weight, estimate)[source]

Update partial-ranking sufficient statistics from one observation.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize statistics from one partial ranking using uniform worths.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update generalized MM statistics from encoded top-m rankings.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize a batch of partial rankings with uniform-worth statistics.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge partial-ranking sufficient statistics from another accumulator.

Parameters:

suff_stat (tuple[float, ndarray, ndarray])

Return type:

PlackettLucePartialAccumulator

value()[source]

Return accumulated partial-ranking count, numerator, and denominator statistics.

Return type:

tuple[float, ndarray, ndarray]

from_value(x)[source]

Restore partial-ranking accumulator state from value output.

Parameters:

x (tuple[float, ndarray, ndarray])

Return type:

PlackettLucePartialAccumulator

key_merge(stats_dict)[source]

Merge this partial accumulator into stats_dict under its configured key.

Parameters:

stats_dict (dict[str, Any])

Return type:

None

key_replace(stats_dict)[source]

Replace this accumulator’s state from stats_dict when its key is present.

Parameters:

stats_dict (dict[str, Any])

Return type:

None

acc_to_encoder()[source]

Return the partial-ranking encoder compatible with this accumulator.

Return type:

PlackettLucePartialDataEncoder

class PlackettLucePartialAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Factory for PlackettLucePartialAccumulator.

Parameters:
make()[source]

Create an empty partial-ranking Plackett-Luce accumulator.

Return type:

PlackettLucePartialAccumulator

class PlackettLucePartialDataEncoder(dim)[source]

Bases: DataSequenceEncoder

Encode partial / top-m orderings (variable length) over a fixed item count dim.

Each datum is an ordered list of m <= dim distinct item indices (best first); the remaining items are left unranked. Encoded as a ragged list of 1-D int arrays.

Parameters:

dim (int)

seq_encode(x)[source]

Validate and encode variable-length top-m rankings as ragged arrays.

Raises:

ValueError – If a row is not 1-D, has a non-integer-valued entry (e.g. 0.5, which would otherwise silently truncate to a plausible-looking index instead of being rejected), has more than dim entries, or its (integer) entries are not distinct item indices in 0,...,dim-1.

Parameters:

x (Sequence[Sequence[int]])

Return type:

list[ndarray]

row_count(x)[source]

Return the number of ragged partial-ranking rows.

Parameters:

x (list[ndarray])

Return type:

int

class PlackettLucePartialEstimator(dim, pseudo_count=None, name=None, keys=None)[source]

Bases: ParameterEstimator

MM estimator of Plackett-Luce log-worths from partial / top-m rankings (item count K fixed).

Parameters:
  • dim (int)

  • pseudo_count (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return a factory for partial-ranking MM sufficient statistics.

Return type:

PlackettLucePartialAccumulatorFactory

estimate(nobs, suff_stat)[source]

Return one MM estimate from accumulated partial-ranking sufficient statistics.

Parameters:
Return type:

PlackettLuceDistribution

class PlackettLuceSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw iid Plackett-Luce orderings via the Gumbel-max construction.

Parameters:
  • dist (PlackettLuceDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw orderings (permutations of 0,…,K-1); a single list when size is None.

Parameters:
Return type:

list[int] | list[list[int]]

class RankVector(values)[source]

Bases: Sequence[int]

A permutation whose entry for each item is that item’s rank.

Parameters:

values (tuple[int, ...])

to_item_ordering()[source]

Return the inverse permutation, indexed by rank.

Return type:

ItemOrdering

class RaoKupperDistribution(log_w, nu=1.5, name=None, keys=None, fit_diagnostics=None)[source]

Bases: _BaseTieDistribution

Bradley-Terry with ties via a threshold nu >= 1 (Rao-Kupper 1967).

Parameters:
  • nu (float)

  • name (str | None)

  • keys (str | None)

  • fit_diagnostics (TieModelFitDiagnostics | None)

estimator(pseudo_count=None)[source]

Return the maximum-likelihood Rao-Kupper estimator.

Parameters:

pseudo_count (float | None)

class RaoKupperEstimator(dim, pseudo_count=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Maximum-likelihood Rao-Kupper worths and threshold (L-BFGS on the count matrices).

pseudo_count adds that many fractional wins to every ordered pair and that many ties to every unordered pair; see BradleyTerryEstimator for how to choose it. Without it, data in which some competitor never lost (or never won) has no finite fit and the estimator raises ValueError rather than return a boundary worth.

Parameters:
  • dim (int)

  • pseudo_count (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return the accumulator factory used by this estimator.

Return type:

_TieAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate Rao-Kupper worths and threshold from sufficient statistics.

Parameters:

nobs (float | None)

Return type:

RaoKupperDistribution

class SpearmanRankingAccumulator(dim, name=None, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate item-indexed rank-vector sums from item orderings.

Parameters:
  • dim (int)

  • name (str | None)

  • keys (str | None)

update(x, weight, estimate)[source]

Update from one item ordering.

Parameters:
  • x (Sequence[int] | ItemOrdering)

  • weight (float)

  • estimate (SpearmanRankingDistribution | None)

Return type:

None

initialize(x, weight, rng)[source]

Initialize from one item ordering.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update from encoded item orderings.

Parameters:
  • x (ndarray)

  • weights (ndarray)

  • estimate (SpearmanRankingDistribution | None)

Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize from encoded item orderings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge validated rank-vector statistics.

Parameters:

suff_stat (tuple[float, ndarray])

Return type:

SpearmanRankingAccumulator

value()[source]

Return an ownership-safe sufficient-statistic snapshot.

Return type:

tuple[float, ndarray]

from_value(x)[source]

Restore validated rank-vector statistics.

Parameters:

x (tuple[float, ndarray])

Return type:

SpearmanRankingAccumulator

acc_to_encoder()[source]

Return an encoder with the matching item count.

Return type:

SpearmanRankingDataEncoder

class SpearmanRankingAccumulatorFactory(dim, name=None, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create Spearman ranking accumulators.

Parameters:
  • dim (int)

  • name (str | None)

  • keys (str | None)

make()[source]

Return a fresh accumulator.

Return type:

SpearmanRankingAccumulator

class SpearmanRankingDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Validate and encode full x[rank] = item orderings.

Parameters:

dim (int | None)

seq_encode(x)[source]

Return a dense, support-checked item-ordering matrix.

Parameters:

x (Sequence[Sequence[int] | ItemOrdering])

Return type:

ndarray

row_count(x)[source]

Return the number of encoded item orderings.

Parameters:

x (ndarray)

Return type:

int

class SpearmanRankingDistribution(sigma, rho=1.0, name=None, keys=None, max_dim=_DEFAULT_MAX_DIM, fit_diagnostics=None, *, _sigma_already_centered=False, _sigma_raw_scale_hint=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Exact finite Spearman law over item orderings under a dimension budget.

Known limitation: direct construction from a raw location vector (this class’s sigma argument – see the module docstring’s “possibly fractional mean rank vector”) whose entries share an extremely large common offset – beyond _TRUSTED_SIGMA_RAW_SCALE_CEILING in spearman_rho.py, roughly the range of a 32-bit integer (~2.1e9) – succeeds here, but the one-time float64 cancellation __init__ performs while centering it can leave a residual that a later restore (__pysp_setstate__) cannot always distinguish from genuine state corruption, and may then reject with a ValueError even though it was built validly. The original, pre-centering magnitude is not recoverable from the restored, already-centered state, so this is an accepted, documented limit rather than a bug to silently work around – see the comment above _validate_location in this module for the full reasoning and exact boundary.

Parameters:
  • sigma (Sequence[float] | np.ndarray)

  • rho (float)

  • name (str | None)

  • keys (str | None)

  • max_dim (int)

  • fit_diagnostics (SpearmanRankingFitDiagnostics | None)

  • _sigma_already_centered (bool)

  • _sigma_raw_scale_hint (float | None)

classmethod compute_capabilities()[source]

Declare generated NumPy and Torch scoring support.

classmethod compute_declaration()[source]

Return the generated-compute declaration.

static backend_legacy_sufficient_statistics(x, params, engine)[source]

Return row-wise count and item-indexed rank-vector statistics.

Parameters:
Return type:

tuple[Any, …]

static backend_log_density_from_params(x, sigma, rho, log_const, engine)[source]

Score item orderings after explicit conversion to rank vectors.

Callers arrive under two shape conventions. backend_seq_log_density passes the natural ones – ranks (n, d) against a single sigma (d,). The generated scorer in mixle.stats.compute.declarations pre-aligns both sides instead: data picks up a component axis ((n, 1, d)) and every parameter a leading row axis ((1, k, d)), so the two already broadcast. Inserting a component axis unconditionally, as this did, double-counts it on that path and returns an (n, 1, k) score where the contract is (n, k). Only add the axis when the ranks really are still two-dimensional.

Parameters:
Return type:

Any

property sigma: ndarray

Return an ownership-safe copy of the canonical mean rank vector.

density(x)[source]

Return the probability of an item ordering.

Parameters:

x (Sequence[int] | ItemOrdering)

Return type:

float

log_density(x)[source]

Return the log-probability of one x[rank] = item ordering.

Parameters:

x (Sequence[int] | ItemOrdering)

Return type:

float

seq_log_density(x)[source]

Return vectorized log-probabilities for item orderings.

Parameters:

x (ndarray)

Return type:

ndarray

backend_seq_log_density(x, engine)[source]

Engine-neutral vectorized scoring for encoded item orderings.

Parameters:
Return type:

Any

classmethod backend_stacked_params(dists, engine)[source]

Stack equal-dimensional Spearman parameters.

Parameters:
  • dists (Sequence[SpearmanRankingDistribution])

  • engine (Any)

Return type:

dict[str, Any]

classmethod backend_stacked_log_density(x, params, engine)[source]

Return an observation-by-component score matrix.

Parameters:
Return type:

Any

classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]

Return component-stacked item-indexed rank-vector statistics.

Parameters:
Return type:

tuple[Any, Any]

sampler(seed=None)[source]

Return an exact conditional-permanent sampler.

Parameters:

seed (int | None)

Return type:

SpearmanRankingSampler

estimator(pseudo_count=None)[source]

Return an estimator preserving the dimension and resource budget.

Parameters:

pseudo_count (float | None)

Return type:

SpearmanRankingEstimator

dist_to_encoder()[source]

Return the item-ordering encoder.

Return type:

SpearmanRankingDataEncoder

enumerator()[source]

Return a lazy descending-probability enumerator.

Return type:

SpearmanRankingEnumerator

support_size()[source]

Return the number of full item orderings.

Return type:

int

class SpearmanRankingEnumerator(dist)[source]

Bases: DistributionEnumerator

Enumerate item orderings by increasing rank-to-item assignment cost.

Parameters:

dist (SpearmanRankingDistribution)

class SpearmanRankingEstimator(dim, rho=None, pseudo_count=None, suff_stat=None, name=None, keys=None, max_rho=1.0e6, max_dim=_DEFAULT_MAX_DIM)[source]

Bases: ParameterEstimator

Estimate consensus mean ranks and nonnegative Spearman concentration.

Parameters:
accumulator_factory()[source]

Return a factory for item-ordering sufficient statistics.

Return type:

SpearmanRankingAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate a distribution from validated item-indexed rank sums.

Parameters:
Return type:

SpearmanRankingDistribution

class SpearmanRankingFitDiagnostics(concentration_algorithm, converged, iterations, boundary_solution, regularized, pseudo_count)[source]

Bases: object

Concentration-fit and regularization evidence attached to an estimate.

Parameters:
  • concentration_algorithm (str)

  • converged (bool)

  • iterations (int)

  • boundary_solution (bool)

  • regularized (bool)

  • pseudo_count (float)

class SpearmanRankingSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw exact Spearman item orderings using conditional permanents.

Parameters:
  • dist (SpearmanRankingDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one item ordering or size iid item orderings.

Parameters:
Return type:

list[int] | list[list[int]]

class ThurstoneAccumulator(dim, keys=None)[source]

Bases: SequenceEncodableStatisticAccumulator

Accumulate weighted pairwise-precedence counts from full rankings.

Parameters:
update(x, weight, estimate)[source]

Update pairwise-precedence counts from one full ordering.

Parameters:
Return type:

None

initialize(x, weight, rng)[source]

Initialize precedence counts from one ordering.

Parameters:
Return type:

None

seq_update(x, weights, estimate)[source]

Update pairwise-precedence counts from encoded orderings.

Parameters:
Return type:

None

seq_initialize(x, weights, rng)[source]

Initialize precedence counts from a batch of encoded orderings.

Parameters:
Return type:

None

combine(suff_stat)[source]

Merge validated count and pairwise-precedence statistics.

Parameters:

suff_stat (tuple[float, ndarray])

Return type:

ThurstoneAccumulator

value()[source]

Return an ownership-safe statistics snapshot.

Return type:

tuple[float, ndarray]

from_value(x)[source]

Restore validated accumulator state.

Parameters:

x (tuple[float, ndarray])

Return type:

ThurstoneAccumulator

acc_to_encoder()[source]

Return the ranking encoder compatible with this accumulator.

Return type:

ThurstoneDataEncoder

class ThurstoneAccumulatorFactory(dim, keys=None)[source]

Bases: StatisticAccumulatorFactory

Create accumulators for Thurstone pairwise-precedence statistics.

Parameters:
make()[source]

Create an empty Thurstone accumulator.

Return type:

ThurstoneAccumulator

class ThurstoneApproximationDiagnostics(method, draws, seed, smoothing, distinct_rankings, support_size, maximum_binomial_standard_error)[source]

Bases: object

Provenance and uncertainty scale for the approximating categorical law.

Parameters:
  • method (str)

  • draws (int)

  • seed (int)

  • smoothing (float)

  • distinct_rankings (int)

  • support_size (int)

  • maximum_binomial_standard_error (float)

class ThurstoneDataEncoder(dim=None)[source]

Bases: DataSequenceEncoder

Encode full item orderings into a dense integer matrix.

Parameters:

dim (int | None)

seq_encode(x)[source]

Validate and encode full orderings as a dense integer matrix.

Parameters:

x (Sequence[Sequence[int]])

Return type:

ndarray

row_count(x)[source]

Return the number of encoded ranking rows.

Parameters:

x (ndarray)

Return type:

int

class ThurstoneDistribution(mu, name=None, keys=None, n_mc=4000, seed=0, smoothing=0.5, fit_diagnostics=None, *, _mu_already_centered=False)[source]

Bases: SequenceEncodableProbabilityDistribution

Normalized finite-sample approximation to a Case V Thurstone law.

Parameters:
  • mu (Sequence[float] | np.ndarray)

  • name (str | None)

  • keys (str | None)

  • n_mc (int)

  • seed (int)

  • smoothing (float)

  • fit_diagnostics (ThurstoneFitDiagnostics | None)

  • _mu_already_centered (bool)

classmethod compute_capabilities()[source]

Declare the NumPy execution path used to build the approximation.

density(x)[source]

Return the normalized approximating probability of a full ordering.

Parameters:

x (Sequence[int])

Return type:

float

log_density(x)[source]

Return the normalized approximating log-probability of one ordering.

Parameters:

x (Sequence[int])

Return type:

float

seq_log_density(x)[source]

Return batch-invariant log-probabilities for encoded full orderings.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for this exact approximating categorical law.

Parameters:

seed (int | None)

Return type:

ThurstoneSampler

support_size()[source]

Return the number of full rankings in the smoothed support.

Return type:

int

estimator(pseudo_count=None)[source]

Return a labelled Thurstone-Mosteller pairwise-moment estimator.

Parameters:

pseudo_count (float | None)

Return type:

ThurstoneEstimator

dist_to_encoder()[source]

Return the dense full-ranking encoder used by vectorized methods.

Return type:

ThurstoneDataEncoder

class ThurstoneEstimator(dim, n_mc=4000, seed=0, smoothing=0.5, pseudo_count=None, name=None, keys=None)[source]

Bases: ParameterEstimator

Labelled pairwise-moment estimator for Case V Thurstone utilities.

Parameters:
accumulator_factory()[source]

Return a factory for Thurstone sufficient-statistic accumulators.

Return type:

ThurstoneAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate centered utilities from validated pairwise-precedence statistics.

Parameters:
Return type:

ThurstoneDistribution

class ThurstoneFitDiagnostics(method, exact_mle, regularized, pseudo_count)[source]

Bases: object

Provenance for an estimated Thurstone utility vector.

Parameters:
class ThurstoneMostellerDistribution(mu, name=None, keys=None, fit_diagnostics=None)[source]

Bases: SequenceEncodableProbabilityDistribution

Gaussian/probit paired-comparison model P(i beats j) = Phi((mu_i - mu_j) / sqrt(2)).

Parameters:
  • mu (Sequence[float] | np.ndarray)

  • name (str | None)

  • keys (str | None)

  • fit_diagnostics (ThurstoneMostellerFitDiagnostics | None)

classmethod compute_capabilities()[source]

Return backend capabilities for the probit pairwise likelihood.

density(x)[source]

Return the probability mass of one winner-loser pair.

Parameters:

x (tuple[int, int])

Return type:

float

log_density(x)[source]

Return the JOINT log probability of one winner-loser pair.

The pair is drawn uniformly from all K(K-1)/2 unordered pairs and the winner follows the probit rule, so exp(log_density((i, j))) + exp(log_density((j, i))) is 1/C(K, 2), not one. P(i beats j | compared) is win_probability().

Parameters:

x (tuple[int, int])

Return type:

float

win_probability(i, j)[source]

Return P(i beats j | i and j are compared) = Phi((mu[i] - mu[j]) / sqrt(2)).

Parameters:
Return type:

float

seq_log_density(x)[source]

Score encoded winner-loser pairs.

Parameters:

x (ndarray)

Return type:

ndarray

sampler(seed=None)[source]

Return a sampler for winner-loser comparisons.

Parameters:

seed (int | None)

Return type:

ThurstoneMostellerSampler

estimator(pseudo_count=None)[source]

Return the least-squares probit paired-comparison estimator.

Parameters:

pseudo_count (float | None)

Return type:

ThurstoneMostellerEstimator

dist_to_encoder()[source]

Return the encoder for winner-loser pair data.

Return type:

PairDataEncoder

class ThurstoneMostellerEstimator(dim, pseudo_count=None, name=None, keys=None)[source]

Bases: ParameterEstimator

mu_i - mu_j = sqrt(2) Phi^{-1}(P(i beats j)) from the win-count matrix (least squares).

pseudo_count adds that many fractional wins to every ordered pair before the moment step; see BradleyTerryEstimator for how to choose it and what it does to margins. Here it also keeps a never-lost pair away from the Phi^{-1} clip (clipped_pair_probabilities counts the pairs that hit it).

Parameters:
  • dim (int)

  • pseudo_count (float | None)

  • name (str | None)

  • keys (str | None)

accumulator_factory()[source]

Return the accumulator factory used by this estimator.

Return type:

PairWinAccumulatorFactory

estimate(nobs, suff_stat)[source]

Estimate Thurstone-Mosteller utilities from win-count statistics.

Parameters:

nobs (float | None)

Return type:

ThurstoneMostellerDistribution

class ThurstoneMostellerFitDiagnostics(method, exact_mle, graph_connected, clipped_pair_probabilities, regularized, pseudo_count, strongly_connected)[source]

Bases: object

Provenance and identifiability evidence for the pairwise-moment fit.

Parameters:
  • method (str)

  • exact_mle (bool)

  • graph_connected (bool)

  • clipped_pair_probabilities (int)

  • regularized (bool)

  • pseudo_count (float)

  • strongly_connected (bool)

class ThurstoneMostellerSampler(dist, seed=None)[source]

Bases: DistributionSampler

Sampler for Thurstone-Mosteller winner-loser comparisons.

Parameters:
  • dist (ThurstoneMostellerDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one comparison or a list of comparisons.

Parameters:
Return type:

tuple[int, int] | list[tuple[int, int]]

class TieModelFitDiagnostics(model, converged, status, message, iterations, objective, gradient_norm, worth_boundary_hit, tie_parameter_boundary_hit, graph_connected, regularized, pseudo_count, strongly_connected)[source]

Bases: object

Optimizer, identifiability, and boundary evidence for a tie-model fit.

Parameters:
  • model (str)

  • converged (bool)

  • status (int)

  • message (str)

  • iterations (int)

  • objective (float)

  • gradient_norm (float)

  • worth_boundary_hit (bool)

  • tie_parameter_boundary_hit (bool)

  • graph_connected (bool)

  • regularized (bool)

  • pseudo_count (float)

  • strongly_connected (bool)

class ThurstoneSampler(dist, seed=None)[source]

Bases: DistributionSampler

Draw exactly from a distribution’s empirical-plus-uniform mixture.

Parameters:
  • dist (ThurstoneDistribution)

  • seed (int | None)

sample(size=None, *, batched=True)[source]

Draw one ordering or size iid orderings.

Parameters:
Return type:

list[int] | list[list[int]]

item_ordering_to_rank_vector(value)[source]

Convert x[rank] = item to owned rank[item] = rank data.

Parameters:

value (Sequence[int] | ndarray | ItemOrdering)

Return type:

ndarray

rank_vector_to_item_ordering(value)[source]

Convert rank[item] = rank to owned x[rank] = item data.

Parameters:

value (Sequence[int] | ndarray | RankVector)

Return type:

ndarray

Submodules¶