Skip to content

Utils

Define the functions that laws are written with besides Sage.

They hold reductions over the members of a group, pointwise functions, signals of time, random draws, delays, and the operators of fields. The helpers that only the compiler reads stay in the private modules.

advection(expression, velocity)

Return the rate at which a velocity carries a field along, for one site.

It sums upwind(u, axis, v) over the axes, the velocity times the slope of the field taken on the side the flow comes from, which keeps a moving front from rippling, such as upwind(u, 0, 1.0) + upwind(u, 1, 2.0) for a flow (1, 2). A rate law subtracts it from the rate of the field. It carries a pollutant down a river, heat with the wind, and cars along a road.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a field.

required
velocity Sequence[object] | FreeModuleElement

One entry of the velocity per dimension, numbers or expressions.

required

Returns:

Name Type Description
advection Expression

The advection term, to subtract from the rate of the field.

See Also

divergence: Gives the net outflow of a flux. shifted: Reads a field at a distance from every site.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import advection
>>> sorted(str(term) for term in advection(var('u'), [1.0, 2.0]).operands())
['upwind(u, 0, 1.0)', 'upwind(u, 1, 2.0)']
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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
def advection(expression: object, velocity: Sequence[object] | FreeModuleElement) -> Expression:
    """Return the rate at which a velocity carries a field along, for one site.

    It sums `upwind(u, axis, v)` over the axes, the velocity times the slope of the field taken on the side the flow
    comes from, which keeps a moving front from rippling, such as `upwind(u, 0, 1.0) + upwind(u, 1, 2.0)` for a flow
    `(1, 2)`. A rate law subtracts it from the rate of the field. It carries a pollutant down a river, heat with the
    wind, and cars along a road.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a field.

        velocity:
            One entry of the velocity per dimension, numbers or expressions.

    Returns:
        advection:
            The advection term, to subtract from the rate of the field.

    See Also:
        divergence: Gives the net outflow of a flux.
        shifted: Reads a field at a distance from every site.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import advection
        >>> sorted(str(term) for term in advection(var('u'), [1.0, 2.0]).operands())
        ['upwind(u, 0, 1.0)', 'upwind(u, 1, 2.0)']
    """
    return sum((upwind(SR(expression), SR(axis), SR(item)) for axis, item in enumerate(velocity)), SR(0))

antisymmetric_part(tensor)

Return the antisymmetric part of a square matrix, (M - M^T) / 2.

It gives every entry half its difference with its mirror across the diagonal, such as [[0, a], [-a, 0]] for [[0, 2a], [0, 0]]. Of the matrix of derivatives of a velocity it keeps the spin and drops the stretching. It gives the vorticity of a fluid, the rotation of a solid, and the one-way couplings of a network.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
tensor Matrix

A square matrix of expressions.

required

Returns:

Name Type Description
antisymmetric Matrix

The antisymmetric matrix.

Raises:

Type Description
TensorShapeError

The value is not a square matrix.

See Also

symmetric_part: Keeps the symmetric part instead.

Examples:

>>> from sage.all__sagemath_symbolics import SR, matrix, var
>>> from skcomplex.core.components.laws.utils import antisymmetric_part
>>> antisymmetric_part(matrix(SR, [[0, 2 * var('a')], [0, 0]]))
[ 0  a]
[-a  0]
Source code in src/skcomplex/core/components/laws/utils/_tensors.py
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
def antisymmetric_part(tensor: Matrix) -> Matrix:
    """Return the antisymmetric part of a square matrix, `(M - M^T) / 2`.

    It gives every entry half its difference with its mirror across the diagonal, such as `[[0, a], [-a, 0]]` for
    `[[0, 2a], [0, 0]]`. Of the matrix of derivatives of a velocity it keeps the spin and drops the stretching. It gives
    the vorticity of a fluid, the rotation of a solid, and the one-way couplings of a network.

    Read more in the user guide, under Laws.

    Args:
        tensor:
            A square matrix of expressions.

    Returns:
        antisymmetric:
            The antisymmetric matrix.

    Raises:
        TensorShapeError:
            The value is not a square matrix.

    See Also:
        symmetric_part: Keeps the symmetric part instead.

    Examples:
        >>> from sage.all__sagemath_symbolics import SR, matrix, var
        >>> from skcomplex.core.components.laws.utils import antisymmetric_part
        >>> antisymmetric_part(matrix(SR, [[0, 2 * var('a')], [0, 0]]))
        [ 0  a]
        [-a  0]
    """
    checked = _check_matrix('antisymmetric_part', tensor)
    return (checked - checked.transpose()) / 2

bernoulli(name, p, temperature=None, hard=False)

Return 1 with a probability and 0 otherwise, drawn at every step.

A new value is drawn at every step, 1 with probability p, such as 1 - bernoulli('flip', q) that is 0 with probability q. With a temperature T, the JAX backend gives a smooth value close to the draw, sigmoid((logit p - logit u) / T) for the uniform value u of the step (Maddison et al. 2017), which tends to the exact draw as T tends to 0, so runs have gradients in p. Every other backend draws exactly. It decides whether a contact infects, whether a trader buys, and whether a spin flips.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the draw, a valid Python name.

required
p object

The probability of 1, a number or an expression of states and parameters.

required
temperature float | None

The positive temperature of the smooth value on JAX, or None for the exact draw.

None
hard bool

Whether the JAX value is the exact draw with the gradient of the smooth value.

False

Returns:

Name Type Description
draw Expression

The symbolic draw.

Raises:

Type Description
ValidationError

The name is not a valid Python name, the temperature is not positive, or hard is given without a temperature.

See Also

categorical: Draws one of several categories.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import bernoulli
>>> 1 - bernoulli('flip', var('q'))
-bernoulli_flip(q) + 1
Source code in src/skcomplex/core/components/laws/utils/_draws.py
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
def bernoulli(name: str, p: object, temperature: float | None = None, hard: bool = False) -> Expression:
    """Return 1 with a probability and 0 otherwise, drawn at every step.

    A new value is drawn at every step, 1 with probability `p`, such as `1 - bernoulli('flip', q)` that is 0 with
    probability `q`. With a temperature `T`, the JAX backend gives a smooth value close to the draw,
    `sigmoid((logit p - logit u) / T)` for the uniform value `u` of the step (Maddison et al. 2017), which tends to the
    exact draw as `T` tends to 0, so runs have gradients in `p`. Every other backend draws exactly. It decides whether a
    contact infects, whether a trader buys, and whether a spin flips.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the draw, a valid Python name.

        p:
            The probability of 1, a number or an expression of states and parameters.

        temperature:
            The positive temperature of the smooth value on JAX, or `None` for the exact draw.

        hard:
            Whether the JAX value is the exact draw with the gradient of the smooth value.

    Returns:
        draw:
            The symbolic draw.

    Raises:
        ValidationError:
            The name is not a valid Python name, the temperature is not positive, or `hard` is given without a
            temperature.

    See Also:
        categorical: Draws one of several categories.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import bernoulli
        >>> 1 - bernoulli('flip', var('q'))
        -bernoulli_flip(q) + 1
    """
    return _call('bernoulli', name, (p,), temperature=temperature, hard=hard)

bilinear(rate, outcomes, first, second=None, *, conserved=False)

Return the rate at which two densities meet and move between classes.

A density is a group with one element per class of a trait, holding how much of a population is in each class. When the first density f in class h meets the second density g in class k at the rate rate[h, k], the meeting adds to class i with the probability outcomes[h, k, i], so class i gains Σ_hk rate[h, k] outcomes[h, k, i] f_h g_k, such as bilinear(-0.5, None, f, g) for a loss of f at half the rate of meetings. With conserved=True the first density also loses what moves out of class h, so its total stays the same, and without a second density the form moves amounts between classes at a fixed rate. A RateLaw whose whole rate is the form runs as meetings, which an ODE solver integrates and KineticSolver samples. Traders exchange wealth when they meet, people shift their opinion after a talk, and particles stick together when they collide.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
rate object

The signed rate, a number or a parameter expression, or an array r[h, k] of them.

required
outcomes object

The array B[h, k, i] of the probabilities of the class in the target, numbers or parameter expressions that sum to one over i, or None for the class of the first density, which needs a target of its size. A conserved form needs the array, since the identity makes its gain and loss cancel.

required
first object

The symbol of the first density.

required
second object

The symbol of the second density, or None for a linear redistribution of a conserved form.

None
conserved bool

Whether the form also takes the matching loss from the first density, which is then the target, so df_i/dt = Σ_hk rate[h, k] outcomes[h, k, i] f_h g_k - f_i Σ_k rate[i, k] g_k.

False

Returns:

Name Type Description
form Expression

The unevaluated form, which the compiler turns into sums over the classes of the densities.

Raises:

Type Description
ValidationError

A conserved form has no outcome table, a form without a second density is not conserved, or a table has the wrong dimensions or a shape that disagrees with the other.

See Also

RateLaw: Takes the form as its rate. contraction: Sums a coupling tensor times the values of the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import bilinear
>>> f, g = var('f g')
>>> bilinear(-0.5, None, f, g).operator()
bilinear
Source code in src/skcomplex/core/components/laws/utils/_bilinear.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def bilinear(
    rate: object,
    outcomes: object,
    first: object,
    second: object = None,
    *,
    conserved: bool = False,
) -> Expression:
    """Return the rate at which two densities meet and move between classes.

    A density is a group with one element per class of a trait, holding how much of a population is in each class. When
    the first density `f` in class `h` meets the second density `g` in class `k` at the rate `rate[h, k]`, the meeting
    adds to class `i` with the probability `outcomes[h, k, i]`, so class `i` gains
    `Σ_hk rate[h, k] outcomes[h, k, i] f_h g_k`, such as `bilinear(-0.5, None, f, g)` for a loss of `f` at half the rate
    of meetings. With `conserved=True` the first density also loses what moves out of class `h`, so its total stays the
    same, and without a second density the form moves amounts between classes at a fixed rate. A `RateLaw` whose whole
    rate is the form runs as meetings, which an ODE solver integrates and `KineticSolver` samples. Traders exchange
    wealth when they meet, people shift their opinion after a talk, and particles stick together when they collide.

    Read more in the user guide, under Laws.

    Args:
        rate:
            The signed rate, a number or a parameter expression, or an array `r[h, k]` of them.

        outcomes:
            The array `B[h, k, i]` of the probabilities of the class in the target, numbers or parameter expressions
            that sum to one over `i`, or `None` for the class of the first density, which needs a target of its size. A
            conserved form needs the array, since the identity makes its gain and loss cancel.

        first:
            The symbol of the first density.

        second:
            The symbol of the second density, or `None` for a linear redistribution of a conserved form.

        conserved:
            Whether the form also takes the matching loss from the first density, which is then the target, so
            `df_i/dt = Σ_hk rate[h, k] outcomes[h, k, i] f_h g_k - f_i Σ_k rate[i, k] g_k`.

    Returns:
        form:
            The unevaluated form, which the compiler turns into sums over the classes of the densities.

    Raises:
        ValidationError:
            A conserved form has no outcome table, a form without a second density is not conserved, or a table has the
            wrong dimensions or a shape that disagrees with the other.

    See Also:
        RateLaw: Takes the form as its rate.
        contraction: Sums a coupling tensor times the values of the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import bilinear
        >>> f, g = var('f g')
        >>> bilinear(-0.5, None, f, g).operator()
        bilinear
    """
    if conserved and outcomes is None:
        error_msg = (
            f'The conserved bilinear form of {first} has no outcome table, but without one its gain and loss cancel. '
            'Give the outcome probabilities `B[h, k, i]`.'
        )
        raise ValidationError(error_msg)
    if second is None and not conserved:
        error_msg = (
            f'The bilinear form of {first} has no second density, which only a conserved form takes. Give the second '
            'density, or set `conserved=True`.'
        )
        raise ValidationError(error_msg)
    rates = _get_table('rate', rate, RATE_DIMENSIONS)
    table = None if outcomes is None else _get_table('outcomes', outcomes, OUTCOME_DIMENSIONS)
    if table is not None and rates.ndim and rates.shape != table.shape[:2]:
        error_msg = (
            f'The rate of the bilinear form has the shape {rates.shape}, but its outcomes have the shape '
            f'{table.shape[:2]} over the classes of the first and the second density.'
        )
        raise ValidationError(error_msg)
    operands = [SR(first), SR(second is not None), SR(first if second is None else second), SR(conserved)]
    for item in (rates, table):
        operands += [SR(-1)] if item is None else [SR(item.ndim), *(SR(size) for size in item.shape)]
        operands += [] if item is None else [SR(entry) for entry in item.ravel()]
    return BILINEAR(*operands)

categorical(name, weights, temperature=None, hard=False)

Return the index of a category drawn at every step.

A new index is drawn at every step, each category with a probability proportional to its weight, such as categorical('map', [1, 1, 2]) that gives 2 half the time. The index is the number of running totals c_k of the weights below u W, for the uniform value u of the step and the total weight W. With a temperature T, the JAX backend gives the smooth value Σ_k sigmoid((u - c_k / W) / T), so runs have gradients in the weights, and every other backend draws exactly. It picks the action of an agent, the strategy of a player, and the next word of a text.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the draw, a valid Python name.

required
weights Sequence[object]

The nonnegative weights of the categories 0 to len(weights) - 1, numbers or expressions of states and parameters.

required
temperature float | None

The positive temperature of the smooth value on JAX, or None for the exact draw.

None
hard bool

Whether the JAX value is the exact draw with the gradient of the smooth value.

False

Returns:

Name Type Description
draw Expression

The symbolic draw.

Raises:

Type Description
ValidationError

The name is not a valid Python name, there are no weights, the temperature is not positive, or hard is given without a temperature.

See Also

bernoulli: Draws 1 with a probability and 0 otherwise.

Examples:

>>> from skcomplex.core.components.laws.utils import categorical
>>> categorical('map', [1, 1, 2])
categorical_map(1, 1, 2)
Source code in src/skcomplex/core/components/laws/utils/_draws.py
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 categorical(
    name: str,
    weights: Sequence[object],
    temperature: float | None = None,
    hard: bool = False,
) -> Expression:
    """Return the index of a category drawn at every step.

    A new index is drawn at every step, each category with a probability proportional to its weight, such as
    `categorical('map', [1, 1, 2])` that gives 2 half the time. The index is the number of running totals `c_k` of the
    weights below `u W`, for the uniform value `u` of the step and the total weight `W`. With a temperature `T`, the JAX
    backend gives the smooth value `Σ_k sigmoid((u - c_k / W) / T)`, so runs have gradients in the weights, and every
    other backend draws exactly. It picks the action of an agent, the strategy of a player, and the next word of a text.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the draw, a valid Python name.

        weights:
            The nonnegative weights of the categories `0` to `len(weights) - 1`, numbers or expressions of states and
            parameters.

        temperature:
            The positive temperature of the smooth value on JAX, or `None` for the exact draw.

        hard:
            Whether the JAX value is the exact draw with the gradient of the smooth value.

    Returns:
        draw:
            The symbolic draw.

    Raises:
        ValidationError:
            The name is not a valid Python name, there are no weights, the temperature is not positive, or `hard` is
            given without a temperature.

    See Also:
        bernoulli: Draws 1 with a probability and 0 otherwise.

    Examples:
        >>> from skcomplex.core.components.laws.utils import categorical
        >>> categorical('map', [1, 1, 2])
        categorical_map(1, 1, 2)
    """
    if isinstance(weights, str) or not len(weights):
        error_msg = f'The categorical draw {name!r} needs a list of at least one weight, but got {weights!r}.'
        raise ValidationError(error_msg)
    return _call('categorical', name, tuple(weights), temperature=temperature, hard=hard)

circular_mean(angle, over=None, where=None, weights=None, by=None)

Return the mean direction of an angle over the members of a group.

It is arctan2(Σ_j sin a_j, Σ_j cos a_j), the direction of the sum of the unit vectors at the angles, or 0 when no member is selected, so 350 and 10 degrees average to 0 rather than 180. It gives the heading of a flock, the phase of a group of fireflies, and the mean wind direction.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
angle object

The angle of one member, in radians.

required
over object

The namespace of the group to reduce over, or None for the group the angle reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None
weights object

A constant matrix with one row per reading member and one column per reduced member, or None.

None
by str | None

The name of a state of the group, so every member reduces over the members that share its value of the state, or None for all members. It needs the namespace of the group as over.

None

Returns:

Name Type Description
reduction Expression

The symbolic circular mean, in [-pi, pi].

Raises:

Type Description
ValidationError

The group is not a namespace or a symbol, the weights are not a matrix, or by comes without the namespace of the group.

See Also

mean: Averages an expression that is not an angle.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import circular_mean
>>> circular_mean(var('theta'))
arctan2(total(sin(theta)), total(cos(theta)))
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def circular_mean(
    angle: object,
    over: object = None,
    where: object = None,
    weights: object = None,
    by: str | None = None,
) -> Expression:
    """Return the mean direction of an angle over the members of a group.

    It is `arctan2(Σ_j sin a_j, Σ_j cos a_j)`, the direction of the sum of the unit vectors at the angles, or 0 when no
    member is selected, so 350 and 10 degrees average to 0 rather than 180. It gives the heading of a flock, the phase
    of a group of fireflies, and the mean wind direction.

    Read more in the user guide, under Laws.

    Args:
        angle:
            The angle of one member, in radians.

        over:
            The namespace of the group to reduce over, or `None` for the group the angle reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

        weights:
            A constant matrix with one row per reading member and one column per reduced member, or `None`.

        by:
            The name of a state of the group, so every member reduces over the members that share its value of the
            state, or `None` for all members. It needs the namespace of the group as `over`.

    Returns:
        reduction:
            The symbolic circular mean, in `[-pi, pi]`.

    Raises:
        ValidationError:
            The group is not a namespace or a symbol, the weights are not a matrix, or `by` comes without the namespace
            of the group.

    See Also:
        mean: Averages an expression that is not an angle.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import circular_mean
        >>> circular_mean(var('theta'))
        arctan2(total(sin(theta)), total(cos(theta)))
    """
    sines = total(sin(SR(angle)), over, where, weights, by)
    cosines = total(cos(SR(angle)), over, where, weights, by)
    return arctan2(sines, cosines)

clip(x, low=None, high=None)

Return an expression limited to an interval.

It gives low where the expression is below it, high where it is above it, and the expression itself in between, such as 0, 0.5, and 1 for clip(x, 0, 1) at -2, 0.5, and 3. It keeps a concentration from turning negative, an order within the stock a firm holds, and a control signal within what a motor can do.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The expression to limit.

required
low object

The lower bound, or None for none.

None
high object

The upper bound, or None for none.

None

Returns:

Name Type Description
value Expression

The symbolic limited value.

See Also

sign: Gives the sign of an expression.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import clip
>>> x = var('x')
>>> [clip(x, 0, 1).subs(x=value) for value in (-2, 0.5, 3)]
[0, 0.5, 1]
Source code in src/skcomplex/core/components/laws/utils/_pointwise.py
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
def clip(x: object, low: object = None, high: object = None) -> Expression:
    """Return an expression limited to an interval.

    It gives `low` where the expression is below it, `high` where it is above it, and the expression itself in between,
    such as 0, 0.5, and 1 for `clip(x, 0, 1)` at -2, 0.5, and 3. It keeps a concentration from turning negative, an
    order within the stock a firm holds, and a control signal within what a motor can do.

    Read more in the user guide, under Laws.

    Args:
        x:
            The expression to limit.

        low:
            The lower bound, or `None` for none.

        high:
            The upper bound, or `None` for none.

    Returns:
        value:
            The symbolic limited value.

    See Also:
        sign: Gives the sign of an expression.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import clip
        >>> x = var('x')
        >>> [clip(x, 0, 1).subs(x=value) for value in (-2, 0.5, 3)]
        [0, 0.5, 1]
    """
    value = SR(x)
    if high is not None:
        value = where(SR(x) > high, high, value)
    if low is not None:
        value = where(SR(x) < low, low, value)
    return value

codifferential(expression)

Return the net flow of a state of a cell complex, one degree down.

It is (-1)^k star^-1 d^T star for a state of degree k, where d^T turns the differences of exterior_derivative around. On a lattice with unit spacings it gives every site the outflow minus the inflow of a state of the edges, such as codifferential(flow), and every edge the circulation of a state of the faces. Applied twice it gives 0 up to rounding, and applied to the differences of a state of the sites it gives the graph Laplacian. It gives the net current into the nodes of a circuit, the net trade of every country, and the divergence of a flow on a mesh.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a group on the edges or faces of a cell complex.

required

Returns:

Name Type Description
codifferential Expression

The call codifferential(expression).

See Also

