Skip to content

Interactions

Define interactions, the components that change the states of elements.

An interaction reads the states of the elements its roles bind and returns laws that change them, such as a rate, a map, a random event, or a transfer between members.

BaseInteraction(label)

Bases: BaseComponent[SimpleNamespace]

An abstract interaction, the component that changes the values of elements.

An interaction binds elements through roles, such as 'source' and 'target', reads their values, and returns the laws that change them in laws_ when it is prepared. It holds no values of its own, and a value on a link, such as the weight of an edge, lives in an element on the edges of a network. A subclass takes each role, typed Role, and each parameter as a plain argument of its __init__ and stores it under the same name, as a scikit-learn estimator does, and lists the laws it may return in law_classes, so that get_requirements and get_tags name them before a run. Its subclasses spread an infection in an epidemic, run a chemical reaction, and pay wages from a firm to its workers.

Read more in the user guide, under Interactions.

Parameters:

Name Type Description Default
label str

The name of the interaction, unique among the components of its system, such as 'growth'.

required

Attributes:

Name Type Description
laws_ Sequence[BaseLaw]

The laws the interaction states for the elements it was last prepared against.

See Also

Interaction: Runs its laws once for the elements its roles bind. BaseElement: The base of the components that hold values.

Examples:

>>> from skcomplex.core.components.interactions import BaseInteraction, Interaction
>>> growth = Interaction('growth', roles={'target': 'rabbits'})
>>> isinstance(growth, BaseInteraction), growth.label
(True, 'growth')
Source code in src/skcomplex/core/components/base.py
69
70
def __init__(self, label: str) -> None:
    self.label = label

get_requirements()

Return what the interaction needs.

It needs the element kinds and states of its roles, and its laws' time and space.

Returns:

Name Type Description
requirements _InteractionRequirementSpec

The roles by name, with the states each reads for the values of this interaction, the law classes the class lists, and the classes of time and of space these laws run in.

Examples:

>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> growth = Interaction('growth', roles={'target': 'rabbits'}, laws=lambda s: [RateLaw(s.target.n, 1.0)])
>>> list(growth.get_requirements().roles)
['target']
Source code in src/skcomplex/core/components/interactions/_base.py
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
def get_requirements(self) -> _InteractionRequirementSpec:
    """Return what the interaction needs.

    It needs the element kinds and states of its roles, and its laws' time and space.

    Returns:
        requirements:
            The roles by name, with the states each reads for the values of this interaction, the law classes
            the class lists, and the classes of time and of space these laws run in.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> growth = Interaction('growth', roles={'target': 'rabbits'}, laws=lambda s: [RateLaw(s.target.n, 1.0)])
        >>> list(growth.get_requirements().roles)
        ['target']
    """
    laws = self._get_law_classes()
    needs = [law.get_requirements() for law in laws]
    return _InteractionRequirementSpec(
        time=self._get_accepted([need.time for need in needs]),
        space=self._get_accepted([need.space for need in needs]),
        sites=any(need.sites for need in needs),
        roles={
            name: replace(spec, states=self._get_state_names(spec.states or self._get_state_arguments(spec)))
            for name, spec in self._get_component_specs().items()
            if isinstance(spec, RoleSpec)
        },
        laws=laws,
    )

prepare(context=None)

Check the interaction, and set its laws in laws_ on a namespace.

The engine prepares a copy of the interaction on the namespace of every binding of its roles. Only a namespace reaches the hook _prepare, so a subclass reads its roles, the time, and its parameters there. On the space of its system, or on nothing, the interaction checks its arguments and learns no laws.

Parameters:

Name Type Description Default
context BaseSpace | SimpleNamespace | None

The namespace of the elements a binding of the roles names, the space of the system, or None.

None

Returns:

Name Type Description
self Self

The prepared interaction.

Raises:

Type Description
SpaceError

A variant needs a kind of space the system does not have.

ValidationError

An argument is invalid, named in the message.

Source code in src/skcomplex/core/components/interactions/_base.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
def prepare(self, context: BaseSpace | SimpleNamespace | None = None) -> Self:
    """Check the interaction, and set its laws in `laws_` on a namespace.

    The engine prepares a copy of the interaction on the namespace of every binding of its roles. Only a namespace
    reaches the hook `_prepare`, so a subclass reads its roles, the time, and its parameters there. On the space
    of its system, or on nothing, the interaction checks its arguments and learns no laws.

    Args:
        context:
            The namespace of the elements a binding of the roles names, the space of the system, or `None`.

    Returns:
        self:
            The prepared interaction.

    Raises:
        SpaceError:
            A variant needs a kind of space the system does not have.
        ValidationError:
            An argument is invalid, named in the message.
    """
    if isinstance(context, SimpleNamespace):
        return super().prepare(context)
    self._check_arguments()
    self._prepare_on(context)
    return self

