dit.inference

Module for basic inference tools.

Classes

EntropyRatePosterior

Posterior samples of the entropy rate, from entropy_rate_posterior().

MarkovOrderTest

The result of markov_order_test().

Trials

Independent realizations (trials) of the same process.

Functions

binned

Discretize a real-valued list.

block_entropy

Estimate \(H[X_{0:L}]\), the entropy of overlapping length-length words.

block_surrogates

Randomly permute contiguous blocks of data.

conditional_entropy_rate

Estimate \(h_L = H[X_L \mid X_{0:L}] = H[X_{0:L+1}] - H[X_{0:L}]\).

conditional_mutual_information

Estimate \(I[X : Y \mid Z]\) in bits from paired samples.

copula_normalize

Map each column of data through its empirical CDF and then the inverse standard normal CDF, giving standard normal marginals with the same ranks.

cross_entropy_knn

Estimate the differential cross entropy \(-\mathbb{E}_P[\log q(X)]\) from samples x of \(P\) and y of \(Q\) [LPS08].

differential_entropy_knn

Compute the differential entropy of data using a k-nearest neighbors density estimator.

dispersion_entropy

The dispersion entropy of a real-valued series [RA16].

dist_from_timeseries

Infer a distribution from time series observations.

distribution_from_data

Returns a distribution over words of length L from d.

entropy_0

Estimate the entropy of length length subsequences in data.

entropy_1

Estimate the entropy of length length subsequences in data.

entropy_2

Estimate the entropy of length length subsequences in data.

entropy_from_counts

Estimate an entropy, in bits, from a vector of outcome counts.

entropy_rate_posterior

Posterior samples of the entropy rate under an order-order Markov model.

gaussian_copula_mutual_information

Estimate \(I[X : Y \mid Z]\) with the Gaussian copula [IGK+17].

get_counts

Count the occurrences of all words of length in data.

jackknife_entropy

The delete-one jackknife of an entropy estimator, with its variance.

jensen_shannon_divergence_knn

Estimate the Jensen–Shannon divergence of \(P\) and \(Q\) from samples.

kullback_leibler_divergence_knn

Estimate \(D_{KL}[P \| Q]\) from samples x of \(P\) and y of \(Q\).

lz76_complexity

The Lempel–Ziv (1976) complexity of a sequence [LZ76].

lz_entropy_rate

Estimate the entropy rate in bits per symbol from match lengths.

markov_order_test

Test the null hypothesis that data is Markov of order order against the alternative that it is of order order + 1.

multiscale_permutation_entropy

The permutation entropy of a series coarse-grained at scales 1 through scale [AA05].

mutual_information_mixed_ksg

Estimate \(I[X : Y]\) from samples that may be discrete, continuous, or a mixture of the two [GKOV17].

ordinal_patterns

Map each delay window of a real-valued series to its ordinal pattern.

permutation_entropy

The permutation entropy of a real-valued series [BP02].

relative_rank

The rank of each value among the order values preceding it.

renyi_entropy_knn

Estimate the differential Rényi entropy \(\frac{1}{1 - q} \log \int f^q\) from samples [LPS08].

select_markov_order

Estimate the Markov order of data.

shift_surrogates

Circularly shift data by uniformly random nonzero offsets.

stationary_bootstrap

Resample a series with the stationary bootstrap [PR94a].

total_correlation_ksg

Compute the total correlation from observations.

tsallis_entropy_knn

Estimate the differential Tsallis entropy \(\frac{1}{q - 1} \left(1 - \int f^q\right)\) from samples [LPS08].

weighted_permutation_entropy

The weighted permutation entropy of a real-valued series [FCKPrincipe13].

whittle_count

The natural log of the number of sequences sharing the observed (order + 1)-gram counts, first order-word, and last order-word.

whittle_surrogates

Draw surrogates that exactly preserve the (order + 1)-gram counts.

Exceptions

UndersamplingWarning

Warned when counts are too sparse for plug-in (and most bias-corrected) information estimates to be trusted.

Reference

class EntropyRatePosterior(samples: ndarray, order: int)[source]

Bases: object

Posterior samples of the entropy rate, from entropy_rate_posterior().

samples

Entropy rates (bits per symbol) of chains drawn from the posterior.

Type:

np.ndarray

order

The Markov order of the model.

Type:

int

property mean

The posterior mean.

interval(confidence=0.95)[source]

The equal-tailed credible interval with the given coverage.

class MarkovOrderTest(order: int, statistic: str, value: float, pvalue: float, dof: int, null: ndarray | None = None, n_windows: int | None = None)[source]

Bases: object

The result of markov_order_test().

order

The Markov order of the null hypothesis.

Type:

int

statistic

The name of the test statistic.

Type:

str

value

The observed value of the statistic.

Type:

float

pvalue

The p-value of the observed statistic.

Type:

float

dof

Degrees of freedom of the asymptotic chi-squared distribution.

Type:

int

null

The statistic evaluated on each surrogate (exact tests only).

Type:

np.ndarray or None

n_windows

The number of (order + 2)-windows (the effective sample size).

Type:

int or None

class Trials(iterable=(), /)[source]

Bases: list

Independent realizations (trials) of the same process.