exterior_derivative: Goes one degree up. hodge_star: Scales a state by the sizes of its cells.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import codifferential
>>> codifferential(var('flow'))
codifferential(flow)
Source code in src/skcomplex/core/components/laws/utils/_cells.py
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
def codifferential(expression: object) -> Expression:
    """Return the net flow of a state of a cell complex, one degree down.

    It is `(-1)^k star^-1 d^T star` for a state of degree `k`, where `d^T` turns the differences of
    `exterior_derivative` around. On a lattice with unit spacings it gives every site the outflow minus the inflow of a
    state of the edges, such as `codifferential(flow)`, and every edge the circulation of a state of the faces. Applied
    twice it gives 0 up to rounding, and applied to the differences of a state of the sites it gives the graph
    Laplacian. It gives the net current into the nodes of a circuit, the net trade of every country, and the divergence
    of a flow on a mesh.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a group on the edges or faces of a cell complex.

    Returns:
        codifferential:
            The call `codifferential(expression)`.

    See Also:
        exterior_derivative: Goes one degree up.
        hodge_star: Scales a state by the sizes of its cells.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import codifferential
        >>> codifferential(var('flow'))
        codifferential(flow)
    """
    return CODIFFERENTIAL(SR(expression))

collision_integral(density, kernel)

Return the rate at which collisions between pairs change a density of speeds.

It is the Boltzmann integral Q(f, f)(v) = ∫∫ B(|g|, cos t) (f(v') f(v'*) - f(v) f(v*)) ds dv* over the two velocity axes of the phase space of the density, with the relative speed |g| and the cosine cos t of the angle the collision turns by. The kernel B is called once with two real symbols for the speed and the cosine and must use Sage functions, such as lambda speed, cosine: 1 / (2 * pi) for Maxwell molecules, and the call keeps its expression. It relaxes a gas toward equilibrium, mixes the speeds of granular matter, and spreads the opinions of agents who meet in pairs.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
density object

The symbol of a density on a phase space with two interval velocity axes.

required
kernel Callable[[Expression, Expression], object]

The function B(speed, cosine) of the collision kernel, such as lambda speed, cosine: 1 / (2 * pi) for Maxwell molecules.

required

Returns:

Name Type Description
integral Expression

The unevaluated call of the integral, which the compiler computes with the fast spectral method.

See Also

bilinear: Gives the rate of meetings between classes of two densities.

Examples:

>>> from sage.all__sagemath_symbolics import pi, var
>>> from skcomplex.core.components.laws.utils import collision_integral
>>> collision_integral(var('f'), lambda speed, cosine: 1 / (2 * pi))
collision_integral(f, 1/2/pi)
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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 collision_integral(density: object, kernel: Callable[[Expression, Expression], object]) -> Expression:
    """Return the rate at which collisions between pairs change a density of speeds.

    It is the Boltzmann integral `Q(f, f)(v) = ∫∫ B(|g|, cos t) (f(v') f(v'*) - f(v) f(v*)) ds dv*` over the two
    velocity axes of the phase space of the density, with the relative speed `|g|` and the cosine `cos t` of the angle
    the collision turns by. The kernel `B` is called once with two real symbols for the speed and the cosine and must
    use Sage functions, such as `lambda speed, cosine: 1 / (2 * pi)` for Maxwell molecules, and the call keeps its
    expression. It relaxes a gas toward equilibrium, mixes the speeds of granular matter, and spreads the opinions of
    agents who meet in pairs.

    Read more in the user guide, under Laws.

    Args:
        density:
            The symbol of a density on a phase space with two interval velocity axes.

        kernel:
            The function `B(speed, cosine)` of the collision kernel, such as `lambda speed, cosine: 1 / (2 * pi)` for
            Maxwell molecules.

    Returns:
        integral:
            The unevaluated call of the integral, which the compiler computes with the fast spectral method.

    See Also:
        bilinear: Gives the rate of meetings between classes of two densities.

    Examples:
        >>> from sage.all__sagemath_symbolics import pi, var
        >>> from skcomplex.core.components.laws.utils import collision_integral
        >>> collision_integral(var('f'), lambda speed, cosine: 1 / (2 * pi))
        collision_integral(f, 1/2/pi)
    """
    return COLLISION_INTEGRAL(SR(density), SR(kernel(COLLISION_SPEED, COLLISION_COSINE)))

components(active, over=None, reduce='label')

Return the clusters of members joined by active links, as a value per member.

A link joins two neighbours of a group, and it is active where active is not 0, such as components(edges.open > 0, reduce='size') for the size of the cluster of open links each member is in. Inside active, namespace.other holds the values of the neighbour, namespace those of the member, and a group on the edges those of the edge. Two members share a cluster when a path of active links joins them, read in both directions, and a member without active links is a cluster of its own. It finds the spanning cluster of a porous rock, the outbreak cluster of an epidemic, and the groups of firms that a default can reach.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
active object

The value of one link, an expression of the values of namespace.other, namespace, and the edge between them, whose links are active where it is not 0.

required
over BaseNeighborhood | LayerSpec | None

The neighbourhood, or None for the neighbours of the network or lattice the group lives on.

None
reduce str

What to give every member. 'label' gives the smallest index of a member of its cluster, 'size' the number of members of its cluster, 'largest' the number of members of the largest cluster, and 'giant' gives 1 in the largest cluster and 0 elsewhere, taking the smallest label among clusters of equal size.

'label'

Returns:

Name Type Description
reduction Expression

The unevaluated reduction, one value per member.

Raises:

Type Description
ValidationError

The reduction or the neighbourhood is unknown.

See Also

neighbors: Reduces the values of the neighbours of every member. shortest_paths: Measures the shortest paths of the active links.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import components
>>> components(var('open') > 0, reduce='size')
components(open > 0, reduce='size')
Source code in src/skcomplex/core/components/laws/utils/_components.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def components(
    active: object,
    over: BaseNeighborhood | LayerSpec | None = None,
    reduce: str = 'label',
) -> Expression:
    """Return the clusters of members joined by active links, as a value per member.

    A link joins two neighbours of a group, and it is active where `active` is not 0, such as
    `components(edges.open > 0, reduce='size')` for the size of the cluster of open links each member is in. Inside
    `active`, `namespace.other` holds the values of the neighbour, `namespace` those of the member, and a group on the
    edges those of the edge. Two members share a cluster when a path of active links joins them, read in both
    directions, and a member without active links is a cluster of its own. It finds the spanning cluster of a porous
    rock, the outbreak cluster of an epidemic, and the groups of firms that a default can reach.

    Read more in the user guide, under Laws.

    Args:
        active:
            The value of one link, an expression of the values of `namespace.other`, `namespace`, and the edge between
            them, whose links are active where it is not 0.

        over:
            The neighbourhood, or `None` for the neighbours of the network or lattice the group lives on.

        reduce:
            What to give every member. `'label'` gives the smallest index of a member of its cluster, `'size'` the
            number of members of its cluster, `'largest'` the number of members of the largest cluster, and `'giant'`
            gives 1 in the largest cluster and 0 elsewhere, taking the smallest label among clusters of equal size.

    Returns:
        reduction:
            The unevaluated reduction, one value per member.

    Raises:
        ValidationError:
            The reduction or the neighbourhood is unknown.

    See Also:
        neighbors: Reduces the values of the neighbours of every member.
        shortest_paths: Measures the shortest paths of the active links.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import components
        >>> components(var('open') > 0, reduce='size')
        components(open > 0, reduce='size')
    """
    if reduce not in ComponentReductionKind:
        error_msg = f'Unknown components reduction {reduce!r}. Use one of {", ".join(ComponentReductionKind)}.'
        raise ValidationError(error_msg)
    return COMPONENTS(SR(active), _neighborhood_symbol(over), tuple(ComponentReductionKind).index(reduce))

contraction(tensor, *expressions)

Return the sum of a coupling tensor times values of the members of a group.

It gives every member i the sum Σ_jk T_ijk a_j b_k, with one expression per index after the first, such as contraction(T, x, x) for the sum of T_ijk x_j x_k over all pairs of members j and k. The tensor is a parameter of an interaction, an array with one axis per index, whose first index runs over the members that read the sum. Inside the sum the values of each expression are those of the member of its index. It couples triples of neurons in a network with higher order links, of species in a community, and of spins in a model with three body terms.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
tensor object

The symbol of the array parameter, with k axes.

required
*expressions object

The k - 1 expressions of one member, one per index after the first.

()

Returns:

Name Type Description
contraction Expression

The unevaluated contraction, one value per reading member, which every backend lowers.

Raises:

Type Description
ValidationError

The tensor is not a symbol, or no expression is given.

See Also

bilinear: Sums a matrix times the values of two members. neighbors: Reduces the values of the neighbours of every member.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import contraction
>>> T, x = var('T x')
>>> contraction(T, x, x)
contraction(T, x, x)
Source code in src/skcomplex/core/components/laws/utils/_contractions.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def contraction(tensor: object, *expressions: object) -> Expression:
    """Return the sum of a coupling tensor times values of the members of a group.

    It gives every member `i` the sum `Σ_jk T_ijk a_j b_k`, with one expression per index after the first, such as
    `contraction(T, x, x)` for the sum of `T_ijk x_j x_k` over all pairs of members `j` and `k`. The tensor is a
    parameter of an interaction, an array with one axis per index, whose first index runs over the members that read the
    sum. Inside the sum the values of each expression are those of the member of its index. It couples triples of
    neurons in a network with higher order links, of species in a community, and of spins in a model with three body
    terms.

    Read more in the user guide, under Laws.

    Args:
        tensor:
            The symbol of the array parameter, with `k` axes.

        *expressions:
            The `k - 1` expressions of one member, one per index after the first.

    Returns:
        contraction:
            The unevaluated contraction, one value per reading member, which every backend lowers.

    Raises:
        ValidationError:
            The tensor is not a symbol, or no expression is given.

    See Also:
        bilinear: Sums a matrix times the values of two members.
        neighbors: Reduces the values of the neighbours of every member.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import contraction
        >>> T, x = var('T x')
        >>> contraction(T, x, x)
        contraction(T, x, x)
    """
    if not isinstance(tensor, Expression) or not tensor.is_symbol():
        error_msg = f'The tensor of a contraction must be the symbol of an array parameter, but it is {tensor!r}.'
        raise ValidationError(error_msg)
    if len(expressions) < MIN_FACTORS:
        error_msg = f'The contraction of {tensor} needs one expression per index after the first, but none is given.'
        raise ValidationError(error_msg)
    return CONTRACTION(tensor, *(SR(item) for item in expressions))

convolve(expression, kernel, radius=None)

Return the sum of a field around every site, weighted by a kernel of distance.

At every site it sums the field at every other site times the kernel at their distance and the volume of a cell, such as convolve(u, exp(-displacement(0) ** 2), 3) for a bell curve that ends at distance 3. It gives the seeds that land around a plant, the input a neuron gets from its neighbours, and the blur of an image.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a field on a lattice.

required
kernel object

An expression of the symbols displacement(axis) and of parameters.

required
radius object

The distance beyond which the kernel is zero, or None for a kernel over the whole lattice.

None

Returns:

Name Type Description
convolution Expression

The call convolve(expression, kernel, radius).

See Also

displacement: Gives the symbols the kernel is written in. integral_transform: Integrates against a kernel of two points.

Examples:

>>> from sage.all__sagemath_symbolics import var, exp
>>> from skcomplex.core.components.laws.utils import convolve, displacement
>>> convolve(var('u'), exp(-displacement(0) ** 2), 3)
convolve(u, e^(-displacement_0^2), 3)
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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
def convolve(expression: object, kernel: object, radius: object = None) -> Expression:
    """Return the sum of a field around every site, weighted by a kernel of distance.

    At every site it sums the field at every other site times the kernel at their distance and the volume of a cell,
    such as `convolve(u, exp(-displacement(0) ** 2), 3)` for a bell curve that ends at distance 3. It gives the seeds
    that land around a plant, the input a neuron gets from its neighbours, and the blur of an image.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a field on a lattice.

        kernel:
            An expression of the symbols `displacement(axis)` and of parameters.

        radius:
            The distance beyond which the kernel is zero, or `None` for a kernel over the whole lattice.

    Returns:
        convolution:
            The call `convolve(expression, kernel, radius)`.

    See Also:
        displacement: Gives the symbols the kernel is written in.
        integral_transform: Integrates against a kernel of two points.

    Examples:
        >>> from sage.all__sagemath_symbolics import var, exp
        >>> from skcomplex.core.components.laws.utils import convolve, displacement
        >>> convolve(var('u'), exp(-displacement(0) ** 2), 3)
        convolve(u, e^(-displacement_0^2), 3)
    """
    return CONVOLVE(SR(expression), SR(kernel), oo if radius is None else SR(radius))

coordinate(name)

Return the coordinate along a named axis of the point a law updates.

A phase space adds axes beyond position, such as speed, size, or age, and a law of a field on it reads the coordinate of its point along such an axis, such as coordinate('v') ** 2 for the square of the speed. It weighs the energy of particles by speed, the growth of cells by size, and the death rate of people by age.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the axis.

required

Returns:

Name Type Description
coordinate Expression

The symbol of the coordinate, a real number at every point of the space.

Raises:

Type Description
ValidationError

The name is not a valid Python name.

See Also

reduce_axes: Integrates over some axes at every position. integration_variable: Gives the point an integral runs over.

Examples:

>>> from skcomplex.core.components.laws.utils import coordinate
>>> coordinate('v') ** 2
_coordinate_v^2
Source code in src/skcomplex/core/components/laws/utils/_phase.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def coordinate(name: str) -> Expression:
    """Return the coordinate along a named axis of the point a law updates.

    A phase space adds axes beyond position, such as speed, size, or age, and a law of a field on it reads the
    coordinate of its point along such an axis, such as `coordinate('v') ** 2` for the square of the speed. It weighs
    the energy of particles by speed, the growth of cells by size, and the death rate of people by age.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the axis.

    Returns:
        coordinate:
            The symbol of the coordinate, a real number at every point of the space.

    Raises:
        ValidationError:
            The name is not a valid Python name.

    See Also:
        reduce_axes: Integrates over some axes at every position.
        integration_variable: Gives the point an integral runs over.

    Examples:
        >>> from skcomplex.core.components.laws.utils import coordinate
        >>> coordinate('v') ** 2
        _coordinate_v^2
    """
    if not isinstance(name, str) or not name.isidentifier():
        error_msg = f'The name of an axis must be a valid Python name, such as `v`, but it is {name!r}.'
        raise ValidationError(error_msg)
    return SR.var(f'{COORDINATE_PREFIX}{name}', domain='real')

count(over=None, where=None, by=None)

Return the number of members of a group a condition selects, or of all members.

It counts the members that meet where, such as count(where=x > 0.5), and with by only those that share the value of a state with the member that reads the count, such as the members in the same cell. It gives the number of infected people, of buyers at a price, and of birds in a patch.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
over object

The namespace of the group to count, or None for the group the condition reads, or else the group of the law.

None
where object

A condition on the counted member, or None for all members.

None
by str | None

The name of a state of the group, so every member reduces over the members that share its value of the state, or None for all members. It needs the namespace of the group as over.

None

Returns:

Name Type Description
reduction Expression

The unevaluated count.

Raises:

Type Description
ValidationError

The group is not a namespace or a symbol, or by comes without the namespace of the group.

See Also

total: Sums an expression over the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import count
>>> count(where=var('x') > 0.5)
count(where=x > 0.5)
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def count(over: object = None, where: object = None, by: str | None = None) -> Expression:
    """Return the number of members of a group a condition selects, or of all members.

    It counts the members that meet `where`, such as `count(where=x > 0.5)`, and with `by` only those that share the
    value of a state with the member that reads the count, such as the members in the same cell. It gives the number of
    infected people, of buyers at a price, and of birds in a patch.

    Read more in the user guide, under Laws.

    Args:
        over:
            The namespace of the group to count, or `None` for the group the condition reads, or else the group of the
            law.

        where:
            A condition on the counted member, or `None` for all members.

        by:
            The name of a state of the group, so every member reduces over the members that share its value of the
            state, or `None` for all members. It needs the namespace of the group as `over`.

    Returns:
        reduction:
            The unevaluated count.

    Raises:
        ValidationError:
            The group is not a namespace or a symbol, or `by` comes without the namespace of the group.

    See Also:
        total: Sums an expression over the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import count
        >>> count(where=var('x') > 0.5)
        count(where=x > 0.5)
    """
    return _reduce('count', 1, over, where, None, by=by)

cumulative_integral(expression, axis, *, reverse=False)

Return the running integral of an expression along one axis of a lattice.

At every site it sums the cells from the start of the axis to the site, or from the site to the end with reverse=True, counting half of the cell of the site itself and weighting every cell by its width and its volume, such as cumulative_integral(f, 1, reverse=True) for the amount above every size along axis 1. It gives the mass of all larger particles, the number of older people in a population, and the wealth of the richer households.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states of a field on a lattice.

required
axis int

The axis of the lattice to integrate along, such as an axis of a phase space after its position axes.

required
reverse bool

Whether to integrate from every site to the end of the axis rather than from the start to the site.

False

Returns:

Name Type Description
integral Expression

The call cumulative_integral(expression, axis, reverse).

Raises:

Type Description
ValidationError

The axis is not a whole number of 0 or more.

See Also

integral_transform: Integrates over some axes against a kernel.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import cumulative_integral
>>> cumulative_integral(var('f'), 1, reverse=True)
cumulative_integral(f, 1, 1)
Source code in src/skcomplex/core/components/laws/utils/_integrals.py
 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
def cumulative_integral(expression: object, axis: int, *, reverse: bool = False) -> Expression:
    """Return the running integral of an expression along one axis of a lattice.

    At every site it sums the cells from the start of the axis to the site, or from the site to the end with
    `reverse=True`, counting half of the cell of the site itself and weighting every cell by its width and its volume,
    such as `cumulative_integral(f, 1, reverse=True)` for the amount above every size along axis 1. It gives the mass of
    all larger particles, the number of older people in a population, and the wealth of the richer households.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states of a field on a lattice.

        axis:
            The axis of the lattice to integrate along, such as an axis of a phase space after its position axes.

        reverse:
            Whether to integrate from every site to the end of the axis rather than from the start to the site.

    Returns:
        integral:
            The call `cumulative_integral(expression, axis, reverse)`.

    Raises:
        ValidationError:
            The axis is not a whole number of 0 or more.

    See Also:
        integral_transform: Integrates over some axes against a kernel.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import cumulative_integral
        >>> cumulative_integral(var('f'), 1, reverse=True)
        cumulative_integral(f, 1, 1)
    """
    if isinstance(axis, bool) or not isinstance(axis, int) or axis < 0:
        error_msg = f'The axis of a cumulative integral must be a whole number of 0 or more, but it is {axis!r}.'
        raise ValidationError(error_msg)
    return CUMULATIVE_INTEGRAL(SR(expression), SR(axis), SR(int(reverse)))

displacement(axis)

Return the symbol of the distance along an axis, for a convolution kernel.

A kernel of convolve is written in these symbols, such as exp(-displacement(0) ** 2) for a bell curve of the distance along axis 0. It shapes how far seeds disperse, how far neurons reach, and how a blur spreads a pixel.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
axis int

The axis of the lattice.

required

Returns:

Name Type Description
displacement Expression

The real symbol displacement_<axis>.

See Also

convolve: Sums a field against a kernel of these symbols.

Examples:

>>> from skcomplex.core.components.laws.utils import displacement
>>> displacement(0) ** 2
displacement_0^2
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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
def displacement(axis: int) -> Expression:
    """Return the symbol of the distance along an axis, for a convolution kernel.

    A kernel of `convolve` is written in these symbols, such as `exp(-displacement(0) ** 2)` for a bell curve of the
    distance along axis 0. It shapes how far seeds disperse, how far neurons reach, and how a blur spreads a pixel.

    Read more in the user guide, under Laws.

    Args:
        axis:
            The axis of the lattice.

    Returns:
        displacement:
            The real symbol `displacement_<axis>`.

    See Also:
        convolve: Sums a field against a kernel of these symbols.

    Examples:
        >>> from skcomplex.core.components.laws.utils import displacement
        >>> displacement(0) ** 2
        displacement_0^2
    """
    return SR.var(f'displacement_{axis}', domain='real')

distribute_operators(expression)

Return an expression with the linear operators of fields applied term by term.

Every linear operator, such as laplacian or partial, is split over the terms of a sum and has its number factors moved outside, so laplacian(-a) + laplacian(a) becomes -laplacian(a) + laplacian(a), which is 0. The compiler reads it to find terms that cancel and to build one matrix per operator and symbol. It tidies the diffusion of heat, the spread of a pollutant, and the waves of a membrane.

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

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a field.

required

Returns:

Name Type Description
expression Expression

