Skip to content

Components

Define the components of a system and the specs of the values they read.

An element holds values, such as Element('ball', values={'x': 10.0, 'm': 1.0}), an interaction reads them through its roles and states its laws in laws_ when it is prepared, a law is one equation or rule for one value, and a space places the members of a group. The specs here name observables, tensors, and the other values components read.

EntrySpec(name, start, shape, domain, members=None, is_complex=False, period=None, tensor=None) dataclass

Bases: BaseSpec

A spec of where one named value sits in the flat vector of a run.

A run keeps every state in one flat vector, and this spec says where one value starts, its shape, the set of values it takes, and how many members hold it, such as the 1000 positions of a gas from index 0. A complex value takes two places per number, its real and imaginary components, and a tensor only its independent components. Solvers and observers read and write the values of a run through it. It locates the size of a population, the spins of a magnet, and the prices of a market.

Read more in the user guide, under Extend the library.

Parameters:

Name Type Description Default
name str

The dotted name of the value, such as meadow/rabbits.n.

required
start int

The index of its first number in the vector.

required
shape tuple[int, ...]

The shape of the value, () for a number and (n_dim,) for a vector.

required
domain object

The Sage set of the values it takes, such as RR for the real numbers.

required
members int | None

The number of members of the group that holds the value, or None for one element or an interaction.

None
is_complex bool

Whether the value is complex, with the real and imaginary components of every number stored in a row.

False
period float | None

The period that the value wraps around, such as 2 pi for an angle, or None.

None
tensor TensorSpec | None

The independent components of a value that is a matrix of a symmetry, or None.

None
See Also

TensorSpec: The independent components of a matrix value.

Examples:

>>> from sage.all__sagemath_symbolics import CC
>>> from skcomplex.core.components import EntrySpec
>>> entry = EntrySpec('a.z', 0, (2,), CC, is_complex=True)
>>> entry.size, entry.component_names[:2]
(4, ['a.z[0].real', 'a.z[0].imag'])

columns cached property

Number of components of the variable of one member.

component_names property

Names of the components.

They carry an index suffix for vectors, a member index for groups, and complex parts.

generic_names property

Names of the components of one member, with the member index i for groups.

indices cached property

Slice of the variable's components in the vector.

kind property

Kind of value the variable takes.

It is an angle for a periodic variable and a tensor for a tensor component.

member_shape property

Shape of the variable of one member.

It is () for a scalar and (n_dim,) for a vector.

rows cached property

Number of members, 1 for a single element or an interaction.

size cached property

Number of components of the variable.

contains(value)

Check that every component of a value belongs to the domain of the variable.

Parameters:

Name Type Description Default
value object

A value or an array of values.

required

Returns:

Name Type Description
is_contained bool

Whether every component belongs to the domain.

Source code in src/skcomplex/core/components/_entry_spec.py
227
228
229
230
231
232
233
234
235
236
237
238
def contains(self, value: object) -> bool:
    """Check that every component of a value belongs to the domain of the variable.

    Args:
        value:
            A value or an array of values.

    Returns:
        is_contained:
            Whether every component belongs to the domain.
    """
    return EntrySpec._contains(self.domain, value)

decode(values)

Return the stored components of the variable, with complex parts joined.

The components are the last axis of an array.

Parameters:

Name Type Description Default
values Array

The stored components on the last axis.

required

Returns:

Name Type Description
values Array | ComplexArray

The values, complex for a complex variable, with the last axis of the shape of the variable.

Source code in src/skcomplex/core/components/_entry_spec.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def decode(self, values: Array) -> Array | ComplexArray:
    """Return the stored components of the variable, with complex parts joined.

    The components are the last axis of an array.

    Args:
        values:
            The stored components on the last axis.

    Returns:
        values:
            The values, complex for a complex variable, with the last axis of the shape of the variable.
    """
    if not self.is_complex:
        return values
    return np.ascontiguousarray(values).view(complex)

encode(value)

Return a value broadcast to the shape of the variable as flat floats.

A complex variable gives the floats in pairs.

Parameters:

Name Type Description Default
value object

A value in the domain of the variable, of its shape or of a shape that broadcasts to it.

required

Returns:

Name Type Description
components NDArray[float64]

The flat components, as stored in a vector.

Raises:

Type Description
ValueError

The value does not broadcast to the shape of the variable.

Examples:

>>> from sage.all__sagemath_symbolics import CC, RR
>>> from skcomplex.core.components import EntrySpec
>>> EntrySpec('a.z', 0, (), CC, is_complex=True).encode(1 + 2j).tolist()
[1.0, 2.0]
Source code in src/skcomplex/core/components/_entry_spec.py
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 encode(self, value: object) -> npt.NDArray[np.float64]:
    """Return a value broadcast to the shape of the variable as flat floats.

    A complex variable gives the floats in pairs.

    Args:
        value:
            A value in the domain of the variable, of its shape or of a shape that broadcasts to it.

    Returns:
        components:
            The flat components, as stored in a vector.

    Raises:
        ValueError:
            The value does not broadcast to the shape of the variable.

    Examples:
        >>> from sage.all__sagemath_symbolics import CC, RR
        >>> from skcomplex.core.components import EntrySpec
        >>> EntrySpec('a.z', 0, (), CC, is_complex=True).encode(1 + 2j).tolist()
        [1.0, 2.0]
    """
    values = np.broadcast_to(EntrySpec._encode(self.domain, value, self.period), self.shape)
    if self.is_complex:
        return np.ascontiguousarray(values, dtype=complex).ravel().view(float).copy()
    return values.ravel().copy()