Wrap a list of sequences in Trials to tell the estimators in dit.inference that they are separate recordings: counts are pooled across trials, but no word ever spans the boundary between two trials. Trials may have different lengths.

Examples

>>> from dit.inference import Trials, block_entropy
>>> block_entropy(Trials([[0, 1], [1, 0]]), 2)  # (1, 1) never straddles the trials
1.0
binned(ts, bins=2, style='maxent')[source]

Discretize a real-valued list.

Parameters:
  • ts (ndarray) – The real-valued array to bin

  • bins (int) – The number of bins to map the data into.

  • style (str, {'maxent', 'uniform'}) – The method of discretizing the data. Defaults to ‘maxent’.

Returns:

symb – The discretized time-series.

Return type:

ndarray

Raises:

ValueError – Raised if style is not a recognized method.

block_entropy(data, length, estimator='plugin')[source]

Estimate \(H[X_{0:L}]\), the entropy of overlapping length-length words.

Parameters:
  • data (iterable or Trials) – The sequence, or independent Trials (words never span two trials). Rows of a 2D array are joint symbols.

  • length (int) – The word length \(L\).

  • estimator (str) – See entropy_from_counts().

Returns:

h – The estimated block entropy in bits.

Return type:

float

block_surrogates(data, block_length, n=1, rng=None)[source]

Randomly permute contiguous blocks of data.

Dependencies shorter than block_length are (mostly) kept, while longer ones are destroyed.

Parameters:
  • data (iterable or Trials) – The sequence to shuffle (along the first axis); blocks never move between Trials.

  • block_length (int) – The length of each block; the final block may be shorter.

  • n (int) – The number of surrogates.

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

surrogates – Shape (n,) + np.shape(data), or a list of n Trials.

Return type:

np.ndarray or list of Trials

conditional_entropy_rate(data, L, estimator='plugin')[source]

Estimate \(h_L = H[X_L \mid X_{0:L}] = H[X_{0:L+1}] - H[X_{0:L}]\).

As L grows, \(h_L\) decreases to the entropy rate; for a Markov chain of order \(R\) it equals the entropy rate for all \(L \geq R\) [CT06]. Use select_markov_order() to choose L. Bias-corrected estimator choices matter most when the number of observed words is not small compared to the sample size.

Parameters:
  • data (iterable or Trials) – The sequence, or independent Trials (words never span two trials). Rows of a 2D array are joint symbols.

  • L (int) – The history length.

  • estimator (str) – See entropy_from_counts().

Returns:

h – The estimated conditional entropy in bits.

Return type:

float

conditional_mutual_information(x, y, z=None, estimator='plugin', alphabet_sizes=None)[source]

Estimate \(I[X : Y \mid Z]\) in bits from paired samples.

Parameters:
  • x (array_like) – Samples of each variable; rows of 2D arrays are joint outcomes.

  • y (array_like) – Samples of each variable; rows of 2D arrays are joint outcomes.

  • z (array_like, None) – Samples of the conditioning variable. If None, estimate \(I[X : Y]\).

  • estimator (str) – The entropy estimator applied to each term; see entropy_from_counts().

  • alphabet_sizes (tuple of int, None) – The numbers of possible outcomes of x, y and z, used by estimators that need an alphabet size (such as 'nsb' or 'shrink'); each joint term gets the product of its variables’ sizes. Defaults to the number of distinct observed values of each variable.

Returns:

cmi

Return type:

float

copula_normalize(data)[source]

Map each column of data through its empirical CDF and then the inverse standard normal CDF, giving standard normal marginals with the same ranks.

Parameters:

data (array_like) – The samples, one per row.

Returns:

normed – The copula-normalized samples, as a 2D array.

Return type:

np.ndarray

cross_entropy_knn(x, y, k=4, noise=1e-10, rng=None)[source]

Estimate the differential cross entropy \(-\mathbb{E}_P[\log q(X)]\) from samples x of \(P\) and y of \(Q\) [LPS08].

The density of \(Q\) at each \(x_i\) is estimated from the distance \(\nu_k(i)\) to its k-th nearest neighbor among the y (max norm):

\[\hat{H}(P, Q) = \psi(m) - \psi(k) + d \log 2 + \frac{d}{n} \sum_i \log \nu_k(i)\]
Parameters:
  • x (np.ndarray) – Samples of \(P\) (n rows) and \(Q\) (m rows) with the same number d of columns.

  • y (np.ndarray) – Samples of \(P\) (n rows) and \(Q\) (m rows) with the same number d of columns.

  • k (int) – The number of nearest neighbors.

  • noise (float) – The standard deviation of the normally-distributed noise added to break ties.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

xh – The estimated cross entropy, in bits.

Return type:

float

differential_entropy_knn(data, rvs=None, k=4, noise=1e-10, rng=None)[source]

Compute the differential entropy of data using a k-nearest neighbors density estimator.

Parameters:
  • data (np.ndarray) – The data.

  • rvs (list) – The columns of data to use as the random variable. If None, use all.

  • k (int) – The number of nearest neighbors to use.

  • noise (float) – The standard deviation of the normally-distributed noise to add to data.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

h – The estimated entropy.

Return type:

float

Notes

The entropy is returned in units of bits.