The same field, in which every operator reads a product of symbols, such as laplacian(-a) as -laplacian(a).

See Also

laplacian: One of the operators it splits.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import distribute_operators, laplacian
>>> a = var('a')
>>> distribute_operators(laplacian(-a) + laplacian(a))
0
Source code in src/skcomplex/core/components/laws/utils/_tensors.py
 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
def distribute_operators(expression: object) -> Expression:
    """Return an expression with the linear operators of fields applied term by term.

    Every linear operator, such as `laplacian` or `partial`, is split over the terms of a sum and has its number factors
    moved outside, so `laplacian(-a) + laplacian(a)` becomes `-laplacian(a) + laplacian(a)`, which is 0. The compiler
    reads it to find terms that cancel and to build one matrix per operator and symbol. It tidies the diffusion of heat,
    the spread of a pollutant, and the waves of a membrane.

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

    Args:
        expression:
            An expression of the states and parameters of a field.

    Returns:
        expression:
            The same field, in which every operator reads a product of symbols, such as `laplacian(-a)` as
            `-laplacian(a)`.

    See Also:
        laplacian: One of the operators it splits.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import distribute_operators, laplacian
        >>> a = var('a')
        >>> distribute_operators(laplacian(-a) + laplacian(a))
        0
    """
    item = SR(expression)
    operator = item.operator()
    if operator is None:
        return item
    operands = [distribute_operators(operand) for operand in item.operands()]
    return _distribute_call(item, operands) if _is_linear_call(item) else operator(*operands)

distributed_delay(value, time, order=1, *, conserved=True)

Return a value delayed through a chain of hidden stocks.

The delay is order hidden stocks in a row, each holding the value for time / order on average. A conserved delay passes its input on like goods in transit, so its output is the outflow of the last stock and a pulse comes out spread over time with the mean time. A delay that is not conserved smooths its input, each stock moving toward the one before it at gap / (time / order), such as distributed_delay(sales, 2, conserved=False) for a smoothed forecast of sales. These are the DELAY1, DELAY3, and SMOOTH functions of system dynamics. It delays orders in a supply chain, trainees in a hiring pipeline, and the maturation of cells.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
value object

The symbolic input.

required
time object

The mean delay time, a positive number or an expression of parameters.

required
order int

The number of hidden stocks.

1
conserved bool

Whether the delay passes its input on whole, as goods in transit, or smooths it, as a forecast.

True

Returns:

Name Type Description
output Expression

The symbolic output.

Raises:

Type Description
ValueError

The order is not a positive whole number, or the delay time is a number that is not positive.

See Also

fractional: Gives a state a memory of its whole past.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import distributed_delay
>>> distributed_delay(var('orders'), 4, order=3)
material_delay3(orders, 4)
Source code in src/skcomplex/core/components/laws/utils/_delays.py
 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
def distributed_delay(value: object, time: object, order: int = 1, *, conserved: bool = True) -> Expression:
    """Return a value delayed through a chain of hidden stocks.

    The delay is `order` hidden stocks in a row, each holding the value for `time / order` on average. A conserved delay
    passes its input on like goods in transit, so its output is the outflow of the last stock and a pulse comes out
    spread over time with the mean `time`. A delay that is not conserved smooths its input, each stock moving toward the
    one before it at `gap / (time / order)`, such as `distributed_delay(sales, 2, conserved=False)` for a smoothed
    forecast of sales. These are the `DELAY1`, `DELAY3`, and `SMOOTH` functions of system dynamics. It delays orders in
    a supply chain, trainees in a hiring pipeline, and the maturation of cells.

    Read more in the user guide, under Laws.

    Args:
        value:
            The symbolic input.

        time:
            The mean delay time, a positive number or an expression of parameters.

        order:
            The number of hidden stocks.

        conserved:
            Whether the delay passes its input on whole, as goods in transit, or smooths it, as a forecast.

    Returns:
        output:
            The symbolic output.

    Raises:
        ValueError:
            The order is not a positive whole number, or the delay time is a number that is not positive.

    See Also:
        fractional: Gives a state a memory of its whole past.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import distributed_delay
        >>> distributed_delay(var('orders'), 4, order=3)
        material_delay3(orders, 4)
    """
    if isinstance(order, bool) or not isinstance(order, int) or order < 1:
        error_msg = f'The order of a distributed delay must be a positive whole number, but it is {order!r}.'
        raise ValueError(error_msg)
    name = f'{"material" if conserved else "smoothing"}_delay{order}'
    if SR(time).is_numeric() and float(SR(time)) <= 0:
        error_msg = f'The delay time of a distributed delay must be positive, but it is {time}.'
        raise ValueError(error_msg)
    if name not in DELAY_FUNCTIONS:
        DELAY_FUNCTIONS[name] = _DelayFunction(name, nargs=2)
    return DELAY_FUNCTIONS[name](value, time)

divergence(components)

Return the divergence of a vector field, the net outflow at every site.

It sums the derivative of entry i along axis i, such as partial(u, 0) + partial(2*u, 1) for [u, 2 * u]. The rate of a density is minus the divergence of its flux, so what leaves a site arrives at its neighbours. It moves heat through a plate, nutrients through a tissue, and traffic along a road.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
components Sequence[object] | FreeModuleElement

One expression per dimension, such as a flux.

required

Returns:

Name Type Description
divergence Expression

The divergence.

See Also

gradient: Gives the derivative along every axis. advection: Moves a field with a velocity.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import divergence
>>> u = var('u')
>>> sorted(str(term) for term in divergence([u, 2 * u]).operands())
['partial(2*u, 1)', 'partial(u, 0)']
Source code in src/skcomplex/core/components/laws/utils/_operators.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
def divergence(components: Sequence[object] | FreeModuleElement) -> Expression:
    """Return the divergence of a vector field, the net outflow at every site.

    It sums the derivative of entry `i` along axis `i`, such as `partial(u, 0) + partial(2*u, 1)` for `[u, 2 * u]`. The
    rate of a density is minus the divergence of its flux, so what leaves a site arrives at its neighbours. It moves
    heat through a plate, nutrients through a tissue, and traffic along a road.

    Read more in the user guide, under Laws.

    Args:
        components:
            One expression per dimension, such as a flux.

    Returns:
        divergence:
            The divergence.

    See Also:
        gradient: Gives the derivative along every axis.
        advection: Moves a field with a velocity.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import divergence
        >>> u = var('u')
        >>> sorted(str(term) for term in divergence([u, 2 * u]).operands())
        ['partial(2*u, 1)', 'partial(u, 0)']
    """
    return sum((partial(SR(item), SR(axis)) for axis, item in enumerate(components)), SR(0))

draw(name, distribution, **parameters)

Return a value drawn from a distribution of scipy.stats.

A new value is drawn at every step or renewal, such as draw('wait', 'pareto', b=alpha, scale=2) for a waiting time with a heavy tail. The compiler checks that scipy.stats has the distribution and that the keywords are its shape parameters, loc, or scale, and it samples with the rvs method of the distribution and the random numbers of the run. It gives the sizes of firms, the waiting times between trades, and the jumps of a foraging animal.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the draw, a valid Python name.

required
distribution str

The name of a distribution of scipy.stats, such as 'pareto', 'lomax', or 'levy_stable'.

required
**parameters object

The shape parameters, loc, and scale of the distribution, numbers or expressions of states and parameters.

{}

Returns:

Name Type Description
draw Expression

The symbolic draw.

Raises:

Type Description
ValidationError

The name is not a valid Python name, or the distribution is not given by its name.

See Also

uniform: Draws uniformly between two bounds. normal: Draws from a normal distribution.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import draw
>>> draw('wait', 'pareto', b=var('alpha'), scale=2)
pareto_wait_b_scale(alpha, 2)
Source code in src/skcomplex/core/components/laws/utils/_draws.py
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
def draw(name: str, distribution: str, **parameters: object) -> Expression:
    """Return a value drawn from a distribution of `scipy.stats`.

    A new value is drawn at every step or renewal, such as `draw('wait', 'pareto', b=alpha, scale=2)` for a waiting time
    with a heavy tail. The compiler checks that `scipy.stats` has the distribution and that the keywords are its shape
    parameters, `loc`, or `scale`, and it samples with the `rvs` method of the distribution and the random numbers of
    the run. It gives the sizes of firms, the waiting times between trades, and the jumps of a foraging animal.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the draw, a valid Python name.

        distribution:
            The name of a distribution of `scipy.stats`, such as `'pareto'`, `'lomax'`, or `'levy_stable'`.

        **parameters:
            The shape parameters, `loc`, and `scale` of the distribution, numbers or expressions of states and
            parameters.

    Returns:
        draw:
            The symbolic draw.

    Raises:
        ValidationError:
            The name is not a valid Python name, or the distribution is not given by its name.

    See Also:
        uniform: Draws uniformly between two bounds.
        normal: Draws from a normal distribution.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import draw
        >>> draw('wait', 'pareto', b=var('alpha'), scale=2)
        pareto_wait_b_scale(alpha, 2)
    """
    if not isinstance(distribution, str):
        error_msg = (
            f"The draw {name!r} takes the name of a distribution of scipy.stats, such as 'pareto', not "
            f'{distribution!r}.'
        )
        raise ValidationError(error_msg)
    return _call('draw', name, tuple(parameters.values()), distribution, tuple(parameters))

exterior_derivative(expression)

Return the differences of a state of a cell complex, one degree up.

The degree of a state is where its group lives, 0 on sites, 1 on edges, and 2 on faces, which a group holds as hyperedges. On a state of the sites it gives every edge the value at its head minus the value at its tail, and on a state of the edges it gives every face the sum around it, each edge signed by its direction, so applying it twice gives exactly 0. Inside a reduction over CofaceNeighborhood it is the signed sum around the one face, such as exterior_derivative(sin(theta)) for the differences of phases along every edge. It gives the voltage across the wires of a circuit, the pressure drop along a pipe network, and the gradient of a field on a mesh.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a group on the cells of a cell complex.

required

Returns:

Name Type Description
derivative Expression

The call exterior_derivative(expression).

See Also

codifferential: Goes one degree down. hodge_star: Scales a state by the sizes of its cells.

Examples:

>>> from sage.all__sagemath_symbolics import sin, var
>>> from skcomplex.core.components.laws.utils import exterior_derivative
>>> exterior_derivative(sin(var('theta')))
exterior_derivative(sin(theta))
Source code in src/skcomplex/core/components/laws/utils/_cells.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def exterior_derivative(expression: object) -> Expression:
    """Return the differences of a state of a cell complex, one degree up.

    The degree of a state is where its group lives, 0 on sites, 1 on edges, and 2 on faces, which a group holds as
    hyperedges. On a state of the sites it gives every edge the value at its head minus the value at its tail, and on a
    state of the edges it gives every face the sum around it, each edge signed by its direction, so applying it twice
    gives exactly 0. Inside a reduction over `CofaceNeighborhood` it is the signed sum around the one face, such as
    `exterior_derivative(sin(theta))` for the differences of phases along every edge. It gives the voltage across the
    wires of a circuit, the pressure drop along a pipe network, and the gradient of a field on a mesh.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a group on the cells of a cell complex.

    Returns:
        derivative:
            The call `exterior_derivative(expression)`.

    See Also:
        codifferential: Goes one degree down.
        hodge_star: Scales a state by the sizes of its cells.

    Examples:
        >>> from sage.all__sagemath_symbolics import sin, var
        >>> from skcomplex.core.components.laws.utils import exterior_derivative
        >>> exterior_derivative(sin(var('theta')))
        exterior_derivative(sin(theta))
    """
    return EXTERIOR_DERIVATIVE(SR(expression))

fractional(x, alpha)

Return the derivative of a fractional order of a value, for a rate law.

The Caputo derivative D^alpha x of an order 0 < alpha < 1 weighs the whole past of the value, so a value it moves remembers its history. RateLaw(fractional(x, 0.5), -k * x) states D^0.5 x = -k x, a decay slower than any exponential, as the Mittag-Leffler function E_alpha(-k t^alpha), and the order 1 is the ordinary first derivative. It models charges that relax in a dielectric, stress in a material that flows slowly, and drugs held in tissue.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The state, as the interaction reads it, such as s.target.x.

required
alpha float

The order of the derivative, a number in (0, 1].

required

Returns:

Name Type Description
derivative Expression

The unevaluated derivative, the target of a RateLaw.

Raises:

Type Description
ValidationError

The order is not a number in (0, 1], or x is not a state.

See Also

RateLaw: Takes the derivative as its target. distributed_delay: Delays a value through hidden stocks.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import RateLaw
>>> from skcomplex.core.components.laws.utils import fractional
>>> x, k = var('x k')
>>> RateLaw(fractional(x, 0.5), -k * x).target
fractional(x, 0.5)
Source code in src/skcomplex/core/components/laws/utils/_fractional.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
def fractional(x: object, alpha: float) -> Expression:
    """Return the derivative of a fractional order of a value, for a rate law.

    The Caputo derivative `D^alpha x` of an order `0 < alpha < 1` weighs the whole past of the value, so a value it
    moves remembers its history. `RateLaw(fractional(x, 0.5), -k * x)` states `D^0.5 x = -k x`, a decay slower than any
    exponential, as the Mittag-Leffler function `E_alpha(-k t^alpha)`, and the order 1 is the ordinary first derivative.
    It models charges that relax in a dielectric, stress in a material that flows slowly, and drugs held in tissue.

    Read more in the user guide, under Laws.

    Args:
        x:
            The state, as the interaction reads it, such as `s.target.x`.

        alpha:
            The order of the derivative, a number in `(0, 1]`.

    Returns:
        derivative:
            The unevaluated derivative, the target of a `RateLaw`.

    Raises:
        ValidationError:
            The order is not a number in `(0, 1]`, or `x` is not a state.

    See Also:
        RateLaw: Takes the derivative as its target.
        distributed_delay: Delays a value through hidden stocks.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws import RateLaw
        >>> from skcomplex.core.components.laws.utils import fractional
        >>> x, k = var('x k')
        >>> RateLaw(fractional(x, 0.5), -k * x).target
        fractional(x, 0.5)
    """
    order = SR(alpha)
    if not order.is_numeric() or not order.is_real() or not 0 < float(order) <= 1:
        error_msg = (
            f'The order of a fractional derivative is a number in (0, 1], but got {alpha!r}. Give an order such as '
            '`fractional(x, 0.5)`.'
        )
        raise ValidationError(error_msg)
    state = SR(x)
    applied = isinstance(state.operator(), SymbolicFunction) and len(state.operands()) == 1
    if not state.is_symbol() and not applied:
        error_msg = (
            f'A fractional derivative is taken of a state, such as `fractional(s.target.x, 0.5)`, but got {x}. '
            'Move the other terms to the rate.'
        )
        raise ValidationError(error_msg)
    return FRACTIONAL(state, order)

gradient(expression, n_dim=2)

Return the gradient of a field, its derivative along every axis of a lattice.

It gives one partial(expression, axis) per axis, such as (partial(u, 0), partial(u, 1)) for a field u in a plane, which the compiler turns into differences between neighbouring sites. It gives the slope of a landscape, the pull of a chemical on cells that follow it, and the force of a pressure on a fluid.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a field.

required
n_dim int

The number of dimensions of the lattice.

2

Returns:

Name Type Description
gradient FreeModuleElement

One derivative per dimension.

See Also

divergence: Sums the derivatives of a vector field. laplacian: Gives the divergence of the gradient.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import gradient
>>> gradient(var('u'))
(partial(u, 0), partial(u, 1))
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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
def gradient(expression: object, n_dim: int = 2) -> FreeModuleElement:
    """Return the gradient of a field, its derivative along every axis of a lattice.

    It gives one `partial(expression, axis)` per axis, such as `(partial(u, 0), partial(u, 1))` for a field `u` in a
    plane, which the compiler turns into differences between neighbouring sites. It gives the slope of a landscape, the
    pull of a chemical on cells that follow it, and the force of a pressure on a fluid.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a field.

        n_dim:
            The number of dimensions of the lattice.

    Returns:
        gradient:
            One derivative per dimension.

    See Also:
        divergence: Sums the derivatives of a vector field.
        laplacian: Gives the divergence of the gradient.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import gradient
        >>> gradient(var('u'))
        (partial(u, 0), partial(u, 1))
    """
    return vector(SR, [partial(SR(expression), SR(axis)) for axis in range(n_dim)])

has_operator(expression)

Check whether an expression holds a local operator.

An expression that holds a local operator is an operator of a quantum system rather than a number, such as 2 * local_operator(q, 'z'), while J alone is a number. The compiler reads it to tell a Hamiltonian from an ordinary rate. It sorts the terms of a spin chain, a cavity, and a register of qubits.

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

Parameters:

Name Type Description Default
expression object

A Sage expression, or any other value.

required

Returns:

Name Type Description
has_operator bool

Whether a local operator appears in the expression.

See Also

local_operator: Builds the operators it looks for.

Examples:

>>> from sage.all__sagemath_symbolics import SR, var
>>> from skcomplex.core.components.laws.utils import local_operator
>>> from skcomplex.core.components.laws.utils._local_operators import has_operator
>>> has_operator(2 * local_operator(SR.symbol('q'), 'z')), has_operator(var('J'))
(True, False)
Source code in src/skcomplex/core/components/laws/utils/_local_operators.py
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
def has_operator(expression: object) -> bool:
    """Check whether an expression holds a local operator.

    An expression that holds a local operator is an operator of a quantum system rather than a number, such as
    `2 * local_operator(q, 'z')`, while `J` alone is a number. The compiler reads it to tell a Hamiltonian from an
    ordinary rate. It sorts the terms of a spin chain, a cavity, and a register of qubits.

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

    Args:
        expression:
            A Sage expression, or any other value.

    Returns:
        has_operator:
            Whether a local operator appears in the expression.

    See Also:
        local_operator: Builds the operators it looks for.

    Examples:
        >>> from sage.all__sagemath_symbolics import SR, var
        >>> from skcomplex.core.components.laws.utils import local_operator
        >>> from skcomplex.core.components.laws.utils._local_operators import has_operator
        >>> has_operator(2 * local_operator(SR.symbol('q'), 'z')), has_operator(var('J'))
        (True, False)
    """
    return isinstance(expression, Expression) and expression.has(LOCAL_OPERATOR(SR.wild(0), SR.wild(1)))

hill(x, half, n=1)

Return the Hill function x^n / (half^n + x^n), which rises from 0 to 1.

It is one half at x = half, such as hill(x, 2, 3) that gives x^3 / (x^3 + 8), and a larger n makes the rise steeper, close to a switch. The order n = 1 gives the saturating function x / (half + x), and 1 - hill(x, half, n) falls from 1 to 0. It gives the activation of a gene by a protein, the uptake of a nutrient, and the response of a predator to more prey.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The expression the function reads, nonnegative.

required
half object

The value of x where the function is one half.

required
n object

The Hill coefficient, the steepness of the rise.

1

Returns:

Name Type Description
value Expression

The symbolic value.

See Also

logistic: Rises from 0 to 1 through a center for any real input.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import hill
>>> hill(var('x'), 2, 3)
x^3/(x^3 + 8)
Source code in src/skcomplex/core/components/laws/utils/_pointwise.py
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
def hill(x: object, half: object, n: object = 1) -> Expression:
    """Return the Hill function `x^n / (half^n + x^n)`, which rises from 0 to 1.

    It is one half at `x = half`, such as `hill(x, 2, 3)` that gives `x^3 / (x^3 + 8)`, and a larger `n` makes the rise
    steeper, close to a switch. The order `n = 1` gives the saturating function `x / (half + x)`, and
    `1 - hill(x, half, n)` falls from 1 to 0. It gives the activation of a gene by a protein, the uptake of a nutrient,
    and the response of a predator to more prey.

    Read more in the user guide, under Laws.

    Args:
        x:
            The expression the function reads, nonnegative.

        half:
            The value of `x` where the function is one half.

        n:
            The Hill coefficient, the steepness of the rise.

    Returns:
        value:
            The symbolic value.

    See Also:
        logistic: Rises from 0 to 1 through a center for any real input.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import hill
        >>> hill(var('x'), 2, 3)
        x^3/(x^3 + 8)
    """
    return SR(x) ** n / (SR(half) ** n + SR(x) ** n)

hodge_star(expression)

Return a state of a cell complex scaled cell by cell, the Hodge star.

It multiplies the value of every cell by a factor of that cell, such as hodge_star(flow) for the currents that the voltages of the edges drive. On a lattice the factor is the size of the dual cell over the size of the cell, from the spacings. On a network it is the parameter weight of the elements of the group on those cells, as the system holds it when it compiles, or 1 for a group without that parameter. It gives the conductance of the wires of a circuit, the capacity of the pipes of a network, and the areas of the cells of a mesh.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a group on the cells of a cell complex.

