mixle.stats.sequences.integer_markov_chain module¶
Integer Markov-chain distributions with optional lagged transitions.
The data type: Sequence[int].
For a sequence x of length n >= lag > 0, the log density is
- log(P(x)) = log(P_init(x[0:lag]) + sum_{j=0}^{n-lag-1} log(p_mat(x[j + lag] | x[j],…,x[j+lag-1])) +
log(P_len(n)),
where P_len is evaluated at the actual length and P_init generates
exactly lag bounded-integer states. Shorter sequences are outside the
declared domain.
- exception NonGenerativeIntegerMarkovChainError[source]
Bases:
TypeErrorRaised when a conditional integer-chain factor is asked to generate sequences.
- class IntegerMarkovChainStatistics(schema_version, num_values, lag, transition_counts, initial_nobs, initial, length_nobs, length)[source]
Bases:
NamedTupleImmutable sufficient statistics for one fixed integer-chain support.
- Parameters:
- schema_version: int
Alias for field number 0
- num_values: int
Alias for field number 1
- lag: int
Alias for field number 2
- initial_nobs: float
Alias for field number 4
- length_nobs: float
Alias for field number 6
- class IntegerMarkovChainDistribution(num_values, cond_dist, lag=1, init_dist=NullDistribution(), len_dist=NullDistribution(), keys=None, name=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMarkov-chain distribution over integer-valued states.
- Parameters:
- compute_capabilities()[source]
Declare generated-compute support inherited from initial and length distributions.
- compute_declaration()[source]
Return the generated-compute declaration for the integer Markov chain.
- density_semantics()[source]
Classify missing initial/length laws as conditional likelihood factors.
- density(x)[source]
Density of integer Markov chain evaluated at x.
See log_density() for details.
- log_density(x)[source]
Log-density of integer Markov chain evaluated at x.
The initial child scores exactly the first
lagstates, each later state is scored by its lag-indexed transition row, and the length child scores the actual sequence length. Shorter observations are rejected.
- seq_log_density(x)[source]
Vectorized evaluation of log-density at every observation in encoded sequence.
See log_density() for details on likelihood evaluation.
- Sequence encoded arg ‘x’ is a Tuple of length 7 containing:
seq_len (ndarray[int]): Actual observed sequence lengths. init_idx (ndarray[int]): Observed sequence index of chains with lengths >= lag. seq_idx (ndarray[int]): Observed sequence index of chains with transitions. u_seq_idx (ndarray[object]): Numpy array of tuples containing the unique transitions. u_seq_values (ndarray[object]): Numpy array of tuples containing the transitions. init_enc (Optional[E]): Sequence encoding of initial values (has type E). len_enc (Optional[E2]): Sequence encoding of length values (has type E2).
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for grouped integer Markov-chain encodings.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked integer Markov-chain parameters for shared support/lag.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of integer Markov-chain log densities.
- classmethod backend_stacked_sufficient_statistics_with_estimator(x, weights, params, engine, estimator)[source]
Return per-component versioned fixed-support sufficient statistics.
- sampler(seed=None)[source]
Return a sampler for this integer Markov chain.
- Parameters:
seed (int | None)
- Return type:
IntegerMarkovChainSampler
- transition_sampler(seed=None)[source]
Return a sampler exposing only
sample_givenfor conditional transition use.- Parameters:
seed (int | None)
- Return type:
IntegerMarkovChainSampler
- estimator(pseudo_count=None)[source]
Return an estimator initialized from this integer Markov chain.
- Parameters:
pseudo_count (float | None)
- dist_to_encoder()[source]
Return a data encoder for iid integer Markov-chain observations.
- Return type:
IntegerMarkovChainDataEncoder
- enumerator()[source]
Returns IntegerMarkovChainEnumerator iterating integer sequences in descending probability order.
- Return type:
IntegerMarkovChainEnumerator
- class IntegerMarkovChainEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerates integer Markov-chain sequences in descending probability order.
- Parameters:
dist (IntegerMarkovChainDistribution)
- class IntegerMarkovChainSampler(dist, seed)[source]
Bases:
DistributionSamplerDraw integer-valued sequences from an
IntegerMarkovChainDistribution.- Parameters:
dist (IntegerMarkovChainDistribution)
seed (int | None)
- single_sample()[source]
Returns a single sample from the integer Markov chain distribution.
- sample(size=None, *, batched=True)[source]
Draw iid samples from an integer Markov chain distribution.
With
batched=True(default) andsizenot None, the lengths and initial states are drawn per chain (byte-identical to the loop) and the lag-conditional transitions are vectorized across all live chains at each time index. The transition draws change RNG consumption order, so the output is statistically equivalent but NOT byte-identical tobatched=False. Setbatched=Falseto reproduce the exact legacy per-sequence output for a given seed.- Parameters:
- Returns:
Sequence[int] if size is None, else List[Sequence[int]] with length equal to size.
- Return type:
- class IntegerMarkovChainAccumulator(num_values, lag, init_accumulator=NullAccumulator(), len_accumulator=NullAccumulator(), keys=None, name=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate transition, initial-state, and length statistics for Markov chains.
- Parameters:
- update(x, weight, estimate)[source]
Update sufficient statistics with a single weighted observation.
- initialize(x, weight, rng)[source]
Initialize sufficient statistics from a single observation.
Note: Calls _rng_initialize() to ensure consistency with seq_initialize() function.
- seq_update(x, weights, estimate)[source]
Vectorized update of sufficient statistics from an encoded sequence of observations ‘x’.
- Sequence encoded arg ‘x’ is a Tuple of length 7 containing:
seq_len (ndarray[int]): Actual observed sequence lengths. init_idx (ndarray[int]): Observed sequence index of chains with lengths >= lag. seq_idx (ndarray[int]): Observed sequence index of chains with transitions. u_seq_idx (ndarray[object]): Numpy array of tuples containing the unique transitions. u_seq_values (ndarray[object]): Numpy array of tuples containing the transitions. init_enc (Optional[E]): Sequence encoding of initial values (has type E). len_enc (Optional[E2]): Sequence encoding of length values (has type E2).
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident E-step: per-unique-transition counts are reduced on the active engine before being scattered into the sparse transition dict; the init/len children are routed through the engine. Matches seq_update.
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of sufficient statistics from an encoded sequence of observations in ‘x’.
Note: Calls _rng_initialize() to ensure consistency with seq_initialize() function.
- Sequence encoded arg ‘x’ is a Tuple of length 7 containing:
seq_len (ndarray[int]): Actual observed sequence lengths. init_idx (ndarray[int]): Observed sequence index of chains with lengths >= lag. seq_idx (ndarray[int]): Observed sequence index of chains with transitions. u_seq_idx (ndarray[object]): Numpy array of tuples containing the unique transitions. u_seq_values (ndarray[object]): Numpy array of tuples containing the transitions. init_enc (Optional[E]): Sequence encoding of initial values (has type E). len_enc (Optional[E2]): Sequence encoding of length values (has type E2).
- combine(suff_stat)[source]
Combine another versioned fixed-support statistic into this accumulator.
- Parameters:
suff_stat (IntegerMarkovChainStatistics) – See above for details.
- Returns:
This accumulator after combination.
- Return type:
IntegerMarkovChainAccumulator
- value()[source]
Return copied child statistics and immutable canonical transition counts.
- Return type:
IntegerMarkovChainStatistics
- from_value(x)[source]
Restore accumulator state from a versioned fixed-support statistic.
- Parameters:
x (IntegerMarkovChainStatistics) – See above for details.
- Returns:
This accumulator after restoration.
- Return type:
IntegerMarkovChainAccumulator
- scale(c)[source]
Scale numeric evidence while preserving support and schema metadata.
- Parameters:
c (float)
- Return type:
IntegerMarkovChainAccumulator
- key_merge(stats_dict)[source]
Merge this accumulator into keyed sufficient statistics.
- Parameters:
stats_dict (Dict[str, Any]) – Dictionary mapping keys to corresponding sufficient statistics.
- Returns:
None.
- Return type:
None
- key_replace(stats_dict)[source]
Replace this accumulator’s statistics from matching keyed values.
- Parameters:
stats_dict (Dict[str, Any]) – Dictionary mapping keys to corresponding sufficient statistics.
- Returns:
None.
- Return type:
None
- acc_to_encoder()[source]
Return a data encoder built from the child accumulators.
- Return type:
IntegerMarkovChainDataEncoder
- class IntegerMarkovChainAccumulatorFactory(num_values, lag, init_factory=NullAccumulatorFactory(), len_factory=NullAccumulatorFactory(), keys=None, name=None)[source]
Bases:
StatisticAccumulatorFactoryCreate integer Markov-chain accumulators with child accumulator factories.
- Parameters:
- make()[source]
Return a new integer Markov-chain accumulator.
- Return type:
IntegerMarkovChainAccumulator
- class IntegerMarkovChainEstimator(num_values, lag=1, init_estimator=NullEstimator(), len_estimator=NullEstimator(), init_dist=None, len_dist=None, pseudo_count=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate integer Markov-chain transition probabilities and child models.
- Parameters:
- get_prior()[source]
Returns the implicit per-row symmetric-Dirichlet prior
pseudo_countinduces, or None.pseudo_countsmoothing (cond_mat += pseudo_countbefore row-normalizing inestimate()) is the exact MAP point estimate under an independentSymmetricDirichletDistribution(pseudo_count + 1)prior on each row of the conditional matrix – seemodel_log_density(). Letsmixle.inference.estimation.optimize()auto-detect the'map'objective instead of silently tracking plain (unpenalized) MLE for a pseudo-count-regularized fit.
- model_log_density(model)[source]
Log-density of the fitted conditional matrix under the implicit row prior (see
get_prior()), plusinit_dist/len_dist’s ownmodel_log_densitywhen the estimator that actually fit them (rather than a fixed, caller-supplied distribution) exposes one. Returns0.0(a plain MLE fit) whenpseudo_countis None.- Parameters:
model (IntegerMarkovChainDistribution)
- Return type:
- accumulator_factory()[source]
Return an accumulator factory configured from this estimator.
- Return type:
IntegerMarkovChainAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate an integer Markov-chain distribution from versioned sufficient statistics.
- Parameters:
nobs (Optional[float]) – Number of observations used in aggregation of ‘suff_stat’.
suff_stat (IntegerMarkovChainStatistics) – See above for details.
- Returns:
IntegerMarkovChainDistribution object.
- Return type:
IntegerMarkovChainDistribution
- class IntegerMarkovChainDataEncoder(num_values, lag, init_encoder=NullDataEncoder(), len_encoder=NullDataEncoder())[source]
Bases:
DataSequenceEncoderEncode integer-valued sequences for vectorized Markov-chain scoring.
- Parameters:
- seq_encode(x)[source]
Encode iid observations from an integer Markov chain.
- The returned tuple contains:
seq_len (ndarray[int]): Actual observed sequence lengths. init_idx (ndarray[int]): Observed sequence index of chains with lengths >= lag. seq_idx (ndarray[int]): Observed sequence index of chains with transitions. u_seq_idx (ndarray[object]): Numpy array of tuples containing the unique transitions. u_seq_values (ndarray[object]): Numpy array of tuples containing the transitions. init_enc (Optional[E]): Sequence encoding of initial values (has type E). len_enc (Optional[E2]): Sequence encoding of length values (has type E2).