get_view(vector)

Return the variable's components of a flat vector as a view.

The view has one row per member.

Parameters:

Name Type Description Default
vector NDArray[float64]

A flat vector.

required

Returns:

Name Type Description
view NDArray[float64]

A (rows, columns) view that writes through to the vector.

Source code in src/skcomplex/core/components/_entry_spec.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def get_view(self, vector: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
    """Return the variable's components of a flat vector as a view.

    The view has one row per member.

    Args:
        vector:
            A flat vector.

    Returns:
        view:
            A `(rows, columns)` view that writes through to the vector.
    """
    return vector[self.indices].reshape(self.rows, self.columns)

read(values)

Return stored numbers as values of the domain.

They are labels for a categorical domain and booleans for a boolean one.

Parameters:

Name Type Description Default
values ArrayLike

The stored numbers.

required

Returns:

Name Type Description
values NDArray[generic]

The values.

Examples:

>>> from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
>>> from skcomplex.core.components import EntrySpec
>>> EntrySpec('a.s', 0, (), FiniteEnumeratedSet(['S', 'I'])).read([1.0, 0.0]).tolist()
['I', 'S']
Source code in src/skcomplex/core/components/_entry_spec.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def read(self, values: npt.ArrayLike) -> npt.NDArray[np.generic]:
    """Return stored numbers as values of the domain.

    They are labels for a categorical domain and booleans for a boolean one.

    Args:
        values:
            The stored numbers.

    Returns:
        values:
            The values.

    Examples:
        >>> from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        >>> from skcomplex.core.components import EntrySpec
        >>> EntrySpec('a.s', 0, (), FiniteEnumeratedSet(['S', 'I'])).read([1.0, 0.0]).tolist()
        ['I', 'S']
    """
    return EntrySpec._decode(self.domain, values)

MatrixGroupSpec(name='SU', degree=2) dataclass

Bases: BaseSpec

A spec of the values of a state that are unitary matrices of one size.

A unitary matrix keeps the length of every complex vector it multiplies, and the group is U(n) of all of them or SU(n) of those with determinant 1, such as MatrixGroupSpec('SU', 2) for the rotations of a spin. A state of the group holds each matrix by the real and imaginary components of its entries in row order, 2 n^2 numbers. The product of the matrices along a path of edges, inverting those walked against their direction, is the holonomy of the path. It holds the links of a lattice gauge theory, the rotations of a rigid body, and the gates of a quantum circuit.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
name str

'SU' for the special unitary group, or 'U' for the unitary group.

'SU'
degree int

The number of rows and columns of the matrices.

2

Raises:

Type Description
ValidationError

The name is unknown, or the degree is not a positive integer.

See Also

PowerSeriesSpec: Values that are truncated power series. TensorSpec: The independent components of a matrix value.

Examples:

>>> from skcomplex.core.components import MatrixGroupSpec
>>> group = MatrixGroupSpec('SU', 2)
>>> group.size, group.identity.tolist()
(8, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0])

identity cached property

Components of the identity matrix.

size cached property

Number of real components of a matrix of the group.

get_components_of(matrices)

Return the real components of matrices on the last two axes.

Parameters:

Name Type Description Default
matrices ArrayLike

The complex matrices on the last two axes.

required

Returns:

Name Type Description
components Array

The components, 2 n^2 on the last axis.

Examples:

>>> from skcomplex.core.components import MatrixGroupSpec
>>> MatrixGroupSpec('U', 1).get_components_of([[1j]]).tolist()
[0.0, 1.0]
Source code in src/skcomplex/core/components/_matrix_group_spec.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def get_components_of(self, matrices: npt.ArrayLike) -> Array:
    """Return the real components of matrices on the last two axes.

    Args:
        matrices:
            The complex matrices on the last two axes.

    Returns:
        components:
            The components, `2 n^2` on the last axis.

    Examples:
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> MatrixGroupSpec('U', 1).get_components_of([[1j]]).tolist()
        [0.0, 1.0]
    """
    array = np.asarray(matrices, dtype=complex)
    return np.stack([array.real, array.imag], axis=-1).reshape(*array.shape[:-2], self.size)

get_holonomy_of(matrices, edges, signs)

Return the path-ordered products of the matrices of the edges along paths.

Every path is a row of edges on the last axis with the sign of its traversal, 1 along the orientation of the edge, -1 against it, and 0 for padding that contributes the identity.

Parameters:

Name Type Description Default
matrices ArrayLike

The matrix of every edge, one per row of the first axis.

required
edges ArrayLike

The edges of the paths, in path order on the last axis.

required
signs ArrayLike

The sign of the traversal of every edge, of the shape of edges.

required

Returns:

Name Type Description
holonomies ComplexArray

The product along every path, with the shape of the paths and the matrix on the last two axes.

Raises:

Type Description
ValidationError

The edges and the signs do not have the same shape, or a sign is not 1, -1, or 0.

Examples:

>>> import numpy as np
>>> from skcomplex.core.components import MatrixGroupSpec
>>> group = MatrixGroupSpec('U', 1)
>>> phases = np.exp(1j * np.array([0.5, 0.25])).reshape(2, 1, 1)
>>> round(float(np.angle(group.get_holonomy_of(phases, [0, 1], [1, -1]))[0, 0]), 12)
0.25
Source code in src/skcomplex/core/components/_matrix_group_spec.py
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
def get_holonomy_of(self, matrices: npt.ArrayLike, edges: npt.ArrayLike, signs: npt.ArrayLike) -> ComplexArray:
    """Return the path-ordered products of the matrices of the edges along paths.

    Every path is a row of edges on the last axis with the sign of its traversal, 1 along the orientation of the
    edge, -1 against it, and 0 for padding that contributes the identity.

    Args:
        matrices:
            The matrix of every edge, one per row of the first axis.

        edges:
            The edges of the paths, in path order on the last axis.

        signs:
            The sign of the traversal of every edge, of the shape of `edges`.

    Returns:
        holonomies:
            The product along every path, with the shape of the paths and the matrix on the last two axes.

    Raises:
        ValidationError:
            The edges and the signs do not have the same shape, or a sign is not 1, -1, or 0.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> group = MatrixGroupSpec('U', 1)
        >>> phases = np.exp(1j * np.array([0.5, 0.25])).reshape(2, 1, 1)
        >>> round(float(np.angle(group.get_holonomy_of(phases, [0, 1], [1, -1]))[0, 0]), 12)
        0.25
    """
    array = np.asarray(matrices, dtype=complex)
    path = np.asarray(edges, dtype=np.intp)
    turn = np.asarray(signs)
    if path.shape != turn.shape or not np.isin(turn, (-1, 0, 1)).all():
        error_msg = (
            f'A path takes one sign of 1, -1, or 0 per edge, but got edges of the shape {path.shape} and signs '
            f'{np.unique(turn).tolist()} of the shape {turn.shape}.'
        )
        raise ValidationError(error_msg)
    identity = np.eye(self.degree, dtype=complex)
    product = np.broadcast_to(identity, (*path.shape[:-1], self.degree, self.degree)).copy()
    for step in range(path.shape[-1]):
        factor = array[np.where(turn[..., step] == 0, 0, path[..., step])]
        factor = np.where((turn[..., step] < 0)[..., None, None], np.conj(np.swapaxes(factor, -1, -2)), factor)
        product = product @ np.where((turn[..., step] == 0)[..., None, None], identity, factor)
    return product

get_matrices_of(components)

Return the matrices of real components on the last axis.

Parameters:

Name Type Description Default
components ArrayLike

The components, 2 n^2 on the last axis.

required

Returns:

Name Type Description
matrices ComplexArray

The complex matrices on the last two axes.

Raises:

Type Description
ValidationError

The last axis does not hold 2 n^2 components.

Examples:

>>> from skcomplex.core.components import MatrixGroupSpec
>>> MatrixGroupSpec('U', 1).get_matrices_of([0.0, 1.0]).tolist()
[[1j]]
Source code in src/skcomplex/core/components/_matrix_group_spec.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
def get_matrices_of(self, components: npt.ArrayLike) -> ComplexArray:
    """Return the matrices of real components on the last axis.

    Args:
        components:
            The components, `2 n^2` on the last axis.

    Returns:
        matrices:
            The complex matrices on the last two axes.

    Raises:
        ValidationError:
            The last axis does not hold `2 n^2` components.

    Examples:
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> MatrixGroupSpec('U', 1).get_matrices_of([0.0, 1.0]).tolist()
        [[1j]]
    """
    array = np.asarray(components, dtype=float)
    if array.shape[-1:] != (self.size,):
        error_msg = (
            f'A matrix of {self.name}({self.degree}) has {self.size} real components, but the values have the '
            f'shape {array.shape}.'
        )
        raise ValidationError(error_msg)
    parts = array.reshape(*array.shape[:-1], self.degree, self.degree, PARTS)
    return parts[..., 0] + 1j * parts[..., 1]

get_near_identity_of(rng, width, count)

Return random matrices of the group near the identity.

They are exp(i width H) for random Hermitian H. The entries of H are standard normal up to Hermitian symmetry, and traceless for SU(n). A matrix and its inverse are equally likely, so a move by these matrices is symmetric.

Parameters:

Name Type Description Default
rng Generator

The random generator.

required
width float

The spread of the matrices around the identity.

required
count int

The number of matrices.

required

Returns:

Name Type Description
matrices ComplexArray

The matrices, one per row of the first axis.

Examples:

>>> import numpy as np
>>> from skcomplex.core.components import MatrixGroupSpec
>>> moves = MatrixGroupSpec('SU', 3).get_near_identity_of(np.random.default_rng(0), 0.1, 4)
>>> bool(np.allclose(np.linalg.det(moves), 1.0))
True
Source code in src/skcomplex/core/components/_matrix_group_spec.py
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
def get_near_identity_of(self, rng: np.random.Generator, width: float, count: int) -> ComplexArray:
    """Return random matrices of the group near the identity.

    They are `exp(i width H)` for random Hermitian `H`. The entries of `H` are standard normal up to Hermitian
    symmetry, and traceless for `SU(n)`. A matrix and its inverse are equally likely, so a move by these matrices is
    symmetric.

    Args:
        rng:
            The random generator.

        width:
            The spread of the matrices around the identity.

        count:
            The number of matrices.

    Returns:
        matrices:
            The matrices, one per row of the first axis.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> moves = MatrixGroupSpec('SU', 3).get_near_identity_of(np.random.default_rng(0), 0.1, 4)
        >>> bool(np.allclose(np.linalg.det(moves), 1.0))
        True
    """
    shape = (count, self.degree, self.degree)
    draws = rng.normal(size=shape) + 1j * rng.normal(size=shape)
    hermitian = (draws + np.conj(np.swapaxes(draws, -1, -2))) / 2
    if self.name == 'SU':
        trace = np.trace(hermitian, axis1=-2, axis2=-1).real / self.degree
        hermitian = hermitian - trace[:, None, None] * np.eye(self.degree)
    values, vectors = np.linalg.eigh(hermitian)
    rotations = (vectors * np.exp(1j * width * values)[:, None, :]) @ np.conj(np.swapaxes(vectors, -1, -2))
    return np.asarray(rotations, dtype=complex)

get_projection_of(matrices)

Return the nearest matrices of the group.

They undo the rounding of repeated products. The unitary factor of the polar decomposition is the nearest unitary matrix, and for SU(n) it is divided by the principal n-th root of its determinant.

Parameters:

Name Type Description Default
matrices ArrayLike

The complex matrices on the last two axes.

required

Returns:

Name Type Description
projected ComplexArray

The matrices of the group.

Examples:

>>> import numpy as np
>>> from skcomplex.core.components import MatrixGroupSpec
>>> projected = MatrixGroupSpec('SU', 2).get_projection_of(1.01 * np.eye(2))
>>> bool(np.allclose(projected, np.eye(2)))
True
Source code in src/skcomplex/core/components/_matrix_group_spec.py
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
def get_projection_of(self, matrices: npt.ArrayLike) -> ComplexArray:
    """Return the nearest matrices of the group.

    They undo the rounding of repeated products. The unitary factor of the polar decomposition is the nearest
    unitary matrix, and for `SU(n)` it is divided by the principal `n`-th root of its determinant.

    Args:
        matrices:
            The complex matrices on the last two axes.

    Returns:
        projected:
            The matrices of the group.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> projected = MatrixGroupSpec('SU', 2).get_projection_of(1.01 * np.eye(2))
        >>> bool(np.allclose(projected, np.eye(2)))
        True
    """
    left, _, right = np.linalg.svd(np.asarray(matrices, dtype=complex))
    unitary = left @ right
    if self.name == 'U':
        return unitary
    phase = np.exp(1j * np.angle(np.linalg.det(unitary)) / self.degree)
    return unitary / phase[..., None, None]

get_uniform_of(rng, count)

Return matrices drawn from the Haar measure of the group.

SciPy draws unitary matrices from the Haar measure of U(n), and dividing by the principal n-th root of the determinant keeps the Haar measure of SU(n).

Parameters:

Name Type Description Default
rng Generator

The random generator.

required
count int

The number of matrices.

required

Returns:

Name Type Description
matrices ComplexArray

The matrices, one per row of the first axis.

Examples:

>>> import numpy as np
>>> from skcomplex.core.components import MatrixGroupSpec
>>> draws = MatrixGroupSpec('SU', 2).get_uniform_of(np.random.default_rng(0), 5)
>>> draws.shape, bool(np.allclose(np.linalg.det(draws), 1.0))
((5, 2, 2), True)
Source code in src/skcomplex/core/components/_matrix_group_spec.py
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
def get_uniform_of(self, rng: np.random.Generator, count: int) -> ComplexArray:
    """Return matrices drawn from the Haar measure of the group.

    SciPy draws unitary matrices from the Haar measure of `U(n)`, and dividing by the principal `n`-th root of the
    determinant keeps the Haar measure of `SU(n)`.

    Args:
        rng:
            The random generator.

        count:
            The number of matrices.

    Returns:
        matrices:
            The matrices, one per row of the first axis.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> draws = MatrixGroupSpec('SU', 2).get_uniform_of(np.random.default_rng(0), 5)
        >>> draws.shape, bool(np.allclose(np.linalg.det(draws), 1.0))
        ((5, 2, 2), True)
    """
    if self.degree == 1:
        unitary = np.exp(2j * np.pi * rng.random(count)).reshape(count, 1, 1)
    else:
        drawn = scipy.stats.unitary_group.rvs(self.degree, size=count, random_state=rng)
        unitary = np.asarray(drawn, dtype=complex).reshape(count, self.degree, self.degree)
    if self.name == 'U':
        return unitary
    return self.get_projection_of(unitary)

Observable(label, expression=None, element=None, group=None, reduce='mean', variable=None, function=None) dataclass

Bases: BaseSpec

A spec of a named value of a system that a run computes at every frame.

A run computes it from the values of the system and records it in its trajectory under <system path>/<label>, or <element>.<label> for one element, such as the mean wealth of the traders in Observable('mean_wealth', group='traders', variable='wealth'). It is a function of the elements of the system, of one element, or of one member, or a reduction such as a sum or a mean over the members of a group. Laws of other systems read it through a role bound to its path. It measures the total population of an epidemic, the energy of a pendulum, and the magnetization of a lattice of spins.

Read more in the user guide, under Observe.

Parameters:

Name Type Description Default
label str

The label of the observable, unique among the observables of its system.