required

Returns:

Name Type Description
star Expression

The call hodge_star(expression).

See Also

exterior_derivative: Takes the differences of a state, one degree up. codifferential: Takes the net flow of a state, one degree down.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import hodge_star
>>> hodge_star(var('flow'))
hodge_star(flow)
Source code in src/skcomplex/core/components/laws/utils/_cells.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
def hodge_star(expression: object) -> Expression:
    """Return a state of a cell complex scaled cell by cell, the Hodge star.

    It multiplies the value of every cell by a factor of that cell, such as `hodge_star(flow)` for the currents that the
    voltages of the edges drive. On a lattice the factor is the size of the dual cell over the size of the cell, from
    the spacings. On a network it is the parameter `weight` of the elements of the group on those cells, as the system
    holds it when it compiles, or 1 for a group without that parameter. It gives the conductance of the wires of a
    circuit, the capacity of the pipes of a network, and the areas of the cells of a mesh.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a group on the cells of a cell complex.

    Returns:
        star:
            The call `hodge_star(expression)`.

    See Also:
        exterior_derivative: Takes the differences of a state, one degree up.
        codifferential: Takes the net flow of a state, one degree down.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import hodge_star
        >>> hodge_star(var('flow'))
        hodge_star(flow)
    """
    return HODGE_STAR(SR(expression))

hyperedges(expression, reduce='sum', size=None, weight=None, over=None)

Return a summary of an expression over the hyperedges around every member.

A hyperedge joins several members at once, and the expression is written for one hyperedge around the member that reads the result. namespace.others holds the values of the other members in order, namespace.members those of all its members, which total or mean sum with over=namespace.members, and namespace those of the reading member, such as hyperedges(sin(s.others[0].theta + s.others[1].theta - 2 * s.theta), size=3) for a coupling of oscillators in triangles. The hyperedges are those of the network by default, and in a continuous space with over=RadiusNeighborhood(r) or NearestNeighborhood(k) they are the member with every set of size - 1 of its current neighbours, for a size of at most 5. A member without hyperedges gets 0. It couples oscillators in groups, spreads a rumour that needs two sources, and models a group of three animals that forage together.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The value of one hyperedge, an expression of the values of namespace.others, namespace.members, and namespace, or a vector of them.

required
reduce str

How to combine the values of the hyperedges, as in neighbors, 'sum', 'mean', 'count', 'max', 'min', 'normalized-mean', 'argmax', or 'circular-mean'.

'sum'
size int | None

The number of members of the hyperedges, or None for every size of the network, where the expression reads namespace.members rather than namespace.others and only the sum, the mean, and the count apply.

None
weight object

The weight of one hyperedge, an expression of the same symbols, or None for 1.

None
over BaseNeighborhood | None

The neighbourhood whose current neighbours form the hyperedges, found again at every step, or None for the hyperedges of the network.

None

Returns:

Name Type Description
reduction Expression | FreeModuleElement

The unevaluated reduction, one per entry of a vector expression.

Raises:

Type Description
ValidationError

The reduction or the neighbourhood is unknown, or the size is not a whole number of at least two, or with a neighbourhood is missing or above 5.

See Also

neighbors: Reduces over the neighbours of every member.

Examples:

>>> from sage.all__sagemath_symbolics import sin, var
>>> from skcomplex.core.components.laws.utils import hyperedges
>>> theta, first, second = var('theta first second')
>>> hyperedges(sin(first + second - 2 * theta), size=3)
hyperedges(sin(first + second - 2*theta), reduce='sum', size=3)
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
def hyperedges(
    expression: object,
    reduce: str = 'sum',
    size: int | None = None,
    weight: object = None,
    over: BaseNeighborhood | None = None,
) -> Expression | FreeModuleElement:
    """Return a summary of an expression over the hyperedges around every member.

    A hyperedge joins several members at once, and the expression is written for one hyperedge around the member that
    reads the result. `namespace.others` holds the values of the other members in order, `namespace.members` those of
    all its members, which `total` or `mean` sum with `over=namespace.members`, and `namespace` those of the reading
    member, such as `hyperedges(sin(s.others[0].theta + s.others[1].theta - 2 * s.theta), size=3)` for a coupling of
    oscillators in triangles. The hyperedges are those of the network by default, and in a continuous space with
    `over=RadiusNeighborhood(r)` or `NearestNeighborhood(k)` they are the member with every set of `size - 1` of its
    current neighbours, for a size of at most 5. A member without hyperedges gets 0. It couples oscillators in groups,
    spreads a rumour that needs two sources, and models a group of three animals that forage together.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The value of one hyperedge, an expression of the values of `namespace.others`, `namespace.members`, and
            `namespace`, or a vector of them.

        reduce:
            How to combine the values of the hyperedges, as in `neighbors`, `'sum'`, `'mean'`, `'count'`, `'max'`,
            `'min'`, `'normalized-mean'`, `'argmax'`, or `'circular-mean'`.

        size:
            The number of members of the hyperedges, or `None` for every size of the network, where the expression reads
            `namespace.members` rather than `namespace.others` and only the sum, the mean, and the count apply.

        weight:
            The weight of one hyperedge, an expression of the same symbols, or `None` for 1.

        over:
            The neighbourhood whose current neighbours form the hyperedges, found again at every step, or `None` for the
            hyperedges of the network.

    Returns:
        reduction:
            The unevaluated reduction, one per entry of a vector expression.

    Raises:
        ValidationError:
            The reduction or the neighbourhood is unknown, or the size is not a whole number of at least two, or with a
            neighbourhood is missing or above 5.

    See Also:
        neighbors: Reduces over the neighbours of every member.

    Examples:
        >>> from sage.all__sagemath_symbolics import sin, var
        >>> from skcomplex.core.components.laws.utils import hyperedges
        >>> theta, first, second = var('theta first second')
        >>> hyperedges(sin(first + second - 2 * theta), size=3)
        hyperedges(sin(first + second - 2*theta), reduce='sum', size=3)
    """
    if size is not None and (
        isinstance(size, bool) or not isinstance(size, numbers.Integral) or size < MIN_HYPEREDGE_SIZE
    ):
        error_msg = f'A hyperedge reduction takes a size of 2 or more, or None for every size, not {size!r}.'
        raise ValidationError(error_msg)
    if over is not None and not isinstance(over, RadiusNeighborhood | NearestNeighborhood):
        error_msg = (
            f'A hyperedge reduction runs over the neighbours of a continuous space, not {over!r}. Give a '
            'RadiusNeighborhood or a NearestNeighborhood.'
        )
        raise ValidationError(error_msg)
    if over is not None and size is None:
        error_msg = f'A hyperedge reduction over {over!r} forms hyperedges of one size. Give it a size of 2 or more.'
        raise ValidationError(error_msg)
    if reduce == 'circular-mean':
        sines = hyperedges(sin(SR(expression)), 'sum', size, weight, over)
        return arctan2(sines, hyperedges(cos(SR(expression)), 'sum', size, weight, over))
    if reduce not in NEIGHBOR_REDUCTIONS:
        error_msg = (
            f'Unknown hyperedge reduction {reduce!r}. Use one of {", ".join((*NEIGHBOR_REDUCTIONS, "circular-mean"))}.'
        )
        raise ValidationError(error_msg)
    code = SR(NEIGHBOR_REDUCTIONS.index(reduce))
    weighted = SR(1) if weight is None else SR(weight)
    sized = SR(0 if size is None else int(size))
    over_symbol = _neighborhood_symbol(over)
    if isinstance(expression, FreeModuleElement):
        return vector(SR, [HYPEREDGES(SR(item), weighted, sized, code, over_symbol) for item in expression])
    return HYPEREDGES(SR(expression), weighted, sized, code, over_symbol)

integral_transform(expression, kernel, axes)

Return the integral of an expression over some axes, weighted by a kernel.

The value at the point c is the integral of K(c, c') u(c') over the points c' of the named axes, at the same position and the same coordinates of the other axes. The kernel K is written in coordinate(name) for c, integration_variable(name) for c', and the parameters, so it need not depend on c - c' alone, such as tanh(coordinate('z') - integration_variable('z') ** 2). It gives the fragments that break off larger ones, the newborns of parents of every age, and the particles that scatter from one speed to another.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states of a field on a phase space and the coordinates.

required
kernel object

The kernel, an expression of the coordinates, the integration variables, and the parameters.

required
axes Sequence[str]

The names of the axes to integrate over, each cell weighted by its width and its volume.

required

Returns:

Name Type Description
integral Expression

The call integral_transform(expression, kernel, *coordinates).

See Also

cumulative_integral: Integrates along one axis up to every site. convolve: Integrates against a kernel of the gap between two points.

Examples:

>>> from sage.all__sagemath_symbolics import var, tanh
>>> from skcomplex.core.components.laws.utils import coordinate, integral_transform, integration_variable
>>> kernel = tanh(coordinate('z') - integration_variable('z') ** 2)
>>> integral_transform(var('f'), kernel, ('z',))
integral_transform(f, tanh(-_integration_variable_z^2 + _coordinate_z), _coordinate_z)
Source code in src/skcomplex/core/components/laws/utils/_integrals.py
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
def integral_transform(expression: object, kernel: object, axes: Sequence[str]) -> Expression:
    """Return the integral of an expression over some axes, weighted by a kernel.

    The value at the point `c` is the integral of `K(c, c') u(c')` over the points `c'` of the named axes, at the same
    position and the same coordinates of the other axes. The kernel `K` is written in `coordinate(name)` for `c`,
    `integration_variable(name)` for `c'`, and the parameters, so it need not depend on `c - c'` alone, such as
    `tanh(coordinate('z') - integration_variable('z') ** 2)`. It gives the fragments that break off larger ones, the
    newborns of parents of every age, and the particles that scatter from one speed to another.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states of a field on a phase space and the coordinates.

        kernel:
            The kernel, an expression of the coordinates, the integration variables, and the parameters.

        axes:
            The names of the axes to integrate over, each cell weighted by its width and its volume.

    Returns:
        integral:
            The call `integral_transform(expression, kernel, *coordinates)`.

    See Also:
        cumulative_integral: Integrates along one axis up to every site.
        convolve: Integrates against a kernel of the gap between two points.

    Examples:
        >>> from sage.all__sagemath_symbolics import var, tanh
        >>> from skcomplex.core.components.laws.utils import coordinate, integral_transform, integration_variable
        >>> kernel = tanh(coordinate('z') - integration_variable('z') ** 2)
        >>> integral_transform(var('f'), kernel, ('z',))
        integral_transform(f, tanh(-_integration_variable_z^2 + _coordinate_z), _coordinate_z)
    """
    return INTEGRAL_TRANSFORM(SR(expression), SR(kernel), *coordinates_of(axes))

integration_variable(name)

Return the coordinate along a named axis of the point an integral runs over.

Inside the kernel of integral_transform, coordinate(name) is the point that receives the integral and integration_variable(name) the point it sums over, such as coordinate('z') - integration_variable('z') for the gap between the two. The axis is one of the axes of a phase space beyond position, such as size, age, or speed. It writes how a fragment of one size breaks into smaller ones, how parents of one age give birth, and how particles of one speed scatter to another.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the axis.

required

Returns:

Name Type Description
variable Expression

The symbol of the coordinate, a real number at every point integrated over.

Raises:

Type Description
ValidationError

The name is not a valid Python name.

See Also

coordinate: Gives the coordinate of the point that receives the integral. integral_transform: Integrates against a kernel of both points.

Examples:

>>> from skcomplex.core.components.laws.utils import coordinate, integration_variable
>>> coordinate('z') - integration_variable('z')
_coordinate_z - _integration_variable_z
Source code in src/skcomplex/core/components/laws/utils/_integrals.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def integration_variable(name: str) -> Expression:
    """Return the coordinate along a named axis of the point an integral runs over.

    Inside the kernel of `integral_transform`, `coordinate(name)` is the point that receives the integral and
    `integration_variable(name)` the point it sums over, such as `coordinate('z') - integration_variable('z')` for the
    gap between the two. The axis is one of the axes of a phase space beyond position, such as size, age, or speed. It
    writes how a fragment of one size breaks into smaller ones, how parents of one age give birth, and how particles of
    one speed scatter to another.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the axis.

    Returns:
        variable:
            The symbol of the coordinate, a real number at every point integrated over.

    Raises:
        ValidationError:
            The name is not a valid Python name.

    See Also:
        coordinate: Gives the coordinate of the point that receives the integral.
        integral_transform: Integrates against a kernel of both points.

    Examples:
        >>> from skcomplex.core.components.laws.utils import coordinate, integration_variable
        >>> coordinate('z') - integration_variable('z')
        _coordinate_z - _integration_variable_z
    """
    if not isinstance(name, str) or not name.isidentifier():
        error_msg = f'The name of an axis must be a valid Python name, such as `v`, but it is {name!r}.'
        raise ValidationError(error_msg)
    return SR.var(f'{INTEGRATION_PREFIX}{name}', domain='real')

inverse_helmholtz(expression, screening=0, boundary=None)

Return the field psi with (laplacian - screening**2) psi = expression.

The compiler solves the equation over the whole lattice at every step, so a law reads a potential that its sources set at once, such as inverse_helmholtz(q, 2) for the potential of the charge q screened over a distance of one half. Without screening it solves the Poisson equation laplacian(psi) = expression. It gives the electric potential of charges, the gravity of a mass, and the signal that cells emit and that decays as it spreads.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a field.

required
screening object

The screening, an expression of the parameters of 0 or more, or 0 for the Poisson equation.

0
boundary object

The boundary condition of the solution, 'periodic', 'zero-flux', or ('fixed', value), or None for the boundary condition of the states of the expression.

None

Returns:

Name Type Description
solution Expression

The call inverse_helmholtz(expression, screening), followed for a given boundary by its position in INVERSION_BOUNDARIES and its fixed value, 0 for the other boundaries.

Raises:

Type Description
ValidationError

The boundary is not one of INVERSION_BOUNDARIES or a fixed boundary with its value.

See Also

laplacian: Gives the operator it inverts. leray_projection: Removes the outflow of a vector field with it.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import inverse_helmholtz
>>> inverse_helmholtz(var('q'), 2)
inverse_helmholtz(q, 2)
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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
def inverse_helmholtz(expression: object, screening: object = 0, boundary: object = None) -> Expression:
    """Return the field `psi` with `(laplacian - screening**2) psi = expression`.

    The compiler solves the equation over the whole lattice at every step, so a law reads a potential that its sources
    set at once, such as `inverse_helmholtz(q, 2)` for the potential of the charge `q` screened over a distance of one
    half. Without screening it solves the Poisson equation `laplacian(psi) = expression`. It gives the electric
    potential of charges, the gravity of a mass, and the signal that cells emit and that decays as it spreads.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a field.

        screening:
            The screening, an expression of the parameters of 0 or more, or 0 for the Poisson equation.

        boundary:
            The boundary condition of the solution, `'periodic'`, `'zero-flux'`, or `('fixed', value)`, or `None` for
            the boundary condition of the states of the expression.

    Returns:
        solution:
            The call `inverse_helmholtz(expression, screening)`, followed for a given boundary by its position in
            `INVERSION_BOUNDARIES` and its fixed value, 0 for the other boundaries.

    Raises:
        ValidationError:
            The boundary is not one of `INVERSION_BOUNDARIES` or a fixed boundary with its value.

    See Also:
        laplacian: Gives the operator it inverts.
        leray_projection: Removes the outflow of a vector field with it.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import inverse_helmholtz
        >>> inverse_helmholtz(var('q'), 2)
        inverse_helmholtz(q, 2)
    """
    if boundary is None:
        return INVERSE_HELMHOLTZ(SR(expression), SR(screening))
    kind, *values = boundary if isinstance(boundary, tuple) else (boundary,)
    if kind not in INVERSION_BOUNDARIES or (kind == 'fixed') != bool(values) or len(values) > 1:
        error_msg = (
            f"The boundary of inverse_helmholtz must be 'periodic', 'zero-flux', ('fixed', value), or None, but it is "
            f'{boundary!r}.'
        )
        raise ValidationError(error_msg)
    code = SR(INVERSION_BOUNDARIES.index(kind))
    return INVERSE_HELMHOLTZ(SR(expression), SR(screening), code, SR(values[0] if values else 0))

leray_projection(field)

Return the divergence-free part of a vector field, with no net outflow anywhere.

It is v - grad(inverse_helmholtz(div(v))), the field minus the gradient that carries its outflow, so what is left neither gathers nor spreads at any point, such as the three entries of a velocity [u, v, w] kept free of compression. It keeps the flow of water incompressible, the magnetic field free of sources, and a crowd from piling up in place.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
field Sequence[object] | FreeModuleElement

One expression per dimension.

required

Returns:

Name Type Description
projection FreeModuleElement

The divergence-free vector.

Raises:

Type Description
TensorShapeError

The value is not a vector.

See Also

inverse_helmholtz: Solves for the potential it removes. divergence: Gives the outflow it removes.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import leray_projection
>>> len(leray_projection([var('u'), var('v'), var('w')]))
3
Source code in src/skcomplex/core/components/laws/utils/_tensors.py
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
def leray_projection(field: Sequence[object] | FreeModuleElement) -> FreeModuleElement:
    """Return the divergence-free part of a vector field, with no net outflow anywhere.

    It is `v - grad(inverse_helmholtz(div(v)))`, the field minus the gradient that carries its outflow, so what is left
    neither gathers nor spreads at any point, such as the three entries of a velocity `[u, v, w]` kept free of
    compression. It keeps the flow of water incompressible, the magnetic field free of sources, and a crowd from piling
    up in place.

    Read more in the user guide, under Laws.

    Args:
        field:
            One expression per dimension.

    Returns:
        projection:
            The divergence-free vector.

    Raises:
        TensorShapeError:
            The value is not a vector.

    See Also:
        inverse_helmholtz: Solves for the potential it removes.
        divergence: Gives the outflow it removes.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import leray_projection
        >>> len(leray_projection([var('u'), var('v'), var('w')]))
        3
    """
    components = _check_vector('leray_projection', field)
    potential = inverse_helmholtz(divergence(components))
    return components - gradient(potential, len(components))

local_operator(subsystem, name)

Return a named operator that acts on one subsystem alone.

The name picks an operator of the Hilbert space of the subsystem, such as local_operator(q, 'z') for the Pauli Z of the qubit q. Operators do not commute, so a product is written operator_product(a, b) and an adjoint dagger(a), both kept as they are until the compiler turns them into matrices. A coefficient is an ordinary expression, so a coupling of strength J is J * operator_product(a, b). It builds the Hamiltonian of a spin chain, of a cavity holding light and an atom, and of a register of qubits.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
subsystem object

The symbol of the state of the subsystem, such as namespace.psi.

required
name object

The name of the operator in the Hilbert space, such as 'z', or its symbol.

required

Returns:

Name Type Description
operator Expression

The unevaluated local operator.

See Also

has_operator: Checks whether an expression holds a local operator.

Examples:

>>> from sage.all__sagemath_symbolics import SR
>>> from skcomplex.core.components.laws.utils import local_operator
>>> local_operator(SR.symbol('q'), 'z')
local_operator(q, z)
Source code in src/skcomplex/core/components/laws/utils/_local_operators.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def local_operator(subsystem: object, name: object) -> Expression:
    """Return a named operator that acts on one subsystem alone.

    The name picks an operator of the Hilbert space of the subsystem, such as `local_operator(q, 'z')` for the Pauli `Z`
    of the qubit `q`. Operators do not commute, so a product is written `operator_product(a, b)` and an adjoint
    `dagger(a)`, both kept as they are until the compiler turns them into matrices. A coefficient is an ordinary
    expression, so a coupling of strength `J` is `J * operator_product(a, b)`. It builds the Hamiltonian of a spin
    chain, of a cavity holding light and an atom, and of a register of qubits.

    Read more in the user guide, under Laws.

    Args:
        subsystem:
            The symbol of the state of the subsystem, such as `namespace.psi`.

        name:
            The name of the operator in the Hilbert space, such as `'z'`, or its symbol.

    Returns:
        operator:
            The unevaluated local operator.

    See Also:
        has_operator: Checks whether an expression holds a local operator.

    Examples:
        >>> from sage.all__sagemath_symbolics import SR
        >>> from skcomplex.core.components.laws.utils import local_operator
        >>> local_operator(SR.symbol('q'), 'z')
        local_operator(q, z)
    """
    return LOCAL_OPERATOR(subsystem, SR.symbol(name) if isinstance(name, str) else name)

log_sum_exp(expression, over=None, where=None)

Return the log of the sum of the exponentials of an expression over members.