Interaction(label, *, roles=None, laws=None, among=None, along=None, within=None)

Bases: BaseInteraction

An interaction whose laws run once for the elements its roles bind.

It states the laws that change the values of the elements its roles bind, such as gravity on a ball in Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)]). When a role binds a group, the laws run once for every member, as arrays. With among and along, they run once for every edge of a network and read s.source and s.target, the members at its two ends, or once for every hyperedge or random small group and read s.member, s.others, and s.members. With within, they run once for every pair of members closer than a radius and read s.first and s.second. A subclass takes its roles, typed Role, and its parameters as arguments of its __init__ and sets laws_ in its _prepare. It states predation between two populations, a reaction between two chemicals, and an infection along the contacts of a network.

Read more in the user guide, under Interactions.

Parameters:

Name Type Description Default
label str

The name of the interaction, unique among the components of its system, such as 'predation'.

required
roles Mapping[str, object] | None

The element each role binds, by the name of the role, such as {'target': 'ball'}, for a rule written without a class, or None.

None
laws Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None

The function of the namespace that returns the laws of a rule written without a class, such as lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)], the laws themselves when they read no element, or None.

None
among str | None

The group whose members sit at the ends of the edges, such as 'people', or None to bind elements by their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

None
along bool | str | tuple[str, int] | RandomPartition | None

True for the edges of the network the group lives on, the name of a layer of a network with several, such as 'contacts', 'hyperedges' for its hyperedges, ('hyperedges', k) for its hyperedges of k members, RandomPartition(k) for random groups of k members drawn at every step, 'neighborhoods' for every member with the members around it, or None for no edges. On the edges, the laws read the member of an element that sits on them as s.edge, and on the hyperedges as s.hyperedge.

None
within RadiusNeighborhood | None

A RadiusNeighborhood(r) for laws that run once for every pair of members of the roles first and second closer than r, which read s.first and s.second and give the laws of both, such as the repulsion of walkers of two crowds, or None for no pairs. With among, both members come from that group. The laws may give the energy of the pair as ObjectiveLaw(V) in place of its forces, and each member then feels the force -dV/dx on its position x.

None
See Also

BaseInteraction: The base of every interaction. RandomPartition: Groups the members of a group at random at every step. TrainingInteraction: Trains the parameters of a nested system.

Examples:

>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
>>> birth.roles
{'target': 'fish'}
Source code in src/skcomplex/core/components/interactions/_interaction.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(
    self,
    label: str,
    *,
    roles: Mapping[str, object] | None = None,
    laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
    among: str | None = None,
    along: bool | str | tuple[str, int] | RandomPartition | None = None,
    within: RadiusNeighborhood | None = None,
) -> None:
    super().__init__(label)
    self.roles = roles
    self.laws = laws
    self.among = among
    self.along = along
    self.within = within

RandomPartition(size) dataclass

Bases: BaseSpec

A random partition of a group into small groups, drawn anew at every step.

An interaction bound with along=RandomPartition(3) shuffles the members of the group among at every step, cuts them into groups of three, and runs its laws once for every member of every group. The members left over form one smaller group. The laws read s.member, the member they change, s.others, the other members of its group, and s.members, every member of the group. Unlike along='hyperedges', whose groups a network fixes, it draws new groups at every step. Voters discuss in small groups, players of a public goods game meet every round, and animals meet in random encounters.

Read more in the user guide, under Interactions.

Parameters:

Name Type Description Default
size int

The number of members of a group, at least 2.

required
See Also

Interaction: Runs its laws once for every member of every group.

Examples:

>>> from skcomplex.core.components.interactions import Interaction, RandomPartition
>>> talks = Interaction('talks', among='citizens', along=RandomPartition(3))
>>> talks.along.size
3

TrainingInteraction(label, *, system, trained, loss, data, optimizer='adam', learning_rate=0.001, momentum=0.9, beta1=0.9, beta2=0.999, batch_size=32, truncation=None, metrics=())

Bases: Interaction

An interaction that trains the parameters of a nested system by gradient steps.

The role system binds a nested system, which the training runs over the sequences of a dataset and differentiates. One step of the outer system is one epoch: shuffled batches, each followed by one step of the optimizer on the parameters named in trained. The settings of the optimizer are parameters of the interaction, so a schedule of simulate can change them between epochs. It states no laws of its own, and GradientDescentSolver reads its settings. A recurrent neural network learns to predict a time series, an echo state network fits its readout, and a learning agent improves its policy between rounds.

Read more in the user guide, under Interactions.