dispersion_entropy(ts, classes=3, order=3, delay=1, mapping='ncdf', normalize=False, estimator='plugin')[source]

The dispersion entropy of a real-valued series [RA16].

Each value is mapped to one of classes levels, through the normal CDF with the series’ mean and standard deviation (mapping='ncdf') or by min-max scaling ('linear'): a scaled value \(y \in [0, 1]\) gets class \(\min(\lfloor c y \rfloor + 1, c)\). The dispersion entropy is the entropy of the length-order patterns of classes, taken delay apart. Unlike permutation_entropy() it keeps amplitude information and has no ties to break.

Parameters:
  • ts (array_like) – The real-valued series.

  • classes (int) – The number of classes \(c\).

  • order (int) – The pattern length \(m\) and the delay between its entries.

  • delay (int) – The pattern length \(m\) and the delay between its entries.

  • mapping ({'ncdf', 'linear'}) – How values are scaled to \([0, 1]\) before classing.

  • normalize (bool) – Divide by \(m \log_2 c\), giving a value in \([0, 1]\).

  • estimator (str) – See entropy_from_counts(); alphabet-dependent estimators use \(c^m\) patterns.

Returns:

h – The dispersion entropy, in bits. It is 0 for a constant series.

Return type:

float

dist_from_timeseries(observations, history_length=1, base='linear', max_history=None, rng=None)[source]

Infer a distribution from time series observations. For each variable, infer a history_length past and a single observation present.

Parameters:
  • observations (list of tuples, ndarray, Trials) – A sequence of observations in time order, or independent Trials whose windows are pooled without any window spanning two trials.

  • history_length (int or str) – The history length to utilize. If a string, the history length is the Markov order of the joint series estimated by select_markov_order(): 'auto' (the exact surrogate test) or one of its methods 'exact', 'chi2', 'aic', 'bic'.

  • base (float, str) – The base to use for the distribution. Defaults to ‘linear’.

  • max_history (int, None) – The largest history length considered when history_length is a string. Defaults to the largest L with M**(L + 1) <= N / 5, for M joint symbols and N observations.

  • rng (None, int, Generator, RandomState) – Source of randomness for 'auto' / 'exact'.

Returns:

ts – A distribution with the first half of the indices as the pasts of the various time series, and the second half their present values.

Return type:

Distribution

distribution_from_data(d, L, trim=True, base=None)[source]

Returns a distribution over words of length L from d.

The returned distribution is the naive estimate of the distribution, which assigns probabilities equal to the number of times a particular word appeared in the data divided by the total number of times a word could have appeared in the data.

Roughly, it corresponds to the stationary distribution of a maximum likelihood estimate of the transition matrix of an (L-1)th order Markov chain.

Parameters:
  • d (list or Trials) – A list of symbols to be converted into a distribution, or independent Trials, whose word counts are pooled without any word spanning two trials.

  • L (integer) – The length of the words for the distribution.

  • trim (bool) – If true, then words with zero probability are trimmed from the distribution.

  • base (int or string) – The desired base of the returned distribution. If None, then the value of dit.ditParams[‘base’] is used.

Notes

With trim=True only the observed words are built, rather than all len(alphabet) ** L of them. A Distribution still indexes its outcomes densely by each variable’s alphabet, so for large alphabets and word lengths use the count-level estimators (block_entropy(), conditional_entropy_rate()), which never build a distribution.

entropy_0(data, length=1)[source]

Estimate the entropy of length length subsequences in data.

Parameters:
  • data (iterable) – An iterable of samples.

  • length (int) – The length to group samples into.

Returns:

h0 – An estimate of the entropy.

Return type:

float

Notes

This returns the naive estimate of the entropy.

entropy_1(data, length=1)[source]

Estimate the entropy of length length subsequences in data.

Parameters:
  • data (iterable) – An iterable of samples.

  • length (int) – The length to group samples into.

Returns:

h1 – An estimate of the entropy.

Return type:

float

Notes

This is the digamma correction \(\hat{H} = \psi(N) - \sum_i \frac{n_i}{N} \psi(n_i)\), the leading term of Grassberger’s estimator [Gra88] (not the Miller–Madow correction; see entropy_from_counts()).

If M is the alphabet size and N is the number of samples, then the bias of this estimator is:

B ~ M/N

entropy_2(data, length=1)[source]

Estimate the entropy of length length subsequences in data.

Parameters:
  • data (iterable) – An iterable of samples.

  • length (int) – The length to group samples into.

Returns:

h2 – An estimate of the entropy.

Return type:

float

Notes

This is Grassberger’s (2003) estimator [Gra03], \(\hat{H} = \psi(N) - \sum_i \frac{n_i}{N} G(n_i)\) with \(G(n) = \psi(n) + \tfrac{1}{2}(-1)^n [\psi(\tfrac{n+1}{2}) - \psi(\tfrac{n}{2})]\), using \(\psi(N)\) in place of Grassberger’s \(\ln N\). It is not the Nemenman–Shafee–Bialek (NSB) estimator.

If M is the alphabet size and N is the number of samples, then the bias of this estimator is:

B ~ (M+1)/(2N)

entropy_from_counts(counts, estimator='plugin', alphabet_size=None)[source]