It is log Σ_j exp(a_j) over the selected members, computed so that large values do not overflow, such as log_sum_exp(-E / T) for the log of the partition function of states of energy E at temperature T. It gives the free energy of a physical system, the expected utility of a choice among options, and the normaliser of a softmax.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The expression of one member, a logarithm of the terms of the sum.

required
over object

The namespace of the group to reduce over, or None for the group the expression reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None

Returns:

Name Type Description
reduction Expression

The unevaluated reduction, 0 when no member is selected.

Raises:

Type Description
ValidationError

The group is not a namespace or a symbol.

See Also

total: Sums an expression over the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import log_sum_exp
>>> log_sum_exp(-var('E') / var('T'))
log_sum_exp(-E/T)
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def log_sum_exp(expression: object, over: object = None, where: object = None) -> Expression:
    """Return the log of the sum of the exponentials of an expression over members.

    It is `log Σ_j exp(a_j)` over the selected members, computed so that large values do not overflow, such as
    `log_sum_exp(-E / T)` for the log of the partition function of states of energy `E` at temperature `T`. It gives the
    free energy of a physical system, the expected utility of a choice among options, and the normaliser of a softmax.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The expression of one member, a logarithm of the terms of the sum.

        over:
            The namespace of the group to reduce over, or `None` for the group the expression reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

    Returns:
        reduction:
            The unevaluated reduction, 0 when no member is selected.

    Raises:
        ValidationError:
            The group is not a namespace or a symbol.

    See Also:
        total: Sums an expression over the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import log_sum_exp
        >>> log_sum_exp(-var('E') / var('T'))
        log_sum_exp(-E/T)
    """
    return _reduce('log_sum_exp', expression, over, where, None)

logistic(x, center=0, width=1)

Return the logistic curve 1 / (1 + exp(-(x - center) / width)).

It rises from 0 to 1 and is one half at x = center, such as logistic(x, 1, 2) that is one half at 1. It is written as (1 + tanh((x - center) / (2 width))) / 2, which gives the same value and stays accurate for large inputs, where the exponential form that Sage may produce loses all its digits. It gives the firing rate of a neuron, the chance that a buyer adopts a product, and the share of a population that has caught on.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The expression the function reads.

required
center object

The value of x where the function is one half.

0
width object

The scale of the rise, the inverse of its steepness, negative for a falling curve.

1

Returns:

Name Type Description
value Expression

The symbolic value.

See Also

hill: Rises from 0 to 1 for a nonnegative input.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import logistic
>>> logistic(var('x'), 1, 2)
1/2*tanh(1/4*x - 1/4) + 1/2
Source code in src/skcomplex/core/components/laws/utils/_pointwise.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
def logistic(x: object, center: object = 0, width: object = 1) -> Expression:
    """Return the logistic curve `1 / (1 + exp(-(x - center) / width))`.

    It rises from 0 to 1 and is one half at `x = center`, such as `logistic(x, 1, 2)` that is one half at 1. It is
    written as `(1 + tanh((x - center) / (2 width))) / 2`, which gives the same value and stays accurate for large
    inputs, where the exponential form that Sage may produce loses all its digits. It gives the firing rate of a neuron,
    the chance that a buyer adopts a product, and the share of a population that has caught on.

    Read more in the user guide, under Laws.

    Args:
        x:
            The expression the function reads.

        center:
            The value of `x` where the function is one half.

        width:
            The scale of the rise, the inverse of its steepness, negative for a falling curve.

    Returns:
        value:
            The symbolic value.

    See Also:
        hill: Rises from 0 to 1 for a nonnegative input.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import logistic
        >>> logistic(var('x'), 1, 2)
        1/2*tanh(1/4*x - 1/4) + 1/2
    """
    return (1 + tanh((SR(x) - center) / (2 * SR(width)))) / 2

maximum(*expressions, over=None, where=None)

Return the largest value of an expression over selected members, or of several.

With one expression it gives the largest value over the members of a group, as max of an array, and 0 when no member is selected. With several it gives the largest of them for every member, as max of its arguments, such as maximum(x, y) that is 2 for x = 1 and y = 2. It gives the highest bid of an auction, the tallest tree that shades a forest, and the larger of a demand and a floor.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
*expressions object

The expression of one member, or several expressions to compare member by member.

()
over object

The namespace of the group to reduce over, or None for the group the expression reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None

Returns:

Name Type Description
value Expression

The unevaluated reduction, 0 when no member is selected, or the largest of the expressions.

Raises:

Type Description
ValidationError

No expression is given, several expressions come with a group or a condition, or the group is not a namespace or a symbol.

See Also

minimum: Gives the smallest value instead.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import maximum
>>> x, y = var('x y')
>>> maximum(x, y).subs(x=1, y=2)
2
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def maximum(*expressions: object, over: object = None, where: object = None) -> Expression:
    """Return the largest value of an expression over selected members, or of several.

    With one expression it gives the largest value over the members of a group, as `max` of an array, and 0 when no
    member is selected. With several it gives the largest of them for every member, as `max` of its arguments, such as
    `maximum(x, y)` that is 2 for `x = 1` and `y = 2`. It gives the highest bid of an auction, the tallest tree that
    shades a forest, and the larger of a demand and a floor.

    Read more in the user guide, under Laws.

    Args:
        *expressions:
            The expression of one member, or several expressions to compare member by member.

        over:
            The namespace of the group to reduce over, or `None` for the group the expression reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

    Returns:
        value:
            The unevaluated reduction, 0 when no member is selected, or the largest of the expressions.

    Raises:
        ValidationError:
            No expression is given, several expressions come with a group or a condition, or the group is not a
            namespace or a symbol.

    See Also:
        minimum: Gives the smallest value instead.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import maximum
        >>> x, y = var('x y')
        >>> maximum(x, y).subs(x=1, y=2)
        2
    """
    if len(expressions) == 1:
        return _reduce('maximum', expressions[0], over, where, None)
    if not expressions or over is not None or where is not None:
        error_msg = (
            'maximum takes one expression to reduce over a group, or several expressions to compare member by member '
            f'without a group or a condition, but got {len(expressions)} expressions.'
        )
        raise ValidationError(error_msg)
    return _largest(expressions)

maximum_entropy(expression, axes, order=2)

Return the smoothest density with the same low moments as an expression.

It is the density of largest entropy whose moments up to order equal those of the expression, exp(a + b c) for the order 1 and exp(a + b c + d |c|^2) for the order 2, with c the coordinates of the named axes, such as maximum_entropy(f, ('v',)) for the bell curve of speeds with the density, mean, and spread of f. Its parameters are found at every position so that its moments equal those of the expression up to rounding. It relaxes a gas toward equilibrium, closes the equations of a crowd, and fills in a distribution of incomes from its mean and variance.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states of a field on a phase space and the coordinates.

required
axes Sequence[str]

The names of the axes of the density.

required
order int

The highest order of the moments that are kept, 0, 1, or 2.

2

Returns:

Name Type Description
density Expression

The call maximum_entropy(expression, order, *coordinates).

Raises:

Type Description
ValidationError

The order is not 0, 1, or 2.

See Also

moment: Gives a moment of a density.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import maximum_entropy
>>> maximum_entropy(var('f'), ('v',))
maximum_entropy(f, 2, _coordinate_v)
Source code in src/skcomplex/core/components/laws/utils/_phase.py
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
def maximum_entropy(expression: object, axes: Sequence[str], order: int = 2) -> Expression:
    """Return the smoothest density with the same low moments as an expression.

    It is the density of largest entropy whose moments up to `order` equal those of the expression, `exp(a + b c)` for
    the order 1 and `exp(a + b c + d |c|^2)` for the order 2, with `c` the coordinates of the named axes, such as
    `maximum_entropy(f, ('v',))` for the bell curve of speeds with the density, mean, and spread of `f`. Its parameters
    are found at every position so that its moments equal those of the expression up to rounding. It relaxes a gas
    toward equilibrium, closes the equations of a crowd, and fills in a distribution of incomes from its mean and
    variance.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states of a field on a phase space and the coordinates.

        axes:
            The names of the axes of the density.

        order:
            The highest order of the moments that are kept, 0, 1, or 2.

    Returns:
        density:
            The call `maximum_entropy(expression, order, *coordinates)`.

    Raises:
        ValidationError:
            The order is not 0, 1, or 2.

    See Also:
        moment: Gives a moment of a density.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import maximum_entropy
        >>> maximum_entropy(var('f'), ('v',))
        maximum_entropy(f, 2, _coordinate_v)
    """
    if order not in {0, 1, 2}:
        error_msg = f'The order of a maximum entropy density must be 0, 1, or 2, but it is {order!r}.'
        raise ValidationError(error_msg)
    return MAXIMUM_ENTROPY(SR(expression), SR(order), *coordinates_of(axes))

mean(expression, over=None, where=None, weights=None, by=None)

Return the mean of an expression over the selected members of a group.

It is the sum over the members that where selects divided by their number, or 0 when none is selected, such as mean(cos(theta)) for how well the phases of a group line up. It gives the mean opinion of voters, the order of oscillators that synchronise, and the average price in a market.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The expression of one member.

required
over object

The namespace of the group to reduce over, or None for the group the expression reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None
weights object

A constant matrix with one row per reading member and one column per reduced member, or None.

None
by str | None

The name of a state of the group, so every member reduces over the members that share its value of the state, or None for all members. It needs the namespace of the group as over.

None

Returns:

Name Type Description
reduction Expression

The unevaluated reduction, 0 when no member is selected.

Raises:

Type Description
ValidationError

The group is not a namespace or a symbol, the weights are not a matrix, or by comes without the namespace of the group.

See Also

total: Sums an expression over the members of a group. circular_mean: Averages an angle over the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import cos, var
>>> from skcomplex.core.components.laws.utils import mean
>>> mean(cos(var('theta')))
mean(cos(theta))
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def mean(
    expression: object,
    over: object = None,
    where: object = None,
    weights: object = None,
    by: str | None = None,
) -> Expression:
    """Return the mean of an expression over the selected members of a group.

    It is the sum over the members that `where` selects divided by their number, or 0 when none is selected, such as
    `mean(cos(theta))` for how well the phases of a group line up. It gives the mean opinion of voters, the order of
    oscillators that synchronise, and the average price in a market.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The expression of one member.

        over:
            The namespace of the group to reduce over, or `None` for the group the expression reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

        weights:
            A constant matrix with one row per reading member and one column per reduced member, or `None`.

        by:
            The name of a state of the group, so every member reduces over the members that share its value of the
            state, or `None` for all members. It needs the namespace of the group as `over`.

    Returns:
        reduction:
            The unevaluated reduction, 0 when no member is selected.

    Raises:
        ValidationError:
            The group is not a namespace or a symbol, the weights are not a matrix, or `by` comes without the namespace
            of the group.

    See Also:
        total: Sums an expression over the members of a group.
        circular_mean: Averages an angle over the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import cos, var
        >>> from skcomplex.core.components.laws.utils import mean
        >>> mean(cos(var('theta')))
        mean(cos(theta))
    """
    return _reduce('mean', expression, over, where, weights, by=by)

minimum(*expressions, over=None, where=None)

Return the smallest value of an expression over selected members, or of several.

With one expression it gives the smallest value over the members of a group, as min of an array, and 0 when no member is selected. With several it gives the smallest of them for every member, as min of its arguments, such as minimum(x, y) that is 1 for x = 1 and y = 2. It gives the lowest ask of a market, the nutrient that limits growth, and the smaller of an order and the stock on hand.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
*expressions object

The expression of one member, or several expressions to compare member by member.

()
over object

The namespace of the group to reduce over, or None for the group the expression reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None

Returns:

Name Type Description
value Expression

The unevaluated reduction, 0 when no member is selected, or the smallest of the expressions.

Raises:

Type Description
ValidationError

No expression is given, several expressions come with a group or a condition, or the group is not a namespace or a symbol.

See Also

maximum: Gives the largest value instead.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import minimum
>>> x, y = var('x y')
>>> minimum(x, y).subs(x=1, y=2)
1
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def minimum(*expressions: object, over: object = None, where: object = None) -> Expression:
    """Return the smallest value of an expression over selected members, or of several.

    With one expression it gives the smallest value over the members of a group, as `min` of an array, and 0 when no
    member is selected. With several it gives the smallest of them for every member, as `min` of its arguments, such as
    `minimum(x, y)` that is 1 for `x = 1` and `y = 2`. It gives the lowest ask of a market, the nutrient that limits
    growth, and the smaller of an order and the stock on hand.

    Read more in the user guide, under Laws.

    Args:
        *expressions:
            The expression of one member, or several expressions to compare member by member.

        over:
            The namespace of the group to reduce over, or `None` for the group the expression reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

    Returns:
        value:
            The unevaluated reduction, 0 when no member is selected, or the smallest of the expressions.

    Raises:
        ValidationError:
            No expression is given, several expressions come with a group or a condition, or the group is not a
            namespace or a symbol.

    See Also:
        maximum: Gives the largest value instead.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import minimum
        >>> x, y = var('x y')
        >>> minimum(x, y).subs(x=1, y=2)
        1
    """
    if len(expressions) == 1:
        return _reduce('minimum', expressions[0], over, where, None)
    if not expressions or over is not None or where is not None:
        error_msg = (
            'minimum takes one expression to reduce over a group, or several expressions to compare member by member '
            f'without a group or a condition, but got {len(expressions)} expressions.'
        )
        raise ValidationError(error_msg)
    return _smallest(expressions)

moment(expression, order, coordinates=None, *, over=None, normalized=False, central=False, axes=None)

Return a moment of a distribution that a group holds over a grid.

Every member j holds the density f_j at the coordinate c_j, and the moment of order r is Σ_j c_j^r f_j, such as moment(f, 0, [0.0, 1.0, 2.0]) that gives the total total(f). A normalized moment divides by the total, so the normalized moment of order 1 is the mean coordinate, and a central moment is taken about the mean, so the central moment of order 2 is the variance. With axes, it sums a field of a phase space over those axes, such as velocity, at every position, and over several axes the coordinate is the length of the vector of coordinates. It gives the mean activity of a neural population, the mean wealth of a class of households, and the pressure of a gas.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The expression of one member, usually the density.

required
order int

The order r, a whole number of 0 or more.

required
coordinates object

The coordinate of every member, such as the activity values of a grid, or None with axes.

None
over object

The namespace of the group to reduce over, or None for the group the expression reads.

None
normalized bool

Whether to divide by the density.

False
central bool

Whether to take the moment about the mean, which also normalizes it.

False
axes Sequence[str] | None

The names of the axes of a phase space to sum over, or None to sum over every member.

None

Returns:

Name Type Description
moment Expression

The moment as an expression of sums, which laws read and observables record.

Raises:

Type Description
ValidationError

The order is not a whole number of 0 or more, the coordinates are not a list of one number per member, both coordinates and axes are given, or an odd order is taken over several axes.

See Also

total: Sums an expression over the members of a group. reduce_axes: Sums a field of a phase space over some axes.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import moment
>>> moment(var('f'), 0, [0.0, 1.0, 2.0])
total(f)
Source code in src/skcomplex/core/components/laws/utils/_moments.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
def moment(
    expression: object,
    order: int,
    coordinates: object = None,
    *,
    over: object = None,
    normalized: bool = False,
    central: bool = False,
    axes: Sequence[str] | None = None,
) -> Expression:
    """Return a moment of a distribution that a group holds over a grid.

    Every member `j` holds the density `f_j` at the coordinate `c_j`, and the moment of order `r` is `Σ_j c_j^r f_j`,
    such as `moment(f, 0, [0.0, 1.0, 2.0])` that gives the total `total(f)`. A normalized moment divides by the total,
    so the normalized moment of order 1 is the mean coordinate, and a central moment is taken about the mean, so the
    central moment of order 2 is the variance. With `axes`, it sums a field of a phase space over those axes, such as
    velocity, at every position, and over several axes the coordinate is the length of the vector of coordinates. It
    gives the mean activity of a neural population, the mean wealth of a class of households, and the pressure of a gas.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The expression of one member, usually the density.

        order:
            The order `r`, a whole number of 0 or more.

        coordinates:
            The coordinate of every member, such as the activity values of a grid, or `None` with `axes`.

        over:
            The namespace of the group to reduce over, or `None` for the group the expression reads.

        normalized:
            Whether to divide by the density.

        central:
            Whether to take the moment about the mean, which also normalizes it.

        axes:
            The names of the axes of a phase space to sum over, or `None` to sum over every member.

    Returns:
        moment:
            The moment as an expression of sums, which laws read and observables record.

    Raises:
        ValidationError:
            The order is not a whole number of 0 or more, the coordinates are not a list of one number per member, both
            coordinates and axes are given, or an odd order is taken over several axes.

    See Also:
        total: Sums an expression over the members of a group.
        reduce_axes: Sums a field of a phase space over some axes.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import moment
        >>> moment(var('f'), 0, [0.0, 1.0, 2.0])
        total(f)
    """
    if isinstance(order, bool) or not isinstance(order, int) or order < 0:
        error_msg = f'The order of a moment must be a whole number of 0 or more, but it is {order!r}.'
        raise ValidationError(error_msg)
    if axes is not None:
        if coordinates is not None:
            error_msg = f'A moment over the axes {axes} reads the coordinates of the axes. Give no other coordinates.'
            raise ValidationError(error_msg)
        return _combined(lambda power: _raw_over_axes(expression, power, axes), order, normalized, central)
    values = np.asarray(coordinates, dtype=float)
    if values.ndim != 1 or not values.size:
        error_msg = f'The coordinates of a moment must be one number per member, but they are {coordinates!r}.'
        raise ValidationError(error_msg)
    return _combined(lambda power: _raw(expression, power, values, over), order, normalized, central)

neighbors(expression, over=None, reduce='sum', weight=None)

Return a summary of an expression over the neighbours of every member.

The expression is written for one neighbour, with namespace.other holding the values of the neighbour and namespace those of the member that reads the result, such as neighbors(sin(s.other.theta - s.theta)) for the pull of every neighbour on the phase of an oscillator. The neighbours are those of the network by default, of a layer with AdjacencyNeighborhood(layer=label) or its LayerSpec, of a lattice neighbourhood, or in a continuous space those within a distance, RadiusNeighborhood(r), inside a cone, RadiusNeighborhood(r, angle=angle), or the nearest, NearestNeighborhood(k). A member without neighbours gets 0. It couples oscillators on a network, aligns the headings of birds in a flock, and lets players copy their most successful neighbour.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The value of one neighbour, an expression of the values of namespace.other and namespace, or a vector of them.

required
over BaseNeighborhood | LayerSpec | None

The neighbourhood, or None for the neighbours of the network or lattice the group lives on.

None
reduce str

How to combine the values f_j of the neighbours with their weights w_j. 'sum' gives Σ_j w_j f_j, 'mean' that sum over the number of neighbours, 'count' gives Σ_j w_j [f_j != 0], 'max' and 'min' the largest and smallest w_j f_j, 'normalized-mean' gives Σ_j w_j f_j / Σ_j w_j, 'argmax' the value of the neighbour of largest weight, the first in neighbour order, and 'circular-mean' gives arctan2(Σ_j w_j sin f_j, Σ_j w_j cos f_j). 'each' gives the values at every offset of a lattice neighbourhood or a memory, in order, without combining them.

'sum'
weight object

The weight of one neighbour, an expression of the same symbols, or None for 1. The 'argmax' reduction picks the neighbour whose weight is largest.

None

Returns:

Name Type Description
reduction Expression | FreeModuleElement

The unevaluated reduction, one per entry of a vector expression, or with reduce='each' the values of a lattice state at the offsets of a lattice neighbourhood.

Raises:

Type Description
ValidationError

The reduction or the neighbourhood is unknown.

See Also

