dit.inference
Module for basic inference tools.
Classes
Posterior samples of the entropy rate, from |
|
The result of |
|
Independent realizations (trials) of the same process. |
Functions
Discretize a real-valued list. |
|
Estimate \(H[X_{0:L}]\), the entropy of overlapping length-length words. |
|
Randomly permute contiguous blocks of data. |
|
Estimate \(h_L = H[X_L \mid X_{0:L}] = H[X_{0:L+1}] - H[X_{0:L}]\). |
|
Estimate \(I[X : Y \mid Z]\) in bits from paired samples. |
|
Map each column of data through its empirical CDF and then the inverse standard normal CDF, giving standard normal marginals with the same ranks. |
|
Estimate the differential cross entropy \(-\mathbb{E}_P[\log q(X)]\) from samples x of \(P\) and y of \(Q\) [LPS08]. |
|
Compute the differential entropy of data using a k-nearest neighbors density estimator. |
|
The dispersion entropy of a real-valued series [RA16]. |
|
Infer a distribution from time series observations. |
|
Returns a distribution over words of length L from d. |
|
Estimate the entropy of length length subsequences in data. |
|
Estimate the entropy of length length subsequences in data. |
|
Estimate the entropy of length length subsequences in data. |
|
Estimate an entropy, in bits, from a vector of outcome counts. |
|
Posterior samples of the entropy rate under an order-order Markov model. |
|
Estimate \(I[X : Y \mid Z]\) with the Gaussian copula [IGK+17]. |
|
Count the occurrences of all words of length in data. |
|
The delete-one jackknife of an entropy estimator, with its variance. |
|
Estimate the Jensen–Shannon divergence of \(P\) and \(Q\) from samples. |
|
Estimate \(D_{KL}[P \| Q]\) from samples x of \(P\) and y of \(Q\). |
|
The Lempel–Ziv (1976) complexity of a sequence [LZ76]. |
|
Estimate the entropy rate in bits per symbol from match lengths. |
|
Test the null hypothesis that data is Markov of order order against the alternative that it is of order |
|
The permutation entropy of a series coarse-grained at scales 1 through scale [AA05]. |
|
Estimate \(I[X : Y]\) from samples that may be discrete, continuous, or a mixture of the two [GKOV17]. |
|
Map each delay window of a real-valued series to its ordinal pattern. |
|
The permutation entropy of a real-valued series [BP02]. |
|
The rank of each value among the order values preceding it. |
|
Estimate the differential Rényi entropy \(\frac{1}{1 - q} \log \int f^q\) from samples [LPS08]. |
|
Estimate the Markov order of data. |
|
Circularly shift data by uniformly random nonzero offsets. |
|
Resample a series with the stationary bootstrap [PR94a]. |
|
Compute the total correlation from observations. |
|
Estimate the differential Tsallis entropy \(\frac{1}{q - 1} \left(1 - \int f^q\right)\) from samples [LPS08]. |
|
The weighted permutation entropy of a real-valued series [FCKPrincipe13]. |
|
The natural log of the number of sequences sharing the observed |
|
Draw surrogates that exactly preserve the |
Exceptions
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:
objectPosterior samples of the entropy rate, from
entropy_rate_posterior().- samples
Entropy rates (bits per symbol) of chains drawn from the posterior.
- Type:
np.ndarray
- property mean
The posterior mean.
- class MarkovOrderTest(order: int, statistic: str, value: float, pvalue: float, dof: int, null: ndarray | None = None, n_windows: int | None = None)[source]
Bases:
objectThe result of
markov_order_test().- null
The statistic evaluated on each surrogate (exact tests only).
- Type:
np.ndarray or None
- class Trials(iterable=(), /)[source]
Bases:
listIndependent realizations (trials) of the same process.
Wrap a list of sequences in
Trialsto tell the estimators indit.inferencethat 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:
- 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.
- 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:
- Returns:
surrogates – Shape
(n,) + np.shape(data), or a list of nTrials.- Return type:
- 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.
- 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:
- 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\) (
nrows) and \(Q\) (mrows) with the same numberdof columns.y (np.ndarray) – Samples of \(P\) (
nrows) and \(Q\) (mrows) with the same numberdof 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:
- 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:
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. Unlikepermutation_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:
- 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
Trialswhose 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
LwithM**(L + 1) <= N / 5, forMjoint symbols andNobservations.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_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=Trueonly the observed words are built, rather than alllen(alphabet) ** Lof them. ADistributionstill 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:
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:
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:
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] (asentropy_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]; seejackknife_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 tolen(counts), so pass a count vector that includes the zero counts or set this explicitly.
- Returns:
h – The estimated entropy in bits.
- Return type:
- 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.5is the Jeffreys prior,1the uniform prior.n_samples (int) – The number of posterior draws.
rng (None, int, Generator, RandomState) – Source of randomness.
- Returns:
posterior
- Return type:
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:
- 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:
counts (array_like) – The number of times each outcome was observed. Zeros are ignored.
estimator (str) – The estimator to jackknife; see
entropy_from_counts().alphabet_size (int, None) – See
entropy_from_counts().
- 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:
- 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()minusdifferential_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:
- 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
0001101001000101parses as0 | 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:
- 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:
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}]\) withn = 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 againstwhittle_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:
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). AnUndersamplingWarningis 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:
ts (array_like) – The real-valued series.
scale (int) – The largest scale.
order – See
permutation_entropy().delay – See
permutation_entropy().normalize – See
permutation_entropy().estimator – See
permutation_entropy().ties – See
permutation_entropy().rng – See
permutation_entropy().
- Returns:
h – The permutation entropy at each scale, in bits; entry
s - 1is scales.- 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.
- 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
tis \((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); entryiis the window ending att = i + (order - 1) * delay. With'first'or'noise'codes are the lexicographic index of the permutation, in0 .. 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:
- 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
tthis is the number of values among \(x_{t-\tau}, \ldots, x_{t-m\tau}\) that are smaller than \(x_t\) (or, withties='first', not larger), in0 .. order. Paired withordinal_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
iis the rank of \(x_t\) witht = 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 givesdifferential_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:
- 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 ordernagainstn + 1forn = 0, 1, ...and return the first order that is not rejected at level alpha ('exact'usesmarkov_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:
Notes
An
UndersamplingWarningis raised whenmax_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:
- Returns:
surrogates – Shape
(n,) + np.shape(data), or a list of nTrials.- Return type:
- 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:
- Returns:
resamples – Shape
(n,) + np.shape(data), or a list of nTrials.- Return type:
- 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:
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:
- 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:
- whittle_count(data, order=1)[source]
The natural log of the number of sequences sharing the observed
(order + 1)-gram counts, firstorder-word, and lastorder-word.- Parameters:
- Returns:
log_count – The natural log of the size of the surrogate set.
- Return type:
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}\). Fororder=0it 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
ordersymbols and the same count of every(order + 1)-gram as data (and hence the same lastorder-word). Under the null hypothesis that data is anorder-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
Trialsis drawn independently from its own surrogate set.order (int) – The Markov order to preserve.
order=0is 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 nTrials.- Return type:
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 theorder-word de Bruijn multigraph from a random last-exit arborescence [KMUW96].