Estimate an entropy, in bits, from a vector of outcome counts.

Parameters:
  • counts (array_like) – The number of times each outcome was observed. Zeros are ignored.

  • estimator (str) –

    One of:

    • 'plugin' — the maximum-likelihood (naive) estimate.

    • 'miller_madow' — plug-in plus \((K - 1) / 2N\) nats for \(K\) observed outcomes [Mil55].

    • 'digamma' — \(\psi(N) - \sum_i \frac{n_i}{N} \psi(n_i)\) [Gra88] (as entropy_1()).

    • 'grassberger' — Grassberger’s (2003) estimator [Gra03].

    • 'chao_shen' — coverage-adjusted Horvitz–Thompson estimator, which accounts for unseen outcomes [CS03].

    • 'nsb' — the Nemenman–Shafee–Bialek Bayesian estimator, which averages Dirichlet priors so that the prior on the entropy is nearly uniform [NSB02]. Needs alphabet_size.

    • 'zhang' — Zhang’s estimator, whose bias decays exponentially in \(N\) [Zha12], computed as in [LCBFiC17].

    • 'chao_wang_jost' — the estimator of Chao, Wang & Jost, built from the rate at which new outcomes are discovered [CWJ13].

    • 'shrink' — the plug-in entropy of the James–Stein shrinkage of the empirical distribution toward uniform [HS09]. Needs alphabet_size.

    • 'bayes_jeffreys', 'bayes_laplace', 'bayes_perks', 'bayes_minimax' — the plug-in entropy of the posterior mean under a symmetric Dirichlet prior with concentration \(1/2\) (Krichevsky–Trofimov [KT81]), \(1\), \(1/K\), and \(\sqrt{N}/K\) [HS09]. Need alphabet_size.

    • 'ansb' — the asymptotic NSB estimate \((\gamma - \ln 2) + 2 \ln N - \psi(\Delta)\), with \(\Delta\) the number of coincidences (samples minus distinct outcomes), for \(N \ll K\) [NBdRvS04]. It raises if there are no coincidences and is badly biased when \(N\) is comparable to \(K\).

    • 'bonachela' — Bonachela, Hinrichsen & Muñoz’s estimator, which balances bias and variance on short series rather than minimizing bias [BHMunoz08]. It sums over the observed outcomes.

    • 'good_turing' — the plug-in entropy of the simple Good–Turing probabilities [GS95]. The unseen mass \(N_1/N\) is shared among the unseen outcomes implied by alphabet_size.

    • 'jackknife' — the delete-one jackknife of the plug-in estimate [ES81]; see jackknife_entropy() to jackknife any estimator.

    • 'panzeri_treves' — plug-in plus \((\tilde{R} - 1)/2N\), with \(\tilde{R}\) a Bayesian count of the relevant outcomes [PT96].

    • 'quadratic_extrapolation' — fits \(H_\infty + b/n + c/n^2\) to the plug-in entropy at \(n = N, N/2, N/4\) [SKdRvSB98], using the exact expected entropy of random subsamples rather than a particular split.

    • 'wu_yang' — the minimax-rate estimator built from the best polynomial approximation of \(-p \ln p\) [WY16]. Its degree, \(\lfloor 1.6 \ln K \rfloor\), is capped at 22.

    • 'bub' — Paninski’s best-upper-bound estimator, linear in the count histogram, minimizing a bound on the worst-case error [Pan03]. It is meant for \(N/K \lesssim 100\).

    • 'unseen' — the entropy of the probability histogram recovered by linear programming from the fingerprint [VV17].

    • 'pym' — the posterior mean under a mixture of Pitman–Yor process priors, suited to heavy-tailed distributions on unbounded alphabets [APP14]. It raises without repeated outcomes.

  • alphabet_size (int, None) – The number of possible outcomes \(K\), used by 'nsb', 'shrink', the 'bayes_*' estimators, 'good_turing', 'panzeri_treves', 'wu_yang' and 'bub'. Defaults to len(counts), so pass a count vector that includes the zero counts or set this explicitly.

Returns:

h – The estimated entropy in bits.

Return type:

float

Warns:

UndersamplingWarning – If more than a fifth as many outcomes were observed as samples.

entropy_rate_posterior(data, order, prior=0.5, n_samples=1000, rng=None)[source]

Posterior samples of the entropy rate under an order-order Markov model.

Each history’s next-symbol distribution gets an independent symmetric Dirichlet(prior) prior, so its posterior is Dirichlet(counts + prior). For each posterior draw of the transition probabilities, the entropy rate \(h_\mu = \sum_u \pi(u) H[X_k \mid X_{0:k} = u]\) is computed from the draw’s own stationary distribution \(\pi\) [SCHubler07].

Parameters:
  • data (iterable or Trials) – The observed sequence, or independent Trials. Rows of a 2D array are joint symbols.

  • order (int) – The Markov order \(k\); choose it with select_markov_order().

  • prior (float) – The Dirichlet concentration per symbol. 0.5 is the Jeffreys prior, 1 the uniform prior.

  • n_samples (int) – The number of posterior draws.

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

posterior

Return type:

EntropyRatePosterior

Notes