required
expression object

A function of the namespace of the system, of the element, or of one member, or a symbolic expression.

None
element str | None

The label of an element or an interaction of the root system whose namespace the expression reads, or None.

None
group str | None

The path of the group to reduce over, relative to the system, or None for no reduction.

None
reduce str | Callable[[AnyArray], object]

'count', 'sum', 'mean', 'min', 'max', 'var', 'logsumexp', or a function of the array of member values.

'mean'
variable str | None

The name of the member value to reduce, instead of an expression.

None
function Callable[[float, Mapping[str, object]], object] | None

A function f(t, values) of time and the mapping from the dotted name of every state and parameter to its value, instead of an expression, for a system without agents. A module-level function, since observables are pickled.

None
See Also

System: Takes observables as an argument of simulate.

Examples:

>>> from skcomplex.core.components import Observable
>>> Observable('mean_wealth', group='traders', variable='wealth').reduce
'mean'

PowerSeriesSpec(order=8, field='QQ', variable='t') dataclass

Bases: BaseSpec

A spec of the values of a state that are power series cut after some terms.

A value is a series a_0 + a_1 t + a_2 t^2 + ... kept by its first order coefficients, such as PowerSeriesSpec(4) for the terms up to t^3. Sums add the coefficients, and products multiply the series and drop the terms past the order, so the kept coefficients are exact. Local rules read the coefficients of every neighbour on a last axis, and ring converts them to Sage power series. It holds the generating functions of cellular automata, the counts of paths in a network, and the Taylor terms of an orbit.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
order int

The number of coefficients kept.

8
field str

'QQ' for the rationals, 'RR' for the reals, or 'GF(p)' for the whole numbers modulo a prime p.

'QQ'
variable str

The name of the variable of the series.

't'

Raises:

Type Description
ValidationError

The order is not a positive integer, or the field is unknown.

See Also

MatrixGroupSpec: Values that are unitary matrices.

Examples:

>>> from skcomplex.core.components import PowerSeriesSpec
>>> series = PowerSeriesSpec(4)
>>> series.multiply([1, 1, 0, 0], [1, -1, 0, 0]).tolist()
[1.0, 0.0, -1.0, 0.0]

alphabet property

Sage set of the stored values of a coefficient.

It is the field or the residues 0 to p - 1 of a prime field.

characteristic property

Characteristic of the field, 0 for the rationals and the reals.

ring property

Sage ring of power series over the field with the precision of the order.

sage_field property

Sage field of the coefficients.

get_coefficients_of(series)

Return the coefficients of a series of the ring up to the order.

The series can also be anything the ring converts.

Parameters:

Name Type Description Default
series object

A series, a polynomial in the indeterminate, or a number.

required

Returns:

Name Type Description
coefficients Array

The coefficients a_0, ..., a_{order - 1}, as floats.

Source code in src/skcomplex/core/components/_power_series_spec.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def get_coefficients_of(self, series: object) -> Array:
    """Return the coefficients of a series of the ring up to the order.

    The series can also be anything the ring converts.

    Args:
        series:
            A series, a polynomial in the indeterminate, or a number.

    Returns:
        coefficients:
            The coefficients `a_0, ..., a_{order - 1}`, as floats.
    """
    element = self.ring(series)
    values = element.padded_list(self.order)
    return np.asarray([float(int(item)) if self.characteristic else float(item) for item in values])

get_series_of(coefficients)

Return the series of the ring with some coefficients.

Parameters:

Name Type Description Default
coefficients ArrayLike

The coefficients a_0, ..., a_{order - 1}.

required

Returns:

Name Type Description
series PowerSeries

The series of ring, with the precision of the order.

Source code in src/skcomplex/core/components/_power_series_spec.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def get_series_of(self, coefficients: npt.ArrayLike) -> PowerSeries:
    """Return the series of the ring with some coefficients.

    Args:
        coefficients:
            The coefficients `a_0, ..., a_{order - 1}`.

    Returns:
        series:
            The series of `ring`, with the precision of the order.
    """
    field = self.sage_field
    values = [field(int(item)) if self.characteristic else field(item) for item in np.ravel(coefficients)]
    return self.ring(values, prec=self.order)

multiply(first, second)

Return the product of two series truncated at the order.

The series are coefficient arrays on the last axis.

Parameters:

Name Type Description Default
first ArrayLike

The coefficients of the first factor, whose leading axes broadcast with those of the second.

required
second ArrayLike

The coefficients of the second factor.

required

Returns:

Name Type Description
product Array

The coefficients of the product, sum_{j <= i} a_j b_{i - j} at every power i below the order.

Source code in src/skcomplex/core/components/_power_series_spec.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def multiply(self, first: npt.ArrayLike, second: npt.ArrayLike) -> Array:
    """Return the product of two series truncated at the order.

    The series are coefficient arrays on the last axis.

    Args:
        first:
            The coefficients of the first factor, whose leading axes broadcast with those of the second.

        second:
            The coefficients of the second factor.

    Returns:
        product:
            The coefficients of the product, `sum_{j <= i} a_j b_{i - j}` at every power `i` below the order.
    """
    first_values = np.asarray(first, dtype=float)
    second_values = np.asarray(second, dtype=float)
    shape = np.broadcast_shapes(first_values.shape[:-1], second_values.shape[:-1])
    product = np.zeros((*shape, self.order))
    for power in range(self.order):
        product[..., power:] += first_values[..., power, None] * second_values[..., : self.order - power]
    return self.reduce(product)