hyperedges: Reduces over the hyperedges around every member. total: Sums an expression over all the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import sin, var
>>> from skcomplex.core.components.laws.utils import neighbors
>>> from skcomplex.core.components.spaces import RadiusNeighborhood
>>> neighbors(sin(var('theta_other')), over=RadiusNeighborhood(1.0), reduce='mean')
neighbors(sin(theta_other), over=RadiusNeighborhood(radius=1.0), reduce='mean')
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
def neighbors(
    expression: object,
    over: BaseNeighborhood | LayerSpec | None = None,
    reduce: str = 'sum',
    weight: object = None,
) -> Expression | FreeModuleElement:
    """Return a summary of an expression over the neighbours of every member.

    The expression is written for one neighbour, with `namespace.other` holding the values of the neighbour and
    `namespace` those of the member that reads the result, such as `neighbors(sin(s.other.theta - s.theta))` for the
    pull of every neighbour on the phase of an oscillator. The neighbours are those of the network by default, of a
    layer with `AdjacencyNeighborhood(layer=label)` or its `LayerSpec`, of a lattice neighbourhood, or in a continuous
    space those within a distance, `RadiusNeighborhood(r)`, inside a cone, `RadiusNeighborhood(r, angle=angle)`, or the
    nearest, `NearestNeighborhood(k)`. A member without neighbours gets 0. It couples oscillators on a network, aligns
    the headings of birds in a flock, and lets players copy their most successful neighbour.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The value of one neighbour, an expression of the values of `namespace.other` and `namespace`, or a vector of
            them.

        over:
            The neighbourhood, or `None` for the neighbours of the network or lattice the group lives on.

        reduce:
            How to combine the values `f_j` of the neighbours with their weights `w_j`. `'sum'` gives `Σ_j w_j f_j`,
            `'mean'` that sum over the number of neighbours, `'count'` gives `Σ_j w_j [f_j != 0]`, `'max'` and `'min'`
            the largest and smallest `w_j f_j`, `'normalized-mean'` gives `Σ_j w_j f_j / Σ_j w_j`, `'argmax'` the value
            of the neighbour of largest weight, the first in neighbour order, and `'circular-mean'` gives
            `arctan2(Σ_j w_j sin f_j, Σ_j w_j cos f_j)`. `'each'` gives the values at every offset of a lattice
            neighbourhood or a memory, in order, without combining them.

        weight:
            The weight of one neighbour, an expression of the same symbols, or `None` for 1. The `'argmax'` reduction
            picks the neighbour whose weight is largest.

    Returns:
        reduction:
            The unevaluated reduction, one per entry of a vector expression, or with `reduce='each'` the values of a
            lattice state at the offsets of a lattice neighbourhood.

    Raises:
        ValidationError:
            The reduction or the neighbourhood is unknown.

    See Also:
        hyperedges: Reduces over the hyperedges around every member.
        total: Sums an expression over all the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import sin, var
        >>> from skcomplex.core.components.laws.utils import neighbors
        >>> from skcomplex.core.components.spaces import RadiusNeighborhood
        >>> neighbors(sin(var('theta_other')), over=RadiusNeighborhood(1.0), reduce='mean')
        neighbors(sin(theta_other), over=RadiusNeighborhood(radius=1.0), reduce='mean')
    """
    if reduce == 'each':
        items = over._get_slots() if isinstance(over, BaseNeighborhood) else None
        if items is None:
            error_msg = (
                f"The reduction 'each' reads a neighbourhood whose offsets are known before its lattice, such as a "
                f'LatticeNeighborhood, or a memory neighbourhood, not {over!r}.'
            )
            raise ValidationError(error_msg)
        return vector(SR, [NEIGHBOR(expression, index) for index in range(len(items))])
    if reduce == 'circular-mean':
        sines = neighbors(sin(SR(expression)), over, 'sum', weight)
        return arctan2(sines, neighbors(cos(SR(expression)), over, 'sum', weight))
    if reduce not in NEIGHBOR_REDUCTIONS:
        error_msg = (
            'Unknown neighbourhood reduction '
            f'{reduce!r}. Use one of {", ".join((*NEIGHBOR_REDUCTIONS, "circular-mean", "each"))}.'
        )
        raise ValidationError(error_msg)
    over_symbol = _neighborhood_symbol(over)
    code = SR(NEIGHBOR_REDUCTIONS.index(reduce))
    weighted = SR(1) if weight is None else SR(weight)
    if isinstance(expression, FreeModuleElement):
        return vector(SR, [NEIGHBORS(SR(item), weighted, over_symbol, code) for item in expression])
    return NEIGHBORS(SR(expression), weighted, over_symbol, code)

normal(name, mean=0, deviation=1)

Return a value drawn from a normal distribution at every step.

A new value of mean mean and standard deviation deviation is drawn at every step, shared by every use of the same name in one element and drawn apart for every member of a group, such as x + normal('step', 0, 1) for a random walk. It gives the shocks to a price, the errors of a measurement, and the jitter of a firing neuron.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the draw, a valid Python name.

required
mean object

The mean, a number or an expression of states and parameters.

0
deviation object

The standard deviation.

1

Returns:

Name Type Description
draw Expression

The symbolic draw.

Raises:

Type Description
ValidationError

The name is not a valid Python name.

See Also

uniform: Draws uniformly between two bounds. draw: Draws from any distribution of scipy.stats.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import normal
>>> var('x') + normal('step', 0, 1)
x + normal_step(0, 1)
Source code in src/skcomplex/core/components/laws/utils/_draws.py
 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
def normal(name: str, mean: object = 0, deviation: object = 1) -> Expression:
    """Return a value drawn from a normal distribution at every step.

    A new value of mean `mean` and standard deviation `deviation` is drawn at every step, shared by every use of the
    same name in one element and drawn apart for every member of a group, such as `x + normal('step', 0, 1)` for a
    random walk. It gives the shocks to a price, the errors of a measurement, and the jitter of a firing neuron.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the draw, a valid Python name.

        mean:
            The mean, a number or an expression of states and parameters.

        deviation:
            The standard deviation.

    Returns:
        draw:
            The symbolic draw.

    Raises:
        ValidationError:
            The name is not a valid Python name.

    See Also:
        uniform: Draws uniformly between two bounds.
        draw: Draws from any distribution of `scipy.stats`.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import normal
        >>> var('x') + normal('step', 0, 1)
        x + normal_step(0, 1)
    """
    return _call('normal', name, (mean, deviation))

pairs(left, right, rng, pairing=None, *, capacity=1, feasible=None)

Pair the agents of one or two groups, inside a rule.

By default the agents pair uniformly at random, such as 2 pairs for 3 buyers and 2 sellers. A PartnerSpec picks partners within reach, by score, or among neighbours, and any other pairing, such as a stable matching or an auction, is a function pairing(left, right, rng, capacity) that returns the pairs. With feasible, the pairs come one at a time in a random order of agents, so a rule can settle each pair before the next one is checked. It matches workers with firms, buyers with sellers, birds with mates, and players with opponents.

Read more in the user guide, under Agents.

Parameters:

Name Type Description Default
left Sequence[AgentViewProtocol]

The agents of the first group, as a rule reads them with system.get_agents(path).

required
right Sequence[AgentViewProtocol] | None

The agents of the second group, or None for pairs within the first.

required
rng Generator

The random generator, such as system.rng.

required
pairing Pairing | PartnerSpec | None

A PartnerSpec, a function of both groups that returns their pairs, or None for uniform random pairs.

None
capacity int

The largest number of pairs of every member, for random pairs and for a function.

1
feasible Feasibility | None

The function feasible(agent, candidate) that says whether an agent can pair with a candidate now, or None. It needs a PartnerSpec.

None

Returns:

Name Type Description
pairs Iterator[tuple[AgentViewProtocol, AgentViewProtocol]]

The pairs of agents, the first of every pair from the first group.

Raises:

Type Description
ValidationError

The capacity is not a positive whole number, the selection of partners is invalid or names a state the agents do not have, or feasible comes without a PartnerSpec.

See Also

PartnerSpec: Says how agents pick their partners. transfer: Moves a quantity between the two agents of a pair.

Examples:

>>> import numpy as np
>>> from types import SimpleNamespace
>>> from skcomplex.core.components.laws.utils import pairs
>>> buyers, sellers = [SimpleNamespace(id=k) for k in range(3)], [SimpleNamespace(id=k) for k in range(3, 5)]
>>> len(list(pairs(buyers, sellers, np.random.default_rng(0))))
2
Source code in src/skcomplex/core/components/laws/utils/_pairs.py
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
def pairs(
    left: Sequence[AgentViewProtocol],
    right: Sequence[AgentViewProtocol] | None,
    rng: np.random.Generator,
    pairing: Pairing | PartnerSpec | None = None,
    *,
    capacity: int = 1,
    feasible: Feasibility | None = None,
) -> Iterator[tuple[AgentViewProtocol, AgentViewProtocol]]:
    """Pair the agents of one or two groups, inside a rule.

    By default the agents pair uniformly at random, such as 2 pairs for 3 buyers and 2 sellers. A `PartnerSpec` picks
    partners within reach, by score, or among neighbours, and any other pairing, such as a stable matching or an
    auction, is a function `pairing(left, right, rng, capacity)` that returns the pairs. With `feasible`, the pairs come
    one at a time in a random order of agents, so a rule can settle each pair before the next one is checked. It matches
    workers with firms, buyers with sellers, birds with mates, and players with opponents.

    Read more in the user guide, under Agents.

    Args:
        left:
            The agents of the first group, as a rule reads them with `system.get_agents(path)`.

        right:
            The agents of the second group, or `None` for pairs within the first.

        rng:
            The random generator, such as `system.rng`.

        pairing:
            A `PartnerSpec`, a function of both groups that returns their pairs, or `None` for uniform random pairs.

        capacity:
            The largest number of pairs of every member, for random pairs and for a function.

        feasible:
            The function `feasible(agent, candidate)` that says whether an agent can pair with a candidate now, or
            `None`. It needs a `PartnerSpec`.

    Returns:
        pairs:
            The pairs of agents, the first of every pair from the first group.

    Raises:
        ValidationError:
            The capacity is not a positive whole number, the selection of partners is invalid or names a state the
            agents do not have, or `feasible` comes without a `PartnerSpec`.

    See Also:
        PartnerSpec: Says how agents pick their partners.
        transfer: Moves a quantity between the two agents of a pair.

    Examples:
        >>> import numpy as np
        >>> from types import SimpleNamespace
        >>> from skcomplex.core.components.laws.utils import pairs
        >>> buyers, sellers = [SimpleNamespace(id=k) for k in range(3)], [SimpleNamespace(id=k) for k in range(3, 5)]
        >>> len(list(pairs(buyers, sellers, np.random.default_rng(0))))
        2
    """
    if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 1:
        error_msg = f'The capacity of pairs must be a positive whole number, but it is {capacity!r}.'
        raise ValidationError(error_msg)
    right = left if right is None else right
    if feasible is not None:
        if not isinstance(pairing, PartnerSpec):
            error_msg = f'Pairs with `feasible` need a `PartnerSpec` as their pairing, but it is {pairing!r}.'
            raise ValidationError(error_msg)
        pairing._check()
        return _get_partners(pairing, left, right, rng, feasible)
    if pairing is None:
        return iter(_get_random_pairs(left, right, rng, capacity))
    if not isinstance(pairing, PartnerSpec):
        return iter(cast(list[tuple[AgentViewProtocol, AgentViewProtocol]], pairing(left, right, rng, capacity)))
    pairing._check()
    if (pairing.candidates, pairing.choice, pairing.capacity, pairing.fallback) == ('all', 'uniform', 1, None):
        return iter(_get_disjoint_pairs(left, right, rng))
    return iter(list(_get_partners(pairing, left, right, rng, None)))

periodic_guard(t, period, start=0.0, count=None)

Return an expression of time that crosses zero at periodic times.

It crosses zero once at every start + j * period for j from 0, count times or without end, and stays away from zero between those times and after the last one, such as periodic_guard(t, 2.0, count=2) that is 0 at times 0 and 2 only. A CrossingLaw with this guard and the direction 0 acts at every such time. It pays a dividend every quarter, harvests a crop every year, and gives a vaccine at fixed dates.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
t Expression

The time symbol, s.t in laws.

required
period float

The time between two crossings.

required
start float

The time of the first crossing.

0.0
count int | None

The number of crossings, or None for crossings without end.

None

Returns:

Name Type Description
guard Expression

The symbolic guard.

Raises:

Type Description
ValidationError

The period is not positive, or the count is not a positive whole number.

See Also

CrossingLaw: Acts where the guard crosses zero. pulse_train: Repeats a pulse at a period, for rates.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import periodic_guard
>>> t = var('t')
>>> guard = periodic_guard(t, 2.0, count=2)
>>> [round(float(guard.subs({t: time})), 6) for time in (0.0, 1.0, 2.0, 4.0)]
[0.0, 1.0, 0.0, -1.0]
Source code in src/skcomplex/core/components/laws/utils/_signals.py
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
def periodic_guard(t: Expression, period: float, start: float = 0.0, count: int | None = None) -> Expression:
    """Return an expression of time that crosses zero at periodic times.

    It crosses zero once at every `start + j * period` for `j` from 0, `count` times or without end, and stays away from
    zero between those times and after the last one, such as `periodic_guard(t, 2.0, count=2)` that is 0 at times 0 and
    2 only. A `CrossingLaw` with this guard and the direction 0 acts at every such time. It pays a dividend every
    quarter, harvests a crop every year, and gives a vaccine at fixed dates.

    Read more in the user guide, under Laws.

    Args:
        t:
            The time symbol, `s.t` in laws.

        period:
            The time between two crossings.

        start:
            The time of the first crossing.

        count:
            The number of crossings, or `None` for crossings without end.

    Returns:
        guard:
            The symbolic guard.

    Raises:
        ValidationError:
            The period is not positive, or the count is not a positive whole number.

    See Also:
        CrossingLaw: Acts where the guard crosses zero.
        pulse_train: Repeats a pulse at a period, for rates.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import periodic_guard
        >>> t = var('t')
        >>> guard = periodic_guard(t, 2.0, count=2)
        >>> [round(float(guard.subs({t: time})), 6) for time in (0.0, 1.0, 2.0, 4.0)]
        [0.0, 1.0, 0.0, -1.0]
    """
    if not period > 0:
        error_msg = f'The period of a periodic guard must be positive, but it is {period!r}.'
        raise ValidationError(error_msg)
    guard = where(t < start - period / 2, -1, sin(pi * (t - start) / period))
    if count is None:
        return guard
    if isinstance(count, bool) or not isinstance(count, int) or count < 1:
        error_msg = f'The count of a periodic guard must be a positive whole number or None, but it is {count!r}.'
        raise ValidationError(error_msg)
    last = count - SR(1) / 2
    return where(t > start + last * period, sin(pi * last), guard)

pulse(t, start, width, height=1.0)

Return a rectangular pulse of a width and a height that starts at a time.

It is height from start until start + width and 0 otherwise, such as pulse(t, 2, 1, 3) that is 3 at time 2.5 and 0 at time 3.5. It gives a single dose of a drug, a short shock to demand, and a burst of current into a neuron.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
t Expression

The time symbol, s.t in laws.

required
start float

The time the pulse starts.

required
width float

The duration of the pulse.

required
height float

The height of the pulse.

1.0

Returns:

Name Type Description
input Expression

The symbolic input.

See Also

pulse_train: Repeats a pulse at a period. step: Switches from 0 to a height and stays there.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import pulse
>>> t = var('t')
>>> [float(pulse(t, 2, 1, 3).subs({t: time})) for time in (1.5, 2.5, 3.5)]
[0.0, 3.0, 0.0]
Source code in src/skcomplex/core/components/laws/utils/_signals.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
def pulse(t: Expression, start: float, width: float, height: float = 1.0) -> Expression:
    """Return a rectangular pulse of a width and a height that starts at a time.

    It is `height` from `start` until `start + width` and 0 otherwise, such as `pulse(t, 2, 1, 3)` that is 3 at time 2.5
    and 0 at time 3.5. It gives a single dose of a drug, a short shock to demand, and a burst of current into a neuron.

    Read more in the user guide, under Laws.

    Args:
        t:
            The time symbol, `s.t` in laws.

        start:
            The time the pulse starts.

        width:
            The duration of the pulse.

        height:
            The height of the pulse.

    Returns:
        input:
            The symbolic input.

    See Also:
        pulse_train: Repeats a pulse at a period.
        step: Switches from 0 to a height and stays there.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import pulse
        >>> t = var('t')
        >>> [float(pulse(t, 2, 1, 3).subs({t: time})) for time in (1.5, 2.5, 3.5)]
        [0.0, 3.0, 0.0]
    """
    return where(both(t >= start, t < start + width), height, 0)

pulse_train(t, period, width, height=1.0, start=0.0, *, count=None)

Return a train of rectangular pulses repeated at a period.

A pulse of height lasting width starts at start and again every period, without end or count times, such as pulse_train(t, 10, 1) that is 1 at times 0.5 and 20.5 and 0 at time 5. It gives daily doses of a drug, the beats of a pacemaker, and the monthly payments of a loan.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
t Expression

The time symbol, s.t in laws.

required
period float

The time between the starts of pulses.

required
width float

The duration of every pulse.

required
height float

The height of every pulse.

1.0
start float

The time of the first pulse.

0.0
count int | None

The number of pulses, or None for a train that never ends.

None

Returns:

Name Type Description
input Expression

The symbolic input.

Raises:

Type Description
ValidationError

The count is not a positive whole number.

See Also

pulse: Gives a single pulse. periodic_guard: Crosses zero at periodic times, for crossing laws.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import pulse_train
>>> t = var('t')
>>> [float(pulse_train(t, 10, 1).subs({t: time})) for time in (0.5, 5, 20.5)]
[1.0, 0.0, 1.0]
Source code in src/skcomplex/core/components/laws/utils/_signals.py
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
def pulse_train(
    t: Expression,
    period: float,
    width: float,
    height: float = 1.0,
    start: float = 0.0,
    *,
    count: int | None = None,
) -> Expression:
    """Return a train of rectangular pulses repeated at a period.

    A pulse of `height` lasting `width` starts at `start` and again every `period`, without end or `count` times, such
    as `pulse_train(t, 10, 1)` that is 1 at times 0.5 and 20.5 and 0 at time 5. It gives daily doses of a drug, the
    beats of a pacemaker, and the monthly payments of a loan.

    Read more in the user guide, under Laws.

    Args:
        t:
            The time symbol, `s.t` in laws.

        period:
            The time between the starts of pulses.

        width:
            The duration of every pulse.

        height:
            The height of every pulse.

        start:
            The time of the first pulse.

        count:
            The number of pulses, or `None` for a train that never ends.

    Returns:
        input:
            The symbolic input.

    Raises:
        ValidationError:
            The count is not a positive whole number.

    See Also:
        pulse: Gives a single pulse.
        periodic_guard: Crosses zero at periodic times, for crossing laws.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import pulse_train
        >>> t = var('t')
        >>> [float(pulse_train(t, 10, 1).subs({t: time})) for time in (0.5, 5, 20.5)]
        [1.0, 0.0, 1.0]
    """
    if count is None:
        return where(both(t >= start, mod(t - start, period) < width), height, 0)
    if isinstance(count, bool) or not isinstance(count, int) or count < 1:
        error_msg = f'The count of a pulse train must be a positive whole number or None, but it is {count!r}.'
        raise ValidationError(error_msg)
    return where(both(t >= start, t < start + count * period, mod(t - start, period) < width), height, 0)

ramp(t, start, end, height=1.0)

Return an input that rises in a straight line from 0 to a height.

It is 0 before start, rises evenly to height at end, and stays there, such as ramp(t, 0, 10, 5) that is 2 at time 4. It phases in a subsidy, warms an oven to its setting, and raises the load on a bridge.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
t Expression

The time symbol, s.t in laws.

required
start float

The time the ramp starts.

required
end float

The time the ramp ends.

required
height float

The value after the ramp.

1.0

Returns:

Name Type Description
input Expression

The symbolic input.

See Also

step: Switches from 0 to a height at once.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import ramp
>>> t = var('t')
>>> [float(ramp(t, 0, 10, 5).subs({t: time})) for time in (-1, 4, 20)]
[0.0, 2.0, 5.0]
Source code in src/skcomplex/core/components/laws/utils/_signals.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
def ramp(t: Expression, start: float, end: float, height: float = 1.0) -> Expression:
    """Return an input that rises in a straight line from 0 to a height.

    It is 0 before `start`, rises evenly to `height` at `end`, and stays there, such as `ramp(t, 0, 10, 5)` that is 2 at
    time 4. It phases in a subsidy, warms an oven to its setting, and raises the load on a bridge.

    Read more in the user guide, under Laws.

    Args:
        t:
            The time symbol, `s.t` in laws.

        start:
            The time the ramp starts.

        end:
            The time the ramp ends.

        height:
            The value after the ramp.

    Returns:
        input:
            The symbolic input.

    See Also:
        step: Switches from 0 to a height at once.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import ramp
        >>> t = var('t')
        >>> [float(ramp(t, 0, 10, 5).subs({t: time})) for time in (-1, 4, 20)]
        [0.0, 2.0, 5.0]
    """
    return where(t < start, 0, where(t < end, height * (t - start) / (end - start), height))

reduce_axes(expression, axes)

Return the integral of an expression over some axes of a phase space.

At every position it sums the expression over the cells of the named axes, each weighted by its width, such as reduce_axes(f, ('v',)) for the density of particles of any speed. Laws read the result as the same value at every point of the summed axes. It gives the density of a gas from its speeds, the number of cells of all sizes, and the population of all ages.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states of a field on a phase space and the coordinates.

required
axes Sequence[str]