Every history, observed or not, is included, and a positive prior makes the sampled chain irreducible, so each draw has a unique stationary distribution. Histories never observed contribute prior-dominated rows weighted by their (small) stationary probability. The posterior reflects uncertainty given the order; it does not account for choosing the order from the same data.

gaussian_copula_mutual_information(x, y, z=None, bias_correct=True)[source]

Estimate \(I[X : Y \mid Z]\) with the Gaussian copula [IGK+17].

Each variable is copula-normalized (copula_normalize()) and the information is computed for a Gaussian with the resulting covariance. This is a lower bound on the true information (exact when the copula is Gaussian), insensitive to the marginals, and fast and stable in high dimensions.

Parameters:
  • x (array_like) – Paired continuous samples, one per row.

  • y (array_like) – Paired continuous samples, one per row.

  • z (array_like, None) – Samples of the conditioning variable. If None, estimate \(I[X : Y]\).

  • bias_correct (bool) – Remove the analytic finite-sample bias of each Gaussian entropy.

Returns:

mi – The estimate, in bits.

Return type:

float

get_counts(data, length)[source]

Count the occurrences of all words of length in data.

Parameters:
  • data (iterable) – The sequence of samples

  • length (int) – The length to group samples into.

Returns:

counts – Array with the count values.

Return type:

np.array

jackknife_entropy(counts, estimator='plugin', alphabet_size=None)[source]

The delete-one jackknife of an entropy estimator, with its variance.

With \(\hat{H}_{-i}\) the estimate after removing one sample of outcome \(i\), the jackknifed estimate is \(N \hat{H} - \frac{N-1}{N} \sum_i n_i \hat{H}_{-i}\), which removes the \(1/N\) term of the bias, and the jackknife variance is \(\frac{N-1}{N} \sum_i n_i (\hat{H}_{-i} - \bar{H})^2\) [ES81].

Parameters:
Returns:

  • h (float) – The jackknifed entropy estimate, in bits.

  • variance (float) – The jackknife estimate of its variance, in bits squared.

jensen_shannon_divergence_knn(x, y, k=4, noise=1e-10, rng=None)[source]

Estimate the Jensen–Shannon divergence of \(P\) and \(Q\) from samples.

The pooled samples are a sample of the mixture \(M = \pi P + (1 - \pi) Q\) with \(\pi = n / (n + m)\), so this is \(h(M) - \pi h(P) - (1 - \pi) h(Q)\) with each differential entropy from differential_entropy_knn() [Lin91]. With equal sample sizes it is the usual (equally weighted) divergence.

Parameters:
  • x (np.ndarray) – Samples of \(P\) and \(Q\) with the same number of columns.

  • y (np.ndarray) – Samples of \(P\) and \(Q\) with the same number of columns.

  • k (int) – The number of nearest neighbors.

  • noise (float) – The standard deviation of the normally-distributed noise added to break ties.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

jsd – The estimated divergence, in bits.

Return type:

float

kullback_leibler_divergence_knn(x, y, k=4, noise=1e-10, rng=None)[source]

Estimate \(D_{KL}[P \| Q]\) from samples x of \(P\) and y of \(Q\).

This is the nearest-neighbor estimator of Wang, Kulkarni & Verdú [WKVerdu09], \(\frac{d}{n} \sum_i \log \frac{\nu_k(i)}{\rho_k(i)}\) plus a sample-size correction, where \(\rho_k(i)\) is the distance from \(x_i\) to its k-th nearest neighbor among the other x and \(\nu_k(i)\) among the y. It equals cross_entropy_knn() minus differential_entropy_knn().

Parameters:
  • x (np.ndarray) – Samples of \(P\) and \(Q\) with the same number of columns.

  • y (np.ndarray) – Samples of \(P\) and \(Q\) with the same number of columns.

  • k (int) – The number of nearest neighbors.

  • noise (float) – The standard deviation of the normally-distributed noise added to break ties.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

dkl – The estimated divergence, in bits.

Return type:

float

lz76_complexity(data, normalize=False)[source]

The Lempel–Ziv (1976) complexity of a sequence [LZ76].

This is the number \(c(n)\) of phrases in the exhaustive history of the sequence: scanning left to right, each phrase is the shortest string that does not occur earlier (overlaps allowed), computed with the algorithm of Kaspar & Schuster [KS87]. For example 0001101001000101 parses as 0 | 001 | 10 | 100 | 1000 | 101, so \(c = 6\).

Parameters:
  • data (iterable) – The sequence; rows of a 2D array are joint symbols.

  • normalize (bool) – Return \(c(n) \log_k(n) / n\) for an alphabet of \(k\) observed symbols. For a stationary ergodic source this converges to the entropy rate divided by \(\log_2 k\); random sequences score near 1. A constant sequence is normalized with \(k = 2\).

Returns:

c – The phrase count, or its normalization.

Return type:

int or float

lz_entropy_rate(data)[source]

Estimate the entropy rate in bits per symbol from match lengths.

For each position \(i\), \(\Lambda_i\) is the length of the shortest string starting at \(i\) that does not appear starting at any earlier position. The increasing-window estimator of Kontoyiannis et al. [KASW98] is