reduce(coefficients)

Return coefficients reduced modulo the characteristic.

They are unchanged over a field of characteristic 0.

Parameters:

Name Type Description Default
coefficients ArrayLike

The coefficients on the last axis.

required

Returns:

Name Type Description
coefficients Array

The reduced coefficients, as floats.

Source code in src/skcomplex/core/components/_power_series_spec.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def reduce(self, coefficients: npt.ArrayLike) -> Array:
    """Return coefficients reduced modulo the characteristic.

    They are unchanged over a field of characteristic 0.

    Args:
        coefficients:
            The coefficients on the last axis.

    Returns:
        coefficients:
            The reduced coefficients, as floats.
    """
    values = np.asarray(coefficients, dtype=float)
    return np.mod(np.rint(values), self.characteristic) if self.characteristic else values

RoleSpec(variadic=False, noise=False, optional=False, elements=(), states=(), domains=()) dataclass

Bases: BaseSpec

A spec of a role of an interaction: what it binds and which values it reads.

It annotates an argument of an interaction, such as prey: Annotated[str, RoleSpec(states=('n',))], and says what the argument binds: one element, one group, or one member written <group>[<index>], a sequence of them when variadic, or Wiener processes when it is a noise role. It names the kinds of element the role accepts and the values it reads, so a system rejects a wrong binding before a run. An optional role may be bound to None. It types the predator and the prey of predation, the payer of a payment, and the two ends of a spring.

Read more in the user guide, under Interactions.

Parameters:

Name Type Description Default
variadic bool

Whether the role binds a sequence of entries instead of one path.

False
noise bool

Whether the role binds a set of Wiener processes instead of a path.

False
optional bool

Whether the role may be bound to None, so it binds nothing.

False
elements tuple[ElementKind, ...]

The kinds of element the role accepts, with ElementKind.ANY for all of them. Empty accepts any element.

()
states tuple[str, ...]

The names of the states the role reads, or of the arguments of the constructor that hold these names.

()
domains tuple[str, ...]

The domain tags the role accepts for the states it reads, or for every state of the element when it names none, such as ('real', 'integer'). Empty accepts any domain.

()
See Also

Interaction: Binds elements through its roles.

Examples:

>>> from skcomplex.core.components import RoleSpec
>>> from skcomplex.core.enums import ElementKind
>>> role = RoleSpec(elements=(ElementKind.GROUP,), states=('state',))
>>> role.accepts(ElementKind.ELEMENT), role.accepts(ElementKind.GROUP)
(False, True)

accepts(kind)

Check whether the role accepts an element of a kind.

Parameters:

Name Type Description Default
kind ElementKind

The kind of the element.

required

Returns:

Name Type Description
accepted bool

Whether the role names the kind, names every kind, or names none.

Source code in src/skcomplex/core/components/_role_spec.py
76
77
78
79
80
81
82
83
84
85
86
87
def accepts(self, kind: ElementKind) -> bool:
    """Check whether the role accepts an element of a kind.

    Args:
        kind:
            The kind of the element.

    Returns:
        accepted:
            Whether the role names the kind, names every kind, or names none.
    """
    return not self.elements or ElementKind.ANY in self.elements or kind in self.elements

SubshiftSpec(neighborhood, forbidden, states=2) dataclass

Bases: BaseSpec

A spec of the values of cells that no forbidden pattern may appear in.

The cells take the values 0 to states - 1, and a pattern is a tuple of values over the cells of a neighbourhood, such as (1, 1) for two live cells side by side. A configuration is allowed when no forbidden pattern appears at any site, and patterns that reach past the edge of a space are not checked. A run checks that every cell holds a value of alphabet, and automaton decides whether a whole configuration is allowed. It describes the golden mean shift of symbolic dynamics, hard core gases, and codes that forbid long runs of one symbol.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
neighborhood object

The neighbourhood of offsets on a lattice, or of elements on a group space, that patterns cover.

required
forbidden Sequence[tuple[int, ...]]

The forbidden patterns.

required
states int

The number of values of a cell, 0 to states - 1.

2
See Also

LatticeNeighborhood: The offsets a pattern covers.

Examples:

>>> from skcomplex.core.components import SubshiftSpec
>>> from skcomplex.core.components.spaces import LatticeNeighborhood
>>> golden = SubshiftSpec(LatticeNeighborhood(((0,), (1,))), ((1, 1),))
>>> golden.forbidden, golden.states
(((1, 1),), 2)

alphabet property

Sage set of the values of a cell.

Tags(time=frozenset(), domains=frozenset(), space=frozenset(), laws=frozenset(), randomness='deterministic', structure=frozenset(), reparameterized=False) dataclass

Bases: BaseSpec

A set of tags that say what a component, a solver, or a backend handles.

They say the times a component runs in, the domains of its values, its spaces, the kinds of its laws, whether it draws random numbers, and whether its structure changes, such as a continuous time and rate and noise laws for a stochastic differential equation. They come from the arguments and annotations of a component alone, so they are known before prepare, and a system compares them with those of a solver to pick one that runs it. An empty set means any value, and a law kind or randomness of None means the component does not show it. They match an epidemic, a market, or a magnet with a solver that runs it.

