Skip to content

Elements

Define elements, the components of a system that hold its values.

An element holds the values of one thing or of a group of members, such as the height and mass of a ball in Element('ball', values={'x': 10.0, 'm': 1.0}), and says how a visualisation observer draws it. Specs written in Annotated mark a value as an angle, a conserved quantity, a matrix, or a link to a member of another group.

BaseElement(label)

Bases: BaseComponent[BaseSpace]

An abstract element, the component of a system that holds its values.

An element holds the values of one thing or of a group of members, such as the height and mass of a ball in Element('ball', values={'x': 10.0, 'm': 1.0}). A value that a law changes is a state, and every other value is a parameter. A subclass takes each value as a plain argument of its __init__ and stores it under the same name, as a scikit-learn estimator does. It holds no laws, which interactions state, and it is drawn as its class attribute visual says. Its subclasses hold a population in ecology, a chemical in a reactor, and an account in a bank.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
label str

The name of the element, unique among the components of its system, such as 'rabbits'.

required

Attributes:

Name Type Description
default_visual_

How the element is drawn by default, the visual of its class.

See Also

Element: Holds named values of one thing or of many members. VisualSpec: Says how an element is drawn.

Examples:

>>> from skcomplex.core.components.elements import BaseElement, Element
>>> ball = Element('ball', values={'x': 10.0, 'm': 1.0})
>>> isinstance(ball, BaseElement), ball.label
(True, 'ball')
Source code in src/skcomplex/core/components/base.py
69
70
def __init__(self, label: str) -> None:
    self.label = label

get_states()

Return the states of the element with their specs.

The states are those its class declares and those it takes as data.

Returns:

Name Type Description
states dict[str, _StateSpec]

The spec of every state, by name.

Source code in src/skcomplex/core/components/elements/_base.py
119
120
121
122
123
124
125
126
127
128
def get_states(self) -> dict[str, _StateSpec]:
    """Return the states of the element with their specs.

    The states are those its class declares and those it takes as data.

    Returns:
        states:
            The spec of every state, by name.
    """
    return {name: spec for name, spec in self._get_component_specs().items() if isinstance(spec, _StateSpec)}

prepare(context=None)

Prepare the element on its space, checking that it holds values and no laws.

Laws come from interactions, so an element whose _prepare sets laws_ is rejected. Gravity on a ball, for example, is an interaction whose _prepare sets self.laws_ = [RateLaw(s.target.x.diff(s.t, 2), -s.g)].

Parameters:

Name Type Description Default
context BaseSpace | None

The space the element inherits from its system, or None.

None

Returns:

Name Type Description
self Self

The prepared element.

Raises:

Type Description
ValidationError

The _prepare of the element sets laws_.

Source code in src/skcomplex/core/components/elements/_base.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def prepare(self, context: BaseSpace | None = None) -> Self:
    """Prepare the element on its space, checking that it holds values and no laws.

    Laws come from interactions, so an element whose `_prepare` sets `laws_` is rejected. Gravity on a ball, for
    example, is an interaction whose `_prepare` sets `self.laws_ = [RateLaw(s.target.x.diff(s.t, 2), -s.g)]`.

    Args:
        context:
            The space the element inherits from its system, or `None`.

    Returns:
        self:
            The prepared element.

    Raises:
        ValidationError:
            The `_prepare` of the element sets `laws_`.
    """
    if hasattr(self, 'laws_'):
        del self.laws_
    super().prepare(context)
    if hasattr(self, 'laws_'):
        error_msg = (
            f'Element {self.label!r} sets laws_ in _prepare, but an element holds values only. Write the law in '
            f'an interaction instead, such as a Gravity interaction whose _prepare sets '
            f'self.laws_ = [RateLaw(s.target.x.diff(s.t, 2), -s.g)].'
        )
        raise ValidationError(error_msg)
    return self

Element(label, *, values=None, size=None, space=None, on=None)

Bases: BaseElement

An element that holds named values of one thing or of a group of members.

It holds its values by name, such as the height and mass of a ball in Element('ball', values={'x': 10.0, 'm': 1.0}), and the laws of the interactions decide which values change. With size it holds a group of members with values of their own, such as 1000 molecules of a gas, and with space one member per site, such as the cells of a grid. A subclass may take its values as arguments of __init__ instead, such as a population class with a growth rate. Members whose values change by agent rules, Python functions run for each member at each step, act as agents, and their values may be any Python object. It holds a prey population, a firm of an economy, and the charge of a capacitor.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
label str