\[\hat{h} = \left[\frac{1}{n} \sum_{i} \frac{\Lambda_i}{\log_2 (i + 1)}\right]^{-1}.\]

It is consistent for stationary ergodic processes and needs no history length. That makes it a check on conditional_entropy_rate(), whose answer depends on the chosen \(L\). Like the Lempel–Ziv compression rate [CT06], it converges slowly: \(\Lambda_i\) exceeds \(\log_2 i / h\) by a roughly constant amount, so the estimate usually approaches the entropy rate from below (e.g. about 0.9 bits for a fair coin at \(n = 10^4\)). Treat it as a cross-check rather than a precise estimate.

Parameters:

data (iterable or Trials) – The sequence. Rows of a 2D array are joint symbols. For Trials, the per-trial sums are pooled; matches are sought only within each trial.

Returns:

h – The estimated entropy rate in bits per symbol.

Return type:

float

Notes

Positions whose match runs to the end of the data are excluded, since their \(\Lambda_i\) is censored. The cost is roughly \(O(n^2 \log n)\) character comparisons, done by str.find.

markov_order_test(data, order=1, statistic='entropy_rate', method='exact', n_surrogates=1000, rng=None)[source]

Test the null hypothesis that data is Markov of order order against the alternative that it is of order order + 1.

Parameters:
  • data (iterable or Trials) – The observed sequence, or independent Trials. Rows of a 2D array are joint symbols.

  • order (int) – The Markov order of the null hypothesis.

  • statistic ({'entropy_rate', 'chi2'}) – 'entropy_rate' uses the plug-in conditional entropy \(H[X_{n+1} \mid X_{0:n+1}]\) with n = order; small values are evidence against the null. 'chi2' uses Pearson’s statistic for the (order + 2)-gram counts; large values are evidence against the null.

  • method ({'exact', 'asymptotic'}) – 'exact' compares against whittle_surrogates(), which is valid at any sample size [PH14]. 'asymptotic' uses the chi-squared limit [AG57]; for 'entropy_rate' this is the G-test, since \(G = 2 N \ln 2 \, (h_n - h_{n+1})\).

  • n_surrogates (int) – The number of surrogates for the exact test.

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

result

Return type:

MarkovOrderTest

Notes

