Laws
Define laws, the equations and rules that change the values of elements.
A law says how one value changes, such as RateLaw(s.ball.x.diff(s.t, 2), -s.g) for a falling ball, the next value
after a step, a random jump, or an equation the compiler solves. Interactions return laws in laws_, and the compiler
turns them into a problem that a solver runs. The specs here hold the settings that laws and their rules read.
BaseLaw()
dataclass
Bases: BaseSpec, ABC
An abstract law, one equation or rule that changes the values of elements.
A law says how a value changes, such as RateLaw(s.ball.x.diff(s.t, 2), -s.g) inside the interaction of a falling
ball, which gives the height x the acceleration -g. It is a frozen value, equal to any law of its class with the
same fields, and it is not added to a system on its own. An interaction returns its laws in laws_ when it is
prepared, and the compiler checks them and turns them into a problem that a solver runs. A subclass says which
values it changes, whether it needs continuous or discrete time, and its value at given values of the symbols it
reads. Its subclasses give the spread of an epidemic, the next generation of a cellular automaton, a chemical
reaction one molecule at a time, and the currents of a circuit.
Read more in the user guide, under Laws.
See Also
RateLaw: Adds a rate to a derivative of a value. UpdateLaw: Gives the next value after one step of discrete time. Interaction: Returns the laws of the elements its roles bind.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import BaseLaw, RateLaw
>>> n, r = var('n r')
>>> isinstance(RateLaw(n, r * n), BaseLaw), RateLaw(n, r * n) == RateLaw(n, r * n)
(True, True)
get_requirements()
classmethod
Return what the laws of the class require of a system before any law exists.
Returns:
| Name | Type | Description |
|---|---|---|
requirements |
RequirementSpec
|
The classes of time and of space the laws run in, where an empty field accepts any class. A law whose
arguments narrow them, such as an |
Examples:
>>> from skcomplex.core.components.laws import UpdateLaw
>>> UpdateLaw.get_requirements().space
()
Source code in src/skcomplex/core/components/laws/_base.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
CallSpec(function, arguments=(), relative=False, random=False, vectorized=False)
dataclass
Bases: BaseSpec
A spec of a law value that a Python function computes.
It hands the value of a law to a function, such as RateLaw(s.cell.n, CallSpec(growth, (s.cell.n,))) inside an
interaction, which calls growth(t, n) for the rate of every cell. The function runs once per member or pair and
returns a number for a scalar target, or one number per entry for a vector target. The Numba backend calls a
function that Numba compiles inside its own compiled loops, and the NumPy backend calls any function. A law that
sets relative, random, or vectorized runs in Python on every backend. It reads a measured input from a table,
asks a weather model for the rain on a crop, and runs a trained network for the force on a robot.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
object
|
The function |
required |
arguments
|
tuple[object, ...] | None
|
The symbolic expressions whose values are passed to the function, or |
()
|
relative
|
bool
|
Whether to pass the mapping with the names of the component of the law, such as |
False
|
random
|
bool
|
Whether to pass the random generator of the run as the keyword argument |
False
|
vectorized
|
bool
|
Whether to call the function once per evaluation with one array per argument, instead of once per member or pair. It returns one value, or one value per member or pair. |
False
|
See Also
RateLaw: Takes a call as its rate. EventLaw: Takes a call as the expression it watches.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import CallSpec, RateLaw
>>> n = var('n')
>>> RateLaw(n, CallSpec(lambda t, n: 2 * n, (n,))).value.arguments
(n,)
ConstraintLaw(lhs, rhs=None, *, target=None, label='')
dataclass
Bases: BaseLaw
A law that states an equation the compiler solves for derivatives of values.
It gives an equation in place of a rate, such as ConstraintLaw(s.l * s.theta.diff(s.t, 2), -s.g * sin(s.theta))
inside the interaction of a pendulum, which the compiler solves for the acceleration of the angle theta. The
equation holds the highest derivatives of its values linearly, as Newton's second law holds an acceleration, and
the compiler solves all the equations of a system together and adds the rate laws on the same values to the
solution. The values are functions of time, such as function('theta')(t). The equations of one target add into
one before the solve, so a component may add a term without a highest derivative, such as a coupling. In static
time it holds at the minimum of an ObjectiveLaw, where an inequality such as v <= upper bounds a value. The
swings of a double pendulum, the currents of a circuit, and the joints of a robot arm follow such equations.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lhs
|
object
|
The left side, or a Sage relation |
required |
rhs
|
object
|
The right side, or |
None
|
target
|
object
|
The value whose equation this is, so that the equations of one target add, or |
None
|
label
|
str
|
The name of the law, or the empty string for a law without one. |
''
|
See Also
RateLaw: Gives a derivative of a value directly. ObjectiveLaw: Gives a cost to make least, under the equations of the system.
Examples:
>>> from sage.all__sagemath_symbolics import function, sin, var
>>> from skcomplex.core.components.laws import ConstraintLaw
>>> t, g, l = var('t g l')
>>> theta = function('theta')(t)
>>> ConstraintLaw(l * theta.diff(t, 2), -g * sin(theta)).rhs
-g*sin(theta(t))
DatasetSpec(values, weights=None, times=None)
dataclass
Bases: BaseSpec
A spec of sequences of parameter values that a training run steps through.
It gives the inputs a nested system reads at every step of its training, such as DatasetSpec({'inputs.x': x})
with x of shape (sequences, steps, 1) for a recurrent network that reads one number per step. At step k of
sequence i every parameter takes its value at [i, k] before the laws of the step run, as a schedule sets a
parameter in a simulation, and the loss reads the values the step gives. Every sequence starts from the initial
values of the system. It holds the words of sentences for a language model, the daily prices for a forecast, and
the stimuli of a neural circuit.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Mapping[str, AnyArray]
|
A mapping from the dotted path of a parameter of the system, such as |
required |
weights
|
AnyArray | Mapping[str, AnyArray] | None
|
The weights of the steps in the loss and in every metric, an array of shape |
None
|
times
|
AnyArray | None
|
The times of the ends of the inner steps of a system of ordinary differential equations, one per step and
increasing from a positive time, since the run starts at time 0, or |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The values are empty, a path is not a string, or an array has fewer than two dimensions. |
See Also
TrainingInteraction: Trains the parameters of a nested system on the spec.
Examples:
>>> import numpy as np
>>> from skcomplex.core.components.laws import DatasetSpec
>>> data = DatasetSpec({'inputs.x': np.zeros((5, 12, 1))})
>>> data.sequences, data.steps
(5, 12)
sequences
property
Number of sequences, the length of the first axis of the first array.
steps
property
Number of inner steps of every sequence.
It is the length of the second axis of the first array.
DrawSpec(kind, name, distribution=None, keywords=(), arguments=(), call=None, temperature=None, hard=False)
dataclass
Bases: BaseSpec
A spec of a random draw in an expression, with its kind and its name.
The compiler finds the draws of a law and reads each as this spec, such as the spec of kind 'bernoulli' of
bernoulli('flip', 0.5) inside the update of a coin, which is 1 with probability one half at every step. A draw
from a distribution of scipy.stats, such as draw('wait', 'expon'), also holds the name of the distribution and
its keywords. With a temperature, a Bernoulli or categorical draw is replaced by a smooth draw that the JAX backend
can take derivatives through. It draws the flip of a coin, the waiting time of a customer, and the mutation of a
gene.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
required |
name
|
str
|
The name of the draw. |
required |
distribution
|
str | None
|
The name of the |
None
|
keywords
|
tuple[str, ...]
|
The keyword of every argument of a draw of kind |
()
|
arguments
|
tuple[Expression, ...]
|
The arguments of the distribution in a call, empty for the draw of a function. |
()
|
call
|
Expression | None
|
The symbolic call of the draw in the expression it was found in, or |
None
|
temperature
|
float | None
|
The temperature of the smooth draw that the JAX backend draws in place of a Bernoulli or categorical draw,
or |
None
|
hard
|
bool
|
Whether a draw with a temperature gives the exact value, and the derivatives of the smooth draw, on JAX. |
False
|
See Also
bernoulli: Returns a draw of 1 with a probability and 0 otherwise.
draw: Returns a draw from a distribution of scipy.stats.
Examples:
>>> from skcomplex.core.components.laws.utils import bernoulli
>>> from skcomplex.core.components.laws.utils._draws import draws_in
>>> draws_in(bernoulli('flip', 0.5))[0].kind
'bernoulli'
parameters
property
Arguments of a draw from a scipy.stats distribution by keyword.
EventLaw(guard, reset=None, direction=0, terminal=False, *, label='')
dataclass
Bases: BaseLaw
A law that sets values or ends the run when an expression crosses zero.
It watches an expression of the values and acts when it crosses zero, such as EventLaw(s.ball.x, {s.ball.v: -0.8 *
s.ball.v}, direction=-1) inside the interaction of a bouncing ball, which turns and slows the speed v when the
height x falls through zero. At the crossing the values of reset take their new values, or the run ends when
terminal is true. The solver finds the time of the crossing within its tolerance, which a step of an UpdateLaw
cannot, and the trajectory records every crossing with its time and the values before and after it. The rate laws
of the system stay as they are. A ball bounces off the floor, a neuron fires when its voltage reaches a threshold,
and a thermostat switches a heater at a set temperature.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guard
|
object
|
A symbolic expression of values and time whose crossing of zero sets off the event, a function
|
required |
reset
|
Mapping[Expression, object] | None
|
A mapping from the symbol of a value to its new value, all set at once, or |
None
|
direction
|
int
|
|
0
|
terminal
|
bool
|
Whether the crossing ends the run. |
False
|
label
|
str
|
The name of the crossing in the trajectory, or the empty string for the path of the element. |
''
|
See Also
JumpLaw: Changes values at random times. UpdateLaw: Gives the next value after one step of discrete time.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import EventLaw
>>> x, v = var('x v')
>>> EventLaw(x, {v: -0.8 * v}, direction=-1).reset
{v: -0.8*v}
JumpLaw(rate=None, changes=None, waiting=None, reset=None, *, label='')
dataclass
Bases: BaseLaw
A law of a random event that changes values by whole amounts.
It fires at random times and changes values at once, such as JumpLaw(s.beta * s.S * s.I, {s.S: -1, s.I: +1})
inside an interaction of an epidemic, where one person at a time moves from the susceptible S to the infected I
at the rate beta S I. With rate, the event fires at that rate, with exponential times between firings, and adds
changes to the values. With waiting, it fires after a waiting time drawn anew at every firing, sets the values
of reset, and the trajectory counts the firings of each member in <label>.renewals. Rate and noise laws move
the values between firings. Molecules react one at a time in a cell, people are born and die in a small
population, customers arrive at a queue, and a walker jumps between sites.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate
|
object
|
How often the event fires per unit of time, a symbolic expression, a |
None
|
changes
|
Mapping[Expression, object] | None
|
A mapping from the symbol of a scalar value to the number it adds when the event fires. In a law of a
group, a key may also be the value of the member at an offset, |
None
|
waiting
|
object
|
The time until the next firing, usually a draw from a distribution of positive numbers, such as
|
None
|
reset
|
Mapping[Expression, object] | None
|
With a waiting time, a mapping from the symbol of a value to its new value, which may hold draws, or
|
None
|
label
|
str
|
The name of the event, such as |
''
|
See Also
RateLaw: Changes a value smoothly at a rate. EventLaw: Sets values when an expression crosses zero.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import JumpLaw
>>> S, I, beta = var('S I beta')
>>> JumpLaw(beta * S * I, {S: -1, I: 1}, label='infection').changes
{S: -1, I: 1}
LinearObjectiveSpec(expression, sense='max')
dataclass
Bases: BaseSpec
A spec of the cost of a linear program, to make least or greatest.
The compiler builds it from an ObjectiveLaw whose value is linear in its targets, such as
LinearObjectiveSpec(-v_growth, sense='min') for the greatest growth of a cell, and a linear program makes its
expression least or greatest under the constraints of the system. The expression is linear in the variables of
the program or a sum of their absolute values. It finds the fluxes of a cell at its greatest growth, the cheapest
dispatch of power plants, and the plan of a factory of greatest profit.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
object
|
The objective, a symbolic expression of the variables of the program. |
required |
sense
|
str
|
|
'max'
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The sense is unknown, raised when its owner checks it. |
See Also
ObjectiveLaw: Gives a cost of values, which the system makes least.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import LinearObjectiveSpec
>>> LinearObjectiveSpec(2 * var('v'), sense='min').sense
'min'
LinearRuleSpec(coefficients, field='GF(2)')
dataclass
Bases: BaseSpec
A spec of a local rule that adds the values of the neighbours with coefficients.
It gives the next value of a cell as sum_s a_s x(g s) over its neighbours s with the coefficients a_s,
counted in a finite field or in the rationals, such as LinearRuleSpec((1, 1)) with the left and right neighbours
of a cell for rule 90, where every cell becomes the sum modulo 2 of its two neighbours. Over the group ring K[G]
the rule is the element sum_s a_s s, so the algebra of the ring describes the patterns it makes. Rule 90 draws a
Sierpinski triangle, linear codes spread errors, and additive automata draw the stripes of seashells.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficients
|
Sequence[float]
|
The coefficient of every neighbour, in neighbourhood order, integers or rationals. |
required |
field
|
str
|
|
'GF(2)'
|
See Also
TotalisticSpec: A local rule given by the sum of the neighbours. UpdateLaw: Takes the spec as the value of a local rule.
Examples:
>>> from skcomplex.core.components.laws import LinearRuleSpec
>>> LinearRuleSpec((1, 1), 'GF(3)').characteristic
3
characteristic
property
Characteristic of the field, 0 for the rationals.
sage_field
property
Sage field of the coefficients.
MoveSpec(target, kind='flip', values=(), width=0.0, function=None)
dataclass
Bases: BaseSpec
A spec of the change a Monte Carlo sweep proposes for the value of a site.
A MetropolisSolver with moves builds it for the value of every site of a lattice, such as
MoveSpec(s.magnet.spin, 'flip'), which proposes to turn a spin from 1 to -1, and its SamplerSpec keeps or
rejects the change. A move flips a value, draws one of a list of values, adds a uniform or a normal number, calls a
function, or flips a whole cluster at once. It flips the spins of a magnet, changes the opinions of voters, and
turns the letters of a sequence of DNA.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
object
|
The symbol of the value of a lattice that the move changes. |
required |
kind
|
str
|
|
'flip'
|
values
|
tuple[float, ...]
|
The values a random-value move draws from. |
()
|
width
|
float
|
The largest change of a rotation, or the standard deviation of a Gaussian move. |
0.0
|
function
|
Callable[..., object] | None
|
The function |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The kind of move is unknown, or a function move has no callable function. |
See Also
SamplerSpec: Keeps or rejects the moves of a sweep. ObjectiveSpec: The cost of one site that a move changes.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import MoveSpec
>>> MoveSpec(var('color'), 'random-value', values=(0.0, 1.0, 2.0)).values
(0.0, 1.0, 2.0)
NoiseLaw(target, value, *, convention='ito', process=None, conserved=False, hurst=None, label='')
dataclass
Bases: BaseLaw
A law that adds a random change to a time derivative of a value.
It shakes a value at random in continuous time, adding value dW to the derivative it targets, where dW is the
random step of a Wiener process over a time step, such as NoiseLaw(s.stock.p, s.stock.sigma * s.stock.p) for the
random moves of a stock price. A RateLaw on the same value gives the mean change, and together they form a
stochastic differential equation. Every member and every entry of a vector draws its own random steps, unless laws
name the same process and share them. A conserved noise on a lattice moves amounts between neighbouring sites, so
the total stays the same, and a Hurst index makes the steps remember the past, as in a fractional Brownian motion.
A stock price moves at random, a particle diffuses in a fluid, molecules shake the expression of a gene, and
turbulence stirs the temperature of a fluid.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Target
|
The symbol of a scalar value, a derivative of it such as |
required |
value
|
object
|
The size of the random change, a symbolic expression, a |
required |
convention
|
str
|
How the random change reads the value it changes, |
'ito'
|
process
|
Process
|
|
None
|
conserved
|
bool
|
Whether the noise moves amounts between neighbouring sites of a lattice, with random steps of its own on every link, so the total of the field changes only by its rate laws. |
False
|
hurst
|
object
|
The Hurst index |
None
|
label
|
str
|
The name of the law, or the empty string for a law without one. |
''
|
See Also
RateLaw: Adds the mean change to a derivative of a value. WienerProcessSpec: Random steps that several interactions share.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import NoiseLaw
>>> p, sigma = var('p sigma')
>>> NoiseLaw(p, sigma * p, process='market').value
p*sigma
ObjectiveLaw(value, targets=None, *, controls=None, terminal=0, active=None, infeasible='raise', duals=False, label='')
dataclass
Bases: BaseLaw
A law that gives a cost of values, which the system makes least.
It gives a cost that the system makes least, such as ObjectiveLaw(s.k * s.spring.x**2 / 2 - s.f * s.spring.x,
s.spring.x) inside the interaction of a loaded spring, which finds the stretch x = f / k of least energy. The
costs of several laws add up, and the constraint laws of the system hold at the minimum. A cost linear in its
targets is solved as a linear program with the constraint laws that read them, at every time of a run, and a
sequence of costs is made least in order, each minimum held while the next is sought. With controls, the law
steers values over a run instead, and makes least the integral of the cost plus the cost at the end, while the
rate laws move the values. A cost to make greatest, such as a profit, is made least with its sign changed. A loaded
structure rests at its least energy, a cell routes its fluxes to its greatest growth, a model takes the weights of
its least loss, and a health authority times a vaccination campaign at the least cost.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
object
|
The scalar symbolic expression to minimise, or a sequence of them linear in the targets, minimised in order. |
required |
targets
|
object
|
The symbol of a value, or the symbols of the values, that the minimum is sought over, or |
None
|
controls
|
Sequence[object] | None
|
The symbols of the values the law steers over a run, or |
None
|
terminal
|
object
|
With controls, the cost at the end of the run, a symbolic expression or a number. |
0
|
active
|
object
|
For a linear value, a condition under which the minimum is sought, such as |
None
|
infeasible
|
str
|
For a linear value, what a run does when the constraints cannot all hold, |
'raise'
|
duals
|
bool
|
For a linear value, whether a run records the dual value of each constraint, under |
False
|
label
|
str
|
The name of the law, or the empty string for a law without one. |
''
|
See Also
ConstraintLaw: States an equation or a bound that holds at the minimum. UpdateLaw: Gives the next value after one step, such as one step of a descent.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import ObjectiveLaw
>>> x, k, f = var('x k f')
>>> ObjectiveLaw(k * x**2 / 2 - f * x, x).targets
x
ObjectiveSpec(expression, over)
dataclass
Bases: BaseSpec
A spec of the cost of one site of a lattice, which a Monte Carlo move changes.
It holds every term of the total cost that reads the value of the site, such as ObjectiveSpec(-J * s.spin *
neighbors(s.spin), around) for a magnet, where neighbours that point the same way lower the energy. The change of
a move is the cost at the proposed value less the cost at the current value. The expression reads the neighbours
with neighbors(..., reduce='each') in the order of the neighbourhood, or their sum with neighbors(...,
reduce='sum'). It gives the energy of a spin in a magnet, the discomfort of a resident among unlike neighbours,
and the cost of a letter in a sequence of DNA.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
object
|
The local objective, a symbolic expression of the states of the site, its neighbours, and parameters. |
required |
over
|
object
|
The neighbourhood that |
required |
See Also
MoveSpec: The change of a site that a sweep proposes. ObjectiveLaw: Gives the total cost that the compiler splits into sites.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.spaces import RadiusNeighborhood
>>> from skcomplex.core.components.laws import ObjectiveSpec
>>> spin, J = var('spin J')
>>> ObjectiveSpec(-J * spin, RadiusNeighborhood(1, metric='manhattan')).expression
-J*spin
OuterTotalisticSpec(rule, default=0.0, states=2)
dataclass
Bases: BaseSpec
A spec of a local rule of the value of a cell and the sum of its neighbours.
It gives the next value of a cell from its own value and the sum of the values of its neighbours, such as the Game
of Life, OuterTotalisticSpec({(0, 3): 1, (1, 2): 1, (1, 3): 1}) with neighborhood=MOORE, where a dead cell with
three live neighbours comes alive and a live cell with two or three stays alive. The rule is a mapping from the
pair of the value and the sum to the next value, or a function of the arrays of values and sums. It runs the Game
of Life, the spread of a forest fire, and the waves of a beating heart.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule
|
Mapping[tuple[int, int], float] | Callable[[IntArray, IntArray], ArrayLike]
|
A mapping from the pair |
required |
default
|
float
|
The next value of pairs a mapping leaves out. |
0.0
|
states
|
int
|
The number of values of a cell, |
2
|
See Also
TotalisticSpec: A local rule of the sum of the neighbours alone. UpdateLaw: Takes the spec as the value of a local rule.
Examples:
>>> from skcomplex.core.components.laws import OuterTotalisticSpec
>>> life = OuterTotalisticSpec({(0, 3): 1, (1, 2): 1, (1, 3): 1})
>>> life.rule[(0, 3)], life.default
(1, 0.0)
PartnerSpec(candidates='all', choice='uniform', fallback=None, capacity=None, score=None)
dataclass
Bases: BaseSpec
A spec of how agents choose partners, by reach, choice, fallback, and capacity.
It says whom every agent of one side pairs with among the agents of the other side, such as
PartnerSpec('reach', fallback='nearest') for people who eat at a restaurant within their reach, or at the
nearest one when none is. Every agent picks among its candidates that still have room. With a capacity the agents
act in random order, since the first to act take the room, and without one they act in their order. A capacity of
1 with every agent as a candidate and a uniform choice draws random pairs with no agent in two of them. It matches
workers to firms, buyers to sellers, and people to restaurants.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidates
|
str | float
|
The agents an agent considers, |
'all'
|
choice
|
str
|
How an agent picks among its candidates, |
'uniform'
|
fallback
|
str | None
|
The partner of an agent without candidates, |
None
|
capacity
|
str | float | None
|
The largest number of pairs of an agent in one step, a number, the name of a state of the agent that holds
it, or |
None
|
score
|
Preference | None
|
The function |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The choice or the fallback is unknown, the distance or the capacity is not positive, or the score does not fit the choice, raised when its owner checks it. |
See Also
pairs: Returns the pairs of two groups that the spec chooses.
Examples:
>>> from skcomplex.core.components.laws import PartnerSpec
>>> PartnerSpec(candidates='reach', fallback='nearest').candidates
'reach'
RateLaw(target, value, *, label='')
dataclass
Bases: BaseLaw
A law that adds a rate to a time derivative of a value.
It says how fast a value changes in continuous time, such as RateLaw(s.ball.x.diff(s.t, 2), -s.g) inside the
interaction of a falling ball, which gives the height x the acceleration -g. A rate on x is its first
derivative, and a rate on x.diff(t, k) is its derivative of order k. Rates on the same value add up, so each
cause of a change writes its own law, and a system of rate laws alone is a system of ordinary differential
equations. A flow moves an amount between two stocks and maps each stock to the sign of its change, such as
RateLaw({s.alive: -1, s.dead: +1}, f, label='deaths'), where f leaves the living and enters the dead. Infected
people recover at a rate, a balance grows by interest, a reactant is used up by a reaction, and a pendulum swings
under gravity.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Target | Matrix | Mapping[Expression, int]
|
The symbol of a scalar value, a derivative of it such as |
required |
value
|
object
|
A symbolic expression, a matrix of the shape of a tensor value, a |
required |
label
|
str
|
The name of a flow, which the trajectory records under the element of its stocks, such as
|
''
|
See Also
NoiseLaw: Adds a random change to a derivative of a value. UpdateLaw: Gives the next value after one step of discrete time. ConstraintLaw: States an equation that the compiler solves for the derivatives.
Examples:
>>> from sage.all__sagemath_symbolics import function, var
>>> from skcomplex.core.components.laws import RateLaw
>>> t, g = var('t g')
>>> x = function('x')(t)
>>> RateLaw(x.diff(t, 2), -g).value
-g
RequirementSpec(time=(), space=(), sites=False)
dataclass
Bases: BaseSpec
A spec of the time and the space that a law needs of a system.
It names the classes of time and of space a law runs in, such as the continuous time of RateLaw.get_requirements()
or the discrete time of an UpdateLaw, and an empty field accepts any class. A law class returns it before any law
exists, so a system can say which laws fit its time and its space. With sites, a law that reads sites also runs
on any other space with sites, such as the graph of a group that a system package defines. A chemical reaction
needs continuous time, a cellular automaton a lattice, and a voter model any space of sites.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time
|
tuple[type, ...]
|
The classes of time the law runs in, such as continuous time alone. |
()
|
space
|
tuple[type, ...]
|
The classes of space the law runs in, such as |
()
|
sites
|
bool
|
Whether the law also runs on any other space with sites. |
False
|
See Also
BaseLaw: Returns the spec of its class from get_requirements.
Examples:
>>> from skcomplex.core.components.laws import RequirementSpec
>>> from skcomplex.core.components.spaces import LatticeSpace
>>> needs = RequirementSpec(space=(LatticeSpace,), sites=True)
>>> needs.sites, needs.time
(True, ())
SamplerSpec(kind='metropolis', intensity=1.0, schedule='checkerboard')
dataclass
Bases: BaseSpec
A spec of the rule that keeps or rejects the moves of a Monte Carlo sweep.
It decides whether a proposed move of a site is kept, from the change d of the cost of the site at an intensity,
such as SamplerSpec('metropolis', s.beta) for a magnet at the inverse temperature beta, which always keeps a
move that lowers the energy and keeps one that raises it with probability exp(-beta d). It sweeps the lattice
once per unit of time, in the order of schedule. It samples the spins of a magnet, the letters of a sequence of
DNA, and the opinions of a population at a level of noise.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
'metropolis'
|
intensity
|
object
|
The intensity, usually a parameter symbol so that it changes live. |
1.0
|
schedule
|
str
|
|
'checkerboard'
|
See Also
MoveSpec: The change of a site that a sweep proposes.
Examples:
>>> from skcomplex.core.components.laws import SamplerSpec
>>> SamplerSpec('glauber', 2.0).schedule
'checkerboard'
TableSpec(mapping, default=0.0, states=None)
dataclass
Bases: BaseSpec
A spec of a local rule given by the next value of every pattern of neighbours.
It lists the next value of a cell for every pattern of the values of its neighbours, in the order of the
neighbourhood, such as rule 30, TableSpec({(1, 0, 0): 1, (0, 1, 1): 1, (0, 1, 0): 1, (0, 0, 1): 1}), where a cell
reads its left neighbour, itself, and its right neighbour. Patterns the mapping leaves out take default, and the
values run from 0 to states - 1. It runs the elementary automata, draws the patterns of seashells, and makes
the random numbers of rule 30.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[tuple[int, ...], float]
|
A mapping from a pattern, a tuple of values in the order of the neighbourhood, to the next value. |
required |
default
|
float
|
The next value of patterns the mapping leaves out. |
0.0
|
states
|
int | None
|
The number of values of a cell, or |
None
|
See Also
TotalisticSpec: A local rule of the sum of the neighbours. UpdateLaw: Takes the spec as the value of a local rule.
Examples:
>>> from skcomplex.core.components.laws import TableSpec
>>> rule30 = TableSpec({(1, 0, 0): 1, (0, 1, 1): 1, (0, 1, 0): 1, (0, 0, 1): 1})
>>> rule30.n_states, rule30.default
(2, 0.0)
n_states
property
Number of state values.
It is the given states or one more than the largest value in the patterns, at least 2.
TopologyRequestSpec(kind, edges=1, toward=None, keep='source', layer=None, values=(), hyperedge=None, independent=False, direction='out', candidates=1, score=None, one=False, inherit=1.0, parent=0.0)
dataclass
Bases: BaseSpec
A spec of a change of a network, such as a new edge, that a law requests.
It is the target of a law that changes a network as it runs, such as UpdateLaw(TopologyRequestSpec('rewire'),
0.1) inside an interaction on the edges of a network, which moves one end of every edge with probability 0.1 at
every step. The value of an UpdateLaw is the chance that the request fires at every step for the member or edge
the law runs for, and JumpLaw(rate, {request: 1}) fires it at a rate. The requests that fire apply after the
step, in the order of the members and edges, and add or remove the members of the groups on the nodes, the edges,
or the hyperedges of the network. New ends are drawn among the nodes present that are not yet joined to the node,
with weights toward. Friends make and drop ties, a web page draws links in proportion to the links it has, and a
gene is copied in the network of the proteins of a cell.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
required |
edges
|
int
|
The number of edges a new node or a node adding edges joins to other nodes. |
1
|
toward
|
Callable[[SimpleNamespace], object] | None
|
A function of the namespace of a candidate node that returns its weight for a new end, such as
|
None
|
keep
|
str
|
The end of an edge that a rewiring keeps, |
'source'
|
layer
|
str | None
|
The layer whose edges the request changes, or |
None
|
values
|
tuple[tuple[str, object], ...]
|
The initial values of a new node or edge as pairs of a name and a value, or a function of the random generator that draws the value for every new node or edge, or nothing for the defaults of its element. |
()
|
hyperedge
|
int | None
|
The size of the hyperedge a new node or the node of |
None
|
independent
|
bool
|
Whether every candidate node becomes a new end on its own with the probability |
False
|
direction
|
str
|
The direction of the new edges of a node on a directed layer: |
'out'
|
candidates
|
int
|
The number of candidate edges an |
1
|
score
|
Callable[[SimpleNamespace], object] | None
|
A function of the namespace of a candidate end that returns the score of its edge, which reads the other
end as |
None
|
one
|
bool
|
Whether the request runs at every step for one member drawn uniformly among the members present, in place of every member. |
False
|
inherit
|
float
|
The probability that the copy of |
1.0
|
parent
|
float
|
The probability that the copy of |
0.0
|
See Also
UpdateLaw: Fires the request with a chance at every step. JumpLaw: Fires the request at a rate.
Examples:
>>> from skcomplex.core.components.laws import TopologyRequestSpec, UpdateLaw
>>> UpdateLaw(TopologyRequestSpec('rewire', keep='target'), 0.1).target.keep
'target'
TotalisticSpec(rule, default=0.0, states=2)
dataclass
Bases: BaseSpec
A spec of a local rule given by the next value of every sum of neighbours.
It gives the next value of a cell from the sum of the values of its neighbours alone, such as
TotalisticSpec(lambda total: total % 2) with a neighbourhood that holds the cell, where a cell becomes 1 when an
odd number of the cells around it, itself included, are 1. The rule is a mapping from the sum to the next value,
or a function of the array of sums, and the values run from 0 to states - 1. It runs a majority vote of
neighbours, the growth of a crystal, and the spread of a rumour.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule
|
Mapping[int, float] | Callable[[IntArray], ArrayLike]
|
A mapping from sum to next value, or a function of the sums that returns the next values. |
required |
default
|
float
|
The next value of sums a mapping leaves out. |
0.0
|
states
|
int
|
The number of values of a cell, |
2
|
See Also
OuterTotalisticSpec: A local rule of the value of a cell and the sum of its neighbours. UpdateLaw: Takes the spec as the value of a local rule.
Examples:
>>> from skcomplex.core.components.laws import TotalisticSpec
>>> TotalisticSpec(lambda total: total > 4).states
2
UpdateLaw(target, value, *, label='', increment=False, source=None, order=None, phase=None, neighborhood=None, reads=None, schedule=None, score=None, arrays=False, stochastic=False)
dataclass
Bases: BaseLaw
A law that gives what a value becomes after one step of discrete time.
It says what a value becomes at the next step, such as UpdateLaw(s.insects.x, s.insects.r * s.insects.x * (1 -
s.insects.x)) inside the interaction of a logistic map, where a population of insects grows and crowds itself out
from year to year. Every update reads the values and the time at the start of the step, so the order of the laws
does not matter. A value takes one update law, unless each of its laws says how it combines with the others, by
increment or by source. With neighborhood, the law is a local rule that reads the neighbours of every cell of
a lattice or node of a network, such as the Game of Life, and with arrays, a function of the whole array changes
every member at once. Its target may also be a group, whose members each run a rule rule(agent, system) that may
add and remove members, or a TopologyRequestSpec, whose value is the chance that the network changes. A
population breeds from year to year, a cellular automaton steps its cells, an account earns interest every month,
and a player revises a strategy every round.
Read more in the user guide, under Laws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Target | tuple[Target, ...] | TopologyRequestSpec | SimpleNamespace
|
The symbol of a scalar value, the column of symbols of a vector value, a |
required |
value
|
object
|
A symbolic expression, a |
required |
label
|
str
|
The name of the law, or the empty string for a law without one. |
''
|
increment
|
bool
|
Whether the value is the value plus a change, such as |
False
|
source
|
float | None
|
The value the law moves members from, such as |
None
|
order
|
object
|
A symbolic expression of the values, parameters, and draws of a member, such as a random number, whose
values order the members that update one after the other, each reading the values set before it, or
|
None
|
phase
|
str | None
|
The name of the phase of the step the law runs in, which a |
None
|
neighborhood
|
BaseNeighborhood | None
|
The ordered neighbours of every cell that a local rule reads, such as
|
None
|
reads
|
Sequence[Target] | None
|
The values whose neighbours a local rule reads, or |
None
|
schedule
|
str | None
|
The order in which a local rule updates the cells, or |
None
|
score
|
Callable[..., object] | None
|
A function |
None
|
arrays
|
bool
|
Whether the value is a NumPy function of the whole array of the value, shaped like the lattice or with one row per member, which replaces the value of every member at once. |
False
|
stochastic
|
bool
|
Whether the function of a local rule or of a whole array draws numbers. Its keyword |
False
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The value is a NumPy array, an increment law has a source, a local rule has a neighbourhood that is no
neighbourhood, an unknown schedule, or a setting of a law of one member, a law has a score but no function
of the whole array, |
See Also
RateLaw: Adds a rate to a derivative of a value in continuous time. TopologyRequestSpec: A change of a network that an update law may request. TotalisticSpec: A local rule given by the sum of the neighbours.
Examples:
>>> from sage.all__sagemath_symbolics import var
>>> from skcomplex.core.components.laws import UpdateLaw
>>> x, r = var('x r')
>>> law = UpdateLaw(x, r * x * (1 - x))
>>> float(law.value.subs(x=0.5, r=3))
0.75