Read more in the user guide, under Solvers.

Parameters:

Name Type Description Default
time frozenset[str]

The times the component runs in, among 'continuous', 'discrete', and 'static'.

frozenset()
domains frozenset[str]

The domains of the states, among 'real', 'integer', 'boolean', 'categorical', 'complex', 'vector', 'matrix group', and 'power series'.

frozenset()
space frozenset[str]

The spaces, among 'none', 'continuous', 'lattice', 'network', 'hypergraph', 'cell complex', 'phase space', and 'curved spacetime'.

frozenset()
laws frozenset[str] | None

The kinds of the laws, among 'rate', 'noise', 'jump', 'update', 'equation', 'objective', and 'sampling', or None when the arguments do not show them.

frozenset()
randomness str | None

'deterministic', 'stochastic', or None when the arguments do not show it.

'deterministic'
structure frozenset[str]

How the structure changes, among 'variable membership' and 'changing topology', empty for a fixed one.

frozenset()
reparameterized bool

Whether every random draw of a stochastic component is a function of a uniform or normal number of the step, so its runs have gradients at fixed random numbers.

False
See Also

BaseComponent: Gives its tags through get_tags.

Examples:

>>> from skcomplex.core.components import Tags
>>> tags = Tags(time=frozenset({'continuous'}), laws=frozenset({'rate', 'noise'}), randomness='stochastic')
>>> Tags(time=frozenset({'continuous'}), laws=frozenset({'rate'})).get_missing(tags)
{'laws': ['noise']}

differentiable property

Whether runs of the component can be differentiated in its parameters.

It holds for rate, update, and equation laws, which the JAX backend lowers to pure functions, when they are deterministic or their draws are reparameterized, so the JAX run draws them from a key.

get_missing(tags)

Return the tags of a system that these supported tags do not support, by field.

A field of the supported tags that is empty supports any value. The system needs one of its times to be supported, and every one of its spaces, domains, and law kinds. Law kinds that are None are 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 unsupported tags of every field that has some, sorted.

Source code in src/skcomplex/core/components/_tags.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def get_missing(self, tags: Tags) -> dict[str, list[str]]:
    """Return the tags of a system that these supported tags do not support, by field.

    A field of the supported tags that is empty supports any value. The system needs one of its times to be
    supported, and every one of its spaces, domains, and law kinds. Law kinds that are `None` are not checked.

    Args:
        tags:
            The tags of a system.

    Returns:
        missing:
            The unsupported tags of every field that has some, sorted.
    """
    found: dict[str, list[str]] = {}
    if self.time and tags.time and not self.time & tags.time:
        found['time'] = sorted(tags.time)
    needed = {'space': (self.space, tags.space), 'domains': (self.domains, tags.domains)}
    needed['laws'] = (self.laws or frozenset(), tags.laws or frozenset())
    for name, (supported, values) in needed.items():
        if supported and values - supported:
            found[name] = sorted(values - supported)
    return found

TensorSpec(symmetry, n_dim) dataclass

Bases: BaseSpec

A spec of the independent components of a matrix value of one symmetry.

A matrix value of two or three rows, such as a stress or an orientation order, often has a symmetry that ties its entries, and the spec keeps only the entries that are free, such as xx and xy for a symmetric traceless matrix of two rows. It turns these components into the full matrix and back. It holds the order of liquid crystals, the stress of a material, and the covariance of two prices.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
symmetry str

'full', 'symmetric', 'antisymmetric', or 'traceless', which means symmetric and traceless.

required
n_dim int

The number of rows and columns, 2 or 3.

required

Raises:

Type Description
ValidationError

The symmetry is unknown or the matrix does not have two or three rows.

See Also

EntrySpec: Locates a matrix value in the vector of a run.

Examples:

>>> from skcomplex.core.components import TensorSpec
>>> tensor = TensorSpec('traceless', 2)
>>> tensor.names, tensor.get_array_of([1.0, 2.0]).tolist()
(('xx', 'xy'), [[1.0, 2.0], [2.0, -1.0]])

basis cached property

Tensors of the independent components.

There is one tensor per component on the first axis.

indices cached property

Row and column of every independent component, in row order.

names cached property

Name of every independent component, such as xx and xy.

get_array_of(components)

Return the arrays of tensors of independent components on the last axis.

Parameters:

Name Type Description Default
components ArrayLike

The independent components on the last axis.

required

Returns:

Name Type Description
tensors Array

The tensors on the last two axes.

Examples:

>>> from skcomplex.core.components import TensorSpec
>>> TensorSpec('antisymmetric', 2).get_array_of([3.0]).tolist()
[[0.0, 3.0], [-3.0, 0.0]]
Source code in src/skcomplex/core/components/_tensor_spec.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def get_array_of(self, components: npt.ArrayLike) -> Array:
    """Return the arrays of tensors of independent components on the last axis.

    Args:
        components:
            The independent components on the last axis.

    Returns:
        tensors:
            The tensors on the last two axes.

    Examples:
        >>> from skcomplex.core.components import TensorSpec
        >>> TensorSpec('antisymmetric', 2).get_array_of([3.0]).tolist()
        [[0.0, 3.0], [-3.0, 0.0]]
    """
    return np.tensordot(np.asarray(components, dtype=float), self.basis, axes=1)

get_components_of(value)

