mixle.stats.sequences.integer_markov_chain module¶
Create, estimate, and sample from a Markov chain with support on the integers (chain can include a lag).
Defines the IntegerMarkovChainDistribution, IntegerMarkovChainSampler, IntegerMarkovChainAccumulatorFactory, IntegerMarkovChainAccumulator, IntegerMarkovChainEstimator, and the IntegerMarkovChainDataEncoder classes for use with mixle.
The data type: Sequence[int].
Consider a sequence of length n > 0 s.t. x = (x[0],x[1],…,x[n-1]). With lag > 0, we have the integer Markov chain has a log-density given by:
- log(P(x)) = log(P_init(x[0:lag]) + sum_{j=0}^{n-1} log(p_mat(x[j + lag] | x[j], x[j+1],..,x[j+lag-1])) +
log(P_len(n)),
where P_len(n) is the density for the length distribution evaluated for length ‘n’, and P_init() is the density for the initial distribution. If the sequence length is less than the lag, i.e. len(x) < lag, then
log(P(x)) = log(P_len(n)).
Note: P_len() should be compatible with non-negative integers. P_init() must be compatible with sequences of ints.
- 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]
- compute_declaration()[source]
- 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.
Consider a sequence of length n > 0 s.t. x = (x[0],x[1],…,x[n-1]). With lag > 0, we have log-density given by:
- log(P(x)) = log(P_init(x[0:lag]) + sum_{j=0}^{n-1} log(p_mat(x[j + lag] | x[j], x[j+1],..,x[j+lag-1])) +
log(P_len(n)),
where P_len(n) is the density for the length distribution evaluated for length ‘n’, and P_init() is the density for the initial distribution. If the sequence length is less than the lag, i.e. len(x) < lag, then
log(P(x)) = log(P_len(n)).
- 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]): Lengths of chains - lag. If less than lag length is 0. 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 legacy
(transition_counts, initial_stat, length_stat)statistics.
- sampler(seed=None)[source]
Returns an IntegerMarkovChainSampler object.
- Parameters:
seed (int | None)
- Return type:
IntegerMarkovChainSampler
- estimator(pseudo_count=None)[source]
Returns an IntegerMarkovChainEstimator object.
- Parameters:
pseudo_count (float | None)
- dist_to_encoder()[source]
Returns an IntegerMarkovChainDataEncoder object for encoding sequences of 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:
DistributionSampler- 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(lag, init_accumulator=NullAccumulator(), len_accumulator=NullAccumulator(), keys=None, name=None)[source]
Bases:
SequenceEncodableStatisticAccumulator- Parameters:
- update(x, weight, estimate)[source]
Update the sufficient statistics of object instance with a single 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]): Lengths of chains - lag. If less than lag length is 0. 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]): Lengths of chains - lag. If less than lag length is 0. 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 sufficient statistics with object instance.
- Arg suff_stat is a Tuple of length 3 containing:
suff_stat[0] (Dict[Tuple[Tuple[int, …], int], float]): Dictionary mapping state transition counts. suff_stat[1] (Optional[SS1]): Optional sufficient statistics for init accumulator of type SS1. suff_stat[2] (Optional[SS2]): Optional sufficient statistics for length accumulator of type SS2.
- value()[source]
Returns sufficient statistics of integer Markov chain.
- Returned suff_stat is a Tuple of length 3 containing:
suff_stat[0] (Dict[Tuple[Tuple[int, …], int], float]): Dictionary mapping state transition counts. suff_stat[1] (Optional[SS1]): Optional sufficient statistics for init accumulator of type SS1. suff_stat[2] (Optional[SS2]): Optional sufficient statistics for length accumulator of type SS2.
- from_value(x)[source]
Set sufficient statistics of object instance to aggregated sufficient statistics in arg ‘x’.
- Arg value ‘x’ is a Tuple of length 3 containing:
x[0] (Dict[Tuple[Tuple[int, …], int], float]): Dictionary mapping state transition counts. x[1] (Optional[SS1]): Optional sufficient statistics for init accumulator of type SS1. x[2] (Optional[SS2]): Optional sufficient statistics for length accumulator of type SS2.
- key_merge(stats_dict)[source]
Merge sufficient statistics of object instance with matching keys in stats_dict.
- Parameters:
stats_dict (Dict[str, Any]) – Dictionary mapping keys to corresponding sufficient statistics.
- Returns:
None.
- Return type:
None
- key_replace(stats_dict)[source]
Replace the sufficient statistics of object instance with those containing matching keys in ‘stats_dict’.
- Parameters:
stats_dict (Dict[str, Any]) – Dictionary mapping keys to corresponding sufficient statistics.
- Returns:
None.
- Return type:
None
- acc_to_encoder()[source]
Returns IntegerMarkovChainDataEncoder object.
- Return type:
IntegerMarkovChainDataEncoder
- class IntegerMarkovChainAccumulatorFactory(lag, init_factory=NullAccumulatorFactory(), len_factory=NullAccumulatorFactory(), keys=None, name=None)[source]
Bases:
StatisticAccumulatorFactory- Parameters:
- make()[source]
Returns an IntegerMarkovChainAccumulator object from instance.
- 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:
ParameterEstimator- Parameters:
- accumulator_factory()[source]
Returns an IntegerMarkovChainAccumulatorFactory object from attributes values.
- Return type:
IntegerMarkovChainAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate IntegerMarkovChainDistribution object from aggregated sufficient statistics in arg ‘suff_stat’.
- Arg ‘suff_stat’ is a Tuple of length 3 containing:
suff_stat[0] (Dict[Tuple[Tuple[int, …], int], float]): Dictionary mapping state transition counts. suff_stat[1] (Optional[SS1]): Optional sufficient statistics for init accumulator of type SS1. suff_stat[2] (Optional[SS2]): Optional sufficient statistics for length accumulator of type SS2.
- class IntegerMarkovChainDataEncoder(lag, init_encoder=NullDataEncoder(), len_encoder=NullDataEncoder())[source]
Bases:
DataSequenceEncoder- Parameters:
lag (int)
init_encoder (DataSequenceEncoder)
len_encoder (DataSequenceEncoder)
- seq_encode(x)[source]
Encode sequence of iid observations from integer Markov chain.
- Returns a Tuple of length 7 containing:
seq_len (ndarray[int]): Lengths of chains - lag. If less than lag length is 0. 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).