API¶
- complexeva.hfd(x, k_max=10)¶
Estimate the Higuchi fractal dimension of one signal, or of every signal along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples, converted to float64, with time on the last axis: one signal of shape (time,) or a batch such as (channels, time). Requires at least 2 * k_max samples. Batch rows share one reusable workspace instead of allocating one per worker.
k_max (int | integer) – Largest integer time interval included in the regression. Must be between 2 and len(x) // 2, inclusive. Defaults to 10; report the chosen value with results.
- Returns:
Slope of log curve length against log inverse interval, approximately 1 for smooth signals, 1.5 for Brownian motion, and 2 for white noise. The dimension of a constant signal is undefined and is returned as NaN. A float for one signal; for a batch, a float64 array of shape x.shape[:-1] whose entries equal hfd on each signal.
- Raises:
ValueError – If x is a scalar, not finite and real, or k_max is not an integer in the stated range. The error identifies the invalid value, its position, or the shape.
- Return type:
float | NDArray[float64]
- complexeva.hfd_hilbert(x, k_max=10)¶
Estimate Higuchi dimension on the Hilbert envelope of a signal.
- Parameters:
x (ArrayLike) – Nonempty, one-dimensional, finite, real-valued samples, converted to float64 before the Hilbert transform. Requires at least 2 * k_max samples.
k_max (int | integer) – Largest integer time interval, between 2 and len(x) // 2 inclusive. Defaults to 10.
- Returns:
Higuchi fractal dimension of abs(hilbert(x)), the instantaneous amplitude. A constant envelope has undefined dimension and produces NaN, as in hfd.
- Raises:
ValueError – If x is empty or not a finite, real, one-dimensional signal, or k_max is outside the integer range accepted by hfd.
- Return type:
float
- complexeva.katz_fd(x)¶
Katz fractal dimension of one signal, or of every signal along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples with time on the last axis and at least 2 samples per signal. Arithmetic uses float64; batch rows are read without work arrays.
- Returns:
log10(N - 1) / (log10(N - 1) + log10(d / L)), where L is the sum of Euclidean distances between successive points (i, x[i]), and d is the largest Euclidean distance from (0, x[0]). A float for one signal; for a batch, a float64 array of shape x.shape[:-1] whose entries equal katz_fd on each signal bit for bit. A constant signal is a horizontal line and returns 1. A signal of length 2 returns NaN because there is only one step and both logarithms vanish.
- Raises:
ValueError – If x is scalar, not finite and real, or has fewer than 2 samples on its time axis. Invalid samples include their full index in the error.
- Return type:
float | NDArray[float64]
Note
Implements Katz (1988), Computers in Biology and Medicine 18(3), 145-156, doi:10.1016/0010-4825(88)90041-8, Methods equations (2)-(5) and the Appendix program, on unit-spaced time coordinates. Both time and amplitude contribute to the planar Euclidean distance, so amplitude scaling can change the result. antropy.katz_fd, neurokit2.fractal_katz, and mne_features.compute_katz_fd instead use amplitude-only distances and therefore compute a different quantity. The method uses one O(N) pass after input validation and O(1) workspace per signal, with no fastmath.
- complexeva.petrosian_fd(x)¶
Petrosian fractal dimension of one signal, or of every signal along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples with time on the last axis and at least 2 samples per signal. Arithmetic uses float64; batch rows are read without work arrays.
- Returns:
log10(N) / (log10(N) + log10(N / (N + 0.4 * N_delta))), where N is the number of input samples and N_delta counts sign-bit changes in successive differences. A float for one signal; for a batch, a float64 array of shape x.shape[:-1] whose entries equal petrosian_fd on each signal bit for bit. A constant or monotonic signal has no sign changes and returns 1, not NaN, because the formula is defined.
- Raises:
ValueError – If x is scalar, not finite and real, or has fewer than 2 samples on its time axis. Invalid samples include their full index in the error.
- Return type:
float | NDArray[float64]
Note
Uses Petrosian’s (1995) derivative-sign symbolization (method C), Proceedings Eighth IEEE Symposium on Computer-Based Medical Systems, 212-217, doi:10.1109/CBMS.1995.465426. As in antropy.petrosian_fd, +0 differences belong to the nonnegative class; a negative signed zero retains its sign bit. N is the original signal length. NeuroKit2’s default method C instead uses N - 1, the derivative-symbol length, and therefore differs for finite N. The method uses one O(N) pass after input validation and O(1) workspace per signal, with no derivative array, symbol array, or fastmath.
- complexeva.lempel_ziv(x, method='median', normalize=False)¶
Compute Kaspar-Schuster Lempel-Ziv complexity along the last axis.
- Parameters:
x (ArrayLike | str) – A binary string containing only “0” and “1”, used without binarization, or finite, real-valued samples with time on the last axis, converted to float64 per row. A numeric batch has shape (…, time); NUMBA_NUM_THREADS limits parallel workers, additionally bounded by a one-row scratch budget. Small batches run serially. Strings and lempel_ziv_hilbert remain one-dimensional.
method (str) – Numeric binarization rule: “median” (default) or “mean” marks samples strictly above that row’s threshold, and “diff” marks strictly increasing adjacent samples. Ignored for binary-string input, which is already encoded.
normalize (bool) – False returns the integer count c. True returns c * log2(n) / n, where n is the binary sequence length (one fewer numeric sample for “diff”). Defaults to False.
- Returns:
Raw integer component count, or a normalized float that is approximately 1 for a long random binary sequence and need not be bounded by 1. For n <= 1, normalized complexity is 0.0; the raw count of an empty or single-symbol sequence is 1. Returns a Python scalar for one signal or an int64 (raw) / float64 (normalized) array of shape x.shape[:-1] for a numeric batch, bitwise equal to separate 1D calls. A constant row follows the 1D rule.
- Raises:
ValueError – If a string contains nonbinary characters, numeric input is scalar, not finite and real, or the numeric binarization method is unknown. Non-finite errors identify the full index within a batch.
- Return type:
int | float | NDArray[int64] | NDArray[float64]
- complexeva.lempel_ziv_hilbert(x, method='median', normalize=False)¶
Compute Lempel-Ziv complexity on the Hilbert envelope of a signal.
- Parameters:
x (ArrayLike) – Nonempty, one-dimensional, finite, real-valued samples, converted to float64 before taking the Hilbert transform. Binary strings are not accepted by this variant.
method (str) – Envelope binarization rule: “median” (default), “mean”, or “diff” for rising steps. Threshold comparisons are strict, as in lempel_ziv.
normalize (bool) – False returns the raw integer count. True returns c * log2(n) / n using the binarized envelope length n, or 0.0 for n <= 1. Defaults to False.
- Returns:
Integer count or normalized float for abs(hilbert(x)), the instantaneous amplitude. Normalized values near 1 indicate random binary structure, not a strict bound.
- Raises:
ValueError – If x is empty or not a finite, real, one-dimensional signal, or the binarization method is unknown.
- Return type:
int | float
- complexeva.sample_entropy(x, order=2, tolerance=None)¶
Sample entropy using the Chebyshev distance, in natural-log units (nats).
- Parameters:
x (ArrayLike) – Finite, real samples with time on the last axis, with at least order + 2 samples per signal. A batch is computed in parallel over signals; set NUMBA_NUM_THREADS to limit threads.
order (int | integer) – Length of the templates before extending them by one sample. Defaults to 2.
tolerance (float | floating | integer | None) – Nonnegative, finite distance threshold in the units of x. None (default) uses 0.2 * std(row, ddof=0) independently for each signal, and zero for an exactly constant signal. Matches require distance strictly less than this threshold, not less than or equal to it.
- Returns:
-log(A / B), where B counts matching pairs of length order and A counts those that still match at length order + 1. Returns NaN if B is zero (including zero tolerance), and infinity if only A is zero. A constant series has NaN at the default zero tolerance, or 0 at a positive tolerance. Returns a float for 1D input, or a float64 array of shape x.shape[:-1] whose entries equal the 1D calls bit for bit.
- Raises:
ValueError – If the input has no time axis, is not finite and real, is too short, or a parameter is outside its allowed range. Non-finite errors include the full index.
- Return type:
float | NDArray[float64]
Note
Self-matches are excluded. Both counts use the same len(x) - order templates, omitting the last length-order template because it cannot be extended. Long inputs with order <= 4 use exact dual-tree pair counting; other inputs use an allocation-free diagonal scan. Worst-case counting is quadratic, with O(N) auxiliary memory for the bounded-dimensional tree and O(1) auxiliary memory for diagonal counting, per active worker. Batch bookkeeping uses O(number of signals) memory. C-contiguous float64 batches and 2D float64 views use rows directly; other native layouts and dtypes need one float64 row buffer per active worker. Default tolerances still use contiguous float64 rows to match 1D std. Concurrent trees share a 12 MiB array budget (at least one tree); this limits active row workers without changing the Numba thread pool or the exact counting method. This is the Richman and Moorman (2000) sample entropy definition, with the same default tolerance as antropy.sample_entropy.
- complexeva.approximate_entropy(x, order=2, r=None)¶
Pincus approximate entropy with the Chebyshev distance, in nats.
- Parameters:
x (ArrayLike) – Finite, real samples with time on the last axis. Each signal needs at least order + 1 samples. Native batch layouts need at most one float64 row buffer.
order (int | integer) – Positive template length before extending by one sample. Defaults to 2.
r (float | floating | integer | None) – Nonnegative finite distance threshold in the units of x. None (default) uses 0.2 * std(row, ddof=0) independently for each signal. A match includes distances equal to r and includes the template itself.
- Returns:
Phi(order) - Phi(order + 1), where Phi(m) is the mean of log(C_i(m)) over all len(x) - m + 1 templates and C_i(m) is the fraction matching template i. A float for 1D input, or a float64 array of shape x.shape[:-1] whose entries equal individual 1D calls bit for bit. Constant signals return 0, including at the default r = 0: all templates match, so approximate entropy is defined. Finite-sample values can be negative; they are not clipped.
- Raises:
ValueError – If x has no time axis, is not finite and real, is too short, order is not a positive integer, or r is not a nonnegative finite number. Invalid samples include their full index in the error.
- Return type:
float | NDArray[float64]
Note
Implements Pincus (1991), PNAS 88:2297-2301, equations 1, 2, 6 and 10, doi:10.1073/pnas.88.6.2297. Self-matches and the final length-order template are retained, unlike sample entropy. The default order and population-SD tolerance follow the usual Richman and Moorman (2000) / antropy convention. Short or high-order inputs use a diagonal scan; long inputs with order <= 4 use exact dual-tree neighbourhood counting. Both have quadratic worst-case time and O(N) auxiliary memory. Batch execution is serial and reuses one signal’s workspace, plus O(number of signals) output and tolerance arrays.
- complexeva.multiscale_entropy(x, scales=20, order=2, r=None, *, method='coarse')¶
Conventional (Costa) or modified (Wu) multiscale sample entropy, in nats.
- Parameters:
x (ArrayLike) – Finite, real samples with time on the last axis. At every requested scale, floor(len(row) / scale) must be at least order + 2.
scales (int | integer | ArrayLike) – Positive maximum scale, meaning 1 through scales inclusive, or a nonempty 1D sequence of positive integer factors. Explicit factors retain their order and repetitions. Defaults to 20, the range used by Costa et al. (2002).
order (int | integer) – Sample-entropy template length before extension by one sample. Defaults to 2.
r (float | floating | integer | None) – Nonnegative, finite absolute matching threshold, in the units of x. None uses 0.15 * std(row, ddof=0), as in Costa et al. (2002), independently for each original signal. This threshold is fixed across all scales, never recalculated from the coarse-grained series. This differs from sample_entropy’s default 0.2 * std(row); set r=0.2*std(x) to match common library defaults.
method (str) – “coarse” (default) averages nonoverlapping blocks as in Costa (2002). “modified” uses every moving-average window, embedding delay equal to scale, and excludes template pairs whose start indices differ by less than scale, following Wu et al. (2013), Section 2.3, Eq. (15) and the Appendix.
- Returns:
-1] + (number_of_scales,). The final axis holds the sample entropy at each requested scale; every batch row equals its 1D call bit for bit. A scale returns NaN when there are no matching order-length pairs (including a constant original signal with default r), or infinity when those pairs exist but none remain after extension. With explicit positive r, a constant signal has zero entropy at every scale.
- Return type:
A float64 array of shape x.shape[
- Raises:
ValueError – If x is scalar, not finite and real, too short at a requested scale, or order, scales, r, or method is outside its allowed range. Non-finite input errors include the full index.
Note
This implements Costa, Goldberger and Peng (2002), Physical Review Letters 89, 068102, doi:10.1103/PhysRevLett.89.068102. At scale s, consecutive nonoverlapping blocks of s samples are averaged; an incomplete final block is discarded. Sample entropy reuses sample_entropy’s exact Chebyshev counting kernel: self matches are excluded, distances must be strictly less than r, and both template lengths use the same number of extendible templates. Coarse-grained means use float64 arithmetic, without fastmath.
For method=”modified”, Wu, Wu, Lee and Lin (2013), Physica A 392:5865-5873, doi:10.1016/j.physa.2013.07.075, replace block means with z[j] = mean(x[j:j+s]), j=0,…,N-s. The length is N-s+1, and templates use delay s with N-(order+1)*s+1 common starting positions. Only pairs with j-i >= s are counted. This follows the paper’s equations and Appendix loop; its prose j>i+s conflicts by one. The strict <r convention follows the Appendix and this package’s SampEn, rather than the prose’s <=r. The Appendix’s movingaverage code leaves s-1 original tail values; they are discarded here as required by Section 2.3’s length formula. At scale 1, both methods return identical values.
The curve is returned rather than collapsing scales. For ordered factors s and the returned h, numpy.trapezoid(h, x=s, axis=-1) gives the area under the scale curve. For consecutive unit-spaced scales, h.sum(axis=-1) gives the commonly used complexity index (as in EntropyHub). These summaries are different; report which one is used. Neither summary silently drops NaN or infinity.
Batch rows run in parallel, reusing one coarse-graining buffer and, only when needed, one float64 row buffer per active worker. Concurrent tree and row workspaces share sample_entropy’s 12 MiB array budget (at least one worker). Single rows avoid the parallel scheduler. The imported sample-entropy kernel has O(N) auxiliary memory for long low-order signals and O(1) for its diagonal scan.
- complexeva.fuzzy_entropy(x, order=2, r=None, n=2)¶
Fuzzy entropy with exponential membership exp(-distance**n / r), in nats.
- Parameters:
x (ArrayLike) – Finite, real-valued samples with time on the last axis. Each signal requires at least order + 2 samples. Non-contiguous batches are converted one row at a time.
order (int | integer) – Template length before extension by one sample, a positive integer. Defaults to 2.
r (float | floating | integer | None) – Nonnegative exponential divisor, not a distance threshold raised to n. None uses 0.2 * std(row, ddof=0) independently for each signal. Zero gives NaN.
n (float | floating | integer) – Positive finite exponent of the Chebyshev distance. Defaults to 2.
- Returns:
-log(A / B), where A and B are sums of memberships for baseline-centred templates of lengths order + 1 and order, respectively. Returns NaN when B is zero (including the default zero divisor of a constant signal), or infinity when only A is zero. A constant signal with positive r has entropy 0. A float for 1D input; a float64 array of shape x.shape[:-1] for a batch, bitwise equal to calling the function on every row separately.
- Raises:
ValueError – If x has no time axis, is not finite and real, is too short, order is not a positive integer, r is negative or non-finite, or n is not positive and finite. Invalid samples are reported with their full index.
- Return type:
float | NDArray[float64]
Note
Each template has its own mean subtracted before measuring Chebyshev distance. Self-matches are excluded and both lengths use the same len(x) - order extendible templates. The membership divisor is r, not r**n. This is the Chen et al. (2007), IEEE TNSRE 15:266-272 definition (doi:10.1109/TNSRE.2007.897025), matching EntropyHub.FuzzEn(…, m=order, tau=1, r=(r, n))[0][-1]. pyentrp uses exp(-(distance / tolerance)**n), so pass tolerance=r**(1/n) to match. EntropyHub defaults to r=0.2 regardless of signal scale. neurokit2 0.2.13 always uses exponent 1 (its public n keyword is not forwarded), so it agrees only with n=1; pass tolerance=r to override its default sample-SD scaling. The paper does not prescribe a universal default width; its EMG example uses 0.3 * SD (section III.B). Computation is exact pair enumeration, O(N**2 * order) time and O(N * order) heap per active worker. Long single signals parallelize anchor rows. Batches parallelize signals when enough rows are available, otherwise reuse the anchor-parallel kernel for long rows (exp_033). All schedules use deterministic reductions and no fastmath. NUMBA_NUM_THREADS bounds the worker count. Batch template and conversion buffers share a 60-coordinate budget (12 default-order workers for direct float64 rows, and at least one worker for arbitrary order). No membership cutoff or sampled pairs are used.
- complexeva.permutation_entropy(x, order=3, delay=1, normalize=False)¶
Ordinal-pattern entropy of one signal, or of every signal along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples, converted to float64, with time on the last axis. Each signal requires at least (order - 1) * delay + 1 samples. Orders 2–7 use a compiled row loop with one reusable conversion buffer when needed.
order (int | integer) – Number of samples per ordinal pattern, at least 2. Defaults to 3.
delay (int | integer) – Positive sample spacing within each pattern. Pattern starting points advance by one sample, regardless of the delay. Defaults to 1.
normalize (bool) – Divide the entropy in bits by log2(order!) to obtain a value between 0 and 1. Defaults to False.
- Returns:
Entropy of the observed ordinal-pattern probabilities. A constant or strictly monotonic series has entropy 0. A float for one signal; for a batch, a float64 array of shape x.shape[:-1] whose entries equal permutation_entropy on each signal bit for bit.
- Raises:
ValueError – If the input is scalar, not finite and real, is too short on the time axis, or order/delay is not an integer in its allowed range. Invalid samples include their full index in the error.
- Return type:
float | NDArray[float64]
Note
Equal values retain their temporal order (stable sorting); no random jitter is added. Orders up to 7 use collision-free factorial codes and a bounded histogram; larger orders count patterns directly, without an integer hash that can overflow. This implements Bandt and Pompe (2002) permutation entropy, as in antropy.perm_entropy.
- complexeva.spectral_entropy(x, sf, method='fft', nperseg=None, normalize=False)¶
Shannon entropy of the normalized one-sided power spectrum, in bits.
- Parameters:
x (ArrayLike) – Finite, real-valued samples, with time on the last axis. Each signal needs at least two samples. Computation uses float64 without modifying the input.
sf (float) – Positive, finite sampling frequency in Hz. Its common PSD scaling cancels during probability normalization, so it does not change the entropy.
method (str) – Spectral estimator: ‘fft’ for a boxcar periodogram of the whole signal, or ‘welch’ for the mean of periodic-Hann periodograms with 50% overlap. Each segment is detrended by subtracting its mean. Defaults to ‘fft’.
nperseg (int | integer | None) – Positive integer Welch segment length. None uses min(256, len(x)); a value above the signal length is clipped to that length. Ignored by ‘fft’.
normalize (bool) – Divide the entropy by log2(number of one-sided frequency bins), giving a value between 0 and 1. Defaults to False.
- Returns:
Entropy -sum(p * log2(p)), with p obtained by normalizing the estimated PSD. Zero-power bins contribute zero. Constant signals, or Welch segments whose detrended power is all zero, return NaN because their probabilities are undefined. One signal returns a float; batches return a float64 array of shape x.shape[:-1]. Every batch entry equals the corresponding 1D call bit for bit.
- Raises:
ValueError – If x has no time axis, is not real and finite, or has fewer than two samples; if sf is not positive and finite; if method is not ‘fft’ or ‘welch’; or if a Welch nperseg is not a positive integer. Non-finite input errors name the full sample index.
- Return type:
float | NDArray[float64]
Note
Spectral entropy follows Inouye et al. (1991), Electroencephalography and Clinical Neurophysiology 79, 204–210, doi:10.1016/0013-4694(91)90138-T. The estimator, base-2 logarithm, endpoint handling and optional normalization match antropy.spectral_entropy: include DC and the Nyquist bin, and double only the non-endpoint one-sided powers. Unlike a full-batch spectrogram, the implementation reuses one row’s FFT workspace for every batch row.
- complexeva.svd_entropy(x, order=3, delay=1, normalize=False)¶
Singular-value entropy of delay-embedded signals along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples, converted to float64, with time on the last axis. Each signal requires at least (order - 1) * delay + 1 samples.
order (int | integer) – Embedding dimension, an integer at least 2. Defaults to 3.
delay (int | integer) – Positive integer sample spacing within each embedding vector. Starting points advance by one sample, irrespective of delay. Defaults to 1.
normalize (bool) – Divide the entropy in bits by log2(order), yielding a value between 0 and 1. Defaults to False.
- Returns:
Shannon entropy -sum(p * log2(p)), where p contains the singular values of the uncentered delay embedding divided by their sum. An all-zero embedding returns NaN; a nonzero constant signal returns 0. A float for one signal; for a batch, a float64 array of shape x.shape[:-1], with each entry equal bit for bit to a call on that signal alone.
- Raises:
ValueError – If x is scalar, not finite and real, too short on the time axis, or order/delay is not an integer in its allowed range. Invalid samples include their full index in the error.
- Return type:
float | NDArray[float64]
Note
Implements the temporal embedding-space entropy in Roberts, Penny and Rezek (1999), Medical and Biological Engineering and Computing 37:93-98, section 3.3, DOI: 10.1007/BF02513272. Samples are not demeaned, and singular values, not squared singular values, define the probabilities. The lagged Gram matrix avoids copying the embedding; ill-conditioned embeddings use a streaming QR factor to preserve small singular values. Working storage is O(k**2), with k = min(order, N - (order - 1) * delay), plus a single length-N conversion buffer for batch rows that need one.
- complexeva.dfa(x, nvals=None)¶
First-order detrended fluctuation analysis along the last axis, with non-overlapping windows.
- Parameters:
x (ArrayLike) – Finite, real samples with time on the last axis, converted to float64. One signal has shape (time,); batches have shape (…, time). At least 6 samples per signal are needed with explicit sizes; default sizes need at least 58. Batch signals run in parallel; set NUMBA_NUM_THREADS to limit threads.
nvals (ArrayLike | None) – At least two distinct integer window sizes, each between 4 and x.shape[-1] - 1. None (default) uses floor(4 * 1.2**k) up to x.shape[-1] / 10, with duplicate sizes removed, as in antropy.detrended_fluctuation. Report the fitted window sizes with results.
- Returns:
Slope of log RMS fluctuation versus log window size. White noise has an exponent near 0.5 and Brownian motion near 1.5. Returns NaN when fewer than two scales have nonzero fluctuation, including constant input. This is a scaling exponent, not a fractal dimension. Returns a float for one signal, or a float64 array of shape x.shape[:-1] for a batch, bitwise equal to calling dfa on each signal separately.
- Raises:
ValueError – If the input is scalar, not finite and real, is too short along the last axis, or the window sizes are invalid or insufficient for a slope fit. A non-finite error identifies the full index in a batch.
- Return type:
float | NDArray[float64]
Note
The demeaned series is cumulatively summed, then a least-squares linear trend is removed independently from each complete window. A trailing incomplete window is discarded at each scale. Squared residuals are averaged across all samples and windows before taking one square root. The log-log slope is an ordinary least-squares fit (not RANSAC). This is DFA-1 (Peng et al., 1994); it also matches nolds.dfa with the same nvals, overlap=False, order=1 and both fits set to “poly”.
- complexeva.correlation_dimension(x, order=2, delay=1, radii=None)¶
Grassberger–Procaccia correlation dimension along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples with time on the last axis. Each signal requires at least (order - 1) * delay + 2 samples.
order (int | integer) – Positive delay-embedding dimension. Defaults to 2.
delay (int | integer) – Positive sample spacing within each embedded vector. Defaults to 1.
radii (ArrayLike | None) – At least two finite, positive, strictly increasing Euclidean radii in the units of x. The same supplied radii apply to every row. None uses 55 radii, 0.1 * std(x, ddof=1) * 1.03**arange(55), for each signal separately, matching nolds’ radius grid.
- Returns:
Ordinary least-squares slope of log(C(r)) against log(r), retaining only radii with nonzero correlation sums. A float for one signal, or a float64 array of shape x.shape[:-1] for a batch. Every batch entry equals its 1D call bit for bit. Constant signals and fits with fewer than two nonzero correlation sums return NaN.
- Raises:
ValueError – If x is scalar, non-real, non-finite, or too short; order or delay is not a positive integer; or radii is not a 1D sequence of at least two finite, positive, strictly increasing values. Invalid samples are reported with their full index.
- Return type:
float | NDArray[float64]
Note
Implements Grassberger and Procaccia (1983), Physica D 9, 189–208, sections 1 and 5 and Appendix A, doi:10.1016/0167-2789(83)90298-1. C(r) counts distinct embedded vectors with Euclidean distance < r; self-matches are excluded and no Theiler window is applied. Its finite-sample normalization is 1 / (M * (M - 1)); replacing it with the paper’s 1 / M**2 changes only the intercept, not the dimension. A dual k-d-tree traversal stores O(M * order + len(radii)) values, never an M by M distance matrix. Batches run serially to retain just one row’s workspace. Radii near a pair distance are resolved with a compiled strict-distance scan to avoid squared-distance roundoff. Worst-case counting time remains quadratic.
With matched radii this agrees with neurokit2.fractal_correlation. nolds.corr_dim(fit=”poly”) uses <= and inadvertently retains the zero diagonal of its distance matrix. Its self-match bias is not reproduced. The default RANSAC regression of nolds is also not used. A finite-radius slope need not equal the limiting attractor dimension: choose radii, delay, and embedding dimension for the signal’s scaling region.
- complexeva.hjorth(x)¶
Hjorth mobility and complexity of signals along the last axis.
- Parameters:
x (ArrayLike) – Finite, real-valued samples, converted to float64, with time on the last axis. Each signal requires at least three samples.
- Returns:
A tuple (mobility, complexity). Each element is a float for one signal, or a float64 array of shape x.shape[:-1] for a batch. Batch entries equal the corresponding one-dimensional call bit for bit. Mobility is sqrt(var(diff(x)) / var(x)), in inverse samples. Complexity is the mobility of diff(x) divided by the mobility of x. Variances use ddof=0. Constant signals return (NaN, NaN); a nonconstant signal with constant first differences has zero mobility and NaN complexity.
- Raises:
ValueError – If x is scalar, not finite and real, or has fewer than three samples on its last axis. Non-finite samples include their full index in the error.
- Return type:
tuple[float, float] | tuple[NDArray[float64], NDArray[float64]]
Note
Implements Hjorth (1970), EEG analysis based on time domain properties, Electroencephalography and Clinical Neurophysiology 29, 306–310, doi:10.1016/0013-4694(70)90143-4. Derivatives are successive unpadded first differences, as in antropy.hjorth_params and neurokit2.complexity_hjorth. One compiled pass computes all three variances with constant workspace, without materializing derivatives.
- complexeva.lyapunov_exponent(x, tau=1, m=2, dt=1.0, min_tsep=None, trajectory_len=20, fit_offset=0)¶
Estimate the largest Lyapunov exponent by Rosenstein et al. (1993).
The series is delay-embedded, each point is paired with its nearest neighbour outside a Theiler window, and the exponent is the slope of the mean log divergence of those pairs over trajectory_len steps.
- Parameters:
x (ArrayLike) – One-dimensional, finite, real-valued samples, converted to float64. The resulting number of trajectories, len(x) - (m - 1) * tau - trajectory_len + 1, must be at least 2 * min_tsep + 2.
tau (int | integer) – Positive integer embedding delay in samples. Defaults to 1.
m (int | integer) – Positive integer embedding dimension. Defaults to 2.
dt (float) – Finite, strictly positive sampling interval. Defaults to 1.0; the result has units of 1/dt.
min_tsep (int | integer | None) – Nonnegative integer Theiler window in samples. Pairs at this separation or closer are excluded. None estimates the ceil of the reciprocal power-weighted mean frequency, capped at len(x) // 4. Constant data requires an explicit value.
trajectory_len (int | integer) – Integer number of future steps followed per pair, at least 2. Defaults to 20.
fit_offset (int | integer) – Nonnegative integer number of initial steps excluded from the line fit. Must be at most trajectory_len - 2 so that two steps remain. Defaults to 0.
- Returns:
Largest Lyapunov exponent per unit time. Positive values suggest chaos; values near zero or below indicate regular dynamics. Returns negative infinity when fewer than two fitted steps have finite mean log distances, including constant data with an explicit min_tsep.
- Raises:
ValueError – If x is not a finite one-dimensional signal, a parameter is outside its stated range, the series is too short, or a default window cannot be inferred.
- Return type:
float
- complexeva.compression_complexity(x)¶
Measure zlib-compressed size relative to the original array bytes.
- Parameters:
x (NDArray[generic]) – One-dimensional NumPy array whose byte representation is nonempty. Its dtype is preserved; values, including NaN and infinity, are serialized with x.tobytes() in C order. No floating-point conversion, scaling, or finiteness check is performed.
- Returns:
Compressed byte count divided by uncompressed byte count, using zlib’s default compression level. Lower values indicate more compressible bytes. Small inputs can exceed 1 because the compressed stream includes overhead; the result depends on dtype as well as values.
- Raises:
ValueError – If x is not one-dimensional or contains no bytes. The error names its shape and, for empty bytes, its dtype.
- Return type:
float