The name of the element, unique among the components of its system, such as 'rabbits'.

required
values Mapping[str, object] | None

Values by name, such as {'x': 10.0, 'm': 1.0}. A derivative or a past value that a law reads starts from the value named with primes or a past index, such as {'x': 10.0, "x'": 3.0} for a ball thrown upwards or {'y': 1.0, 'y[-1]': 0.5} for an economy. A group of members takes one value per member as an array.

None
size int | None

The number of members, each with its own values, such as 1000 molecules of a gas, or None for one.

None
space BaseSpace | None

The space of the element, with one member per site, such as a lattice of cells, or None for none.

None
on str | None

The part of a network space that holds one member each: 'edges' for every link, 'hyperedges' for every hyperedge, the name of a layer for every link of that layer, such as 'immune', or None for every site.

None

Attributes:

Name Type Description
default_visual_

How the element is drawn by default, the visual of its class.

See Also

BaseElement: The base of every element. Interaction: States the laws that change the values of elements.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> ball = Element('ball', values={'x': 10.0, 'm': 1.0})
>>> ball.get_params()['x']
10.0
Source code in src/skcomplex/core/components/elements/_element.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def __init__(
    self,
    label: str,
    *,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
    on: str | None = None,
) -> None:
    super().__init__(label)
    self.values = values
    self.size = size
    self.space = space
    self.on: object = on

get_params(deep=True)

Return the parameters of the element, with each entry of values when deep.

An entry of values whose name is a Python identifier is listed under its own name, so a system lists it as <element>__<name> and set_params(ball__x=2.0), grid searches, and sweeps reach it. A primed or past value, such as "x'" or 'x[-1]', is no identifier and stays inside values. An entry that has the name of an argument is not listed twice.

Parameters:

Name Type Description Default
deep bool

Whether to add the parameters of nested estimators and the entries of values.

True

Returns:

Name Type Description
params dict[str, Any]

The parameters by name.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> params = Element('ball', values={'x': 10.0, "x'": 3.0}).get_params()
>>> params['x'], "x'" in params
(10.0, False)
Source code in src/skcomplex/core/components/elements/_element.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def get_params(self, deep: bool = True) -> dict[str, Any]:
    """Return the parameters of the element, with each entry of `values` when deep.

    An entry of `values` whose name is a Python identifier is listed under its own name, so a system lists it as
    `<element>__<name>` and `set_params(ball__x=2.0)`, grid searches, and sweeps reach it. A primed or past value,
    such as `"x'"` or `'x[-1]'`, is no identifier and stays inside `values`. An entry that has the name of an
    argument is not listed twice.

    Args:
        deep:
            Whether to add the parameters of nested estimators and the entries of `values`.

    Returns:
        params:
            The parameters by name.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> params = Element('ball', values={'x': 10.0, "x'": 3.0}).get_params()
        >>> params['x'], "x'" in params
        (10.0, False)
    """
    params = super().get_params(deep=deep)
    if deep and isinstance(self.values, Mapping):
        entries = self._get_value_entries()
        params.update({name: value for name, value in entries.items() if name not in params})
    return params

set_params(**params)

Set parameters of the element and entries of values by name.

An entry of values takes its new value in a new mapping, so the mapping the user gave never changes, as clone of scikit-learn leaves the arguments of an estimator unchanged. A new values is set first, so the output of get_params is accepted as it is.

Parameters:

Name Type Description Default
**params object

The new values, by the name of a parameter or of an entry of values, such as x=2.0.

{}

Returns:

Name Type Description
self Self

The element.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> values = {'x': 10.0}
>>> Element('ball', values=values).set_params(x=2.0).values, values
({'x': 2.0}, {'x': 10.0})
Source code in src/skcomplex/core/components/elements/_element.py
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
def set_params(self, **params: object) -> Self:
    """Set parameters of the element and entries of `values` by name.

    An entry of `values` takes its new value in a new mapping, so the mapping the user gave never changes, as
    `clone` of scikit-learn leaves the arguments of an estimator unchanged. A new `values` is set first, so the
    output of `get_params` is accepted as it is.

    Args:
        **params:
            The new values, by the name of a parameter or of an entry of `values`, such as `x=2.0`.

    Returns:
        self:
            The element.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> values = {'x': 10.0}
        >>> Element('ball', values=values).set_params(x=2.0).values, values
        ({'x': 2.0}, {'x': 10.0})
    """
    arguments = super().get_params(deep=True)
    if 'values' in params:
        super().set_params(values=params['values'])
    entries = self._get_value_entries()
    changed = {name: value for name, value in params.items() if name in entries and name not in arguments}
    rest = {name: value for name, value in params.items() if name not in changed and name != 'values'}
    super().set_params(**rest)
    if changed:
        self.values = {**(self.values or {}), **changed}
    return self