Pethel & Hahs show that the asymptotic test is badly anti-conservative for short sequences and higher orders (e.g. a size of 0.22 instead of 0.05 for third-order chains on four symbols with 400 samples), while the exact test keeps its nominal size [PH14]. The exact p-value is (1 + #{surrogates at least as extreme}) / (1 + n_surrogates). An UndersamplingWarning is raised when the (order + 2)-gram counts are sparse; the exact test stays valid, but its power is low.

For Trials, counts are pooled over trials and each surrogate draws every trial independently from its own surrogate set, which is the exact conditional null given all trials’ counts.

multiscale_permutation_entropy(ts, scale, order=3, delay=1, normalize=False, estimator='plugin', ties='first', rng=None)[source]

The permutation entropy of a series coarse-grained at scales 1 through scale [AA05].

At scale \(s\) the series is replaced by the means of consecutive, non-overlapping blocks of \(s\) values [CGP02], and permutation_entropy() is applied to the result.

Parameters:
Returns:

h – The permutation entropy at each scale, in bits; entry s - 1 is scale s.

Return type:

np.ndarray

mutual_information_mixed_ksg(x, y, k=5)[source]

Estimate \(I[X : Y]\) from samples that may be discrete, continuous, or a mixture of the two [GKOV17].

This is the mixed KSG estimator: with \(\rho_i\) the max-norm distance from sample \(i\) to its k-th nearest neighbor in the joint space,

\[\hat{I} = \frac{1}{N} \sum_i \left[\psi(\tilde{k}_i) + \log N - \psi(n_{x,i}) - \psi(n_{y,i})\right]\]

where \(n_{x,i}\) and \(n_{y,i}\) count the samples (including \(i\)) strictly within \(\rho_i\) in each marginal, and \(\tilde{k}_i = k\) unless \(\rho_i = 0\), in which case \(\tilde{k}_i\), \(n_{x,i}\) and \(n_{y,i}\) count the exact repeats of sample \(i\). No noise is added, since repeated values are what identify the discrete part.

Parameters:
  • x (np.ndarray) – Paired samples, one per row.

  • y (np.ndarray) – Paired samples, one per row.

  • k (int) – The number of nearest neighbors.

Returns:

mi – The estimated mutual information, in bits.

Return type:

float

ordinal_patterns(ts, order=3, delay=1, ties='first', rng=None)[source]

Map each delay window of a real-valued series to its ordinal pattern.

The window ending at time t is \((x_{t-(m-1)\tau}, \ldots, x_{t-\tau}, x_t)\) with \(m\) = order and \(\tau\) = delay; its pattern is the permutation that sorts it [BP02]. Patterns are invariant to monotone transforms of the series.

Parameters:
  • ts (array_like or Trials) – A real-valued series, or independent Trials.

  • order (int) – The window length \(m \geq 2\).

  • delay (int) – The spacing \(\tau \geq 1\) between window elements.

  • ties ({'first', 'noise', 'distinct'}) – How equal values are ranked. 'first' ranks the earlier occurrence lower (the usual convention); 'noise' adds negligible random noise; 'distinct' keeps ties as their own patterns [BQMS12].

  • rng (None, int, Generator, RandomState) – Source of randomness for ties='noise'.

Returns:

patterns – Integer pattern codes, one per window (len(ts) - (order - 1) * delay); entry i is the window ending at t = i + (order - 1) * delay. With 'first' or 'noise' codes are the lexicographic index of the permutation, in 0 .. order! - 1. With 'distinct' they are base-order codes of the dense rank vector.

Return type:

np.ndarray or Trials

permutation_entropy(ts, order=3, delay=1, normalize=False, estimator='plugin', ties='first', rng=None)[source]

The permutation entropy of a real-valued series [BP02].

This is the entropy, in bits, of the distribution of ordinal_patterns() of order \(m\) and delay \(\tau\). For piecewise-monotone maps, the permutation entropy per symbol converges to the Kolmogorov–Sinai entropy as \(m \to \infty\).

Parameters:
  • ts (array_like or Trials) – The series, or independent trials (patterns are pooled).

  • order (int) – The pattern order \(m\) and delay \(\tau\).

  • delay (int) – The pattern order \(m\) and delay \(\tau\).

  • normalize (bool) – Divide by \(\log_2 m!\), giving a value in \([0, 1]\).

  • estimator (str) – See entropy_from_counts(); 'nsb' uses \(m!\) outcomes.

  • ties ({'first', 'noise', 'distinct'}) – See ordinal_patterns().

  • rng (None, int, Generator, RandomState) – Source of randomness for ties='noise'.

Returns:

h

Return type:

float

relative_rank(ts, order=3, delay=1, ties='first', rng=None)[source]

The rank of each value among the order values preceding it.

For time t this is the number of values among \(x_{t-\tau}, \ldots, x_{t-m\tau}\) that are smaller than \(x_t\) (or, with ties='first', not larger), in 0 .. order. Paired with ordinal_patterns() of the preceding window, it encodes the present of a series without sharing values with its past, which removes the leakage that biases symbolic transfer entropy [Kug12].

Parameters:
  • ts (array_like or Trials) – A real-valued series, or independent trials.

  • order (int) – The number \(m\) of preceding values.

  • delay (int) – The spacing \(\tau\) between them.

  • ties ({'first', 'noise', 'distinct'}) – 'first' counts earlier equal values as smaller; 'distinct' counts only strictly smaller values; 'noise' adds negligible noise first.

  • rng (None, int, Generator, RandomState) – Source of randomness for ties='noise'.

Returns:

ranks – Entry i is the rank of \(x_t\) with t = i + order * delay.

Return type:

np.ndarray or Trials

renyi_entropy_knn(data, order, k=4, noise=1e-10, rng=None)[source]

Estimate the differential Rényi entropy \(\frac{1}{1 - q} \log \int f^q\) from samples [LPS08].

Parameters:
  • data (np.ndarray) – The samples, one per row.

  • order (float) – The order \(q\); it must be less than k + 1. Order 1 gives differential_entropy_knn().

  • k (int) – The number of nearest neighbors.

  • noise (float) – The standard deviation of the normally-distributed noise added to break ties.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

h – The estimated Rényi entropy, in bits.

Return type:

float

select_markov_order(data, max_order, method='exact', alpha=0.05, n_surrogates=1000, rng=None)[source]

Estimate the Markov order of data.

Parameters:
  • data (iterable or Trials) – The observed sequence, or independent Trials. Rows of a 2D array are joint symbols.

  • max_order (int) – The largest order considered.

  • method ({'exact', 'chi2', 'aic', 'bic'}) – 'exact' and 'chi2' test order n against n + 1 for n = 0, 1, ... and return the first order that is not rejected at level alpha ('exact' uses markov_order_test() with Whittle surrogates [PH14]; 'chi2' its asymptotic G-test). 'aic' and 'bic' minimize the information criterion over orders fitted on a common set of targets [Kat81, Ton75].

  • alpha (float) – The significance level for the testing methods.

  • n_surrogates (int) – The number of surrogates per test for 'exact'.

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

order – The estimated order.

Return type:

int

Notes

An UndersamplingWarning is raised when max_order + 1-words are sparse. The selected order then reflects what the data can resolve, and may be smaller than the process’s true order.

A process with infinite Markov order (e.g. a strictly sofic process such as the even process) has no true order; every method returns larger orders as the sample grows.

shift_surrogates(data, n=1, rng=None)[source]

Circularly shift data by uniformly random nonzero offsets.

Shifting a source series relative to a target preserves each series’ own dynamics while destroying their alignment, which gives a null for directed measures such as transfer entropy.

Parameters:
  • data (iterable or Trials) – The sequence to shift (along the first axis); each of several Trials is shifted independently.

  • n (int) – The number of surrogates.

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

surrogates – Shape (n,) + np.shape(data), or a list of n Trials.

Return type:

np.ndarray or list of Trials

stationary_bootstrap(data, n=1, mean_block_length=None, rng=None)[source]

Resample a series with the stationary bootstrap [PR94a].

Each resample concatenates blocks that start at uniformly random positions and have geometrically distributed lengths, wrapping around the end of the series. Rows of multivariate data are resampled together. For Trials, whole trials are resampled with replacement instead (a cluster bootstrap), so no resample joins two trials.

Parameters:
  • data (array_like or Trials) – The series (along the first axis), or independent trials.

  • n (int) – The number of resamples.

  • mean_block_length (float, None) – The mean block length; defaults to N ** (1 / 3).

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

resamples – Shape (n,) + np.shape(data), or a list of n Trials.

Return type:

np.ndarray or list of Trials

total_correlation_ksg(data, rvs, crvs=None, k=4, noise=1e-10, rng=None)

Compute the total correlation from observations. The total correlation is computed between the columns specified in rvs, given the columns specified in crvs. This utilizes the KSG kNN density estimator, and works on discrete, continuous, and mixed data.

Parameters:
  • data (np.array) – Real valued time series data.

  • rvs (iterable of iterables) – The columns for which the total correlation is to be computed.

  • crvs (iterable) – The columns upon which the total correlation should be conditioned.

  • k (int) – The number of nearest neighbors to use in estimating the local kernel density.

  • noise (float) – The standard deviation of the normally-distributed noise to add to the data.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

tc – The total correlation of rvs given crvs.

Return type:

float

Notes

The total correlation is computed in bits, not nats as most KSG estimators do.

This implementation uses scikit-learn.

tsallis_entropy_knn(data, order, k=4, noise=1e-10, rng=None)[source]

Estimate the differential Tsallis entropy \(\frac{1}{q - 1} \left(1 - \int f^q\right)\) from samples [LPS08].

Parameters:
  • data (np.ndarray) – The samples, one per row.

  • order (float) – The order \(q\); it must be less than k + 1. Order 1 gives the Shannon differential entropy in nats.

  • k (int) – The number of nearest neighbors.

  • noise (float) – The standard deviation of the normally-distributed noise added to break ties.

  • rng (None, int, Generator, RandomState) – Source of randomness for the noise.

Returns:

s – The estimated Tsallis entropy.

Return type:

float

weighted_permutation_entropy(ts, order=3, delay=1, normalize=False, ties='first', rng=None)[source]

The weighted permutation entropy of a real-valued series [FCKPrincipe13].

Each window’s pattern is weighted by the variance of the window, so patterns of large fluctuations count more than patterns of noise-level wiggles. This restores some of the amplitude information that permutation_entropy() discards. Garland, James & Bradley use it as a model-free measure of predictability [GJB14].

Parameters:
  • ts (array_like or Trials) – The series, or independent trials (weights are pooled).

  • order (int) – The pattern order \(m\) and delay \(\tau\).

  • delay (int) – The pattern order \(m\) and delay \(\tau\).

  • normalize (bool) – Divide by \(\log_2 m!\).

  • ties ({'first', 'noise', 'distinct'}) – See ordinal_patterns().

  • rng (None, int, Generator, RandomState) – Source of randomness for ties='noise'.

Returns:

h

Return type:

float

whittle_count(data, order=1)[source]

The natural log of the number of sequences sharing the observed (order + 1)-gram counts, first order-word, and last order-word.

Parameters:
  • data (iterable or Trials) – The observed sequence. Rows of a 2D array are joint symbols. For Trials, the log of the product of the per-trial counts.

  • order (int) – The Markov order of the null hypothesis.

Returns:

log_count – The natural log of the size of the surrogate set.

Return type:

float

Notes

This is Whittle’s formula [Bil61, Whi55], as used by [PH14]:

\[N_{uv}(F) = \frac{\prod_i F_{i\cdot}!}{\prod_{ij} F_{ij}!} C_{vu}\]

where \(F\) counts transitions between observed order-words and \(C_{vu}\) is the \((v, u)\) cofactor of \(\delta_{ij} - F_{ij} / F_{i\cdot}\). For order=0 it reduces to the multinomial coefficient of the symbol counts.

whittle_surrogates(data, order=1, n=1, rng=None)[source]

Draw surrogates that exactly preserve the (order + 1)-gram counts.

Each surrogate is drawn uniformly from the set of sequences with the same first order symbols and the same count of every (order + 1)-gram as data (and hence the same last order-word). Under the null hypothesis that data is an order-th order Markov chain, the observed sequence is itself a uniform draw from this set, so statistics computed on the surrogates give an exact null distribution at any sample size [PH14].

Parameters:
  • data (iterable or Trials) – The observed sequence. Rows of a 2D array are joint symbols. Each of several Trials is drawn independently from its own surrogate set.

  • order (int) – The Markov order to preserve. order=0 is a random permutation.

  • n (int) – The number of surrogates.

  • rng (None, int, Generator, RandomState) – Source of randomness.

Returns:

surrogates – Shape (n,) + np.shape(data), or a list of n Trials.

Return type:

np.ndarray or list of Trials

Notes

[PH14] sample by weighting each step with Whittle’s formula (whittle_count()), which costs a determinant per symbol. This implementation samples the same uniform distribution in linear time by drawing a random Eulerian trail of the order-word de Bruijn multigraph from a random last-exit arborescence [KMUW96].

exception UndersamplingWarning[source]

Warned when counts are too sparse for plug-in (and most bias-corrected) information estimates to be trusted.