The names of the axes to integrate over, each cell weighted by its width.

required

Returns:

Name Type Description
integral Expression

The call reduce_axes(expression, *coordinates), which laws read as the same value along the summed axes.

See Also

moment: Integrates a power of the coordinates. integral_transform: Integrates against a kernel of two points.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import reduce_axes
>>> reduce_axes(var('f'), ('v',))
reduce_axes(f, _coordinate_v)
Source code in src/skcomplex/core/components/laws/utils/_phase.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
def reduce_axes(expression: object, axes: Sequence[str]) -> Expression:
    """Return the integral of an expression over some axes of a phase space.

    At every position it sums the expression over the cells of the named axes, each weighted by its width, such as
    `reduce_axes(f, ('v',))` for the density of particles of any speed. Laws read the result as the same value at every
    point of the summed axes. It gives the density of a gas from its speeds, the number of cells of all sizes, and the
    population of all ages.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states of a field on a phase space and the coordinates.

        axes:
            The names of the axes to integrate over, each cell weighted by its width.

    Returns:
        integral:
            The call `reduce_axes(expression, *coordinates)`, which laws read as the same value along the summed axes.

    See Also:
        moment: Integrates a power of the coordinates.
        integral_transform: Integrates against a kernel of two points.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import reduce_axes
        >>> reduce_axes(var('f'), ('v',))
        reduce_axes(f, _coordinate_v)
    """
    return REDUCE_AXES(SR(expression), *coordinates_of(axes))

reduction(function, expression, over=None, where=None)

Return a summary of the values of the members of a group by any function.

The function receives the array of the values of the selected members and returns one number, such as reduction(np.median, x) for the median of x over the group. It runs in Python, so a law that reads it runs in Python on the Numba backend too. It gives the median income of households, a quantile of the sizes of firms, and the spread of the opinions of voters.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
function Callable[[AnyArray], object]

The function of the one-dimensional array of the values of the members that where selects.

required
expression object

The value of one member, a symbolic expression.

required
over object

The group to reduce over, or None for the group the expression reads.

None
where object

A condition on each member, or None for every member.

None

Returns:

Name Type Description
reduction Expression

The reduction, a symbolic expression.

Raises:

Type Description
ValidationError

The function cannot be called.

See Also

total: Sums an expression over the members of a group. mean: Averages an expression over the members of a group.

Examples:

>>> import numpy as np
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import reduction
>>> reduction(np.median, var('x')).operator().name()
'reduction'
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
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
def reduction(
    function: Callable[[AnyArray], object],
    expression: object,
    over: object = None,
    where: object = None,
) -> Expression:
    """Return a summary of the values of the members of a group by any function.

    The function receives the array of the values of the selected members and returns one number, such as
    `reduction(np.median, x)` for the median of `x` over the group. It runs in Python, so a law that reads it runs in
    Python on the Numba backend too. It gives the median income of households, a quantile of the sizes of firms, and the
    spread of the opinions of voters.

    Read more in the user guide, under Laws.

    Args:
        function:
            The function of the one-dimensional array of the values of the members that `where` selects.

        expression:
            The value of one member, a symbolic expression.

        over:
            The group to reduce over, or `None` for the group the expression reads.

        where:
            A condition on each member, or `None` for every member.

    Returns:
        reduction:
            The reduction, a symbolic expression.

    Raises:
        ValidationError:
            The function cannot be called.

    See Also:
        total: Sums an expression over the members of a group.
        mean: Averages an expression over the members of a group.

    Examples:
        >>> import numpy as np
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import reduction
        >>> reduction(np.median, var('x')).operator().name()
        'reduction'
    """
    if not callable(function):
        error_msg = f'A reduction takes a function of the array of the values of the members, but got {function!r}.'
        raise ValidationError(error_msg)
    name = f'_reduction_{id(function)}'
    FUNCTIONS[name] = function
    condition = SR(1) if where is None else SR(where)
    return REDUCTIONS['reduction'](SR(expression), condition, var(name), _over_symbol(over))

relax(state, rules, stable, *, drive=(), activity=None, max_iterations=100000)

Return a state after a push and the rules that settle it until it is stable.

In one step of an UpdateLaw, the drive laws run once, then the rules run in turn again and again until stable holds, so a slow push and the fast cascade it starts fit in one step, such as relax(height, topple, stable, drive=grain) for a sandpile that gets one grain per step. Every cascade that changes the state is recorded as an event under the label of the update law, with its size, the number of member updates, its duration, the number of rounds, and its area, the number of distinct members updated. A member update is a member that changes in a round, or one that activity marks as active. It gives the avalanches of a sandpile, the spread of a forest fire after lightning, and the slips along a fault in an earthquake.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
state object

The symbol of the state on a lattice that the update law sets.

required
rules BaseLaw | Sequence[BaseLaw]

The law, or the laws applied in turn, that relax the state, such as local rules or array updates.

required
stable Callable[..., bool]

A function of the arrays of the targets of the rules, in lattice shape, that returns whether the state is stable.

required
drive BaseLaw | Sequence[BaseLaw]

The law, or the laws, applied once per step before the relaxation, such as local rules or array updates.

()
activity Callable[..., object] | None

A function of the arrays of the targets that returns a boolean array of the active members of a round, or None to count the members that change.

None
max_iterations int

The largest number of rounds in one step.

100000

Returns:

Name Type Description
relaxation Expression

The unevaluated relaxation, the value of an UpdateLaw of the state.

Raises:

Type Description
ValidationError

No rule settles the state, or a rule or a drive is not a law.

See Also

UpdateLaw: Sets the state to the relaxation once per step.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import UpdateLaw
>>> from skcomplex.core.components.laws.utils import relax
>>> burn = UpdateLaw(var('fire'), lambda fire, **kwargs: fire, arrays=True)
>>> relax(var('fire'), burn, lambda fire: True)
relax(fire)
Source code in src/skcomplex/core/components/laws/utils/_relaxations.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def relax(
    state: object,
    rules: BaseLaw | Sequence[BaseLaw],
    stable: Callable[..., bool],
    *,
    drive: BaseLaw | Sequence[BaseLaw] = (),
    activity: Callable[..., object] | None = None,
    max_iterations: int = 100_000,
) -> Expression:
    """Return a state after a push and the rules that settle it until it is stable.

    In one step of an `UpdateLaw`, the `drive` laws run once, then the `rules` run in turn again and again until
    `stable` holds, so a slow push and the fast cascade it starts fit in one step, such as
    `relax(height, topple, stable, drive=grain)` for a sandpile that gets one grain per step. Every cascade that changes
    the state is recorded as an event under the label of the update law, with its size, the number of member updates,
    its duration, the number of rounds, and its area, the number of distinct members updated. A member update is a
    member that changes in a round, or one that `activity` marks as active. It gives the avalanches of a sandpile, the
    spread of a forest fire after lightning, and the slips along a fault in an earthquake.

    Read more in the user guide, under Laws.

    Args:
        state:
            The symbol of the state on a lattice that the update law sets.

        rules:
            The law, or the laws applied in turn, that relax the state, such as local rules or array updates.

        stable:
            A function of the arrays of the targets of the rules, in lattice shape, that returns whether the state is
            stable.

        drive:
            The law, or the laws, applied once per step before the relaxation, such as local rules or array updates.

        activity:
            A function of the arrays of the targets that returns a boolean array of the active members of a round, or
            `None` to count the members that change.

        max_iterations:
            The largest number of rounds in one step.

    Returns:
        relaxation:
            The unevaluated relaxation, the value of an `UpdateLaw` of the state.

    Raises:
        ValidationError:
            No rule settles the state, or a rule or a drive is not a law.

    See Also:
        UpdateLaw: Sets the state to the relaxation once per step.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws import UpdateLaw
        >>> from skcomplex.core.components.laws.utils import relax
        >>> burn = UpdateLaw(var('fire'), lambda fire, **kwargs: fire, arrays=True)
        >>> relax(var('fire'), burn, lambda fire: True)
        relax(fire)
    """
    rules = (rules,) if isinstance(rules, BaseLaw) else tuple(rules)
    drive = (drive,) if isinstance(drive, BaseLaw) else tuple(drive)
    if not rules:
        error_msg = 'A relaxation has no rules to settle the state with. Give it an UpdateLaw.'
        raise ValidationError(error_msg)
    if not all(isinstance(law, BaseLaw) for law in (*rules, *drive)):
        error_msg = 'The rules and the drive of a relaxation must be laws, such as an UpdateLaw.'
        raise ValidationError(error_msg)
    spec = _RelaxationSpec(rules, stable, drive, activity, int(max_iterations))
    name = f'_relaxation_{id(spec)}'
    RELAXATIONS[name] = spec
    return RELAX(SR(state), var(name))

series(x, points, values, kind='linear')

Return a curve through given points, joined by lines or held as steps.

Between two points it draws a straight line, or holds the earlier value with kind='previous', and it keeps the first value before the first point and the last value after the last point, such as 2.5 at time 5 for series(t, [0, 10, 20], [0.0, 5.0, 1.0]). With the time s.t as the value it is an input that follows data, and with any other expression it is a lookup table, such as the table functions of system dynamics. It replays measured rainfall, maps food to fertility, and gives a tax rate by income.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The symbolic value the series reads, such as the time symbol s.t or a state.

required
points Sequence[float]

The increasing points of the data.

required
values Sequence[float]

The values at those points.

required
kind str

'linear' for linear interpolation, or 'previous' to hold every value until the next point.

'linear'

Returns:

Name Type Description
series Expression

The symbolic curve, nested choices on the value that every backend can run.

Raises:

Type Description
ValueError

The points do not increase, the lengths differ, or the kind is unknown.

See Also

ramp: Rises in a straight line between two times.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import series
>>> t = var('t')
>>> data = series(t, [0, 10, 20], [0.0, 5.0, 1.0])
>>> [float(data.subs({t: time})) for time in (-5, 5, 15, 30)]
[0.0, 2.5, 3.0, 1.0]
Source code in src/skcomplex/core/components/laws/utils/_signals.py
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
def series(x: object, points: Sequence[float], values: Sequence[float], kind: str = 'linear') -> Expression:
    """Return a curve through given points, joined by lines or held as steps.

    Between two points it draws a straight line, or holds the earlier value with `kind='previous'`, and it keeps the
    first value before the first point and the last value after the last point, such as 2.5 at time 5 for
    `series(t, [0, 10, 20], [0.0, 5.0, 1.0])`. With the time `s.t` as the value it is an input that follows data, and
    with any other expression it is a lookup table, such as the table functions of system dynamics. It replays measured
    rainfall, maps food to fertility, and gives a tax rate by income.

    Read more in the user guide, under Laws.

    Args:
        x:
            The symbolic value the series reads, such as the time symbol `s.t` or a state.

        points:
            The increasing points of the data.

        values:
            The values at those points.

        kind:
            `'linear'` for linear interpolation, or `'previous'` to hold every value until the next point.

    Returns:
        series:
            The symbolic curve, nested choices on the value that every backend can run.

    Raises:
        ValueError:
            The points do not increase, the lengths differ, or the kind is unknown.

    See Also:
        ramp: Rises in a straight line between two times.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import series
        >>> t = var('t')
        >>> data = series(t, [0, 10, 20], [0.0, 5.0, 1.0])
        >>> [float(data.subs({t: time})) for time in (-5, 5, 15, 30)]
        [0.0, 2.5, 3.0, 1.0]
    """
    value = SR(x)
    levels = [float(item) for item in values]
    points = [float(item) for item in points]
    if len(points) != len(levels) or not points or any(b <= a for a, b in itertools.pairwise(points)):
        error_msg = 'The points of a series must increase, and every point needs one value.'
        raise ValueError(error_msg)
    if kind not in {'linear', 'previous'}:
        error_msg = f"Unknown series kind {kind!r}. Use 'linear' or 'previous'."
        raise ValueError(error_msg)
    return where(value < points[0], levels[0], _search(value, points, levels, kind, (0, len(points) - 1)))

shift_member(expression, offset, *, boundary='periodic', fill=0.0)

Return an expression read at the member some places further along a group.

Member i reads the expression at member i + offset, such as shift_member(x, 1) - x for the difference to the next member. Past the ends, 'periodic' wraps around to close a ring, 'reflecting' mirrors the order so the last member reads itself for an offset of 1, and 'fixed' reads fill. An offset of 0 gives the expression itself. It links the masses of a chain of springs, the cars of a queue on a road, and the stages of a pipeline.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression Expression

An expression of the member symbols of one group.

required
offset int

The number of members along the group order, negative to read members behind.

required
boundary str

'periodic', 'reflecting', or 'fixed'.

'periodic'
fill float

The value read past the ends of a fixed boundary.

0.0

Returns:

Name Type Description
shifted Expression

The symbolic read at the offset member.

Raises:

Type Description
ValidationError

The offset is not a whole number or the boundary is unknown.

See Also

neighbors: Reduces over the neighbours of every member.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import shift_member
>>> x = var('x')
>>> shift_member(x, 1) - x
-x + shift_member(x, 1, 0, 0.0)
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def shift_member(expression: Expression, offset: int, *, boundary: str = 'periodic', fill: float = 0.0) -> Expression:
    """Return an expression read at the member some places further along a group.

    Member `i` reads the expression at member `i + offset`, such as `shift_member(x, 1) - x` for the difference to the
    next member. Past the ends, `'periodic'` wraps around to close a ring, `'reflecting'` mirrors the order so the last
    member reads itself for an offset of 1, and `'fixed'` reads `fill`. An offset of 0 gives the expression itself. It
    links the masses of a chain of springs, the cars of a queue on a road, and the stages of a pipeline.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the member symbols of one group.

        offset:
            The number of members along the group order, negative to read members behind.

        boundary:
            `'periodic'`, `'reflecting'`, or `'fixed'`.

        fill:
            The value read past the ends of a fixed boundary.

    Returns:
        shifted:
            The symbolic read at the offset member.

    Raises:
        ValidationError:
            The offset is not a whole number or the boundary is unknown.

    See Also:
        neighbors: Reduces over the neighbours of every member.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import shift_member
        >>> x = var('x')
        >>> shift_member(x, 1) - x
        -x + shift_member(x, 1, 0, 0.0)
    """
    if boundary not in BOUNDARIES or isinstance(offset, bool) or not isinstance(offset, numbers.Integral):
        error_msg = (
            f'shift_member takes a whole number of members and a boundary among {", ".join(BOUNDARIES)}, but '
            f'got the offset {offset!r} and the boundary {boundary!r}.'
        )
        raise ValidationError(error_msg)
    return SHIFT_MEMBER(expression, int(offset), BOUNDARIES.index(boundary), float(fill))

shifted(expression, offset, order=1)

Return a field read at a given distance from every site.

It reads the field at the point offset away from every site, with one distance per axis, and fills in between sites with a straight line or a cubic curve, such as shifted(u, [v, 1]) for the field at v along the first axis and 1 along the second. It moves a field back along a flow, reads the past position of a moving front, and shifts a population along an axis of age.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

An expression of the states and parameters of a field on a lattice.

required
offset Sequence[object]

The displacement along every axis, numbers or expressions of the states and parameters.

required
order int

The order of the spline that interpolates between sites, 1 for linear or 3 for cubic.

1

Returns:

Name Type Description
read Expression

The call shifted(expression, *offset), followed by the order when it is 3.

Raises:

Type Description
ValidationError

The order is not 1 or 3.

See Also

advection: Carries a field along with a velocity.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import shifted
>>> shifted(var('u'), [var('v'), 1])
shifted(u, v, 1)
Source code in src/skcomplex/core/components/laws/utils/_operators.py
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
def shifted(expression: object, offset: Sequence[object], order: int = 1) -> Expression:
    """Return a field read at a given distance from every site.

    It reads the field at the point `offset` away from every site, with one distance per axis, and fills in between
    sites with a straight line or a cubic curve, such as `shifted(u, [v, 1])` for the field at `v` along the first axis
    and 1 along the second. It moves a field back along a flow, reads the past position of a moving front, and shifts a
    population along an axis of age.

    Read more in the user guide, under Laws.

    Args:
        expression:
            An expression of the states and parameters of a field on a lattice.

        offset:
            The displacement along every axis, numbers or expressions of the states and parameters.

        order:
            The order of the spline that interpolates between sites, 1 for linear or 3 for cubic.

    Returns:
        read:
            The call `shifted(expression, *offset)`, followed by the order when it is 3.

    Raises:
        ValidationError:
            The order is not 1 or 3.

    See Also:
        advection: Carries a field along with a velocity.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import shifted
        >>> shifted(var('u'), [var('v'), 1])
        shifted(u, v, 1)
    """
    if order not in ORDERS:
        error_msg = f'The order of a shifted read is {order!r}. Use 1 for linear or 3 for cubic interpolation.'
        raise ValidationError(error_msg)
    orders = [SR(order)] if order != 1 else []
    return SHIFTED(SR(expression), *[SR(item) for item in offset], *orders)

shortest_paths(active, over=None, reduce='betweenness')

Return how central every member is on the shortest paths of active links.

A link joins two neighbours of a group, read in both directions, and it is active where active is not 0, as in components, such as shortest_paths(edges.up, reduce='closeness') for how close every member is to the others over the links that are up. The graph of active links is read again at every step, so the measure follows a network that changes during a run, and NetworkX computes it again only when the active links changed. It gives the load on the nodes of a power grid, the brokers of a trade network, and the hubs of a road network.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
active object

The activity of one link, an expression of the symbols of namespace.other, namespace, and the edge between them, whose links are active where it is not 0.

required
over BaseNeighborhood | LayerSpec | None

The neighbourhood, or None for the neighbours of the network or lattice the group lives on.

None
reduce str

What to give every member. 'betweenness' gives the number of shortest paths between other members that pass through it, each path counted as its share of the shortest paths of its pair, as networkx.betweenness_centrality(graph, normalized=False) gives it. 'closeness' gives the closeness of networkx.closeness_centrality(graph), scaled by the share of members it reaches.

'betweenness'

Returns:

Name Type Description
reduction Expression

The unevaluated reduction, one value per member.

Raises:

Type Description
ValidationError

The reduction is unknown.

See Also

components: Finds the clusters of the active links. neighbors: Reduces the values of the neighbours of every member.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import shortest_paths
>>> shortest_paths(var('up'), reduce='closeness')
shortest_paths(up, reduce='closeness')
Source code in src/skcomplex/core/components/laws/utils/_paths.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def shortest_paths(
    active: object,
    over: BaseNeighborhood | LayerSpec | None = None,
    reduce: str = 'betweenness',
) -> Expression:
    """Return how central every member is on the shortest paths of active links.

    A link joins two neighbours of a group, read in both directions, and it is active where `active` is not 0, as in
    `components`, such as `shortest_paths(edges.up, reduce='closeness')` for how close every member is to the others
    over the links that are up. The graph of active links is read again at every step, so the measure follows a network
    that changes during a run, and NetworkX computes it again only when the active links changed. It gives the load on
    the nodes of a power grid, the brokers of a trade network, and the hubs of a road network.

    Read more in the user guide, under Laws.

    Args:
        active:
            The activity of one link, an expression of the symbols of `namespace.other`, `namespace`, and the edge
            between them, whose links are active where it is not 0.

        over:
            The neighbourhood, or `None` for the neighbours of the network or lattice the group lives on.

        reduce:
            What to give every member. `'betweenness'` gives the number of shortest paths between other members that
            pass through it, each path counted as its share of the shortest paths of its pair, as
            `networkx.betweenness_centrality(graph, normalized=False)` gives it. `'closeness'` gives the closeness of
            `networkx.closeness_centrality(graph)`, scaled by the share of members it reaches.

    Returns:
        reduction:
            The unevaluated reduction, one value per member.

    Raises:
        ValidationError:
            The reduction is unknown.

    See Also:
        components: Finds the clusters of the active links.
        neighbors: Reduces the values of the neighbours of every member.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import shortest_paths
        >>> shortest_paths(var('up'), reduce='closeness')
        shortest_paths(up, reduce='closeness')
    """
    if reduce not in PathReductionKind:
        error_msg = f'Unknown shortest paths reduction {reduce!r}. Use one of {", ".join(PathReductionKind)}.'
        raise ValidationError(error_msg)
    return SHORTEST_PATHS(SR(active), _neighborhood_symbol(over), tuple(PathReductionKind).index(reduce))

sign(x)

Return the sign of an expression, 1 above 0, -1 below 0, and 0 at 0.

It gives the direction of a value without its size, such as -1, 0, and 1 for sign(x) at -2, 0, and 3, and its derivative is 0 away from 0, so solvers that need derivatives stay finite. It turns a field into the spin of a magnet, a signal into the side a trader takes, and a velocity into the direction of friction.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The expression.

required

Returns:

Name Type Description
value Expression