Member(group) dataclass

Bases: BaseSpec

A spec of a value that names a member of another group, such as a parent.

It is written in Annotated beside the allowed values, such as employer: Annotated[int, Member('firms')] = -1. The value is the index of a member of that group, and -1 names none. When a member of the group is removed, every value that names it becomes -1, so a worker whose firm closes has no employer. A rule reads the member a value names with agent.get_referenced('employer'). It links a worker to a firm, a customer to a bank, and a child to a parent.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
group str

The label of the group whose members the value names, such as 'firms'.

required
See Also

Quantity: Marks a value whose total only flows change. Period: Marks a value that wraps around, such as an angle.

Examples:

>>> from skcomplex.core.components.elements import Member
>>> Member('firms').group
'firms'

Period(length) dataclass

Bases: BaseSpec

A spec of a value that wraps around a period, such as 2 * pi for an angle.

It is written in Annotated beside the allowed values, such as theta: Annotated[float, Period(2 * pi)] = 0.0. The value is brought back within one period after every step, so 0 and 2 * pi are the same angle. The analyses read a periodic value as a phase, or as a heading when its element moves in a space. It holds the angle of a pendulum, the phase of a firefly, and the heading of a bird.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
length float

The length of the period, a positive number.

required
See Also

Quantity: Marks a value whose total only flows change. Tensor: Marks a value that holds a square matrix.

Examples:

>>> import math
>>> from skcomplex.core.components.elements import Period
>>> round(Period(2 * math.pi).length, 4)
6.2832

Quantity(name) dataclass

Bases: BaseSpec

A spec of a value that holds a conserved quantity, such as money.

It is written in Annotated beside the allowed values, such as stock: Annotated[float, Quantity('money')] = 100.0. The total of a quantity changes only by its flows to and from the outside, so the conservation observer checks it at every frame, and a law other than a flow cannot change a value that holds it. It holds the money of a bank, the people of an epidemic, and the energy of a reserve.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
name str

The name of the quantity, such as 'money'.

required
See Also

Member: Marks a value that names a member of another group. ConservationObserver: Checks that the totals of quantities hold.

Examples:

>>> from skcomplex.core.components.elements import Quantity
>>> Quantity('money').name
'money'

Tensor(symmetry) dataclass

Bases: BaseSpec

A spec of a value that holds a square matrix of a symmetry, such as a stress.

It is written in Annotated beside the allowed values, such as Q: Annotated[object, Tensor('traceless')] = 0.0. The value holds the independent entries of the matrix, row after row, such as Q_xx and Q_xy of a traceless matrix in two dimensions, and the matrix has one row per dimension of the space of the element. Laws read the value as a Sage matrix, so s.target.Q.trace() works, and a traceless matrix stays traceless. It holds the alignment of a liquid crystal, the stress of a gel, and the strain of a rock.

Read more in the user guide, under Elements.

Parameters:

Name Type Description Default
symmetry str

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

required
See Also

Period: Marks a value that wraps around, such as an angle.

Examples:

>>> from skcomplex.core.components.elements import Tensor
>>> Tensor('traceless').symmetry
'traceless'

VisualSpec(kind='scalars', options=dict()) dataclass

Bases: BaseSpec

A spec of how an element is drawn, a visual and the options it is built with.

It names a visual of the engine, such as 'points' for a cloud of particles or 'line' for a value over time, and the keyword arguments it takes, such as {'position': 'x'}. An element sets it as its class attribute visual, and a visualisation observer may draw the element otherwise. It draws the size of a population as a line, the birds of a flock as points, and a grid of cells as an image.

Read more in the user guide, under Observe.

Parameters:

Name Type Description Default
kind str | type

The name of a visual of the engine, such as 'points', or a visual class, such as one a system package defines on BaseVisual.

'scalars'
options dict[str, object]

The keyword arguments of the visual.

dict()
See Also

BaseElement: Sets the visual of its class.

Examples:

>>> from skcomplex.core.components.elements import VisualSpec
>>> VisualSpec('points', {'position': 'x'}).kind
'points'