LEGION oscillators
A LEGION network, a lattice of relaxation oscillators.
- Class:
LegionSystem - Import:
from skcomplex.systems.biology.neuroscience import LegionSystem - Field:
biology/neuroscience - Topics:
oscillators,synchronization,segmentation,lattice,field - References:
- Terman and Wang 1995
- Wang and Terman 1995
- Gros 2015
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.biology.neuroscience import LegionSystem
trajectory = LegionSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
stimulus |
((1, 1, 0, 0), (1, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 1)) |
epsilon |
0.1 |
W |
6.0 |
W_z |
1.5 |
random_state |
0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | lattice |
| Laws | rate |
| Randomness | unknown |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class LegionSystem(BaseSystem):
"""A LEGION network, a lattice of relaxation oscillators.
The network segments a stimulus into its objects.
Stimulated oscillators excite their stimulated neighbours, so each connected object synchronizes, and a global
inhibitor lets only one object be active at a time, so different objects take turns. The inhibitor is driven by the
largest activity of the oscillators, so one active oscillator drives it fully. Unstimulated sites have a negative
input and stay silent.
The default `epsilon = 0.1` gives a cycle of about 60 time units, so with the default stimulus the second object
first fires near `t = 51` and the first near `t = 70`. The value 0.02 of Terman and Wang makes the slow phases five
times longer, and then no object starts an active phase before `t = 220`. The system has the fast variables
`oscillators.x`, the slow variables `oscillators.y`, and the inhibitor `inhibitor.z`.
Args:
stimulus:
The lattice of 1 for stimulated and 0 for unstimulated sites, by rows. The default holds two objects.
epsilon:
The time scale of the slow variables.
W:
The total excitatory weight into a stimulated site, shared among its stimulated neighbours.
W_z:
The strength of the global inhibition.
random_state:
The seed or generator of the initial states.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Examples:
>>> from skcomplex.systems.biology.neuroscience import LegionSystem
>>> LegionSystem().prepare().system_.elements[0].space.shape
(4, 4)
"""
field = 'biology/neuroscience'
topics = ('oscillators', 'synchronization', 'segmentation', 'lattice', 'field')
references = ('Terman and Wang 1995', 'Wang and Terman 1995', 'Gros 2015')
until = 150.0
dt = 0.5
def __init__(
self,
stimulus: Sequence[Sequence[float]] = LEGION_OBJECTS,
*,
epsilon: float = 0.1,
W: float = 6.0,
W_z: float = 1.5,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.stimulus = stimulus
self.epsilon = epsilon
self.W = W
self.W_z = W_z
self.random_state = random_state
@staticmethod
def _get_excitation(s: SimpleNamespace) -> Expression:
"""Return the excitation of an oscillator by a stimulated neighbour.
The neighbour excites it in its active phase.
"""
active = s.other.m * logistic(s.other.x - s.other.theta_x, 0, s.other.kappa)
excitation: Expression = s.member.W * s.member.m * active
return excitation
@staticmethod
def _get_exchange(s: SimpleNamespace) -> list[BaseLaw]:
"""Return the excitation of the two oscillators at the ends of a bond, each by the other."""
get_excitation = LegionSystem._get_excitation
return [
RateLaw(s.target.x, get_excitation(SimpleNamespace(member=s.target, other=s.source))),
RateLaw(s.source.x, get_excitation(SimpleNamespace(member=s.source, other=s.target))),
]
@staticmethod
def _link_weights(stimulus: Array, total: float) -> Array:
"""Return the weight of each link into every site.
A total weight is shared among the stimulated neighbours of the site.
"""
neighbours = convolve(stimulus, NEAREST, mode='constant')
return total / np.maximum(neighbours, 1.0)
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of a LEGION network.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
marks = np.asarray(self.stimulus, dtype=float)
rng = np.random.default_rng(self.random_state)
oscillators = TermanWangElement(
'oscillators',
x=rng.uniform(-2.0, 2.0, marks.shape),
y=rng.uniform(0.0, 6.0, marks.shape),
I=np.where(marks > 0, 0.2, -0.02),
m=marks,
W=self._link_weights(marks, self.W),
epsilon=self.epsilon,
space=LatticeSpace(marks.shape, boundary={'x': ('fixed', SILENT), 'y': 'zero-flux'}),
)
excitation = Interaction('excitation', roles={'nodes': 'oscillators'}, laws=self._get_exchange, along=True)
drive = InhibitorDriveInteraction('drive', inhibitor='inhibitor', oscillators='oscillators')
inhibition = GlobalInhibitionInteraction(
'inhibition',
inhibitor='inhibitor',
oscillators='oscillators',
W_z=self.W_z,
)
self.system_ = System(
self.label,
elements=[oscillators, InhibitorElement('inhibitor')],
interactions=[
TermanWangInteraction('oscillation', target='oscillators'),
InhibitorDecayInteraction('decay', target='inhibitor'),
excitation,
drive,
inhibition,
],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
TermanWangInteraction, fromInteractionInhibitorDecayInteraction, fromInteractionInteractionInhibitorDriveInteraction, fromInteractionGlobalInhibitionInteraction, fromInteraction
class TermanWangElement(Element):
"""Relaxation oscillators of Terman and Wang, one per site of a LEGION lattice.
The parameters `m`, `W`, `theta_x`, and `kappa` belong to the coupling of a lattice of oscillators, a
coupling along its bonds that adds `W m (sum_k m_k H(x_k - theta_x))` over the four nearest sites, where `H` is a
smooth step of width `kappa` and `m` marks the stimulated sites, so only stimulated neighbours excite each other.
Args:
label:
The label of the oscillator or the lattice field.
x:
The initial fast variable.
y:
The initial slow variable.
I:
The external input.
m:
1 for a stimulated site and 0 otherwise.
W:
The weight of each excitatory link into the site.
epsilon:
The time scale of the slow variable.
gamma:
The height of the slow nullcline.
beta:
The width of the slow nullcline's step.
theta_x:
The threshold of the active phase.
kappa:
The width of the smooth steps.
space:
The lattice whose sites hold one oscillator each, or `None` for one oscillator.
Examples:
>>> from skcomplex.systems.biology.neuroscience import TermanWangElement
>>> TermanWangElement('oscillator').gamma
6.0
"""
def __init__(
self,
label: str,
*,
x: float | Array = SILENT,
y: float | Array = 0.0,
I: float | Array = 0.2,
m: Annotated[float | Array, RealSet.closed_open(0, oo)] = 1.0,
W: Annotated[float | Array, RealSet.closed_open(0, oo)] = 6.0,
epsilon: Annotated[float | Array, RealSet.open(0, oo)] = 0.02,
gamma: Annotated[float | Array, RealSet.open(0, oo)] = 6.0,
beta: Annotated[float | Array, RealSet.open(0, oo)] = 0.1,
theta_x: float = -0.5,
kappa: Annotated[float | Array, RealSet.open(0, oo)] = 0.02,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, space=space)
self.x = x
self.y = y
self.I = I
self.m = m
self.W = W
self.epsilon = epsilon
self.gamma = gamma
self.beta = beta
self.theta_x = theta_x
self.kappa = kappa
class InhibitorElement(Element):
"""Global inhibitor of a LEGION network, with its activity `z` and its rate `phi`.
Args:
label:
The label of the inhibitor.
z:
The initial activity.
phi:
The rate of the inhibitor.
Examples:
>>> from skcomplex.systems.biology.neuroscience import InhibitorElement
>>> InhibitorElement('inhibitor').phi
3.0
"""
def __init__(
self,
label: str,
*,
z: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
phi: Annotated[float, RealSet.open(0, oo)] = 3.0,
) -> None:
super().__init__(label)
self.z = z
self.phi = phi
class TermanWangInteraction(Interaction):
"""Dynamics of relaxation oscillators of Terman and Wang.
The fast variable follows `x' = 3x - x³ + 2 - y + I` and the slow one `y' = epsilon (gamma (1 + tanh(x / beta)) -
y)`. A positive input `I` makes the oscillator oscillate and a negative one makes it excitable.
Args:
label:
The label of the interaction.
target:
The path of the oscillators, whose values are `x`, `y`, `I`, `epsilon`, `gamma`, and `beta`.
Examples:
>>> from skcomplex.systems.biology.neuroscience import TermanWangInteraction
>>> TermanWangInteraction('oscillation', target='oscillators').target
'oscillators'
"""
law_classes = (RateLaw,)
def __init__(self, label: str, *, target: Role) -> None:
super().__init__(label)
self.target = target
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the fast variable and the slow recovery of the target.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
s = context.target
self.laws_ = [
RateLaw(s.x, 3 * s.x - s.x**3 + 2 - s.y + s.I),
RateLaw(s.y, s.epsilon * (s.gamma * (1 + tanh(s.x / s.beta)) - s.y)),
]
class InhibitorDecayInteraction(Interaction):
"""Decay of a global inhibitor without drive, `z' = -phi z`.
Args:
label:
The label of the interaction.
target:
The path of the inhibitor, whose values are `z` and `phi`.
Examples:
>>> from skcomplex.systems.biology.neuroscience import InhibitorDecayInteraction
>>> InhibitorDecayInteraction('decay', target='inhibitor').target
'inhibitor'
"""
law_classes = (RateLaw,)
def __init__(self, label: str, *, target: Role) -> None:
super().__init__(label)
self.target = target
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the decay of the inhibitor.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
self.laws_ = [RateLaw(context.target.z, -context.target.phi * context.target.z)]
class Interaction(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.
Args:
label:
The name of the interaction, unique among the components of its system, such as `'predation'`.
roles:
The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
without a class, or `None`.
laws:
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`.
among:
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.
along:
`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`.
within:
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`.
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'}
"""
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
def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
"""Return the numeric arguments as parameters, and `roles` and `among` as roles.
With `within`, `among` binds both members of a pair, `first` and `second`.
"""
declared = dict(super()._get_declared())
for name, binding in (self.roles or {}).items():
declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
if self.among is not None and self.within is not None:
for name in PAIR_ROLES:
declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
return declared
@classmethod
def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
"""Return the arguments that name the states a role reads.
The mapping `roles` of bindings names none.
"""
return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')
def _get_binding(self, role: str) -> object:
"""Return what a role binds, from `roles` or from the argument of its name.
Args:
role:
The name of the role.
Returns:
binding:
The label, labels, or entries the role binds, or `None` when it binds nothing.
"""
if self.roles is not None and role in self.roles:
return self.roles[role]
if self.among is not None and self.within is not None and role in PAIR_ROLES:
return self.among
return super()._get_binding(role)
def _check_arguments(self) -> None:
"""Raise an error for roles, laws, or groups the interaction cannot take.
Raises:
ValidationError:
A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
`along` names hyperedges of fewer than two members.
"""
clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
if clashes:
error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
raise ValidationError(error_msg)
if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
error_msg = (
f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
'`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
)
raise ValidationError(error_msg)
if isinstance(self.along, tuple) and not self._is_sized(self.along):
error_msg = (
f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
"more, such as `along=('hyperedges', 3)`."
)
raise ValidationError(error_msg)
if isinstance(self.along, RandomPartition):
self.along._check()
grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
if grouped and self.among is None:
error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
raise ValidationError(error_msg)
super()._check_arguments()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of `laws` for a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
if self.laws is not None:
self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)
@staticmethod
def _is_sized(along: tuple[object, ...]) -> bool:
"""Return whether `along` names hyperedges of a whole size of at least two."""
if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
return False
size = along[1]
return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE
def _get_draws(self) -> bool:
"""Return whether the interaction draws, as it does along random groups."""
return super()._get_draws() or isinstance(self.along, RandomPartition)
def _runs_on_edges(self) -> bool:
"""Return whether the interaction runs along edges."""
grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
return self.along is not None and self.along is not False and not grouped
def _runs_on_hyperedges(self) -> bool:
"""Return whether the interaction runs along the hyperedges of a network."""
return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)
def _get_hyperedge_size(self) -> int | None:
"""Return the size `along` gives the hyperedges, or `None` for every size."""
return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None
def _get_within(self) -> RadiusNeighborhood | None:
"""Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
return self.within
def _get_layer(self) -> str | None:
"""Return the layer `along` names, or `None` for no layer."""
if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
return None
return self.along
def _get_grouping(self) -> tuple[str, int, str] | None:
"""Return the kind, size, and reduction of the groups `along` names, or `None`."""
if isinstance(self.along, RandomPartition):
return ('partition', self.along.size, 'sum')
if self.along == NEIGHBORHOODS:
return ('neighborhood', 0, 'sum')
return None
class InhibitorDriveInteraction(Interaction):
"""Drive of a global inhibitor by the largest activity of the lattice oscillators.
The activity is `m H(x - theta_x)`.
The inhibitor gets `phi max_j m_j H(x_j - theta_x)`, with the rate `phi` of the inhibitor and a smooth step of
width `kappa` of every oscillator, so it is driven when at least one stimulated oscillator is active. It is the
coupling of a hub element to a group by the largest value over the group.
Args:
label:
The label of the interaction.
inhibitor:
The path of the inhibitor.
oscillators:
The path of the lattice of oscillators.
Examples:
>>> from skcomplex.systems.biology.neuroscience import InhibitorDriveInteraction
>>> InhibitorDriveInteraction('drive', inhibitor='z', oscillators='grid').oscillators
'grid'
"""
law_classes = (RateLaw,)
def __init__(
self,
label: str,
*,
inhibitor: Role,
oscillators: Role,
) -> None:
super().__init__(label)
self.inhibitor = inhibitor
self.oscillators = oscillators
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the drive `phi max_j m_j H(x_j - theta_x)` of the inhibitor.
Args:
context:
The namespace of the inhibitor and the oscillators.
"""
super()._prepare(context)
hub, other = context.inhibitor, context.oscillators
drive = hub.phi * other.m * logistic(other.x - other.theta_x, 0, other.kappa) * SR(1)
self.laws_: list[BaseLaw] = [RateLaw(hub.z, maximum(drive, over=other))]
class GlobalInhibitionInteraction(Interaction):
"""Inhibition of every oscillator of a lattice by a global inhibitor.
The inhibition acts once the inhibitor exceeds its threshold.
Every oscillator gets `-W_z H(z - theta_z)` from the inhibitor, a smooth step of width `kappa` of the oscillator.
It is the coupling of the members of a group to a hub element, and `InhibitorDriveInteraction` drives the hub.
Args:
label:
The label of the interaction.
oscillators:
The path of the lattice of oscillators.
inhibitor:
The path of the inhibitor.
W_z:
The strength of the inhibition.
theta_z:
The threshold of the inhibitor.
Examples:
>>> from skcomplex.systems.biology.neuroscience import GlobalInhibitionInteraction
>>> GlobalInhibitionInteraction('inhibition', inhibitor='z', oscillators='grid').W_z
1.5
"""
law_classes = (RateLaw,)
def __init__(
self,
label: str,
*,
oscillators: Role,
inhibitor: Role,
W_z: Annotated[float, RealSet.closed_open(0, oo)] = 1.5,
theta_z: float = 0.1,
) -> None:
super().__init__(label)
self.oscillators = oscillators
self.inhibitor = inhibitor
self.W_z = W_z
self.theta_z = theta_z
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the inhibition `-W_z H(z - theta_z)` of every oscillator.
Args:
context:
The namespace of the oscillators and the inhibitor.
"""
super()._prepare(context)
member, hub = context.oscillators, context.inhibitor
inhibition = -context.W_z * logistic(hub.z - context.theta_z, 0, member.kappa)
self.laws_: list[BaseLaw] = [RateLaw(member.x, inhibition)]