Skip to content

Analysis

Analyse systems, trajectories, and measured data by the kind of data.

The kinds of data are series, paths, fields, agents, and networks, such as the price of a stock over time, the grid of a forest fire, or the friendships of a school, and each analysis takes a system, a trajectory, or plain arrays.

AlignmentResult(angles, vectors, positions, order, tensors=None, axes=None, phase=None) dataclass

A result of alignment, how well the members line up at every frame.

It holds one order value per frame, 1 when every member points the same way and near 0 when they point at random, such as [1.0] for three birds flying north, with the angles, vectors, positions, axes, or mean phase the kind reads. It measures the order of a flock, the line-up of the spins of a magnet, and the synchrony of fireflies.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
angles Array | None

The angles, frames by members, or None without them.

required
vectors Array | None

The vectors or velocities, frames by members by components, or None without them.

required
positions Array | None

The positions of agents, frames by agents by dimensions, or None without them.

required
order Array

The alignment of every frame, between 0 and 1, or the scalar order of every site of every frame.

required
tensors Array | None

The independent components of the tensors, with one frame per row of the first axis, for 'principal-axis'.

None
axes Array | None

The principal axis of every site of every frame, with the components on the last axis, for 'principal-axis'.

None
phase Array | None

The mean phase of every frame, for 'mean-phase'.

None
See Also

alignment: Returns this result.

Examples:

>>> from skcomplex.core.analysis import alignment
>>> alignment([0.0, 0.0, 0.0]).order.tolist()
[1.0]

AnalysisTags(data, time=frozenset(), space=frozenset(), randomness=None) dataclass

Bases: BaseSpec

A set of tags that an analysis needs of its data and of the system.

It names the kind of data an analysis reads and the tags the system behind the data must have, so an analysis refuses data it cannot read before doing any work, such as AnalysisTags('system', randomness='deterministic') for an analysis of systems with no randomness. An analysis module declares it as the constant TAGS, and an empty field needs nothing. It keeps a stability analysis off a random epidemic and a network measure off a price series.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
data DataKind | str

The kind of data the analysis reads.

required
time frozenset[str]

The times of which the system needs one, among 'continuous', 'discrete', and 'static'.

frozenset()
space frozenset[str]

The spaces of which the system needs one, such as 'network'.

frozenset()
randomness str | None

The randomness the system needs, 'deterministic' or 'stochastic', or None for either.

None
See Also

applicable_analyses: Lists the analyses whose tags a source meets.

Examples:

>>> from skcomplex.core.analysis import AnalysisTags
>>> from skcomplex.core.components import Tags
>>> needed = AnalysisTags('system', randomness='deterministic')
>>> needed.get_missing(Tags(time=frozenset({'continuous'}), randomness='stochastic'))
{'randomness': ['stochastic']}

get_missing(tags)

Return the tags of a system that do not give what the analysis needs, by field.

The system needs one of the needed times and one of the needed spaces, and the needed randomness. A field of the system that is empty or None is unknown and not checked.

Parameters:

Name Type Description Default
tags Tags

The tags of a system.

required

Returns:

Name Type Description
missing dict[str, list[str]]

The tags of the system of every field that misses what is needed, sorted.

Source code in src/skcomplex/core/analysis/_analysis_tags.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def get_missing(self, tags: Tags) -> dict[str, list[str]]:
    """Return the tags of a system that do not give what the analysis needs, by field.

    The system needs one of the needed times and one of the needed spaces, and the needed randomness. A field of
    the system that is empty or `None` is unknown and not checked.

    Args:
        tags:
            The tags of a system.

    Returns:
        missing:
            The tags of the system of every field that misses what is needed, sorted.
    """
    found: dict[str, list[str]] = {}
    for name, needed, values in (('time', self.time, tags.time), ('space', self.space, tags.space)):
        if needed and values and not needed & values:
            found[name] = sorted(values)
    if self.randomness is not None and tags.randomness is not None and tags.randomness != self.randomness:
        found['randomness'] = [tags.randomness]
    return found

ApplicableAnalysesResult(kinds, readings, analyses) dataclass

A result of applicable_analyses, the analyses that fit a source, by kind.

It holds the kinds of data the source holds, such as ['field', 'series'] for a 2D array, what each kind reads from it, and the analyses that apply under each kind, ready to call. It answers which measures fit a run of an epidemic, a grid of a forest, or a table of prices.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
kinds list[str]

The data kinds of the source, in the order agents, field, network, path, series.

required
readings dict[str, str]

How the analyses of every data kind read the source, by data kind.

required
analyses dict[str, list[partial[object]]]

The analyses that apply to the source by data kind, each bound to its kind for a family, so calling one on the source gives its result.

required
See Also

applicable_analyses: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import applicable_analyses
>>> applicable_analyses(np.zeros((16, 16))).kinds
['field', 'series']

AutocatalyticSetsResult(snapshots, reactions, products, sizes, fractions, exists) dataclass

A result of autocatalytic_sets, the largest such set at every frame.

It holds, for every frame, the reactions of the largest set that makes its own helpers from the food, the products of those reactions, their number and share, and whether such a set exists. It reports the self-making chemistry of the origin of life and the goods of an economy that are made from each other.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
snapshots list[NetworkSnapshotSpec]

The network snapshot of every analysed frame.

required
reactions list[Indices]

The rows, in the hyperedges of the snapshot, of the reactions of the largest RAF of every frame.

required
products list[Indices]

The node rows that the reactions of the largest RAF of every frame produce.

required
sizes NDArray[int_]

The number of reactions of the largest RAF of every frame.

required
fractions Array

The share of the reactions of every frame that the largest RAF holds, 0 for a frame without reactions.

required
exists NDArray[bool_]

Whether every frame holds a RAF.

required
See Also

autocatalytic_sets: Returns this result.

Examples:

>>> from skcomplex.core.analysis import AutocatalyticSetsResult
>>> AutocatalyticSetsResult((), (), (), [], [], [False]).exists
[False]

AutomatonResult(automaton, injective=None, surjective=None, pre_injective=None, pattern=None, inverse=None, composition=None, differences=None, entropy=None, matrix=None, polynomial=None, admissible=None, violations=None, count=None, sample=None) dataclass

A result of automaton, a decision or a measure of a cellular automaton.

It holds the answer the kind asks for, such as whether no two grids share their next grid, a grid that no grid leads to, an automaton that undoes another, or the number of allowed grids, and leaves the other fields None. It answers whether a model of traffic, of growth, or of a crystal loses information.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
automaton System

The System of the automaton or of the subshift, the one a ready-made system builds for it.

required
injective bool | None

Whether the automaton is injective.

None
surjective bool | None

Whether the automaton is surjective.

None
pre_injective bool | None

Whether no two configurations that differ only inside the window share their image.

None
pattern IntArray | None

A configuration whose values on the window have no preimage, or None when none is found.

None
inverse System | None

The System of the inverse automaton, whose interaction sets an update law with a table rule and its neighbourhood, or None when the automaton is not injective or no memory up to the radius determines the cells.

None
composition System | None

The System of the automaton of the composition, whose interaction sets an update law with a function rule and its neighbourhood.

None
differences NDArray[bool_] | None

One row per step, the initial one first, true where the runs differ.

None
entropy NDArray[float64] | None

One entropy per window.

None
matrix Matrix | None

The Sage matrix of the linear automaton.

None
polynomial LaurentPolynomial | None

The Sage Laurent polynomial in the variables x0 to x(d-1).

None
admissible bool | None

Whether the configuration belongs to the subshift.

None
violations NDArray[bool_] | None

One flag per site, true where a forbidden pattern appears.

None
count int | None

The number of configurations without a forbidden pattern.

None
sample IntArray | None

The admissible configuration.

None
See Also

automaton: Returns this result.

Examples:

>>> from skcomplex.core.analysis import automaton
>>> from skcomplex.systems.computer_science.automata import ElementaryAutomatonSystem
>>> automaton(ElementaryAutomatonSystem(rule=170, size=8)).injective
True

CellComplexResult(complex, values, period, betti=None, gradient=None, curl=None, harmonic=None, potential=None, share=None, energy=None) dataclass

A result of cell_complex, a split of flows, counts of holes, or curved faces.

It holds, one row per frame, the three flows that a flow on links splits into, the counts of holes of each dimension of a complex, or the faces around which an angle winds. A grid of 4 by 4 sites joined at its edges has one piece, two loops, and one hollow, the Betti numbers (1, 2, 1). It reports the cycles of a road network, the holes of a pattern, and the vortices of a gauge field.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
complex CellComplexSpace

The cell complex the analysis reads.

required
values Array

The values of the source, with one row per frame.

required
period float

The period of the values.

required
betti tuple[int, ...] | None

The Betti numbers of every degree, for the kind 'betti'.

None
gradient Array | None

The part of every frame that is the exterior derivative of a site potential, for the kind 'hodge'.

None
curl Array | None

The part of every frame that the transposed incidence of a face potential gives, for the kind 'hodge'.

None
harmonic Array | None

The remainder of every frame, for the kind 'hodge'.

None
potential Array | None

The site potential of every frame, of zero mean, for the kind 'hodge'.

None
share Array | None

The share of the faces of every frame that are curved, for the kind 'curvature'.

None
energy Array | None

The sum over the faces of every frame of one minus the cosine of the oriented sum, for the kind 'curvature'.

None
See Also

cell_complex: Returns this result.

Examples:

>>> from skcomplex.core.analysis import cell_complex
>>> from skcomplex.core.components.spaces import CellComplexSpace, LatticeSpace
>>> cell_complex(None, kind='betti', space=CellComplexSpace(LatticeSpace((4, 4))).prepare()).betti
(1, 2, 1)

ChainShapeResult(positions, values) dataclass

A result of chain_shape, the geometry of a chain of points per frame.

It holds the positions and one value per frame, the radius of gyration, the distance between the ends, or the deviation from a reference shape, such as the radius 1 of two points 2 apart. It reports the size of a polymer, the stretch of a strand of DNA, and how far a folding protein lies from its native shape.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
positions Array

The positions, frames by points by dimensions.

required
values Array

The value per frame.

required
See Also

chain_shape: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import chain_shape
>>> chain_shape(np.array([[[0.0, 0.0], [2.0, 0.0]]])).values.tolist()
[1.0]

ClustersResult(points=None, faces=None, grids=None, graph=None, labels=None, sizes=None, strength=None, mean_size=None, spanning=None, probability=None) dataclass

A result of clusters, the clusters of a grid, a graph, or points.

It holds the label of every cell, the size of every cluster, largest first, and for percolation the share of the largest cluster, the mean size, and whether a cluster joins two opposite edges, such as [2, 1] for a pair and a single. It reports the flow paths of a porous rock, the burnt patches of a forest, and the groups of like-minded voters.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
points NDArray[float64] | None

The arrays of points, one per entry of the first axis, or None for grids and graphs.

None
faces NDArray[float64] | None

The sides of the space that holds the points of a trajectory, or None for the bounding box of the points.

None
grids NDArray[bool_] | None

The grids, one per entry of the first axis, or None for a graph or points.

None
graph Graph | None

The graph, or None for grids and points.

None
labels IntArray | None

The label of every cell, 0 for empty cells and 1 onwards for clusters, for 'labels' and for points.

None
sizes IntArray | None

The size of every cluster, in label order for 'labels' and largest first otherwise, or None for 'spanning'.

None
strength float | None

The share of all sites or nodes in the largest cluster, for 'percolation' and for points.

None
mean_size float | None

The mean size of the cluster of an occupied site outside the largest, Σ' s² / Σ' s, for 'percolation' and for points.

None
spanning bool | None

Whether a cluster of the grid joins the two opposite edges of axis, always false for graphs, for 'labels', 'percolation', and points.

None
probability float | None

The spanning probability of the ensemble, for 'spanning'.

None
See Also

clusters: Returns this result.

Examples:

>>> from skcomplex.core.analysis import clusters
>>> clusters([[1, 1, 0], [0, 0, 1]], kind='sizes').sizes.tolist()
[2, 1]

CoarseGrainResult(positions, box, field) dataclass

A result of coarse_grain, agents counted on a grid or spread over values.

It holds the counts of agents in every cell of a grid, one grid per frame, with the positions and the box, or the share of members at every value, which sums to 1. It reports the density of a herd, the spread of wealth, and the density of a fluid.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
positions Array

The positions, one row per agent, with one leading axis of frames for a trajectory, or the values of the state of every member with over.

required
box Array | None

The sides of the box, or None with over.

required
field Array

The grid of counts, or of sums with the value components last, with one grid per frame for a trajectory, ready for field analyses, or the fractions of members at every value of over, one row per frame.

required
See Also

coarse_grain: Returns this result.

Examples:

>>> from skcomplex.core.analysis import coarse_grain
>>> coarse_grain([-1.0, 0.4, 0.6, 1.5, 9.0], over=[0.0, 1.0, 2.0]).field.tolist()
[0.4, 0.4, 0.2]

ComplexityResult(values, labels, entropy, complexity, minimum, maximum) dataclass

A result of complexity, places on the complexity and entropy plane.

It holds the entropy and the complexity of every series or frame, with the lowest and highest complexity that each entropy allows. Noise sits near entropy 1 and complexity 0, and chaos higher up. It tells chaos from noise in heart beats, climate records, and prices.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column, or the frames of the field.

required
labels list[str]

The label of every series, or of the field.

required
entropy Array

The normalized permutation entropy of every series or frame.

required
complexity Array

The statistical complexity of every series or frame.

required
minimum Array

The curve of least complexity, one row of entropy and complexity per point.

required
maximum Array

The curve of largest complexity, one row of entropy and complexity per point.

required
See Also

complexity: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import complexity
>>> complexity(np.random.default_rng(0).standard_normal(50_000), dimension=4).entropy.round(2).tolist()
[1.0]

CorrelationResult(values, labels, lags=None, correlation=None, time=None, distances=None, length=None, overlap=None) dataclass

A result of correlation, the correlation of series or of a field.

It holds the correlation at every lag, time, or distance, the correlation time or length, or the overlap of two configurations, such as [[1.0, -0.75]] for a series that flips sign at every step. It reports how long a price remembers, how far order reaches in a magnet, and how alike two states of a glass are.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column, the ensemble, the field, or the two configurations.

required
labels list[str]

The label of every series, of the ensemble or field, or of the two configurations.

required
lags Array | None

The lags in time, for 'auto'.

None
correlation Array | None

One autocorrelation per series for 'auto', one row per waiting time and one column per lag for 'two-time', and the correlation at every distance for 'function'.

None
time Array | None

The integrated autocorrelation time of every series, for 'auto'.

None
distances Array | None

The distances, for 'function'.

None
length float | Array | None

The correlation length, for 'length'.

None
overlap float | Array | None

The overlap of the two configurations, one per frame for frames, for 'overlap'.

None
See Also

correlation: Returns this result.

Examples:

>>> from skcomplex.core.analysis import correlation
>>> correlation([1.0, -1.0, 1.0, -1.0], max_lag=1).correlation.round(2).tolist()
[[1.0, -0.75]]

DataCollapseResult(values, labels, critical=None, nu=None, exponent=None, quality=None, time_spread=None, ratio_spread=None, ratios=None, densities=None, spread=None, crossings=None) dataclass

A result of data_collapse, curves of several sizes laid onto one.

It holds the rescaled curves, the fitted critical point and exponents with the quality of the collapse, the spreads of aging curves, or the points where the curves of consecutive sizes cross, such as [2.0]. It reports the critical point of a magnet, the growth exponents of a rough surface, and the aging of a glass.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values dict[float, Array] | Array

The curve of every size, the curves of every waiting time, or the samples of every age.

required
labels list[float]

The size, waiting time, or age of every curve.

required
critical float | None

The critical value used or fitted, for 'scaling'.

None
nu float | None

The correlation length exponent used or fitted, for 'scaling'.

None
exponent float | None

The exponent a used or fitted, for 'scaling'.

None
quality float | None

The mean squared relative distance between the scaled curves, 0 for a perfect collapse, for 'scaling'.

None
time_spread float | None

The largest difference between the curves against the lag, 0 without aging, for 'aging'.

None
ratio_spread float | None

The largest difference between the curves against tau / t_w, 0 under simple aging, for 'aging'.

None
ratios Array | None

The centres of the bins of tau / t, for 'distribution'.

None
densities Array | None

One row per age of t P(tau, t) on the bins, for 'distribution'.

None
spread float | None

The largest relative difference between the rows where every row is positive, for 'distribution'.

None
crossings Array | None

The first crossing of the curves of every pair of consecutive sizes, nan where they do not cross, for 'crossings'.

None
See Also

data_collapse: Returns this result.

Examples:

>>> from skcomplex.core.analysis import data_collapse
>>> curves = {8: [0.6, 0.5, 0.2], 16: [0.65, 0.5, 0.1]}
>>> data_collapse(curves, kind='crossings', parameters=[1.0, 2.0, 3.0]).crossings.tolist()
[2.0]

DefectsResult(angles, positions, charges) dataclass

A result of defects, the points where a field of angles winds around.

It holds, for every frame, the angles, the positions of the defects, and their charges, the number of whole turns the angle makes around each, such as one defect of charge 1 at the centre of a vortex. It reports the vortices of a superfluid, the defects of a liquid crystal, and the swirls of a swarm of bacteria.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
angles Array

The angles, with one frame per row of the first axis.

required
positions list[Array]

The centres of the plaquettes with a defect at every frame, each an array of defects by dimensions.

required
charges list[Array]

The charges of the defects at every frame, each an array in the order of positions.

required
See Also

defects: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import defects
>>> rows, columns = np.meshgrid(np.arange(8.0), np.arange(8.0), indexing='ij')
>>> result = defects(np.arctan2(rows - 3.5, columns - 3.5), period=2 * np.pi, periodic=False)
>>> result.positions[0].tolist(), result.charges[0].tolist()
([[3.5, 3.5]], [1.0])

DisplacementResult(positions, lags, msd, exponent, diffusion) dataclass

A result of displacement, the mean squared distance travelled over every lag.

It holds the positions, the lags, the mean squared distance at every lag, the exponent of its growth with the lag, 1 for plain diffusion and 2 for straight flight, and the diffusion coefficient. It reports how molecules spread in a fluid, how cells crawl in a tissue, and how animals forage.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
positions Array

The unwrapped positions, frames by particles by dimensions.

required
lags Array

The lags in time.

required
msd Array

The mean squared displacement at every lag.

required
exponent float

The slope of log msd against log lag over the fit range, 1 for normal diffusion, below 1 for subdiffusion, and above 1 for superdiffusion.

required
diffusion float

The coefficient D of msd = 2 d D lag fitted over the fit range in d dimensions.

required
See Also

displacement: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import displacement
>>> walks = np.cumsum(np.random.default_rng(0).standard_normal((2000, 500)), axis=0)
>>> round(displacement(walks).exponent, 1)
1.0

DistributionResult(values, labels, edges=None, density=None, support=None, survival=None, mean=None, variance=None, skewness=None, kurtosis=None, ratio=None, cumulant=None, index=None, gini=None, tail_index=None, records=None, distance=None) dataclass

A result of distribution, the distribution of the values of a source.

It holds what the kind measures: a histogram, the share of values at or above each value, the moments, the Gini coefficient, the tail index, the count of records, or the distance between two distributions, such as a Gini coefficient of 0.75 when one of four holds everything. It reports the spread of incomes, the sizes of cities, and the avalanches of a sandpile.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The pooled sample, or the samples, one per column.

required
labels list[str]

The label of every sample.

required
edges Array | None

The bin edges of the histogram, for 'histogram'.

None
density Array | None

The probability density in every bin of the histogram, for 'histogram'.

None
support Array | None

The sorted distinct values of the complementary cumulative distribution, for 'ccdf'.

None
survival Array | None

The share of samples at or above every distinct value, P(X >= x), for 'ccdf'.

None
mean Array | None

The mean of every sample, for 'moments'.

None
variance Array | None

The variance of every sample, for 'moments'.

None
skewness Array | None

The skewness of every sample, for 'moments'.

None
kurtosis Array | None

The excess kurtosis of every sample, 0 for Gaussian samples, for 'moments'.

None
ratio Array | None

The moment ratio of every sample, for 'moment-ratio'.

None
cumulant Array | None

The normalized cumulant of every sample, for 'moment-ratio'.

None
index Array | None

The dispersion index of every sample, for 'dispersion-index'.

None
gini float | None

The Gini coefficient, for 'gini'.

None
tail_index float | None

The Hill estimate of the tail index, for 'tail-index'.

None
records NDArray[int64] | None

The number of records of every series, the first value included, for 'records'.

None
distance float | None

The total variation distance between the two groups, for 'total-variation'.

None
See Also

distribution: Returns this result.

Examples:

>>> from skcomplex.core.analysis import distribution
>>> distribution([0, 0, 0, 4], kind='gini').gini
0.75

DomainsResult(frames, times, size=None, exponent=None, wavelength=None, wavenumber=None, orientation=None, density=None) dataclass

A result of domains, the size, growth, or pattern of the regions of a field.

It holds the size of the regions of equal value in every frame, the exponent of their growth, the dominant wavelength and orientation of a pattern, or the share of neighbours that differ, such as [0.25] for stripes two sites wide. It reports the growth of magnetic domains, of regions of opinion, and of the phases of an alloy.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
frames list[Graph] | Array

The frames of the field, or the graph.

required
times Array

The time of every frame.

required
size Array | None

The domain size of every frame, for 'size' and 'growth'.

None
exponent float | None

The growth exponent of the domain size, for 'growth'.

None
wavelength Array | None

The wavelength of the peak of every frame, for 'wavelength'.

None
wavenumber Array | None

The wavenumber of the peak of every frame, for 'wavelength'.

None
orientation Array | None

The orientation order of the wave vectors near the peak of every frame, for 'wavelength'.

None
density Array | None

The interface density of every frame, for 'interface-density'.

None
See Also

domains: Returns this result.

Examples:

>>> from skcomplex.core.analysis import domains
>>> domains([[1, 1, -1, -1]] * 4, kind='interface-density').density.tolist()
[0.25]

ElementaryModesResult(labels, modes, lines) dataclass

A result of elementary_modes, the simplest steady routes through a network.

It holds the names of the variables, the routes, one row per route in exact fractions, and the routes that can run both ways, such as one route through a chain of three reactions. It reports the pathways of a metabolism, the routes of a chemical plant, and the flows of a supply chain.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
labels tuple[str, ...]

The name of every column of modes.

required
modes NDArray[object_]

One row per generator, scaled to normalize or to the smallest integer vector, as fractions.

required
lines NDArray[object_]

The generators that run in both directions, the lines of a cone that is not pointed, one row per line.

required
See Also

elementary_modes: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import elementary_modes
>>> elementary_modes(np.array([[1.0, -1.0, 0.0], [0.0, 1.0, -1.0]]), normalize='v0').modes.tolist()
[[Fraction(1, 1), Fraction(1, 1), Fraction(1, 1)]]

EmbeddingResult(values, labels, delay, dimension=None, points=None, mutual_information=None, false_neighbors=None) dataclass

A result of embedding, the delayed copies of a series.

It holds the delay, the dimension, the points made of delayed copies of the series, and the measures that chose them, the auto mutual information and the share of false neighbours. It reports the rebuilt orbit of a heart beat, of a river flow, or of a price.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, as one column.

required
labels list[str]

The label of the series.

required
delay int

The delay in steps.

required
dimension int | None

The dimension of 'delay', or None for 'false-nearest-neighbors'.

None
points Array | None

One row per delay vector of 'delay', or None for 'false-nearest-neighbors'.

None
mutual_information Array | None

The auto mutual information at every delay from 0, or None when the delay is given.

None
false_neighbors Array | None

The fraction of false nearest neighbours in every dimension from 1, or None when 'delay' is given the dimension.

None
See Also

embedding: Returns this result.

Examples:

>>> from skcomplex.core.analysis import embedding
>>> embedding([0, 1, 2, 3, 4], delay=2, dimension=2).points.tolist()
[[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]]

EmergenceResult(matrix=None, values=None, labels=None, information=None, determinism=None, degeneracy=None, states=None, partition=None, macro_matrix=None, micro_information=None, macro_information=None, gain=None, psi=None, delta=None, gamma=None, macro_uncertainty=None, micro_uncertainty=None, gap=None) dataclass

A result of emergence, how much a coarse scale adds over a fine scale.

It holds what the kind measures: the effective information of a matrix of moves with its determinism and degeneracy, the best grouping of states with its gain, the criteria of Rosas et al., or the gap of a closed coarse view. Four states that each go to themselves carry 2 bits. It asks whether a flock, a brain region, or an economy acts as more than its parts.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
matrix Array | None

The micro transition matrix, for 'effective-information' and 'causal'.

None
values AnyArray | None

The micro series, one column per micro variable, for 'criteria' and 'closure'.

None
labels list[str] | None

The label of every micro series.

None
information float | None

The effective information in bits, for 'effective-information'.

None
determinism float | None

log2 n minus the mean entropy of the rows, high when every state has one successor.

None
degeneracy float | None

log2 n minus the entropy of the mean row, high when many states share a successor.

None
states NDArray[int64] | None

The states with observed transitions, the rows the effective information uses.

None
partition IntArray | None

The macro label of every micro state, for 'causal'.

None
macro_matrix Array | None

The macro transition matrix of the partition, every row summing to one.

None
micro_information float | None

The effective information of the micro matrix.

None
macro_information float | None

The effective information of the macro matrix.

None
gain float | None

The macro minus the micro effective information in bits.

None
psi float | None

I(V_t ; V_t') - Σ_j I(X_t^j ; V_t'), positive when the macro feature predicts its own future beyond what every micro variable does, a sufficient condition for causal emergence.

None
delta float | None

max_j [I(V_t ; X_t'^j) - Σ_i I(X_t^i ; X_t'^j)], positive when the macro feature predicts a micro variable beyond the micro variables, a sufficient condition for downward causation.

None
gamma float | None

max_j I(V_t ; X_t'^j), zero for a causally decoupled feature when psi is positive.

None
macro_uncertainty float | None

H(V_t | V_past), the entropy of the macro future given the macro past.

None
micro_uncertainty float | None

H(V_t | X_past), the entropy of the macro future given the micro past.

None
gap float | None

The information the micro past adds about the macro future, zero for a closed coarse-graining.

None
See Also

emergence: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import emergence
>>> emergence(np.eye(4), kind='effective-information').information
2.0

EntropyResult(values, labels, entropy, divergence=None, error=None) dataclass

A result of entropy, the entropy of series or of the frames of a field.

It holds the values read and one entropy per series or frame, with the divergence from a reference law for an ensemble, such as 1 bit for a series that takes two values equally often. It reports the disorder of a heart rate, a written text, and the configurations of a lattice.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values NDArray[int64] | Array

The series, one per column, or the frames of the field, or the runs of the ensemble.

required
labels list[str]

The label of every series, or of the field.

required
entropy Array

One entropy per series or frame, with one column per block length for 'block' and per scale for 'multiscale'.

required
divergence Array | None

The divergence in bits of the outcomes of every frame of an ensemble from the reference law, or None for kinds other than 'ensemble'.

None
error float | None

The expected divergence of a sample of the reference law of the ensemble's size, (k - 1) / (2 n ln 2) for k outcomes and n runs, below which a divergence is sampling noise, or None for kinds other than 'ensemble'.

None
See Also

entropy: Returns this result.

Examples:

>>> from skcomplex.core.analysis import entropy
>>> entropy([0, 0, 1, 1] * 100, kind='excess', dimension=4).entropy.round(3).tolist()
[2.0]

EpsilonMachineResult(values, labels, alphabet, histories, transitions, probabilities, stationary, statistical_complexity, entropy_rate) dataclass

A result of epsilon_machine, the hidden states that predict a series.

It holds the alphabet, the pasts that lead to each hidden state, the moves between states with their chances, how often each state is visited, how much memory the states hold, the statistical complexity, and how much new randomness each symbol brings, the entropy rate. A series 0, 0, 1 repeated has three states, a memory of log2 3 bits, and no randomness. It reports the hidden states of an automaton, of the spikes of a neuron, and of a text.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series of symbols.

required
labels list[str]

The label of the series.

required
alphabet Array

The distinct symbols, whose positions are the codes of the histories and of the columns.

required
histories tuple[tuple[IntTuple, ...], ...]

The histories of every causal state, as codes of their symbols, oldest first.

required
transitions IntArray

The state reached from every state on every symbol, -1 for symbols a state never emits.

required
probabilities Array

The probability of every symbol from every state.

required
stationary Array

The fraction of time spent in every state.

required
statistical_complexity float

The entropy of the stationary distribution of the causal states in bits.

required
entropy_rate float

The mean entropy of the next symbol given the causal state in bits.

required
See Also

epsilon_machine: Returns this result.

Examples:

>>> from skcomplex.core.analysis import epsilon_machine
>>> machine = epsilon_machine([0, 0, 1] * 300, max_length=3)
>>> len(machine.histories), round(machine.statistical_complexity, 3), round(machine.entropy_rate, 3)
(3, 1.585, 0.0)

ErgodicityResult(values=None, mapping=None, ergodicity_breaking=None, times=None, metric=None, exponent=None, ergodicity_distance=None, edges=None, density=None, transition_matrix=None) dataclass

A result of ergodicity, whether a time average equals an ensemble average.

It holds the runs or the map it read and the measure of the kind, such as an ergodicity breaking of 0 for two runs that visit the same values and near 1 for runs frozen in their own states. It tells whether one long run of a gas, a wealth process, or a neuron stands for the whole ensemble.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array | None

The runs, one row per run, or the values of the run.

None
mapping Callable[[Array], Array] | None

The map of 'ulam'.

None
ergodicity_breaking float | None

The ergodicity-breaking parameter, of 'breaking'.

None
times Array | None

The times of the columns, of 'metric'.

None
metric Array | None

The fluctuation metric at every time, of 'metric'.

None
exponent float | None

The slope of log metric against log time at log-spaced later times, -1 for ergodic runs and 0 for frozen ones, of 'metric'.

None
ergodicity_distance float | None

The median distance between the law of every run and that of the ensemble, of 'distance'.

None
edges Array | None

The edges of the bins or of the cells, of the density kinds.

None
density Array | None

The density in every bin or cell, of the density kinds.

None
transition_matrix Array | None

The probability that a point of every cell lands in every cell, of 'ulam'.

None
See Also

ergodicity: Returns this result.

Examples:

>>> from skcomplex.core.analysis import ergodicity
>>> ergodicity([[0.0, 0.0], [1.0, 1.0]], kind='distance').ergodicity_distance
0.5

EventsResult(times, values, labels, starts=None, sizes=None, durations=None, shapes=None, peaks=None, waiting_times=None, counts=None, branching_ratio=None) dataclass

A result of events, the events of one series or of event times.

It holds the series it read and what the kind measures: the start, size, duration, and peak of every event, the counts in windows, the laminar phases, the excursions, or the branching ratio, such as the sizes 4 and 2 of the two bursts of [0, 3, 1, 0, 0, 2, 0]. It reports the crashes of a market, the spikes of a neuron, and the floods of a river.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
times Array | None

The time of every value, or of every event for 'counts'.

required
values Array | None

The series, as one column, or one column per trial for 'branching', or None for records.

required
labels list[str]

The label of the series or the state.

required
starts Array | None

The time at which every event starts.

None
sizes Array | None

The sum of the values of every event.

None
durations Array | None

The time every event lasts for 'detect', every laminar phase lasts for 'laminar-durations', or the number of samples of every excursion for 'excursions'.

None
shapes list[Array] | None

The profile of every excursion of a series, empty for records.

None
peaks Array | None

The largest value of every event.

None
waiting_times Array | None

The time between the end of every event and the start of the next.

None
counts Array | None

The number of events in every window.

None
branching_ratio float | None

The branching ratio m, 1 at criticality.

None
See Also

events: Returns this result.

Examples:

>>> from skcomplex.core.analysis import events
>>> events([0, 3, 1, 0, 0, 2, 0]).sizes.tolist()
[4.0, 2.0]

FitLawResult(values, labels, exponent=None, minimum=None, maximum=None, statistic=None, p_value=None, tail=None, comparisons=None, index=None, skewness=None, shape=None, location=None, scale=None, maxima=None, parameters=None) dataclass

A result of fit_law, a law fitted to a pooled sample.

It holds the sample and the fitted parameters of the law with how well it fits, such as an exponent near 2.5 for samples drawn from p(x) ∝ x^-2.5. It reports whether the sizes of earthquakes, cities, or firms follow a power law, and the scale of the energies of a gas.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The pooled sample.

required
labels list[str]

The label of every series.

required
exponent float | None

The exponent alpha of the density of the power law, for 'power'.

None
minimum float | None

The lower cutoff of the power law, for 'power'.

None
maximum float | None

The upper cutoff of the power law, or None without one.

None
statistic float | None

The Kolmogorov-Smirnov distance between the tail and the power law, or between the sample and a named law.

None
p_value float | None

For the power law, the share of bootstrap samples from the fit whose distance exceeds statistic, or None without bootstrap, values above 0.1 not rejecting it. For a named law, the Monte Carlo p-value, values below the significance level rejecting it.

None
tail int | None

The number of samples between the cutoffs of the power law, for 'power'.

None
comparisons dict[str, tuple[float, float]] | None

For every alternative of compare_with, the log-likelihood ratio of the power law against it, positive when the power law fits better, and its p-value, for 'power'.

None
index float | None

The stability index of the stable law, 2 for the normal law, for 'stable'.

None
skewness float | None

The skewness of the stable law, for 'stable'.

None
shape float | None

The shape xi of the extreme-value law, 0 for the Gumbel class, positive for the Fréchet class of heavy tails, and negative for the Weibull class of bounded tails, for 'extreme-value'.

None
location float | None

The location of the stable or the extreme-value law.

None
scale float | None

The scale of the stable or the extreme-value law.

None
maxima Array | None

The maximum of every block of the extreme-value law, for 'extreme-value'.

None
parameters dict[str, float] | None

The fitted and fixed parameters of a named law.

None
See Also

fit_law: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import fit_law
>>> fit = fit_law(np.random.default_rng(0).exponential(2.0, 1000), law='exponential', fixed={'loc': 0})
>>> round(fit.parameters['scale'], 0), fit.p_value > 0.05
(2.0, True)

InformationResult(values, labels, symbols, information) dataclass

A result of information, the information among series.

It holds the series, the symbols it read them as, and the measure of the kind, a matrix for pairs, a value per series, or one value for all series, such as the 1 bit a copied coin flip passes to its copy. It reports the flow of information between regions of the brain, between markets, and between the members of a flock.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column.

required
labels list[str]

The label of every series.

required
symbols AnyArray

The symbols the kinds measure, one column per series, the series themselves without symbols.

required
information float | Array

A matrix with the measure from the series of every row to the series of every column for 'mutual', 'transfer', and 'kl-divergence', nan from a series to itself for 'transfer'. One value per series, with one column per delay or block length for 'auto-mutual' and 'correlation-information'. One value per series for 'o-information-gradients'. A single value for the other kinds of all series together.

required
See Also

information: Returns this result.

Examples:

>>> from skcomplex.core.analysis import information
>>> xor = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
>>> round(information(xor, kind='o-information').information, 6)
-1.0

InvariantsResult(problem, system, dynamics, namespace, rates, conserved, methods) dataclass

A result of invariants, the rates of expressions and if they are conserved.

It holds the system, its equations, and for every expression its rate of change, whether it is conserved, and the method that decided, such as the energy x² + x'² of a unit spring with a rate of 0. It reports the conserved energy of a pendulum, the conserved total of an epidemic, and the conserved money of an exchange economy.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec

The compiled problem.

required
system System

The System whose expressions were checked, the one a ready-made system builds.

required
dynamics _DynamicsSpec

The first-order equations of the system, with the values of its parameters.

required
namespace SimpleNamespace

The namespace of the symbols of the states and parameters of the system, where s.<element>.<state> is the symbol of a state.

required
rates dict[str, Expression]

A mapping from every label to the rate of change of its expression.

required
conserved dict[str, bool]

A mapping from every label to whether its expression is conserved.

required
methods dict[str, str]

A mapping from every label to the method that decided, 'symbolic' or 'numeric'.

required
See Also

invariants: Returns this result.

Examples:

>>> from skcomplex.core.analysis import invariants
>>> from skcomplex.core.components import Observable
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> position = Observable('position', lambda s: s.mass.x)
>>> invariants(HarmonicOscillatorSystem(), expressions=[position]).rates['position']
x_d1_mass

IrreversibilityResult(values, duration=None, entropy_production=None, entropies=None, currents=None, statistic=None, p_value=None, balanced=None, centres=None, log_ratios=None, slope=None, mean=None, variance=None, product=None, error=None, holds=None, response=None, fluctuation_dissipation_ratio=None) dataclass

A result of irreversibility, how far a process is from its reverse in time.

It holds the rates, paths, or samples it read and what the kind measures: the entropy production, the test of detailed balance, the fluctuation relations, or the response, such as an entropy production of ln 2 for a ring of five states that steps forward twice as often as back. It reports how far molecular motors, heart beats, and the prices of a market are from equilibrium.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values NDArray[int64] | Array

The rate matrix, the paths one row per path, or the samples the kind reads.

required
duration float | None

The duration of the jump paths, the setting or the duration of a trajectory.

None
entropy_production float | None

The entropy production per unit time in units of k_B, of the entropy production kinds.

None
entropies Array | None

The entropy produced along every path, of 'jump-entropy-production' and 'langevin-entropy-production'.

None
currents Array | None

The net number of transitions from every state to every other per step, of 'detailed-balance'.

None
statistic float | None

The statistic Σ (N_ij - N_ji)² / (N_ij + N_ji) over pairs of states, of 'detailed-balance'.

None
p_value float | None

The chi-squared p-value of the statistic under detailed balance, of 'detailed-balance'.

None
balanced bool | None

Whether the p-value exceeds the significance level, of 'detailed-balance'.

None
centres Array | None

The centres of the bins of entropy whose mirror bin is also populated, of 'fluctuation-theorem'.

None
log_ratios Array | None

ln P(s) / P(-s) at every centre, of 'fluctuation-theorem'.

None
slope float | None

The slope of the log ratio against the entropy, of 'fluctuation-theorem'.

None
mean float | None

The mean of the current over the paths, of 'uncertainty-relation'.

None
variance float | None

The variance of the current over the paths, of 'uncertainty-relation'.

None
product float | None

The squared relative fluctuation of the current times the entropy, of 'uncertainty-relation'.

None
error float | None

The standard error of the product from bootstrap resamples of the paths, of 'uncertainty-relation'.

None
holds bool | None

Whether the product is at least 2 within two standard errors, of 'uncertainty-relation'.

None
response Array | None

The integrated response at every frame, of 'response' and 'fluctuation-dissipation'.

None
fluctuation_dissipation_ratio float | None

The fluctuation-dissipation ratio, of 'fluctuation-dissipation'.

None
See Also

irreversibility: Returns this result.

Examples:

>>> from skcomplex.core.analysis import irreversibility
>>> irreversibility([0, 1, 2] * 1000, kind='detailed-balance').balanced
False

KramersMoyalResult(values, positions, drift, diffusion) dataclass

A result of kramers_moyal, the drift and diffusion of one series.

It holds the series, the centres of the bins of values, and the drift and the diffusion in every bin, such as a diffusion of 1 everywhere for a random walk whose steps have the variance 2 dt. It reports the pull and the noise of wind speeds, heart rates, and exchange rates.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series.

required
positions Array

The centres of the bins of values.

required
drift Array

The first coefficient <dx | x> / dt in every bin.

required
diffusion Array

The second coefficient <dx² | x> / (2 dt) in every bin, so dx = a dt + sqrt(2 D) dW gives D.

required
See Also

kramers_moyal: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import kramers_moyal
>>> x = np.cumsum(np.random.default_rng(0).normal(0, np.sqrt(0.02), 100_000))
>>> kramers_moyal(x, dt=0.01, bins=21).positions.size
21

LargeDeviationsResult(rates=None, increments=None, system=None, samples=None, observations=None, tilts=None, scgf=None, effective_population=None, values=None, rate_function=None, weights=None, mean=None, effective_size=None) dataclass

A result of large_deviations, the odds of rare values of an observable.

It holds the data it read, the scaled cumulant generating function at every tilt, and the rate function at the values, such as 2 (e - 1) at the tilt 1 for the count of a Poisson process of rate 2. It reports the odds of a run of losses of an insurer, a rare current through a channel, or a long drought.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
rates Array | None

The rate matrix of 'tilted'.

None
increments Array | None

The increments of 'block'.

None
system System | ProblemSpec | None

The System, the one a ready-made system builds, or the compiled problem of 'cloning'.

None
samples dict[int, Array] | None

The samples at every size of 'histogram'.

None
observations Array | None

The samples of 'reweight'.

None
tilts Array | None

The tilts of the generating function.

None
scgf Array | None

The scaled cumulant generating function at every tilt.

None
effective_population Array | None

The smallest effective number of clones over the selection steps at every tilt, (Σ w)² / Σ w².

None
values Array | None

The values of the rate function, the centres of the bins of 'histogram'.

None
rate_function Array | None

The rate function at every value, 0 at its minimum and nan where a size left the bin empty for 'histogram'.

None
weights Array | None

The normalized weight of every sample of 'reweight'.

None
mean float | None

The weighted mean of the samples of 'reweight'.

None
effective_size float | None

The effective number of samples 1 / Σ w² of 'reweight'.

None
See Also

large_deviations: Returns this result.

Examples:

>>> from skcomplex.core.analysis import large_deviations
>>> large_deviations([-1.0, 1.0], kind='reweight', log_weights=[0.0, 0.0]).mean
0.0

LinearizationResult(problem, A, B, C, D, states, controls, outputs, controllability, observability, gain) dataclass

A result of linearization, a linear state-space system.

It holds the matrices of x' = A x + B u and y = C x + D u, the ranks that tell whether the controls reach every state and the outputs reveal every state, and the gain of the regulator, such as A = [[0, 1], [-1, 0]] for a unit spring. It gives the linear model of an aircraft near trim, a power grid, or an economy near its steady state.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec

The compiled problem.

required
A Array

The state matrix, the Jacobian of the rates by the states.

required
B Array

The input matrix, the Jacobian of the rates by the controls.

required
C Array

The output matrix, the Jacobian of the outputs by the states.

required
D Array

The feedthrough matrix, the Jacobian of the outputs by the controls.

required
states tuple[str, ...]

The names of the state components, in the order of the rows of A, with a prime for a derivative, such as "cart.x'".

required
controls tuple[str, ...]

The names of the controls, in the order of the columns of B.

required
outputs tuple[str, ...]

The names of the outputs, in the order of the rows of C.

required
controllability int

The rank of the controllability matrix.

required
observability int

The rank of the observability matrix.

required
gain Array | None

The gain of the regulator, one row per control and one column per state, or None without weights.

required
See Also

linearization: Returns this result.

Examples:

>>> from skcomplex.core.analysis import linearization
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> linearization(HarmonicOscillatorSystem()).A.tolist()
[[0.0, 1.0], [-1.0, 0.0]]

LocalInformationResult(values, labels, information) dataclass

A result of local_information, the information sample by sample.

It holds the series and the information of every sample, such as 2 bits for the rare 1 of [0, 0, 0, 1] and less for each common 0. It reports the moments when information moves in a flock, in a cellular automaton, and in the spikes of neurons.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column.

required
labels list[str]

The label of every series.

required
information Array

One row of local entropies per series for 'entropy', and for 'mutual' and 'transfer' one row of local values from the series of every first index to the series of every second index, nan from a series to itself.

required
See Also

local_information: Returns this result.

Examples:

>>> from skcomplex.core.analysis import local_information
>>> local_information([0, 0, 0, 1]).information.round(3).tolist()
[[0.415, 0.415, 0.415, 2.0]]

LoopsResult(problem, trajectory=None, graph=None, loops=None, polarities=None, gains=None, times=None, dominant=None, flows=None, holders=None, matrix=None) dataclass

A result of loops, the feedback loops of a system.

It holds the signed graph of which state drives which, its loops with their polarity and gain, the dominant loop at every frame, or the matrix of the flows between holders, such as a reinforcing loop of word of mouth and a balancing loop of saturation in the spread of a product. It reports the loops of a model of system dynamics, a gene network, and an ecosystem.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec

The compiled problem.

required
trajectory Trajectory | None

The trajectory of 'dominance' and 'flow-matrix'.

None
graph DiGraph | None

The signed dependency graph from each state or flow to every node whose amount or rate depends on it, with the edge attributes sign and gain, for 'loops'. The members of a group and the components of a vector that the Jacobian describes are nodes of their own, named like species.x[0].

None
loops list[tuple[str, ...]] | None

The nodes of every loop, in the order of their influence, starting at its first state by name, or at its first node by name when it holds no state.

None
polarities list[str] | None

The polarity of every loop, at the first frame for 'dominance': 'reinforcing' for a positive product of edge signs, 'balancing' for a negative one, or 'neutral' when an edge has no influence.

None
gains Array | None

The gain of every loop, with one row per frame for 'dominance'.

None
times Array | None

The time of every frame of 'dominance'.

None
dominant NDArray[intp] | None

The index of the loop with the largest absolute gain at every frame of 'dominance'.

None
flows tuple[str, ...] | None

The paths of the flows of the flow matrix.

None
holders tuple[str, ...] | None

The states and environments the flows connect.

None
matrix Array | None

The outflow, negative, and the inflow, positive, of every flow for every holder.

None
See Also

loops: Returns this result.

Examples:

>>> from skcomplex.core.analysis import loops
>>> from skcomplex.systems.economics.innovation import BassDiffusionSystem
>>> loops(BassDiffusionSystem().prepare().system_).polarities
['reinforcing', 'balancing']

LyapunovResult(problem=None, exponents=None, kaplan_yorke_dimension=None, kolmogorov_sinai_entropy=None, values=None, labels=None, largest_exponent=None) dataclass

A result of lyapunov, the Lyapunov exponents of a system or of series.

It holds the exponents, the rates at which nearby runs separate along each direction, with the dimension and the entropy they give, or the largest exponent of every recorded series, such as ln 2 for the logistic map at r = 4. It reports how fast small errors grow in the weather, a double pendulum, and the orbits of asteroids.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec | None

The compiled problem of the spectrum of a system, or None for an array of exponents or for 'largest'.

None
exponents Array | None

The exponents of the spectrum in decreasing order, per unit of time for flows and per iteration for maps, or None for 'largest'.

None
kaplan_yorke_dimension float | None

The Kaplan-Yorke dimension of the spectrum, with j the largest number of exponents whose sum is nonnegative, or None for 'largest'.

None
kolmogorov_sinai_entropy float | None

The entropy rate of the dynamics in nats per unit time, the sum of the positive exponents, or None for 'largest'.

None
values Array | None

The series of 'largest', one per column, or None for 'spectrum'.

None
labels list[str] | None

The label of every series of 'largest', or None for 'spectrum'.

None
largest_exponent Array | None

The largest exponent per unit time of every series of 'largest', or None for 'spectrum'.

None
See Also

lyapunov: Returns this result.

Examples:

>>> from skcomplex.core.analysis import lyapunov
>>> round(lyapunov([0.906, 0.0, -14.572]).kaplan_yorke_dimension, 2)
2.06

MarkovResult(path=None, matrix=None, counts=None, transition_matrix=None, stationary=None, spectral_gap=None, relaxation_times=None, states=None, timescales=None, metastable_sets=None) dataclass

A result of markov, a Markov chain of paths or of a matrix.

It holds the paths or the matrix it read and what the kind measures: the chances of moving from every state to every state, the share of time spent in each state, how fast the chain forgets its start, or the sets of states it lingers in, such as the shares 1/3 and 2/3 of a chain that leaves its second state less often. It reports the chain of weather states, credit ratings, and the shapes of a folding protein.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
path NDArray[int64] | None

The integer states of the paths, one row per path, read without a matrix.

None
matrix Array | None

The matrix read with matrix.

None
counts NDArray[int64] | None

The transition counts, one row per origin, of 'transition-matrix'.

None
transition_matrix Array | None

The probability of every destination after one lag from every origin, of 'transition-matrix' and 'state-system'.

None
stationary Array | None

The stationary law, of 'stationary' and 'state-system'.

None
spectral_gap float | None

The spectral gap, of 'spectral-gap'.

None
relaxation_times Array | None

-dt / ln |lambda|, or -1 / Re lambda for rates, of every mode slowest first, of 'spectral-gap'.

None
states NDArray[int64] | None

The states of the largest connected set, which index the rows of the matrix, of 'state-system'.

None
timescales Array | None

The implied timescales -lag dt / ln |lambda_i| slowest first, of 'state-system', and one row per lag of 'timescales'.

None
metastable_sets list[NDArray[int64]] | None

The states of every metastable set, empty without a number of sets, of 'state-system'.

None
See Also

markov: Returns this result.

Examples:

>>> from skcomplex.core.analysis import markov
>>> markov([[0.5, 0.5], [0.25, 0.75]], kind='stationary', matrix='transition').stationary.round(3).tolist()
[0.333, 0.667]

ModeDecompositionResult(samples, system, labels, states, last_state, dt, training_error, validation_error, eigenvalues, modes, amplitudes, generator, input_generator, operator, input_matrix, dictionary, inputs, forecast) dataclass

A result of mode_decomposition, a linear system fitted to series.

It holds the fitted System, its matrices, its modes with their growth rates and frequencies, the errors of the fit, and the forecast, such as the frequencies 1 and -1 of a point that turns on the unit circle. It reports the patterns of a fluid flow, brain activity, and traffic in a city.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
samples _SamplesSpec

The series of every run, the names of the variables, and the step.

required
system System

The System of one surrogate element and one interaction whose rate laws dg/dt = L g + M u flow in continuous time.

required
labels list[str]

The variables, or the observables of the dictionary, in the order of the states.

required
states list[str]

The names of the states of the surrogate element.

required
last_state Array

The values of the states at the last sample of the last run, where the forecast starts.

required
dt float

The time between the samples it was fitted to.

required
training_error float

The relative error of the predicted increments over one sample on the training samples.

required
validation_error float

The relative error on the held-out samples, NaN when none are held out.

required
eigenvalues ComplexArray

The continuous eigenvalues ln(mu) / dt of the modes, from the eigenvalues mu of the one-sample map.

required
modes ComplexArray

The modes, one column per mode and one row per state.

required
amplitudes ComplexArray

The amplitudes of the modes at the last sample of the last run.

required
generator Array

The matrix L of the rate law, one row and one column per state.

required
input_generator Array

The matrix M of the rate law, one row per state and one column per input.

required
operator Array

The matrix A of the one-sample map, one row and one column per state.

required
input_matrix Array

The matrix B of the one-sample map, one row per state and one column per input.

required
dictionary TransformerMixin | None

The fitted dictionary, which lifts new states to the observables, or None without a dictionary.

required
inputs list[str]

The names of the parameters of the surrogate element that hold the inputs.

required
forecast Array

The states at the horizon samples after the last one, one row per sample.

required
See Also

mode_decomposition: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import mode_decomposition
>>> times = np.arange(0.0, 10.0, 0.1)
>>> result = mode_decomposition(np.column_stack([np.cos(times), np.sin(times)]), horizon=5, dt=0.1)
>>> result.forecast.shape
(5, 2)

MotifsResult(graphs, counts, null_mean=None, null_std=None, z_scores=None) dataclass

A result of motifs, the counts and scores of small subgraphs.

It holds the graph of every frame, the count of every motif, and for z-scores how far each count lies from those of random graphs with the same degrees, such as the four triangles of four nodes all joined. It reports the feedforward loops of a gene network, the triangles of a social network, and the circuits of a food web.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
graphs list[Graph]

The graph of every frame.

required
counts list[dict[str, int]]

The count of every motif of every frame.

required
null_mean list[dict[str, float]] | None

The mean count of every motif over the null ensemble of every frame, for 'z-scores'.

None
null_std list[dict[str, float]] | None

The standard deviation of every count over the null ensemble of every frame, for 'z-scores'.

None
z_scores list[dict[str, float]] | None

The z-score of every motif of every frame, for 'z-scores'.

None
See Also

motifs: Returns this result.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.analysis import motifs
>>> motifs(nx.complete_graph(4), size=4).counts
[{'clique': 1}]

NeighborsResult(positions=None, box=None, frames=None, distances=None, ratio=None, radii=None, distribution=None, share=None) dataclass

A result of neighbors, the neighbours of agents, cells, or nodes.

It holds the positions or the states it read and the statistic of the kind for every frame, such as a distance of 1 between two points at 0.5 and 9.5 in a periodic box of side 10. It reports how close birds sit in a flock, how cells pack in a tissue, and how far households live from others like them.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
positions Array | None

The positions, frames by agents by dimensions, for the agent kinds.

None
box Array | None

The sides of the periodic box, or None for open space, for the agent kinds.

None
frames list[Array] | list[Graph] | None

The grids of states, or the graphs, for 'like-share'.

None
distances Array | None

The nearest-neighbour distances, frames by agents, for 'distances'.

None
ratio Array | None

One Clark-Evans ratio per frame, for 'clark-evans'.

None
radii Array | None

The bin centres of g(r), for 'radial-distribution'.

None
distribution Array | None

g(r) at every bin centre, for 'radial-distribution'.

None
share Array | None

One like share per frame, for 'like-share'.

None
See Also

neighbors: Returns this result.

Examples:

>>> from skcomplex.core.analysis import neighbors
>>> neighbors([[1, 1, 2, 2]] * 4, kind='like-share', diagonal=False).share.tolist()
[0.75]

NetworkMeasuresResult(graphs, degrees=None, moments=None, exponent=None, assortativity=None, centrality=None, labels=None, modularity=None, agreement=None, distinct_degrees=None, neighbor_degree=None, nodes=None, edges=None, mean_degree=None, clustering=None, path_length=None, diameter=None, components=None) dataclass

A result of network_measures, measures of a network at every frame.

It holds the graph of every frame and what the kind measures: the degrees, how alike linked nodes are, how central each node is, the communities, or a summary of size, clustering, and paths, such as the mean degree 2 of a ring. It reports the hubs of the internet, the clustering of a social network, and the paths of a power grid.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
graphs list[Graph]

The graph of every frame.

required
degrees list[NDArray[int64]] | None

The degree of every node of every frame, for 'degrees'.

None
moments Array | None

The degree moments, frames by orders, for 'degrees'.

None
exponent Array | None

The fitted degree exponent of every frame, for 'degrees'.

None
assortativity Array | None

The assortativity of every frame, for 'assortativity'.

None
centrality list[dict[object, float]] | None

A mapping from node to its centrality for every frame, for 'centrality'.

None
labels list[NDArray[int64]] | None

The community of every node of every frame, for 'communities'.

None
modularity Array | None

The modularity of every frame, for 'communities'.

None
agreement Array | None

The normalized mutual information with the reference of every frame, or None without a reference.

None
distinct_degrees list[NDArray[int64]] | None

The distinct degrees of every frame, for 'neighbor-degree'.

None
neighbor_degree list[NDArray[float64]] | None

The mean neighbour degree of the nodes of every distinct degree of every frame, for 'neighbor-degree'.

None
nodes NDArray[int64] | None

The number of nodes of every frame, for 'summary'.

None
edges NDArray[int64] | None

The number of edges of every frame, for 'summary'.

None
mean_degree Array | None

The mean degree of every frame, for 'summary'.

None
clustering Array | None

The average clustering of every frame, for 'summary'.

None
path_length Array | None

The average shortest path length of the largest component of every frame, for 'summary'.

None
diameter NDArray[int64] | None

The diameter of the largest component of every frame, for 'summary'.

None
components list[list[int]] | None

The sizes of the connected components of every frame, largest first, for 'summary'.

None
See Also

network_measures: Returns this result.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.analysis import network_measures
>>> network_measures(nx.star_graph(3), kind='degrees').moments.tolist()
[[1.5, 3.0]]

PartialInformationResult(values, labels, redundancy, unique_first, unique_second, synergy, total) dataclass

A result of partial_information, the parts of the information of two sources.

It holds the symbols and the four parts of what two sources tell about a target, the shared, the two unique, and the synergistic part, with their sum, such as 1 bit unique to the first source when the target copies it. It reports what two genes tell about a trait, two neurons about a stimulus, or two indicators about a market.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The symbols of the two sources and the target, one per column.

required
labels list[str]

The label of every series.

required
redundancy float

The information both sources give.

required
unique_first float

The information only the first source gives.

required
unique_second float

The information only the second source gives.

required
synergy float

The information only the two sources together give.

required
total float

The mutual information of the two sources together with the target, the sum of the four parts.

required
See Also

partial_information: Returns this result.

Examples:

>>> from skcomplex.core.analysis import partial_information
>>> copy = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
>>> round(partial_information(copy).unique_first, 6)
1.0

PassageResult(values=None, times=None, matrix=None, passage_times=None, hitting_probabilities=None, return_times=None, committor=None, mean_first_passage_time=None) dataclass

A result of passage, the first passages of paths to a level or a set.

It holds the paths, the series, or the matrix it read and what the kind measures: when every path first reaches a level or a set of states, where it ends, how long it takes to come back, or the chance of reaching one set before another, such as the time 2 of a path that climbs one step at a time to the level 2. It reports the time until a population dies out, a price hits a barrier, or a protein folds.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array | None

The paths, one row per path, or the series of 'return-times'.

None
times Array | None

The common times of the steps.

None
matrix Array | None

The transition matrix of the matrix kinds.

None
passage_times Array | None

The time from the start to the first passage of every path, nan for paths that never pass, of 'first-passage'.

None
hitting_probabilities Array | None

The share of paths that hit every target state first, of 'hitting'.

None
return_times Array | None

The time between every return and the next, of 'return-times'.

None
committor Array | None

The committor of every state, 0 on the origin and 1 on the target, of 'committor'.

None
mean_first_passage_time float | None

The mean first-passage time, of 'mean-first-passage'.

None
See Also

passage: Returns this result.

Examples:

>>> from skcomplex.core.analysis import passage
>>> walk = [[0.5, 0.5, 0.0], [0.25, 0.5, 0.25], [0.0, 0.5, 0.5]]
>>> passage(walk, kind='committor', origin=[0], target=[2]).committor.tolist()
[0.0, 0.5, 1.0]

RecurrenceResult(values, labels, radius, matrix, rate, determinism, laminarity, mean_diagonal, longest_diagonal, trapping_time, entropy) dataclass

A result of recurrence, the recurrence matrix and its statistics.

It holds the points, the matrix that marks every pair of times whose points lie within the radius, and the statistics of its lines, such as a determinism near 1 for a sine wave. It tells regular rhythms of a heart, regime changes of the climate, and periodic orbits of an oscillator apart from noise.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The points, one per row.

required
labels list[str]

The label of every coordinate.

required
radius float

The recurrence radius.

required
matrix csr_array

The symmetric sparse boolean recurrence matrix, with a true diagonal.

required
rate float

The share of recurrent pairs off the Theiler window.

required
determinism float

The share of recurrent points on diagonal lines of at least the minimum length.

required
laminarity float

The share of recurrent points on vertical lines of at least the minimum length.

required
mean_diagonal float

The mean length of those diagonal lines.

required
longest_diagonal int

The length of the longest diagonal line.

required
trapping_time float

The mean length of those vertical lines.

required
entropy float

The Shannon entropy in nats of the distribution of those diagonal line lengths.

required
See Also

recurrence: Returns this result.

Examples:

>>> from skcomplex.core.analysis import recurrence
>>> recurrence([0.0, 0.1, 5.0, 5.1], radius=0.5).matrix.toarray().astype(int).tolist()
[[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]

RenormalizationResult(graph, graphs, degrees, exponents, clustering) dataclass

A result of renormalization, the network at every scale.

It holds the network it read, the network after every merge of nodes into supernodes, and the degrees, the degree exponent, and the clustering at every scale, such as two dense groups joined by one link that merge into two linked supernodes. It reports the structure of the internet, the brain, and transport networks across scales.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
graph Graph

The network read from the source.

required
graphs list[Graph]

The network at every scale, the original first.

required
degrees list[NDArray[int64]]

The degree of every node at every scale.

required
exponents Array

The fitted degree exponent at every scale, nan below 50 nodes or for a narrow distribution, as network_measures(kind='degrees') fits it.

required
clustering Array

The average clustering at every scale.

required
See Also

renormalization: Returns this result.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.analysis import renormalization
>>> ring = nx.cycle_graph(8)
>>> nx.set_node_attributes(ring, {node: float(node) for node in ring}, 'angle')
>>> [graph.number_of_nodes() for graph in renormalization(ring, kind='geometric', steps=2).graphs]
[8, 4, 2]

ReservoirResult(samples, system, labels, states, last_state, dt, training_error, validation_error, step, forecast) dataclass

A result of reservoir, a reservoir system fitted to series.

It holds the fitted System, which steps once per sample, its states, the errors of its predicted increments over one sample, the map it steps with, and the forecast, such as the states x, memory_0, and memory_1 of a reservoir that reads two consecutive samples of x. It gives a model of a chaotic flow, a power demand, or a speech signal learned from series alone.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
samples _SamplesSpec

The series of every run, the names of the variables, and the step.

required
system System

The System of one surrogate element and one interaction whose update law steps in discrete time, one step per sample, and whose states are the variables and then the memory of the reservoir.

required
labels list[str]

The variables the surrogate was fitted to.

required
states list[str]

The names of the states of the surrogate element, the variables first.

required
last_state Array

The variables at the last sample of the last series and the memory the series left, where forecasts start.

required
dt float

The time between the samples it was fitted to, which one step of the system stands for.

required
training_error float

The relative error of the predicted increments on the training samples, with the reservoir driven by the series.

required
validation_error float

The relative error on the held-out samples, NaN when none are held out.

required
step _ReservoirStep

The map from the states to the states one step later, which the update law calls, holding the fitted reservoir node node, the ridge node readout, and the standardisation mean and scale.

required
forecast Array

The variables at the horizon samples after the last one, one row per sample.

required
See Also

reservoir: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import reservoir
>>> reservoir(np.sin(0.1 * np.arange(400.0)), variables=['x']).states
['x', 'memory_0', 'memory_1']

RollingResult(values, labels, statistic, trend) dataclass

A result of rolling, a statistic in rolling windows and its trend.

It holds the series, the statistic of every window set at its last sample, and the trend of the statistic, such as a trend of 1 for a variance that grows in every window. It reports the early warnings of a lake that turns turbid, a market that crashes, or a climate that shifts.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column.

required
labels list[str]

The label of every series.

required
statistic Array

The statistic of every series in every window, one row per series, nan before the first full window.

required
trend Array

Kendall's tau of the statistic of every series against time, positive when it rises.

required
See Also

rolling: Returns this result.

Examples:

>>> from skcomplex.core.analysis import rolling
>>> rolling([0, 1, 0, 2, 0, 3], window=3).statistic.round(2).tolist()
[[nan, nan, 0.22, 0.67, 0.89, 1.56]]

ScalingResult(values, samples, labels, exponent, scales=None, fluctuations=None, counts=None, sums=None, means=None, deviations=None, fit_range=None, interval=None) dataclass

A result of scaling, a scaling exponent, a fractal dimension, or a law.

It holds what the source was read as, the exponent of every series or the dimension of a set of cells or points, and the curves it is fitted on, such as the dimension 2 of a filled square. It reports the long memory of river flows, the fractal dimension of a coastline, and the critical exponents of a magnet.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column, the field or its frames, or the points, an empty array for samples by size, and the pairs of sizes and samples of 'allometric', one per row.

required
samples dict[float, Array] | None

The samples by size, or None for a source of series, points, or a field.

required
labels list[str]

The label of every series, of the field, or of every size.

required
exponent float | Array

The exponent of every series for the fluctuation kinds and 'power', the slope of the variance-mean law, the exponent of the allometric law, and the dimension for the other kinds.

required
scales Array | None

The window sizes, the box sides, the radii, or the sizes, or None for 'power'.

None
fluctuations Array | None

The fluctuation, or the rescaled range, of every series at every window size, for the fluctuation kinds.

None
counts Array | None

The number of occupied boxes of every side, for 'box-counting'.

None
sums Array | None

The share of pairs of points closer than every radius, for 'correlation-dimension'.

None
means Array | None

The mean of the quantity at every scale, for 'variance-mean'.

None
deviations Array | None

The standard deviation of the quantity at every scale, for 'variance-mean'.

None
fit_range tuple[float, float] | None

The smallest and largest radii of the fit of the correlation dimension, for 'correlation-dimension'.

None
interval tuple[float, float] | None

The lower and upper ends of the confidence interval of the allometric exponent, for 'allometric'.

None
See Also

scaling: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import scaling
>>> round(scaling(np.ones((256, 256)), kind='box-counting').exponent, 2)
2.0

SectionResult(problem, times, states, values) dataclass

A result of section, the states of a flow at a crossing or at each period.

It holds the time and the state of every point of the section and the values of the read states there, such as a unit spring that crosses x = 0 upward every 2 pi with the speed 1. It reports the crossings of the orbit of a planet, a forced pendulum, and a heart rhythm.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec

The compiled problem of a Poincaré or stroboscopic section.

required
times Array

The time of every point of a section.

required
states Array

One state vector per point of a section.

required
values dict[str, Array]

A mapping from the name of every read state to its values at the points of a section, one row per point for a vector state. A derivative is named with a prime, such as mass.x', as in trajectories.

required
See Also

section: Returns this result.

Examples:

>>> from skcomplex.core.analysis import section
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> section(HarmonicOscillatorSystem(), state='mass.x', until=20.0).values["mass.x'"].round(3).tolist()
[1.0, 1.0, 1.0]

SignatureSpec(kind, title, xlabel, ylabel, curves, values=dict(), xscale='linear', yscale='linear', points=False) dataclass

Bases: BaseSpec

A spec of the default analysis of one kind of data, ready to plot.

It holds the title, the labels and scales of the axes, the curves, and the values worth stating of one figure, such as the power spectrum of the prey and the predators of a Lotka-Volterra run on log axes. It gives the first look at the series of an ecosystem, the jumps of a market, or the field of a chemical pattern.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
kind DataKind

The kind of data analysed.

required
title str

The title of the figure.

required
xlabel str

The label of the horizontal axis.

required
ylabel str

The label of the vertical axis.

required
curves dict[str, tuple[Array, Array]]

A mapping from label to the abscissas and ordinates of every curve.

required
values dict[str, float]

The measured values worth stating, by name.

dict()
xscale str

'linear' or 'log'.

'linear'
yscale str

'linear' or 'log'.

'linear'
points bool

Whether the curves are drawn as points rather than lines.

False
See Also

signatures: Returns one spec per kind of data of a trajectory.

Examples:

>>> from skcomplex.core.analysis import signatures
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> trajectory = LotkaVolterraSystem().prepare().simulate(until=20.0, random_state=0)
>>> signatures(trajectory).signatures[0].xlabel
'frequency'

SignaturesResult(kinds, discrete, signatures, snapshots=None, frames=None, graphs=None, path=None, jumps=None, series=None) dataclass

A result of signatures, one default analysis per kind of data.

It holds the kinds of data of the trajectory, the data read for each, and one figure per kind with its curves, axis labels, title, and values, such as the power spectrum of the series of a Lotka-Volterra run. It gives the first look at the series of an ecosystem, the jumps of a market, or the field of a chemical pattern.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
kinds list[DataKind]

The data kinds of the trajectory, in the order agents, field, network, path, series.

required
discrete bool

Whether the trajectory is that of a map, whose series give a return map.

required
signatures list[SignatureSpec]

One signature per data kind, in the order of kinds, each with its kind, title, axis labels and scales, curves, and stated values.

required
snapshots _SnapshotsSpec | None

The agents of the first group at every frame, for the agents kind.

None
frames Array | None

The frames of the first lattice state, for the field kind.

None
graphs list[Graph] | None

The network of every frame, for the network kind.

None
path _JumpPathSpec | None

The jump path of the first discrete state, for the path kind.

None
jumps Array | None

The size of the jumps of that state between frames, for the path kind.

None
series _SeriesSpec | None

The scalar series, for the series kind.

None
See Also

signatures: Returns this result.

Examples:

>>> from skcomplex.core.analysis import signatures
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> trajectory = LotkaVolterraSystem().prepare().simulate(until=20.0, random_state=0)
>>> [kind.value for kind in signatures(trajectory).kinds]
['series']

SparseIdentificationResult(samples, system, labels, states, last_state, dt, training_error, validation_error, features, coefficients, forecast) dataclass

A result of sparse_identification, a sparse symbolic system.

It holds the fitted System, the candidate terms and the coefficient of each in the rate of every state, the errors of the fit, and the forecast, such as the rate x' = -2 x found from a decaying exponential. It reports the equations of a fluid flow, a chemical reaction, and a predator and prey cycle.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
samples _SamplesSpec

The series of every run, the names of the variables, and the step.

required
system System

The System of one surrogate element and one interaction with one rate law per variable, which flows in continuous time.

required
labels list[str]

The variables the system was fitted to, in the order of its states.

required
states list[str]

The names of the states of the surrogate element.

required
last_state Array

The values of the states at the last sample of the last run, where the forecast starts.

required
dt float

The time between the samples it was fitted to.

required
training_error float

The relative error of the predicted derivatives on the training samples.

required
validation_error float

The relative error on the held-out samples, NaN when none are held out.

required
features list[str]

The candidate monomials of the states, such as x y.

required
coefficients Array

The coefficient of every monomial in the rate of every state, one row per state and one column per monomial, zero where the term is absent.

required
forecast Array

The variables at the horizon samples after the last one, one row per sample.

required
See Also

sparse_identification: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import sparse_identification
>>> times = np.arange(0.0, 2.0, 0.001)
>>> sparse_identification(np.exp(-2 * times), variables=['x'], degree=1, dt=0.001).features
['1', 'x']

SpectrumResult(values, labels, power, frequencies=None, wavenumbers=None) dataclass

A result of spectrum, the spectrum of series or of a field.

It holds the data read and how its power spreads over frequencies, or over wavenumbers for a field, such as a peak at the wavelength 8 for stripes that repeat every 8 sites. It reports the rhythms of brain waves, the cycles of a business, and the energy cascade of turbulence.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The series, one per column, or the field.

required
labels list[str]

The label of every series, or of the field.

required
power Array

One density per series and frequency for 'power', and the mean power in every shell for 'structure-factor'.

required
frequencies Array | None

The frequencies, for 'power'.

None
wavenumbers Array | None

The wavenumbers of the shells, without 0, for 'structure-factor'.

None
See Also

spectrum: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import spectrum
>>> factor = spectrum(np.cos(2 * np.pi * np.arange(64) / 8)[:, None] * np.ones(64), kind='structure-factor')
>>> round(float(2 * np.pi / factor.wavenumbers[factor.power.argmax()]), 1)
8.0

StabilityResult(problem=None, names=None, jacobian=None, divergence=None, nullclines=None, fixed_points=None, eigenvalues=None, classifications=None, system=None, wavenumbers=None, magnitudes=None, growth_rates=None, frequencies=None, uniform=None, band=None) dataclass

A result of stability, the linear stability of a system.

It holds the Jacobian, the nullclines, and the fixed points with their classes, or the growth rate of every wave of a field, such as a stable node at the carrying capacity of logistic growth. It reports whether a steady state of an epidemic, a chemical reactor, or a power grid returns after a small push.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec | None

The compiled problem, set for 'fixed-points'.

None
names list[str] | None

The state component names, in the order of the rows of the Jacobian, set for 'fixed-points'.

None
jacobian Matrix | None

The Sage matrix of the partial derivatives of the right sides by the states, set for 'fixed-points'.

None
divergence Expression | None

The trace of the Jacobian, 0 for volume-preserving flows, set for 'fixed-points'.

None
nullclines dict[str, Expression] | None

A mapping from state component name to its nullcline as a Sage relation, where its rate is 0 or where it is its own next value, set for 'fixed-points'.

None
fixed_points list[dict[str, Expression | float]] | None

One mapping from state component name to its value per point, the fixed points found or the given points, set for 'fixed-points'.

None
eigenvalues list[NDArray[complex128]] | None

The eigenvalues of the Jacobian at every point, set for 'fixed-points'.

None
classifications list[str] | None

The class of every point: stable node, stable focus, unstable node, unstable focus, saddle, centre, or marginal for flows, and stable, unstable, saddle, or marginal for maps, set for 'fixed-points'.

None
system System | None

The System of one field, the one a ready-made system builds, set for 'dispersion'.

None
wavenumbers Array | None

The wave vector of every mode, one row per mode, set for 'dispersion'.

None
magnitudes Array | None

The length of every wave vector, set for 'dispersion'.

None
growth_rates Array | None

The largest real part of the eigenvalues of the linearisation at every mode, set for 'dispersion'.

None
frequencies Array | None

The imaginary part of the leading eigenvalue at every mode, nonzero for travelling or oscillating modes, set for 'dispersion'.

None
uniform dict[str, float] | None

The uniform state the system is linearised around, by state name, set for 'dispersion'.

None
band Array | None

The lengths of the wave vectors whose modes grow, set for 'dispersion'.

None
See Also

stability: Returns this result.

Examples:

>>> from skcomplex.core.analysis import stability
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> stability(LogisticGrowthSystem(), points=[{'population.x': 100.0}]).classifications
['stable node']

SurrogateTestResult(values, value, surrogates, p_value) dataclass

A result of surrogate_test, a measure tested against surrogates.

It holds the data, the measure on the data and on every surrogate, where every variable is shuffled on its own, and the p-value, such as 0.05 for three copies of one coin flip tested against 19 surrogates. It reports whether a coupling between brain regions, markets, or climate indices is more than chance.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
values Array

The data, one row per sample and one column per variable.

required
value float

The measure on the data.

required
surrogates Array

The measure on every surrogate.

required
p_value float

The p-value of the data against the surrogates.

required
See Also

surrogate_test: Returns this result.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import bind_analysis, information, surrogate_test
>>> bits = np.column_stack([np.random.default_rng(0).integers(0, 2, 500)] * 3)
>>> measure = bind_analysis(information, kind='o-information')
>>> surrogate_test(bits, analysis=measure, attribute='information', n=19).surrogates.shape
(19,)

SymbolicResult(problem, equations=None, solutions=None, hamiltonian=None, inflows=None) dataclass

A result of symbolic, the symbolic form of a system.

It holds the compiled problem and what the kind derives: the equations, their exact solution, the Hamiltonian, or the flows across the boundary, such as x' = r x for exponential growth. It reports the equations of an epidemic, a circuit, and a mechanical system, and their exact solutions where they exist.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
problem ProblemSpec | OperatorProblemSpec

The compiled problem.

required
equations dict[str, Expression] | None

A mapping from state component name to its equation, set for 'equations'.

None
solutions dict[str, Expression] | None

A mapping from state component name to its solution, a relation f(t) == solution, set for 'solve'. States of higher order appear once, without their derivatives.

None
hamiltonian Expression | None

The Hamiltonian, a Sage expression of local operators, set for 'hamiltonian'.

None
inflows dict[str, Expression] | None

The symbolic rate, or amount per step, at which each quantity enters the system from the environment, set for 'conservation'.

None
See Also

symbolic: Returns this result.

Examples:

>>> from skcomplex.core.analysis import symbolic
>>> from skcomplex.systems.biology.ecology import ExponentialGrowthSystem
>>> symbolic(ExponentialGrowthSystem(), kind='solve', use_initial_state=True).solutions['population.x']
x_population(t) == 10*e^(r_growth*t)

alignment(source, *, kind='mean-vector', variables=None, group=None, vectors=False)

Return how well the members of a source line up at every frame.

Each member holds an angle or a direction, and the order is the length of their mean direction, 1 when every member points the same way and about 1 / sqrt(n) for n random directions, as in alignment([0.0, 0.0, 0.0]). The members are the agents of a group, the sites of a field, or the columns of a set of series, and other kinds measure turning around a centre, line-up that ignores the sign, the mean phase, and the main axis of a matrix value. It measures how well the birds of a flock fly together, how the spins of a magnet line up, and how the cells of a tissue orient.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of angles, vectors, positions and velocities, or tensor components.

required
kind str

What to measure. 'mean-vector' is the length of the mean unit vector. 'mean-rotation' is the mean turning of agents about their centre in a plane, 1 when every agent turns the same way, read from positions followed by velocities. 'axial' is |<exp(2 i theta)>|, which ignores the sign of a direction. 'mean-phase' gives the modulus r and the argument psi of r exp(i psi) = <exp(i theta)>, the synchrony and the mean phase. 'principal-axis' gives the main axis of a symmetric matrix value at every site and its order. An array of angles holds one snapshot in one dimension and one frame per row otherwise.

'mean-vector'
variables Sequence[str] | None

The field or the series of a trajectory to read, or None for its agents, or else its first field, its states with the role 'phase', or its scalar series.

None
group str | None

The path of the agent group of a trajectory, or None for the first one.

None
vectors bool

Whether the members hold vectors rather than angles.

False

Returns:

Name Type Description
result AlignmentResult

The members read and their alignment at every frame.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, the trajectory holds no kind of data the function reads, or the source lacks what the kind needs.

See Also

correlation: Measures how values at two places or times move together. spectrum: Finds the frequencies of a series.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import alignment
>>> phases = alignment([[0.5, 0.5], [0.0, np.pi]], kind='mean-phase')
>>> phases.order.round(6).tolist()
[1.0, 0.0]
Source code in src/skcomplex/core/analysis/_alignment.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def alignment(
    source: DataSource,
    *,
    kind: str = 'mean-vector',
    variables: Sequence[str] | None = None,
    group: str | None = None,
    vectors: bool = False,
) -> AlignmentResult:
    """Return how well the members of a source line up at every frame.

    Each member holds an angle or a direction, and the order is the length of their mean direction, 1 when every member
    points the same way and about `1 / sqrt(n)` for `n` random directions, as in `alignment([0.0, 0.0, 0.0])`. The
    members are the agents of a group, the sites of a field, or the columns of a set of series, and other kinds measure
    turning around a centre, line-up that ignores the sign, the mean phase, and the main axis of a matrix value. It
    measures how well the birds of a flock fly together, how the spins of a magnet line up, and how the cells of a
    tissue orient.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of angles, vectors, positions and velocities, or tensor components.

        kind:
            What to measure. `'mean-vector'` is the length of the mean unit vector. `'mean-rotation'` is the mean
            turning of agents about their centre in a plane, 1 when every agent turns the same way, read from positions
            followed by velocities. `'axial'` is `|<exp(2 i theta)>|`, which ignores the sign of a direction.
            `'mean-phase'` gives the modulus `r` and the argument `psi` of `r exp(i psi) = <exp(i theta)>`, the
            synchrony and the mean phase. `'principal-axis'` gives the main axis of a symmetric matrix value at every
            site and its order. An array of angles holds one snapshot in one dimension and one frame per row otherwise.

        variables:
            The field or the series of a trajectory to read, or `None` for its agents, or else its first field, its
            states with the role `'phase'`, or its scalar series.

        group:
            The path of the agent group of a trajectory, or `None` for the first one.

        vectors:
            Whether the members hold vectors rather than angles.

    Returns:
        result:
            The members read and their alignment at every frame.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, the trajectory holds no kind of data the
            function reads, or the source lacks what the kind needs.

    See Also:
        correlation: Measures how values at two places or times move together.
        spectrum: Finds the frequencies of a series.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import alignment
        >>> phases = alignment([[0.5, 0.5], [0.0, np.pi]], kind='mean-phase')
        >>> phases.order.round(6).tolist()
        [1.0, 0.0]
    """
    _check_choice('alignment', 'kind', kind, KINDS)
    _check_settings(alignment, 'kind', SETTINGS[kind], kind=kind, variables=variables, group=group, vectors=vectors)
    if isinstance(source, Trajectory):
        angles, velocities, positions, tensors = _read_trajectory(source, kind, variables, group, vectors=vectors)
    else:
        angles, velocities, positions, tensors = _read_array(source, kind, vectors=vectors)
    if kind == 'principal-axis':
        axes, order = _principal_axis(tensors)
        return AlignmentResult(angles, velocities, positions, order, tensors=tensors, axes=axes)
    derived = angles
    if derived is None and velocities is not None:
        across = velocities[..., 1] if velocities.shape[-1] > 1 else np.zeros_like(velocities[..., 0])
        derived = np.arctan2(across, velocities[..., 0])
    error_msg = (
        f'alignment of kind {kind!r} needs the angles, vectors, or positions that the source lacks. Use a source with '
        'them.'
    )
    if kind == 'mean-rotation':
        if positions is None or velocities is None:
            raise AnalysisError(error_msg)
        return AlignmentResult(angles, velocities, positions, _mean_rotation(positions, velocities))
    if derived is None:
        raise AnalysisError(error_msg)
    if kind == 'mean-vector':
        order = (
            _mean_vector_length(velocities, vectors=True) if velocities is not None else _mean_vector_length(derived)
        )
        return AlignmentResult(angles, velocities, positions, order)
    if kind == 'axial':
        return AlignmentResult(angles, velocities, positions, _axial_order(derived))
    mean = _mean_phase(derived)
    return AlignmentResult(angles, velocities, positions, np.abs(mean), phase=np.angle(mean))

applicable_analyses(source)

Return the analyses that apply to a trajectory, a system, or an array.

It reads the kinds of data the source holds, such as a field and a set of series for a 2D array, and keeps every analysis of the library that reads one of them and needs no setting, bound once per kind. A system or a trajectory of one also drops the analyses whose tags the system lacks, such as lyapunov of a random system. It answers which measures fit a run of an epidemic, a grid of a forest, or a table of prices.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, the system, the graph, or the array.

required

Returns:

Name Type Description
result ApplicableAnalysesResult

The data kinds of the source, how they are read, and the analyses of every kind.

See Also

AnalysisTags: Names what an analysis needs of its data. bind_analysis: Fixes the settings of an analysis.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import applicable_analyses
>>> applicable_analyses(np.zeros((16, 16))).readings['series']
'every column of the array as a series'
Source code in src/skcomplex/core/analysis/_discovery.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def applicable_analyses(source: DataSource) -> ApplicableAnalysesResult:
    """Return the analyses that apply to a trajectory, a system, or an array.

    It reads the kinds of data the source holds, such as a field and a set of series for a 2D array, and keeps every
    analysis of the library that reads one of them and needs no setting, bound once per kind. A system or a trajectory
    of one also drops the analyses whose tags the system lacks, such as `lyapunov` of a random system. It answers which
    measures fit a run of an epidemic, a grid of a forest, or a table of prices.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, the system, the graph, or the array.

    Returns:
        result:
            The data kinds of the source, how they are read, and the analyses of every kind.

    See Also:
        AnalysisTags: Names what an analysis needs of its data.
        bind_analysis: Fixes the settings of an analysis.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import applicable_analyses
        >>> applicable_analyses(np.zeros((16, 16))).readings['series']
        'every column of the array as a series'
    """
    source = _composite(source)
    kinds = [str(kind) for kind in _get_data_kinds(source)]
    if isinstance(source, Trajectory | _CompositeSystem | nx.Graph | NetworkSnapshotSpec):
        readings = {kind: DataKind(kind).reading for kind in kinds}
    else:
        readings = {kind: _get_array_reading(DataKind(kind), np.ndim(source)) for kind in kinds}
    tags = _get_source_tags(source)
    analyses: dict[str, list[partial[object]]] = {kind: [] for kind in kinds}
    for function in ANALYSES:
        parameters = list(inspect.signature(function).parameters.values())[1:]
        if any(parameter.default is inspect.Parameter.empty for parameter in parameters):
            continue
        family = getattr(sys.modules[function.__module__], 'KINDS', None)
        if family is not None and any(parameter.name == 'kind' for parameter in parameters):
            bound = [(bind_analysis(function, kind=kind), _get_analysis_tags(function, kind)) for kind in family]
        else:
            bound = [(bind_analysis(function), _get_analysis_tags(function))]
        for analysis, needed in bound:
            if needed.data in analyses and (tags is None or not needed.get_missing(tags)):
                analyses[needed.data].append(analysis)
    return ApplicableAnalysesResult(kinds, readings, analyses)

autocatalytic_sets(source, *, food=None, frames=None)

Return the largest set of reactions that catalyse each other, at every frame.

The network is a snapshot whose hyperedges are reactions, each making its last member from the others, and whose edges are catalysis, an edge from c to p making c a helper of every reaction that makes p. A set of reactions is autocatalytic when every reaction has a helper made by the set or found in the food, and every reactant can be made from the food by the set. The algorithm of Hordijk and Steel (2004) drops the reactions that fail, again and again, and returns what is left, an empty set when there is none. It finds sets of molecules that make themselves at the origin of life and goods that are made from each other in the economies of Hordijk and Kauffman (2022).

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The network snapshot, or the trajectory of a network whose hyperedges change.

required
food Sequence[int] | None

The node rows of the food set, or None for the nodes present that no reaction produces.

None
frames Sequence[int] | None

The frames of a trajectory to analyse, or None for every frame.

None

Returns:

Name Type Description
result AutocatalyticSetsResult

The snapshots, and the reactions, products, size, and share of the largest RAF of every frame.

Raises:

Type Description
AnalysisError

The source is neither a network snapshot nor a trajectory of a network whose hyperedges change.

See Also

loops: Finds the feedback loops of a network. elementary_modes: Finds the pathways of a metabolism.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import autocatalytic_sets
>>> from skcomplex.core.engine.problems import NetworkSnapshotSpec
>>> edges, reactions = np.array([[3, 4, 0], [2, 3, 4]]), np.array([[0, 1, 2], [2, 0, 3], [3, 1, 4]])
>>> autocatalytic_sets(NetworkSnapshotSpec(np.arange(5), *edges, np.arange(3), reactions)).reactions[0].tolist()
[0, 1, 2]
Source code in src/skcomplex/core/analysis/_autocatalytic.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def autocatalytic_sets(
    source: DataSource,
    *,
    food: Sequence[int] | None = None,
    frames: Sequence[int] | None = None,
) -> AutocatalyticSetsResult:
    """Return the largest set of reactions that catalyse each other, at every frame.

    The network is a snapshot whose hyperedges are reactions, each making its last member from the others, and whose
    edges are catalysis, an edge from `c` to `p` making `c` a helper of every reaction that makes `p`. A set of
    reactions is autocatalytic when every reaction has a helper made by the set or found in the food, and every reactant
    can be made from the food by the set. The algorithm of Hordijk and Steel (2004) drops the reactions that fail, again
    and again, and returns what is left, an empty set when there is none. It finds sets of molecules that make
    themselves at the origin of life and goods that are made from each other in the economies of Hordijk and Kauffman
    (2022).

    Read more in the user guide, under Analyse.

    Args:
        source:
            The network snapshot, or the trajectory of a network whose hyperedges change.

        food:
            The node rows of the food set, or `None` for the nodes present that no reaction produces.

        frames:
            The frames of a trajectory to analyse, or `None` for every frame.

    Returns:
        result:
            The snapshots, and the reactions, products, size, and share of the largest RAF of every frame.

    Raises:
        AnalysisError:
            The source is neither a network snapshot nor a trajectory of a network whose hyperedges change.

    See Also:
        loops: Finds the feedback loops of a network.
        elementary_modes: Finds the pathways of a metabolism.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import autocatalytic_sets
        >>> from skcomplex.core.engine.problems import NetworkSnapshotSpec
        >>> edges, reactions = np.array([[3, 4, 0], [2, 3, 4]]), np.array([[0, 1, 2], [2, 0, 3], [3, 1, 4]])
        >>> autocatalytic_sets(NetworkSnapshotSpec(np.arange(5), *edges, np.arange(3), reactions)).reactions[0].tolist()
        [0, 1, 2]
    """
    if isinstance(source, NetworkSnapshotSpec):
        snapshots = [source]
    elif isinstance(source, Trajectory):
        chosen = range(len(source.times)) if frames is None else frames
        snapshots = [source.get_network(int(frame)) for frame in chosen]
    else:
        error_msg = f'Autocatalytic sets are read from a network snapshot or a trajectory, not {type(source).__name__}.'
        raise AnalysisError(error_msg)
    if any(snapshot.hyperedges is None for snapshot in snapshots):
        error_msg = (
            'Autocatalytic sets read the reactions as hyperedges that change. Give the network a variable group on '
            'its hyperedges.'
        )
        raise AnalysisError(error_msg)
    found = [_largest_raf(snapshot, food) for snapshot in snapshots]
    reactions = [rows for rows, _ in found]
    sizes = np.asarray([rows.size for rows in reactions], dtype=int)
    totals = np.asarray([len(_reactions_of(snapshot)) for snapshot in snapshots])
    fractions = np.divide(sizes, totals, out=np.zeros(len(totals)), where=totals > 0)
    return AutocatalyticSetsResult(
        snapshots,
        reactions,
        [products for _, products in found],
        sizes,
        fractions,
        sizes > 0,
    )

automaton(source, *, kind='injective', method='auto', window=None, infinite=False, tries=200, random_state=None, max_radius=2, second=None, configuration=None, site=0, steps=1, windows=None, base=2.0, sweeps=100)

Return a decision or a measure of a cellular automaton or subshift of a system.

An automaton is a group of cells on a grid with one rule that updates every cell at once from its neighbours, such as ElementaryAutomatonSystem(rule=170, size=8), which shifts every cell left. A subshift is a group whose value lists forbidden patterns. The function decides whether the rule loses information, finds a grid no grid leads to, builds the rule that undoes it, and counts or samples the allowed grids. Small grids are checked one by one and larger ones with a SAT solver. It tells whether a model of traffic, of crystal growth, or of a computer loses information, and reversible rules model physics that keeps energy.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system of the automaton or of the subshift.

required
kind str

What to decide or measure. 'injective', 'surjective', and 'pre-injective' ask whether no two grids share their next grid, whether every grid has a grid before it, and whether two grids that differ in a window never share their next grid. 'garden-of-eden' finds a pattern no grid leads to. 'inverse' finds the rule that undoes a reversible rule, trying radii up to max_radius. 'compose' applies the rule and then second. 'difference' shows where two runs differ when one cell of configuration at site changes. 'entropy' is log |X_F| / |F| of the allowed patterns of each window F. 'matrix' and 'polynomial' give a linear rule as a matrix or a Laurent polynomial. 'admissible' and 'violations' check configuration against the forbidden patterns. 'count' counts the allowed grids of a subshift and 'sample' draws one.

'injective'
method str

'enumeration', 'sat', or 'auto' to enumerate up to MAX_CONFIGURATIONS configurations.

'auto'
window Sequence[int] | None

The sites where configurations may differ, or of the Garden of Eden pattern, or None for every site.

None
infinite bool

Whether to decide a linear automaton on Z^d from its Laurent polynomial instead of on its space.

False
tries int

The number of random patterns tried by SAT.

200
random_state int | Generator | None

The seed or generator of the random patterns or of the moves of a sample.

None
max_radius int

The largest radius of the memory of the inverse.

2
second DataSource | None

The system of the automaton applied after the analysed one.

None
configuration ArrayLike | None

The values of the sites: the initial ones of the difference pattern or of a sample, or the ones checked.

None
site int

The site of the changed cell.

0
steps int

The number of steps of the difference pattern.

1
windows Sequence[BaseSpace] | None

The windows of the entropy, such as lattices with fixed edges of growing size.

None
base float

The base of the logarithm.

2.0
sweeps int

The number of sweeps of a sample, each proposing a random value at every site in a random order.

100

Returns:

Name Type Description
result AutomatonResult

The system and the decision or measure of the kind.

Raises:

Type Description
AnalysisError

The system holds nothing the kind reads, the method is unknown, enumeration is asked for too many configurations, composed automata differ in space or number of states, the rule returns a value outside the states, a linear automaton has a matrix on a ball or a polynomial without offsets, or the initial configuration of a sample is not admissible.

See Also

symbolic: Turns a series into symbols and measures their patterns.

Examples:

>>> from skcomplex.core.analysis import automaton
>>> from skcomplex.systems.computer_science.automata import ElementaryAutomatonSystem
>>> automaton(ElementaryAutomatonSystem(rule=30, size=8), kind='injective').injective
False
Source code in src/skcomplex/core/analysis/_automata.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def automaton(
    source: DataSource,
    *,
    kind: str = 'injective',
    method: str = 'auto',
    window: Sequence[int] | None = None,
    infinite: bool = False,
    tries: int = 200,
    random_state: int | np.random.Generator | None = None,
    max_radius: int = 2,
    second: DataSource | None = None,
    configuration: npt.ArrayLike | None = None,
    site: int = 0,
    steps: int = 1,
    windows: Sequence[BaseSpace] | None = None,
    base: float = 2.0,
    sweeps: int = 100,
) -> AutomatonResult:
    """Return a decision or a measure of a cellular automaton or subshift of a system.

    An automaton is a group of cells on a grid with one rule that updates every cell at once from its neighbours, such
    as `ElementaryAutomatonSystem(rule=170, size=8)`, which shifts every cell left. A subshift is a group whose value
    lists forbidden patterns. The function decides whether the rule loses information, finds a grid no grid leads to,
    builds the rule that undoes it, and counts or samples the allowed grids. Small grids are checked one by one and
    larger ones with a SAT solver. It tells whether a model of traffic, of crystal growth, or of a computer loses
    information, and reversible rules model physics that keeps energy.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system of the automaton or of the subshift.

        kind:
            What to decide or measure. `'injective'`, `'surjective'`, and `'pre-injective'` ask whether no two grids
            share their next grid, whether every grid has a grid before it, and whether two grids that differ in a
            window never share their next grid. `'garden-of-eden'` finds a pattern no grid leads to. `'inverse'` finds
            the rule that undoes a reversible rule, trying radii up to `max_radius`. `'compose'` applies the rule and
            then `second`. `'difference'` shows where two runs differ when one cell of `configuration` at `site`
            changes. `'entropy'` is `log |X_F| / |F|` of the allowed patterns of each window `F`. `'matrix'` and
            `'polynomial'` give a linear rule as a matrix or a Laurent polynomial. `'admissible'` and `'violations'`
            check `configuration` against the forbidden patterns. `'count'` counts the allowed grids of a subshift and
            `'sample'` draws one.

        method:
            `'enumeration'`, `'sat'`, or `'auto'` to enumerate up to `MAX_CONFIGURATIONS` configurations.

        window:
            The sites where configurations may differ, or of the Garden of Eden pattern, or `None` for every site.

        infinite:
            Whether to decide a linear automaton on `Z^d` from its Laurent polynomial instead of on its space.

        tries:
            The number of random patterns tried by SAT.

        random_state:
            The seed or generator of the random patterns or of the moves of a sample.

        max_radius:
            The largest radius of the memory of the inverse.

        second:
            The system of the automaton applied after the analysed one.

        configuration:
            The values of the sites: the initial ones of the difference pattern or of a sample, or the ones checked.

        site:
            The site of the changed cell.

        steps:
            The number of steps of the difference pattern.

        windows:
            The windows of the entropy, such as lattices with fixed edges of growing size.

        base:
            The base of the logarithm.

        sweeps:
            The number of sweeps of a sample, each proposing a random value at every site in a random order.

    Returns:
        result:
            The system and the decision or measure of the kind.

    Raises:
        AnalysisError:
            The system holds nothing the kind reads, the method is unknown, enumeration is asked for too many
            configurations, composed automata differ in space or number of states, the rule returns a value outside the
            states, a linear automaton has a matrix on a ball or a polynomial without offsets, or the initial
            configuration of a sample is not admissible.

    See Also:
        symbolic: Turns a series into symbols and measures their patterns.

    Examples:
        >>> from skcomplex.core.analysis import automaton
        >>> from skcomplex.systems.computer_science.automata import ElementaryAutomatonSystem
        >>> automaton(ElementaryAutomatonSystem(rule=30, size=8), kind='injective').injective
        False
    """
    system = _get_system(source)
    source = _get_declared(system)
    second_system = None if second is None else _get_system(second)
    second = None if second_system is None else _get_second(second_system)
    _check_choice('automaton', 'kind', kind, KINDS)
    _check_settings(
        automaton,
        'kind',
        SETTINGS[kind],
        kind=kind,
        method=method,
        window=window,
        infinite=infinite,
        tries=tries,
        random_state=random_state,
        max_radius=max_radius,
        second=second,
        configuration=configuration,
        site=site,
        steps=steps,
        windows=windows,
        base=base,
        sweeps=sweeps,
    )
    if method not in METHODS:
        error_msg = f'automaton has method={method!r}. Use one of {", ".join(METHODS)}.'
        raise AnalysisError(error_msg)
    needed = {
        'compose': ('second', second),
        'difference': ('configuration', configuration),
        'entropy': ('windows', windows),
        'admissible': ('configuration', configuration),
        'violations': ('configuration', configuration),
    }.get(kind)
    if needed is not None and needed[1] is None:
        error_msg = f'automaton of kind {kind!r} needs {needed[0]}. Give it.'
        raise AnalysisError(error_msg)
    sources = SOURCES[kind]
    error_msg = (
        f'automaton of kind {kind!r} reads a system with {" or ".join(sources)}, not {type(source).__name__}. Build '
        'one of them.'
    )
    if not isinstance(system, System) or not isinstance(source, _CompositeSystem):
        raise AnalysisError(error_msg)
    found = _find_subshift(source)
    rule = _find_rule(source)
    if found is not None and SUBSHIFT in sources:
        result = _run_subshift(
            source,
            kind,
            found[1],
            _get_space(source, found[0]),
            configuration=configuration,
            windows=windows,
            base=base,
            sweeps=sweeps,
            random_state=random_state,
        )
        return replace(result, automaton=system)
    if rule is None or _get_rule_source(rule) not in sources:
        raise AnalysisError(error_msg)
    read = _read_automaton(source, rule)
    if kind in {'injective', 'surjective', 'pre-injective'}:
        result = _decide(read, kind, method=method, window=window, infinite=infinite)
    elif kind in {'compose', 'difference'}:
        result = _run_pair(read, kind, system, second=second, configuration=configuration, site=site, steps=steps)
    else:
        result = _measure(
            read,
            kind,
            system,
            window=window,
            tries=tries,
            random_state=random_state,
            max_radius=max_radius,
            windows=windows,
            base=base,
        )
    return replace(result, automaton=system)

bind_analysis(analysis, **settings)

Return an analysis with fixed settings, in the role of make_scorer.

It fixes the settings of an analysis so the result takes the source alone, such as bind_analysis(rolling, kind='variance', window=3), which an experiment applies to every run and names after the function. The bound analysis keeps the function in func and the settings in keywords, so it travels to other processes. It measures the variance before the collapse of a fishery, the entropy of every run of a market, and the peak of every run of an epidemic.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
analysis Callable[..., ResultT]

The analysis function, such as entropy.

required
**settings object

The settings of the analysis by name, as its keyword arguments take them.

{}

Returns:

Name Type Description
bound partial[ResultT]

The callable that applies the analysis with the settings to a source and returns its result.

Raises:

Type Description
AnalysisError

The analysis is not callable, or it takes no setting of a given name.

See Also

sweep: Runs a system over values and applies bound analyses to every run.

Examples:

>>> from skcomplex.core.analysis import bind_analysis, rolling
>>> variance = bind_analysis(rolling, kind='variance', window=3)
>>> variance([0.0, 1.0, 0.0, 1.0]).statistic.round(2).tolist()
[[nan, nan, 0.22, 0.22]]
Source code in src/skcomplex/core/analysis/_base.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def bind_analysis[ResultT](analysis: Callable[..., ResultT], **settings: object) -> partial[ResultT]:
    """Return an analysis with fixed settings, in the role of `make_scorer`.

    It fixes the settings of an analysis so the result takes the source alone, such as
    `bind_analysis(rolling, kind='variance', window=3)`, which an experiment applies to every run and names after the
    function. The bound analysis keeps the function in `func` and the settings in `keywords`, so it travels to other
    processes. It measures the variance before the collapse of a fishery, the entropy of every run of a market, and the
    peak of every run of an epidemic.

    Read more in the user guide, under Analyse.

    Args:
        analysis:
            The analysis function, such as `entropy`.

        **settings:
            The settings of the analysis by name, as its keyword arguments take them.

    Returns:
        bound:
            The callable that applies the analysis with the settings to a source and returns its result.

    Raises:
        AnalysisError:
            The analysis is not callable, or it takes no setting of a given name.

    See Also:
        sweep: Runs a system over values and applies bound analyses to every run.

    Examples:
        >>> from skcomplex.core.analysis import bind_analysis, rolling
        >>> variance = bind_analysis(rolling, kind='variance', window=3)
        >>> variance([0.0, 1.0, 0.0, 1.0]).statistic.round(2).tolist()
        [[nan, nan, 0.22, 0.22]]
    """
    if not callable(analysis):
        error_msg = f'An analysis is a function of a source, not {analysis!r}.'
        raise AnalysisError(error_msg)
    try:
        inspect.signature(analysis).bind_partial(None, **settings)
    except TypeError as error:
        error_msg = f'{getattr(analysis, "__name__", analysis)!r} does not take these settings: {error}.'
        raise AnalysisError(error_msg) from error
    return partial(analysis, **settings)

cell_complex(source, *, kind, space=None, variables=None)

Return the split of a flow, the holes, or the curved faces of a complex.

It reads a value on the links of a CellComplexSpace from a trajectory, or an array with the complex passed as space, one row per frame. The kind 'hodge' splits a flow on links into a flow that runs downhill from site to site, a flow that circulates around faces, and a flow that does neither, three flows at right angles. The kind 'betti' counts the pieces, loops, and hollows of the complex, and 'curvature' finds the faces around which an angle winds a whole turn. It splits the flows of a network, counts the holes of a pattern, and finds the vortices of a gauge field.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array of values on the edges, or None for the kind 'betti' with a space.

required
kind str

'hodge', 'betti', or 'curvature'.

required
space CellComplexSpace | None

The cell complex, or None for the complex of the group of variables on a trajectory.

None
variables str | None

The dotted name of the state of a trajectory, or None for a source that is an array.

None

Returns:

Name Type Description
result CellComplexResult

The complex, the values, and the results of the kind.

Raises:

Type Description
AnalysisError

The kind is unknown, the source names no state of a cell complex, or the values do not fit the complex.

See Also

network_measures: Measures the structure of a graph.

Examples:

>>> from skcomplex.core.analysis import cell_complex
>>> from skcomplex.core.components.spaces import CellComplexSpace, LatticeSpace
>>> space = CellComplexSpace(LatticeSpace((4, 4))).prepare()
>>> cell_complex(None, kind='betti', space=space).betti
(1, 2, 1)
Source code in src/skcomplex/core/analysis/_cell_complex.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def cell_complex(
    source: DataSource,
    *,
    kind: str,
    space: CellComplexSpace | None = None,
    variables: str | None = None,
) -> CellComplexResult:
    """Return the split of a flow, the holes, or the curved faces of a complex.

    It reads a value on the links of a `CellComplexSpace` from a trajectory, or an array with the complex passed as
    `space`, one row per frame. The kind `'hodge'` splits a flow on links into a flow that runs downhill from site to
    site, a flow that circulates around faces, and a flow that does neither, three flows at right angles. The kind
    `'betti'` counts the pieces, loops, and hollows of the complex, and `'curvature'` finds the faces around which an
    angle winds a whole turn. It splits the flows of a network, counts the holes of a pattern, and finds the vortices of
    a gauge field.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array of values on the edges, or `None` for the kind `'betti'` with a `space`.

        kind:
            `'hodge'`, `'betti'`, or `'curvature'`.

        space:
            The cell complex, or `None` for the complex of the group of `variables` on a trajectory.

        variables:
            The dotted name of the state of a trajectory, or `None` for a source that is an array.

    Returns:
        result:
            The complex, the values, and the results of the kind.

    Raises:
        AnalysisError:
            The kind is unknown, the source names no state of a cell complex, or the values do not fit the complex.

    See Also:
        network_measures: Measures the structure of a graph.

    Examples:
        >>> from skcomplex.core.analysis import cell_complex
        >>> from skcomplex.core.components.spaces import CellComplexSpace, LatticeSpace
        >>> space = CellComplexSpace(LatticeSpace((4, 4))).prepare()
        >>> cell_complex(None, kind='betti', space=space).betti
        (1, 2, 1)
    """
    _check_choice('cell_complex', 'kind', kind, KINDS)
    if space is not None and not isinstance(space, CellComplexSpace):
        error_msg = f'cell_complex reads a CellComplexSpace, not {space!r}.'
        raise AnalysisError(error_msg)
    values, period = (np.empty((0, 0)), DEFAULT_PERIOD) if source is None else _read_values(source, variables)
    found = _space_of(source, variables) if space is None and isinstance(source, Trajectory) else space
    if found is None:
        error_msg = 'cell_complex reads no complex. Give `space`, or the state of a group on a cell complex.'
        raise AnalysisError(error_msg)
    complex_space = found.prepare()
    if kind != 'betti' and values.shape[-1] != complex_space.incidences_[0].shape[0]:
        error_msg = (
            f'cell_complex reads {values.shape[-1]} values, but the complex has '
            f'{complex_space.incidences_[0].shape[0]} edges. Read a state of a group on its edges.'
        )
        raise AnalysisError(error_msg)
    if kind == 'hodge':
        return _hodge(complex_space, values, period)
    if kind == 'betti':
        return _betti(complex_space, values, period)
    return _curvature(complex_space, values, period)

chain_shape(source, *, kind='gyration', group=None, reference=None)

Return the geometry of a chain of points per frame.

The chain is made of the positions of the members of a group in member order, and every frame gives one value of its size or shape, such as the distance 5 between the ends of a chain from (0, 0) to (3, 4). It measures the size of a polymer, the end to end distance of a strand of DNA, and how far a folding protein lies from its native shape.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of frames by points by dimensions.

required
kind str

'gyration' for the radius of gyration, 'end-to-end' for the distance between the first and the last point, or 'rmsd' for the root mean square deviation from reference after optimal superposition.

'gyration'
group str | None

The path of an agent or particle group of a trajectory, or the dotted name of a lattice state whose last axis holds the coordinates of a point, or None for the first agent or particle group.

None
reference ArrayLike | None

The positions the deviation compares with, points by dimensions, for the kind 'rmsd'.

None

Returns:

Name Type Description
result ChainShapeResult

The positions and the value of every frame.

Raises:

Type Description
AnalysisError

The kind is unknown, the kind 'rmsd' has no reference, or the positions are not frames by points by dimensions.

See Also

displacement: Gives the mean squared distance particles travel over every lag. neighbors: Gives the neighbours of agents, grid cells, or network nodes.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import chain_shape
>>> chain = np.array([[[0.0, 0.0], [3.0, 4.0]]])
>>> chain_shape(chain, kind='end-to-end').values.tolist()
[5.0]
Source code in src/skcomplex/core/analysis/_shape.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def chain_shape(
    source: DataSource,
    *,
    kind: str = 'gyration',
    group: str | None = None,
    reference: npt.ArrayLike | None = None,
) -> ChainShapeResult:
    """Return the geometry of a chain of points per frame.

    The chain is made of the positions of the members of a group in member order, and every frame gives one value of
    its size or shape, such as the distance 5 between the ends of a chain from `(0, 0)` to `(3, 4)`. It measures the
    size of a polymer, the end to end distance of a strand of DNA, and how far a folding protein lies from its native
    shape.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of frames by points by dimensions.

        kind:
            `'gyration'` for the radius of gyration, `'end-to-end'` for the distance between the first and the last
            point, or `'rmsd'` for the root mean square deviation from `reference` after optimal superposition.

        group:
            The path of an agent or particle group of a trajectory, or the dotted name of a lattice state whose last
            axis holds the coordinates of a point, or `None` for the first agent or particle group.

        reference:
            The positions the deviation compares with, points by dimensions, for the kind `'rmsd'`.

    Returns:
        result:
            The positions and the value of every frame.

    Raises:
        AnalysisError:
            The kind is unknown, the kind `'rmsd'` has no reference, or the positions are not frames by points by
            dimensions.

    See Also:
        displacement: Gives the mean squared distance particles travel over every lag.
        neighbors: Gives the neighbours of agents, grid cells, or network nodes.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import chain_shape
        >>> chain = np.array([[[0.0, 0.0], [3.0, 4.0]]])
        >>> chain_shape(chain, kind='end-to-end').values.tolist()
        [5.0]
    """
    _check_choice('chain_shape', 'kind', kind, SHAPE_KINDS)
    if kind == 'rmsd' and reference is None:
        error_msg = "chain_shape(kind='rmsd') compares with a reference. Pass `reference`."
        raise AnalysisError(error_msg)
    read = _read_positions(source, group) if isinstance(source, Trajectory) else source
    positions: Array = np.asarray(read, dtype=float)
    if positions.ndim != FRAME_DIMENSIONS:
        error_msg = f'chain_shape reads frames by points by dimensions, not the shape {positions.shape}.'
        raise AnalysisError(error_msg)
    centred = positions - positions.mean(axis=1, keepdims=True)
    if kind == 'gyration':
        values = np.sqrt(np.mean(np.sum(centred**2, axis=2), axis=1))
    elif kind == 'end-to-end':
        values = np.linalg.norm(positions[:, -1] - positions[:, 0], axis=1)
    else:
        target = np.asarray(reference, dtype=float)
        target = target - target.mean(axis=0)
        values = np.array([_deviation(frame, target) for frame in centred])
    return ChainShapeResult(positions, values)

clusters(source, *, kind='labels', variables=None, periodic=False, diagonal=False, axis=0, radius=None)

Return the clusters of a grid, a graph, or points.

A cluster is a set of occupied cells of a grid that touch through faces, or corners with diagonal=True, the connected nodes of a graph, or points closer than twice radius, such as the clusters of sizes 2 and 1 in [[1, 1, 0], [0, 0, 1]]. A trajectory gives its last field, network, or positions. A cluster spans when it joins two opposite edges along axis. It finds the path of water through a porous rock, the burnt patches of a forest fire, and the groups of an opinion model.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The grid or the grids, the graph, the points, or the trajectory.

required
kind str

What to return. 'labels' gives the label of every cell, the size of every cluster in label order, and whether a cluster spans. 'sizes' gives the sizes, largest first. 'percolation' gives the sizes, the share of the largest cluster, the mean size, and spanning. 'spanning' gives the share of the grids of an ensemble, stacked on the first axis, with a spanning cluster.

'labels'
variables Sequence[str] | None

The field of a trajectory to read, or None for its first field.

None
periodic bool

Whether clusters of a grid wrap around its edges.

False
diagonal bool

Whether cells that share only a corner are connected.

False
axis int

The axis whose two opposite edges a spanning cluster joins.

0
radius float | None

The contact radius of points, or None for grids and graphs.

None

Returns:

Name Type Description
result ClustersResult

What the source was read as, and the measures of the kind.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, the radius is not positive or comes with settings of grids, or a kind that reads grids gets a graph.

See Also

domains: Finds the regions of equal value of a field. defects: Finds the defects of a field of angles.

Examples:

>>> from skcomplex.core.analysis import clusters
>>> result = clusters([[1, 1, 0], [1, 0, 1]], kind='percolation')
>>> result.strength, result.mean_size, result.spanning
(0.5, 1.0, True)
Source code in src/skcomplex/core/analysis/_clusters.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def clusters(
    source: DataSource,
    *,
    kind: str = 'labels',
    variables: Sequence[str] | None = None,
    periodic: bool = False,
    diagonal: bool = False,
    axis: int = 0,
    radius: float | None = None,
) -> ClustersResult:
    """Return the clusters of a grid, a graph, or points.

    A cluster is a set of occupied cells of a grid that touch through faces, or corners with `diagonal=True`, the
    connected nodes of a graph, or points closer than twice `radius`, such as the clusters of sizes 2 and 1 in
    `[[1, 1, 0], [0, 0, 1]]`. A trajectory gives its last field, network, or positions. A cluster spans when it joins
    two opposite edges along `axis`. It finds the path of water through a porous rock, the burnt patches of a forest
    fire, and the groups of an opinion model.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The grid or the grids, the graph, the points, or the trajectory.

        kind:
            What to return. `'labels'` gives the label of every cell, the size of every cluster in label order, and
            whether a cluster spans. `'sizes'` gives the sizes, largest first. `'percolation'` gives the sizes, the
            share of the largest cluster, the mean size, and spanning. `'spanning'` gives the share of the grids of an
            ensemble, stacked on the first axis, with a spanning cluster.

        variables:
            The field of a trajectory to read, or `None` for its first field.

        periodic:
            Whether clusters of a grid wrap around its edges.

        diagonal:
            Whether cells that share only a corner are connected.

        axis:
            The axis whose two opposite edges a spanning cluster joins.

        radius:
            The contact radius of points, or `None` for grids and graphs.

    Returns:
        result:
            What the source was read as, and the measures of the kind.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, the radius is not positive or comes with
            settings of grids, or a kind that reads grids gets a graph.

    See Also:
        domains: Finds the regions of equal value of a field.
        defects: Finds the defects of a field of angles.

    Examples:
        >>> from skcomplex.core.analysis import clusters
        >>> result = clusters([[1, 1, 0], [1, 0, 1]], kind='percolation')
        >>> result.strength, result.mean_size, result.spanning
        (0.5, 1.0, True)
    """
    _check_choice('clusters', 'kind', kind, KINDS)
    _check_settings(
        clusters,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        periodic=periodic,
        diagonal=diagonal,
        axis=axis,
        radius=radius,
    )
    if radius is not None:
        if radius <= 0 or periodic or diagonal:
            error_msg = (
                f'clusters has radius={radius!r}, periodic={periodic!r}, and diagonal={diagonal!r}. A radius is '
                'positive, and points take neither of the settings of grids.'
            )
            raise AnalysisError(error_msg)
        points, faces = _read_points(source, kind, variables)
        return _of_points(points, faces, kind, axis, radius)
    if isinstance(source, nx.Graph):
        if kind in {'labels', 'spanning'}:
            error_msg = f'clusters of kind {kind!r} reads grids, not graphs. Use the kind sizes or percolation.'
            raise AnalysisError(error_msg)
        return _of_graph(source, kind)
    name = variables[0] if variables else None
    read = np.asarray(_read_fields(source, name), dtype=bool)
    if kind == 'spanning':
        spans = [_spans(_label(grid, periodic=False, diagonal=diagonal)[0], axis) for grid in read]
        return ClustersResult(grids=read, probability=float(np.mean(spans)))
    grids = read[-1:] if isinstance(source, Trajectory) else read[None]
    if kind == 'labels':
        labels, sizes = _label(grids[0], periodic=periodic, diagonal=diagonal)
        return ClustersResult(grids=grids, labels=labels, sizes=sizes, spanning=_spans(labels, axis))
    if kind == 'sizes':
        _, sizes = _label(grids[0], periodic=periodic, diagonal=diagonal)
        return ClustersResult(grids=grids, sizes=np.sort(sizes)[::-1])
    labels, sizes = _label(grids[0], periodic=False, diagonal=diagonal)
    ordered = np.sort(sizes)[::-1]
    strength, mean_size = _strength(ordered, grids[0].size)
    return ClustersResult(
        grids=grids,
        sizes=ordered,
        strength=strength,
        mean_size=mean_size,
        spanning=_spans(labels, axis),
    )

coarse_grain(source, *, shape=(32, 32), box=None, values=None, over=None, state=None)

Return agents counted on a grid, or members spread over the values of a state.

It counts the agents in every cell of a grid of shape over the box, one grid per frame, such as two agents in one corner and one in the other of a box of side 1. With over, it counts every member at the given value nearest to its own instead, and returns the share at every value. An array holds one snapshot, one row per agent, and a trajectory gives the first group at every frame. It turns animals into the density of a herd, traders into the spread of wealth, and particles into the density of a fluid.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of positions or of values of a state.

required
shape Sequence[int]

The number of cells along every side.

(32, 32)
box Sequence[float] | None

The sides of the box, or None for the box of the space of a trajectory.

None
values ArrayLike | None

One value or one row of values per agent of an array, such as unit directions for a polarization field, or None to count agents.

None
over ArrayLike | None

The increasing values of a state to coarse-grain the members over, or None to coarse-grain positions.

None
state str | None

The dotted name of the state whose values a trajectory gives, such as traders.wealth, with over.

None

Returns:

Name Type Description
result CoarseGrainResult

The positions or values, the box, and the field.

Raises:

Type Description
AnalysisError

A setting is invalid or missing, or the source holds no positions or values to coarse-grain.

See Also

distribution: Fits and tests the distribution of values. clusters: Finds the clusters of a grid.

Examples:

>>> from skcomplex.core.analysis import coarse_grain
>>> positions = [[0.1, 0.1], [0.2, 0.1], [0.9, 0.9]]
>>> coarse_grain(positions, shape=[2, 2], box=[1.0, 1.0]).field.tolist()
[[2.0, 0.0], [0.0, 1.0]]
Source code in src/skcomplex/core/analysis/_coarse_grain.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def coarse_grain(
    source: DataSource,
    *,
    shape: Sequence[int] = (32, 32),
    box: Sequence[float] | None = None,
    values: npt.ArrayLike | None = None,
    over: npt.ArrayLike | None = None,
    state: str | None = None,
) -> CoarseGrainResult:
    """Return agents counted on a grid, or members spread over the values of a state.

    It counts the agents in every cell of a grid of `shape` over the box, one grid per frame, such as two agents in one
    corner and one in the other of a box of side 1. With `over`, it counts every member at the given value nearest to
    its own instead, and returns the share at every value. An array holds one snapshot, one row per agent, and a
    trajectory gives the first group at every frame. It turns animals into the density of a herd, traders into the
    spread of wealth, and particles into the density of a fluid.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of positions or of values of a state.

        shape:
            The number of cells along every side.

        box:
            The sides of the box, or `None` for the box of the space of a trajectory.

        values:
            One value or one row of values per agent of an array, such as unit directions for a polarization field, or
            `None` to count agents.

        over:
            The increasing values of a state to coarse-grain the members over, or `None` to coarse-grain positions.

        state:
            The dotted name of the state whose values a trajectory gives, such as `traders.wealth`, with `over`.

    Returns:
        result:
            The positions or values, the box, and the field.

    Raises:
        AnalysisError:
            A setting is invalid or missing, or the source holds no positions or values to coarse-grain.

    See Also:
        distribution: Fits and tests the distribution of values.
        clusters: Finds the clusters of a grid.

    Examples:
        >>> from skcomplex.core.analysis import coarse_grain
        >>> positions = [[0.1, 0.1], [0.2, 0.1], [0.9, 0.9]]
        >>> coarse_grain(positions, shape=[2, 2], box=[1.0, 1.0]).field.tolist()
        [[2.0, 0.0], [0.0, 1.0]]
    """
    _check(shape, box, values, over, state)
    if over is not None:
        positions = _read_state(source, state)
        grid = np.asarray(over, dtype=float)
        frames = positions if positions.ndim == SNAPSHOT_DIMENSIONS else positions[None]
        densities = np.asarray([_get_density(row, grid) for row in frames])
        return CoarseGrainResult(positions, None, densities if positions.ndim == SNAPSHOT_DIMENSIONS else densities[0])
    if isinstance(source, Trajectory):
        snapshots = _read_snapshots(source)
        if snapshots.positions is None:
            error_msg = 'The agents of the trajectory have no positions with coordinates to coarse-grain.'
            raise AnalysisError(error_msg)
        positions = snapshots.positions
        sides = box if box is not None else snapshots.box
    else:
        positions = np.asarray(source, dtype=float)
        sides = box
    if sides is None:
        error_msg = 'coarse_grain needs the sides of the box. Set `box`.'
        raise AnalysisError(error_msg)
    read_box = np.asarray(sides, dtype=np.float64)
    if len(shape) != read_box.size:
        error_msg = f'The shape {tuple(shape)} needs one entry per dimension of the box, {read_box.size}.'
        raise AnalysisError(error_msg)
    if positions.ndim > SNAPSHOT_DIMENSIONS:
        field = np.asarray([_get_field(frame, shape, read_box, values) for frame in positions])
    else:
        field = _get_field(positions, shape, read_box, values)
    return CoarseGrainResult(positions, read_box, field)

complexity(source, *, variables=None, dimension=6, delay=1, ties='order', random_state=None)

Return the place of series on Rosso's complexity and entropy plane.

It turns every series, or every frame of a field, into the order patterns of its values and measures how even the patterns are, the entropy, and how far they are from even, times the entropy, the complexity, with ordpy. Noise has an entropy near 1 and a complexity near 0, a regular series both near 0, and chaos lies between with a high complexity. It tells chaos from noise in heart beats, climate records, and the prices of a market.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array with one row per time and one column per series, or the frames of a field.

required
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series, or the first field for a field.

None
dimension int | tuple[int, int]

The length of the patterns of a series, or the window (columns, rows) of the patterns of a field.

6
delay int

The number of steps between the values of a pattern.

1
ties str

'order' to rank equal values by position, or 'random' to rank them at random.

'order'
random_state int | None

The seed of the random ranks of equal values.

None

Returns:

Name Type Description
result ComplexityResult

The values read, the place of every series or frame on the plane, and the bounds of the plane.

Raises:

Type Description
AnalysisError

The ties are unknown, or the pattern length, the window, or the delay is below 1.

See Also

entropy: Measures the entropy of a series. lyapunov: Measures how fast nearby runs drift apart.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import complexity
>>> plane = complexity(np.random.default_rng(0).standard_normal(50_000), dimension=4)
>>> plane.entropy.round(2).tolist(), plane.complexity.round(2).tolist()
([1.0], [0.0])
Source code in src/skcomplex/core/analysis/_complexity.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def complexity(
    source: DataSource,
    *,
    variables: Sequence[str] | None = None,
    dimension: int | tuple[int, int] = 6,
    delay: int = 1,
    ties: str = 'order',
    random_state: int | None = None,
) -> ComplexityResult:
    """Return the place of series on Rosso's complexity and entropy plane.

    It turns every series, or every frame of a field, into the order patterns of its values and measures how even the
    patterns are, the entropy, and how far they are from even, times the entropy, the complexity, with `ordpy`. Noise
    has an entropy near 1 and a complexity near 0, a regular series both near 0, and chaos lies between with a high
    complexity. It tells chaos from noise in heart beats, climate records, and the prices of a market.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array with one row per time and one column per series, or the frames of a field.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series, or the first field for a field.

        dimension:
            The length of the patterns of a series, or the window `(columns, rows)` of the patterns of a field.

        delay:
            The number of steps between the values of a pattern.

        ties:
            `'order'` to rank equal values by position, or `'random'` to rank them at random.

        random_state:
            The seed of the random ranks of equal values.

    Returns:
        result:
            The values read, the place of every series or frame on the plane, and the bounds of the plane.

    Raises:
        AnalysisError:
            The ties are unknown, or the pattern length, the window, or the delay is below 1.

    See Also:
        entropy: Measures the entropy of a series.
        lyapunov: Measures how fast nearby runs drift apart.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import complexity
        >>> plane = complexity(np.random.default_rng(0).standard_normal(50_000), dimension=4)
        >>> plane.entropy.round(2).tolist(), plane.complexity.round(2).tolist()
        ([1.0], [0.0])
    """
    if ties not in TieKind:
        error_msg = f'complexity has ties={ties!r}. Use one of {", ".join(TieKind)}.'
        raise AnalysisError(error_msg)
    sizes = dimension if isinstance(dimension, tuple) else (dimension,)
    if any(int(size) < 1 for size in sizes) or delay < 1:
        error_msg = f'complexity has dimension={dimension!r} and delay={delay!r}. Use 1 or more.'
        raise AnalysisError(error_msg)
    if isinstance(dimension, tuple):
        name = variables[0] if variables else None
        frames = _read_fields(source, name)
        values = frames[None] if frames.ndim == SNAPSHOT_DIMENSIONS else frames
        labels = [name or 'field']
        items = list(values)
    else:
        series = _read_series(source, variables)
        values, labels = series.values, series.labels
        items = list(values.T)
    dx, dy = (dimension, 1) if isinstance(dimension, int) else dimension
    places = [
        ordpy.complexity_entropy(_break_ties(item, ties, random_state), dx=dx, dy=dy, taux=delay, tauy=delay)
        for item in items
    ]
    return ComplexityResult(
        values,
        labels,
        np.asarray([entropy for entropy, _ in places], dtype=float),
        np.asarray([measure for _, measure in places], dtype=float),
        np.asarray(ordpy.minimum_complexity_entropy(dx=dx, dy=dy), dtype=float),
        np.asarray(ordpy.maximum_complexity_entropy(dx=dx, dy=dy), dtype=float),
    )

correlation(source, *, kind='auto', variables=None, max_lag=None, dt=None, waiting=None, lags=None, connected=False, max_distance=None, method='moment', spacing=1.0, frames=False)

Return the correlation of series, of an ensemble at two times, or of a field.

A correlation says how much a value at one time or place moves with the value at another, from 1 for together to -1 for opposite, such as -0.75 at lag 1 for a series that flips sign at every step. It reads series for the correlation over time, an ensemble of runs for the correlation between two times, and a field for the correlation over distance and how far it reaches. It finds how long a stock price remembers its past, how far order reaches in a magnet, and how two regions of the brain move together.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array of series, an ensemble, a field, or a pair of replicas for 'overlap'.

required
kind str

'auto' gives the correlation of every series with itself at lags 0 to max_lag, with the FFT, and the correlation time dt (1/2 + sum r(k)) up to the first negative value. 'two-time' gives C(t_w + tau, t_w) = <x(t_w) x(t_w + tau)> of an ensemble, one row per run and one column per frame. 'function' gives the correlation of a periodic field averaged over directions, 1 at distance 0. 'length' gives how far the correlation of a field reaches, by the 'moment' fit of the Ornstein-Zernike form or the 'fit' of C(r) ~ r^-a exp(-r / xi). 'overlap' gives q = <s_i t_i> of two configurations of the same sites, 1 for equal and near 0 for unrelated ones. The field kinds read the last frame of a trajectory, or every frame when frames is true.

'auto'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series, or the first field for a field.

None
max_lag int | None

The largest lag in steps, or None for half the series length.

None
dt float | None

The time between the samples of an array, or None for 1. A trajectory gives its own step.

None
waiting Sequence[int] | None

The waiting times t_w in frames.

None
lags Sequence[int] | None

The lags tau in frames.

None
connected bool

Whether to subtract the product of the means at the two times.

False
max_distance int | None

The largest distance in cells, or None for half the smallest side.

None
method str

The method of the correlation length, 'moment' or 'fit'.

'moment'
spacing float

The distance between neighbouring sites.

1.0
frames bool

Whether the first axis of an array indexes frames, and whether to read every frame of a trajectory.

False

Returns:

Name Type Description
result CorrelationResult

The data read and its correlation.

Raises:

Type Description
AnalysisError

The kind or method is unknown, a setting the kind does not read is changed, a setting the kind needs is missing, a setting is not positive, or dt differs from the step of a trajectory.

See Also

spectrum: Finds the frequencies of a series. information: Measures shared information between series.

Examples:

>>> from skcomplex.core.analysis import correlation
>>> correlation([[1, -1, 1, 1], [1, -1, -1, 1]], kind='overlap').overlap
0.5
Source code in src/skcomplex/core/analysis/_correlation.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def correlation(
    source: DataSource,
    *,
    kind: str = 'auto',
    variables: Sequence[str] | None = None,
    max_lag: int | None = None,
    dt: float | None = None,
    waiting: Sequence[int] | None = None,
    lags: Sequence[int] | None = None,
    connected: bool = False,
    max_distance: int | None = None,
    method: str = 'moment',
    spacing: float = 1.0,
    frames: bool = False,
) -> CorrelationResult:
    """Return the correlation of series, of an ensemble at two times, or of a field.

    A correlation says how much a value at one time or place moves with the value at another, from 1 for together to -1
    for opposite, such as `-0.75` at lag 1 for a series that flips sign at every step. It reads series for the
    correlation over time, an ensemble of runs for the correlation between two times, and a field for the correlation
    over distance and how far it reaches. It finds how long a stock price remembers its past, how far order reaches in a
    magnet, and how two regions of the brain move together.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array of series, an ensemble, a field, or a pair of replicas for `'overlap'`.

        kind:
            `'auto'` gives the correlation of every series with itself at lags 0 to `max_lag`, with the FFT, and the
            correlation time `dt (1/2 + sum r(k))` up to the first negative value. `'two-time'` gives
            `C(t_w + tau, t_w) = <x(t_w) x(t_w + tau)>` of an ensemble, one row per run and one column per frame.
            `'function'` gives the correlation of a periodic field averaged over directions, 1 at distance 0. `'length'`
            gives how far the correlation of a field reaches, by the `'moment'` fit of the Ornstein-Zernike form or the
            `'fit'` of `C(r) ~ r^-a exp(-r / xi)`. `'overlap'` gives `q = <s_i t_i>` of two configurations of the same
            sites, 1 for equal and near 0 for unrelated ones. The field kinds read the last frame of a trajectory, or
            every frame when `frames` is true.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series, or the first field for a field.

        max_lag:
            The largest lag in steps, or `None` for half the series length.

        dt:
            The time between the samples of an array, or `None` for 1. A trajectory gives its own step.

        waiting:
            The waiting times `t_w` in frames.

        lags:
            The lags `tau` in frames.

        connected:
            Whether to subtract the product of the means at the two times.

        max_distance:
            The largest distance in cells, or `None` for half the smallest side.

        method:
            The method of the correlation length, `'moment'` or `'fit'`.

        spacing:
            The distance between neighbouring sites.

        frames:
            Whether the first axis of an array indexes frames, and whether to read every frame of a trajectory.

    Returns:
        result:
            The data read and its correlation.

    Raises:
        AnalysisError:
            The kind or method is unknown, a setting the kind does not read is changed, a setting the kind needs is
            missing, a setting is not positive, or `dt` differs from the step of a trajectory.

    See Also:
        spectrum: Finds the frequencies of a series.
        information: Measures shared information between series.

    Examples:
        >>> from skcomplex.core.analysis import correlation
        >>> correlation([[1, -1, 1, 1], [1, -1, -1, 1]], kind='overlap').overlap
        0.5
    """
    _check_choice('correlation', 'kind', kind, KINDS)
    _check_choice('correlation', 'method', method, METHODS)
    _check_settings(
        correlation,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        max_lag=max_lag,
        dt=dt,
        waiting=waiting,
        lags=lags,
        connected=connected,
        max_distance=max_distance,
        method=method,
        spacing=spacing,
        frames=frames,
    )
    if kind == 'two-time' and (waiting is None or lags is None):
        error_msg = 'correlation of kind two-time needs waiting times and lags. Give both in frames.'
        raise AnalysisError(error_msg)
    if (dt is not None and dt <= 0) or spacing <= 0:
        error_msg = f'correlation has dt={dt!r} and spacing={spacing!r}. Use positive values.'
        raise AnalysisError(error_msg)
    if kind == 'auto':
        series = _read_series(source, variables)
        step = _read_step(source, series, dt)
        values = series.values
        autocorrelation = np.asarray([_autocorrelation(column, max_lag) for column in values.T])
        return CorrelationResult(
            values,
            series.labels,
            lags=np.asarray(np.arange(autocorrelation.shape[1]) * step, dtype=float),
            correlation=autocorrelation,
            time=np.asarray([_autocorrelation_time(column, step) for column in values.T]),
        )
    name = variables[0] if variables else None
    if kind == 'two-time' and waiting is not None and lags is not None:
        ensemble = np.asarray(source, dtype=float)
        two_time = _two_time_correlation(ensemble, waiting, lags, connected=connected)
        return CorrelationResult(ensemble, [name or 'ensemble'], correlation=two_time)
    if kind == 'overlap':
        replicas = _read_replicas(source, name)
        product = replicas[0] * replicas[1]
        overlap = float(product.mean()) if product.ndim == 1 else product.reshape(product.shape[0], -1).mean(axis=1)
        return CorrelationResult(replicas, ['first', 'second'], overlap=overlap)
    field = _read_fields(source, name)
    if isinstance(source, Trajectory) and not frames:
        field = field[-1]
    labels = [name or 'field']
    if kind == 'function':
        distances, curve = _correlation_function(field, max_distance)
        return CorrelationResult(field, labels, correlation=curve, distances=distances)
    grids = field if frames else field[None]
    return CorrelationResult(field, labels, length=_correlation_length(grids, method, spacing))

data_collapse(source, *, kind='scaling', parameters=None, critical=None, nu=None, exponent=0.0, fit=(), waiting=None, lags=None, ratios=None)

Return the collapse of curves or distributions of several sizes or ages.

Curves measured at several sizes or ages often fall onto one curve once their axes are rescaled, and the rescaling that does it gives the exponents of the system, such as y_L(p) = L^a f((p - p_c) L^(1/nu)) for curves of sizes L near a critical point p_c. It fits the names of fit among critical, nu, and exponent, measures how far aging curves stay apart, or finds where the curves of consecutive sizes cross. It estimates the critical point of a magnet from lattices of several sizes, the growth exponents of a rough surface, and the aging of a glass.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

A mapping from size or age to its curve or samples, or an array with one curve per row.

required
kind str

'scaling' fits the collapse of curves of every size against parameters. 'aging' measures how far correlation curves of several waiting times stay apart against the lag and against tau / t_w. 'distribution' lays the densities t P(tau, t) of samples at several ages against tau / t. 'crossings' finds where the curves of consecutive sizes cross against parameters.

'scaling'
parameters Sequence[float] | None

The control parameter values, shared by every curve of 'scaling' and 'crossings'.

None
critical float | None

The critical value, or the starting value of a fit.

None
nu float | None

The correlation length exponent, or the starting value of a fit.

None
exponent float

The exponent a of the scaled curves y L^-a, such as gamma / nu for a susceptibility, or the starting value of a fit.

0.0
fit Sequence[str]

The names among 'critical', 'nu', and 'exponent' to fit.

()
waiting Sequence[float] | None

The waiting times of the curves of 'aging'.

None
lags Sequence[float] | None

The lags shared by every curve of 'aging'.

None
ratios Sequence[float] | None

The edges of the bins of tau / t, or None for 20 logarithmic bins from 0.01 to 10.

None

Returns:

Name Type Description
result DataCollapseResult

The curves, their labels, and the collapse of the kind.

Raises:

Type Description
AnalysisError

The kind or a fitted name is unknown, a setting the kind needs is missing or one it does not read is changed, or the source has too few sizes or is not a mapping where the kind needs one.

See Also

scaling: Fits power laws and exponents.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import data_collapse
>>> grid = np.linspace(-1, 1, 401)
>>> curves = {size: np.tanh(grid * size) for size in (8, 16, 32)}
>>> round(data_collapse(curves, parameters=grid, critical=0.2, nu=1.5, fit=('critical', 'nu')).nu, 1)
1.0
Source code in src/skcomplex/core/analysis/_collapse.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def data_collapse(
    source: DataSource,
    *,
    kind: str = 'scaling',
    parameters: Sequence[float] | None = None,
    critical: float | None = None,
    nu: float | None = None,
    exponent: float = 0.0,
    fit: Sequence[str] = (),
    waiting: Sequence[float] | None = None,
    lags: Sequence[float] | None = None,
    ratios: Sequence[float] | None = None,
) -> DataCollapseResult:
    """Return the collapse of curves or distributions of several sizes or ages.

    Curves measured at several sizes or ages often fall onto one curve once their axes are rescaled, and the rescaling
    that does it gives the exponents of the system, such as `y_L(p) = L^a f((p - p_c) L^(1/nu))` for curves of sizes `L`
    near a critical point `p_c`. It fits the names of `fit` among `critical`, `nu`, and `exponent`, measures how far
    aging curves stay apart, or finds where the curves of consecutive sizes cross. It estimates the critical point of a
    magnet from lattices of several sizes, the growth exponents of a rough surface, and the aging of a glass.

    Read more in the user guide, under Analyse.

    Args:
        source:
            A mapping from size or age to its curve or samples, or an array with one curve per row.

        kind:
            `'scaling'` fits the collapse of curves of every size against `parameters`. `'aging'` measures how far
            correlation curves of several waiting times stay apart against the lag and against `tau / t_w`.
            `'distribution'` lays the densities `t P(tau, t)` of samples at several ages against `tau / t`.
            `'crossings'` finds where the curves of consecutive sizes cross against `parameters`.

        parameters:
            The control parameter values, shared by every curve of `'scaling'` and `'crossings'`.

        critical:
            The critical value, or the starting value of a fit.

        nu:
            The correlation length exponent, or the starting value of a fit.

        exponent:
            The exponent `a` of the scaled curves `y L^-a`, such as `gamma / nu` for a susceptibility, or the
            starting value of a fit.

        fit:
            The names among `'critical'`, `'nu'`, and `'exponent'` to fit.

        waiting:
            The waiting times of the curves of `'aging'`.

        lags:
            The lags shared by every curve of `'aging'`.

        ratios:
            The edges of the bins of `tau / t`, or `None` for 20 logarithmic bins from 0.01 to 10.

    Returns:
        result:
            The curves, their labels, and the collapse of the kind.

    Raises:
        AnalysisError:
            The kind or a fitted name is unknown, a setting the kind needs is missing or one it does not read is
            changed, or the source has too few sizes or is not a mapping where the kind needs one.

    See Also:
        scaling: Fits power laws and exponents.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import data_collapse
        >>> grid = np.linspace(-1, 1, 401)
        >>> curves = {size: np.tanh(grid * size) for size in (8, 16, 32)}
        >>> round(data_collapse(curves, parameters=grid, critical=0.2, nu=1.5, fit=('critical', 'nu')).nu, 1)
        1.0
    """
    _check_choice('data_collapse', 'kind', kind, KINDS)
    for name in fit:
        _check_choice('data_collapse', 'fit', name, FITTED)
    _check_settings(
        data_collapse,
        'kind',
        SETTINGS[kind],
        kind=kind,
        parameters=parameters,
        critical=critical,
        nu=nu,
        exponent=exponent,
        fit=fit,
        waiting=waiting,
        lags=lags,
        ratios=ratios,
    )
    if kind == 'scaling' and (parameters is None or critical is None or nu is None):
        error_msg = 'data_collapse of kind scaling needs parameters, critical, and nu. Give all three.'
        raise AnalysisError(error_msg)
    if kind == 'crossings' and parameters is None:
        error_msg = 'data_collapse of kind crossings needs the control parameter values. Set `parameters`.'
        raise AnalysisError(error_msg)
    if kind == 'aging' and (waiting is None or lags is None):
        error_msg = 'data_collapse of kind aging needs waiting times and lags. Give both.'
        raise AnalysisError(error_msg)
    values: dict[float, Array] | Array
    if isinstance(source, Mapping):
        values = {key: np.asarray(value, dtype=np.float64) for key, value in source.items()}
        labels = [float(key) for key in source]
    else:
        values = np.asarray(source, dtype=np.float64)
        labels = [float(item) for item in waiting] if waiting is not None else list(range(len(values)))
    if kind in {'scaling', 'crossings'} and len(values) < MIN_SIZES:
        error_msg = f'data_collapse needs at least {MIN_SIZES} sizes, not {len(values)}. Give more sizes.'
        raise AnalysisError(error_msg)
    if kind == 'scaling' and critical is not None and nu is not None:
        start = {'critical': critical, 'nu': nu, 'exponent': exponent}
        grid = np.asarray(parameters, dtype=np.float64)
        fitted, quality = _scaling_collapse(grid, _curves_by_key(values, kind), start, fit)
        return DataCollapseResult(
            values,
            labels,
            critical=fitted['critical'],
            nu=fitted['nu'],
            exponent=fitted['exponent'],
            quality=quality,
        )
    if kind == 'aging' and waiting is not None:
        grid = np.asarray(lags, dtype=np.float64)
        curves = np.asarray(values, dtype=float)
        return DataCollapseResult(
            values,
            labels,
            time_spread=_spread([(grid, row) for row in curves]),
            ratio_spread=_spread([(grid / start, row) for start, row in zip(waiting, curves, strict=True)]),
        )
    if kind == 'crossings':
        rows = np.asarray([values[size] for size in sorted(values)]) if isinstance(values, dict) else values
        return DataCollapseResult(values, labels, crossings=_crossings(np.asarray(parameters, dtype=np.float64), rows))
    edges = np.geomspace(0.01, 10, 21) if ratios is None else np.asarray(ratios, dtype=float)
    densities, spread = _scaled_densities(_curves_by_key(values, kind), edges)
    return DataCollapseResult(
        values,
        labels,
        ratios=np.sqrt(edges[1:] * edges[:-1]),
        densities=densities,
        spread=spread,
    )

defects(source, *, period=np.pi, variables=None, periodic=True)

Return the points where a field of angles winds around, at every frame.

Around every square of four neighbouring sites it adds the changes of the angle along the sides, each wrapped to within half a turn, and divides by a whole turn, so a square the angle winds around once holds a defect of charge 1. The charges of a periodic grid sum to 0. An array of two dimensions holds one frame and one of three dimensions one frame per row. It finds the vortices of a superfluid, the defects of a liquid crystal, and the swirls of a swarm of bacteria.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of angles of one snapshot or of one frame per row.

required
period float

The period of the angles, np.pi for axes without head and tail and 2 * np.pi for vectors.

pi
variables Sequence[str] | None

The field of a trajectory to read, or None for its first field.

None
periodic bool

Whether the lattice joins its opposite edges, or has plaquettes only between its sites.

True

Returns:

Name Type Description
result DefectsResult

The angles, and the positions and the charges of the defects of every frame.

Raises:

Type Description
AnalysisError

The period is not positive, or the field is not two-dimensional.

See Also

alignment: Measures how well the members line up. domains: Finds the regions of a field.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import defects
>>> rows, columns = np.meshgrid(np.arange(8.0), np.arange(8.0), indexing='ij')
>>> result = defects(np.arctan2(rows - 3.5, columns - 3.5), period=2 * np.pi, periodic=False)
>>> result.positions[0].tolist(), result.charges[0].tolist()
([[3.5, 3.5]], [1.0])
Source code in src/skcomplex/core/analysis/_defects.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def defects(
    source: DataSource,
    *,
    period: float = np.pi,
    variables: Sequence[str] | None = None,
    periodic: bool = True,
) -> DefectsResult:
    """Return the points where a field of angles winds around, at every frame.

    Around every square of four neighbouring sites it adds the changes of the angle along the sides, each wrapped to
    within half a turn, and divides by a whole turn, so a square the angle winds around once holds a defect of charge 1.
    The charges of a periodic grid sum to 0. An array of two dimensions holds one frame and one of three dimensions one
    frame per row. It finds the vortices of a superfluid, the defects of a liquid crystal, and the swirls of a swarm of
    bacteria.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of angles of one snapshot or of one frame per row.

        period:
            The period of the angles, `np.pi` for axes without head and tail and `2 * np.pi` for vectors.

        variables:
            The field of a trajectory to read, or `None` for its first field.

        periodic:
            Whether the lattice joins its opposite edges, or has plaquettes only between its sites.

    Returns:
        result:
            The angles, and the positions and the charges of the defects of every frame.

    Raises:
        AnalysisError:
            The period is not positive, or the field is not two-dimensional.

    See Also:
        alignment: Measures how well the members line up.
        domains: Finds the regions of a field.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import defects
        >>> rows, columns = np.meshgrid(np.arange(8.0), np.arange(8.0), indexing='ij')
        >>> result = defects(np.arctan2(rows - 3.5, columns - 3.5), period=2 * np.pi, periodic=False)
        >>> result.positions[0].tolist(), result.charges[0].tolist()
        ([[3.5, 3.5]], [1.0])
    """
    if not period > 0:
        error_msg = f'The period of the angles is {period!r}. Give a positive number.'
        raise AnalysisError(error_msg)
    frames = _read_fields(source, variables[0] if variables else None)
    if frames.ndim not in {FIELD_RANK, FIELD_RANK + 1}:
        error_msg = f'defects reads a two-dimensional field, but got the shape {frames.shape}.'
        raise AnalysisError(error_msg)
    angles = frames[None] if frames.ndim == FIELD_RANK else frames
    positions, charges = [], []
    for frame in angles:
        windings = _windings(frame, period, periodic=periodic)
        found = np.argwhere(np.abs(windings) > CHARGE_TOLERANCE)
        positions.append(np.asarray(found + 0.5, dtype=float))
        charges.append(np.round(windings[tuple(found.T)], 6))
    return DefectsResult(angles, positions, charges)

displacement(source, *, group=None, dt=1.0, lags=None, fit_range=None)

Return the mean squared distance particles travel over every lag.

For every lag it averages the squared distance each particle moves in that time, MSD(tau) = <|x(t + tau) - x(t)|^2>, and fits MSD ~ tau^a, where a is 1 for diffusion and 2 for straight flight, with an FFT over all lags at once. Positions must be unwrapped across periodic walls, as a trajectory gives them. It tells diffusion from flight in the paths of molecules in a fluid, of cells in a tissue, and of animals that forage.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of positions with time as the first axis.

required
group str | None

The path of the agent group of a trajectory, or None for the first one.

None
dt float

The time between frames.

1.0
lags Sequence[int] | None

The lags in frames to keep, or None for every lag from 1.

None
fit_range tuple[float, float] | None

The smallest and largest lags in time of the fits, or None for one frame to a quarter of the run.

None

Returns:

Name Type Description
result DisplacementResult

The positions, the mean squared displacement at every lag, its exponent, and the diffusion coefficient.

Raises:

Type Description
AnalysisError

The time step or a lag is not positive, the agents have no positions, or the fit range holds too few lags.

See Also

passage: Measures the times to reach a level. kramers_moyal: Estimates the drift and noise of a path.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import displacement
>>> walks = np.cumsum(np.random.default_rng(0).standard_normal((2000, 500)), axis=0)
>>> round(displacement(walks).exponent, 1)
1.0
Source code in src/skcomplex/core/analysis/_displacement.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def displacement(
    source: DataSource,
    *,
    group: str | None = None,
    dt: float = 1.0,
    lags: Sequence[int] | None = None,
    fit_range: tuple[float, float] | None = None,
) -> DisplacementResult:
    """Return the mean squared distance particles travel over every lag.

    For every lag it averages the squared distance each particle moves in that time,
    `MSD(tau) = <|x(t + tau) - x(t)|^2>`, and fits `MSD ~ tau^a`, where `a` is 1 for diffusion and 2 for straight
    flight, with an FFT over all lags at once. Positions must be unwrapped across periodic walls, as a trajectory gives
    them. It tells diffusion from flight in the paths of molecules in a fluid, of cells in a tissue, and of animals that
    forage.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of positions with time as the first axis.

        group:
            The path of the agent group of a trajectory, or `None` for the first one.

        dt:
            The time between frames.

        lags:
            The lags in frames to keep, or `None` for every lag from 1.

        fit_range:
            The smallest and largest lags in time of the fits, or `None` for one frame to a quarter of the run.

    Returns:
        result:
            The positions, the mean squared displacement at every lag, its exponent, and the diffusion coefficient.

    Raises:
        AnalysisError:
            The time step or a lag is not positive, the agents have no positions, or the fit range holds too few lags.

    See Also:
        passage: Measures the times to reach a level.
        kramers_moyal: Estimates the drift and noise of a path.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import displacement
        >>> walks = np.cumsum(np.random.default_rng(0).standard_normal((2000, 500)), axis=0)
        >>> round(displacement(walks).exponent, 1)
        1.0
    """
    if dt <= 0:
        error_msg = f'displacement has dt={dt!r}. Use a positive time step.'
        raise AnalysisError(error_msg)
    if lags is not None and min(lags, default=1) < 1:
        error_msg = f'displacement has lags={lags!r}. Use lags of 1 frame or more.'
        raise AnalysisError(error_msg)
    if isinstance(source, Trajectory):
        read = _read_snapshots(source, group).positions
        if read is None:
            error_msg = f'The agents of {group or "the first group"} have no positions. Use agents in a space.'
            raise AnalysisError(error_msg)
        positions = _particle_axes(read)
    else:
        positions = _particle_axes(np.asarray(source))
    msd = np.mean([_get_msd(positions[:, particle]) for particle in range(positions.shape[1])], axis=0)
    all_lags = np.arange(1, positions.shape[0], dtype=np.float64) * dt
    chosen = _fit_lags(all_lags, fit_range)
    exponent = float(np.polyfit(np.log(all_lags[chosen]), np.log(msd[chosen]), 1)[0])
    slope = float(np.polyfit(all_lags[chosen], msd[chosen], 1)[0])
    diffusion = slope / (2 * positions.shape[2])
    if lags is None:
        return DisplacementResult(positions, all_lags, msd, exponent, diffusion)
    steps = np.asarray(lags, dtype=int)
    return DisplacementResult(positions, steps * dt, msd[steps - 1], exponent, diffusion)

distribution(source, *, kind='histogram', variables=None, group=None, bins=30, log=False, absolute=False, orders=(4, 2), tail=10)

Return the distribution of the values of a source, of one kind.

It reads samples as columns, the series of a trajectory or an array, or the speeds of the agents at every frame, and measures how the values spread, such as the Gini coefficient, 0 when all hold the same and near 1 when one holds everything. Some kinds pool every sample into one and others describe every sample. It describes the spread of incomes in an economy, the sizes of cities, and the avalanches of a sandpile.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array with one column per sample.

required
kind str

Pooled kinds: 'histogram' gives the edges and density of bins bins, spaced in the logarithm with log=True. 'ccdf' gives the share of values at or above every distinct value. 'gini' gives the Gini coefficient of nonnegative values. 'tail-index' gives the Hill estimate of the tail index from the tail largest values. Per sample kinds: 'moments' gives the mean, variance, skewness, and excess kurtosis, of the absolute values with absolute=True. 'moment-ratio' gives <x^p> / <x^q>^(p / q) of the even orders and the cumulant 1 - ratio / ratio_gauss, 0 for Gaussian samples. 'dispersion-index' gives the variance over the mean of counts, 1 for Poisson counts. 'records' counts the values larger than all before them. 'total-variation' gives the distance 1/2 sum |a_u / A - b_u / B| between the distributions of two groups across units, from one row per item with its group and unit.

'histogram'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series.

None
group str | None

The path of the agent or particle group whose speeds are read, or None for the series of a trajectory, or the first group of a trajectory without series.

None
bins int

The number of bins of the histogram.

30
log bool

Whether the bins of the histogram are equally spaced in the logarithm of the values, which needs positive values.

False
absolute bool

Whether the moments are those of the absolute values.

False
orders tuple[int, int]

The positive even orders (p, q) of the moment ratio.

(4, 2)
tail int

The number of largest samples of the Hill estimate.

10

Returns:

Name Type Description
result DistributionResult

The samples and their description.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a setting is out of range, or the samples do not suit the kind.

See Also

scaling: Fits power laws and exponents. coarse_grain: Counts members at values.

Examples:

>>> from skcomplex.core.analysis import distribution
>>> distribution([1, 1, 2, 4], kind='ccdf').survival.tolist()
[1.0, 0.5, 0.25]
Source code in src/skcomplex/core/analysis/_distribution.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def distribution(
    source: DataSource,
    *,
    kind: str = 'histogram',
    variables: Sequence[str] | None = None,
    group: str | None = None,
    bins: int = 30,
    log: bool = False,
    absolute: bool = False,
    orders: tuple[int, int] = (4, 2),
    tail: int = 10,
) -> DistributionResult:
    """Return the distribution of the values of a source, of one kind.

    It reads samples as columns, the series of a trajectory or an array, or the speeds of the agents at every frame, and
    measures how the values spread, such as the Gini coefficient, 0 when all hold the same and near 1 when one holds
    everything. Some kinds pool every sample into one and others describe every sample. It describes the spread of
    incomes in an economy, the sizes of cities, and the avalanches of a sandpile.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array with one column per sample.

        kind:
            Pooled kinds: `'histogram'` gives the edges and density of `bins` bins, spaced in the logarithm with
            `log=True`. `'ccdf'` gives the share of values at or above every distinct value. `'gini'` gives the Gini
            coefficient of nonnegative values. `'tail-index'` gives the Hill estimate of the tail index from the `tail`
            largest values. Per sample kinds: `'moments'` gives the mean, variance, skewness, and excess kurtosis, of
            the absolute values with `absolute=True`. `'moment-ratio'` gives `<x^p> / <x^q>^(p / q)` of the even
            `orders` and the cumulant `1 - ratio / ratio_gauss`, 0 for Gaussian samples. `'dispersion-index'` gives the
            variance over the mean of counts, 1 for Poisson counts. `'records'` counts the values larger than all before
            them. `'total-variation'` gives the distance `1/2 sum |a_u / A - b_u / B|` between the distributions of two
            groups across units, from one row per item with its group and unit.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series.

        group:
            The path of the agent or particle group whose speeds are read, or `None` for the series of a trajectory, or
            the first group of a trajectory without series.

        bins:
            The number of bins of the histogram.

        log:
            Whether the bins of the histogram are equally spaced in the logarithm of the values, which needs positive
            values.

        absolute:
            Whether the moments are those of the absolute values.

        orders:
            The positive even orders `(p, q)` of the moment ratio.

        tail:
            The number of largest samples of the Hill estimate.

    Returns:
        result:
            The samples and their description.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a setting is out of range, or the
            samples do not suit the kind.

    See Also:
        scaling: Fits power laws and exponents.
        coarse_grain: Counts members at values.

    Examples:
        >>> from skcomplex.core.analysis import distribution
        >>> distribution([1, 1, 2, 4], kind='ccdf').survival.tolist()
        [1.0, 0.5, 0.25]
    """
    _check_choice('distribution', 'kind', kind, KINDS)
    _check_settings(
        distribution,
        'kind',
        SETTINGS[kind] | {'variables', 'group'},
        kind=kind,
        variables=variables,
        group=group,
        bins=bins,
        log=log,
        absolute=absolute,
        orders=orders,
        tail=tail,
    )
    if bins < 1 or tail < 1:
        error_msg = f'distribution has bins={bins!r} and tail={tail!r}. Use 1 or more.'
        raise AnalysisError(error_msg)
    if len(orders) != ORDER_COUNT or any(order <= 0 or order % 2 for order in orders):
        error_msg = f'distribution has orders={orders!r}. Use two positive even orders.'
        raise AnalysisError(error_msg)
    series = _read_samples_of(source, variables, group)
    samples = _read_real(series.values, 'values')
    values = samples.ravel() if kind in POOLED else samples
    labels = series.labels
    if kind == 'total-variation' and values.shape[1] != UNIT_COLUMNS:
        error_msg = (
            'distribution of kind total-variation reads one row per item with its group and its unit, not an array '
            f'of shape {values.shape}.'
        )
        raise AnalysisError(error_msg)
    if kind in POOLED:
        return _describe_pooled(values, labels, kind, bins, tail, log=log)
    return _describe_samples(values, labels, kind, orders, absolute=absolute)

domains(source, *, kind='size', variables=None, method='moment', spacing=1.0, fit_range=None, times=None, attribute='state')

Return the regions of every frame of a field, or of the states on a network.

A domain is a region of equal value, such as a patch of spins pointing up. It measures their typical size, how fast they grow, the dominant wavelength of a pattern, or the share of neighbours whose values differ, 0 for one domain and 1/2 for random values. A trajectory gives the frames and times of a lattice value, and a graph holds values on its nodes. It measures the growth of magnetic domains after a quench, of regions of opinion in a voter model, and of the phases of an alloy.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array of frames, or a graph.

required
kind str

'size' gives the typical size, 2 pi / <k> of the structure factor with method='moment' or the first zero of the correlation with method='zero'. 'growth' gives the size of every frame and the slope of log size against log time, 1/2 when the total is free and 1/3 when it is kept. 'wavelength' gives the peak of the structure factor and how parallel the waves near it are, 1 for stripes. 'interface-density' gives the share of neighbouring pairs whose values differ, on a periodic grid or along the edges of a network.

'size'
variables Sequence[str] | None

The lattice state of a trajectory to read, or None for the first one.

None
method str

The domain size method, 'moment' or 'zero'.

'moment'
spacing float

The distance between neighbouring sites.

1.0
fit_range tuple[float, float] | None

The first and last times of the growth fit, or None for every positive time.

None
times Sequence[float] | None

The time of every frame of an array, or None for an array of one frame.

None
attribute str

The node attribute of the states of a graph.

'state'

Returns:

Name Type Description
result DomainsResult

The frames, their times, and the domain measure of every frame.

Raises:

Type Description
AnalysisError

The kind or method is unknown, a setting the kind does not read is changed, the spacing is not positive, or a kind that reads a field is given a graph.

See Also

clusters: Finds the clusters of a grid. correlation: Measures how far order reaches.

Examples:

>>> from skcomplex.core.analysis import domains
>>> domains([[1, 1, -1, -1]] * 4, kind='interface-density').density.tolist()
[0.25]
Source code in src/skcomplex/core/analysis/_domains.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def domains(
    source: DataSource,
    *,
    kind: str = 'size',
    variables: Sequence[str] | None = None,
    method: str = 'moment',
    spacing: float = 1.0,
    fit_range: tuple[float, float] | None = None,
    times: Sequence[float] | None = None,
    attribute: str = 'state',
) -> DomainsResult:
    """Return the regions of every frame of a field, or of the states on a network.

    A domain is a region of equal value, such as a patch of spins pointing up. It measures their typical size, how fast
    they grow, the dominant wavelength of a pattern, or the share of neighbours whose values differ, 0 for one domain
    and 1/2 for random values. A trajectory gives the frames and times of a lattice value, and a graph holds values on
    its nodes. It measures the growth of magnetic domains after a quench, of regions of opinion in a voter model, and of
    the phases of an alloy.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array of frames, or a graph.

        kind:
            `'size'` gives the typical size, `2 pi / <k>` of the structure factor with `method='moment'` or the first
            zero of the correlation with `method='zero'`. `'growth'` gives the size of every frame and the slope of
            `log size` against `log time`, 1/2 when the total is free and 1/3 when it is kept. `'wavelength'` gives the
            peak of the structure factor and how parallel the waves near it are, 1 for stripes. `'interface-density'`
            gives the share of neighbouring pairs whose values differ, on a periodic grid or along the edges of a
            network.

        variables:
            The lattice state of a trajectory to read, or `None` for the first one.

        method:
            The domain size method, `'moment'` or `'zero'`.

        spacing:
            The distance between neighbouring sites.

        fit_range:
            The first and last times of the growth fit, or `None` for every positive time.

        times:
            The time of every frame of an array, or `None` for an array of one frame.

        attribute:
            The node attribute of the states of a graph.

    Returns:
        result:
            The frames, their times, and the domain measure of every frame.

    Raises:
        AnalysisError:
            The kind or method is unknown, a setting the kind does not read is changed, the spacing is not positive,
            or a kind that reads a field is given a graph.

    See Also:
        clusters: Finds the clusters of a grid.
        correlation: Measures how far order reaches.

    Examples:
        >>> from skcomplex.core.analysis import domains
        >>> domains([[1, 1, -1, -1]] * 4, kind='interface-density').density.tolist()
        [0.25]
    """
    _check_choice('domains', 'kind', kind, KINDS)
    _check_choice('domains', 'method', method, METHODS)
    _check_settings(
        domains,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        method=method,
        spacing=spacing,
        fit_range=fit_range,
        times=times,
        attribute=attribute,
    )
    if spacing <= 0:
        error_msg = f'domains has spacing={spacing!r}. Use a positive spacing.'
        raise AnalysisError(error_msg)
    frames, frame_times = _read_frames(source, kind, variables, times)
    if kind in {'size', 'growth'}:
        size = np.asarray([_domain_size(frame, method, spacing) for frame in frames])
        exponent = _growth_exponent(frame_times, size, fit_range) if kind == 'growth' else None
        return DomainsResult(frames, frame_times, size=size, exponent=exponent)
    if kind == 'wavelength':
        patterns = np.asarray([_pattern(frame, spacing) for frame in frames]).reshape(-1, 3)
        wavelength, wavenumber, orientation = patterns.T
        return DomainsResult(
            frames,
            frame_times,
            wavelength=wavelength,
            wavenumber=wavenumber,
            orientation=orientation,
        )
    density = np.asarray([_interface_density(frame, attribute) for frame in frames])
    return DomainsResult(frames, frame_times, density=density)

elementary_modes(source, *, kind='modes', normalize=None, exchanges=None, timeout=60.0, labels=None, irreversible=None, sort=None)

Return the simplest steady routes through a network of flows.

A steady route is a set of flows v that keeps every amount fixed, S v = 0, with every one-way flow running its own way. The simplest routes use as few flows as they can, and every steady state is a mix of them. A system gives the matrix and the directions of its linear program law at its initial values, and a matrix gives them directly with the indices of its one-way columns. It lists the pathways of a metabolism, the routes of a chemical plant, and the ways goods can flow through a supply chain.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, or the matrix.

required
kind str

'modes' gives the steady routes of fewest flows with every one-way flow in its own direction, by splitting every two-way column, finding the edges of the cone with the Parma Polyhedra Library, and mapping back (Gagneur and Klamt 2004). 'pathways' gives the edges of the cone with every two-way internal column split and each exchange kept whole (Schilling et al. 2000), without any route that mixes others (Raman 2021). Routes that run both ways move to lines.

'modes'
normalize str | None

The name of a variable to scale every row to one where it is not zero, or None for the smallest integer vector.

None
exchanges Sequence[str] | None

The names of the exchange variables, or None for the variables in one row.

None
timeout float

The time limit of the enumeration in seconds.

60.0
labels Sequence[str] | None

The names of the columns of a matrix, or None for v0, v1, and so on.

None
irreversible Sequence[int] | None

The indices of the irreversible columns of a matrix, or None for every column.

None
sort str | None

The name of a variable to order the rows by, largest first, such as the growth flux of modes normalised to the uptake, which orders them by yield, or None for a fixed order.

None

Returns:

Name Type Description
result ElementaryModesResult

The names of the columns, the generators, and the lines.

Raises:

Type Description
AnalysisError

The kind is unknown, the right side of a balance is not zero, a coefficient is not close to a fraction, or no system or matrix holds a program.

EnumerationLimitError

The enumeration does not finish within the time limit.

See Also

loops: Finds the feedback loops of a network. autocatalytic_sets: Finds sets of reactions that help each other.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import elementary_modes
>>> elementary_modes(np.array([[1.0, -1.0, 0.0], [0.0, 1.0, -1.0]]), normalize='v0').modes.tolist()
[[Fraction(1, 1), Fraction(1, 1), Fraction(1, 1)]]
Source code in src/skcomplex/core/analysis/_elementary_modes.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def elementary_modes(
    source: DataSource,
    *,
    kind: str = 'modes',
    normalize: str | None = None,
    exchanges: Sequence[str] | None = None,
    timeout: float = 60.0,
    labels: Sequence[str] | None = None,
    irreversible: Sequence[int] | None = None,
    sort: str | None = None,
) -> ElementaryModesResult:
    """Return the simplest steady routes through a network of flows.

    A steady route is a set of flows `v` that keeps every amount fixed, `S v = 0`, with every one-way flow running its
    own way. The simplest routes use as few flows as they can, and every steady state is a mix of them. A system gives
    the matrix and the directions of its linear program law at its initial values, and a matrix gives them directly with
    the indices of its one-way columns. It lists the pathways of a metabolism, the routes of a chemical plant, and the
    ways goods can flow through a supply chain.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, or the matrix.

        kind:
            `'modes'` gives the steady routes of fewest flows with every one-way flow in its own direction, by splitting
            every two-way column, finding the edges of the cone with the Parma Polyhedra Library, and mapping back
            (Gagneur and Klamt 2004). `'pathways'` gives the edges of the cone with every two-way internal column split
            and each exchange kept whole (Schilling et al. 2000), without any route that mixes others (Raman 2021).
            Routes that run both ways move to `lines`.

        normalize:
            The name of a variable to scale every row to one where it is not zero, or `None` for the smallest integer
            vector.

        exchanges:
            The names of the exchange variables, or `None` for the variables in one row.

        timeout:
            The time limit of the enumeration in seconds.

        labels:
            The names of the columns of a matrix, or `None` for `v0`, `v1`, and so on.

        irreversible:
            The indices of the irreversible columns of a matrix, or `None` for every column.

        sort:
            The name of a variable to order the rows by, largest first, such as the growth flux of modes normalised to
            the uptake, which orders them by yield, or `None` for a fixed order.

    Returns:
        result:
            The names of the columns, the generators, and the lines.

    Raises:
        AnalysisError:
            The kind is unknown, the right side of a balance is not zero, a coefficient is not close to a fraction, or
            no system or matrix holds a program.

        EnumerationLimitError:
            The enumeration does not finish within the time limit.

    See Also:
        loops: Finds the feedback loops of a network.
        autocatalytic_sets: Finds sets of reactions that help each other.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import elementary_modes
        >>> elementary_modes(np.array([[1.0, -1.0, 0.0], [0.0, 1.0, -1.0]]), normalize='v0').modes.tolist()
        [[Fraction(1, 1), Fraction(1, 1), Fraction(1, 1)]]
    """
    source = _composite(source)
    if kind not in KINDS:
        error_msg = f'Unknown kind {kind!r}. Use one of {", ".join(KINDS)}.'
        raise AnalysisError(error_msg)
    if not timeout > 0:
        error_msg = f'The time limit must be positive, but it is {timeout!r}.'
        raise AnalysisError(error_msg)
    if isinstance(source, _CompositeSystem):
        cone = _system_cone(source, exchanges)
    elif isinstance(source, np.ndarray):
        cone = _matrix_cone(np.asarray(source, dtype=float), exchanges, labels, irreversible)
    else:
        error_msg = f'elementary_modes takes a system or a matrix, not {type(source).__name__}.'
        raise AnalysisError(error_msg)
    fractions = _exact_matrix(cone)
    vectors = _mapped_rays(cone, fractions, _split_columns(cone, kind), kind, timeout)
    rays = _unique(cone, vectors, normalize, sort)
    if kind == 'pathways':
        rays = _independent(cone, rays, timeout)
    kept = {tuple(row) for row in rays}
    opposite = [tuple(-item for item in row) in kept for row in rays]
    size = len(cone.labels)
    lines = np.asarray(
        [row for row, both in zip(rays, opposite, strict=True) if both and next(i for i in row if i != 0) > 0],
        dtype=object,
    ).reshape(-1, size)
    modes = rays if kind == 'modes' else rays[~np.asarray(opposite, dtype=bool)]
    return ElementaryModesResult(cone.labels, modes, lines)

embedding(source, *, kind='delay', variables=None, delay=None, dimension=None, threshold=0.01, max_delay=100, max_dimension=10, bins=16, ratio=10.0, escape=2.0)

Return the points made of delayed copies of one series.

It builds the points (x_t, x_{t+delay}, ..., x_{t+(dimension-1) delay}), which rebuild the shape of the orbit of a system from one measured series, such as [[0, 2], [1, 3], [2, 4]] for 0, 1, 2, 3, 4 with delay 2. Without a delay it takes the first minimum of the auto mutual information, and without a dimension the first one whose share of false neighbours lies below threshold. It rebuilds the orbit of a heart rate, of a river flow, and of a stock price.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array that holds one series.

required
kind str

'delay' gives the delayed points. 'false-nearest-neighbors' gives the share of false neighbours of Kennel for dimensions 1 to max_dimension, a neighbour in dimension d being false when the next coordinate moves it away by more than ratio times their distance or escape times the spread of the series.

'delay'
variables Sequence[str] | None

The one variable of a trajectory to read, or None for the only scalar series.

None
delay int | None

The delay in steps, or None for the first minimum of the auto mutual information.

None
dimension int | None

The dimension, or None for the first one with a fraction of false nearest neighbours below threshold.

None
threshold float

The fraction of false nearest neighbours accepted.

0.01
max_delay int

The largest delay tried.

100
max_dimension int

The largest dimension tried.

10
bins int

The number of equally populated bins of the auto mutual information.

16
ratio float

The threshold on the relative growth of the distance of a false neighbour.

10.0
escape float

The threshold on the distance of a false neighbour in the next dimension, in standard deviations.

2.0

Returns:

Name Type Description
result EmbeddingResult

The series, the delay, and the embedding or the fraction of false neighbours.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a size is below 1, the source holds several series, or no dimension has few enough false neighbours.

See Also

recurrence: Finds when an orbit returns near itself. lyapunov: Measures how fast nearby runs drift apart.

Examples:

>>> from skcomplex.core.analysis import embedding
>>> embedding([0, 1, 2, 3, 4], delay=2, dimension=2).points.tolist()
[[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]]
Source code in src/skcomplex/core/analysis/_embedding.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def embedding(
    source: DataSource,
    *,
    kind: str = 'delay',
    variables: Sequence[str] | None = None,
    delay: int | None = None,
    dimension: int | None = None,
    threshold: float = 0.01,
    max_delay: int = 100,
    max_dimension: int = 10,
    bins: int = 16,
    ratio: float = 10.0,
    escape: float = 2.0,
) -> EmbeddingResult:
    """Return the points made of delayed copies of one series.

    It builds the points `(x_t, x_{t+delay}, ..., x_{t+(dimension-1) delay})`, which rebuild the shape of the orbit of a
    system from one measured series, such as `[[0, 2], [1, 3], [2, 4]]` for `0, 1, 2, 3, 4` with delay 2. Without a
    delay it takes the first minimum of the auto mutual information, and without a dimension the first one whose share
    of false neighbours lies below `threshold`. It rebuilds the orbit of a heart rate, of a river flow, and of a stock
    price.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array that holds one series.

        kind:
            `'delay'` gives the delayed points. `'false-nearest-neighbors'` gives the share of false neighbours of
            Kennel for dimensions 1 to `max_dimension`, a neighbour in dimension `d` being false when the next
            coordinate moves it away by more than `ratio` times their distance or `escape` times the spread of the
            series.

        variables:
            The one variable of a trajectory to read, or `None` for the only scalar series.

        delay:
            The delay in steps, or `None` for the first minimum of the auto mutual information.

        dimension:
            The dimension, or `None` for the first one with a fraction of false nearest neighbours below `threshold`.

        threshold:
            The fraction of false nearest neighbours accepted.

        max_delay:
            The largest delay tried.

        max_dimension:
            The largest dimension tried.

        bins:
            The number of equally populated bins of the auto mutual information.

        ratio:
            The threshold on the relative growth of the distance of a false neighbour.

        escape:
            The threshold on the distance of a false neighbour in the next dimension, in standard deviations.

    Returns:
        result:
            The series, the delay, and the embedding or the fraction of false neighbours.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a size is below 1, the source holds
            several series, or no dimension has few enough false neighbours.

    See Also:
        recurrence: Finds when an orbit returns near itself.
        lyapunov: Measures how fast nearby runs drift apart.

    Examples:
        >>> from skcomplex.core.analysis import embedding
        >>> embedding([0, 1, 2, 3, 4], delay=2, dimension=2).points.tolist()
        [[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]]
    """
    _check_choice('embedding', 'kind', kind, KINDS)
    _check_settings(
        embedding,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        delay=delay,
        dimension=dimension,
        threshold=threshold,
        max_delay=max_delay,
        max_dimension=max_dimension,
        bins=bins,
        ratio=ratio,
        escape=escape,
    )
    sizes = [size for size in (delay, dimension) if size is not None]
    if any(size < 1 for size in [*sizes, max_delay, max_dimension, bins]):
        error_msg = (
            f'embedding has delay={delay!r}, dimension={dimension!r}, max_delay={max_delay!r}, '
            f'max_dimension={max_dimension!r}, and bins={bins!r}. Use 1 or more.'
        )
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    if series.values.shape[1] != 1:
        error_msg = (
            f'embedding embeds one series, but the source has {series.values.shape[1]}: {", ".join(series.labels)}. '
            'Pick one with `variables`.'
        )
        raise AnalysisError(error_msg)
    array = series.values[:, 0]
    mutual_information = None
    if delay is None:
        mutual_information = _auto_mutual_information(array, max_delay, bins)
        delay = _first_minimum(mutual_information)
    false_neighbors: Array | None = None
    if kind == 'false-nearest-neighbors':
        false_neighbors = _false_nearest_neighbors(array, delay, max_dimension, ratio=ratio, escape=escape)
        return EmbeddingResult(
            series.values,
            series.labels,
            delay,
            mutual_information=mutual_information,
            false_neighbors=false_neighbors,
        )
    if dimension is None:
        false_neighbors = _false_nearest_neighbors(array, delay, max_dimension)
        below = np.flatnonzero(false_neighbors < threshold)
        if not below.size:
            error_msg = (
                f'No dimension up to {max_dimension} has fewer than {threshold} false neighbours. Raise '
                'max_dimension or threshold.'
            )
            raise AnalysisError(error_msg)
        dimension = int(below[0] + 1)
    return EmbeddingResult(
        series.values,
        series.labels,
        delay,
        dimension,
        _delay_embedding(array, dimension, delay),
        mutual_information,
        false_neighbors,
    )

emergence(source, *, kind='causal', variables=None, partition=None, weighting='uniform', search='greedy', lag=1, history=1, estimator='plugin', k=3, base=2.0)

Return how much a coarse scale adds over a fine scale, of one kind.

It reads a matrix of the chances of moving between fine states, or series of fine variables, and asks whether grouping the states into coarse ones predicts better, such as the 2 bits of four states that each stay put. It asks whether a flock, a brain region, or an economy acts as more than its parts.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

A transition matrix or transition counts for 'effective-information' and 'causal', and the trajectory or an array of micro series for 'criteria' and 'closure'.

required
kind str

'effective-information' gives H(mean row) - mean H(row) of a matrix of moves, split into determinism and degeneracy, normalising a matrix of counts by row. 'causal' gives the gain of the coarse matrix of a given or searched grouping over the fine one, weighting the states of a group evenly (Hoel et al. 2013) or by how often they are visited (Klein and Hoel 2020), with a greedy search or an exhaustive one up to 10 states. 'criteria' gives the criteria Psi, Delta, and Gamma of Rosas et al. (2020) for the coarse feature that partition gives, lag steps ahead. 'closure' gives how much better the fine past predicts the coarse future than the coarse past does, 0 for a closed view.

'causal'
variables Sequence[str] | None

The micro variables of a trajectory to read, or None for every scalar series.

None
partition Partition | None

The macro label of every integer micro state, numbered 0, 1, and so on, or a function from an array of micro states, or from the micro series with one column per variable, to their macro labels. None to search a partition of the matrix.

None
weighting str

'uniform' or 'stationary', the weight of the micro states within a block.

'uniform'
search str

'greedy' or 'exhaustive', the search when no partition is given.

'greedy'
lag int

The number of steps between the present and the future of the criteria.

1
history int

The number of past steps the closure conditions on.

1
estimator str

'plugin' for the frequencies of symbols, 'gaussian' for the closed form of a fitted Gaussian, or 'knn' for nearest-neighbour conditional mutual informations.

'plugin'
k int

The number of neighbours of the 'knn' estimator.

3
base float

The base of the logarithm, 2 for bits.

2.0

Returns:

Name Type Description
result EmergenceResult

The matrix or the micro series read, and the measures of the kind.

Raises:

Type Description
AnalysisError

A choice is unknown, a setting the kind does not read is changed, a setting is out of range, the macro feature is missing, the matrix is not square or has no observed transition, the partition is not valid, or the exhaustive search gets more than 10 states.

Warns:

Type Description
UnobservedStatesWarning

Some rows of the micro matrix hold no transition, and the warning names their states.

See Also

information: Measures shared information between series. markov: Fits a chain of moves between states.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import emergence
>>> emergence(np.eye(4), kind='effective-information').information
2.0
Source code in src/skcomplex/core/analysis/_emergence.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def emergence(
    source: DataSource,
    *,
    kind: str = 'causal',
    variables: Sequence[str] | None = None,
    partition: Partition | None = None,
    weighting: str = 'uniform',
    search: str = 'greedy',
    lag: int = 1,
    history: int = 1,
    estimator: str = 'plugin',
    k: int = 3,
    base: float = 2.0,
) -> EmergenceResult:
    """Return how much a coarse scale adds over a fine scale, of one kind.

    It reads a matrix of the chances of moving between fine states, or series of fine variables, and asks whether
    grouping the states into coarse ones predicts better, such as the 2 bits of four states that each stay put. It asks
    whether a flock, a brain region, or an economy acts as more than its parts.

    Read more in the user guide, under Analyse.

    Args:
        source:
            A transition matrix or transition counts for `'effective-information'` and `'causal'`, and the trajectory or
            an array of micro series for `'criteria'` and `'closure'`.

        kind:
            `'effective-information'` gives `H(mean row) - mean H(row)` of a matrix of moves, split into determinism and
            degeneracy, normalising a matrix of counts by row. `'causal'` gives the gain of the coarse matrix of a given
            or searched grouping over the fine one, weighting the states of a group evenly (Hoel et al. 2013) or by how
            often they are visited (Klein and Hoel 2020), with a greedy search or an exhaustive one up to 10 states.
            `'criteria'` gives the criteria Psi, Delta, and Gamma of Rosas et al. (2020) for the coarse feature that
            `partition` gives, `lag` steps ahead. `'closure'` gives how much better the fine past predicts the coarse
            future than the coarse past does, 0 for a closed view.

        variables:
            The micro variables of a trajectory to read, or `None` for every scalar series.

        partition:
            The macro label of every integer micro state, numbered 0, 1, and so on, or a function from an array of
            micro states, or from the micro series with one column per variable, to their macro labels. `None` to
            search a partition of the matrix.

        weighting:
            `'uniform'` or `'stationary'`, the weight of the micro states within a block.

        search:
            `'greedy'` or `'exhaustive'`, the search when no partition is given.

        lag:
            The number of steps between the present and the future of the criteria.

        history:
            The number of past steps the closure conditions on.

        estimator:
            `'plugin'` for the frequencies of symbols, `'gaussian'` for the closed form of a fitted Gaussian, or
            `'knn'` for nearest-neighbour conditional mutual informations.

        k:
            The number of neighbours of the `'knn'` estimator.

        base:
            The base of the logarithm, 2 for bits.

    Returns:
        result:
            The matrix or the micro series read, and the measures of the kind.

    Raises:
        AnalysisError:
            A choice is unknown, a setting the kind does not read is changed, a setting is out of range, the macro
            feature is missing, the matrix is not square or has no observed transition, the partition is not valid, or
            the exhaustive search gets more than 10 states.

    Warns:
        UnobservedStatesWarning:
            Some rows of the micro matrix hold no transition, and the warning names their states.

    See Also:
        information: Measures shared information between series.
        markov: Fits a chain of moves between states.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import emergence
        >>> emergence(np.eye(4), kind='effective-information').information
        2.0
    """
    for name, value, choices in (
        ('kind', kind, KINDS),
        ('weighting', weighting, WEIGHTINGS),
        ('search', search, SEARCHES),
        ('estimator', estimator, ESTIMATORS),
    ):
        _check_choice('emergence', name, value, choices)
    _check_settings(
        emergence,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        partition=partition,
        weighting=weighting,
        search=search,
        lag=lag,
        history=history,
        estimator=estimator,
        k=k,
        base=base,
    )
    if kind in {'criteria', 'closure'} and partition is None:
        error_msg = (
            f'emergence of kind {kind!r} needs the macro feature. Pass the macro label of every micro state, or a '
            'function of the micro series, as `partition`.'
        )
        raise AnalysisError(error_msg)
    if lag < 1 or history < 1 or k < 1 or base <= 0:
        error_msg = (
            f'emergence has lag={lag!r}, history={history!r}, k={k!r}, and base={base!r}. Use a lag, a history, and '
            'neighbours of 1 or more and a positive base.'
        )
        raise AnalysisError(error_msg)
    if kind not in MATRIX_KINDS:
        series = _read_series(source, variables)
        macro = _macro_series(series.values, _get_partition(partition, kind))
        if kind == 'criteria':
            return _criteria(series.values, series.labels, macro, lag=lag, estimator=estimator, k=k, base=base)
        return _closure(series.values, series.labels, macro, history, base)
    if isinstance(source, Trajectory):
        error_msg = (
            f'emergence of kind {kind!r} reads a transition matrix. Pass the matrix or the transition counts as an '
            'array.'
        )
        raise AnalysisError(error_msg)
    matrix = _square(np.asarray(source))
    if kind == 'effective-information':
        information, determinism, degeneracy, states = _effective_information(matrix)
        return EmergenceResult(
            matrix=matrix,
            information=information,
            determinism=determinism,
            degeneracy=degeneracy,
            states=states,
        )
    return _causal(matrix, partition, weighting, search)

entropy(source, *, kind='shannon', variables=None, order=2.0, base=2.0, probabilities=False, dimension=3, delay=1, tolerance=0.2, scales=tuple(range(1, 11)), normalize=True, dt=1.0, measure='shannon', ties='order', random_state=None, reference=None)

Return the entropy of every series of a source, or of every frame of a field.

Entropy measures how unpredictable values are, in bits, such as 1 bit for a series that takes two values equally often and 0 for a constant one. The kinds read symbols, patterns, or real values. It measures the disorder of a heart rate, a written text, and the configurations of a lattice.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array with one row per time and one column per series, the frames of a field, or the outcomes of an ensemble.

required
kind str

What to return. 'shannon', 'renyi', and 'tsallis' give the entropy of the distribution of the symbols, or of a probability vector with probabilities=True, the Rényi order and the Tsallis index given by order. 'block', 'rate', and 'excess' give the block entropies S_0 to S_m, the entropy rate, and the excess entropy of the blocks of up to dimension symbols, or of square patches of a field. 'lempel-ziv' gives the number of new phrases of the LZ76 parsing. 'permutation' gives the entropy of the ordinal patterns of length dimension, or of the windows (columns, rows) of a field, measured with measure. 'sample' and 'approximate' give the regularity of patterns of length dimension, close within tolerance standard deviations. 'multiscale' gives the sample entropy of the means of windows that do not overlap, of every scale of scales. 'spectral' gives the Shannon entropy of the normalized periodogram. 'ensemble' gives the Shannon entropy in bits of the outcomes of an ensemble at every frame, and their Kullback-Leibler divergence from the reference law, as in the H theorem. The ensemble has one row per run and one column per frame of integer outcomes, such as ExperimentResult.get_ensemble returns.

'shannon'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series, or the first field for a field.

None
order float

The order of the Rényi entropy or the index of the Tsallis entropy.

2.0
base float

The base of the logarithm, 2 for bits.

2.0
probabilities bool

Whether every series is already a probability vector.

False
dimension int | tuple[int, int]

The length of patterns or the largest block length, or the window (columns, rows) of a field.

3
delay int

The number of steps between the values of an ordinal pattern.

1
tolerance float

The largest distance of close patterns, as a fraction of the standard deviation.

0.2
scales Sequence[int]

The window lengths of the multiscale entropy.

tuple(range(1, 11))
normalize bool

Whether to divide by the largest value, so the entropy lies between 0 and 1.

True
dt float

The time between samples of the spectral entropy.

1.0
measure str

The entropy of the ordinal patterns: 'shannon', 'renyi', or 'tsallis'.

'shannon'
ties str

'order' to rank equal values by position, or 'random' to rank them at random.

'order'
random_state int | None

The seed of the random ranks of equal values.

None
reference ArrayLike | None

The probability of every outcome under the reference law of an ensemble, such as the stationary law.

None

Returns:

Name Type Description
result EntropyResult

The values read, their entropy, and the divergence of an ensemble.

Raises:

Type Description
AnalysisError

A choice is unknown, a setting the kind does not read is changed, a setting is out of range, or the outcomes of an ensemble lie outside the reference law.

See Also

information: Gives the information among series. complexity: Places series on the complexity and entropy plane of Rosso.

Examples:

>>> from skcomplex.core.analysis import entropy
>>> entropy([0, 1, 0, 1]).entropy.tolist()
[1.0]
Source code in src/skcomplex/core/analysis/_entropy.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def entropy(
    source: DataSource,
    *,
    kind: str = 'shannon',
    variables: Sequence[str] | None = None,
    order: float = 2.0,
    base: float = 2.0,
    probabilities: bool = False,
    dimension: int | tuple[int, int] = 3,
    delay: int = 1,
    tolerance: float = 0.2,
    scales: Sequence[int] = tuple(range(1, 11)),
    normalize: bool = True,
    dt: float = 1.0,
    measure: str = 'shannon',
    ties: str = 'order',
    random_state: int | None = None,
    reference: npt.ArrayLike | None = None,
) -> EntropyResult:
    """Return the entropy of every series of a source, or of every frame of a field.

    Entropy measures how unpredictable values are, in bits, such as 1 bit for a series that takes two values equally
    often and 0 for a constant one. The kinds read symbols, patterns, or real values. It measures the disorder of a
    heart rate, a written text, and the configurations of a lattice.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array with one row per time and one column per series, the frames of a field, or the
            outcomes of an ensemble.

        kind:
            What to return. `'shannon'`, `'renyi'`, and `'tsallis'` give the entropy of the distribution of the
            symbols, or of a probability vector with `probabilities=True`, the Rényi order and the Tsallis index given
            by `order`. `'block'`, `'rate'`, and `'excess'` give the block entropies `S_0` to `S_m`, the entropy rate,
            and the excess entropy of the blocks of up to `dimension` symbols, or of square patches of a field.
            `'lempel-ziv'` gives the number of new phrases of the LZ76 parsing. `'permutation'` gives the entropy of the
            ordinal patterns of length `dimension`, or of the windows `(columns, rows)` of a field, measured with
            `measure`. `'sample'` and `'approximate'` give the regularity of patterns of length `dimension`, close
            within `tolerance` standard deviations. `'multiscale'` gives the sample entropy of the means of windows
            that do not overlap, of every scale of `scales`. `'spectral'` gives the Shannon entropy of the normalized
            periodogram. `'ensemble'` gives the Shannon entropy in bits of the outcomes of an ensemble at every frame,
            and their Kullback-Leibler divergence from the `reference` law, as in the H theorem. The ensemble has one
            row per run and one column per frame of integer outcomes, such as `ExperimentResult.get_ensemble` returns.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series, or the first field for a field.

        order:
            The order of the Rényi entropy or the index of the Tsallis entropy.

        base:
            The base of the logarithm, 2 for bits.

        probabilities:
            Whether every series is already a probability vector.

        dimension:
            The length of patterns or the largest block length, or the window `(columns, rows)` of a field.

        delay:
            The number of steps between the values of an ordinal pattern.

        tolerance:
            The largest distance of close patterns, as a fraction of the standard deviation.

        scales:
            The window lengths of the multiscale entropy.

        normalize:
            Whether to divide by the largest value, so the entropy lies between 0 and 1.

        dt:
            The time between samples of the spectral entropy.

        measure:
            The entropy of the ordinal patterns: `'shannon'`, `'renyi'`, or `'tsallis'`.

        ties:
            `'order'` to rank equal values by position, or `'random'` to rank them at random.

        random_state:
            The seed of the random ranks of equal values.

        reference:
            The probability of every outcome under the reference law of an ensemble, such as the stationary law.

    Returns:
        result:
            The values read, their entropy, and the divergence of an ensemble.

    Raises:
        AnalysisError:
            A choice is unknown, a setting the kind does not read is changed, a setting is out of range, or the
            outcomes of an ensemble lie outside the reference law.

    See Also:
        information: Gives the information among series.
        complexity: Places series on the complexity and entropy plane of Rosso.

    Examples:
        >>> from skcomplex.core.analysis import entropy
        >>> entropy([0, 1, 0, 1]).entropy.tolist()
        [1.0]
    """
    _check_choice('entropy', 'kind', kind, KINDS)
    _check_choice('entropy', 'measure', measure, MEASURES)
    _check_choice('entropy', 'ties', ties, TieKind)
    _check_settings(
        entropy,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        order=order,
        base=base,
        probabilities=probabilities,
        dimension=dimension,
        delay=delay,
        tolerance=tolerance,
        scales=scales,
        normalize=normalize,
        dt=dt,
        measure=measure,
        ties=ties,
        random_state=random_state,
        reference=reference,
    )
    if isinstance(dimension, tuple) and kind != 'permutation':
        error_msg = (
            f'entropy has the window dimension={dimension!r}, which only the permutation kind reads. Use one length.'
        )
        raise AnalysisError(error_msg)
    sizes = dimension if isinstance(dimension, tuple) else (dimension,)
    if any(int(size) < 1 for size in sizes) or delay < 1:
        error_msg = f'entropy has dimension={dimension!r} and delay={delay!r}. Use 1 or more.'
        raise AnalysisError(error_msg)
    if kind == 'ensemble' and reference is None:
        error_msg = 'entropy of kind ensemble needs the reference law. Set `reference`.'
        raise AnalysisError(error_msg)
    if tolerance <= 0 or base <= 0 or dt <= 0:
        error_msg = f'entropy has tolerance={tolerance!r}, base={base!r}, and dt={dt!r}. Use positive values.'
        raise AnalysisError(error_msg)
    if kind == 'ensemble':
        return _ensemble_entropy(source, np.asarray(reference, dtype=float))
    if isinstance(dimension, tuple):
        name = variables[0] if variables else None
        frames = _read_fields(source, name)
        values = frames[None] if frames.ndim == SNAPSHOT_DIMENSIONS else frames
        labels = [name or 'field']
        items = list(values)
    else:
        series = _read_series(source, variables)
        values, labels = series.values, series.labels
        items = list(values.T)
    settings = _EntropySpec(
        kind,
        order,
        base,
        probabilities,
        dimension,
        delay,
        tolerance,
        scales,
        normalize,
        dt,
        measure,
        ties,
        random_state,
    )
    result = np.asarray([_compute(item, settings) for item in items], dtype=float)
    return EntropyResult(values, labels, result)

epsilon_machine(source, *, variables=None, max_length=3, significance=0.001)

Return the smallest machine of hidden states that predicts a series of symbols.

It groups the pasts of up to max_length symbols into hidden states, two pasts sharing a state when a chi-square test finds the same chances of the next symbol after both, and splits states until every symbol leads to one next state, the method CSSR. The machine shows how much a series remembers and how random it is. It finds the hidden states of a cellular automaton, of the spikes of a neuron, and of a written text.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array that holds one series of symbols.

required
variables Sequence[str] | None

The variable of a trajectory to read, a list of one name, or None for the only scalar series.

None
max_length int

The longest history, kept well below the logarithm of the series length in the alphabet size.

3
significance float

The significance level of the test that splits a history from a state.

0.001

Returns:

Name Type Description
result EpsilonMachineResult

The series, the causal states with their histories, transitions, and laws, and their entropies.

Raises:

Type Description
AnalysisError

A setting is out of range, the source does not hold one series, or the longest history is not shorter than the series.

See Also

symbolic: Turns a series into symbols and measures their patterns. markov: Fits a chain of moves between observed states.

Examples:

>>> from skcomplex.core.analysis import epsilon_machine
>>> machine = epsilon_machine([0, 0, 1] * 300, max_length=3)
>>> len(machine.histories), round(machine.statistical_complexity, 3), round(machine.entropy_rate, 3)
(3, 1.585, 0.0)
Source code in src/skcomplex/core/analysis/_computational_mechanics.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def epsilon_machine(
    source: DataSource,
    *,
    variables: Sequence[str] | None = None,
    max_length: int = 3,
    significance: float = 0.001,
) -> EpsilonMachineResult:
    """Return the smallest machine of hidden states that predicts a series of symbols.

    It groups the pasts of up to `max_length` symbols into hidden states, two pasts sharing a state when a chi-square
    test finds the same chances of the next symbol after both, and splits states until every symbol leads to one next
    state, the method CSSR. The machine shows how much a series remembers and how random it is. It finds the hidden
    states of a cellular automaton, of the spikes of a neuron, and of a written text.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array that holds one series of symbols.

        variables:
            The variable of a trajectory to read, a list of one name, or `None` for the only scalar series.

        max_length:
            The longest history, kept well below the logarithm of the series length in the alphabet size.

        significance:
            The significance level of the test that splits a history from a state.

    Returns:
        result:
            The series, the causal states with their histories, transitions, and laws, and their entropies.

    Raises:
        AnalysisError:
            A setting is out of range, the source does not hold one series, or the longest history is not shorter than
            the series.

    See Also:
        symbolic: Turns a series into symbols and measures their patterns.
        markov: Fits a chain of moves between observed states.

    Examples:
        >>> from skcomplex.core.analysis import epsilon_machine
        >>> machine = epsilon_machine([0, 0, 1] * 300, max_length=3)
        >>> len(machine.histories), round(machine.statistical_complexity, 3), round(machine.entropy_rate, 3)
        (3, 1.585, 0.0)
    """
    if max_length < 1 or not 0 < significance < 1:
        error_msg = (
            f'epsilon_machine has max_length={max_length!r} and significance={significance!r}. Use a longest history '
            'of 1 or more and a significance between 0 and 1.'
        )
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    if series.values.shape[1] != 1:
        error_msg = (
            f'epsilon_machine reads one series of symbols, but the source has {series.values.shape[1]}. Select one '
            'with `variables`.'
        )
        raise AnalysisError(error_msg)
    values = series.values[:, 0]
    alphabet, codes = np.unique(values, return_inverse=True)
    if not max_length < codes.size:
        error_msg = f'The longest history must be shorter than the series of length {codes.size}. Lower max_length.'
        raise AnalysisError(error_msg)
    codes = codes.astype(np.int64)
    size = alphabet.size
    counts = [_history_counts(codes, length, size) for length in range(max_length + 1)]
    states = _determinize(_homogenize(counts, size, significance), counts[max_length])
    index = {history: number for number, state in enumerate(states) for history in state}
    pooled = np.asarray([_pooled(state, counts) for state in states], dtype=float)
    totals = pooled.sum(axis=1)
    probabilities = pooled / totals[:, None]
    stationary = totals / totals.sum()
    return EpsilonMachineResult(
        values,
        series.labels,
        alphabet,
        tuple(tuple(state) for state in states),
        np.asarray([_transitions(state, counts[max_length], index) for state in states], dtype=np.int64),
        probabilities,
        stationary,
        float(stats.entropy(stationary, base=2)),
        float(stationary @ stats.entropy(probabilities, base=2, axis=1)),
    )

ergodicity(source, *, kind='breaking', variables=None, start=0.01, dt=1.0, bins=None, value_range=None, edges=None, samples=100)

Return whether a time average equals an ensemble average, of one kind.

The ensemble kinds read one row per run and one column per time, such as ExperimentResult.get_ensemble returns, and compare what one run visits over time with what all runs visit, such as a breaking of 0 for two runs that swap between 1 and -1. The density kinds read one long run or a map of the line and give the density it settles to. It asks whether the growth of one fortune, the motion of one gas molecule, or one firing neuron stands for the whole ensemble.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource | Callable[[Array], Array]

The runs of an ensemble, one row per run, for the ensemble kinds, the trajectory or the values of one run for 'invariant-density', or the map, a function of an array of points, for 'ulam'.

required
kind str

What to return. 'breaking' gives the variance across runs of the time averages over the variance of all the values, near 0 for ergodic runs longer than their relaxation time and near 1 when every run is frozen in its own state. 'metric' gives the fluctuation metric of Thirumalai and Mountain, the mean square deviation of the running time averages from their ensemble mean, which decays as 1 / t for ergodic runs and levels off for frozen ones. 'distance' gives the median total variation distance between the values one run visits over time and the values of all runs, after Lesmana et al. (2026), near 0 for ergodic runs and near 1 - p when every run stays in its own state of ensemble weight p. 'invariant-density' gives the histogram density of the values of a long run. 'ulam' gives the Markov chain of a map on the cells between edges by Ulam's method, and the density of its stationary vector.

'breaking'
variables Sequence[str] | None

The variable of a trajectory whose values 'invariant-density' reads, or None for the first one.

None
start float

The fraction of the run after which the exponent of the metric is fitted, at 50 log-spaced times.

0.01
dt float

The time between the columns of the runs.

1.0
bins int | ArrayLike | None

The number of bins or their edges, or None for 20 for 'distance' and 100 for 'invariant-density'.

None
value_range tuple[float, float] | None

The range of the bins, or None for the range of the values.

None
edges ArrayLike | None

The increasing edges of the cells of 'ulam'.

None
samples int

The number of evenly spaced points per cell of 'ulam'.

100

Returns:

Name Type Description
result ErgodicityResult

The values read and the diagnostic of the kind.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a setting is out of range, the edges of the Ulam chain are missing, the map is not callable, or the ensemble has fewer than two runs.

See Also

irreversibility: Measures how far a run is from its reverse in time. markov: Estimates a Markov chain from a run.

Examples:

>>> from skcomplex.core.analysis import ergodicity
>>> runs = [[1.0, -1.0, 1.0, -1.0], [-1.0, 1.0, -1.0, 1.0]]
>>> ergodicity(runs).ergodicity_breaking
0.0
Source code in src/skcomplex/core/analysis/_ergodicity.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def ergodicity(
    source: DataSource | Callable[[Array], Array],
    *,
    kind: str = 'breaking',
    variables: Sequence[str] | None = None,
    start: float = 0.01,
    dt: float = 1.0,
    bins: int | npt.ArrayLike | None = None,
    value_range: tuple[float, float] | None = None,
    edges: npt.ArrayLike | None = None,
    samples: int = 100,
) -> ErgodicityResult:
    """Return whether a time average equals an ensemble average, of one kind.

    The ensemble kinds read one row per run and one column per time, such as `ExperimentResult.get_ensemble` returns,
    and compare what one run visits over time with what all runs visit, such as a breaking of 0 for two runs that swap
    between 1 and -1. The density kinds read one long run or a map of the line and give the density it settles to. It
    asks whether the growth of one fortune, the motion of one gas molecule, or one firing neuron stands for the whole
    ensemble.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The runs of an ensemble, one row per run, for the ensemble kinds, the trajectory or the values of one run
            for `'invariant-density'`, or the map, a function of an array of points, for `'ulam'`.

        kind:
            What to return. `'breaking'` gives the variance across runs of the time averages over the variance of all
            the values, near 0 for ergodic runs longer than their relaxation time and near 1 when every run is frozen
            in its own state. `'metric'` gives the fluctuation metric of Thirumalai and Mountain, the mean square
            deviation of the running time averages from their ensemble mean, which decays as `1 / t` for ergodic runs
            and levels off for frozen ones. `'distance'` gives the median total variation distance between the values
            one run visits over time and the values of all runs, after Lesmana et al. (2026), near 0 for ergodic runs
            and near `1 - p` when every run stays in its own state of ensemble weight `p`. `'invariant-density'` gives
            the histogram density of the values of a long run. `'ulam'` gives the Markov chain of a map on the cells
            between `edges` by Ulam's method, and the density of its stationary vector.

        variables:
            The variable of a trajectory whose values `'invariant-density'` reads, or `None` for the first one.

        start:
            The fraction of the run after which the exponent of the metric is fitted, at 50 log-spaced times.

        dt:
            The time between the columns of the runs.

        bins:
            The number of bins or their edges, or `None` for 20 for `'distance'` and 100 for `'invariant-density'`.

        value_range:
            The range of the bins, or `None` for the range of the values.

        edges:
            The increasing edges of the cells of `'ulam'`.

        samples:
            The number of evenly spaced points per cell of `'ulam'`.

    Returns:
        result:
            The values read and the diagnostic of the kind.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a setting is out of range, the edges of
            the Ulam chain are missing, the map is not callable, or the ensemble has fewer than two runs.

    See Also:
        irreversibility: Measures how far a run is from its reverse in time.
        markov: Estimates a Markov chain from a run.

    Examples:
        >>> from skcomplex.core.analysis import ergodicity
        >>> runs = [[1.0, -1.0, 1.0, -1.0], [-1.0, 1.0, -1.0, 1.0]]
        >>> ergodicity(runs).ergodicity_breaking
        0.0
    """
    _check_choice('ergodicity', 'kind', kind, KINDS)
    _check_settings(
        ergodicity,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        start=start,
        dt=dt,
        bins=bins,
        value_range=value_range,
        edges=edges,
        samples=samples,
    )
    if kind == 'ulam' and edges is None:
        error_msg = f'ergodicity of kind {kind!r} needs the edges of the cells. Give edges.'
        raise AnalysisError(error_msg)
    if samples < 1 or dt <= 0:
        error_msg = f'ergodicity has samples={samples!r} and dt={dt!r}. Use positive values.'
        raise AnalysisError(error_msg)
    if kind == 'ulam':
        if not callable(source):
            error_msg = (
                f'ergodicity of kind ulam reads a map, not {type(source).__name__}. Pass a function of an array of '
                'points.'
            )
            raise AnalysisError(error_msg)
        return _ulam(source, np.asarray(edges, dtype=float), samples)
    if callable(source):
        error_msg = f'ergodicity of kind {kind!r} reads data, not a function.'
        raise AnalysisError(error_msg)
    if kind == 'invariant-density':
        values = _read_series(source, variables).values[:, 0].astype(float)
        count = BINS['invariant-density'] if bins is None else bins
        density, found = np.histogram(values, bins=count, range=value_range, density=True)
        return ErgodicityResult(values=values, edges=found, density=density)
    runs = np.asarray(source, dtype=float)
    times = np.arange(1, runs.shape[-1] + 1) * dt
    if runs.ndim != ENSEMBLE_DIMENSIONS or runs.shape[0] < MIN_RUNS:
        error_msg = f'The diagnostics need at least two runs, one row per run, not an array of shape {runs.shape}.'
        raise AnalysisError(error_msg)
    if kind == 'breaking':
        spread = float(runs.var())
        breaking = float(runs.mean(axis=1).var() / spread) if spread > 0 else 0.0
        return ErgodicityResult(values=runs, times=times, ergodicity_breaking=breaking)
    if kind == 'metric':
        metric = (np.cumsum(runs, axis=1) / np.arange(1, runs.shape[1] + 1)).var(axis=0)
        spaced = np.unique(np.geomspace(max(int(start * times.size), 1), times.size, FIT_POINTS).astype(int) - 1)
        fitted = spaced[(times[spaced] > 0) & (metric[spaced] > 0)]
        exponent = float(np.polyfit(np.log(times[fitted]), np.log(metric[fitted]), 1)[0]) if fitted.size > 1 else 0.0
        return ErgodicityResult(values=runs, times=times, metric=metric, exponent=exponent)
    found = np.histogram_bin_edges(runs, bins=BINS['distance'] if bins is None else bins)
    ensemble = np.histogram(runs, bins=found)[0] / runs.size
    distances = [0.5 * np.abs(np.histogram(run, bins=found)[0] / run.size - ensemble).sum() for run in runs]
    return ErgodicityResult(values=runs, times=times, ergodicity_distance=float(np.median(distances)))

events(source, *, kind='detect', variables=None, threshold=0.0, window=None, start=0.0, end=None, max_step=40, dt=1.0)

Return the events of one series or of event times, of one kind.

An event is a run of consecutive values above a threshold, such as the bursts of sizes 4 and 2 in [0, 3, 1, 0, 0, 2, 0], with the waiting time between them. Times are the times of a trajectory, and the step indices of an array. It finds the crashes of a market, the spikes of a neuron, the avalanches of a sandpile, and the floods of a river.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array that holds one series, or one column per trial for 'branching', the times of the events for 'counts', or records of excursions for 'excursions'.

required
kind str

What to return. 'detect' gives every maximal run of values above threshold, with its start, size, duration, and peak, and the waiting times between runs. 'counts' gives the number of events in consecutive windows of length window, from the times of the events or the jump times of a discrete state of a trajectory. 'laminar-durations' gives the durations of the complete runs of values within threshold of 0 between two bursts, the quiet phases of on and off intermittency. 'excursions' gives the profile of every run above threshold, its values minus the threshold, with its size, the sum of the profile, and its duration, the number of its samples. Records with a size and a duration, such as the cascade records of a lattice, are excursions already. 'branching' gives the branching ratio by the multistep regression of mrestimator, which fits r_k ∝ m^k to the slopes r_k of the values k steps apart and stays unbiased when only some of the units are observed, with every series one trial.

'detect'
variables Sequence[str] | None

The one variable of a trajectory to read, or None for the only scalar series or discrete state.

None
threshold float

The value an event must exceed, or the largest absolute value of a laminar phase.

0.0
window float | None

The length of every window of 'counts'.

None
start float

The start of the first window.

0.0
end float | None

The end of the last full window, or None for the last event.

None
max_step int

The largest step k of the regression of the branching ratio.

40
dt float

The duration of a step of the branching ratio.

1.0

Returns:

Name Type Description
result EventsResult

The values read and the events, counts, durations, excursions, or branching ratio of the kind.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a setting is out of range, or the source does not suit the kind.

See Also

distribution: Fits the distribution of the sizes or the waiting times. fit_law: Fits a power law to the sizes of avalanches.

Examples:

>>> from skcomplex.core.analysis import events
>>> found = events([0, 3, 1, 0, 0, 2, 0])
>>> found.sizes.tolist(), found.durations.tolist(), found.waiting_times.tolist()
([4.0, 2.0], [2.0, 1.0], [2.0])
Source code in src/skcomplex/core/analysis/_events.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def events(
    source: DataSource,
    *,
    kind: str = 'detect',
    variables: Sequence[str] | None = None,
    threshold: float = 0.0,
    window: float | None = None,
    start: float = 0.0,
    end: float | None = None,
    max_step: int = 40,
    dt: float = 1.0,
) -> EventsResult:
    """Return the events of one series or of event times, of one kind.

    An event is a run of consecutive values above a threshold, such as the bursts of sizes 4 and 2 in
    `[0, 3, 1, 0, 0, 2, 0]`, with the waiting time between them. Times are the times of a trajectory, and the step
    indices of an array. It finds the crashes of a market, the spikes of a neuron, the avalanches of a sandpile, and
    the floods of a river.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array that holds one series, or one column per trial for `'branching'`, the times of the
            events for `'counts'`, or records of excursions for `'excursions'`.

        kind:
            What to return. `'detect'` gives every maximal run of values above `threshold`, with its start, size,
            duration, and peak, and the waiting times between runs. `'counts'` gives the number of events in
            consecutive windows of length `window`, from the times of the events or the jump times of a discrete
            state of a trajectory. `'laminar-durations'` gives the durations of the complete runs of values within
            `threshold` of 0 between two bursts, the quiet phases of on and off intermittency. `'excursions'` gives the
            profile of every run above `threshold`, its values minus the threshold, with its size, the sum of the
            profile, and its duration, the number of its samples. Records with a `size` and a `duration`, such as the
            cascade records of a lattice, are excursions already. `'branching'` gives the branching ratio by the
            multistep regression of `mrestimator`, which fits `r_k ∝ m^k` to the slopes `r_k` of the values `k` steps
            apart and stays unbiased when only some of the units are observed, with every series one trial.

        variables:
            The one variable of a trajectory to read, or `None` for the only scalar series or discrete state.

        threshold:
            The value an event must exceed, or the largest absolute value of a laminar phase.

        window:
            The length of every window of `'counts'`.

        start:
            The start of the first window.

        end:
            The end of the last full window, or `None` for the last event.

        max_step:
            The largest step `k` of the regression of the branching ratio.

        dt:
            The duration of a step of the branching ratio.

    Returns:
        result:
            The values read and the events, counts, durations, excursions, or branching ratio of the kind.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a setting is out of range, or the source
            does not suit the kind.

    See Also:
        distribution: Fits the distribution of the sizes or the waiting times.
        fit_law: Fits a power law to the sizes of avalanches.

    Examples:
        >>> from skcomplex.core.analysis import events
        >>> found = events([0, 3, 1, 0, 0, 2, 0])
        >>> found.sizes.tolist(), found.durations.tolist(), found.waiting_times.tolist()
        ([4.0, 2.0], [2.0, 1.0], [2.0])
    """
    _check_choice('events', 'kind', kind, KINDS)
    _check_settings(
        events,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        threshold=threshold,
        window=window,
        start=start,
        end=end,
        max_step=max_step,
        dt=dt,
    )
    _check(kind, window, max_step, dt)
    records = _records(source)
    if records:
        if kind != 'excursions':
            error_msg = 'events reads records of excursions for the kind excursions only.'
            raise AnalysisError(error_msg)
        return EventsResult(
            None,
            None,
            ['cascades'],
            sizes=np.asarray([record.size for record in records], dtype=np.float64),
            durations=np.asarray([record.duration for record in records], dtype=np.float64),
            shapes=[],
        )
    name = variables[0] if variables else None
    if kind == 'counts':
        if isinstance(source, Trajectory):
            path = _read_path(source, name)
            times, labels = path.times[1:], [path.label]
        else:
            times, labels = np.asarray(source, dtype=float), [name or 'events']
        counts = _event_counts(times, float(window or 0), start, end)
        return EventsResult(times, times[:, None], labels, counts=counts)
    series = _read_series(source, variables)
    if series.values.shape[1] != 1 and kind != 'branching':
        error_msg = (
            f'events reads one series, but the source has {series.values.shape[1]}: {", ".join(series.labels)}. Pick '
            'one with `variables`.'
        )
        raise AnalysisError(error_msg)
    times, values, labels = np.asarray(series.times, dtype=float), series.values, series.labels
    if kind == 'excursions':
        shapes = _excursions(np.asarray(values[:, 0], dtype=np.float64), threshold)
        return EventsResult(
            times,
            values,
            labels,
            sizes=np.asarray([shape.sum() for shape in shapes], dtype=np.float64),
            durations=np.asarray([shape.size for shape in shapes], dtype=np.float64),
            shapes=shapes,
        )
    if kind == 'branching':
        ratio = _branching_ratio(np.asarray(values, dtype=np.float64), max_step, dt)
        return EventsResult(times, values, labels, branching_ratio=ratio)
    array = _read_real(values[:, 0], 'values')
    if kind == 'laminar-durations':
        return EventsResult(times, values, labels, durations=_laminar_durations(array, times, threshold))
    starts, sizes, durations, peaks, waiting_times = _detect_events(array, times, threshold)
    return EventsResult(
        times,
        values,
        labels,
        starts=starts,
        sizes=sizes,
        durations=durations,
        peaks=peaks,
        waiting_times=waiting_times,
    )

fit_law(source, *, law='power', variables=None, group=None, minimum=None, maximum=None, discrete=False, bootstrap=100, candidates=50, compare_with=ALTERNATIVES, block=None, fixed=None, simulations=199, random_state=0)

Return the law fitted to the values of a source, pooled into one sample.

It pools the series of a trajectory or an array, or the speeds of the agents of a trajectory at every frame, into one sample and fits the law to it, such as an exponent near 2.5 for samples drawn from p(x) ∝ x^-2.5. It tests whether the sizes of earthquakes, cities, or firms follow a power law, and whether the energies of a gas or the money of traders are exponential.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of samples.

required
law str

The law to fit. 'power' fits p(x) ∝ x^-alpha to the tail of the positive samples by maximum likelihood, with the method of Clauset, Shalizi, and Newman. The lower cutoff makes the Kolmogorov-Smirnov distance between the tail and the fit smallest, unless minimum fixes it. The goodness of fit is the share of bootstrap samples whose distance exceeds that of the data, and the law is compared with every alternative of compare_with by a likelihood ratio test. Discrete samples use the exact discrete likelihood, and the warnings of powerlaw about its optimiser are silenced. 'stable' fits the Lévy stable law by the quantile method of McCulloch, in the S1 parameters of SciPy. 'extreme-value' fits the generalized extreme value law by maximum likelihood to the maxima of blocks of block samples. 'exponential', 'normal', 'lognormal', 'gamma', 'maxwell', 'rayleigh', and 'uniform' fit the free parameters of the named law and test it with a Monte Carlo Kolmogorov-Smirnov test that accounts for the fit.

'power'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series.

None
group str | None

The path of the agent or particle group whose speeds are read, or None for the series of a trajectory, or the first group of a trajectory without series.

None
minimum float | None

A fixed lower cutoff of the power law, or None to choose it.

None
maximum float | None

A fixed upper cutoff of the power law, or None for none.

None
discrete bool

Whether the samples of the power law are integers, such as avalanche sizes.

False
bootstrap int

The number of bootstrap samples for the p-value of the power law, 0 for none.

100
candidates int

The largest number of lower cutoffs tried.

50
compare_with Sequence[str]

The alternatives the power law is compared with, among 'exponential', 'lognormal', 'stretched_exponential', and 'truncated_power_law'.

ALTERNATIVES
block int | None

The number of samples per block of the extreme-value law.

None
fixed Mapping[str, float] | None

The parameters of a named law held fixed by SciPy name, such as {'loc': 0}, or None to fit all.

None
simulations int

The number of Monte Carlo samples of the null distribution of a named law.

199
random_state int | None

The seed of the bootstrap of the power law and of the Monte Carlo samples of a named law.

0

Returns:

Name Type Description
result FitLawResult

The pooled sample and the fitted law.

Raises:

Type Description
AnalysisError

The law or an alternative is unknown, a setting the law does not read is changed, a needed setting is missing, or the sample is too small for the fit.

See Also

distribution: Measures the shape of a distribution without fitting a law. scaling: Fits how a measure grows with the size of a sample.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import fit_law
>>> samples = (1 - np.random.default_rng(0).random(5000)) ** (-1 / 1.5)
>>> round(fit_law(samples, law='power', minimum=1.0, bootstrap=0).exponent, 1)
2.5
Source code in src/skcomplex/core/analysis/_fit.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def fit_law(
    source: DataSource,
    *,
    law: str = 'power',
    variables: Sequence[str] | None = None,
    group: str | None = None,
    minimum: float | None = None,
    maximum: float | None = None,
    discrete: bool = False,
    bootstrap: int = 100,
    candidates: int = 50,
    compare_with: Sequence[str] = ALTERNATIVES,
    block: int | None = None,
    fixed: Mapping[str, float] | None = None,
    simulations: int = 199,
    random_state: int | None = 0,
) -> FitLawResult:
    """Return the law fitted to the values of a source, pooled into one sample.

    It pools the series of a trajectory or an array, or the speeds of the agents of a trajectory at every frame, into
    one sample and fits the law to it, such as an exponent near 2.5 for samples drawn from `p(x) ∝ x^-2.5`. It tests
    whether the sizes of earthquakes, cities, or firms follow a power law, and whether the energies of a gas or the
    money of traders are exponential.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of samples.

        law:
            The law to fit. `'power'` fits `p(x) ∝ x^-alpha` to the tail of the positive samples by maximum likelihood,
            with the method of Clauset, Shalizi, and Newman. The lower cutoff makes the Kolmogorov-Smirnov distance
            between the tail and the fit smallest, unless `minimum` fixes it. The goodness of fit is the share of
            `bootstrap` samples whose distance exceeds that of the data, and the law is compared with every alternative
            of `compare_with` by a likelihood ratio test. Discrete samples use the exact discrete likelihood, and the
            warnings of `powerlaw` about its optimiser are silenced. `'stable'` fits the Lévy stable law by the quantile
            method of McCulloch, in the `S1` parameters of SciPy. `'extreme-value'` fits the generalized extreme value
            law by maximum likelihood to the maxima of blocks of `block` samples. `'exponential'`, `'normal'`,
            `'lognormal'`, `'gamma'`, `'maxwell'`, `'rayleigh'`, and `'uniform'` fit the free parameters of the named
            law and test it with a Monte Carlo Kolmogorov-Smirnov test that accounts for the fit.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series.

        group:
            The path of the agent or particle group whose speeds are read, or `None` for the series of a trajectory, or
            the first group of a trajectory without series.

        minimum:
            A fixed lower cutoff of the power law, or `None` to choose it.

        maximum:
            A fixed upper cutoff of the power law, or `None` for none.

        discrete:
            Whether the samples of the power law are integers, such as avalanche sizes.

        bootstrap:
            The number of bootstrap samples for the p-value of the power law, 0 for none.

        candidates:
            The largest number of lower cutoffs tried.

        compare_with:
            The alternatives the power law is compared with, among `'exponential'`, `'lognormal'`,
            `'stretched_exponential'`, and `'truncated_power_law'`.

        block:
            The number of samples per block of the extreme-value law.

        fixed:
            The parameters of a named law held fixed by SciPy name, such as `{'loc': 0}`, or `None` to fit all.

        simulations:
            The number of Monte Carlo samples of the null distribution of a named law.

        random_state:
            The seed of the bootstrap of the power law and of the Monte Carlo samples of a named law.

    Returns:
        result:
            The pooled sample and the fitted law.

    Raises:
        AnalysisError:
            The law or an alternative is unknown, a setting the law does not read is changed, a needed setting is
            missing, or the sample is too small for the fit.

    See Also:
        distribution: Measures the shape of a distribution without fitting a law.
        scaling: Fits how a measure grows with the size of a sample.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import fit_law
        >>> samples = (1 - np.random.default_rng(0).random(5000)) ** (-1 / 1.5)
        >>> round(fit_law(samples, law='power', minimum=1.0, bootstrap=0).exponent, 1)
        2.5
    """
    if law not in LAWS:
        error_msg = f'fit_law has law={law!r}. Use one of {", ".join(LAWS)}.'
        raise AnalysisError(error_msg)
    unknown = [name for name in compare_with if name not in ALTERNATIVES]
    if unknown:
        error_msg = f'fit_law has compare_with={compare_with!r}. Use some of {", ".join(ALTERNATIVES)}.'
        raise AnalysisError(error_msg)
    _check_settings(
        fit_law,
        'law',
        SETTINGS[law] | {'variables', 'group'},
        law=law,
        variables=variables,
        group=group,
        minimum=minimum,
        maximum=maximum,
        discrete=discrete,
        bootstrap=bootstrap,
        candidates=candidates,
        compare_with=compare_with,
        block=block,
        fixed=fixed,
        simulations=simulations,
        random_state=random_state,
    )
    if law == 'extreme-value' and block is None:
        error_msg = f'fit_law of law {law!r} needs the number of samples per block. Set `block`.'
        raise AnalysisError(error_msg)
    series = _read_samples_of(source, variables, group)
    values = _read_real(series.values, 'values').ravel()
    labels = series.labels
    if law == 'power':
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', module=r'powerlaw\.')
            return _fit_power(
                values,
                labels,
                minimum,
                maximum,
                discrete=discrete,
                bootstrap=bootstrap,
                candidates=candidates,
                compare_with=compare_with,
                random_state=random_state,
            )
    if law == 'stable':
        index, skewness, location, scale = stats.levy_stable.fit(values, optimizer=_starting_point)
        return FitLawResult(
            values,
            labels,
            index=float(index),
            skewness=float(skewness),
            location=float(location),
            scale=float(scale),
        )
    if law == 'extreme-value':
        return _fit_extreme_value(values, labels, block)
    result = stats.goodness_of_fit(
        NAMED_LAWS[law],
        values,
        known_params=dict(fixed or {}),
        statistic='ks',
        n_mc_samples=simulations,
        rng=np.random.default_rng(random_state),
    )
    return FitLawResult(
        values,
        labels,
        statistic=float(result.statistic),
        p_value=float(result.pvalue),
        parameters={name: float(value) for name, value in result.fit_result.params._asdict().items()},
    )

information(source, *, kind='mutual', variables=None, symbols=None, bins=2, order=3, delay=1, history=1, lag=1, max_delay=100, dimension=8, estimator='plugin', k=3, base=2.0)

Return the information among the series of a source, of one kind.

Information counts in bits how much knowing one series tells about another, about its own future, or how much all series share, such as the 1 bit that a coin flip passes to a copy of it one step later. Every kind but 'kl-divergence' reads the series as symbols, or first turns them into symbols with symbols. It measures the flow of information between regions of the brain, between markets, and between the members of a flock.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array with one row per time and one column per series.

required
kind str

What to return. 'mutual' gives the mutual information H(X) + H(Y) - H(X, Y) of every pair of series, by counts of symbols. 'transfer' gives the transfer entropy H(Y_t | Y_past) - H(Y_t | Y_past, X_{t-lag}) from every series to every series, the target conditioned on history past values, by counts or by the Kraskov, Stögbauer, and Grassberger estimate of k neighbours. 'kl-divergence' gives the Kullback-Leibler divergence of every series, a probability vector, from every series. 'auto-mutual' gives the mutual information of every series with itself delayed by 0 to max_delay steps. 'active-storage' gives the information the past history values of every series hold about its next value. 'correlation-information' gives the correlation information of Lindgren, k_m = ΔS_{m-1} - ΔS_m, of every series for block lengths 2 to dimension. 'total-correlation' gives the information all series share at any order, 'dual-total-correlation' the information two or more of them share, and 'o-information' their difference, positive for redundancy and negative for synergy, by counts with dit, the closed form of a fitted Gaussian, or chains of neighbour estimates. 'o-information-gradients' gives the O-information every series adds to the others.

'mutual'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series.

None
symbols str | None

None to read the series as symbols, 'bins' for bins bins of equal width, 'quantiles' for bins equally populated bins, or 'ordinal' for the rank pattern of every order values spaced by delay steps.

None
bins int

The number of symbols of bins and quantiles.

2
order int

The length of ordinal patterns.

3
delay int

The number of steps between the values of an ordinal pattern.

1
history int

The number of past values of the target of the transfer entropy, or of the series of the storage.

1
lag int

The delay of the source of the transfer entropy.

1
max_delay int

The largest delay of the auto mutual information.

100
dimension int

The largest block length of the correlation information.

8
estimator str

'plugin' for counts of symbols, 'gaussian' for a fitted Gaussian, or 'knn' for nearest neighbours.

'plugin'
k int

The number of neighbours of the 'knn' estimator.

3
base float

The base of the logarithm, 2 for bits.

2.0

Returns:

Name Type Description
result InformationResult

The series, their symbols, and the information among them.

Raises:

Type Description
AnalysisError

A choice is unknown, a setting the kind does not read is changed, or a setting is out of range.

See Also

partial_information: Splits the information of two sources into unique, shared, and synergistic parts. local_information: Gives the information at every time step. entropy: Measures how unpredictable a series is.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import information
>>> x = np.random.default_rng(0).integers(0, 2, 10000)
>>> transfer = information(np.column_stack([x, np.roll(x, 1)]), kind='transfer')
>>> transfer.information.round(1).tolist()
[[nan, 1.0], [0.0, nan]]
Source code in src/skcomplex/core/analysis/_information.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def information(
    source: DataSource,
    *,
    kind: str = 'mutual',
    variables: Sequence[str] | None = None,
    symbols: str | None = None,
    bins: int = 2,
    order: int = 3,
    delay: int = 1,
    history: int = 1,
    lag: int = 1,
    max_delay: int = 100,
    dimension: int = 8,
    estimator: str = 'plugin',
    k: int = 3,
    base: float = 2.0,
) -> InformationResult:
    """Return the information among the series of a source, of one kind.

    Information counts in bits how much knowing one series tells about another, about its own future, or how much all
    series share, such as the 1 bit that a coin flip passes to a copy of it one step later. Every kind but
    `'kl-divergence'` reads the series as symbols, or first turns them into symbols with `symbols`. It measures the
    flow of information between regions of the brain, between markets, and between the members of a flock.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array with one row per time and one column per series.

        kind:
            What to return. `'mutual'` gives the mutual information `H(X) + H(Y) - H(X, Y)` of every pair of series, by
            counts of symbols. `'transfer'` gives the transfer entropy `H(Y_t | Y_past) - H(Y_t | Y_past, X_{t-lag})`
            from every series to every series, the target conditioned on `history` past values, by counts or by the
            Kraskov, Stögbauer, and Grassberger estimate of `k` neighbours. `'kl-divergence'` gives the Kullback-Leibler
            divergence of every series, a probability vector, from every series. `'auto-mutual'` gives the mutual
            information of every series with itself delayed by 0 to `max_delay` steps. `'active-storage'` gives the
            information the past `history` values of every series hold about its next value.
            `'correlation-information'` gives the correlation information of Lindgren, `k_m = ΔS_{m-1} - ΔS_m`, of
            every series for block lengths 2 to `dimension`. `'total-correlation'` gives the information all series
            share at any order, `'dual-total-correlation'` the information two or more of them share, and
            `'o-information'` their difference, positive for redundancy and negative for synergy, by counts with
            `dit`, the closed form of a fitted Gaussian, or chains of neighbour estimates. `'o-information-gradients'`
            gives the O-information every series adds to the others.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series.

        symbols:
            `None` to read the series as symbols, `'bins'` for `bins` bins of equal width, `'quantiles'` for `bins`
            equally populated bins, or `'ordinal'` for the rank pattern of every `order` values spaced by `delay` steps.

        bins:
            The number of symbols of bins and quantiles.

        order:
            The length of ordinal patterns.

        delay:
            The number of steps between the values of an ordinal pattern.

        history:
            The number of past values of the target of the transfer entropy, or of the series of the storage.

        lag:
            The delay of the source of the transfer entropy.

        max_delay:
            The largest delay of the auto mutual information.

        dimension:
            The largest block length of the correlation information.

        estimator:
            `'plugin'` for counts of symbols, `'gaussian'` for a fitted Gaussian, or `'knn'` for nearest neighbours.

        k:
            The number of neighbours of the `'knn'` estimator.

        base:
            The base of the logarithm, 2 for bits.

    Returns:
        result:
            The series, their symbols, and the information among them.

    Raises:
        AnalysisError:
            A choice is unknown, a setting the kind does not read is changed, or a setting is out of range.

    See Also:
        partial_information: Splits the information of two sources into unique, shared, and synergistic parts.
        local_information: Gives the information at every time step.
        entropy: Measures how unpredictable a series is.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import information
        >>> x = np.random.default_rng(0).integers(0, 2, 10000)
        >>> transfer = information(np.column_stack([x, np.roll(x, 1)]), kind='transfer')
        >>> transfer.information.round(1).tolist()
        [[nan, 1.0], [0.0, nan]]
    """
    _check_choice('information', 'kind', kind, KINDS)
    _check_choice('information', 'symbols', symbols, (None, *SYMBOLS))
    _check_settings(
        information,
        'kind',
        SETTINGS[kind] | SYMBOL_SETTINGS[symbols] | {'variables'},
        kind=kind,
        variables=variables,
        symbols=symbols,
        bins=bins,
        order=order,
        delay=delay,
        history=history,
        lag=lag,
        max_delay=max_delay,
        dimension=dimension,
        estimator=estimator,
        k=k,
        base=base,
    )
    estimators = TRANSFER_ESTIMATORS if kind == 'transfer' else JOINT_ESTIMATORS
    _check_choice('information', 'estimator', estimator, estimators)
    counts = {'bins': bins, 'order': order, 'delay': delay, 'history': history, 'lag': lag, 'k': k}
    small = [f'{name}={value!r}' for name, value in counts.items() if value < 1]
    if small:
        error_msg = f'information has {", ".join(small)}. Use 1 or more.'
        raise AnalysisError(error_msg)
    if max_delay < 0 or dimension < MIN_DIMENSION or base <= 0:
        error_msg = (
            f'information has max_delay={max_delay!r}, dimension={dimension!r}, and base={base!r}. Use a max_delay '
            'of 0 or more, a dimension of 2 or more, and a positive base.'
        )
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    columns: AnyArray = series.values
    if symbols is not None:
        columns = np.column_stack(
            [_symbolize(column, symbols, bins, order=order, delay=delay) for column in series.values.T],
        )
    measure: float | Array
    if kind in PAIRWISE:
        measure = np.asarray(
            [
                [
                    _compute_pair(
                        kind,
                        first,
                        second,
                        history=history,
                        lag=lag,
                        estimator=estimator,
                        k=k,
                        base=base,
                        same=row == column,
                    )
                    for column, second in enumerate(columns.T)
                ]
                for row, first in enumerate(columns.T)
            ],
            dtype=float,
        )
    elif kind in JOINT:
        measure = _compute_joint(kind, columns, estimator, k, base)
    else:
        measure = np.asarray(
            [
                _compute_series(kind, column, max_delay=max_delay, history=history, dimension=dimension, base=base)
                for column in columns.T
            ],
            dtype=float,
        )
    return InformationResult(series.values, series.labels, columns, measure)

invariants(source, *, expressions=(), samples=16, random_state=None)

Return the rates of expressions of a system and whether they are conserved.

The rate df/dt of an expression f is its derivative along the equations of the system, diff(f, t) + sum df/dx x'. An expression is conserved when its rate simplifies to zero, or, when simplification does not decide, when the rate is zero within a tolerance at random states with the parameters at their values, such as the energy x² + x'² of a unit spring. The expressions are Observables whose expression is a function of the namespace of the system, where s.<element>.<state> is the symbol of a state. It finds the conserved energy of a pendulum, the conserved total of an epidemic, and the conserved money of an exchange economy.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, or a trajectory of it.

required
expressions Sequence[Observable]

The expressions to check.

()
samples int

The number of random states of the numeric check.

16
random_state int | Generator | None

The seed or generator of the random states.

None

Returns:

Name Type Description
result InvariantsResult

The rates of the expressions and whether they are conserved.

Raises:

Type Description
AnalysisError

The source is not a system, the system is not an ODE, or an expression or the number of samples is invalid.

See Also

stability: Finds the fixed points of a system and whether they are stable. symbolic: Derives the equations of a system as symbolic expressions.

Examples:

>>> from skcomplex.core.analysis import invariants
>>> from skcomplex.core.components import Observable
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> energy = Observable('energy', lambda s: s.mass.x**2 + s.mass.x_d1**2)
>>> invariants(HarmonicOscillatorSystem(), expressions=[energy]).conserved
{'energy': True}
Source code in src/skcomplex/core/analysis/_invariants.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def invariants(
    source: DataSource,
    *,
    expressions: Sequence[Observable] = (),
    samples: int = 16,
    random_state: int | np.random.Generator | None = None,
) -> InvariantsResult:
    """Return the rates of expressions of a system and whether they are conserved.

    The rate `df/dt` of an expression `f` is its derivative along the equations of the system, `diff(f, t) + sum
    df/dx x'`. An expression is conserved when its rate simplifies to zero, or, when simplification does not decide,
    when the rate is zero within a tolerance at random states with the parameters at their values, such as the energy
    `x² + x'²` of a unit spring. The expressions are `Observable`s whose expression is a function of the namespace of
    the system, where `s.<element>.<state>` is the symbol of a state. It finds the conserved energy of a pendulum, the
    conserved total of an epidemic, and the conserved money of an exchange economy.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, or a trajectory of it.

        expressions:
            The expressions to check.

        samples:
            The number of random states of the numeric check.

        random_state:
            The seed or generator of the random states.

    Returns:
        result:
            The rates of the expressions and whether they are conserved.

    Raises:
        AnalysisError:
            The source is not a system, the system is not an ODE, or an expression or the number of samples is
            invalid.

    See Also:
        stability: Finds the fixed points of a system and whether they are stable.
        symbolic: Derives the equations of a system as symbolic expressions.

    Examples:
        >>> from skcomplex.core.analysis import invariants
        >>> from skcomplex.core.components import Observable
        >>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
        >>> energy = Observable('energy', lambda s: s.mass.x**2 + s.mass.x_d1**2)
        >>> invariants(HarmonicOscillatorSystem(), expressions=[energy]).conserved
        {'energy': True}
    """
    _check_inputs(expressions, samples)
    system = _get_system(source)
    declared = _read_system(system)
    if not isinstance(system, System) or not isinstance(declared, _CompositeSystem):
        error_msg = (
            f'Invariants are derived from the interactions of a system, not from {type(declared).__name__}. Give the '
            'system.'
        )
        raise AnalysisError(error_msg)
    dynamics = StabilityResult._get_dynamics_of(declared)
    namespace = ObservableEvaluator._get_namespace_of(dynamics.problem)
    rng = np.random.default_rng(random_state)
    rates, conserved, methods = {}, {}, {}
    for expression in expressions:
        value = _evaluate(namespace, expression)
        terms = [value.diff(SR(dynamics.problem.time))]
        terms += [value.diff(item) * rate for item, rate in zip(dynamics.symbols, dynamics.rates, strict=True)]
        rate, is_conserved, method = _decide(dynamics, terms, rng, samples)
        rates[expression.label] = rate
        conserved[expression.label], methods[expression.label] = is_conserved, method
    return InvariantsResult(dynamics.problem, system, dynamics, namespace, rates, conserved, methods)

irreversibility(source, *, kind='entropy-production', variables=None, rates=None, duration=None, drive=1.0, intensity=1.0, dt=1.0, n_states=None, significance=0.05, bins=40, entropy=None, resamples=200, random_state=None, unperturbed=None, field=1.0, correlation=None)

Return the irreversibility of a process, of one kind.

A process is reversible when a film of it run backwards is as likely as the film run forwards. The kinds read a rate matrix, jump paths, Langevin paths, samples, or ensembles, and give how much entropy the process produces, whether its transitions balance, or how it responds to a field, such as an entropy production of ln 2 for a ring of five states that steps forward twice as often as back. It measures how far molecular motors, heart beats, and the prices of a market are from equilibrium.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The rate matrix, the trajectory or an array of paths, one row per path, the samples, or the ensemble the kind measures.

required
kind str

What to return. 'entropy-production' gives the stationary entropy production rate of a jump process from its rate matrix, Σ_{i<j} (p_i k_ij - p_j k_ji) ln(p_i k_ij / (p_j k_ji)), 0 under detailed balance. 'jump-entropy-production' gives the entropy every jump path produces in the medium, Σ ln(k_ij / k_ji) over its jumps with the rates, and the mean rate over the duration of the paths. 'langevin-entropy-production' gives the entropy every overdamped Langevin path produces, the work of the drive times the intensity, b ∫ F(x) ∘ dx, and the mean rate. 'count-entropy-production' gives the entropy production rate of a discrete path from its transition counts alone, Σ_{i<j} (N_ij - N_ji) ln(N_ij / N_ji) per unit time. 'detailed-balance' gives the chi-squared test of detailed balance on the transition counts of discrete paths. 'fluctuation-theorem' gives the log ratio of the probabilities of producing s and -s from samples of the entropy, and its slope against s, 1 when the theorem holds. 'uncertainty-relation' gives the squared relative fluctuation Var(J) / ⟨J⟩² of samples of an integrated current times the mean entropy produced over the same duration, at least 2 (Barato and Seifert 2015). 'response' gives the integrated response chi(t) = (<x(t)>_h - <x(t)>_0) / h of an ensemble with the field against the unperturbed ensemble. 'fluctuation-dissipation' gives the response and the slope of chi / b against C(t_w, t_w) - C(t, t_w) of the two-time correlation over the same lags, 1 in equilibrium and below 1 in an aging system.

'entropy-production'
variables Sequence[str] | None

The discrete state or the position of a trajectory to read, or None for the first one.

None
rates ArrayLike | None

The rate of every jump, one row per origin.

None
duration float | None

The duration of every jump path, or None for the duration of a trajectory.

None
drive Callable[[Array], Array] | float

The drift along a Langevin path, a function of position or a constant.

1.0
intensity float

The factor b of the work of the drive in the entropy, and one over the factor of the response in the fluctuation-dissipation ratio, as in the acceptance exp(-intensity * change) of sampling.

1.0
dt float

The time between frames of Langevin paths, or between records of a discrete path.

1.0
n_states int | None

The number of states, or None for the largest state plus one.

None
significance float

The level below which the p-value rejects detailed balance.

0.05
bins int

The number of bins of entropy, symmetric about 0.

40
entropy float | None

The mean entropy produced along a path over the duration of the currents.

None
resamples int

The number of bootstrap resamples of the standard error of the uncertainty product.

200
random_state int | None

The seed of the bootstrap.

None
unperturbed ArrayLike | None

The ensemble without the field, one row per run and one column per frame.

None
field float

The strength of the field.

1.0
correlation ArrayLike | None

The two-time correlation over lags from 0.

None

Returns:

Name Type Description
result IrreversibilityResult

The values read and the measures of the kind.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a setting the kind needs is missing, a setting is out of range, or the data do not suit the kind.

See Also

ergodicity: Tells whether one run stands for the whole ensemble. markov: Estimates the Markov chain of a discrete path.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import irreversibility
>>> ring = 2 * np.roll(np.eye(5), 1, axis=1) + np.roll(np.eye(5), -1, axis=1)
>>> production = irreversibility(ring).entropy_production
>>> bool(abs(production - np.log(2)) < 1e-12)
True
Source code in src/skcomplex/core/analysis/_irreversibility.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def irreversibility(
    source: DataSource,
    *,
    kind: str = 'entropy-production',
    variables: Sequence[str] | None = None,
    rates: npt.ArrayLike | None = None,
    duration: float | None = None,
    drive: Callable[[Array], Array] | float = 1.0,
    intensity: float = 1.0,
    dt: float = 1.0,
    n_states: int | None = None,
    significance: float = 0.05,
    bins: int = 40,
    entropy: float | None = None,
    resamples: int = 200,
    random_state: int | None = None,
    unperturbed: npt.ArrayLike | None = None,
    field: float = 1.0,
    correlation: npt.ArrayLike | None = None,
) -> IrreversibilityResult:
    """Return the irreversibility of a process, of one kind.

    A process is reversible when a film of it run backwards is as likely as the film run forwards. The kinds read a
    rate matrix, jump paths, Langevin paths, samples, or ensembles, and give how much entropy the process produces,
    whether its transitions balance, or how it responds to a field, such as an entropy production of `ln 2` for a ring
    of five states that steps forward twice as often as back. It measures how far molecular motors, heart beats, and
    the prices of a market are from equilibrium.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The rate matrix, the trajectory or an array of paths, one row per path, the samples, or the ensemble the
            kind measures.

        kind:
            What to return. `'entropy-production'` gives the stationary entropy production rate of a jump process from
            its rate matrix, `Σ_{i<j} (p_i k_ij - p_j k_ji) ln(p_i k_ij / (p_j k_ji))`, 0 under detailed balance.
            `'jump-entropy-production'` gives the entropy every jump path produces in the medium, `Σ ln(k_ij / k_ji)`
            over its jumps with the `rates`, and the mean rate over the `duration` of the paths.
            `'langevin-entropy-production'` gives the entropy every overdamped Langevin path produces, the work of the
            `drive` times the `intensity`, `b ∫ F(x) ∘ dx`, and the mean rate. `'count-entropy-production'` gives the
            entropy production rate of a discrete path from its transition counts alone,
            `Σ_{i<j} (N_ij - N_ji) ln(N_ij / N_ji)` per unit time. `'detailed-balance'` gives the chi-squared test of
            detailed balance on the transition counts of discrete paths. `'fluctuation-theorem'` gives the log ratio
            of the probabilities of producing `s` and `-s` from samples of the entropy, and its slope against `s`, 1
            when the theorem holds. `'uncertainty-relation'` gives the squared relative fluctuation `Var(J) / ⟨J⟩²` of
            samples of an integrated current times the mean `entropy` produced over the same duration, at least 2
            (Barato and Seifert 2015). `'response'` gives the integrated response `chi(t) = (<x(t)>_h - <x(t)>_0) / h`
            of an ensemble with the field against the `unperturbed` ensemble. `'fluctuation-dissipation'` gives the
            response and the slope of `chi / b` against `C(t_w, t_w) - C(t, t_w)` of the two-time `correlation` over
            the same lags, 1 in equilibrium and below 1 in an aging system.

        variables:
            The discrete state or the position of a trajectory to read, or `None` for the first one.

        rates:
            The rate of every jump, one row per origin.

        duration:
            The duration of every jump path, or `None` for the duration of a trajectory.

        drive:
            The drift along a Langevin path, a function of position or a constant.

        intensity:
            The factor `b` of the work of the drive in the entropy, and one over the factor of the response in the
            fluctuation-dissipation ratio, as in the acceptance `exp(-intensity * change)` of sampling.

        dt:
            The time between frames of Langevin paths, or between records of a discrete path.

        n_states:
            The number of states, or `None` for the largest state plus one.

        significance:
            The level below which the p-value rejects detailed balance.

        bins:
            The number of bins of entropy, symmetric about 0.

        entropy:
            The mean entropy produced along a path over the duration of the currents.

        resamples:
            The number of bootstrap resamples of the standard error of the uncertainty product.

        random_state:
            The seed of the bootstrap.

        unperturbed:
            The ensemble without the field, one row per run and one column per frame.

        field:
            The strength of the field.

        correlation:
            The two-time correlation over lags from 0.

    Returns:
        result:
            The values read and the measures of the kind.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a setting the kind needs is missing, a
            setting is out of range, or the data do not suit the kind.

    See Also:
        ergodicity: Tells whether one run stands for the whole ensemble.
        markov: Estimates the Markov chain of a discrete path.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import irreversibility
        >>> ring = 2 * np.roll(np.eye(5), 1, axis=1) + np.roll(np.eye(5), -1, axis=1)
        >>> production = irreversibility(ring).entropy_production
        >>> bool(abs(production - np.log(2)) < 1e-12)
        True
    """
    _check_choice('irreversibility', 'kind', kind, KINDS)
    _check_settings(
        irreversibility,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        rates=rates,
        duration=duration,
        drive=drive,
        intensity=intensity,
        dt=dt,
        n_states=n_states,
        significance=significance,
        bins=bins,
        entropy=entropy,
        resamples=resamples,
        random_state=random_state,
        unperturbed=unperturbed,
        field=field,
        correlation=correlation,
    )
    _check(
        kind,
        rates=rates,
        unperturbed=unperturbed,
        correlation=correlation,
        entropy=entropy,
        intensity=intensity,
        dt=dt,
        field=field,
    )
    values, read_duration = _read_values(source, kind, variables, duration)
    if kind == 'entropy-production':
        return IrreversibilityResult(values, read_duration, entropy_production=_entropy_production(values))
    if kind == 'jump-entropy-production':
        return _jumps(values, read_duration, np.asarray(rates, dtype=float))
    if kind == 'count-entropy-production':
        production = _count_entropy_production(values, n_states, dt)
        return IrreversibilityResult(values, read_duration, entropy_production=production)
    if kind == 'detailed-balance':
        return _detailed_balance(values, read_duration, n_states, significance)
    return _of_ensemble(
        values,
        read_duration,
        kind,
        drive=drive,
        intensity=intensity,
        dt=dt,
        bins=bins,
        entropy=entropy,
        resamples=resamples,
        random_state=random_state,
        unperturbed=unperturbed,
        field=field,
        correlation=correlation,
    )

kramers_moyal(source, *, variables=None, dt=1.0, bins=50, bandwidth=None)

Return the drift and the diffusion of one series.

The drift is the mean step from a value per unit time and the diffusion half the mean squared step, so a series that follows dx = a(x) dt + sqrt(2 D(x)) dW gives a and D, such as a diffusion of 1 for a random walk whose steps have the variance 2 dt. The steps are binned by the value they start from, and an Epanechnikov kernel smooths the bins, the estimator of Lamouroux and Lehnertz. It estimates the pull and the noise of wind speeds, heart rates, and exchange rates from one record.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array that holds one series.

required
variables Sequence[str] | None

The variable of a trajectory to read, or None for the only scalar series.

None
dt float

The time between samples.

1.0
bins int

The number of bins of values.

50
bandwidth float | None

The width of the Epanechnikov kernel, or None for Silverman's rule.

None

Returns:

Name Type Description
result KramersMoyalResult

The series, the centres of the bins, and the drift and the diffusion in every bin.

Raises:

Type Description
AnalysisError

A setting is not positive, the source does not hold one series of at least two values, or the series is constant without a bandwidth.

See Also

sparse_identification: Finds the equations of a series from a library of terms. fit_law: Fits a law to the values of a series.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import kramers_moyal
>>> x = np.cumsum(np.random.default_rng(0).normal(0, np.sqrt(0.02), 100_000))
>>> round(float(np.median(kramers_moyal(x, dt=0.01, bins=21).diffusion)), 1)
1.0
Source code in src/skcomplex/core/analysis/_kramers_moyal.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def kramers_moyal(
    source: DataSource,
    *,
    variables: Sequence[str] | None = None,
    dt: float = 1.0,
    bins: int = 50,
    bandwidth: float | None = None,
) -> KramersMoyalResult:
    """Return the drift and the diffusion of one series.

    The drift is the mean step from a value per unit time and the diffusion half the mean squared step, so a series
    that follows `dx = a(x) dt + sqrt(2 D(x)) dW` gives `a` and `D`, such as a diffusion of 1 for a random walk whose
    steps have the variance `2 dt`. The steps are binned by the value they start from, and an Epanechnikov kernel
    smooths the bins, the estimator of Lamouroux and Lehnertz. It estimates the pull and the noise of wind speeds,
    heart rates, and exchange rates from one record.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array that holds one series.

        variables:
            The variable of a trajectory to read, or `None` for the only scalar series.

        dt:
            The time between samples.

        bins:
            The number of bins of values.

        bandwidth:
            The width of the Epanechnikov kernel, or `None` for Silverman's rule.

    Returns:
        result:
            The series, the centres of the bins, and the drift and the diffusion in every bin.

    Raises:
        AnalysisError:
            A setting is not positive, the source does not hold one series of at least two values, or the series is
            constant without a bandwidth.

    See Also:
        sparse_identification: Finds the equations of a series from a library of terms.
        fit_law: Fits a law to the values of a series.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import kramers_moyal
        >>> x = np.cumsum(np.random.default_rng(0).normal(0, np.sqrt(0.02), 100_000))
        >>> round(float(np.median(kramers_moyal(x, dt=0.01, bins=21).diffusion)), 1)
        1.0
    """
    if dt <= 0 or bins < 1 or (bandwidth is not None and bandwidth <= 0):
        error_msg = f'kramers_moyal has dt={dt!r}, bins={bins!r}, and bandwidth={bandwidth!r}. Use positive values.'
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    if series.values.shape[1] != 1:
        error_msg = (
            f'kramers_moyal reads one series, but the source has {series.values.shape[1]}: {", ".join(series.labels)}. '
            'Select one with variables.'
        )
        raise AnalysisError(error_msg)
    if series.values.shape[0] < MIN_SERIES_SIZE:
        error_msg = f'kramers_moyal reads increments, but the series has {series.values.shape[0]} value.'
        raise AnalysisError(error_msg)
    values = np.asarray(series.values[:, 0], dtype=float)
    width_of_kernel = _get_bandwidth(values, bandwidth)
    starts, increments = values[:-1], np.diff(values)
    edges = np.linspace(starts.min() - width_of_kernel, starts.max() + width_of_kernel, bins + 1)
    width = edges[1] - edges[0]
    histograms = np.stack([np.histogram(starts, edges, weights=increments**power)[0] for power in (0, 1, 2)])
    kernel = _get_kernel(width * np.arange(-bins - 1, bins + 2), width_of_kernel)
    mass, first, second = convolve(histograms, kernel[None, :], mode='same')
    counted = np.abs(mass) >= ZERO_MASS
    return KramersMoyalResult(
        values,
        edges[:-1] + width / 2,
        np.divide(first, mass, out=np.zeros(bins), where=counted) / dt,
        np.divide(second, 2 * mass, out=np.zeros(bins), where=counted) / dt,
    )

large_deviations(source, *, kind='tilted', variables=None, weights=None, tilts=1.0, values=None, block=10, dt=1.0, observable=None, population=1000, interval=1.0, until=20.0, random_state=None, simulation=None, bins=41, value_range=None, log_weights=None)

Return the large deviations of a time-additive observable, of one kind.

A time-additive observable sums over a run, such as the number of jumps or the money paid out, and its rare values have odds that fall off as exp(-T I(a)) with the length T of the run. The kinds estimate the scaled cumulant generating function lambda(k) at the tilts, and with values the rate function I(a) = max_k (k a - lambda(k)), such as lambda(1) = 2 (e - 1) for the count of a Poisson process of rate 2. It estimates the odds of a run of losses of an insurer, a rare current through a channel, or a long drought.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource | ProblemSpec | Mapping[int, ArrayLike]

The rate matrix for 'tilted', the trajectory or an array of increments for 'block', the system or its problem for 'cloning', a mapping of every size to its samples for 'histogram', or the samples for 'reweight'.

required
kind str

What to return. 'tilted' gives the exact generating function of a counting observable of a jump process that adds weights[i, j] at every jump from i to j, the largest eigenvalue of the tilted generator rates * exp(k weights) - diag(escape rates) of the rate matrix. A diagonal rate counts jumps that keep the state, such as the events of a Poisson process. 'block' gives ln <exp(k A)> / (block dt) from blocks of block steps of one long run of the increments of the observable. 'cloning' gives the estimate of the fixed population cloning of Giardinà, Kurchan, and Peliti, which advances every clone of a system by interval, weights it by exp(k A) for the increment A of the observable, and resamples the population by the weights. The system is compiled once and every segment restarts the clock at zero, so the laws must not depend on time explicitly, and a warning names a population whose effective size falls below a tenth of the clones or below 10 clones. 'histogram' gives the rate function of P_N(m) ≍ exp(-N I(m)) from the samples of an order parameter at several sizes N, fitting -ln P_N linearly in N in every bin. 'reweight' gives samples reweighted to another law by the logarithms of the likelihood ratios, such as beta dh M.

'tilted'
variables Sequence[str] | None

The series of a trajectory whose values are the increments of 'block', or None for the first one.

None
weights ArrayLike | None

The increment of the observable at every jump of 'tilted'.

None
tilts float | ArrayLike

The values of the tilt k.

1.0
values ArrayLike | None

The values a of the observable per unit time of the rate function, or None for none.

None
block int

The number of steps of every block.

10
dt float

The time of one step.

1.0
observable str | Callable[[Trajectory], float] | None

The dotted name of a state whose increment over each interval is the observable, such as a counter, or a function of the trajectory of one interval that returns the increment.

None
population int

The number of clones.

1000
interval float

The time between two selection steps.

1.0
until float

The simulated time of every clone, a multiple of the interval.

20.0
random_state int | None

The seed of the clones and of the selection.

None
simulation Mapping[str, object] | None

Other run settings, such as solver or dt.

None
bins int | ArrayLike

The number of bins or their edges of 'histogram'.

41
value_range tuple[float, float] | None

The range of the bins, or None for the range of all samples.

None
log_weights ArrayLike | None

The logarithm of the ratio of the new to the old probability of every sample.

None

Returns:

Name Type Description
result LargeDeviationsResult

The data read, the generating function at every tilt, and the rate function at the values.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a setting the kind needs is missing, a setting is out of range, or the source does not suit the kind.

See Also

events: Finds the events of a series and counts them in windows. fit_law: Fits a law to the tail of a sample.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import large_deviations
>>> tilts = np.linspace(-3, 3, 6001)
>>> rate = large_deviations([[2.0]], weights=[[1.0]], tilts=tilts, values=[3.0])
>>> round(float(rate.rate_function[0]), 4)
0.2164
Source code in src/skcomplex/core/analysis/_large_deviations.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def large_deviations(
    source: DataSource | ProblemSpec | Mapping[int, npt.ArrayLike],
    *,
    kind: str = 'tilted',
    variables: Sequence[str] | None = None,
    weights: npt.ArrayLike | None = None,
    tilts: float | npt.ArrayLike = 1.0,
    values: npt.ArrayLike | None = None,
    block: int = 10,
    dt: float = 1.0,
    observable: str | Callable[[Trajectory], float] | None = None,
    population: int = 1000,
    interval: float = 1.0,
    until: float = 20.0,
    random_state: int | None = None,
    simulation: Mapping[str, object] | None = None,
    bins: int | npt.ArrayLike = 41,
    value_range: tuple[float, float] | None = None,
    log_weights: npt.ArrayLike | None = None,
) -> LargeDeviationsResult:
    """Return the large deviations of a time-additive observable, of one kind.

    A time-additive observable sums over a run, such as the number of jumps or the money paid out, and its rare
    values have odds that fall off as `exp(-T I(a))` with the length `T` of the run. The kinds estimate the scaled
    cumulant generating function `lambda(k)` at the `tilts`, and with `values` the rate function
    `I(a) = max_k (k a - lambda(k))`, such as `lambda(1) = 2 (e - 1)` for the count of a Poisson process of rate 2. It
    estimates the odds of a run of losses of an insurer, a rare current through a channel, or a long drought.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The rate matrix for `'tilted'`, the trajectory or an array of increments for `'block'`, the system or its
            problem for `'cloning'`, a mapping of every size to its samples for `'histogram'`, or the samples for
            `'reweight'`.

        kind:
            What to return. `'tilted'` gives the exact generating function of a counting observable of a jump process
            that adds `weights[i, j]` at every jump from `i` to `j`, the largest eigenvalue of the tilted generator
            `rates * exp(k weights) - diag(escape rates)` of the rate matrix. A diagonal rate counts jumps that keep the
            state, such as the events of a Poisson process. `'block'` gives `ln <exp(k A)> / (block dt)` from blocks
            of `block` steps of one long run of the increments of the observable. `'cloning'` gives the estimate of the
            fixed population cloning of Giardinà, Kurchan, and Peliti, which advances every clone of a system by
            `interval`, weights it by `exp(k A)` for the increment `A` of the observable, and resamples the population
            by the weights. The system is compiled once and every segment restarts the clock at zero, so the laws must
            not depend on time explicitly, and a warning names a population whose effective size falls below a tenth
            of the clones or below 10 clones. `'histogram'` gives the rate function of `P_N(m) ≍ exp(-N I(m))` from the
            samples of an order parameter at several sizes `N`, fitting `-ln P_N` linearly in `N` in every bin.
            `'reweight'` gives samples reweighted to another law by the logarithms of the likelihood ratios, such as
            `beta dh M`.

        variables:
            The series of a trajectory whose values are the increments of `'block'`, or `None` for the first one.

        weights:
            The increment of the observable at every jump of `'tilted'`.

        tilts:
            The values of the tilt `k`.

        values:
            The values `a` of the observable per unit time of the rate function, or `None` for none.

        block:
            The number of steps of every block.

        dt:
            The time of one step.

        observable:
            The dotted name of a state whose increment over each interval is the observable, such as a counter, or a
            function of the trajectory of one interval that returns the increment.

        population:
            The number of clones.

        interval:
            The time between two selection steps.

        until:
            The simulated time of every clone, a multiple of the interval.

        random_state:
            The seed of the clones and of the selection.

        simulation:
            Other run settings, such as `solver` or `dt`.

        bins:
            The number of bins or their edges of `'histogram'`.

        value_range:
            The range of the bins, or `None` for the range of all samples.

        log_weights:
            The logarithm of the ratio of the new to the old probability of every sample.

    Returns:
        result:
            The data read, the generating function at every tilt, and the rate function at the values.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a setting the kind needs is missing, a
            setting is out of range, or the source does not suit the kind.

    See Also:
        events: Finds the events of a series and counts them in windows.
        fit_law: Fits a law to the tail of a sample.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import large_deviations
        >>> tilts = np.linspace(-3, 3, 6001)
        >>> rate = large_deviations([[2.0]], weights=[[1.0]], tilts=tilts, values=[3.0])
        >>> round(float(rate.rate_function[0]), 4)
        0.2164
    """
    given = _get_system(source)
    source = _composite(given)
    _check_choice('large_deviations', 'kind', kind, KINDS)
    _check_settings(
        large_deviations,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        weights=weights,
        tilts=tilts,
        values=values,
        block=block,
        dt=dt,
        observable=observable,
        population=population,
        interval=interval,
        until=until,
        random_state=random_state,
        simulation=simulation,
        bins=bins,
        value_range=value_range,
        log_weights=log_weights,
    )
    needed = {'tilted': weights, 'cloning': observable, 'reweight': log_weights}
    names = {'tilted': 'weights', 'cloning': 'observable', 'reweight': 'log_weights'}
    if kind in needed and needed[kind] is None:
        error_msg = f'large_deviations of kind {kind!r} needs {names[kind]}. Give it.'
        raise AnalysisError(error_msg)
    _check(population, interval, until, block, dt)
    if kind == 'histogram':
        if not isinstance(source, Mapping):
            error_msg = 'large_deviations of kind histogram reads a mapping of every size to its samples.'
            raise AnalysisError(error_msg)
        samples = {size: np.asarray(source[size], dtype=float) for size in sorted(source)}
        centres, histogram_rates = _histogram(samples, bins, value_range)
        return LargeDeviationsResult(samples=samples, values=centres, rate_function=histogram_rates)
    if kind == 'reweight':
        observations = np.asarray(source, dtype=float)
        logs = np.asarray(log_weights, dtype=float)
        normalized = np.exp(logs - special.logsumexp(logs))
        return LargeDeviationsResult(
            observations=observations,
            weights=normalized,
            mean=float(np.sum(normalized * observations)),
            effective_size=float(1 / np.sum(normalized**2)),
        )
    grid = np.atleast_1d(np.asarray(tilts, dtype=float))
    rates: Array | None = None
    increments: Array | None = None
    system: System | ProblemSpec | None = None
    effective_population: Array | None = None
    if kind == 'tilted':
        rates = np.asarray(source, dtype=float)
        tilted = np.asarray(weights, dtype=float)
        escape = np.diag(rates.sum(axis=1))
        scgf = np.asarray([linalg.eigvals(rates * np.exp(tilt * tilted) - escape).real.max() for tilt in grid])
    elif kind == 'block':
        increments = _read_series(source, variables).values[:, 0].astype(float)
        scgf = _block_scgf(increments, grid, block, dt)
    else:
        if not isinstance(source, _CompositeSystem | ProblemSpec):
            error_msg = f'large_deviations of kind cloning reads a system or its problem, not {type(source).__name__}.'
            raise AnalysisError(error_msg)
        estimates = [
            _clone(
                source,
                float(tilt),
                observable=observable,
                population=population,
                interval=interval,
                until=until,
                random_state=random_state,
                simulation=simulation,
            )
            for tilt in grid
        ]
        scgf = np.asarray([value for value, _ in estimates])
        effective_population = np.asarray([effective for _, effective in estimates])
        system = given if isinstance(given, System) else source
    points: Array | None = None
    rate_function: Array | None = None
    if values is not None:
        points = np.atleast_1d(np.asarray(values, dtype=float))
        rate_function = _legendre_transform(grid, scgf, points)
    return LargeDeviationsResult(
        rates=rates,
        increments=increments,
        system=system,
        tilts=grid,
        scgf=scgf,
        effective_population=effective_population,
        values=points,
        rate_function=rate_function,
    )

linearization(source, *, controls=None, outputs=None, at=None, state_weights=None, control_weights=None)

Return the linear state-space system of a system near an operating point.

The system is x' = A x + B u, y = C x + D u. The matrices are the Jacobians of the rates and of the outputs, derived symbolically and evaluated at the operating point. The controls are parameters or adaptive parameters, named by their dotted names, such as the force 'cart.force' that no law of the plant changes, and the outputs are states or controls. The system is controllable when the rank of [B, AB, ..., A^(n-1) B] equals the number of states, and observable when the rank of [C; CA; ...; C A^(n-1)] does. With weights of the states and the controls, the gain K of the linear quadratic regulator u = -K x makes ∫ (x' Q x + u' R u) dt smallest. It gives the linear model of an aircraft near trim, a power grid near its operating point, or an economy near its steady state, for control.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, its compiled problem, or a trajectory of it.

required
controls Sequence[str] | None

The dotted names of the parameters or adaptive parameters that are inputs, or None for the bounded adaptive parameters.

None
outputs Sequence[str] | None

The dotted names of the states and controls that are outputs, or None for every state.

None
at Mapping[str, float] | None

The values of states and controls at the operating point, by dotted name, or None for the initial values.

None
state_weights ArrayLike | None

The weight Q of the states in the cost of the regulator, a symmetric positive semidefinite matrix, or None for no regulator.

None
control_weights ArrayLike | None

The weight R of the controls in the cost of the regulator, a symmetric positive definite matrix, or None for no regulator.

None

Returns:

Name Type Description
result LinearizationResult

The state-space matrices, their ranks, and the gain of the regulator.

Raises:

Type Description
AnalysisError

Only one of the weights is given, or a control or an output is unknown.

ValidationError

The system does not run in continuous time.

See Also

stability: Finds the fixed points of a system and whether they are stable. sparse_identification: Finds the equations of a system from its data.

Examples:

>>> from skcomplex.core.analysis import linearization
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> result = linearization(HarmonicOscillatorSystem(), controls=['spring.k'])
>>> result.B.tolist(), result.controllability
([[0.0], [-1.0]], 2)
Source code in src/skcomplex/core/analysis/_linearization.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def linearization(
    source: DataSource,
    *,
    controls: Sequence[str] | None = None,
    outputs: Sequence[str] | None = None,
    at: Mapping[str, float] | None = None,
    state_weights: npt.ArrayLike | None = None,
    control_weights: npt.ArrayLike | None = None,
) -> LinearizationResult:
    """Return the linear state-space system of a system near an operating point.

    The system is `x' = A x + B u`, `y = C x + D u`. The matrices are the Jacobians of the rates and of the outputs,
    derived symbolically and evaluated at the operating point. The controls are parameters or adaptive parameters,
    named by their dotted names, such as the force `'cart.force'` that no law of the plant changes, and the outputs are
    states or controls. The system is controllable when the rank of `[B, AB, ..., A^(n-1) B]` equals the number of
    states, and observable when the rank of `[C; CA; ...; C A^(n-1)]` does. With weights of the states and the
    controls, the gain `K` of the linear quadratic regulator `u = -K x` makes `∫ (x' Q x + u' R u) dt` smallest. It
    gives the linear model of an aircraft near trim, a power grid near its operating point, or an economy near its
    steady state, for control.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, its compiled problem, or a trajectory of it.

        controls:
            The dotted names of the parameters or adaptive parameters that are inputs, or `None` for the bounded
            adaptive parameters.

        outputs:
            The dotted names of the states and controls that are outputs, or `None` for every state.

        at:
            The values of states and controls at the operating point, by dotted name, or `None` for the initial values.

        state_weights:
            The weight `Q` of the states in the cost of the regulator, a symmetric positive semidefinite matrix, or
            `None` for no regulator.

        control_weights:
            The weight `R` of the controls in the cost of the regulator, a symmetric positive definite matrix, or
            `None` for no regulator.

    Returns:
        result:
            The state-space matrices, their ranks, and the gain of the regulator.

    Raises:
        AnalysisError:
            Only one of the weights is given, or a control or an output is unknown.

        ValidationError:
            The system does not run in continuous time.

    See Also:
        stability: Finds the fixed points of a system and whether they are stable.
        sparse_identification: Finds the equations of a system from its data.

    Examples:
        >>> from skcomplex.core.analysis import linearization
        >>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
        >>> result = linearization(HarmonicOscillatorSystem(), controls=['spring.k'])
        >>> result.B.tolist(), result.controllability
        ([[0.0], [-1.0]], 2)
    """
    source = _composite(source)
    if (state_weights is None) != (control_weights is None):
        error_msg = (
            'linearization computes the regulator from both state_weights and control_weights. Give both, or neither.'
        )
        raise AnalysisError(error_msg)
    problem = compile_problem(_read_system(source), 'Linearization')
    if problem.form != FormKind.ODE:
        error_msg = f'linearization takes systems under continuous time, but the system is a {problem.form}.'
        raise ValidationError(error_msg)
    adaptive = problem.adaptive_parameters
    dynamics = StabilityResult._get_dynamics_of(problem)
    display = LayoutSpec._get_display_name
    internal = {display(name): name for name in [*dynamics.names, *adaptive, *problem.parameters.names]}
    chosen = [name for name, item in adaptive.items() if item.bounds is not None] if controls is None else controls
    known = [display(name) for name in [*adaptive, *problem.parameters.names]]
    inputs = [internal[name] for name in _checked_names(chosen, known, 'parameters or adaptive parameters')]
    states = [name for name in dynamics.names if name not in inputs]
    named = [display(name) for name in [*states, *inputs]]
    wanted = [display(name) for name in states] if outputs is None else outputs
    observed = [internal[name] for name in _checked_names(wanted, named, 'states or controls')]
    values = _initial_values(problem)
    values.update({internal.get(name, name): value for name, value in (at or {}).items()})
    by_name = dict(zip(dynamics.names, dynamics.symbols, strict=True))
    by_name.update({name: problem.symbols[name] for name in inputs if name not in by_name})
    rates = dict(zip(dynamics.names, dynamics.rates, strict=True))
    point = dict(dynamics.parameters)
    point.update({by_name[name]: float(value) for name, value in values.items() if name in by_name})
    point[dynamics.time] = 0.0
    state_matrix = _evaluated([[rates[row].diff(by_name[column]) for column in states] for row in states], point)
    input_matrix = _evaluated([[rates[row].diff(by_name[column]) for column in inputs] for row in states], point)
    output_matrix = np.array([[float(row == column) for column in states] for row in observed]).reshape(
        len(observed),
        len(states),
    )
    feedthrough = np.array([[float(row == column) for column in inputs] for row in observed]).reshape(
        len(observed),
        len(inputs),
    )
    gain = (
        None
        if state_weights is None or control_weights is None
        else _lqr(state_matrix, input_matrix, state_weights, control_weights)
    )
    return LinearizationResult(
        problem=problem,
        A=state_matrix,
        B=input_matrix,
        C=output_matrix,
        D=feedthrough,
        states=tuple(display(name) for name in states),
        controls=tuple(display(name) for name in inputs),
        outputs=tuple(display(name) for name in observed),
        controllability=_controllability(state_matrix, input_matrix),
        observability=_controllability(state_matrix.T, output_matrix.T),
        gain=gain,
    )

local_information(source, *, kind='entropy', variables=None, history=1, lag=1, estimator='plugin', base=2.0)

Return the local information of every series or every pair of series.

Local information splits an average such as the entropy or the mutual information into one value per sample, so a rare value carries more bits than a common one, such as 2 bits for the 1 of [0, 0, 0, 1]. The probabilities are the frequencies of symbols, or the densities of a fitted Gaussian. It finds the moments when information moves in a flock, in a cellular automaton, and in the spikes of neurons.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array with one row per time and one column per series.

required
kind str

What to return. 'entropy' gives the local entropy -log p(x) of every sample of every series. 'mutual' gives the local mutual information log p(x, y) / (p(x) p(y)) of every sample of every pair of series, negative where the series mislead about each other. 'transfer' gives the local transfer entropy log p(y_t | y_past, x_{t-lag}) / p(y_t | y_past) from every series to every series at every time from max(history, lag) on.

'entropy'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series.

None
history int

The number of past target values of the transfer entropy.

1
lag int

The delay of the source of the transfer entropy.

1
estimator str

'plugin' for the frequencies of symbols, or 'gaussian' for the densities of a fitted Gaussian.

'plugin'
base float

The base of the logarithm, 2 for bits.

2.0

Returns:

Name Type Description
result LocalInformationResult

The series and their local information.

Raises:

Type Description
AnalysisError

A choice is unknown, a setting the kind does not read is changed, or a setting is out of range.

See Also

information: Gives the average information among series. entropy: Measures how unpredictable a series is.

Examples:

>>> from skcomplex.core.analysis import local_information
>>> local = local_information([[0, 0], [0, 0], [1, 1], [1, 0]], kind='mutual')
>>> local.information[0, 1].round(3).tolist()
[0.415, 0.415, 1.0, -0.585]
Source code in src/skcomplex/core/analysis/_local_information.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def local_information(
    source: DataSource,
    *,
    kind: str = 'entropy',
    variables: Sequence[str] | None = None,
    history: int = 1,
    lag: int = 1,
    estimator: str = 'plugin',
    base: float = 2.0,
) -> LocalInformationResult:
    """Return the local information of every series or every pair of series.

    Local information splits an average such as the entropy or the mutual information into one value per sample, so a
    rare value carries more bits than a common one, such as 2 bits for the 1 of `[0, 0, 0, 1]`. The probabilities are
    the frequencies of symbols, or the densities of a fitted Gaussian. It finds the moments when information moves in
    a flock, in a cellular automaton, and in the spikes of neurons.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array with one row per time and one column per series.

        kind:
            What to return. `'entropy'` gives the local entropy `-log p(x)` of every sample of every series.
            `'mutual'` gives the local mutual information `log p(x, y) / (p(x) p(y))` of every sample of every pair of
            series, negative where the series mislead about each other. `'transfer'` gives the local transfer entropy
            `log p(y_t | y_past, x_{t-lag}) / p(y_t | y_past)` from every series to every series at every time from
            `max(history, lag)` on.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series.

        history:
            The number of past target values of the transfer entropy.

        lag:
            The delay of the source of the transfer entropy.

        estimator:
            `'plugin'` for the frequencies of symbols, or `'gaussian'` for the densities of a fitted Gaussian.

        base:
            The base of the logarithm, 2 for bits.

    Returns:
        result:
            The series and their local information.

    Raises:
        AnalysisError:
            A choice is unknown, a setting the kind does not read is changed, or a setting is out of range.

    See Also:
        information: Gives the average information among series.
        entropy: Measures how unpredictable a series is.

    Examples:
        >>> from skcomplex.core.analysis import local_information
        >>> local = local_information([[0, 0], [0, 0], [1, 1], [1, 0]], kind='mutual')
        >>> local.information[0, 1].round(3).tolist()
        [0.415, 0.415, 1.0, -0.585]
    """
    _check_choice('local_information', 'kind', kind, KINDS)
    _check_choice('local_information', 'estimator', estimator, ESTIMATORS)
    _check_settings(
        local_information,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        history=history,
        lag=lag,
        estimator=estimator,
        base=base,
    )
    if history < 1 or lag < 1 or base <= 0:
        error_msg = (
            f'local_information has history={history!r}, lag={lag!r}, and base={base!r}. Use a history and a lag of 1 '
            'or more and a positive base.'
        )
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    columns = series.values.T
    local: list[Array] | list[list[Array]]
    if kind == 'entropy':
        local = [-_log_probabilities(column[:, None], estimator) for column in columns]
    else:
        local = [
            [
                _compute_pair(kind, first, second, history=history, lag=lag, estimator=estimator, same=row == column)
                for column, second in enumerate(columns)
            ]
            for row, first in enumerate(columns)
        ]
    return LocalInformationResult(series.values, series.labels, np.asarray(local, dtype=float) / math.log(base))

loops(source, *, kind='loops', at=None, frame=-1, quantity=None)

Return the feedback loops of the signed dependency graph of a system.

The graph has the states as nodes and an edge from x_j to x_i when the rate of x_i depends on x_j, with the sign of df_i/dx_j, the entry of the Jacobian, and a loop is a closed path of edges, reinforcing when the product of its signs is positive and balancing when it is negative, such as word of mouth and saturation in the spread of a product. The rate of a map is its next value minus itself, and delays and smoothings pass their input with gain one. It finds the reinforcing and balancing loops of a model of system dynamics, a gene network, and an ecosystem.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, its compiled problem, or a trajectory of it, and a trajectory for 'dominance' and 'flow-matrix'.

required
kind str

What to return. 'loops' gives the signed graph and its loops, the elementary cycles found with the algorithm of Johnson, with the gain of every loop, the product of the partial derivatives along it, and its polarity, the sign of the gain. Rate laws of single elements give the edges into the states they change, and the Jacobian, as stability derives it with the parameters at their values, gives the edges into every other state, such as the members of a group or the velocity of a state of second order. A flow is a rate law whose target maps each stock to the sign of its change, such as RateLaw({s.source.n: -1, s.sink.n: +1}, f, label='births'), or a transfer. When a system declares flows, the flows are nodes too, with an edge from each state to every flow whose amount depends on it and from each flow to its sink with sign + and to its source with sign -. 'dominance' gives the gains of the loops at every frame of a trajectory and the dominant loop, the one with the largest absolute gain. 'flow-matrix' gives the transaction flow matrix of one frame of a trajectory, with flows as rows and holders as columns. Every row holds the outflow of its flow at the source, negative, and the inflow at the sink, positive, so every row sums to zero, and flows of a group sum over its members. It needs a system that declares flows, since the Jacobian does not hold the amounts the flows move.

'loops'
at ArrayLike | None

The state vector the signs of 'loops' are evaluated at, or None for the initial state.

None
frame int

The index of the frame of the flow matrix.

-1
quantity str | None

The quantity whose flows form the rows of the flow matrix, or None for every flow.

None

Returns:

Name Type Description
result LoopsResult

The loops with their graph, their gains along the trajectory, or the flow matrix.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, the kind reads a trajectory and gets another source, the system has no loop to dominate, or it declares no flows for a flow matrix.

See Also

stability: Finds the fixed points of a system and whether they are stable. elementary_modes: Finds the simplest steady routes through a network of flows.

Examples:

>>> from skcomplex.core.analysis import loops
>>> from skcomplex.systems.economics.innovation import BassDiffusionSystem
>>> trajectory = BassDiffusionSystem().prepare().simulate(until=2, dt=1)
>>> loops(trajectory, kind='dominance').gains.shape
(3, 2)
Source code in src/skcomplex/core/analysis/_loops.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def loops(
    source: DataSource,
    *,
    kind: str = 'loops',
    at: npt.ArrayLike | None = None,
    frame: int = -1,
    quantity: str | None = None,
) -> LoopsResult:
    """Return the feedback loops of the signed dependency graph of a system.

    The graph has the states as nodes and an edge from `x_j` to `x_i` when the rate of `x_i` depends on `x_j`, with
    the sign of `df_i/dx_j`, the entry of the Jacobian, and a loop is a closed path of edges, reinforcing when the
    product of its signs is positive and balancing when it is negative, such as word of mouth and saturation in the
    spread of a product. The rate of a map is its next value minus itself, and delays and smoothings pass their input
    with gain one. It finds the reinforcing and balancing loops of a model of system dynamics, a gene network, and an
    ecosystem.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, its compiled problem, or a trajectory of it, and a trajectory for `'dominance'` and
            `'flow-matrix'`.

        kind:
            What to return. `'loops'` gives the signed graph and its loops, the elementary cycles found with the
            algorithm of Johnson, with the gain of every loop, the product of the partial derivatives along it, and its
            polarity, the sign of the gain. Rate laws of single elements give the edges into the states they change,
            and the Jacobian, as `stability` derives it with the parameters at their values, gives the edges into
            every other state, such as the members of a group or the velocity of a state of second order. A flow is a
            rate law whose target maps each stock to the sign of its change, such as
            `RateLaw({s.source.n: -1, s.sink.n: +1}, f, label='births')`, or a transfer. When a system declares flows,
            the flows are nodes too, with an edge from each state to every flow whose amount depends on it and from
            each flow to its sink with sign `+` and to its source with sign `-`. `'dominance'` gives the gains of the
            loops at every frame of a trajectory and the dominant loop, the one with the largest absolute gain.
            `'flow-matrix'` gives the transaction flow matrix of one frame of a trajectory, with flows as rows and
            holders as columns. Every row holds the outflow of its flow at the source, negative, and the inflow at the
            sink, positive, so every row sums to zero, and flows of a group sum over its members. It needs a system
            that declares flows, since the Jacobian does not hold the amounts the flows move.

        at:
            The state vector the signs of `'loops'` are evaluated at, or `None` for the initial state.

        frame:
            The index of the frame of the flow matrix.

        quantity:
            The quantity whose flows form the rows of the flow matrix, or `None` for every flow.

    Returns:
        result:
            The loops with their graph, their gains along the trajectory, or the flow matrix.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, the kind reads a trajectory and gets
            another source, the system has no loop to dominate, or it declares no flows for a flow matrix.

    See Also:
        stability: Finds the fixed points of a system and whether they are stable.
        elementary_modes: Finds the simplest steady routes through a network of flows.

    Examples:
        >>> from skcomplex.core.analysis import loops
        >>> from skcomplex.systems.economics.innovation import BassDiffusionSystem
        >>> trajectory = BassDiffusionSystem().prepare().simulate(until=2, dt=1)
        >>> loops(trajectory, kind='dominance').gains.shape
        (3, 2)
    """
    source = _composite(source)
    _check_choice('loops', 'kind', kind, KINDS)
    _check_settings(loops, 'kind', SETTINGS[kind], kind=kind, at=at, frame=frame, quantity=quantity)
    if kind != 'loops' and not isinstance(source, Trajectory):
        error_msg = f'loops of kind {kind!r} reads a trajectory, not {type(source).__name__}.'
        raise AnalysisError(error_msg)
    trajectory = source if isinstance(source, Trajectory) else None
    problem = compile_problem(_read_system(source), 'The feedback loop analysis')
    if kind == 'flow-matrix' and not _transfer_network(problem).flows:
        error_msg = (
            'The system declares no flows, so it has no transaction-flow matrix. Read the signed dependency of its '
            "states with the kind 'loops', or its Jacobian with `stability`."
        )
        raise AnalysisError(error_msg)
    if kind == 'loops':
        graph = _Graph(problem)
        state = np.asarray(problem.initial_state if at is None else at, dtype=float)[np.newaxis]
        parameters, times = problem.initial_parameters[np.newaxis], np.zeros(1)
        gains = {
            edge: float(graph.evaluate(SR(value), state, parameters, times)[0]) for edge, value in graph.edges.items()
        }
        directed, found = _signed_loops(graph, gains)
        return LoopsResult(
            problem,
            trajectory=trajectory,
            graph=directed,
            loops=[loop.nodes for loop in found],
            polarities=[loop.polarity for loop in found],
            gains=np.asarray([loop.gain for loop in found], dtype=float),
        )
    if trajectory is None:
        error_msg = f'loops of kind {kind!r} reads a trajectory. Give one.'
        raise AnalysisError(error_msg)
    if kind == 'dominance':
        return _dominance(problem, trajectory)
    return _flow_matrix(problem, trajectory, frame, quantity)

lyapunov(source, *, kind='spectrum', variables=None, n_exponents=None, until=None, dt=None, transient=None, parameters=None, dimension=3, delay=1, min_separation=None, trajectory_length=20, skip=0)

Return the Lyapunov exponents of a system, or the largest exponent of series.

An exponent is the average rate at which two nearby runs separate, |δx(t)| ≈ |δx(0)| exp(λ t), and a positive largest exponent means chaos, such as ln 2 per step for the logistic map at r = 4. The exponents of a system come from its equations, and the largest exponent of a series from how fast its close returns drift apart. It measures how fast small errors grow in the weather, a double pendulum, and the orbits of asteroids.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, its compiled problem, or a trajectory of it for 'spectrum', or an array of exponents, and the trajectory or the array of series for 'largest'.

required
kind str

What to return. 'spectrum' gives the largest n_exponents exponents of a flow or a map from the initial state of the system. The tangent dynamics use the symbolic Jacobian, in which abs(u) has the derivative sign(u), and the compiled functions take the parameters as an argument, so a sweep over parameter values compiles them once. Tangent vectors are made orthonormal again by QR after every step, as in the algorithm of Benettin, and the exponents are the average logarithmic growth of the diagonal of R. The Kaplan-Yorke dimension and the Kolmogorov-Sinai entropy, by the identity of Pesin the sum of the positive exponents, follow from the spectrum, and an array of exponents passes through as the spectrum. 'largest' gives the estimate of Rosenstein of the largest exponent of every series, from the divergence of neighbours of its delay embedding.

'spectrum'
variables Sequence[str] | None

The variables of a trajectory to read for 'largest', or None for every scalar series.

None
n_exponents int | None

The number of exponents of the spectrum, or None for all of them.

None
until float | None

The time averaged over, or the number of iterations of a map, or None for 1000 for flows and 10,000 for maps.

None
dt float | None

The fixed step of the RK4 integration of flows, or the time between samples of a series, or None for 0.01 and 1.

None
transient float | None

The time, or the number of iterations, run before averaging, or None for a tenth of until.

None
parameters Mapping[str, float] | None

Values of parameters by dotted path that replace the system's values.

None
dimension int

The dimension of the delay embedding.

3
delay int

The delay of the embedding in steps.

1
min_separation int | None

The fewest steps between neighbours, or None for the mean period from the spectrum.

None
trajectory_length int

The number of steps over which the divergence of neighbours is followed and fitted.

20
skip int

The number of first steps of the divergence left out of the fit, while neighbours align with the unstable direction.

0

Returns:

Name Type Description
result LyapunovResult

The spectrum with its dimension and entropy, or the largest exponent of every series.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, or a setting is not positive.

TagError

The system of the source is stochastic, since the exponents need a deterministic system.

See Also

embedding: Gives the points made of delayed copies of one series. stability: Finds the fixed points of a system and whether they are stable.

Examples:

>>> from skcomplex.core.analysis import lyapunov
>>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapSystem
>>> float(lyapunov(LogisticMapSystem(r=4.0), until=20000).exponents[0].round(2))
0.69
Source code in src/skcomplex/core/analysis/_lyapunov.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def lyapunov(
    source: DataSource,
    *,
    kind: str = 'spectrum',
    variables: Sequence[str] | None = None,
    n_exponents: int | None = None,
    until: float | None = None,
    dt: float | None = None,
    transient: float | None = None,
    parameters: Mapping[str, float] | None = None,
    dimension: int = 3,
    delay: int = 1,
    min_separation: int | None = None,
    trajectory_length: int = 20,
    skip: int = 0,
) -> LyapunovResult:
    """Return the Lyapunov exponents of a system, or the largest exponent of series.

    An exponent is the average rate at which two nearby runs separate, `|δx(t)| ≈ |δx(0)| exp(λ t)`, and a positive
    largest exponent means chaos, such as `ln 2` per step for the logistic map at `r = 4`. The exponents of a system
    come from its equations, and the largest exponent of a series from how fast its close returns drift apart. It
    measures how fast small errors grow in the weather, a double pendulum, and the orbits of asteroids.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, its compiled problem, or a trajectory of it for `'spectrum'`, or an array of exponents, and
            the trajectory or the array of series for `'largest'`.

        kind:
            What to return. `'spectrum'` gives the largest `n_exponents` exponents of a flow or a map from the initial
            state of the system. The tangent dynamics use the symbolic Jacobian, in which `abs(u)` has the derivative
            `sign(u)`, and the compiled functions take the parameters as an argument, so a sweep over parameter values
            compiles them once. Tangent vectors are made orthonormal again by QR after every step, as in the algorithm
            of Benettin, and the exponents are the average logarithmic growth of the diagonal of `R`. The Kaplan-Yorke
            dimension and the Kolmogorov-Sinai entropy, by the identity of Pesin the sum of the positive exponents,
            follow from the spectrum, and an array of exponents passes through as the spectrum. `'largest'` gives the
            estimate of Rosenstein of the largest exponent of every series, from the divergence of neighbours of its
            delay embedding.

        variables:
            The variables of a trajectory to read for `'largest'`, or `None` for every scalar series.

        n_exponents:
            The number of exponents of the spectrum, or `None` for all of them.

        until:
            The time averaged over, or the number of iterations of a map, or `None` for 1000 for flows and 10,000 for
            maps.

        dt:
            The fixed step of the RK4 integration of flows, or the time between samples of a series, or `None` for
            0.01 and 1.

        transient:
            The time, or the number of iterations, run before averaging, or `None` for a tenth of `until`.

        parameters:
            Values of parameters by dotted path that replace the system's values.

        dimension:
            The dimension of the delay embedding.

        delay:
            The delay of the embedding in steps.

        min_separation:
            The fewest steps between neighbours, or `None` for the mean period from the spectrum.

        trajectory_length:
            The number of steps over which the divergence of neighbours is followed and fitted.

        skip:
            The number of first steps of the divergence left out of the fit, while neighbours align with the unstable
            direction.

    Returns:
        result:
            The spectrum with its dimension and entropy, or the largest exponent of every series.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, or a setting is not positive.

        TagError:
            The system of the source is stochastic, since the exponents need a deterministic system.

    See Also:
        embedding: Gives the points made of delayed copies of one series.
        stability: Finds the fixed points of a system and whether they are stable.

    Examples:
        >>> from skcomplex.core.analysis import lyapunov
        >>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapSystem
        >>> float(lyapunov(LogisticMapSystem(r=4.0), until=20000).exponents[0].round(2))
        0.69
    """
    source = _composite(source)
    _check_choice('lyapunov', 'kind', kind, KINDS)
    _check_tags(lyapunov, source, kind)
    _check_settings(
        lyapunov,
        'kind',
        SETTINGS[kind],
        kind=kind,
        variables=variables,
        n_exponents=n_exponents,
        until=until,
        dt=dt,
        transient=transient,
        parameters=parameters,
        dimension=dimension,
        delay=delay,
        min_separation=min_separation,
        trajectory_length=trajectory_length,
        skip=skip,
    )
    if (dt is not None and dt <= 0) or dimension < 1 or delay < 1:
        error_msg = f'lyapunov has dt={dt!r}, dimension={dimension!r}, and delay={delay!r}. Use positive values.'
        raise AnalysisError(error_msg)
    if kind == 'largest':
        series = _read_series(source, variables)
        largest = np.asarray(
            [
                nolds.lyap_r(
                    np.asarray(column, dtype=float),
                    emb_dim=dimension,
                    lag=delay,
                    min_tsep=min_separation,
                    tau=dt if dt is not None else 1.0,
                    trajectory_len=trajectory_length,
                    fit='poly',
                    fit_offset=skip,
                )
                for column in series.values.T
            ],
            dtype=float,
        )
        return LyapunovResult(values=series.values, labels=series.labels, largest_exponent=largest)
    problem = None
    if isinstance(source, _CompositeSystem | BaseProblemSpec | Trajectory):
        dynamics = StabilityResult._get_dynamics_of(_read_system(source), parameters)
        problem = dynamics.problem
        exponents = _compute_spectrum(dynamics, n_exponents, until, dt, transient)
    else:
        exponents = np.sort(np.asarray(source, dtype=float).ravel())[::-1]
    return LyapunovResult(
        problem=problem,
        exponents=exponents,
        kaplan_yorke_dimension=_kaplan_yorke(exponents),
        kolmogorov_sinai_entropy=float(exponents[exponents > 0].sum()),
    )

markov(source, *, kind='transition-matrix', variables=None, matrix=None, n_states=None, lag=1, lags=(1,), n_timescales=1, n_metastable=None, reversible=True, dt=1.0)

Return the Markov chain of the paths of a source, or of a matrix.

A Markov chain moves between states with chances that depend only on the current state, so it is the matrix of the chances of every move, such as the row [0.5, 0.5] of a state that the path [0, 1, 0, 1, 1] leaves for either state alike. The kinds read the integer states of one path, or one row per path, or a matrix with matrix. It estimates the chain of weather states, credit ratings, and the shapes of a folding protein from their paths.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory of a jump process or of a map with discrete states, an array of integer states with one row per path, or a transition or rate matrix with matrix.

required
kind str

What to return. 'transition-matrix' gives the transitions after lag steps counted along the paths and normalized by row. 'stationary' gives the stationary law pi of the matrix, pi P = pi or pi Q = 0 for rates. 'spectral-gap' gives the gap 1 - |lambda_2|, or -Re lambda_2 for rates, and the relaxation time of every mode. 'state-system' gives the maximum likelihood Markov state model of the largest connected set, with its metastable sets found by PCCA+. 'timescales' gives the slowest implied timescales of Markov state models at every lag of lags, which do not depend on the lag when the states make a Markov chain.

'transition-matrix'
variables Sequence[str] | None

The discrete state of a trajectory to read, or None for the first one.

None
matrix str | None

None to read paths, 'transition' to read the source as a transition matrix, or 'rate' to read it as the rate matrix of a continuous-time chain, whose diagonal is ignored.

None
n_states int | None

The number of states of the paths, or None for the largest state plus one.

None
lag int

The lag time in steps.

1
lags Sequence[int]

The lag times in steps of the implied timescales.

(1,)
n_timescales int

The number of implied timescales.

1
n_metastable int | None

The number of metastable sets PCCA+ groups the states into, or None for none.

None
reversible bool

Whether the state systems obey detailed balance, which PCCA+ needs.

True
dt float

The time of one step.

1.0

Returns:

Name Type Description
result MarkovResult

The paths or the matrix read, and the quantities of the kind.

Raises:

Type Description
AnalysisError

A choice is unknown, a setting the kind does not read is changed, or a setting is out of range.

See Also

passage: Measures the times a path takes to reach a level or a set of states. irreversibility: Measures how far a process is from its reverse in time.

Examples:

>>> from skcomplex.core.analysis import markov
>>> markov([0, 1, 0, 1, 1]).transition_matrix.tolist()
[[0.0, 1.0], [0.5, 0.5]]
Source code in src/skcomplex/core/analysis/_markov.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def markov(
    source: DataSource,
    *,
    kind: str = 'transition-matrix',
    variables: Sequence[str] | None = None,
    matrix: str | None = None,
    n_states: int | None = None,
    lag: int = 1,
    lags: Sequence[int] = (1,),
    n_timescales: int = 1,
    n_metastable: int | None = None,
    reversible: bool = True,
    dt: float = 1.0,
) -> MarkovResult:
    """Return the Markov chain of the paths of a source, or of a matrix.

    A Markov chain moves between states with chances that depend only on the current state, so it is the matrix of
    the chances of every move, such as the row `[0.5, 0.5]` of a state that the path `[0, 1, 0, 1, 1]` leaves for
    either state alike. The kinds read the integer states of one path, or one row per path, or a matrix with `matrix`.
    It estimates the chain of weather states, credit ratings, and the shapes of a folding protein from their paths.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory of a jump process or of a map with discrete states, an array of integer states with one
            row per path, or a transition or rate matrix with `matrix`.

        kind:
            What to return. `'transition-matrix'` gives the transitions after `lag` steps counted along the paths and
            normalized by row. `'stationary'` gives the stationary law `pi` of the matrix, `pi P = pi` or `pi Q = 0`
            for rates. `'spectral-gap'` gives the gap `1 - |lambda_2|`, or `-Re lambda_2` for rates, and the
            relaxation time of every mode. `'state-system'` gives the maximum likelihood Markov state model of the
            largest connected set, with its metastable sets found by PCCA+. `'timescales'` gives the slowest implied
            timescales of Markov state models at every lag of `lags`, which do not depend on the lag when the states
            make a Markov chain.

        variables:
            The discrete state of a trajectory to read, or `None` for the first one.

        matrix:
            `None` to read paths, `'transition'` to read the source as a transition matrix, or `'rate'` to read it as
            the rate matrix of a continuous-time chain, whose diagonal is ignored.

        n_states:
            The number of states of the paths, or `None` for the largest state plus one.

        lag:
            The lag time in steps.

        lags:
            The lag times in steps of the implied timescales.

        n_timescales:
            The number of implied timescales.

        n_metastable:
            The number of metastable sets PCCA+ groups the states into, or `None` for none.

        reversible:
            Whether the state systems obey detailed balance, which PCCA+ needs.

        dt:
            The time of one step.

    Returns:
        result:
            The paths or the matrix read, and the quantities of the kind.

    Raises:
        AnalysisError:
            A choice is unknown, a setting the kind does not read is changed, or a setting is out of range.

    See Also:
        passage: Measures the times a path takes to reach a level or a set of states.
        irreversibility: Measures how far a process is from its reverse in time.

    Examples:
        >>> from skcomplex.core.analysis import markov
        >>> markov([0, 1, 0, 1, 1]).transition_matrix.tolist()
        [[0.0, 1.0], [0.5, 0.5]]
    """
    _check_choice('markov', 'kind', kind, KINDS)
    if matrix is not None:
        _check_choice('markov', 'matrix', matrix, MATRICES)
    _check_settings(
        markov,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        matrix=matrix,
        n_states=n_states,
        lag=lag,
        lags=lags,
        n_timescales=n_timescales,
        n_metastable=n_metastable,
        reversible=reversible,
        dt=dt,
    )
    _check(lag, lags, n_timescales, n_metastable, dt, reversible=reversible)
    if matrix is not None:
        return _of_matrix(np.asarray(source, dtype=float), kind, dt, rates=matrix == 'rate')
    if isinstance(source, Trajectory):
        name = variables[0] if variables else None
        path = _paths(_read_path(source, name).states)
    else:
        path = _paths(np.asarray(source))
    if kind == 'state-system':
        return _state_system(path, lag, n_metastable, dt, reversible=reversible)
    if kind == 'transition-matrix':
        return MarkovResult(
            path=path,
            counts=_transition_counts(path, n_states, lag),
            transition_matrix=_transition_matrix(path, n_states, lag),
        )
    if kind == 'stationary':
        return MarkovResult(path=path, stationary=_stationary_distribution(_transition_matrix(path, n_states, lag)))
    if kind == 'spectral-gap':
        estimated = _transition_matrix(path, n_states, lag)
        return MarkovResult(
            path=path,
            spectral_gap=_spectral_gap(estimated),
            relaxation_times=_relaxation_times(estimated, dt=dt),
        )
    timescales = np.asarray(
        [_implied_timescales(_fit(path, item, reversible=reversible)[1], item)[:n_timescales] * dt for item in lags],
        dtype=float,
    )
    return MarkovResult(path=path, timescales=timescales)

mode_decomposition(source, *, variables=None, rank=None, dictionary=None, inputs=None, validation=0.2, horizon=0, dt=1.0, label='surrogate')

Return the linear system fitted to series by dynamic mode decomposition.

It fits the matrix A of g(t + dt) = A g(t) to the pairs of consecutive samples of every run by the exact DMD of PyDMD, and returns a System that follows dg/dt = L g with L = Phi diag(ln(mu) / dt) Phi^+, starting at the first sample of the first run, such as the frequencies 1 and -1 of a point that turns on the unit circle. With a dictionary, g holds the observables it computes from the variables, and with inputs the fit is g(t + dt) = A g(t) + B u(t) and the system follows dg/dt = L g + M u. It finds the patterns of a fluid flow, brain activity, and traffic in a city, and forecasts them.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source Runs

A trajectory, an array with one row per sample, or several runs as a list or a 3-D array.

required
variables Sequence[str] | None

The variables of trajectories, or None for every scalar state or observable. The inputs join them when they are not listed.

None
rank float | None

The rank of the truncated singular value decomposition: a number of modes, 0 for the optimal hard threshold, a share of the energy below 1, or None to keep every singular value.

None
dictionary TransformerMixin | None

A scikit-learn transformer that computes the observables, such as PolynomialFeatures(2), or None for the variables themselves. This is extended DMD, and the dictionary should keep the variables among its observables.

None
inputs Sequence[str] | None

The names of the variables that are control inputs, or None for none. Every input is a parameter of the surrogate element whose allowed values are its range in the samples, M gives the same one-sample map under an input held over the sample, and the forecast holds the inputs at their last values.

None
validation float

The share of the samples of every run held out at its end to measure the validation error.

0.2
horizon int

The number of samples to forecast after the last sample of the last run, by iterating the map.

0
dt float

The time between the rows of an array.

1.0
label str

The label of the surrogate element.

'surrogate'

Returns:

Name Type Description
result ModeDecompositionResult

The fitted system, its errors, its modes and matrices, and the forecast.

Raises:

Type Description
AnalysisError

The validation share lies outside [0, 1), the horizon is negative, an input is not a variable, or the runs differ in variables or step.

See Also

sparse_identification: Finds nonlinear equations of series from a library of terms. reservoir: Fits a reservoir computer that forecasts series.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import mode_decomposition
>>> times = np.arange(0.0, 10.0, 0.1)
>>> result = mode_decomposition(np.column_stack([np.cos(times), np.sin(times)]), dt=0.1)
>>> np.sort(result.eigenvalues.imag).round(6).tolist()
[-1.0, 1.0]
Source code in src/skcomplex/core/analysis/_mode_decomposition.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def mode_decomposition(
    source: Runs,
    *,
    variables: Sequence[str] | None = None,
    rank: float | None = None,
    dictionary: TransformerMixin | None = None,
    inputs: Sequence[str] | None = None,
    validation: float = 0.2,
    horizon: int = 0,
    dt: float = 1.0,
    label: str = 'surrogate',
) -> ModeDecompositionResult:
    """Return the linear system fitted to series by dynamic mode decomposition.

    It fits the matrix `A` of `g(t + dt) = A g(t)` to the pairs of consecutive samples of every run by the exact DMD of
    PyDMD, and returns a `System` that follows `dg/dt = L g` with `L = Phi diag(ln(mu) / dt) Phi^+`, starting at the
    first sample of the first run, such as the frequencies 1 and -1 of a point that turns on the unit circle. With a
    dictionary, `g` holds the observables it computes from the variables, and with inputs the fit is
    `g(t + dt) = A g(t) + B u(t)` and the system follows `dg/dt = L g + M u`. It finds the patterns of a fluid flow,
    brain activity, and traffic in a city, and forecasts them.

    Read more in the user guide, under Analyse.

    Args:
        source:
            A trajectory, an array with one row per sample, or several runs as a list or a 3-D array.

        variables:
            The variables of trajectories, or `None` for every scalar state or observable. The inputs join them when
            they are not listed.

        rank:
            The rank of the truncated singular value decomposition: a number of modes, 0 for the optimal hard
            threshold, a share of the energy below 1, or `None` to keep every singular value.

        dictionary:
            A scikit-learn transformer that computes the observables, such as `PolynomialFeatures(2)`, or `None` for
            the variables themselves. This is extended DMD, and the dictionary should keep the variables among its
            observables.

        inputs:
            The names of the variables that are control inputs, or `None` for none. Every input is a parameter of the
            surrogate element whose allowed values are its range in the samples, `M` gives the same one-sample map
            under an input held over the sample, and the forecast holds the inputs at their last values.

        validation:
            The share of the samples of every run held out at its end to measure the validation error.

        horizon:
            The number of samples to forecast after the last sample of the last run, by iterating the map.

        dt:
            The time between the rows of an array.

        label:
            The label of the surrogate element.

    Returns:
        result:
            The fitted system, its errors, its modes and matrices, and the forecast.

    Raises:
        AnalysisError:
            The validation share lies outside `[0, 1)`, the horizon is negative, an input is not a variable, or the
            runs differ in variables or step.

    See Also:
        sparse_identification: Finds nonlinear equations of series from a library of terms.
        reservoir: Fits a reservoir computer that forecasts series.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import mode_decomposition
        >>> times = np.arange(0.0, 10.0, 0.1)
        >>> result = mode_decomposition(np.column_stack([np.cos(times), np.sin(times)]), dt=0.1)
        >>> np.sort(result.eigenvalues.imag).round(6).tolist()
        [-1.0, 1.0]
    """
    _check_validation(validation)
    _check_horizon(horizon)
    added = [name for name in inputs or () if name not in (variables or ())]
    read = None if variables is None else [*variables, *added]
    all_samples = _read_samples(source, read, dt)
    samples, input_labels, controls = _split_inputs(all_samples, inputs)
    fitted = None if dictionary is None else clone(dictionary).fit(np.concatenate(samples.series))
    lifted, labels, states = _lift(samples, fitted)
    training, held = _split_samples(lifted, validation)
    driven, driven_held = _split_samples(controls, validation)
    before = np.concatenate([values[:-1] for values in training]).T
    after = np.concatenate([values[1:] for values in training]).T
    applied = np.concatenate([values[:-1] for values in driven]).T
    operator, input_matrix, modes, multipliers = _fit_operators(before, after, applied, rank)
    eigenvalues: ComplexArray = np.asarray(np.log(multipliers) / samples.dt, dtype=complex)
    generator = np.real(modes @ np.diag(eigenvalues) @ np.linalg.pinv(modes))
    input_generator = _input_generator(modes, multipliers, eigenvalues, input_matrix, samples.dt)
    names = _input_names(input_labels, states)
    system = _surrogate_system(
        label,
        dict(zip(states, map(float, lifted[0][0]), strict=True)),
        _linear_laws(states, generator, names, input_generator),
        inputs=_input_declarations(names, controls),
    )
    last_state = np.asarray(lifted[-1][-1], dtype=float)
    return ModeDecompositionResult(
        samples=all_samples,
        system=system,
        labels=labels,
        states=states,
        last_state=last_state,
        dt=samples.dt,
        training_error=_relative_error(*_increments(operator, input_matrix, training, driven)),
        validation_error=_relative_error(*_increments(operator, input_matrix, held, driven_held)),
        eigenvalues=eigenvalues,
        modes=modes,
        amplitudes=np.linalg.lstsq(modes, last_state.astype(complex), rcond=None)[0],
        generator=generator,
        input_generator=input_generator,
        operator=operator,
        input_matrix=input_matrix,
        dictionary=fitted,
        inputs=names,
        forecast=_forecast(last_state, operator, input_matrix, controls[-1][-1], horizon),
    )

motifs(source, *, kind='counts', size=3, null='switch', samples=100, random_state=None)

Return the motifs of three or four nodes of a graph or of the networks of a run.

A motif is a small connected pattern of links, such as a triangle or a path, counted wherever its nodes are linked in that pattern and in no other way, such as the four triangles of four nodes all joined. Directed triads carry the names of the triadic census, such as '030T' for the feedforward loop, undirected motifs the name of their shape, and directed motifs of four nodes their smallest adjacency code. It counts the feedforward loops of a gene network, the triangles of a social network, and the circuits of a food web.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, a graph, or a network snapshot.

required
kind str

What to return. 'counts' gives the number of connected induced subgraphs of every kind. 'z-scores' gives the counts against random graphs that keep the degrees, (count - null_mean) / null_std of every motif, nan where the null count never varies.

'counts'
size int

The number of nodes of the motifs, 3 or 4.

3
null str

'switch' for degree-preserving edge switches, or 'configuration' for the configuration system with self-loops and multiple edges removed.

'switch'
samples int

The number of random graphs.

100
random_state int | None

The seed of the ensemble.

None

Returns:

Name Type Description
result MotifsResult

The graphs and the counts or scores of their motifs.

Raises:

Type Description
AnalysisError

The kind, size, or null ensemble is unknown, a setting the kind does not read is changed, or the number of samples is below 1.

TagError

The system of a trajectory has no network space.

See Also

network_measures: Gives measures of a graph or of the network of every frame. neighbors: Gives the neighbours of agents, grid cells, or network nodes.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.analysis import motifs
>>> motifs(nx.complete_graph(4)).counts
[{'path': 0, 'triangle': 4}]
Source code in src/skcomplex/core/analysis/_motifs.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def motifs(
    source: DataSource,
    *,
    kind: str = 'counts',
    size: int = 3,
    null: str = 'switch',
    samples: int = 100,
    random_state: int | None = None,
) -> MotifsResult:
    """Return the motifs of three or four nodes of a graph or of the networks of a run.

    A motif is a small connected pattern of links, such as a triangle or a path, counted wherever its nodes are linked
    in that pattern and in no other way, such as the four triangles of four nodes all joined. Directed triads carry the
    names of the triadic census, such as `'030T'` for the feedforward loop, undirected motifs the name of their shape,
    and directed motifs of four nodes their smallest adjacency code. It counts the feedforward loops of a gene network,
    the triangles of a social network, and the circuits of a food web.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, a graph, or a network snapshot.

        kind:
            What to return. `'counts'` gives the number of connected induced subgraphs of every kind. `'z-scores'` gives
            the counts against random graphs that keep the degrees, `(count - null_mean) / null_std` of every motif,
            `nan` where the null count never varies.

        size:
            The number of nodes of the motifs, 3 or 4.

        null:
            `'switch'` for degree-preserving edge switches, or `'configuration'` for the configuration system with
            self-loops and multiple edges removed.

        samples:
            The number of random graphs.

        random_state:
            The seed of the ensemble.

    Returns:
        result:
            The graphs and the counts or scores of their motifs.

    Raises:
        AnalysisError:
            The kind, size, or null ensemble is unknown, a setting the kind does not read is changed, or the number of
            samples is below 1.

        TagError:
            The system of a trajectory has no network space.

    See Also:
        network_measures: Gives measures of a graph or of the network of every frame.
        neighbors: Gives the neighbours of agents, grid cells, or network nodes.

    Examples:
        >>> import networkx as nx
        >>> from skcomplex.core.analysis import motifs
        >>> motifs(nx.complete_graph(4)).counts
        [{'path': 0, 'triangle': 4}]
    """
    _check_choice('motifs', 'kind', kind, KINDS)
    _check_tags(motifs, source, kind)
    _check_choice('motifs', 'size', size, SIZES)
    _check_choice('motifs', 'null', null, NULLS)
    _check_settings(
        motifs,
        'kind',
        SETTINGS[kind],
        kind=kind,
        size=size,
        null=null,
        samples=samples,
        random_state=random_state,
    )
    if samples < 1:
        error_msg = f'motifs has samples={samples!r}. Use 1 or more.'
        raise AnalysisError(error_msg)
    graphs = _read_networks(source)
    if kind == 'counts':
        return MotifsResult(graphs, [_motif_counts(graph, size) for graph in graphs])
    scores = [_motif_scores(graph, size, null, samples, random_state) for graph in graphs]
    return MotifsResult(
        graphs,
        [counts for counts, _, _, _ in scores],
        null_mean=[means for _, means, _, _ in scores],
        null_std=[deviations for _, _, deviations, _ in scores],
        z_scores=[values for _, _, _, values in scores],
    )

neighbors(source, *, kind='distances', group=None, variables=None, box=None, bins=100, r_max=None, attribute='state', empty=None, diagonal=True)

Return the neighbours of agents in space, of grid cells, or of network nodes.

An array of positions holds one snapshot, one row per agent, or one snapshot per frame along its first axis, such as a distance of 1 between two points at 0.5 and 9.5 in a periodic box of side 10. A trajectory gives the positions of an agent group with the sides of its periodic space as the box, or its lattice frames for 'like-share'. A grid array is one frame of states, and a graph carries the states on its nodes. It counts the neighbours of birds in a flock, of cells in a tissue, of particles in a liquid, and of households in a city.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array of positions or of states, or a graph.

required
kind str

What to return. 'distances' gives the distance from every agent to its nearest neighbour, across periodic edges in a box. 'clark-evans' gives the mean nearest neighbour distance over its value for uniform random points in a periodic box, 1 for random points, below 1 for clustered ones, and up to 2.15 for a triangular lattice in a plane. 'radial-distribution' gives the radial distribution function g(r) in a periodic box, averaged over frames, 1 for an ideal gas. 'like-share' gives the mean share of the occupied neighbours of an agent that share its state, on a periodic grid or along the edges of a network, near 1 when segregated.

'distances'
group str | None

The path of the agent group of a trajectory, or None for the first one.

None
variables Sequence[str] | None

The lattice state of a trajectory whose frames 'like-share' reads, or None for the first one.

None
box Sequence[float] | None

The sides of a periodic box, or None for the periodic space of a trajectory or for open space.

None
bins int

The number of distance bins of g(r).

100
r_max float | None

The largest distance of g(r), or None for half the smallest side.

None
attribute str

The node attribute of the states of a graph.

'state'
empty float | None

The state of empty cells, left out as agents and as neighbours, or None when every cell is occupied.

None
diagonal bool

Whether grid cells that share only a corner are neighbours, as in Schelling's Moore neighbourhood.

True

Returns:

Name Type Description
result NeighborsResult

The data read and the neighbour statistic of every frame.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, the number of bins is below 1, the agents have no positions, or a kind that needs a periodic box has none.

See Also

clusters: Finds the clusters of a grid, a graph, or points. motifs: Counts the small patterns of links of a network.

Examples:

>>> from skcomplex.core.analysis import neighbors
>>> neighbors([[0.5, 0.0], [9.5, 0.0]], box=[10.0, 10.0]).distances.tolist()
[[1.0, 1.0]]
Source code in src/skcomplex/core/analysis/_neighbors.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def neighbors(
    source: DataSource,
    *,
    kind: str = 'distances',
    group: str | None = None,
    variables: Sequence[str] | None = None,
    box: Sequence[float] | None = None,
    bins: int = 100,
    r_max: float | None = None,
    attribute: str = 'state',
    empty: float | None = None,
    diagonal: bool = True,
) -> NeighborsResult:
    """Return the neighbours of agents in space, of grid cells, or of network nodes.

    An array of positions holds one snapshot, one row per agent, or one snapshot per frame along its first axis, such
    as a distance of 1 between two points at 0.5 and 9.5 in a periodic box of side 10. A trajectory gives the positions
    of an agent group with the sides of its periodic space as the box, or its lattice frames for `'like-share'`. A grid
    array is one frame of states, and a graph carries the states on its nodes. It counts the neighbours of birds in a
    flock, of cells in a tissue, of particles in a liquid, and of households in a city.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array of positions or of states, or a graph.

        kind:
            What to return. `'distances'` gives the distance from every agent to its nearest neighbour, across periodic
            edges in a box. `'clark-evans'` gives the mean nearest neighbour distance over its value for uniform random
            points in a periodic box, 1 for random points, below 1 for clustered ones, and up to 2.15 for a triangular
            lattice in a plane. `'radial-distribution'` gives the radial distribution function `g(r)` in a periodic box,
            averaged over frames, 1 for an ideal gas. `'like-share'` gives the mean share of the occupied neighbours of
            an agent that share its state, on a periodic grid or along the edges of a network, near 1 when segregated.

        group:
            The path of the agent group of a trajectory, or `None` for the first one.

        variables:
            The lattice state of a trajectory whose frames `'like-share'` reads, or `None` for the first one.

        box:
            The sides of a periodic box, or `None` for the periodic space of a trajectory or for open space.

        bins:
            The number of distance bins of `g(r)`.

        r_max:
            The largest distance of `g(r)`, or `None` for half the smallest side.

        attribute:
            The node attribute of the states of a graph.

        empty:
            The state of empty cells, left out as agents and as neighbours, or `None` when every cell is occupied.

        diagonal:
            Whether grid cells that share only a corner are neighbours, as in Schelling's Moore neighbourhood.

    Returns:
        result:
            The data read and the neighbour statistic of every frame.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, the number of bins is below 1, the agents
            have no positions, or a kind that needs a periodic box has none.

    See Also:
        clusters: Finds the clusters of a grid, a graph, or points.
        motifs: Counts the small patterns of links of a network.

    Examples:
        >>> from skcomplex.core.analysis import neighbors
        >>> neighbors([[0.5, 0.0], [9.5, 0.0]], box=[10.0, 10.0]).distances.tolist()
        [[1.0, 1.0]]
    """
    if kind not in KINDS:
        error_msg = f'neighbors has kind={kind!r}. Use one of {", ".join(KINDS)}.'
        raise AnalysisError(error_msg)
    _check_settings(
        neighbors,
        'kind',
        SETTINGS[kind],
        kind=kind,
        group=group,
        variables=variables,
        box=box,
        bins=bins,
        r_max=r_max,
        attribute=attribute,
        empty=empty,
        diagonal=diagonal,
    )
    if bins < 1:
        error_msg = f'neighbors has bins={bins!r}. Use 1 or more.'
        raise AnalysisError(error_msg)
    if kind == 'like-share':
        frames = _read_states(source, variables)
        shares = [_like_neighbor_share(frame, attribute=attribute, empty=empty, diagonal=diagonal) for frame in frames]
        return NeighborsResult(frames=frames, share=np.asarray(shares))
    positions, sides = _read_positions(source, group, box)
    if kind == 'distances':
        distances = np.asarray([_nearest_neighbor_distances(frame, sides) for frame in positions])
        return NeighborsResult(positions=positions, box=sides, distances=distances)
    if sides is None:
        error_msg = f'neighbors of kind {kind!r} needs a periodic box. Set `box` to its sides.'
        raise AnalysisError(error_msg)
    if kind == 'clark-evans':
        ratio = np.asarray([_clark_evans_ratio(frame, sides) for frame in positions])
        return NeighborsResult(positions=positions, box=sides, ratio=ratio)
    radii, distribution = _radial_distribution(positions, sides, bins, r_max)
    return NeighborsResult(positions=positions, box=sides, radii=radii, distribution=distribution)

network_measures(source, *, kind='summary', orders=(1, 2), attribute=None, numeric=False, measure='degree', method='louvain', reference=None, random_state=None)

Return measures of a graph or of the network of every frame of a trajectory.

A network is a set of nodes joined by links, and the measures describe how many links each node has, how they cluster, and how far apart nodes are, such as the mean degree 2, clustering 0, and diameter 5 of a ring of 10 nodes. The kinds read the graph of every frame. It measures the hubs of the internet, the clustering of a social network, and the paths of a power grid.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, a graph, or a network snapshot.

required
kind str

What to return. 'degrees' gives the degree of every node, the moments <k^n> of the degree distribution for every order of orders, and the fitted exponent of a heavy tailed degree distribution, nan below 50 nodes or for a narrow one. 'assortativity' gives the assortativity by degree, or by a node attribute, positive when linked nodes are alike. 'centrality' gives the degree, betweenness, closeness, eigenvector, or PageRank centrality of every node. 'communities' gives the communities by Louvain modularity maximization or label propagation, their modularity, and their agreement with a reference partition. 'neighbor-degree' gives the mean degree of the neighbours of nodes against their degree, rising in assortative networks. 'summary' gives the size, mean degree, clustering, path length, diameter, and components, with the path measures on the largest component.

'summary'
orders Sequence[int]

The orders n of the degree moments.

(1, 2)
attribute str | None

The node attribute of the assortativity, or None for the degree.

None
numeric bool

Whether the attribute is a number compared by correlation rather than a category compared by equality.

False
measure str

The centrality: 'degree', 'betweenness', 'closeness', 'eigenvector', or 'pagerank'.

'degree'
method str

The community detection: 'louvain' or 'label_propagation'.

'louvain'
reference Sequence[object] | str | None

The reference community of every node in node order, the name of a node attribute that holds it, or None.

None
random_state int | None

The seed of the Louvain method.

None

Returns:

Name Type Description
result NetworkMeasuresResult

The graphs and the measure of every frame.

Raises:

Type Description
AnalysisError

The kind, centrality, or method is unknown, or a setting the kind does not read is changed.

TagError

The system of a trajectory has no network space.

See Also

motifs: Counts the small patterns of links of a network. neighbors: Gives the neighbours of agents, grid cells, or network nodes.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.analysis import network_measures
>>> summary = network_measures(nx.cycle_graph(10))
>>> summary.mean_degree.tolist(), summary.clustering.tolist(), summary.diameter.tolist()
([2.0], [0.0], [5])
Source code in src/skcomplex/core/analysis/_networks.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def network_measures(
    source: DataSource,
    *,
    kind: str = 'summary',
    orders: Sequence[int] = (1, 2),
    attribute: str | None = None,
    numeric: bool = False,
    measure: str = 'degree',
    method: str = 'louvain',
    reference: Sequence[object] | str | None = None,
    random_state: int | None = None,
) -> NetworkMeasuresResult:
    """Return measures of a graph or of the network of every frame of a trajectory.

    A network is a set of nodes joined by links, and the measures describe how many links each node has, how they
    cluster, and how far apart nodes are, such as the mean degree 2, clustering 0, and diameter 5 of a ring of 10
    nodes. The kinds read the graph of every frame. It measures the hubs of the internet, the clustering of a social
    network, and the paths of a power grid.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, a graph, or a network snapshot.

        kind:
            What to return. `'degrees'` gives the degree of every node, the moments `<k^n>` of the degree distribution
            for every order of `orders`, and the fitted exponent of a heavy tailed degree distribution, `nan` below 50
            nodes or for a narrow one. `'assortativity'` gives the assortativity by degree, or by a node attribute,
            positive when linked nodes are alike. `'centrality'` gives the degree, betweenness, closeness, eigenvector,
            or PageRank centrality of every node. `'communities'` gives the communities by Louvain modularity
            maximization or label propagation, their modularity, and their agreement with a reference partition.
            `'neighbor-degree'` gives the mean degree of the neighbours of nodes against their degree, rising in
            assortative networks. `'summary'` gives the size, mean degree, clustering, path length, diameter, and
            components, with the path measures on the largest component.

        orders:
            The orders `n` of the degree moments.

        attribute:
            The node attribute of the assortativity, or `None` for the degree.

        numeric:
            Whether the attribute is a number compared by correlation rather than a category compared by equality.

        measure:
            The centrality: `'degree'`, `'betweenness'`, `'closeness'`, `'eigenvector'`, or `'pagerank'`.

        method:
            The community detection: `'louvain'` or `'label_propagation'`.

        reference:
            The reference community of every node in node order, the name of a node attribute that holds it, or
            `None`.

        random_state:
            The seed of the Louvain method.

    Returns:
        result:
            The graphs and the measure of every frame.

    Raises:
        AnalysisError:
            The kind, centrality, or method is unknown, or a setting the kind does not read is changed.

        TagError:
            The system of a trajectory has no network space.

    See Also:
        motifs: Counts the small patterns of links of a network.
        neighbors: Gives the neighbours of agents, grid cells, or network nodes.

    Examples:
        >>> import networkx as nx
        >>> from skcomplex.core.analysis import network_measures
        >>> summary = network_measures(nx.cycle_graph(10))
        >>> summary.mean_degree.tolist(), summary.clustering.tolist(), summary.diameter.tolist()
        ([2.0], [0.0], [5])
    """
    _check_choice('network_measures', 'kind', kind, KINDS)
    _check_tags(network_measures, source, kind)
    _check_choice('network_measures', 'measure', measure, CENTRALITIES)
    _check_choice('network_measures', 'method', method, METHODS)
    _check_settings(
        network_measures,
        'kind',
        SETTINGS[kind],
        kind=kind,
        orders=orders,
        attribute=attribute,
        numeric=numeric,
        measure=measure,
        method=method,
        reference=reference,
        random_state=random_state,
    )
    graphs = _read_networks(source)
    if kind == 'summary':
        rows = [_summary(graph) for graph in graphs]
        return NetworkMeasuresResult(
            graphs,
            nodes=np.asarray([row['nodes'] for row in rows], dtype=int),
            edges=np.asarray([row['edges'] for row in rows], dtype=int),
            mean_degree=np.asarray([row['mean_degree'] for row in rows], dtype=float),
            clustering=np.asarray([row['clustering'] for row in rows], dtype=float),
            path_length=np.asarray([row['path_length'] for row in rows], dtype=float),
            diameter=np.asarray([row['diameter'] for row in rows], dtype=int),
            components=[row['components'] for row in rows if isinstance(row['components'], list)],
        )
    if kind == 'degrees':
        degrees = [_degrees(graph) for graph in graphs]
        return NetworkMeasuresResult(
            graphs,
            degrees=degrees,
            moments=np.asarray(
                [[float(np.mean(values.astype(float) ** order)) for order in orders] for values in degrees],
            ),
            exponent=np.asarray([_degree_exponent(graph) for graph in graphs]),
        )
    if kind == 'assortativity':
        assortativity = np.asarray([_assortativity(graph, attribute, numeric=numeric) for graph in graphs])
        return NetworkMeasuresResult(graphs, assortativity=assortativity)
    if kind == 'centrality':
        return NetworkMeasuresResult(graphs, centrality=[_centrality(graph, measure) for graph in graphs])
    if kind == 'neighbor-degree':
        pairs = [_neighbor_degree(graph) for graph in graphs]
        return NetworkMeasuresResult(
            graphs,
            distinct_degrees=[degrees for degrees, _ in pairs],
            neighbor_degree=[connectivity for _, connectivity in pairs],
        )
    found = [_communities(graph, method, reference, random_state) for graph in graphs]
    return NetworkMeasuresResult(
        graphs,
        labels=[labels for labels, _, _ in found],
        modularity=np.asarray([modularity for _, modularity, _ in found]),
        agreement=None if reference is None else np.asarray([agreement for _, _, agreement in found]),
    )

partial_information(source, *, variables=None, redundancy='mmi', base=2.0)

Return the partial information decomposition of two sources about a target.

The source holds three series: the first source, the second source, and the target. The mutual information of the two sources together with the target splits into the information both give, the information only one of them gives, and the information only the two together give, with a redundancy measure of dit, such as 1 bit of synergy for a target that is the exclusive or of the sources. It splits what two genes tell about a trait, or two neurons about a stimulus, into unique, shared, and synergistic parts.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of three columns: the two sources and the target.

required
variables Sequence[str] | None

The variables of a trajectory to read, the two sources and the target, or None for every scalar series.

None
redundancy str

The redundancy measure of dit: 'mmi' for the minimum mutual information, 'williams_beer' for I_min, 'broja', 'ccs', 'pm', or 'dep'.

'mmi'
base float

The base of the logarithm, 2 for bits.

2.0

Returns:

Name Type Description
result PartialInformationResult

The symbols and the four parts of the information with their sum.

Raises:

Type Description
AnalysisError

The redundancy measure is unknown, the base is not positive, or the source does not hold three series.

See Also

information: Gives the information among series, such as the O-information of many series. local_information: Gives the information at every time step.

Examples:

>>> from skcomplex.core.analysis import partial_information
>>> xor = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
>>> parts = partial_information(xor)
>>> round(parts.synergy, 6), round(parts.redundancy, 6)
(1.0, 0.0)
Source code in src/skcomplex/core/analysis/_partial_information.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def partial_information(
    source: DataSource,
    *,
    variables: Sequence[str] | None = None,
    redundancy: str = 'mmi',
    base: float = 2.0,
) -> PartialInformationResult:
    """Return the partial information decomposition of two sources about a target.

    The source holds three series: the first source, the second source, and the target. The mutual information of the
    two sources together with the target splits into the information both give, the information only one of them
    gives, and the information only the two together give, with a redundancy measure of `dit`, such as 1 bit of synergy
    for a target that is the exclusive or of the sources. It splits what two genes tell about a trait, or two neurons
    about a stimulus, into unique, shared, and synergistic parts.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of three columns: the two sources and the target.

        variables:
            The variables of a trajectory to read, the two sources and the target, or `None` for every scalar series.

        redundancy:
            The redundancy measure of `dit`: `'mmi'` for the minimum mutual information, `'williams_beer'` for
            `I_min`, `'broja'`, `'ccs'`, `'pm'`, or `'dep'`.

        base:
            The base of the logarithm, 2 for bits.

    Returns:
        result:
            The symbols and the four parts of the information with their sum.

    Raises:
        AnalysisError:
            The redundancy measure is unknown, the base is not positive, or the source does not hold three series.

    See Also:
        information: Gives the information among series, such as the O-information of many series.
        local_information: Gives the information at every time step.

    Examples:
        >>> from skcomplex.core.analysis import partial_information
        >>> xor = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
        >>> parts = partial_information(xor)
        >>> round(parts.synergy, 6), round(parts.redundancy, 6)
        (1.0, 0.0)
    """
    if redundancy not in REDUNDANCIES:
        error_msg = f'partial_information has redundancy={redundancy!r}. Use one of {", ".join(REDUNDANCIES)}.'
        raise AnalysisError(error_msg)
    if base <= 0:
        error_msg = f'partial_information has base={base!r}. Use a positive base.'
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    if series.values.shape[1] != SERIES:
        error_msg = (
            f'partial_information reads two sources and a target, but the source has {series.values.shape[1]} series. '
            'Select three with `variables` or pass an array of three columns.'
        )
        raise AnalysisError(error_msg)
    columns = np.column_stack([column.ravel() for column in series.values.T])
    measure = getattr(load_module('dit').pid, REDUNDANCIES[redundancy])
    lattice = measure(_dit_distribution(columns), [[0], [1]], [2])
    scale = math.log(2) / math.log(base)
    shared = float(lattice.get_pi(((0,), (1,)))) * scale
    unique_first = float(lattice.get_pi(((0,),))) * scale
    unique_second = float(lattice.get_pi(((1,),))) * scale
    synergy = float(lattice.get_pi(((0, 1),))) * scale
    return PartialInformationResult(
        series.values,
        series.labels,
        shared,
        unique_first,
        unique_second,
        synergy,
        shared + unique_first + unique_second + synergy,
    )

passage(source, *, kind='first-passage', variables=None, threshold=None, target=None, origin=None, direction='up', level=0.0, lag=1, dt=1.0)

Return the passages of paths to a level or a set, or of a Markov chain.

A first passage is the first time a path reaches a level or enters a set of states, such as the time 2 of a path that climbs one step at a time to the level 2, and a path that never gets there has nan. The kinds read paths, one row per path on common times, or a transition matrix, which the matrix kinds estimate at lag from the jump path of a trajectory. It finds the time until a population dies out, a price hits a barrier, or a protein folds.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, an array of paths, one row per path, a series for 'return-times', or a transition matrix for the matrix kinds.

required
kind str

What to return. 'first-passage' gives the first time every path reaches threshold, from below for direction='up' and from above for 'down', or enters the target states. 'hitting' gives the share of paths that reach each of the absorbing target states before the others. 'return-times' gives the times between successive returns of a series to level, by visit or by crossing. 'committor' gives the forward committor of a transition matrix, the probability that the chain reaches the target states before the origin states. 'mean-first-passage' gives the mean first passage time of a transition matrix at lag from the origin states, started in their stationary weights, to the target states.

'first-passage'
variables Sequence[str] | None

The discrete state of a trajectory to read, or the series for 'return-times', or None for the first.

None
threshold float | None

The level a first passage reaches.

None
target Sequence[float] | None

The states that end a passage, the absorbing states, or the target set of the chain.

None
origin Sequence[float] | None

The origin set of the chain.

None
direction str

'up' to reach values at or above the threshold, 'down' at or below it.

'up'
level float

The level of the returns.

0.0
lag int

The lag of the transition matrix in steps.

1
dt float

The time of one step of an array, while a trajectory gives its own times.

1.0

Returns:

Name Type Description
result PassageResult

The paths, the series, or the matrix read, and the passages of the kind.

Raises:

Type Description
AnalysisError

A choice is unknown, a setting the kind does not read is changed, the sets the kind needs are missing, a setting is not positive, or the matrix is reducible.

See Also

markov: Estimates the Markov chain of a discrete path. events: Finds the runs of a series above a threshold.

Examples:

>>> from skcomplex.core.analysis import passage
>>> passage([[0, 1, 2, 3], [0, 0, 0, 0]], threshold=2).passage_times.tolist()
[2.0, nan]
>>> passage([0, 1, 0, -1, -2, -1, 0], kind='return-times').return_times.tolist()
[2.0, 4.0]
Source code in src/skcomplex/core/analysis/_passage.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def passage(
    source: DataSource,
    *,
    kind: str = 'first-passage',
    variables: Sequence[str] | None = None,
    threshold: float | None = None,
    target: Sequence[float] | None = None,
    origin: Sequence[float] | None = None,
    direction: str = 'up',
    level: float = 0.0,
    lag: int = 1,
    dt: float = 1.0,
) -> PassageResult:
    """Return the passages of paths to a level or a set, or of a Markov chain.

    A first passage is the first time a path reaches a level or enters a set of states, such as the time 2 of a path
    that climbs one step at a time to the level 2, and a path that never gets there has `nan`. The kinds read paths,
    one row per path on common times, or a transition matrix, which the matrix kinds estimate at `lag` from the jump
    path of a trajectory. It finds the time until a population dies out, a price hits a barrier, or a protein folds.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, an array of paths, one row per path, a series for `'return-times'`, or a transition
            matrix for the matrix kinds.

        kind:
            What to return. `'first-passage'` gives the first time every path reaches `threshold`, from below for
            `direction='up'` and from above for `'down'`, or enters the `target` states. `'hitting'` gives the share of
            paths that reach each of the absorbing `target` states before the others. `'return-times'` gives the times
            between successive returns of a series to `level`, by visit or by crossing. `'committor'` gives the forward
            committor of a transition matrix, the probability that the chain reaches the `target` states before the
            `origin` states. `'mean-first-passage'` gives the mean first passage time of a transition matrix at `lag`
            from the `origin` states, started in their stationary weights, to the `target` states.

        variables:
            The discrete state of a trajectory to read, or the series for `'return-times'`, or `None` for the first.

        threshold:
            The level a first passage reaches.

        target:
            The states that end a passage, the absorbing states, or the target set of the chain.

        origin:
            The origin set of the chain.

        direction:
            `'up'` to reach values at or above the threshold, `'down'` at or below it.

        level:
            The level of the returns.

        lag:
            The lag of the transition matrix in steps.

        dt:
            The time of one step of an array, while a trajectory gives its own times.

    Returns:
        result:
            The paths, the series, or the matrix read, and the passages of the kind.

    Raises:
        AnalysisError:
            A choice is unknown, a setting the kind does not read is changed, the sets the kind needs are missing, a
            setting is not positive, or the matrix is reducible.

    See Also:
        markov: Estimates the Markov chain of a discrete path.
        events: Finds the runs of a series above a threshold.

    Examples:
        >>> from skcomplex.core.analysis import passage
        >>> passage([[0, 1, 2, 3], [0, 0, 0, 0]], threshold=2).passage_times.tolist()
        [2.0, nan]
        >>> passage([0, 1, 0, -1, -2, -1, 0], kind='return-times').return_times.tolist()
        [2.0, 4.0]
    """
    _check_choice('passage', 'kind', kind, KINDS)
    _check_choice('passage', 'direction', direction, DIRECTIONS)
    _check_settings(
        passage,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        threshold=threshold,
        target=target,
        origin=origin,
        direction=direction,
        level=level,
        lag=lag,
        dt=dt,
    )
    _check(kind, threshold=threshold, target=target, origin=origin, lag=lag, dt=dt)
    name = variables[0] if variables else None
    if kind in MATRIX_KINDS:
        if isinstance(source, Trajectory):
            states = np.asarray(_read_path(source, name).states, dtype=np.int64)
            matrix = _transition_matrix(states, lag=lag)
        else:
            matrix = np.asarray(source, dtype=float)
        if kind == 'committor':
            chain = MarkovChain(matrix)
            committor = chain.committor_probabilities('forward', _get_indices(origin), _get_indices(target))
            return PassageResult(matrix=matrix, committor=np.asarray(committor, dtype=float))
        time = _mean_first_passage(matrix, origin, target, lag, dt)
        return PassageResult(matrix=matrix, mean_first_passage_time=time)
    if kind == 'return-times':
        series = _read_series(source, variables)
        times = series.times if isinstance(source, Trajectory) else series.times * dt
        return _returns(series.values[:, 0], times, level)
    if isinstance(source, Trajectory):
        path = _read_path(source, name)
        values = _rows(path.states)
        times = np.asarray(path.times, dtype=float)
    else:
        values = _rows(np.asarray(source))
        times = np.arange(values.shape[1], dtype=float) * dt
    if kind == 'first-passage':
        return _first_passage(values, times, threshold, target, direction)
    targets = _get_states(target)
    first = _first_hits(np.isin(values, np.asarray(targets, dtype=float)))
    reached = values[np.arange(values.shape[0]), np.maximum(first, 0)]
    probabilities = np.asarray([np.mean((first >= 0) & (reached == state)) for state in targets], dtype=float)
    return PassageResult(values, times, hitting_probabilities=probabilities)

recurrence(source, *, variables=None, radius=None, rate=0.05, min_line=2, theiler=1, random_state=0)

Return which states of a run come close to each other, with statistics.

A run recurs when it returns close to a state it visited before. Every row of the series is a point, such as an embedded series or the states of a trajectory, and the recurrence matrix marks every pair of times whose points lie within radius of each other. The statistics of its diagonal and vertical lines tell periodic, chaotic, and random runs apart, such as a determinism near 1 for a sine wave. It finds regular rhythms in heart rate records, regime changes in climate series, and periodic orbits in simulated oscillators.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array with one row per point and one column per coordinate.

required
variables Sequence[str] | None

The variables of a trajectory to read as coordinates, or None for every scalar series.

None
radius float | None

The recurrence radius, or None to choose the radius that gives the recurrence rate.

None
rate float

The share of recurrent pairs when the radius is not given.

0.05
min_line int

The shortest diagonal or vertical line counted.

2
theiler int

The number of diagonals next to the main one to leave out, so that states close in time do not count as returns. 1 leaves out the main diagonal alone.

1
random_state int | None

The seed of the sample of pairs that sets the radius of large sets.

0

Returns:

Name Type Description
result RecurrenceResult

The points, the recurrence matrix, and its quantification.

Raises:

Type Description
AnalysisError

A setting is out of range, or no pair of points recurs outside the Theiler window.

See Also

embedding: Gives the points made of delayed copies of one series. passage: Measures the times between the returns of a series to a level.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import embedding, recurrence
>>> sine = embedding(np.sin(np.arange(2000) * 0.1), delay=15, dimension=2)
>>> bool(recurrence(sine.points).determinism > 0.95)
True
Source code in src/skcomplex/core/analysis/_recurrence.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def recurrence(
    source: DataSource,
    *,
    variables: Sequence[str] | None = None,
    radius: float | None = None,
    rate: float = 0.05,
    min_line: int = 2,
    theiler: int = 1,
    random_state: int | None = 0,
) -> RecurrenceResult:
    """Return which states of a run come close to each other, with statistics.

    A run recurs when it returns close to a state it visited before. Every row of the series is a point, such as an
    embedded series or the states of a trajectory, and the recurrence matrix marks every pair of times whose points lie
    within `radius` of each other. The statistics of its diagonal and vertical lines tell periodic, chaotic, and random
    runs apart, such as a determinism near 1 for a sine wave. It finds regular rhythms in heart rate records, regime
    changes in climate series, and periodic orbits in simulated oscillators.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array with one row per point and one column per coordinate.

        variables:
            The variables of a trajectory to read as coordinates, or `None` for every scalar series.

        radius:
            The recurrence radius, or `None` to choose the radius that gives the recurrence rate.

        rate:
            The share of recurrent pairs when the radius is not given.

        min_line:
            The shortest diagonal or vertical line counted.

        theiler:
            The number of diagonals next to the main one to leave out, so that states close in time do not count as
            returns. 1 leaves out the main diagonal alone.

        random_state:
            The seed of the sample of pairs that sets the radius of large sets.

    Returns:
        result:
            The points, the recurrence matrix, and its quantification.

    Raises:
        AnalysisError:
            A setting is out of range, or no pair of points recurs outside the Theiler window.

    See Also:
        embedding: Gives the points made of delayed copies of one series.
        passage: Measures the times between the returns of a series to a level.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import embedding, recurrence
        >>> sine = embedding(np.sin(np.arange(2000) * 0.1), delay=15, dimension=2)
        >>> bool(recurrence(sine.points).determinism > 0.95)
        True
    """
    if (radius is not None and radius <= 0) or not 0 < rate < 1:
        error_msg = (
            f'recurrence has radius={radius!r} and rate={rate!r}. Use a positive radius or None, and a rate between 0 '
            'and 1.'
        )
        raise AnalysisError(error_msg)
    if min_line < 1 or theiler < 0:
        error_msg = (
            f'recurrence has min_line={min_line!r} and theiler={theiler!r}. Use a shortest line of 1 or more and a '
            'Theiler window of 0 or more.'
        )
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    array = series.values
    chosen = _radius_for_rate(array, rate, random_state) if radius is None else radius
    recurrences = _recurrence_matrix(array, chosen)
    matrix = recurrences.tocoo()
    rows, columns = matrix.row.astype(np.int64), matrix.col.astype(np.int64)
    outside = np.abs(rows - columns) >= theiler
    rows, columns = rows[outside], columns[outside]
    if not rows.size:
        error_msg = (
            f'No pair of points recurs within radius {chosen} outside the Theiler window {theiler}. Use a larger '
            'radius or rate.'
        )
        raise AnalysisError(error_msg)
    diagonals = _run_lengths(columns - rows, rows)
    verticals = _run_lengths(columns, rows)
    long_diagonals = diagonals[diagonals >= min_line]
    long_verticals = verticals[verticals >= min_line]
    _, counts = np.unique(long_diagonals, return_counts=True)
    size = array.shape[0]
    allowed = size * size - size - 2 * sum(size - offset for offset in range(1, theiler))
    return RecurrenceResult(
        values=array,
        labels=series.labels,
        radius=chosen,
        matrix=recurrences,
        rate=float(rows.size / max(allowed, 1)),
        determinism=_line_share(diagonals, min_line, rows.size),
        laminarity=_line_share(verticals, min_line, rows.size),
        mean_diagonal=float(long_diagonals.mean()) if long_diagonals.size else 0.0,
        longest_diagonal=int(diagonals.max()),
        trapping_time=float(long_verticals.mean()) if long_verticals.size else 0.0,
        entropy=float(stats.entropy(counts)) if counts.size else 0.0,
    )

renormalization(source, *, kind='laplacian', steps=3, time=None, block=2, angle='angle', beta=1.0)

Return the network at every scale of a coarse-graining of a graph or trajectory.

Every step merges nodes into supernodes, and two supernodes link when any of their nodes link, such as two dense groups joined by one link that become two linked supernodes. A trajectory gives the network of its last frame, with the values of the states and parameters of the group on its nodes as node attributes. It coarse-grains the internet, the brain, and transport networks to find their structure across scales.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, a graph, or a network snapshot.

required
kind str

How to merge. 'laplacian' joins two nodes whose entry of the diffusion operator K = exp(-time L) is at least the smaller of their diagonal entries, and every connected component of these joins is a supernode. It runs at time, or else at the smallest local peak of the specific heat C = -dS / d log(time), of the entropy of the operator normalized by its trace, at which at least one pair of nodes joins, and a network with no such peak stays as it is. 'geometric' makes every block consecutive nodes in the order of their angle a supernode, with the last block holding the nodes left over. The supernode sits at the mean angle of its nodes weighted by z = k^max(1, beta), with the degree k of a node, which is proportional to its hidden degree in the geometric system.

'laplacian'
steps int

The number of times the network is coarse-grained.

3
time float | None

The diffusion time of 'laplacian', or None for the peak of the specific heat.

None
block int

The number of nodes of every supernode of 'geometric'.

2
angle str

The node attribute that holds the angle of 'geometric'.

'angle'
beta float

The parameter of the geometric system that the weights of the angles of 'geometric' read, the inverse of its temperature.

1.0

Returns:

Name Type Description
result RenormalizationResult

The network at every scale and its measures.

Raises:

Type Description
AnalysisError

The kind is unknown, the kind does not read a changed setting, steps is below 1, block is below 2, time or beta is not positive, or a node has no angle.

TagError

The system of a trajectory has no network space.

See Also

clusters: Finds the clusters of a grid, a graph, or points. network_measures: Gives measures of a graph or of the network of every frame.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.analysis import renormalization
>>> blocks = nx.disjoint_union(nx.complete_graph(20), nx.complete_graph(20))
>>> blocks.add_edge(0, 20)
>>> sorted(renormalization(blocks, steps=1).graphs[1].degree())
[(0, 1), (1, 1)]
Source code in src/skcomplex/core/analysis/_renormalization.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def renormalization(
    source: DataSource,
    *,
    kind: str = 'laplacian',
    steps: int = 3,
    time: float | None = None,
    block: int = 2,
    angle: str = 'angle',
    beta: float = 1.0,
) -> RenormalizationResult:
    """Return the network at every scale of a coarse-graining of a graph or trajectory.

    Every step merges nodes into supernodes, and two supernodes link when any of their nodes link, such as two dense
    groups joined by one link that become two linked supernodes. A trajectory gives the network of its last frame, with
    the values of the states and parameters of the group on its nodes as node attributes. It coarse-grains the
    internet, the brain, and transport networks to find their structure across scales.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, a graph, or a network snapshot.

        kind:
            How to merge. `'laplacian'` joins two nodes whose entry of the diffusion operator `K = exp(-time L)` is at
            least the smaller of their diagonal entries, and every connected component of these joins is a supernode.
            It runs at `time`, or else at the smallest local peak of the specific heat `C = -dS / d log(time)`, of the
            entropy of the operator normalized by its trace, at which at least one pair of nodes joins, and a network
            with no such peak stays as it is. `'geometric'` makes every `block` consecutive nodes in the order of their
            `angle` a supernode, with the last block holding the nodes left over. The supernode sits at the mean angle
            of its nodes weighted by `z = k^max(1, beta)`, with the degree `k` of a node, which is proportional to its
            hidden degree in the geometric system.

        steps:
            The number of times the network is coarse-grained.

        time:
            The diffusion time of `'laplacian'`, or `None` for the peak of the specific heat.

        block:
            The number of nodes of every supernode of `'geometric'`.

        angle:
            The node attribute that holds the angle of `'geometric'`.

        beta:
            The parameter of the geometric system that the weights of the angles of `'geometric'` read, the inverse of
            its temperature.

    Returns:
        result:
            The network at every scale and its measures.

    Raises:
        AnalysisError:
            The kind is unknown, the kind does not read a changed setting, `steps` is below 1, `block` is below 2,
            `time` or `beta` is not positive, or a node has no angle.

        TagError:
            The system of a trajectory has no network space.

    See Also:
        clusters: Finds the clusters of a grid, a graph, or points.
        network_measures: Gives measures of a graph or of the network of every frame.

    Examples:
        >>> import networkx as nx
        >>> from skcomplex.core.analysis import renormalization
        >>> blocks = nx.disjoint_union(nx.complete_graph(20), nx.complete_graph(20))
        >>> blocks.add_edge(0, 20)
        >>> sorted(renormalization(blocks, steps=1).graphs[1].degree())
        [(0, 1), (1, 1)]
    """
    _check_choice('renormalization', 'kind', kind, KINDS)
    _check_tags(renormalization, source, kind)
    _check_settings(
        renormalization,
        'kind',
        SETTINGS[kind],
        kind=kind,
        steps=steps,
        time=time,
        block=block,
        angle=angle,
        beta=beta,
    )
    if steps < 1:
        error_msg = f'renormalization has steps={steps!r}. Use 1 or more.'
        raise AnalysisError(error_msg)
    if block < MIN_BLOCK:
        error_msg = f'renormalization has block={block!r}. Use {MIN_BLOCK} or more.'
        raise AnalysisError(error_msg)
    if time is not None and time <= 0:
        error_msg = f'renormalization has time={time!r}. Use a positive time, or None.'
        raise AnalysisError(error_msg)
    if beta <= 0:
        error_msg = f'renormalization has beta={beta!r}. Use a positive value.'
        raise AnalysisError(error_msg)
    graph = _read_frame(source) if isinstance(source, Trajectory) else _read_networks(source)[-1]
    graphs = [graph.to_undirected()]
    for _ in range(steps):
        if kind == 'geometric':
            graphs.append(_merge_by_angle(graphs[-1], angle, block, beta))
        else:
            graphs.append(_coarsen(graphs[-1], time))
    measures = [network_measures(item, kind='degrees') for item in graphs]
    return RenormalizationResult(
        graph,
        graphs,
        degrees=[measure.degrees[0] for measure in measures if measure.degrees is not None],
        exponents=np.asarray(
            [measure.exponent[0] for measure in measures if measure.exponent is not None],
            dtype=float,
        ),
        clustering=np.asarray([nx.average_clustering(item) for item in graphs], dtype=float),
    )

reservoir(source, *, variables=None, kind='next_generation', delay=2, order=2, units=300, spectral_radius=0.9, leak=1.0, input_scaling=0.5, ridge=0.0001, standardize=True, warmup=None, validation=0.2, horizon=0, dt=1.0, random_state=0, label='surrogate')

Return the reservoir system whose ridge readout gives the variable increments.

A reservoir is a fixed set of features of the recent past of the variables, and a ridge regression from these features to the change of the variables over one sample is fitted on the training samples, with ReservoirPy. The fitted System steps once per sample and starts at the last sample of the last run with the memory the runs left, so result.system.prepare().simulate(until=n) forecasts n samples, such as a sine wave continued to within 0.01. It learns a model of a chaotic flow, a power demand, or a speech signal from series alone.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source Runs

A trajectory, an array with one row per sample, or several runs as a list or a 3-D array.

required
variables Sequence[str] | None

The variables of trajectories, or None for every scalar state or observable.

None
kind str

The reservoir. 'next_generation' takes as features the variables at delay consecutive samples and their monomials of degree order. 'echo_state' takes the activities of units leaky tanh units with random recurrent weights.

'next_generation'
delay int

The number of consecutive samples of a next-generation reservoir.

2
order int

The degree of the monomials of a next-generation reservoir.

2
units int

The number of units of an echo state network.

300
spectral_radius float

The spectral radius of the recurrent weights of an echo state network.

0.9
leak float

The leak rate of the units of an echo state network, 1 for no leak.

1.0
input_scaling float

The scale of the input weights of an echo state network.

0.5
ridge float

The strength of the ridge penalty of the readout.

0.0001
standardize bool

Whether the reservoir reads the variables divided by their standard deviations after removing their means, or the variables as they are.

True
warmup int | None

The number of first samples of every series left out of the fit while the memory fills, or None for delay with a next-generation reservoir and 100 with an echo state network.

None
validation float

The share of the samples of every run held out at its end to measure the validation error.

0.2
horizon int

The number of samples to forecast after the last sample of the last run.

0
dt float

The time between the rows of an array.

1.0
random_state int | None

The seed of the random weights of an echo state network.

0
label str

The label of the surrogate element.

'surrogate'

Returns:

Name Type Description
result ReservoirResult

The fitted system, its errors, its reservoir map, and the forecast.

Raises:

Type Description
AnalysisError

The reservoir kind is unknown, the validation share lies outside [0, 1), the horizon is negative, or no training sample is left after the warmup.

See Also

mode_decomposition: Fits a linear system to series. sparse_identification: Finds the equations of series from a library of terms.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import reservoir
>>> result = reservoir(np.sin(0.1 * np.arange(400.0)), variables=['x'], horizon=10)
>>> bool(abs(result.forecast[-1, 0] - np.sin(0.1 * 409)) < 0.01)
True
Source code in src/skcomplex/core/analysis/_reservoirs.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def reservoir(
    source: Runs,
    *,
    variables: Sequence[str] | None = None,
    kind: str = 'next_generation',
    delay: int = 2,
    order: int = 2,
    units: int = 300,
    spectral_radius: float = 0.9,
    leak: float = 1.0,
    input_scaling: float = 0.5,
    ridge: float = 1e-4,
    standardize: bool = True,
    warmup: int | None = None,
    validation: float = 0.2,
    horizon: int = 0,
    dt: float = 1.0,
    random_state: int | None = 0,
    label: str = 'surrogate',
) -> ReservoirResult:
    """Return the reservoir system whose ridge readout gives the variable increments.

    A reservoir is a fixed set of features of the recent past of the variables, and a ridge regression from these
    features to the change of the variables over one sample is fitted on the training samples, with ReservoirPy. The
    fitted `System` steps once per sample and starts at the last sample of the last run with the memory the runs left,
    so `result.system.prepare().simulate(until=n)` forecasts `n` samples, such as a sine wave continued to within 0.01.
    It learns a model of a chaotic flow, a power demand, or a speech signal from series alone.

    Read more in the user guide, under Analyse.

    Args:
        source:
            A trajectory, an array with one row per sample, or several runs as a list or a 3-D array.

        variables:
            The variables of trajectories, or `None` for every scalar state or observable.

        kind:
            The reservoir. `'next_generation'` takes as features the variables at `delay` consecutive samples and their
            monomials of degree `order`. `'echo_state'` takes the activities of `units` leaky tanh units with random
            recurrent weights.

        delay:
            The number of consecutive samples of a next-generation reservoir.

        order:
            The degree of the monomials of a next-generation reservoir.

        units:
            The number of units of an echo state network.

        spectral_radius:
            The spectral radius of the recurrent weights of an echo state network.

        leak:
            The leak rate of the units of an echo state network, 1 for no leak.

        input_scaling:
            The scale of the input weights of an echo state network.

        ridge:
            The strength of the ridge penalty of the readout.

        standardize:
            Whether the reservoir reads the variables divided by their standard deviations after removing their means,
            or the variables as they are.

        warmup:
            The number of first samples of every series left out of the fit while the memory fills, or `None` for
            `delay` with a next-generation reservoir and 100 with an echo state network.

        validation:
            The share of the samples of every run held out at its end to measure the validation error.

        horizon:
            The number of samples to forecast after the last sample of the last run.

        dt:
            The time between the rows of an array.

        random_state:
            The seed of the random weights of an echo state network.

        label:
            The label of the surrogate element.

    Returns:
        result:
            The fitted system, its errors, its reservoir map, and the forecast.

    Raises:
        AnalysisError:
            The reservoir kind is unknown, the validation share lies outside `[0, 1)`, the horizon is negative, or no
            training sample is left after the warmup.

    See Also:
        mode_decomposition: Fits a linear system to series.
        sparse_identification: Finds the equations of series from a library of terms.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import reservoir
        >>> result = reservoir(np.sin(0.1 * np.arange(400.0)), variables=['x'], horizon=10)
        >>> bool(abs(result.forecast[-1, 0] - np.sin(0.1 * 409)) < 0.01)
        True
    """
    _check_validation(validation)
    _check_horizon(horizon)
    if kind not in RESERVOIR_KINDS:
        error_msg = f'The reservoir kind {kind!r} is unknown. Choose one of {RESERVOIR_KINDS}.'
        raise AnalysisError(error_msg)
    samples = _read_samples(source, variables, dt)
    node = _reservoir_node(
        kind,
        delay=delay,
        order=order,
        units=units,
        spectral_radius=spectral_radius,
        leak=leak,
        input_scaling=input_scaling,
        random_state=random_state,
    )
    training, _ = _split_samples(samples.series, validation)
    joined = np.concatenate(training)
    deviation = joined.std(axis=0)
    step = _ReservoirStep(
        kind,
        node,
        load_module('reservoirpy.nodes').Ridge(ridge=ridge),
        joined.mean(axis=0) if standardize else np.zeros(joined.shape[1]),
        np.where(deviation > 0, deviation, 1.0) if standardize else np.ones(joined.shape[1]),
    )
    default_warmup = delay if kind == 'next_generation' else ECHO_STATE_WARMUP
    skipped = default_warmup if warmup is None else warmup
    training_error, validation_error = _fit_readout(step, samples.series, training, skipped)
    memory = step.get_memory()
    states = _state_names([*samples.labels, *(f'memory[{index}]' for index in range(len(memory)))])
    last_state = np.asarray([*samples.series[-1][-1], *memory], dtype=float)
    system = _surrogate_system(
        label,
        dict(zip(states, map(float, last_state), strict=True)),
        _reservoir_laws(states, step),
    )
    current = last_state
    rows = []
    for _ in range(horizon):
        current = step.evaluate(0.0, *current)
        rows.append(current[: len(samples.labels)])
    return ReservoirResult(
        samples,
        system,
        samples.labels,
        states,
        last_state,
        samples.dt,
        training_error,
        validation_error,
        step,
        np.asarray(rows).reshape(horizon, len(samples.labels)),
    )

rolling(source, *, kind='variance', variables=None, window=None, detrend=False)

Return the statistic of every series in rolling windows, and its trend.

Every window holds the window values that end at a sample, possibly with a linear trend removed first, and the statistic of the window is set at that sample. The trend of the statistic is the tau of Kendall against time, such as 1 for the variance of [0, 1, 0, 2, 0, 3], whose swings grow. It finds the early warnings of a tipping point, such as a rising variance before a lake turns turbid, a market crashes, or a climate shifts.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array with one row per time and one column per series.

required
kind str

What to return. 'variance' gives the variance of every window, 'autocorrelation' the correlation of every window with itself one step later, and 'skewness' the skewness of every window.

'variance'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series.

None
window int | None

The number of values in every rolling window.

None
detrend bool

Whether to remove a linear trend in every window first.

False

Returns:

Name Type Description
result RollingResult

The series, the rolling statistic of every series, and its trend.

Raises:

Type Description
AnalysisError

The kind is unknown, or the window is missing or does not fit the series.

See Also

correlation: Gives the correlation of series, of an ensemble, or of a field. events: Finds the runs of a series above a threshold.

Examples:

>>> from skcomplex.core.analysis import rolling
>>> rolling([0, 1, 0, 2, 0, 3], window=3).trend.tolist()
[1.0]
Source code in src/skcomplex/core/analysis/_rolling.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def rolling(
    source: DataSource,
    *,
    kind: str = 'variance',
    variables: Sequence[str] | None = None,
    window: int | None = None,
    detrend: bool = False,
) -> RollingResult:
    """Return the statistic of every series in rolling windows, and its trend.

    Every window holds the `window` values that end at a sample, possibly with a linear trend removed first, and the
    statistic of the window is set at that sample. The trend of the statistic is the tau of Kendall against time, such
    as 1 for the variance of `[0, 1, 0, 2, 0, 3]`, whose swings grow. It finds the early warnings of a tipping point,
    such as a rising variance before a lake turns turbid, a market crashes, or a climate shifts.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array with one row per time and one column per series.

        kind:
            What to return. `'variance'` gives the variance of every window, `'autocorrelation'` the correlation of
            every window with itself one step later, and `'skewness'` the skewness of every window.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series.

        window:
            The number of values in every rolling window.

        detrend:
            Whether to remove a linear trend in every window first.

    Returns:
        result:
            The series, the rolling statistic of every series, and its trend.

    Raises:
        AnalysisError:
            The kind is unknown, or the window is missing or does not fit the series.

    See Also:
        correlation: Gives the correlation of series, of an ensemble, or of a field.
        events: Finds the runs of a series above a threshold.

    Examples:
        >>> from skcomplex.core.analysis import rolling
        >>> rolling([0, 1, 0, 2, 0, 3], window=3).trend.tolist()
        [1.0]
    """
    _check_choice('rolling', 'kind', kind, KINDS)
    if window is None or window < MIN_WINDOW:
        error_msg = f'rolling has window={window!r}. Give a window of {MIN_WINDOW} or more.'
        raise AnalysisError(error_msg)
    series = _read_series(source, variables)
    statistic = np.asarray(
        [_rolling(column, window, _statistic, kind, detrend=detrend) for column in series.values.T],
    )
    trend = np.asarray([_trend(row) for row in statistic])
    return RollingResult(series.values, series.labels, statistic, trend)

scaling(source, *, kind='detrended-fluctuation', variables=None, scales=None, order=1, fit_sums=(0.0001, 0.01), random_state=0, against='mean', parameters=None, critical=None, above=False, confidence=0.95, resamples=1000)

Return the scaling exponent of series, fractal dimension of points, or a law.

A scaling law says how a measure grows with the size of a window, a box, a radius, or a system, y ~ s^b, and the exponent b is the slope of log y against log s, such as 1.5 for the fluctuations of a random walk. The kinds read series, fields, points, or samples at several sizes. It measures the long memory of river flows, the fractal dimension of a coastline, and the critical exponents of a magnet.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource | Mapping[float, ArrayLike]

The trajectory, the series, the field, the points, or a mapping from size to samples.

required
kind str

What to return. 'detrended-fluctuation' gives the slope of the log fluctuation of the integrated series, detrended in windows by a polynomial of degree order, against the log window size, 0.5 for white noise, the Hurst exponent H for fractional Gaussian noise, and H + 1 for its integral. 'rescaled-range' gives the Hurst exponent by the rescaled range, 0.5 for uncorrelated noise, above 0.5 for persistent and below 0.5 for anti-persistent noise. 'box-counting' gives the box counting dimension of the occupied cells of a field, the slope of the log box count against the log box size, read from the last frame of a trajectory. 'correlation-dimension' gives the correlation dimension of Grassberger and Procaccia of a point set, one row per point, such as the columns of an embedded series, from tree counts of close pairs. 'variance-mean' gives the mean and the standard deviation of a quantity at every scale, and the slope of log deviation against log mean with against='mean', or of log (deviation / mean) against log size with against='size'. It reads the counts of a density field in square boxes of growing side over every frame, where the slope against the mean is 1/2 for independent particles and above for giant fluctuations, or a mapping from size to samples, where the slope against the size is -1/2 for the sums of independent parts. 'power' gives the exponent b of the power law y ~ |p - p_c|^b of every series against the distance of the control parameters to the critical value, fitted on the side above or below it where y is positive, such as the exponent beta of an order parameter. 'allometric' gives the slope of the logarithm of every sample of a quantity against the logarithm of its size, the exponent b of y ~ N^b across a set of runs, with a bootstrap confidence interval over the pairs. It reads a mapping from size to samples, or two columns of sizes and samples.

'detrended-fluctuation'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series, or the first field for a field.

None
scales Sequence[float] | None

The window sizes, the box sides in cells, or the radii, or None for windows spaced logarithmically up to a tenth of the series, powers of 2 up to an eighth of the smallest side, or a quarter of it for 'variance-mean', or 30 radii spaced logarithmically over the range of pair distances.

None
order int

The order of the detrending polynomial.

1
fit_sums tuple[float, float]

The smallest and largest correlation sums of the scaling region the slope is fitted in.

(0.0001, 0.01)
random_state int | None

The seed of the sample of pairs that sets the default radii, or of the bootstrap.

0
against str

What the variance-mean law is fitted against, 'mean' or 'size'.

'mean'
parameters Sequence[float] | None

The control parameter value of every row of the series of 'power'.

None
critical float | None

The value of the control parameter the distance is measured to.

None
above bool

Whether the fit uses the values above the critical value, as for couplings, rather than below it, as for temperatures.

False
confidence float

The confidence level of the interval of 'allometric'.

0.95
resamples int

The number of bootstrap resamples of 'allometric'.

1000

Returns:

Name Type Description
result ScalingResult

What the source was read as, the exponent, and the curves it is fitted on.

Raises:

Type Description
AnalysisError

The kind or a setting does not fit, or 'allometric' reads a sample or a size that is not positive, or fewer than two sizes.

See Also

fit_law: Fits a power law to the tail of a sample. embedding: Gives the points made of delayed copies of one series.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import scaling
>>> walk = np.cumsum(np.random.default_rng(0).standard_normal(5000))
>>> scaling(walk).exponent.round(1).tolist()
[1.5]
Source code in src/skcomplex/core/analysis/_scaling.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def scaling(
    source: DataSource | Mapping[float, npt.ArrayLike],
    *,
    kind: str = 'detrended-fluctuation',
    variables: Sequence[str] | None = None,
    scales: Sequence[float] | None = None,
    order: int = 1,
    fit_sums: tuple[float, float] = (1e-4, 1e-2),
    random_state: int | None = 0,
    against: str = 'mean',
    parameters: Sequence[float] | None = None,
    critical: float | None = None,
    above: bool = False,
    confidence: float = 0.95,
    resamples: int = 1000,
) -> ScalingResult:
    """Return the scaling exponent of series, fractal dimension of points, or a law.

    A scaling law says how a measure grows with the size of a window, a box, a radius, or a system, `y ~ s^b`, and the
    exponent `b` is the slope of `log y` against `log s`, such as 1.5 for the fluctuations of a random walk. The kinds
    read series, fields, points, or samples at several sizes. It measures the long memory of river flows, the fractal
    dimension of a coastline, and the critical exponents of a magnet.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, the series, the field, the points, or a mapping from size to samples.

        kind:
            What to return. `'detrended-fluctuation'` gives the slope of the log fluctuation of the integrated series,
            detrended in windows by a polynomial of degree `order`, against the log window size, 0.5 for white noise,
            the Hurst exponent `H` for fractional Gaussian noise, and `H + 1` for its integral. `'rescaled-range'`
            gives the Hurst exponent by the rescaled range, 0.5 for uncorrelated noise, above 0.5 for persistent and
            below 0.5 for anti-persistent noise. `'box-counting'` gives the box counting dimension of the occupied
            cells of a field, the slope of the log box count against the log box size, read from the last frame of a
            trajectory. `'correlation-dimension'` gives the correlation dimension of Grassberger and Procaccia of a
            point set, one row per point, such as the columns of an embedded series, from tree counts of close pairs.
            `'variance-mean'` gives the mean and the standard deviation of a quantity at every scale, and the slope of
            `log deviation` against `log mean` with `against='mean'`, or of `log (deviation / mean)` against `log size`
            with `against='size'`. It reads the counts of a density field in square boxes of growing side over every
            frame, where the slope against the mean is 1/2 for independent particles and above for giant
            fluctuations, or a mapping from size to samples, where the slope against the size is -1/2 for the sums
            of independent parts. `'power'` gives the exponent `b` of the power law `y ~ |p - p_c|^b` of every series
            against the distance of the control `parameters` to the `critical` value, fitted on the side above or
            below it where `y` is positive, such as the exponent `beta` of an order parameter. `'allometric'` gives
            the slope of the logarithm of every sample of a quantity against the logarithm of its size, the exponent
            `b` of `y ~ N^b` across a set of runs, with a bootstrap confidence interval over the pairs. It reads a
            mapping from size to samples, or two columns of sizes and samples.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series, or the first field for a field.

        scales:
            The window sizes, the box sides in cells, or the radii, or `None` for windows spaced logarithmically up
            to a tenth of the series, powers of 2 up to an eighth of the smallest side, or a quarter of it for
            `'variance-mean'`, or 30 radii spaced logarithmically over the range of pair distances.

        order:
            The order of the detrending polynomial.

        fit_sums:
            The smallest and largest correlation sums of the scaling region the slope is fitted in.

        random_state:
            The seed of the sample of pairs that sets the default radii, or of the bootstrap.

        against:
            What the variance-mean law is fitted against, `'mean'` or `'size'`.

        parameters:
            The control parameter value of every row of the series of `'power'`.

        critical:
            The value of the control parameter the distance is measured to.

        above:
            Whether the fit uses the values above the critical value, as for couplings, rather than below it, as for
            temperatures.

        confidence:
            The confidence level of the interval of `'allometric'`.

        resamples:
            The number of bootstrap resamples of `'allometric'`.

    Returns:
        result:
            What the source was read as, the exponent, and the curves it is fitted on.

    Raises:
        AnalysisError:
            The kind or a setting does not fit, or `'allometric'` reads a sample or a size that is not positive, or
            fewer than two sizes.

    See Also:
        fit_law: Fits a power law to the tail of a sample.
        embedding: Gives the points made of delayed copies of one series.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import scaling
        >>> walk = np.cumsum(np.random.default_rng(0).standard_normal(5000))
        >>> scaling(walk).exponent.round(1).tolist()
        [1.5]
    """
    _check_choice('scaling', 'kind', kind, KINDS)
    _check_choice('scaling', 'against', against, AGAINST)
    _check_settings(
        scaling,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        scales=scales,
        order=order,
        fit_sums=fit_sums,
        random_state=random_state,
        against=against,
        parameters=parameters,
        critical=critical,
        above=above,
        confidence=confidence,
        resamples=resamples,
    )
    _check(kind, order, parameters=parameters, critical=critical, confidence=confidence, resamples=resamples)
    values, samples, labels = _read(source, kind, variables)
    if kind == 'allometric':
        x, y = np.log(values).T
        result = bootstrap(
            (x, y),
            _slope,
            paired=True,
            vectorized=True,
            n_resamples=resamples,
            confidence_level=confidence,
            rng=random_state,
        )
        return ScalingResult(
            values,
            samples,
            labels,
            float(linregress(x, y).slope),
            scales=np.unique(values[:, 0]),
            interval=(float(result.confidence_interval.low), float(result.confidence_interval.high)),
        )
    if kind == 'box-counting':
        sides, counts, dimension = _box_counting(values, scales)
        return ScalingResult(values, samples, labels, dimension, scales=sides, counts=counts)
    if kind == 'variance-mean':
        moments = _size_moments(samples) if samples is not None else _box_moments(values, scales)
        exponent = _variance_mean_exponent(*moments, against)
        return ScalingResult(
            values,
            samples,
            labels,
            exponent,
            scales=moments[0],
            means=moments[1],
            deviations=moments[2],
        )
    if kind == 'power':
        exponents = np.asarray(
            [_power_exponent(column, parameters, float(critical or 0.0), above=above) for column in values.T],
        )
        return ScalingResult(values, samples, labels, exponents)
    if kind == 'correlation-dimension':
        radii, sums, dimension, fit_range = _correlation_dimension(
            values,
            scales,
            fit_sums=fit_sums,
            random_state=random_state,
        )
        return ScalingResult(values, samples, labels, dimension, scales=radii, sums=sums, fit_range=fit_range)
    method = 'rs' if kind == 'rescaled-range' else 'dfa'
    curves = [_fluctuation(column, scales, order, method=method) for column in values.T]
    return ScalingResult(
        values,
        samples,
        labels,
        np.asarray([exponent for _, _, exponent in curves]),
        scales=curves[0][0],
        fluctuations=np.asarray([fluctuations for _, fluctuations, _ in curves]),
    )

section(source, *, kind='poincare', variables=None, state=None, value=0.0, direction=1, until=1000.0, transient=None, period=None, n_points=1000, solver=None, random_state=None)

Return the states of a flow where it crosses a value or at each period.

A section turns a flow into a map, by keeping only the states where one state crosses a value in one direction, or the states at every period of a forcing, such as a unit spring that crosses x = 0 upward every 2 pi. It runs the system. It turns a flow into a map of its crossings, as for the orbit of a planet, a forced pendulum, and a heart rhythm.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, its compiled problem, or a trajectory of it.

required
kind str

What to return. 'poincare' gives the states where the scalar state state crosses value in a direction, located like an event. 'stroboscopic' gives the states of a periodically forced flow at multiples of the forcing period.

'poincare'
variables Sequence[str] | None

The dotted names of the states whose values to read at the points of a section, or None for every state.

None
state str | None

The dotted name of the scalar state that defines a Poincaré section, such as oscillator.x.

None
value float

The value of the state on the Poincaré section.

0.0
direction int

1 for crossings upward, -1 for crossings downward, and 0 for both.

1
until float

The time a Poincaré section runs until.

1000.0
transient float | None

The time before which crossings are discarded, or the number of periods discarded before the first stroboscopic point. None gives 0 and 100 periods.

None
period float | None

The period of the forcing, such as 2 * pi / omega.

None
n_points int

The number of points of a stroboscopic section.

1000
solver Solver | None

The solver, as in simulate.

None
random_state int | None

The seed of stochastic solvers.

None

Returns:

Name Type Description
result SectionResult

The times, the states, and the values of the read states at the points of the section.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, a needed setting is missing, the system is not a flow in continuous time, or the state is not a scalar state.

TagError

The system does not run in continuous time.

See Also

lyapunov: Gives the rates at which nearby runs of a system separate. recurrence: Finds which states of a run come close to each other.

Examples:

>>> from skcomplex.core.analysis import section
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> len(section(HarmonicOscillatorSystem(), state='mass.x', until=20.0).times) > 2
True
Source code in src/skcomplex/core/analysis/_sections.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def section(
    source: DataSource,
    *,
    kind: str = 'poincare',
    variables: Sequence[str] | None = None,
    state: str | None = None,
    value: float = 0.0,
    direction: int = 1,
    until: float = 1000.0,
    transient: float | None = None,
    period: float | None = None,
    n_points: int = 1000,
    solver: Solver | None = None,
    random_state: int | None = None,
) -> SectionResult:
    """Return the states of a flow where it crosses a value or at each period.

    A section turns a flow into a map, by keeping only the states where one state crosses a value in one direction, or
    the states at every period of a forcing, such as a unit spring that crosses `x = 0` upward every `2 pi`. It runs
    the system. It turns a flow into a map of its crossings, as for the orbit of a planet, a forced pendulum, and a
    heart rhythm.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, its compiled problem, or a trajectory of it.

        kind:
            What to return. `'poincare'` gives the states where the scalar state `state` crosses `value` in a
            direction, located like an event. `'stroboscopic'` gives the states of a periodically forced flow at
            multiples of the forcing period.

        variables:
            The dotted names of the states whose values to read at the points of a section, or `None` for every state.

        state:
            The dotted name of the scalar state that defines a Poincaré section, such as `oscillator.x`.

        value:
            The value of the state on the Poincaré section.

        direction:
            `1` for crossings upward, `-1` for crossings downward, and `0` for both.

        until:
            The time a Poincaré section runs until.

        transient:
            The time before which crossings are discarded, or the number of periods discarded before the first
            stroboscopic point. `None` gives 0 and 100 periods.

        period:
            The period of the forcing, such as `2 * pi / omega`.

        n_points:
            The number of points of a stroboscopic section.

        solver:
            The solver, as in `simulate`.

        random_state:
            The seed of stochastic solvers.

    Returns:
        result:
            The times, the states, and the values of the read states at the points of the section.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, a needed setting is missing, the system
            is not a flow in continuous time, or the state is not a scalar state.

        TagError:
            The system does not run in continuous time.

    See Also:
        lyapunov: Gives the rates at which nearby runs of a system separate.
        recurrence: Finds which states of a run come close to each other.

    Examples:
        >>> from skcomplex.core.analysis import section
        >>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
        >>> len(section(HarmonicOscillatorSystem(), state='mass.x', until=20.0).times) > 2
        True
    """
    source = _composite(source)
    _check_choice('section', 'kind', kind, KINDS)
    _check_tags(section, source, kind)
    _check_settings(
        section,
        'kind',
        SETTINGS[kind],
        kind=kind,
        variables=variables,
        state=state,
        value=value,
        direction=direction,
        until=until,
        transient=transient,
        period=period,
        n_points=n_points,
        solver=solver,
        random_state=random_state,
    )
    needed: dict[str, object] = {'state': state} if kind == 'poincare' else {'period': period}
    missing = [name for name, item in needed.items() if item is None]
    if missing:
        error_msg = f'section of kind {kind!r} needs {", ".join(missing)}. Give them.'
        raise AnalysisError(error_msg)
    if direction not in DIRECTIONS:
        error_msg = f'section has direction={direction!r}. Use one of -1, 0, or 1.'
        raise AnalysisError(error_msg)
    problem = compile_problem(_read_system(source), 'A section')
    if problem.form not in {FormKind.ODE, FormKind.SDE}:
        error_msg = f'Sections are taken of flows in continuous time, but the system is a {problem.form}.'
        raise AnalysisError(error_msg)
    scalar = state is not None and problem.states.has(state) and problem.states.get_entry(state).size == 1
    if kind == 'poincare' and not scalar:
        error_msg = f'{state!r} is not a scalar state. Available states are: {", ".join(problem.states.names)}.'
        raise AnalysisError(error_msg)
    if kind == 'poincare':
        times, states = _crossings(
            problem,
            state,
            value=value,
            direction=direction,
            until=until,
            transient=transient,
            solver=solver,
            random_state=random_state,
        )
    else:
        times, states = _samples(
            problem,
            period,
            n_points=n_points,
            transient=transient,
            solver=solver,
            random_state=random_state,
        )
    names = list(problem.states.names) if variables is None else variables
    values = {}
    for name in names:
        read = np.asarray([problem.states.read(row, name) for row in states], dtype=float)
        size = problem.states.get_entry(name).size
        values[LayoutSpec._get_display_name(name)] = read.reshape(len(times), -1) if size > 1 else read.reshape(-1)
    return SectionResult(problem, times, states, values)

signatures(source)

Return the default analysis of every kind of data of a trajectory.

Every kind of data gets one figure with its curves, axis labels, and values. A series gives its power spectrum with the autocorrelation time, or its return map for a map, a jump path the survival function of its waiting times with the dispersion index of jumps per frame, and a field the structure factor of its last frame with the peak wavelength or the correlation length. Agents give their polar and milling orders over time, or their nearest neighbour distances against the Poisson law, and a network its degree distribution. It gives the first look at a run of an ecosystem, a market, or a chemical pattern.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory.

required

Returns:

Name Type Description
result SignaturesResult

The data of every kind and one signature per kind.

Raises:

Type Description
AnalysisError

The source is not a trajectory.

See Also

spectrum: Gives the spectrum of every series of a source, or of a field. network_measures: Gives measures of a graph or of the network of every frame.

Examples:

>>> from skcomplex.core.analysis import signatures
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> trajectory = LotkaVolterraSystem().prepare().simulate(until=20.0, random_state=0)
>>> [signature.title for signature in signatures(trajectory).signatures]
['Power spectrum']
Source code in src/skcomplex/core/analysis/_signatures.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def signatures(source: DataSource) -> SignaturesResult:
    """Return the default analysis of every kind of data of a trajectory.

    Every kind of data gets one figure with its curves, axis labels, and values. A series gives its power spectrum with
    the autocorrelation time, or its return map for a map, a jump path the survival function of its waiting times with
    the dispersion index of jumps per frame, and a field the structure factor of its last frame with the peak
    wavelength or the correlation length. Agents give their polar and milling orders over time, or their nearest
    neighbour distances against the Poisson law, and a network its degree distribution. It gives the first look at a
    run of an ecosystem, a market, or a chemical pattern.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory.

    Returns:
        result:
            The data of every kind and one signature per kind.

    Raises:
        AnalysisError:
            The source is not a trajectory.

    See Also:
        spectrum: Gives the spectrum of every series of a source, or of a field.
        network_measures: Gives measures of a graph or of the network of every frame.

    Examples:
        >>> from skcomplex.core.analysis import signatures
        >>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
        >>> trajectory = LotkaVolterraSystem().prepare().simulate(until=20.0, random_state=0)
        >>> [signature.title for signature in signatures(trajectory).signatures]
        ['Power spectrum']
    """
    source = _composite(source)
    if not isinstance(source, Trajectory):
        error_msg = f'signatures reads a trajectory, not {type(source).__name__}.'
        raise AnalysisError(error_msg)
    kinds = _get_data_kinds(source)
    discrete = source.problem.form == FormKind.DISCRETE
    snapshots = _read_snapshots(source) if DataKind.AGENTS in kinds else None
    frames = _read_fields(source) if DataKind.FIELD in kinds else None
    graphs = _read_networks(source) if DataKind.NETWORK in kinds else None
    path = jumps = None
    if DataKind.PATH in kinds:
        path = _read_path(source)
        values = _read_series(source, [path.label]).values
        jumps = np.abs(np.diff(values, axis=0)).sum(axis=1)
    series = _read_series(source) if DataKind.SERIES in kinds else None
    found = []
    for kind in kinds:
        if kind == DataKind.AGENTS and snapshots is not None:
            found.append(_get_agents_signature(snapshots))
        elif kind == DataKind.FIELD and frames is not None:
            found.append(_get_field_signature(frames))
        elif kind == DataKind.NETWORK and graphs is not None:
            found.append(_get_network_signature(graphs))
        elif kind == DataKind.PATH and path is not None and jumps is not None:
            found.append(_get_path_signature(path, jumps))
        elif series is not None:
            found.append(_get_series_signature(series, discrete=discrete))
    return SignaturesResult(kinds, discrete, found, snapshots, frames, graphs, path, jumps, series)

sparse_identification(source, *, variables=None, degree=2, threshold=0.1, alpha=0.05, validation=0.2, horizon=0, dt=1.0, label='surrogate')

Return the sparse symbolic system fitted to series by SINDy, with PySINDy.

SINDy, the sparse identification of nonlinear dynamics, writes the derivative of every variable as a sum of few monomials of the variables up to a degree, such as x' = -2 x for a decaying exponential. It estimates the derivatives by centred finite differences and keeps the terms by least squares that drop small coefficients in turn. The fitted System holds one rate law per variable and starts at the first sample of the first run, so result.system.prepare().simulate(until=...) runs it. It finds the equations of a fluid flow, a chemical reaction, and a predator and prey cycle from their series.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source Runs

A trajectory, an array with one row per sample, or several runs as a list or a 3-D array.

required
variables Sequence[str] | None

The variables of trajectories, or None for every scalar state or observable.

None
degree int

The highest degree of the candidate monomials.

2
threshold float

The smallest magnitude of a kept coefficient.

0.1
alpha float

The strength of the ridge penalty of every least-squares fit.

0.05
validation float

The share of the samples of every run held out at its end to measure the validation error.

0.2
horizon int

The number of samples to forecast after the last sample of the last run, by simulating the fitted system.

0
dt float

The time between the rows of an array.

1.0
label str

The label of the surrogate element.

'surrogate'

Returns:

Name Type Description
result SparseIdentificationResult

The fitted system, its errors, its coefficients, and the forecast.

Raises:

Type Description
AnalysisError

The validation share lies outside [0, 1), the horizon is negative, or the runs differ in variables or step.

See Also

mode_decomposition: Fits a linear system to series. kramers_moyal: Gives the drift and the diffusion of one series.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import sparse_identification
>>> times = np.arange(0.0, 2.0, 0.001)
>>> result = sparse_identification(np.exp(-2 * times), variables=['x'], degree=1, dt=0.001)
>>> result.features, result.coefficients.round(3).tolist()
(['1', 'x'], [[0.0, -2.0]])
Source code in src/skcomplex/core/analysis/_sparse_identification.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def sparse_identification(
    source: Runs,
    *,
    variables: Sequence[str] | None = None,
    degree: int = 2,
    threshold: float = 0.1,
    alpha: float = 0.05,
    validation: float = 0.2,
    horizon: int = 0,
    dt: float = 1.0,
    label: str = 'surrogate',
) -> SparseIdentificationResult:
    """Return the sparse symbolic system fitted to series by SINDy, with PySINDy.

    SINDy, the sparse identification of nonlinear dynamics, writes the derivative of every variable as a sum of few
    monomials of the variables up to a degree, such as `x' = -2 x` for a decaying exponential. It estimates the
    derivatives by centred finite differences and keeps the terms by least squares that drop small coefficients in
    turn. The fitted `System` holds one rate law per variable and starts at the first sample of the first run, so
    `result.system.prepare().simulate(until=...)` runs it. It finds the equations of a fluid flow, a chemical reaction,
    and a predator and prey cycle from their series.

    Read more in the user guide, under Analyse.

    Args:
        source:
            A trajectory, an array with one row per sample, or several runs as a list or a 3-D array.

        variables:
            The variables of trajectories, or `None` for every scalar state or observable.

        degree:
            The highest degree of the candidate monomials.

        threshold:
            The smallest magnitude of a kept coefficient.

        alpha:
            The strength of the ridge penalty of every least-squares fit.

        validation:
            The share of the samples of every run held out at its end to measure the validation error.

        horizon:
            The number of samples to forecast after the last sample of the last run, by simulating the fitted system.

        dt:
            The time between the rows of an array.

        label:
            The label of the surrogate element.

    Returns:
        result:
            The fitted system, its errors, its coefficients, and the forecast.

    Raises:
        AnalysisError:
            The validation share lies outside `[0, 1)`, the horizon is negative, or the runs differ in variables or
            step.

    See Also:
        mode_decomposition: Fits a linear system to series.
        kramers_moyal: Gives the drift and the diffusion of one series.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import sparse_identification
        >>> times = np.arange(0.0, 2.0, 0.001)
        >>> result = sparse_identification(np.exp(-2 * times), variables=['x'], degree=1, dt=0.001)
        >>> result.features, result.coefficients.round(3).tolist()
        (['1', 'x'], [[0.0, -2.0]])
    """
    _check_validation(validation)
    _check_horizon(horizon)
    samples = _read_samples(source, variables, dt)
    states = _state_names(samples.labels)
    training, held = _split_samples(samples.series, validation)
    sindy = load_module('pysindy')
    fitted = sindy.SINDy(
        optimizer=sindy.STLSQ(threshold=threshold, alpha=alpha),
        feature_library=sindy.PolynomialLibrary(degree=degree),
    ).fit(training, t=samples.dt, feature_names=states)
    coefficients = np.asarray(fitted.coefficients(), dtype=float)
    powers = np.asarray(fitted.feature_library.powers_, dtype=int)
    system = _surrogate_system(
        label,
        dict(zip(states, map(float, samples.series[0][0]), strict=True)),
        _sparse_laws(states, coefficients, powers),
    )
    last_state = np.asarray(samples.series[-1][-1], dtype=float)
    predict, differentiate = fitted.predict, fitted.differentiation_method
    return SparseIdentificationResult(
        samples,
        system,
        samples.labels,
        states,
        last_state,
        samples.dt,
        _relative_error(*_derivatives(predict, differentiate, training, samples.dt)),
        _relative_error(*_derivatives(predict, differentiate, held, samples.dt)),
        [str(name) for name in fitted.get_feature_names()],
        coefficients,
        _forecast(system, label, states, last_state, dt=samples.dt, horizon=horizon),
    )

spectrum(source, *, kind='power', variables=None, dt=1.0, spacing=1.0, frames=False)

Return the spectrum of every series of a source, or of a field.

A spectrum splits a series into waves of different frequencies and gives the power of each, such as a peak at 5 for a sine wave that turns 5 times per unit time. A field gives the power of its waves in space, read from the last frame of a trajectory, or every frame when frames is true. It finds the rhythms of brain waves, the cycles of a business, and the energy cascade of turbulence.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array of series or of a field.

required
kind str

What to return. 'power' gives the power spectral density of every series by the method of Welch. 'structure-factor' gives the radially averaged structure factor S(k) of a field on a periodic grid of any dimension, in shells of width 2 pi / (side spacing), averaged over frames when frames is true.

'power'
variables Sequence[str] | None

The variables of a trajectory to read, or None for every scalar series, or the first field for a field.

None
dt float

The time between samples.

1.0
spacing float

The distance between neighbouring sites.

1.0
frames bool

Whether the first axis of an array indexes frames, and whether to read every frame of a trajectory.

False

Returns:

Name Type Description
result SpectrumResult

The data read and its spectrum.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, or a setting is not positive.

See Also

correlation: Gives the correlation of series, of an ensemble, or of a field. mode_decomposition: Fits a linear system to series and gives its modes.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import spectrum
>>> times = np.arange(4096) * 0.01
>>> result = spectrum(np.sin(2 * np.pi * 5 * times), dt=0.01)
>>> round(float(result.frequencies[result.power[0].argmax()]))
5
Source code in src/skcomplex/core/analysis/_spectrum.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def spectrum(
    source: DataSource,
    *,
    kind: str = 'power',
    variables: Sequence[str] | None = None,
    dt: float = 1.0,
    spacing: float = 1.0,
    frames: bool = False,
) -> SpectrumResult:
    """Return the spectrum of every series of a source, or of a field.

    A spectrum splits a series into waves of different frequencies and gives the power of each, such as a peak at 5
    for a sine wave that turns 5 times per unit time. A field gives the power of its waves in space, read from the last
    frame of a trajectory, or every frame when `frames` is true. It finds the rhythms of brain waves, the cycles of a
    business, and the energy cascade of turbulence.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array of series or of a field.

        kind:
            What to return. `'power'` gives the power spectral density of every series by the method of Welch.
            `'structure-factor'` gives the radially averaged structure factor `S(k)` of a field on a periodic grid of
            any dimension, in shells of width `2 pi / (side spacing)`, averaged over frames when `frames` is true.

        variables:
            The variables of a trajectory to read, or `None` for every scalar series, or the first field for a field.

        dt:
            The time between samples.

        spacing:
            The distance between neighbouring sites.

        frames:
            Whether the first axis of an array indexes frames, and whether to read every frame of a trajectory.

    Returns:
        result:
            The data read and its spectrum.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, or a setting is not positive.

    See Also:
        correlation: Gives the correlation of series, of an ensemble, or of a field.
        mode_decomposition: Fits a linear system to series and gives its modes.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import spectrum
        >>> times = np.arange(4096) * 0.01
        >>> result = spectrum(np.sin(2 * np.pi * 5 * times), dt=0.01)
        >>> round(float(result.frequencies[result.power[0].argmax()]))
        5
    """
    _check_choice('spectrum', 'kind', kind, KINDS)
    _check_settings(
        spectrum,
        'kind',
        SETTINGS[kind] | {'variables'},
        kind=kind,
        variables=variables,
        dt=dt,
        spacing=spacing,
        frames=frames,
    )
    if dt <= 0 or spacing <= 0:
        error_msg = f'spectrum has dt={dt!r} and spacing={spacing!r}. Use positive values.'
        raise AnalysisError(error_msg)
    if kind == 'power':
        series = _read_series(source, variables)
        spectra = [_power_spectrum(column, dt) for column in series.values.T]
        power = np.asarray([density for _, density in spectra])
        return SpectrumResult(series.values, series.labels, power, frequencies=spectra[0][0])
    name = variables[0] if variables else None
    field = _read_fields(source, name)
    if isinstance(source, Trajectory) and not frames:
        field = field[-1]
    wavenumbers, power = _structure_factor(field if frames else field[None], spacing)
    return SpectrumResult(field, [name or 'field'], power, wavenumbers=wavenumbers)

stability(source, *, kind='fixed-points', parameters=None, points=None, at=None)

Return the linear stability of a system, of one kind.

A fixed point is a state that does not change, where every rate is 0 for a flow or every state equals its next value for a map, and it is stable when a small push dies out, such as the carrying capacity of logistic growth. The stability of every point comes from the eigenvalues of the Jacobian there, evaluated at the parameter values. It decides whether a steady state of an epidemic, a chemical reactor, or a power grid returns after a small push.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, its compiled problem, or a trajectory of it for 'fixed-points', and the system for 'dispersion'.

required
kind str

What to return. 'fixed-points' gives the fixed points of a flow or a map, their linear stability, and the Jacobian, nullclines, and divergence. Sage solves the equations symbolically, and when it finds no closed form, roots are searched numerically from a grid of starting points with the parameters at their values. 'dispersion' gives the growth rate of every Fourier mode of a system of one field, a site group on a periodic lattice whose laws are rate laws. The laws are linearised symbolically around a uniform state, and every Laplacian, nested ones included, becomes its eigenvalue on a Fourier mode of the lattice, Σ (2 cos(k h) - 2) / h² for finite differences and -|k|² for a spectral field. Without at, the uniform state is the fixed point of the laws nearest the mean initial values.

'fixed-points'
parameters Mapping[str, float] | None

Values of parameters by dotted path that replace the system's values. They are substituted before solving, and without them the symbolic fixed points keep the parameters as symbols.

None
points Sequence[Point] | None

The points whose stability to analyse, each a mapping from state component name to its value, symbolic or numeric, or None for every fixed point found.

None
at Mapping[str, float] | None

The uniform state of the dispersion relation by state name, or None for the nearest fixed point.

None

Returns:

Name Type Description
result StabilityResult

The Jacobian, nullclines, and fixed points with their classes, or the dispersion relation.

Raises:

Type Description
AnalysisError

The kind is unknown, a setting the kind does not read is changed, or the system has no form of the kind.

See Also

linearization: Gives the linear state space system of a system near an operating point. lyapunov: Gives the rates at which nearby runs of a system separate.

Examples:

>>> from skcomplex.core.analysis import stability
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> result = stability(LogisticGrowthSystem())
>>> sorted(str(point['population.x']) for point in result.fixed_points)
['0', 'K_growth']
Source code in src/skcomplex/core/analysis/_stability.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def stability(
    source: DataSource,
    *,
    kind: str = 'fixed-points',
    parameters: Mapping[str, float] | None = None,
    points: Sequence[Point] | None = None,
    at: Mapping[str, float] | None = None,
) -> StabilityResult:
    """Return the linear stability of a system, of one kind.

    A fixed point is a state that does not change, where every rate is 0 for a flow or every state equals its next
    value for a map, and it is stable when a small push dies out, such as the carrying capacity of logistic growth.
    The stability of every point comes from the eigenvalues of the Jacobian there, evaluated at the parameter values.
    It decides whether a steady state of an epidemic, a chemical reactor, or a power grid returns after a small push.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, its compiled problem, or a trajectory of it for `'fixed-points'`, and the system for
            `'dispersion'`.

        kind:
            What to return. `'fixed-points'` gives the fixed points of a flow or a map, their linear stability, and the
            Jacobian, nullclines, and divergence. Sage solves the equations symbolically, and when it finds no closed
            form, roots are searched numerically from a grid of starting points with the parameters at their values.
            `'dispersion'` gives the growth rate of every Fourier mode of a system of one field, a site group on a
            periodic lattice whose laws are rate laws. The laws are linearised symbolically around a uniform state,
            and every Laplacian, nested ones included, becomes its eigenvalue on a Fourier mode of the lattice,
            `Σ (2 cos(k h) - 2) / h²` for finite differences and `-|k|²` for a spectral field. Without `at`, the
            uniform state is the fixed point of the laws nearest the mean initial values.

        parameters:
            Values of parameters by dotted path that replace the system's values. They are substituted before solving,
            and without them the symbolic fixed points keep the parameters as symbols.

        points:
            The points whose stability to analyse, each a mapping from state component name to its value, symbolic
            or numeric, or `None` for every fixed point found.

        at:
            The uniform state of the dispersion relation by state name, or `None` for the nearest fixed point.

    Returns:
        result:
            The Jacobian, nullclines, and fixed points with their classes, or the dispersion relation.

    Raises:
        AnalysisError:
            The kind is unknown, a setting the kind does not read is changed, or the system has no form of the kind.

    See Also:
        linearization: Gives the linear state space system of a system near an operating point.
        lyapunov: Gives the rates at which nearby runs of a system separate.

    Examples:
        >>> from skcomplex.core.analysis import stability
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> result = stability(LogisticGrowthSystem())
        >>> sorted(str(point['population.x']) for point in result.fixed_points)
        ['0', 'K_growth']
    """
    system = _get_system(source)
    source = _composite(system)
    _check_choice('stability', 'kind', kind, KINDS)
    _check_settings(stability, 'kind', SETTINGS[kind], kind=kind, parameters=parameters, points=points, at=at)
    if kind == 'dispersion':
        if not isinstance(system, System) or not isinstance(source, _CompositeSystem):
            error_msg = f'A dispersion relation is computed from a system, not from {type(system).__name__}.'
            raise AnalysisError(error_msg)
        declared = PassCompiler()._get_declared_system(source)
        waves, magnitudes, growth_rates, frequencies, uniform = _dispersion_relation(declared, at)
        return StabilityResult(
            system=system,
            wavenumbers=waves,
            magnitudes=magnitudes,
            growth_rates=growth_rates,
            frequencies=frequencies,
            uniform=uniform,
            band=np.unique(np.round(magnitudes[growth_rates > 0], 12)),
        )
    problem = StabilityResult._get_dynamics_of(_read_system(source), parameters).problem
    dynamics = StabilityResult._get_dynamics_of(problem, parameters)
    jacobian = matrix(SR, [[rate.diff(item) for item in dynamics.symbols] for rate in dynamics.rates])
    nullclines = {
        name: (rate - item if dynamics.discrete else rate) == 0
        for name, item, rate in zip(dynamics.names, dynamics.symbols, dynamics.rates, strict=True)
    }
    fixed_points = (
        _find_points(dynamics, substitute=bool(parameters)) if points is None else [dict(item) for item in points]
    )
    eigenvalues = [_eigenvalues_at(dynamics, jacobian, point) for point in fixed_points]
    return StabilityResult(
        problem=problem,
        names=dynamics.names,
        jacobian=jacobian,
        divergence=jacobian.trace().simplify_full(),
        nullclines=nullclines,
        fixed_points=fixed_points,
        eigenvalues=eigenvalues,
        classifications=[_classify(values, discrete=dynamics.discrete) for values in eigenvalues],
    )

surrogate_test(source, *, analysis, attribute, variables=None, n=99, alternative='two-sided', random_state=None)

Return the test of an analysis of many variables against surrogates.

The surrogates shuffle every variable on its own, which keeps the values of each variable and breaks any link between them. The analysis runs on the data and on n surrogates, and the field of its result gives the value of each. The p-value is the fraction of surrogates, with the data counted among them, at least as extreme as the data, such as 0.05 for three copies of one coin flip tested against 19 surrogates. It tests whether a coupling between brain regions, markets, or climate indices is more than chance.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The trajectory, or an array with one row per sample and one column per variable.

required
analysis Callable[[Array], object]

The analysis of the variables, a function of an array such as one bind_analysis returns, applied to the data and to every surrogate.

required
attribute str

The scalar field of the result of the analysis that measures the dependence, such as 'information'.

required
variables Sequence[str] | None

The variables of a trajectory, or None for every scalar state or observable.

None
n int

The number of surrogates.

99
alternative str

'greater', 'less', or 'two-sided', the direction in which the data differ from independence.

'two-sided'
random_state int | None

The seed of the shuffles.

None

Returns:

Name Type Description
result SurrogateTestResult

The data, the measure on the data and on every surrogate, and the p-value.

Raises:

Type Description
AnalysisError

The alternative is unknown, the number of surrogates is below 1, or the analysis is not callable.

See Also

information: Gives the information among series. correlation: Gives the correlation of series, of an ensemble, or of a field.

Examples:

>>> import numpy as np
>>> from skcomplex.core.analysis import bind_analysis, information, surrogate_test
>>> bits = np.column_stack([np.random.default_rng(0).integers(0, 2, 500)] * 3)
>>> measure = bind_analysis(information, kind='o-information')
>>> surrogate_test(bits, analysis=measure, attribute='information', n=19, random_state=0).p_value
0.05
Source code in src/skcomplex/core/analysis/_surrogates.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def surrogate_test(
    source: DataSource,
    *,
    analysis: Callable[[Array], object],
    attribute: str,
    variables: Sequence[str] | None = None,
    n: int = 99,
    alternative: str = 'two-sided',
    random_state: int | None = None,
) -> SurrogateTestResult:
    """Return the test of an analysis of many variables against surrogates.

    The surrogates shuffle every variable on its own, which keeps the values of each variable and breaks any link
    between them. The analysis runs on the data and on `n` surrogates, and the field of its result gives the value of
    each. The p-value is the fraction of surrogates, with the data counted among them, at least as extreme as the
    data, such as 0.05 for three copies of one coin flip tested against 19 surrogates. It tests whether a coupling
    between brain regions, markets, or climate indices is more than chance.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The trajectory, or an array with one row per sample and one column per variable.

        analysis:
            The analysis of the variables, a function of an array such as one `bind_analysis` returns, applied to the
            data and to every surrogate.

        attribute:
            The scalar field of the result of the analysis that measures the dependence, such as `'information'`.

        variables:
            The variables of a trajectory, or `None` for every scalar state or observable.

        n:
            The number of surrogates.

        alternative:
            `'greater'`, `'less'`, or `'two-sided'`, the direction in which the data differ from independence.

        random_state:
            The seed of the shuffles.

    Returns:
        result:
            The data, the measure on the data and on every surrogate, and the p-value.

    Raises:
        AnalysisError:
            The alternative is unknown, the number of surrogates is below 1, or the analysis is not callable.

    See Also:
        information: Gives the information among series.
        correlation: Gives the correlation of series, of an ensemble, or of a field.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.analysis import bind_analysis, information, surrogate_test
        >>> bits = np.column_stack([np.random.default_rng(0).integers(0, 2, 500)] * 3)
        >>> measure = bind_analysis(information, kind='o-information')
        >>> surrogate_test(bits, analysis=measure, attribute='information', n=19, random_state=0).p_value
        0.05
    """
    if alternative not in ALTERNATIVES:
        error_msg = f'Unknown alternative {alternative!r}. Use one of {", ".join(ALTERNATIVES)}.'
        raise AnalysisError(error_msg)
    if isinstance(n, bool) or not isinstance(n, int) or n < 1:
        error_msg = f'n = {n!r} must be a positive number of surrogates.'
        raise AnalysisError(error_msg)
    if not callable(analysis):
        error_msg = f'The measure of a surrogate test is an analysis function, not {analysis!r}.'
        raise AnalysisError(error_msg)
    values = np.asarray(_read_series(source, variables).values, dtype=float)
    rng = np.random.default_rng(random_state)
    value = _measure(analysis, attribute, values)
    surrogates = np.asarray(
        [
            _measure(analysis, attribute, np.column_stack([rng.permutation(column) for column in values.T]))
            for _ in range(n)
        ],
        dtype=float,
    )
    if alternative == 'greater':
        extreme = int(np.sum(surrogates >= value))
    elif alternative == 'less':
        extreme = int(np.sum(surrogates <= value))
    else:
        center = float(np.mean(surrogates))
        extreme = int(np.sum(np.abs(surrogates - center) >= abs(value - center)))
    return SurrogateTestResult(values, value, surrogates, (1 + extreme) / (1 + surrogates.size))

symbolic(source, *, kind='equations', use_initial_state=False)

Return the symbolic form of a system.

Each state component is a function of time t, and the equations say how it changes, such as x' = r x for exponential growth, which Maxima solves to x(t) = x(0) e^(r t). The equations of a group hold for every member and are named with the member index i, and components driven by a callable law or by a sum over members or pairs are left out. It writes the equations of an epidemic, a circuit, and a mechanical system, and solves them exactly where it can.

Read more in the user guide, under Analyse.

Parameters:

Name Type Description Default
source DataSource

The system, its compiled problem, or a trajectory of it.

required
kind str

What to return. 'equations' gives one equation per state component, a Sage relation. Continuous forms give its time derivative, the drift for stochastic systems, and discrete maps give its value at t + 1. States of higher order give their highest derivative, diff(x(t), t, k), with their companions written as derivatives, and lagged states read their past values as x(t - j). 'solve' gives the exact solution of the equations of an ODE system as functions of time, with Maxima through Sage. One equation of order 1 or 2 is solved with desolve, one of higher order with desolve_laplace, and several with desolve_system after reduction to first order, which solves linear systems with constant coefficients. A result that still holds unevaluated transforms, integrals, or the unknown functions is not a solution and raises the error. Parameters give Maxima their sign from their domain, or from their value when their domain is real. One linear fractional relaxation D^alpha x = c x has the solution x(0) E_alpha(c t^alpha), written with the symbolic function mittag_leffler(alpha, beta, z). 'hamiltonian' gives the Hamiltonian of an operator system, the sum of the operators of its generator laws, whose subsystems are the symbols of the states of the elements, named <state>_<path>, and whose parameters are named <parameter>_<path>. 'conservation' gives the net inflow from the environment of every quantity of a system with a transfer network, after checking that its internal flows cancel, so the total changes only through the boundary.

'equations'
use_initial_state bool

Whether 'solve' uses the initial state of the system, with the initial values of every derivative of states of higher order, as initial conditions at t = 0. Without them, the solution keeps its integration constants.

False

Returns:

Name Type Description
result SymbolicResult

The compiled problem and the symbolic form of the kind.

Raises:

Type Description
AnalysisError

The system has no form of the kind, such as a system that compiles to a form without equations, Maxima cannot solve its equations, or needs the sign of a parameter.

ConservationError

The internal flows of a quantity do not cancel.

See Also

invariants: Gives the rates of expressions of a system and whether they are conserved. stability: Finds the fixed points of a system and whether they are stable.

Examples:

>>> from skcomplex.core.analysis import symbolic
>>> from skcomplex.systems.biology.ecology import ExponentialGrowthSystem
>>> symbolic(ExponentialGrowthSystem()).equations['population.x']
diff(x_population(t), t) == r_growth*x_population(t)
Source code in src/skcomplex/core/analysis/_symbolic.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def symbolic(source: DataSource, *, kind: str = 'equations', use_initial_state: bool = False) -> SymbolicResult:
    """Return the symbolic form of a system.

    Each state component is a function of time `t`, and the equations say how it changes, such as `x' = r x` for
    exponential growth, which Maxima solves to `x(t) = x(0) e^(r t)`. The equations of a group hold for every member
    and are named with the member index `i`, and components driven by a callable law or by a sum over members or pairs
    are left out. It writes the equations of an epidemic, a circuit, and a mechanical system, and solves them exactly
    where it can.

    Read more in the user guide, under Analyse.

    Args:
        source:
            The system, its compiled problem, or a trajectory of it.

        kind:
            What to return. `'equations'` gives one equation per state component, a Sage relation. Continuous forms give
            its time derivative, the drift for stochastic systems, and discrete maps give its value at `t + 1`. States
            of higher order give their highest derivative, `diff(x(t), t, k)`, with their companions written as
            derivatives, and lagged states read their past values as `x(t - j)`. `'solve'` gives the exact solution of
            the equations of an ODE system as functions of time, with Maxima through Sage. One equation of order 1 or 2
            is solved with `desolve`, one of higher order with `desolve_laplace`, and several with `desolve_system`
            after reduction to first order, which solves linear systems with constant coefficients. A result that
            still holds unevaluated transforms, integrals, or the unknown functions is not a solution and raises the
            error. Parameters give Maxima their sign from their domain, or from their value when their domain is real.
            One linear fractional relaxation `D^alpha x = c x` has the solution `x(0) E_alpha(c t^alpha)`, written with
            the symbolic function `mittag_leffler(alpha, beta, z)`. `'hamiltonian'` gives the Hamiltonian of an
            operator system, the sum of the operators of its generator laws, whose subsystems are the symbols of the
            states of the elements, named `<state>_<path>`, and whose parameters are named `<parameter>_<path>`.
            `'conservation'` gives the net inflow from the environment of every quantity of a system with a transfer
            network, after checking that its internal flows cancel, so the total changes only through the boundary.

        use_initial_state:
            Whether `'solve'` uses the initial state of the system, with the initial values of every derivative of
            states of higher order, as initial conditions at `t = 0`. Without them, the solution keeps its integration
            constants.

    Returns:
        result:
            The compiled problem and the symbolic form of the kind.

    Raises:
        AnalysisError:
            The system has no form of the kind, such as a system that compiles to a form without equations, Maxima
            cannot solve its equations, or needs the sign of a parameter.

        ConservationError:
            The internal flows of a quantity do not cancel.

    See Also:
        invariants: Gives the rates of expressions of a system and whether they are conserved.
        stability: Finds the fixed points of a system and whether they are stable.

    Examples:
        >>> from skcomplex.core.analysis import symbolic
        >>> from skcomplex.systems.biology.ecology import ExponentialGrowthSystem
        >>> symbolic(ExponentialGrowthSystem()).equations['population.x']
        diff(x_population(t), t) == r_growth*x_population(t)
    """
    source = _composite(source)
    _check_choice('symbolic', 'kind', kind, KINDS)
    _check_settings(symbolic, 'kind', SETTINGS[kind], kind=kind, use_initial_state=use_initial_state)
    system = _read_system(source)
    compiled = (
        system if isinstance(system, BaseProblemSpec) else _get_compiler_of(system).prepare(system).run().problem_
    )
    if not isinstance(compiled, ProblemSpec | OperatorProblemSpec):
        error_msg = (
            f'The system compiles to the {compiled.form} form, which has no equations. Simulate it and analyse its '
            'trajectory instead.'
        )
        raise AnalysisError(error_msg)
    if kind == 'hamiltonian':
        operators = _operator_problem(compiled)
        return SymbolicResult(operators, hamiltonian=operators.generator_operator)
    if kind == 'equations' and compiled.form == FormKind.OPERATOR:
        error_msg = (
            'An operator system has an operator Hamiltonian, not state equations. Use '
            "`symbolic(system, kind='hamiltonian')`."
        )
        raise AnalysisError(error_msg)
    problem = compile_problem(compiled, PURPOSES[kind])
    if kind == 'equations':
        return SymbolicResult(problem, equations=_equations_of_problem(problem))
    if kind == 'solve':
        return SymbolicResult(problem, solutions=_solve(problem, use_initial_state=use_initial_state))
    return SymbolicResult(problem, inflows=_conservation(problem))