The symbolic sign.

See Also

clip: Limits an expression to an interval.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import sign
>>> x = var('x')
>>> [sign(x).subs(x=value) for value in (-2, 0, 3)]
[-1, 0, 1]
Source code in src/skcomplex/core/components/laws/utils/_pointwise.py
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
def sign(x: object) -> Expression:
    """Return the sign of an expression, 1 above 0, -1 below 0, and 0 at 0.

    It gives the direction of a value without its size, such as -1, 0, and 1 for `sign(x)` at -2, 0, and 3, and its
    derivative is 0 away from 0, so solvers that need derivatives stay finite. It turns a field into the spin of a
    magnet, a signal into the side a trader takes, and a velocity into the direction of friction.

    Read more in the user guide, under Laws.

    Args:
        x:
            The expression.

    Returns:
        value:
            The symbolic sign.

    See Also:
        clip: Limits an expression to an interval.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import sign
        >>> x = var('x')
        >>> [sign(x).subs(x=value) for value in (-2, 0, 3)]
        [-1, 0, 1]
    """
    return where(SR(x) > 0, 1, where(SR(x) < 0, -1, 0))

step(t, at, height=1.0)

Return a step input, 0 before a time and height from it on.

It switches a law on at the time at and keeps it on, such as step(t, 5, 2) that is 0 at time 4 and 2 at time 5. It opens a valve, raises a tax rate, and starts a dose of a drug.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
t Expression

The time symbol, s.t in laws.

required
at float

The time of the step.

required
height float

The height of the step.

1.0

Returns:

Name Type Description
input Expression

The symbolic input.

See Also

ramp: Rises from 0 to a height over an interval. pulse: Is on for an interval only.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import step
>>> t = var('t')
>>> [float(step(t, 5, 2).subs({t: time})) for time in (4, 5)]
[0.0, 2.0]
Source code in src/skcomplex/core/components/laws/utils/_signals.py
34
35
36
37
38
39
40
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
def step(t: Expression, at: float, height: float = 1.0) -> Expression:
    """Return a step input, 0 before a time and `height` from it on.

    It switches a law on at the time `at` and keeps it on, such as `step(t, 5, 2)` that is 0 at time 4 and 2 at time 5.
    It opens a valve, raises a tax rate, and starts a dose of a drug.

    Read more in the user guide, under Laws.

    Args:
        t:
            The time symbol, `s.t` in laws.

        at:
            The time of the step.

        height:
            The height of the step.

    Returns:
        input:
            The symbolic input.

    See Also:
        ramp: Rises from 0 to a height over an interval.
        pulse: Is on for an interval only.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import step
        >>> t = var('t')
        >>> [float(step(t, 5, 2).subs({t: time})) for time in (4, 5)]
        [0.0, 2.0]
    """
    return where(t >= at, height, 0)

stop_gradient(x)

Return an expression unchanged, but with a gradient of zero.

The value is the expression itself, and a gradient taken through it is 0, so x * stop_gradient(x) differentiates to stop_gradient(x). The JAX backend calls jax.lax.stop_gradient and every other backend gives the value as it is. The sum exact + relaxed - stop_gradient(relaxed) has the value of exact and the gradient of relaxed. It trains a network of spiking neurons, rounds the bids of a learned market, and fixes a target in reinforcement learning.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
x object

The expression the function reads.

required

Returns:

Name Type Description
value Expression

The symbolic value.

See Also

sign: Gives the sign of an expression, a common exact value.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import stop_gradient
>>> x = var('x')
>>> (x * stop_gradient(x)).diff(x)
stop_gradient(x)
Source code in src/skcomplex/core/components/laws/utils/_pointwise.py
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
def stop_gradient(x: object) -> Expression:
    """Return an expression unchanged, but with a gradient of zero.

    The value is the expression itself, and a gradient taken through it is 0, so `x * stop_gradient(x)` differentiates
    to `stop_gradient(x)`. The JAX backend calls `jax.lax.stop_gradient` and every other backend gives the value as it
    is. The sum `exact + relaxed - stop_gradient(relaxed)` has the value of `exact` and the gradient of `relaxed`. It
    trains a network of spiking neurons, rounds the bids of a learned market, and fixes a target in reinforcement
    learning.

    Read more in the user guide, under Laws.

    Args:
        x:
            The expression the function reads.

    Returns:
        value:
            The symbolic value.

    See Also:
        sign: Gives the sign of an expression, a common exact value.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import stop_gradient
        >>> x = var('x')
        >>> (x * stop_gradient(x)).diff(x)
        stop_gradient(x)
    """
    return STOP_GRADIENT(SR(x))

symmetric_part(tensor)

Return the symmetric part of a square matrix, (M + M^T) / 2.

It averages every entry with its mirror across the diagonal, such as [[0, a], [a, 0]] for [[0, 2a], [0, 0]]. Of the matrix of derivatives of a velocity it keeps the stretching and drops the spin. It gives the strain rate of a fluid, the strain of a solid, and the symmetric couplings of a network.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
tensor Matrix

A square matrix of expressions.

required

Returns:

Name Type Description
symmetric Matrix

The symmetric matrix.

Raises:

Type Description
TensorShapeError

The value is not a square matrix.

See Also

antisymmetric_part: Keeps the antisymmetric part instead.

Examples:

>>> from sage.all__sagemath_symbolics import SR, matrix, var
>>> from skcomplex.core.components.laws.utils import symmetric_part
>>> symmetric_part(matrix(SR, [[0, 2 * var('a')], [0, 0]]))
[0 a]
[a 0]
Source code in src/skcomplex/core/components/laws/utils/_tensors.py
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 symmetric_part(tensor: Matrix) -> Matrix:
    """Return the symmetric part of a square matrix, `(M + M^T) / 2`.

    It averages every entry with its mirror across the diagonal, such as `[[0, a], [a, 0]]` for `[[0, 2a], [0, 0]]`. Of
    the matrix of derivatives of a velocity it keeps the stretching and drops the spin. It gives the strain rate of a
    fluid, the strain of a solid, and the symmetric couplings of a network.

    Read more in the user guide, under Laws.

    Args:
        tensor:
            A square matrix of expressions.

    Returns:
        symmetric:
            The symmetric matrix.

    Raises:
        TensorShapeError:
            The value is not a square matrix.

    See Also:
        antisymmetric_part: Keeps the antisymmetric part instead.

    Examples:
        >>> from sage.all__sagemath_symbolics import SR, matrix, var
        >>> from skcomplex.core.components.laws.utils import symmetric_part
        >>> symmetric_part(matrix(SR, [[0, 2 * var('a')], [0, 0]]))
        [0 a]
        [a 0]
    """
    checked = _check_matrix('symmetric_part', tensor)
    return (checked + checked.transpose()) / 2

tensor_divergence(tensor)

Return the divergence of a matrix field, one sum of derivatives per row.

Entry i is the sum of partial(T_ij, j) over j, the net outflow of row i, such as the gradient of the pressure p for the matrix p I. It gives the force of the stress in a fluid or a solid, and the push that the crowding of cells exerts on a tissue.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
tensor Matrix

A square matrix of expressions.

required

Returns:

Name Type Description
divergence FreeModuleElement

One expression per row of the matrix.

Raises:

Type Description
TensorShapeError

The value is not a square matrix.

See Also

vector_gradient: Gives the matrix of derivatives of a vector field. divergence: Gives the divergence of a vector field.

Examples:

>>> from sage.all__sagemath_symbolics import SR, identity_matrix, var
>>> from skcomplex.core.components.laws.utils import tensor_divergence
>>> tensor_divergence(var('p') * identity_matrix(SR, 2))
(partial(p, 0), partial(p, 1))
Source code in src/skcomplex/core/components/laws/utils/_tensors.py
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 tensor_divergence(tensor: Matrix) -> FreeModuleElement:
    """Return the divergence of a matrix field, one sum of derivatives per row.

    Entry `i` is the sum of `partial(T_ij, j)` over `j`, the net outflow of row `i`, such as the gradient of the
    pressure `p` for the matrix `p I`. It gives the force of the stress in a fluid or a solid, and the push that the
    crowding of cells exerts on a tissue.

    Read more in the user guide, under Laws.

    Args:
        tensor:
            A square matrix of expressions.

    Returns:
        divergence:
            One expression per row of the matrix.

    Raises:
        TensorShapeError:
            The value is not a square matrix.

    See Also:
        vector_gradient: Gives the matrix of derivatives of a vector field.
        divergence: Gives the divergence of a vector field.

    Examples:
        >>> from sage.all__sagemath_symbolics import SR, identity_matrix, var
        >>> from skcomplex.core.components.laws.utils import tensor_divergence
        >>> tensor_divergence(var('p') * identity_matrix(SR, 2))
        (partial(p, 0), partial(p, 1))
    """
    rows = _check_matrix('tensor_divergence', tensor).rows()
    return vector(SR, [sum((_derivative(item, axis) for axis, item in enumerate(row)), SR(0)) for row in rows])

total(expression, over=None, where=None, weights=None, by=None)

Return the sum of an expression over the members of a group.

It is Σ_j a_j, or Σ_j W_ij a_j with weights, such as tanh(total(x)) for a response to the sum of x over the group, and where keeps only the members that meet a condition. Inside the call the values are those of the member being summed, and outside it those of the member that reads the sum. It gives the total input to a neuron, the demand of all buyers in a market, and the number of infected people a person meets.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The expression of one member, such as namespace.x or cos(namespace.members.theta).

required
over object

The namespace of the group to reduce over, such as namespace.members, or None for the group the expression reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None
weights object

A constant matrix, a NumPy array or a SciPy sparse matrix, with one row per reading member and one column per reduced member, a vector with one weight per reduced member that every reading member shares, or None.

None
by str | None

The name of a state of the group, so every member reduces over the members that share its value of the state, or None for all members. It needs the namespace of the group as over.

None

Returns:

Name Type Description
reduction Expression

The unevaluated reduction, which every backend lowers.

Raises:

Type Description
ValidationError

The group is not a namespace or a symbol, the weights are not a matrix, or by comes without the namespace of the group.

See Also

mean: Averages an expression over the members of a group. count: Counts the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import total
>>> x = var('x')
>>> total(x, where=x > 0.5)
total(x, where=x > 0.5)
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
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
def total(
    expression: object,
    over: object = None,
    where: object = None,
    weights: object = None,
    by: str | None = None,
) -> Expression:
    """Return the sum of an expression over the members of a group.

    It is `Σ_j a_j`, or `Σ_j W_ij a_j` with weights, such as `tanh(total(x))` for a response to the sum of `x` over the
    group, and `where` keeps only the members that meet a condition. Inside the call the values are those of the member
    being summed, and outside it those of the member that reads the sum. It gives the total input to a neuron, the
    demand of all buyers in a market, and the number of infected people a person meets.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The expression of one member, such as `namespace.x` or `cos(namespace.members.theta)`.

        over:
            The namespace of the group to reduce over, such as `namespace.members`, or `None` for the group the
            expression reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

        weights:
            A constant matrix, a NumPy array or a SciPy sparse matrix, with one row per reading member and one column
            per reduced member, a vector with one weight per reduced member that every reading member shares, or `None`.

        by:
            The name of a state of the group, so every member reduces over the members that share its value of the
            state, or `None` for all members. It needs the namespace of the group as `over`.

    Returns:
        reduction:
            The unevaluated reduction, which every backend lowers.

    Raises:
        ValidationError:
            The group is not a namespace or a symbol, the weights are not a matrix, or `by` comes without the namespace
            of the group.

    See Also:
        mean: Averages an expression over the members of a group.
        count: Counts the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import total
        >>> x = var('x')
        >>> total(x, where=x > 0.5)
        total(x, where=x > 0.5)
    """
    return _reduce('total', expression, over, where, weights, by=by)

transfer(source, sink, amount, state, sink_state=None)

Move an amount of a quantity from one agent to another inside a rule.

It subtracts amount from the value state of source and adds it to the value of sink, so the total over all agents stays the same, such as 4 units moving from a holding of 10 to a holding of 0. It is what a rule of an UpdateLaw calls for a flow that RateLaw({s.source.cash: -1, s.target.cash: +1}, f) states for a whole group. A negative holding is an amount the agent owes. It pays a seller, hands food from one ant to another, and moves charge between two cells.

Read more in the user guide, under Agents.

Parameters:

Name Type Description Default
source object

The agent the amount leaves, as the rule receives it.

required
sink object

The agent the amount enters.

required
amount float

The amount moved, negative to move it the other way.

required
state str

The state of the source that holds the quantity.

required
sink_state str | None

The state of the sink that holds the quantity, or None for state.

None

Raises:

Type Description
ValidationError

An agent has no such state.

See Also

UpdateLaw: Runs the rule that calls it.

Examples:

>>> from types import SimpleNamespace
>>> from skcomplex.core.components.laws.utils import transfer
>>> first, second = SimpleNamespace(level=10.0), SimpleNamespace(level=0.0)
>>> transfer(first, second, 4.0, 'level')
>>> first.level, second.level
(6.0, 4.0)
Source code in src/skcomplex/core/components/laws/utils/_agents.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def transfer(source: object, sink: object, amount: float, state: str, sink_state: str | None = None) -> None:
    """Move an amount of a quantity from one agent to another inside a rule.

    It subtracts `amount` from the value `state` of `source` and adds it to the value of `sink`, so the total over all
    agents stays the same, such as 4 units moving from a holding of 10 to a holding of 0. It is what a rule of an
    `UpdateLaw` calls for a flow that `RateLaw({s.source.cash: -1, s.target.cash: +1}, f)` states for a whole group. A
    negative holding is an amount the agent owes. It pays a seller, hands food from one ant to another, and moves charge
    between two cells.

    Read more in the user guide, under Agents.

    Args:
        source:
            The agent the amount leaves, as the rule receives it.

        sink:
            The agent the amount enters.

        amount:
            The amount moved, negative to move it the other way.

        state:
            The state of the source that holds the quantity.

        sink_state:
            The state of the sink that holds the quantity, or `None` for `state`.

    Raises:
        ValidationError:
            An agent has no such state.

    See Also:
        UpdateLaw: Runs the rule that calls it.

    Examples:
        >>> from types import SimpleNamespace
        >>> from skcomplex.core.components.laws.utils import transfer
        >>> first, second = SimpleNamespace(level=10.0), SimpleNamespace(level=0.0)
        >>> transfer(first, second, 4.0, 'level')
        >>> first.level, second.level
        (6.0, 4.0)
    """
    target = state if sink_state is None else sink_state
    for agent, name in ((source, state), (sink, target)):
        if not hasattr(agent, name):
            error_msg = f'The transfer of {amount} reads the state {name!r}, which the agent {agent!r} does not have.'
            raise ValidationError(error_msg)
    if source is sink and state == target:
        return
    source_value, sink_value = getattr(source, state), getattr(sink, target)
    setattr(source, state, source_value - amount)
    setattr(sink, target, sink_value + amount)

uniform(name, low=0, high=1)

Return a value drawn uniformly between two bounds at every step.

A new value between low and high is drawn at every step, every use of the same name in one element reads the same value within a step, and every member of a group draws its own, so uniform('u', 0, x) + uniform('u', 0, x) is twice one draw. It gives the random heading of a walker, the noise of a sensor, and the time a customer waits.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
name str

The name of the draw, a valid Python name.

required
low object

The lower bound, a number or an expression of states and parameters.

0
high object

The upper bound.

1

Returns:

Name Type Description
draw Expression

The symbolic draw.

Raises:

Type Description
ValidationError

The name is not a valid Python name.

See Also

normal: Draws from a normal distribution. draw: Draws from any distribution of scipy.stats.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import uniform
>>> x = var('x')
>>> uniform('u', 0, x) + uniform('u', 0, x)
2*uniform_u(0, x)
Source code in src/skcomplex/core/components/laws/utils/_draws.py
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
def uniform(name: str, low: object = 0, high: object = 1) -> Expression:
    """Return a value drawn uniformly between two bounds at every step.

    A new value between `low` and `high` is drawn at every step, every use of the same name in one element reads the
    same value within a step, and every member of a group draws its own, so `uniform('u', 0, x) + uniform('u', 0, x)` is
    twice one draw. It gives the random heading of a walker, the noise of a sensor, and the time a customer waits.

    Read more in the user guide, under Laws.

    Args:
        name:
            The name of the draw, a valid Python name.

        low:
            The lower bound, a number or an expression of states and parameters.

        high:
            The upper bound.

    Returns:
        draw:
            The symbolic draw.

    Raises:
        ValidationError:
            The name is not a valid Python name.

    See Also:
        normal: Draws from a normal distribution.
        draw: Draws from any distribution of `scipy.stats`.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import uniform
        >>> x = var('x')
        >>> uniform('u', 0, x) + uniform('u', 0, x)
        2*uniform_u(0, x)
    """
    return _call('uniform', name, (low, high))

variance(expression, over=None, where=None)

Return the variance of an expression over the selected members of a group.

It is the mean of the squared distance of every value from the mean, dividing by the number of members, or 0 when no member is selected, such as variance(x) for the spread of x over the group. It gives the spread of opinions in a society, the dispersion of prices in a market, and the diversity of traits in a population.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
expression object

The expression of one member.

required
over object

The namespace of the group to reduce over, or None for the group the expression reads.

None
where object

A condition on the reduced member that selects the members, or None for all members.

None

Returns:

Name Type Description
reduction Expression

The unevaluated reduction, 0 when no member is selected.

Raises:

Type Description
ValidationError

The group is not a namespace or a symbol.

See Also

mean: Averages an expression over the members of a group.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import variance
>>> variance(var('x'))
variance(x)
Source code in src/skcomplex/core/components/laws/utils/_reductions.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def variance(expression: object, over: object = None, where: object = None) -> Expression:
    """Return the variance of an expression over the selected members of a group.

    It is the mean of the squared distance of every value from the mean, dividing by the number of members, or 0 when no
    member is selected, such as `variance(x)` for the spread of `x` over the group. It gives the spread of opinions in a
    society, the dispersion of prices in a market, and the diversity of traits in a population.

    Read more in the user guide, under Laws.

    Args:
        expression:
            The expression of one member.

        over:
            The namespace of the group to reduce over, or `None` for the group the expression reads.

        where:
            A condition on the reduced member that selects the members, or `None` for all members.

    Returns:
        reduction:
            The unevaluated reduction, 0 when no member is selected.

    Raises:
        ValidationError:
            The group is not a namespace or a symbol.

    See Also:
        mean: Averages an expression over the members of a group.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import variance
        >>> variance(var('x'))
        variance(x)
    """
    return _reduce('variance', expression, over, where, None)

vector_gradient(velocity)

Return the matrix of the derivatives of every entry of a vector field.

Entry (i, j) is partial(v_i, j), the derivative of entry i of the vector along axis j, such as the four derivatives of [u, v] in a plane. It gives the shear of a flowing fluid, the strain of a deformed solid, and the rate at which a flock stretches.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
velocity Sequence[object] | FreeModuleElement

One expression per dimension.

required

Returns:

Name Type Description
gradient Matrix

The matrix of the derivative of every entry along every axis.

Raises:

Type Description
TensorShapeError

The value is not a vector.

See Also

tensor_divergence: Sums the derivatives of the rows of a matrix field. symmetric_part: Keeps the symmetric part of a matrix.

Examples:

>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws.utils import vector_gradient
>>> vector_gradient([var('u'), var('v')])
[partial(u, 0) partial(u, 1)]
[partial(v, 0) partial(v, 1)]
Source code in src/skcomplex/core/components/laws/utils/_tensors.py
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 vector_gradient(velocity: Sequence[object] | FreeModuleElement) -> Matrix:
    """Return the matrix of the derivatives of every entry of a vector field.

    Entry `(i, j)` is `partial(v_i, j)`, the derivative of entry `i` of the vector along axis `j`, such as the four
    derivatives of `[u, v]` in a plane. It gives the shear of a flowing fluid, the strain of a deformed solid, and the
    rate at which a flock stretches.

    Read more in the user guide, under Laws.

    Args:
        velocity:
            One expression per dimension.

    Returns:
        gradient:
            The matrix of the derivative of every entry along every axis.

    Raises:
        TensorShapeError:
            The value is not a vector.

    See Also:
        tensor_divergence: Sums the derivatives of the rows of a matrix field.
        symmetric_part: Keeps the symmetric part of a matrix.

    Examples:
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.core.components.laws.utils import vector_gradient
        >>> vector_gradient([var('u'), var('v')])
        [partial(u, 0) partial(u, 1)]
        [partial(v, 0) partial(v, 1)]
    """
    components = _check_vector('vector_gradient', velocity)
    size = len(components)
    return matrix(SR, [[_derivative(item, axis) for axis in range(size)] for item in components])