Return the independent components of a numeric matrix.

Parameters:

Name Type Description Default
value object

A matrix of numbers, such as a nested sequence, a NumPy array, or a Sage matrix.

required

Returns:

Name Type Description
components Array

The independent components.

Raises:

Type Description
ValidationError

The value is not a matrix of the shape and the symmetry of the tensor.

Examples:

>>> from skcomplex.core.components import TensorSpec
>>> TensorSpec('symmetric', 2).get_components_of([[1, 2], [2, 3]]).tolist()
[1.0, 2.0, 3.0]
Source code in src/skcomplex/core/components/_tensor_spec.py
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 get_components_of(self, value: object) -> Array:
    """Return the independent components of a numeric matrix.

    Args:
        value:
            A matrix of numbers, such as a nested sequence, a NumPy array, or a Sage matrix.

    Returns:
        components:
            The independent components.

    Raises:
        ValidationError:
            The value is not a matrix of the shape and the symmetry of the tensor.

    Examples:
        >>> from skcomplex.core.components import TensorSpec
        >>> TensorSpec('symmetric', 2).get_components_of([[1, 2], [2, 3]]).tolist()
        [1.0, 2.0, 3.0]
    """
    array = np.asarray(value.numpy() if isinstance(value, Matrix) else value, dtype=float)
    if array.shape != (self.n_dim, self.n_dim):
        error_msg = f'The value has the shape {array.shape}, but the tensor is {self.n_dim} by {self.n_dim}.'
        raise ValidationError(error_msg)
    components = np.asarray([array[row, column] for row, column in self.indices])
    if not np.allclose(self.get_array_of(components), array):
        error_msg = f'The matrix {array.tolist()} does not have the symmetry {self.symmetry!r}.'
        raise ValidationError(error_msg)
    return components

get_matrix_of(components)

Return the symbolic matrix of independent components.

The dependent entries are written in terms of them.

Parameters:

Name Type Description Default
components Iterable[object]

The expressions of the independent components.

required

Returns:

Name Type Description
matrix Matrix

The matrix over the symbolic ring.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components import TensorSpec
>>> TensorSpec('traceless', 2).get_matrix_of(var('a, b'))
[ a  b]
[ b -a]
Source code in src/skcomplex/core/components/_tensor_spec.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def get_matrix_of(self, components: Iterable[object]) -> Matrix:
    """Return the symbolic matrix of independent components.

    The dependent entries are written in terms of them.

    Args:
        components:
            The expressions of the independent components.

    Returns:
        matrix:
            The matrix over the symbolic ring.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components import TensorSpec
        >>> TensorSpec('traceless', 2).get_matrix_of(var('a, b'))
        [ a  b]
        [ b -a]
    """
    total = matrix(SR, self.n_dim, self.n_dim)
    for component, unit in zip(components, self.basis, strict=True):
        total += SR(component) * matrix(SR, unit.tolist())
    return total

get_principal_of(components)

Return the principal axis and the scalar order of symmetric tensors.

The tensors are given by their independent components. The principal axis is the eigenvector of the largest eigenvalue of the traceless part. The scalar order is that eigenvalue times n_dim / (n_dim - 1), so a tensor S (n n - I / n_dim) has the order S.

Parameters:

Name Type Description Default
components ArrayLike

The independent components on the last axis.

required

Returns:

Name Type Description
axes Array

The axes, unit vectors on the last axis, whose sign has no meaning.

orders Array

The scalar orders.

Raises:

Type Description
ValidationError

The tensor is not symmetric.

Examples:

>>> from skcomplex.core.components import TensorSpec
>>> axes, orders = TensorSpec('traceless', 2).get_principal_of([0.5, 0.0])
>>> abs(axes).round(6).tolist(), float(orders)
([1.0, 0.0], 1.0)
Source code in src/skcomplex/core/components/_tensor_spec.py
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
def get_principal_of(self, components: npt.ArrayLike) -> tuple[Array, Array]:
    """Return the principal axis and the scalar order of symmetric tensors.

    The tensors are given by their independent components. The principal axis is the eigenvector of the largest
    eigenvalue of the traceless part. The scalar order is that eigenvalue times `n_dim / (n_dim - 1)`, so a tensor
    `S (n n - I / n_dim)` has the order `S`.

    Args:
        components:
            The independent components on the last axis.

    Returns:
        axes:
            The axes, unit vectors on the last axis, whose sign has no meaning.

        orders:
            The scalar orders.

    Raises:
        ValidationError:
            The tensor is not symmetric.

    Examples:
        >>> from skcomplex.core.components import TensorSpec
        >>> axes, orders = TensorSpec('traceless', 2).get_principal_of([0.5, 0.0])
        >>> abs(axes).round(6).tolist(), float(orders)
        ([1.0, 0.0], 1.0)
    """
    if self.symmetry not in {'symmetric', 'traceless'}:
        error_msg = f'A tensor of the symmetry {self.symmetry!r} has no principal axes. Use a symmetric tensor.'
        raise ValidationError(error_msg)
    tensors = self.get_array_of(components)
    means = np.trace(tensors, axis1=-2, axis2=-1) / self.n_dim
    values, vectors = np.linalg.eigh(tensors - means[..., None, None] * np.eye(self.n_dim))
    return vectors[..., -1], values[..., -1] * self.n_dim / (self.n_dim - 1)