Parameters:

Name Type Description Default
label str

The name of the interaction, unique among the components of its system, such as 'training'.

required
system Annotated[str, RoleSpec(elements=(ANY,))]

The path of the nested system whose parameters the interaction trains.

required
trained Sequence[str]

The dotted paths of the parameters of the nested system to train, such as readout.W.

required
loss Observable

The observable of the nested system whose weighted mean over the steps of a batch is minimized.

required
data DatasetSpec

The sequences of the parameters of the nested system that set its inputs and targets at every step.

required
optimizer str

The name of the optimizer, one of OptimizerKind. 'sgd' reads the learning rate, 'momentum' also momentum, 'rmsprop' also beta2, and 'adam' also beta1 and beta2.

'adam'
learning_rate Annotated[float, _ParameterSpec(domain=closed_open(0, oo))]

The learning rate of the optimizer.

0.001
momentum Annotated[float, _ParameterSpec(domain=closed_open(0, 1))]

The momentum of 'momentum'.

0.9
beta1 Annotated[float, _ParameterSpec(domain=closed_open(0, 1))]

The decay of the mean gradient of 'adam'.

0.9
beta2 Annotated[float, _ParameterSpec(domain=closed_open(0, 1))]

The decay of the mean squared gradient of 'adam' and 'rmsprop'.

0.999
batch_size int

The number of sequences of a batch.

32
truncation int | None

The number of inner steps the gradient flows back through the inner states, or None for the whole run. A truncation of 1 holds the previous inner states as constant inputs, as Elman's original training does.

None
metrics Sequence[Observable]

The observables of the nested system recorded at the end of every epoch.

()

Raises:

Type Description
ValidationError

The optimizer is unknown, the batch size or the truncation is not a positive integer, no parameter is trained, or the loss, the data, or a metric has the wrong type or label.

See Also

Interaction: Runs its laws once for the elements its roles bind. GradientDescentSolver: Runs the epochs of a training.

Examples:

>>> from skcomplex.core.components import Observable
>>> from skcomplex.core.components.interactions import TrainingInteraction
>>> from skcomplex.core.components.laws import DatasetSpec
>>> data = DatasetSpec({'inputs.x': [[[0.0]], [[1.0]]]})
>>> TrainingInteraction('fit', system='net', trained=['W'], loss=Observable('error', 0), data=data).optimizer
'adam'
Source code in src/skcomplex/core/components/interactions/_training.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def __init__(
    self,
    label: str,
    *,
    system: Annotated[str, RoleSpec(elements=(ElementKind.ANY,))],
    trained: Sequence[str],
    loss: Observable,
    data: DatasetSpec,
    optimizer: str = 'adam',
    learning_rate: Annotated[float, _ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1e-3,
    momentum: Annotated[float, _ParameterSpec(domain=RealSet.closed_open(0, 1))] = 0.9,
    beta1: Annotated[float, _ParameterSpec(domain=RealSet.closed_open(0, 1))] = 0.9,
    beta2: Annotated[float, _ParameterSpec(domain=RealSet.closed_open(0, 1))] = 0.999,
    batch_size: int = 32,
    truncation: int | None = None,
    metrics: Sequence[Observable] = (),
) -> None:
    super().__init__(label)
    self.system = system
    self.trained = trained
    self.loss = loss
    self.data = data
    self.optimizer = optimizer
    self.learning_rate = learning_rate
    self.momentum = momentum
    self.beta1 = beta1
    self.beta2 = beta2
    self.batch_size = batch_size
    self.truncation = truncation
    self.metrics = metrics

WienerProcessSpec(label, dimension=1, covariance=None) dataclass

Bases: BaseSpec

A spec of a set of Wiener processes whose random steps are correlated.

A Wiener process adds a random step of variance h over a time step h, and the steps of these processes have the covariance h C. An interaction takes the spec as an argument, such as process=market, and its noise laws name the steps as s.process.dW, or s.process.dW[k] for process k of several. Interactions that take processes of one label share them, so their laws move with the same random steps. Shared shocks move the prices of a market, a common current moves particles, and one weather pattern moves the yields of many farms.

Read more in the user guide, under Laws.

Parameters:

Name Type Description Default
label str

The label of the processes, unique among the components of the system of the interactions that bind them.

required
dimension int

The number of processes.

1
covariance object

The constant covariance matrix C of the processes, symmetric and positive semidefinite of size dimension, or None for the identity.

None
See Also

Interaction: Takes the spec as an argument.

Examples:

>>> from skcomplex.core.components.interactions import WienerProcessSpec
>>> WienerProcessSpec('shared', dimension=2, covariance=((1.0, 0.5), (0.5, 1.0))).dimension
2