Insider sabotage
The insider sabotage system of employees whose risk of sabotage builds up.
- Class:
InsiderSabotageSystem - Import:
from skcomplex.systems.social.organizations import InsiderSabotageSystem - Field:
social/organizations - Topics:
organizations,agents,grid,insider threat - References:
- Ardiles Cruz et al. 2019
- Carmichael et al. 2019
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.social.organizations import InsiderSabotageSystem
trajectory = InsiderSabotageSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
size |
20 |
n_employees |
130 |
n_supervisors |
3 |
turnover |
0.15 |
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 | discrete |
| Space | lattice |
| Laws | update |
| Randomness | stochastic |
| Domains | boolean, integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class InsiderSabotageSystem(BaseSystem):
"""The insider sabotage system of employees whose risk of sabotage builds up.
The risk builds up over the days of a year. The system has the groups `employees` and `supervisors`.
Args:
size:
The number of rows and columns of the torus.
n_employees:
The number of employees.
n_supervisors:
The number of supervisors.
turnover:
The yearly share of employees who leave.
random_state:
The seed or generator of the predispositions and affects.
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.social.organizations import InsiderSabotageSystem
>>> [group.size for group in InsiderSabotageSystem(n_employees=20, n_supervisors=2).prepare().system_.elements]
[20, 2]
"""
field = 'social/organizations'
topics = ('organizations', 'agents', 'grid', 'insider threat')
references = ('Ardiles Cruz et al. 2019', 'Carmichael et al. 2019')
until = 365
def __init__(
self,
size: int = 20,
*,
n_employees: int = 130,
n_supervisors: int = 3,
turnover: float = 0.15,
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.size = size
self.n_employees = n_employees
self.n_supervisors = n_supervisors
self.turnover = turnover
self.random_state = random_state
@staticmethod
def _feel(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the feeling of a predisposed employee about the organization today.
It is drawn, or else the last one.
"""
if not agent.predisposed:
return float(agent.feeling)
return float(system.rng.normal(agent.culture, np.sqrt(agent.change)))
@staticmethod
def _remember_first(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the first feeling of an employee.
It is today's feeling on the first day of a predisposed employee.
"""
return float(agent.feeling if agent.predisposed and agent.days == 0 else agent.first)
@staticmethod
def _get_disgruntlement(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the disgruntlement.
It is the shortfall of today's feeling from the expectation of a predisposed one.
"""
if not agent.predisposed or agent.days == 0:
return float(agent.disgruntlement)
return float((agent.expectation - agent.feeling) * agent.affect_weight)
@staticmethod
def _count_day(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return one day felt for a predisposed employee, and none otherwise."""
return float(agent.predisposed)
@staticmethod
def _average(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the change of the mean feeling of a predisposed employee.
The change is by today's feeling.
"""
return float((agent.feeling - agent.mean_feeling) / agent.days) if agent.predisposed else 0.0
@staticmethod
def _expect(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the expectation of a predisposed employee.
It weighs the first, the mean, and today's feeling.
"""
if not agent.predisposed:
return float(agent.expectation)
weights = agent.primacy + agent.consistency + agent.recency
weighted = agent.primacy * agent.first + agent.consistency * agent.mean_feeling + agent.recency * agent.feeling
return float(weighted / weights)
@staticmethod
def _get_stress(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the change of stress towards its level.
The level is that in sight of a supervisor, an agent of another group, or out.
"""
supervised = any(other.group != agent.group for other in [*agent.get_neighbors(), *agent.get_agents_here()])
if supervised:
return float(agent.alpha_seen * (agent.lambda_seen - agent.stress))
return float(agent.alpha_unseen * (agent.lambda_unseen - agent.stress))
@staticmethod
def _learn(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the growth of the skill of an employee in a day."""
return float(system.rng.normal(agent.skill_growth, np.sqrt(agent.skill_variance)))
@staticmethod
def _leave(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the daily probability that an employee leaves."""
return float(agent.turnover / DAYS_PER_YEAR)
@staticmethod
def _hire(agent: EmployeeView | None, system: SystemViewProtocol) -> dict[str, object]:
"""Return the values of a new hire who replaces a leaving employee.
The new hire keeps its affect.
"""
return {'predisposed': float(system.rng.random() < PREDISPOSED), **dict.fromkeys(HIRE_RESETS, 0.0)}
@staticmethod
def _sum_risk(agent: EmployeeView, system: SystemViewProtocol) -> float:
"""Return the risk.
It is the sum of the predisposition, the disgruntlement, the stress, the skill, and the affect.
"""
return float(agent.predisposed + agent.disgruntlement + agent.stress + agent.skill + agent.affect)
def _work(self, agent: EmployeeView, system: SystemViewProtocol) -> None:
"""Run the day of an employee.
It sets, in order, its feeling, its first feeling, its disgruntlement, its days, its mean feeling, its
expectation, its stress, and its skill.
"""
agent.feeling = float(self._feel(agent, system))
agent.first = float(self._remember_first(agent, system))
agent.disgruntlement = float(self._get_disgruntlement(agent, system))
agent.days = agent.days + float(self._count_day(agent, system))
agent.mean_feeling = agent.mean_feeling + float(self._average(agent, system))
agent.expectation = float(self._expect(agent, system))
agent.stress = agent.stress + float(self._get_stress(agent, system))
agent.skill = agent.skill + float(self._learn(agent, system))
def _set_risk(self, agent: EmployeeView, system: SystemViewProtocol) -> None:
"""Set the risk of an employee to the sum of its factors."""
agent.risk = float(self._sum_risk(agent, system))
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components built from the model parameters."""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
predisposed = (rng.random(self.n_employees) < PREDISPOSED).astype(float)
affect = rng.choice(AFFECTS, self.n_employees, p=AFFECT_SHARES)
employees = EmployeeElement(
'employees',
predisposed=predisposed,
affect=affect,
risk=predisposed + affect,
turnover=self.turnover,
size=self.n_employees,
)
supervisors = Element('supervisors', size=self.n_supervisors)
wandering = MovementInteraction('wandering', target='supervisors', schedule='member')
work = [
MovementInteraction('working', target='employees', schedule='member'),
Interaction('workday', roles={'target': 'employees'}, laws=lambda s: [UpdateLaw(s.target, self._work)]),
BirthDeathInteraction(
'turnover',
target='employees',
death=self._leave,
renew=True,
values=self._hire,
schedule='member',
),
Interaction('risk', roles={'target': 'employees'}, laws=lambda s: [UpdateLaw(s.target, self._set_risk)]),
]
self.system_ = System(
self.label,
elements=[employees, supervisors],
interactions=[wandering, *work],
space=LatticeSpace((self.size, self.size), boundary='periodic', metric='manhattan'),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
MovementInteraction, fromInteraction, through the shared recipeMovementInteractionInteractionBirthDeathInteraction, fromInteraction, through the shared recipeBirthDeathInteraction
class EmployeeElement(Element):
"""Employee of the insider sabotage system, whose risk is the sum of five factors.
The risk is `R = P + D + S + K + A`: the predisposition `P`, the disgruntlement `D` of predisposed employees whose
daily feeling about the organization falls short of their expectation, the stress `S` raised by seeing a supervisor,
the skill `K` that grows every day, and the fixed affect `A`. The expectation weighs the first, the mean, and the
latest feeling. Every day an employee wanders to an adjacent cell and leaves with probability `turnover / 365`,
replaced by a new hire. In `InsiderSabotageSystem`, a movement, a map of every state, and a life cycle that renews
the employees who leave run these steps in turn in the activation of every employee.
Args:
label:
The label of the agent or group.
predisposed:
Whether the employee is predisposed to sabotage, 1, or not, 0.
disgruntlement:
The initial disgruntlement `D`.
stress:
The initial stress `S`.
skill:
The initial skill `K`.
affect:
The affect `A`.
risk:
The initial risk `R`.
days:
The number of days the employee has felt about the organization.
first:
The first feeling.
mean_feeling:
The mean feeling.
expectation:
The expected feeling.
feeling:
The latest feeling.
turnover:
The yearly share of employees who leave.
culture:
The mean daily feeling about the organization.
change:
The variance of the daily feeling.
primacy:
The weight of the first feeling in the expectation.
consistency:
The weight of the mean feeling in the expectation.
recency:
The weight of the latest feeling in the expectation.
affect_weight:
The factor of the shortfall of a feeling in the disgruntlement.
alpha_seen:
The learning rate of stress when a supervisor is in sight.
lambda_seen:
The level stress approaches when a supervisor is in sight.
alpha_unseen:
The learning rate of stress otherwise.
lambda_unseen:
The level stress approaches otherwise.
skill_growth:
The mean daily growth of skill.
skill_variance:
The variance of the daily growth of skill.
size:
The number of members, or `None` for one.
Examples:
>>> from skcomplex.systems.social.organizations import EmployeeElement
>>> group = EmployeeElement('employees', affect=0.5, size=10)
>>> group.label, group.size
('employees', 10)
"""
visual = VisualSpec('agents', {'color_by': 'risk', 'color_range': (0.0, 5.0)})
def __init__(
self,
label: str,
*,
predisposed: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
disgruntlement: object = 0.0,
stress: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
skill: object = 0.0,
affect: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
risk: object = 0.5,
days: Annotated[object, NN] = 0.0,
first: object = 0.0,
mean_feeling: object = 0.0,
expectation: object = 0.0,
feeling: object = 0.0,
turnover: Annotated[object, RealSet.closed_open(0, oo)] = 0.15,
culture: object = 0.8,
change: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
primacy: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
consistency: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
recency: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
affect_weight: object = 1.0,
alpha_seen: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
lambda_seen: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
alpha_unseen: Annotated[object, RealSet.closed_open(0, oo)] = 0.25,
lambda_unseen: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
skill_growth: object = 0.001,
skill_variance: Annotated[object, RealSet.closed_open(0, oo)] = 0.0005,
size: int | None = None,
) -> None:
super().__init__(label, size=size)
self.predisposed = predisposed
self.disgruntlement = disgruntlement
self.stress = stress
self.skill = skill
self.affect = affect
self.risk = risk
self.days = days
self.first = first
self.mean_feeling = mean_feeling
self.expectation = expectation
self.feeling = feeling
self.turnover = turnover
self.culture = culture
self.change = change
self.primacy = primacy
self.consistency = consistency
self.recency = recency
self.affect_weight = affect_weight
self.alpha_seen = alpha_seen
self.lambda_seen = lambda_seen
self.alpha_unseen = alpha_unseen
self.lambda_unseen = lambda_unseen
self.skill_growth = skill_growth
self.skill_variance = skill_variance
class Element(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.
Args:
label:
The name of the element, unique among the components of its system, such as `'rabbits'`.
values:
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.
size:
The number of members, each with its own values, such as `1000` molecules of a gas, or `None` for one.
space:
The space of the element, with one member per site, such as a lattice of cells, or `None` for none.
on:
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.
Attributes:
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
"""
law_classes: ClassVar[tuple[type, ...]] = ()
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
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
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
def _get_value_entries(self) -> dict[str, object]:
"""Return the entries of `values` whose names are Python identifiers."""
values = self.values if isinstance(self.values, Mapping) else {}
return {name: value for name, value in values.items() if name.isidentifier()}
def _prepare(self, context: BaseSpace | None = None) -> None:
"""Set `default_visual_`, checking the reserved names.
Args:
context:
The space the element inherits from its system, which an element with `on` and no space of its own
sits on.
Raises:
ValidationError:
`size` is not a number of members, `space` is not a space, or `values` is not a mapping, as when a
subclass stores a quantity of its own under a reserved name.
"""
super()._prepare(context)
size = self.size
checks = {
'size': size is None or (isinstance(size, numbers.Integral) and not isinstance(size, bool) and size >= 1),
'space': self.space is None or isinstance(self.space, BaseSpace),
'values': self.values is None or isinstance(self.values, Mapping),
}
for name, valid in checks.items():
if not valid:
error_msg = (
f'Element {self.label!r} has {name} = {getattr(self, name)!r}, but {name} is the '
f'{RESERVED_MEANINGS[name]}. The names {", ".join(RESERVED)} are reserved, so rename the value, '
f'such as half_side for the half side of a table.'
)
raise ValidationError(error_msg)
self._check_on(self.space if self.space is not None else context)
def _get_tags(self) -> Tags:
"""Return the tags of the element, with the tags of its space when it has one.
A field on a phase space thus asks for a solver that supports phase spaces, as a group on it does.
"""
tags = super()._get_tags()
if not isinstance(self.space, BaseSpace):
return tags
return replace(tags, space=self.space.get_tags().space)
def _check_on(self, space: BaseSpace | None) -> None:
"""Raise an error for an `on` that names no part of a network space.
A value named `on` that the element declares as its own state or parameter names no place. The space is the
element's own, or else that of its system.
"""
if isinstance(type(self)._get_specs().get('on'), _StateSpec | _ParameterSpec):
return
on = getattr(self, 'on', None)
if on is None or (isinstance(space, NetworkSpace) and (on in LINKS or on in space.prepare().graphs_)):
return
error_msg = (
f'Element {self.label!r} has on = {on!r}, but on is the part of a network space that holds one member '
"each, 'edges', 'hyperedges', or the name of a layer for its edges, such as "
"Element('links', values={'sign': 1}, space=network, on='edges'). The names "
f'{", ".join(RESERVED)} are reserved, so rename a value of the element named on, such as closed for a '
'switch.'
)
raise ValidationError(error_msg)
@staticmethod
def _get_domain_of(annotation: object, value: object) -> object:
"""Return the domain of a value from its annotation or its Python type.
A value without an annotation, such as one given through `values`, takes the domain of its type, so `3` is an
integer and `0.5 + 1j` is complex. The annotation `object` says nothing of the kind, so a value annotated so,
such as a point that may be one number or an array of complex numbers, also takes the domain of its type, and
so does a value of one of several types, such as `float | Sequence[float]`. A subshift, such as
`Annotated[int, SubshiftSpec(LatticeNeighborhood(((0,), (1,))), ((1, 1),))]`, is the domain of the cells of a
lattice whose configurations hold no forbidden word.
"""
if get_origin(annotation) is Annotated:
for item in get_args(annotation)[1:]:
if isinstance(item, set | frozenset):
return FiniteEnumeratedSet(sorted(item, key=str))
allowed = hasattr(item, '__contains__') and not isinstance(item, str | MatrixGroupSpec)
if allowed or isinstance(item, SubshiftSpec | PowerSeriesSpec):
return item
annotation = get_args(annotation)[0]
annotated = isinstance(annotation, type) and annotation not in {inspect.Parameter.empty, object}
kind = annotation if annotated else type(value)
if kind is bool:
return BOOLEAN
if kind is int:
return ZZ
if kind is complex or (isinstance(kind, type) and issubclass(kind, np.complexfloating)):
return CC
return RR
def _get_domain_tags(self) -> frozenset[str]:
"""Return the domain tags of the states of the element.
An element that declares no states has the domains of all its numeric values, since the laws of the system
decide which of them are states, such as `boolean` for `opinion: Annotated[int, {0, 1}] = 0`.
"""
if self._get_component_specs():
return super()._get_domain_tags()
params = self.get_params(deep=False)
values = {name: params.get(name) for name in self._get_hints()}
values |= {name: value for name, value in (self.values or {}).items() if name.isidentifier()}
hints = self._get_hints()
domains = {
_StateSpec(domain=self._get_domain_of(hints.get(name, inspect.Parameter.empty), value))._get_domain_tag()
for name, value in values.items()
if isinstance(value, numbers.Number | list | np.ndarray)
}
return frozenset(domain for domain in domains if domain is not None)
def _get_hints(self) -> dict[str, object]:
"""Return the type hint of every value argument by name, in their order.
The hints are the annotations of the arguments of the class, such as `Annotated[float, Quantity('energy')]`,
from which the kind, the allowed values, the quantity, and the period of each value are read. A generic
subclass that takes its values through `values` gives their hints here instead, and the arguments it leaves
out, such as the allowed values themselves, are no values.
"""
parameters = inspect.signature(type(self)).parameters
return {name: parameter.annotation for name, parameter in parameters.items() if name not in RESERVED}
@classmethod
def _get_view(cls) -> type | None:
"""Return the class of the views of the element's agents.
The result is `None` for the engine's plain view. An agent element names a subclass of the engine's `AgentView`
that annotates its states and parameters, such as `class WordView(AgentView): count: float`, so its rules read
them with checked types.
"""
return None
class MovementInteraction(Interaction):
"""An interaction that moves the agents of a group by steps at every discrete step.
The `step` says where an agent goes:
- `'neighbor'`: a random cell or node next to its own, on a lattice or a network.
- `'gaussian'`: its position plus a normal vector of deviation `scale`, in a continuous space.
- `'levy'`: a random direction and a Pareto length of least value `scale` and tail `exponent`, in a continuous
space.
- `'best'`: the next cell with the highest `score(agent, cell, system)`, or with a `vision` the best cell along each
direction up to that many cells, with ties broken by `ties`.
- A function `step(agent, system)` that returns the destination, or `None` to stay.
An agent for which `condition` holds attempts one step, or a Poisson number of mean `rate`, takes it with the
probability `probability`, and then with the probability `accept(agent, destination, system)`. An exclusive movement
never enters a cell held by another agent of the group. The agents move one after another by `schedule`, and every
step charges its `cost`.
Unlike an `UpdateLaw` on the edges of a network, which changes the space, it changes where agents stand in it.
Choose it when agents walk, forage, or relocate.
It appears in many fields. Sheep wander a pasture, foragers follow Lévy flights, ants climb a pheromone gradient,
and residents move house in the segregation model of Schelling.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the group whose agents move.
step:
The kind of step, `'neighbor'`, `'gaussian'`, `'levy'`, or `'best'`, or a function of the agent and the
system view that returns the destination.
probability:
The probability that an agent takes an attempted step.
rate:
The mean number of attempted steps of an agent in one unit of time, or `None` for one attempt every step.
condition:
A function of the agent and the system view that returns whether the agent moves, or `None` for every agent.
accept:
A function of the agent, its destination, and the system view that returns the probability of taking the
step, or `None` to take every step.
exclusive:
Whether an agent moves only to cells or nodes no other agent of the group holds.
score:
The function of the agent, a neighbouring cell, and the system view that the step `'best'` maximizes.
scale:
The standard deviation of every component of a Gaussian step, or the least length of a Lévy step.
exponent:
The tail exponent of the length of a Lévy step.
cost:
A function of the agent and the system view run for every step taken, such as one that takes the energy a
step costs from the agent, `def pay(agent, system): agent.energy -= 1.0`, or `None`.
vision:
The number of cells the step `'best'` looks along every direction of a lattice, a number or a function of
the agent and the system view, or `None` for the cells next to the agent.
schedule:
The order of the agents, `'sequential'`, `'random-sequential'`, or `'member'`.
phase:
The phase of the step the movement runs in, or `None` for the default phase.
ties:
The cell the step `'best'` takes among cells of equal highest score, `'random'`, `'first'`, or `'nearest'`,
or `None` for `'random'` without a vision and `'nearest'` with one.
Raises:
ValidationError:
The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable, or
the step `'best'` has no score, raised by `prepare`.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.components.spaces import LatticeSpace
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.agents import MovementInteraction
>>> space = LatticeSpace((5, 5), metric='manhattan')
>>> walkers = Element('walkers', values={'x': [2, 2], 'y': [2, 2]}, size=2, space=space)
>>> walk = MovementInteraction('walk', target='walkers', step='neighbor')
>>> trajectory = System(elements=[walkers], interactions=[walk]).prepare().simulate(until=1, random_state=0)
>>> [bool(abs(cell - 2).sum() == 1) for cell in trajectory.get_agents('walkers', 1).locations]
[True, True]
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def _get_draws(self) -> bool:
"""Return whether the movement draws.
It draws by its order, a random step, a probability or rate, or random ties.
"""
ties = self.ties or ('random' if self.vision is None else 'nearest')
drawn = self.step in ('neighbor', 'gaussian', 'levy') or (self.step == 'best' and ties == 'random')
return (
super()._get_draws() or drawn or self.probability != 1 or self.rate is not None or self.accept is not None
)
def __init__(
self,
label: str,
*,
target: Role,
step: Step = 'neighbor',
probability: Annotated[float, RealSet.closed(0, 1)] = 1.0,
rate: float | None = None,
condition: Callable[[AgentViewProtocol, SystemViewProtocol], bool] | None = None,
accept: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
exclusive: bool = False,
score: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
scale: Annotated[float, RealSet.open(0, oo)] = 1.0,
exponent: Annotated[float, RealSet.open(0, oo)] = 1.5,
cost: Cost | None = None,
vision: Vision | None = None,
schedule: str = 'random-sequential',
phase: str | None = None,
ties: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.step = step
self.probability = probability
self.rate = rate
self.condition = condition
self.accept = accept
self.exclusive = exclusive
self.score = score
self.scale = scale
self.exponent = exponent
self.cost = cost
self.vision = vision
self.schedule = schedule
self.phase = phase
self.ties = ties
def _check_functions(self) -> None:
"""Raise an error for a condition, acceptance, score, or cost that is not callable."""
for name in ('condition', 'accept', 'score', 'cost'):
value = getattr(self, name)
if value is not None and not callable(value):
error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function, or None.'
raise ValidationError(error_msg)
def _check_space(self, space: BaseSpace | None) -> None:
"""Raise an error for a step to a neighbouring cell or node in a continuous space."""
if isinstance(self.step, str) and self.step in GRID_STEPS:
self._check_grid('step', self.step, space, "step='gaussian' or step='levy', or a step function")
def _check_arguments(self) -> None:
"""Raise an error for an unknown step, a rate not positive, or a bad function.
Raises:
ValidationError:
The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable,
or the step `'best'` has no score.
"""
super()._check_arguments()
self._check_variant('step', self.step, STEPS, functions=True)
if self.rate is not None and (isinstance(self.rate, bool) or not self.rate > 0):
error_msg = f'The rate of {self.label!r} is {self.rate!r}. Give a positive number, or None.'
raise ValidationError(error_msg)
if self.schedule not in SCHEDULES:
error_msg = f'Unknown schedule {self.schedule!r} of {self.label!r}. Use one of {", ".join(SCHEDULES)}.'
raise ValidationError(error_msg)
if self.ties is not None:
self._check_variant('ties', self.ties, TIES)
if self.vision is not None and not callable(self.vision) and not isinstance(self.vision, int | float):
error_msg = f'The vision of {self.label!r} is {self.vision!r}. Give a number, a function, or None.'
raise ValidationError(error_msg)
if self.step == 'best' and self.score is None:
error_msg = f'The step `best` of {self.label!r} maximizes a score. Pass `score(agent, cell, system)`.'
raise ValidationError(error_msg)
self._check_functions()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = self._get_movement_laws(context)
def _count_attempts(self, system: SystemViewProtocol) -> int:
"""Return the number of steps an agent attempts in one step of time."""
return 1 if self.rate is None else int(system.rng.poisson(self.rate))
def _get_cells(self, agent: AgentViewProtocol, occupied: set[object]) -> list[object]:
"""Return the cells or nodes around an agent that it may move to."""
cells = agent.get_neighbor_cells()
if not self.exclusive:
return cells
return [cell for cell in cells if cell not in occupied]
def _get_best(
self,
agent: AgentViewProtocol,
cells: list[object],
system: SystemViewProtocol,
distances: list[int] | None = None,
) -> object:
"""Return the cell of the highest score, chosen among ties by the tie rule."""
if self.score is None or not cells:
return None
scores = [self.score(agent, cell, system) for cell in cells]
ties = self.ties or ('random' if distances is None else 'nearest')
if ties != 'nearest':
return cells[self._pick_best(scores, ties, system)]
values = np.asarray(scores, dtype=float)
best = np.flatnonzero(values == values.max())
near = np.asarray([1 if distances is None else distances[int(index)] for index in best])
return cells[int(best[near == near.min()][0])]
@staticmethod
def _shift(here: tuple[int, ...], cell: tuple[int, ...], system: SystemViewProtocol) -> tuple[int, ...]:
"""Return the unit step from a cell to a neighbouring cell.
The step goes across the wrapped edge of a torus.
"""
shift = [b - a for a, b in zip(here, cell, strict=True)]
if system.torus:
sizes = [int(item) for item in system.dimensions or ()]
shift = [d - round(d / n) * n for d, n in zip(shift, sizes, strict=True)]
return tuple(shift)
def _get_sight(
self,
agent: AgentViewProtocol,
occupied: set[object],
system: SystemViewProtocol,
) -> tuple[list[object], list[int]]:
"""Return the cells in sight of an agent along every direction of a lattice.
Its own cell comes first, with the distances.
"""
vision = self.vision(agent, system) if callable(self.vision) else self.vision
reach = int(vision or 0)
here = tuple(int(item) for item in np.atleast_1d(np.asarray(agent.location_key)))
sizes = [int(item) for item in system.dimensions or ()]
cells: list[object] = [agent.location_key]
distances = [0]
shifts = [
self._shift(here, tuple(int(item) for item in np.atleast_1d(np.asarray(neighbor))), system)
for neighbor in agent.get_neighbor_cells()
]
for shift in sorted(shifts, key=lambda step: tuple((item == 0, -item) for item in step)):
for distance in range(1, reach + 1):
point = [a + distance * d for a, d in zip(here, shift, strict=True)]
if system.torus:
point = [item % size for item, size in zip(point, sizes, strict=True)]
elif any(not 0 <= item < size for item, size in zip(point, sizes, strict=True)):
break
cell = tuple(point)
if not self.exclusive or cell not in occupied:
cells.append(cell)
distances.append(distance)
return cells, distances
def _get_destination(self, agent: AgentViewProtocol, system: SystemViewProtocol, occupied: set[object]) -> object:
"""Return the location a step of an agent leads to, or `None` to stay."""
rng = system.rng
if callable(self.step):
return self.step(agent, system)
if self.step == 'best' and self.vision is not None:
cells, distances = self._get_sight(agent, occupied, system)
return self._get_best(agent, cells, system, distances)
if self.step in ('neighbor', 'best'):
cells = self._get_cells(agent, occupied)
if self.step == 'best':
return self._get_best(agent, cells, system)
return cells[int(rng.integers(len(cells)))] if cells else None
position = np.asarray(agent.location, dtype=float)
if self.step == 'gaussian':
return position + rng.normal(0.0, self._get_parameter_value('scale', system), position.shape)
direction = rng.normal(size=position.shape)
length = self._get_parameter_value('scale', system) * (
1.0 + rng.pareto(self._get_parameter_value('exponent', system))
)
return position + length * direction / np.linalg.norm(direction)
def _charge(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Charge the cost of one step taken to an agent."""
if self.cost is not None:
self.cost(agent, system)
def _take(self, agent: AgentViewProtocol, destination: object, occupied: set[object]) -> bool:
"""Move an agent to a destination unless an exclusive movement finds it held.
It returns whether it moved.
"""
if not self.exclusive:
agent.move_to(destination)
return True
if destination == agent.location_key:
return True
if destination in occupied:
return False
occupied.discard(agent.location_key)
agent.move_to(destination)
occupied.add(agent.location_key)
return True
def _move(
self,
agent: AgentViewProtocol,
system: SystemViewProtocol,
probability: float,
occupied: set[object],
) -> None:
"""Take the attempted steps of one agent.
Each step has its probability and acceptance, and every step is charged.
"""
for _ in range(self._count_attempts(system)):
if probability < 1.0 and system.rng.random() >= probability:
continue
destination = self._get_destination(agent, system, occupied)
if destination is None:
continue
if self.accept is not None and system.rng.random() >= self.accept(agent, destination, system):
continue
if self._take(agent, destination, occupied):
self._charge(agent, system)
def _move_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Move one agent whose condition holds, in its own activation."""
if agent.alive and (self.condition is None or self.condition(agent, system)):
occupied = (
{other.location_key for other in system.get_agents(self._get_role('target'))}
if self.exclusive
else set()
)
self._move(agent, system, self._get_parameter_value('probability', system), occupied)
def _move_all(self, system: SystemViewProtocol) -> None:
"""Move every agent of the group whose condition holds.
They move in their order or in random order.
"""
agents = system.get_agents(self._get_role('target'))
occupied = {agent.location_key for agent in agents} if self.exclusive else set()
probability = self._get_parameter_value('probability', system)
order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
for index in order:
agent = agents[int(index)]
if agent.alive and (self.condition is None or self.condition(agent, system)):
self._move(agent, system, probability, occupied)
def _get_movement_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the rule of the movement.
Args:
namespace:
The namespace of the symbols the laws can use.
Returns:
laws:
The rule that moves the agents every step.
"""
if self.schedule == 'member':
return [UpdateLaw(self._get_member(namespace, 'target'), self._move_member, phase=self.phase)]
return [UpdateLaw(namespace, self._move_all, phase=self.phase)]
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 BirthDeathInteraction(Interaction):
"""An interaction by which the agents of a group give birth to offspring and die.
At every step of discrete time each agent acts once, by `schedule`. An agent dies with the probability `death`. An
agent that survives gives birth with the probability `birth`, or as many times as a Poisson number of mean `rate`,
and every birth creates `offspring` new agents of `group`, or of the group of the parent. A probability is a number
or a function of the agent and the system view, and a function that returns a condition gives probability one where
it holds. The new agents stand where `placement` says: in the cell of the parent, in a free neighbouring cell, or
where a function returns.
A new agent copies the states `inherit` of its parent, takes the values that `values(parent, system)` returns, and
shares the states `split` with its parent, which keeps the share `keep`. Then `mutate` may change its values.
Further options reset or replace the parent, renew a dying agent in place, cull a member of a kin group, and add
arrivals without a parent, as their arguments describe. The process reports the `births`, `deaths`, and `arrivals`
of every step.
Unlike a `JumpLaw`, which changes numeric states of a fixed set of members, it adds and removes agents, each with
states of its own. Choose it when a population of individuals grows, shrinks, and passes traits to offspring.
It appears in many fields. Rabbits breed and wolves starve in a predator and prey model, cells divide and die in a
tumour, firms enter and exit a market, and households form and dissolve in a model of demography.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the variable group whose agents give birth and die.
birth:
The probability that an agent gives birth in a step, or `None` for no births by probability.
death:
The probability that an agent dies in a step, or `None` for no deaths.
rate:
The mean number of births of an agent in a step, a number or a function, or `None` for no births by rate.
offspring:
The number of new agents of a birth.
placement:
Where a new agent stands, `'here'`, `'neighbor'`, or a function of the parent, `None` for an arrival, and
the system view that returns its location.
inherit:
The names of the states a new agent copies from its parent.
split:
The names of the states the parent shares with its offspring.
mutate:
A function of the values of a new agent and the system view that returns its values, or `None`.
schedule:
The order of the agents, `'sequential'`, `'random-sequential'`, or `'member'`.
phase:
The phase of the step the process runs in, or `None` for the default phase.
group:
The path of the variable group the new agents join, or `None` for the group of the target.
values:
A function of the parent, `None` for an arrival, and the system view that returns values of a new agent by
state name, or `None`.
keep:
The share of every split state the parent keeps, a number or a function, or `None` for an equal share.
reset:
The values a parent takes after it gives birth, by state name, or `None`.
replace:
Whether a parent that gives birth is removed.
renew:
Whether an agent that dies is renewed in place instead of removed.
cull:
The probability that an agent removes one member of `group`, or of the target without a group, in a
step, or `None` for no removals.
kin:
A function of an agent and a member of `group` that returns whether the agent may remove the member, or
`None` for every member.
arrival:
The mean number of new agents that arrive in a step without a parent, or `None` for no arrivals.
pick:
Which member of `group` a removal takes among those it may remove, `'first'` or `'random'`.
Raises:
ValidationError:
The placement, the schedule, or the pick is unknown, both a birth probability and a rate are given, a
function is not callable, or the schedule `'member'` has arrivals, raised by `prepare`.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.components.spaces import LatticeSpace
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.agents import BirthDeathInteraction
>>> cells = Element('cells', values={'mass': 8.0}, size=1, space=LatticeSpace((3, 3)))
>>> division = BirthDeathInteraction('division', target='cells', birth=1.0, split=('mass',))
>>> trajectory = System(elements=[cells], interactions=[division]).prepare().simulate(until=2, random_state=0)
>>> trajectory.get_agents('cells', 2).values['mass'].tolist()
[2.0, 2.0, 2.0, 2.0]
"""
reports: ClassVar[tuple[str, ...]] = ('births', 'deaths', 'arrivals')
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def _get_tags(self) -> Tags:
"""Return the tags of the rules of births and deaths.
These rules change the membership of groups.
"""
return self._get_variant_tags((UpdateLaw,), structure=frozenset({'variable membership'}))
def _get_draws(self) -> bool:
"""Return whether the cycle draws.
It draws by its order or pick, events of a chance below 1, rates, or free cells.
"""
chances = (self.birth, self.death, self.cull)
return (
super()._get_draws()
or any(callable(chance) or (chance is not None and 0 < chance < 1) for chance in chances)
or self.rate is not None
or self.arrival is not None
or self.placement == 'neighbor'
)
def __init__(
self,
label: str,
*,
target: Role,
birth: Chance | None = None,
death: Chance | None = None,
rate: Chance | None = None,
offspring: Count = 1,
placement: Placement = 'here',
inherit: Sequence[str] = (),
split: Sequence[str] = (),
mutate: Mutation | None = None,
schedule: str = 'random-sequential',
phase: str | None = None,
group: Role | None = None,
values: Values | None = None,
keep: Chance | None = None,
reset: Mapping[str, object] | None = None,
replace: bool = False,
renew: bool = False,
cull: Chance | None = None,
kin: Kinship | None = None,
arrival: Arrival | None = None,
pick: str = 'first',
) -> None:
super().__init__(label)
self.target = target
self.birth = birth
self.death = death
self.rate = rate
self.offspring = offspring
self.placement = placement
self.inherit = inherit
self.split = split
self.mutate = mutate
self.schedule = schedule
self.phase = phase
self.group = group
self.values = values
self.keep = keep
self.reset = reset
self.replace = replace
self.renew = renew
self.cull = cull
self.kin = kin
self.arrival = arrival
self.pick = pick
def _check_variants(self) -> None:
"""Raise an error for an unknown placement, schedule, pick, or arrival schedule.
The arrivals may not have a member schedule.
"""
self._check_variant('placement', self.placement, PLACEMENTS, functions=True)
self._check_variant('schedule', self.schedule, SCHEDULES)
self._check_variant('pick', self.pick, PICKS)
if self.schedule == 'member' and self.arrival is not None:
error_msg = f'{self.label!r} runs member by member, so no agent brings arrivals. Give `arrival=None`.'
raise ValidationError(error_msg)
def _check_space(self, space: BaseSpace | None) -> None:
"""Raise an error for a placement in a neighbouring cell or node.
The error is for a continuous space.
"""
if self.placement == 'neighbor':
self._check_grid('placement', self.placement, space, "placement='here', or a placement function")
def _check_arguments(self) -> None:
"""Raise an error for an unknown placement, a doubled birth, or a bad function.
Raises:
ValidationError:
The placement, the schedule, or the pick is unknown, both a birth probability and a rate are given,
a value is neither a number nor a function, or the schedule `'member'` has arrivals.
"""
super()._check_arguments()
self._check_variants()
if self.birth is not None and self.rate is not None:
error_msg = f'{self.label!r} gives births by a probability and by a rate. Give one of them.'
raise ValidationError(error_msg)
for name in ('birth', 'death', 'rate', 'offspring', 'keep', 'cull', 'arrival'):
value = getattr(self, name)
if value is not None and not callable(value) and not isinstance(value, int | float):
error_msg = f'The {name} of {self.label!r} is {value!r}. Give a number or a function.'
raise ValidationError(error_msg)
for name in ('mutate', 'values', 'kin'):
value = getattr(self, name)
if value is not None and not callable(value):
error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function, or None.'
raise ValidationError(error_msg)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = self._get_birth_death_laws(context)
@staticmethod
def _evaluate(value: Chance | Count, agent: AgentViewProtocol, system: SystemViewProtocol) -> float:
"""Return a number, or the value of a function of an agent and the view.
The view is the system view, and the value is returned as a float.
"""
return float(value(agent, system) if callable(value) else value)
def _happens(self, chance: Chance | None, agent: AgentViewProtocol, system: SystemViewProtocol) -> bool:
"""Return whether an event of a probability happens to an agent in this step."""
if chance is None:
return False
probability = self._evaluate(chance, agent, system)
return probability >= 1.0 or (probability > 0.0 and system.rng.random() < probability)
def _count_births(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> int:
"""Return the number of births of a parent in this step."""
if self.rate is not None:
return int(system.rng.poisson(self._evaluate(self.rate, agent, system)))
return int(self._happens(self.birth, agent, system))
def _get_places(
self,
agent: AgentViewProtocol,
count: int,
occupied: set[object],
system: SystemViewProtocol,
) -> list[object]:
"""Return the locations of the new agents of a parent, fewer when places run out."""
if callable(self.placement):
places = [self.placement(agent, system) for _ in range(count)]
return [place for place in places if place is not None]
if self.placement == 'here':
return [agent.location] * count
free = [cell for cell in agent.get_neighbor_cells() if cell not in occupied]
chosen = [free[int(index)] for index in system.rng.permutation(len(free))[:count]]
occupied.update(chosen)
return chosen
def _get_values(self, agent: AgentViewProtocol | None, system: SystemViewProtocol) -> dict[str, object]:
"""Return the inherited and given values of a new agent.
The agent is the agent of a parent, or an arrival.
"""
values: dict[str, object] = {} if agent is None else {name: getattr(agent, name) for name in self.inherit}
if self.values is not None:
values.update(self.values(agent, system))
return values
def _create(
self,
agent: AgentViewProtocol | None,
place: object,
values: dict[str, object],
system: SystemViewProtocol,
) -> None:
"""Create a new agent with mutated values at a place in the group of the cycle.
The place is `None` for a random one.
"""
if self.mutate is not None:
values = self.mutate(values, system)
if self.group is not None:
system.create(self._get_role('group'), place, **values)
elif agent is not None:
agent.create(None, place, **values)
else:
system.create(self._get_role('target'), place, **values)
def _bear(self, agent: AgentViewProtocol, places: list[object], system: SystemViewProtocol) -> None:
"""Create the new agents of a parent at their places.
Their values are inherited, given, split, and mutated.
"""
kept = 1 / (len(places) + 1) if self.keep is None else self._evaluate(self.keep, agent, system)
totals = {name: float(getattr(agent, name)) for name in self.split}
for name, amount in totals.items():
setattr(agent, name, amount * kept)
shares = {name: (amount - amount * kept) / max(len(places), 1) for name, amount in totals.items()}
for place in places:
values = self._get_values(agent, system)
values.update(shares)
self._create(agent, place, values, system)
def _renew(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Give an agent that dies the values of an offspring of its own, in place."""
values = self._get_values(agent, system)
if self.mutate is not None:
values = self.mutate(values, system)
for name, value in values.items():
setattr(agent, name, value)
def _remove_kin(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Remove the first or a random kin of an agent from the group of the cycle.
It removes a member of the group that is kin of the agent, if there is one.
"""
kin = self.kin
group = self._get_role('target' if self.group is None else 'group')
members = (item for item in system.get_agents(group) if item.alive and (kin is None or kin(agent, item)))
if self.pick == 'random':
candidates = list(members)
if candidates:
candidates[int(system.rng.integers(len(candidates)))].remove()
return
member = next(members, None)
if member is not None:
member.remove()
def _die(self, agent: AgentViewProtocol, occupied: set[object], system: SystemViewProtocol) -> None:
"""Renew an agent in place, or remove it and free its cell."""
if self.renew:
self._renew(agent, system)
return
occupied.discard(agent.location_key)
agent.remove()
def _act(self, agent: AgentViewProtocol, occupied: set[object], system: SystemViewProtocol) -> tuple[int, int]:
"""Let an agent die, or give birth and remove kin.
It returns its numbers of new agents and deaths.
"""
if self._happens(self.death, agent, system):
self._die(agent, occupied, system)
return 0, 1
born, died = self._give_birth(agent, occupied, system)
if self._happens(self.cull, agent, system):
self._remove_kin(agent, system)
return born, died
def _give_birth(
self,
agent: AgentViewProtocol,
occupied: set[object],
system: SystemViewProtocol,
) -> tuple[int, int]:
"""Let an agent give birth.
It returns its number of new agents and whether it was replaced.
"""
born = 0
events = self._count_births(agent, system)
if events > 0:
births = events * int(self._evaluate(self.offspring, agent, system))
places = self._get_places(agent, births, occupied, system) if births else []
if places or self.split:
self._bear(agent, places, system)
born = len(places)
for name, value in (self.reset or {}).items():
setattr(agent, name, value)
if self.replace:
occupied.discard(agent.location_key)
agent.remove()
return born, 1
return born, 0
def _arrive(self, system: SystemViewProtocol) -> int:
"""Create the agents that arrive without a parent in this step.
It returns their number.
"""
if self.arrival is None:
return 0
mean = self.arrival(system) if callable(self.arrival) else self.arrival
count = int(system.rng.poisson(float(mean)))
for _ in range(count):
place = self.placement(None, system) if callable(self.placement) else None
self._create(None, place, self._get_values(None, system), system)
return count
def _live_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Run the process of one agent in its own activation."""
if not agent.alive:
return
neighbor = self.placement == 'neighbor'
occupied = {other.location_key for other in system.get_agents(self._get_role('target'))} if neighbor else set()
self._act(agent, occupied, system)
def _live(self, system: SystemViewProtocol) -> None:
"""Remove or renew the dying agents and create the offspring of the bearing ones.
It follows the schedule, and creates the offspring of those that give birth.
"""
agents = system.get_agents(self._get_role('target'))
occupied = {agent.location_key for agent in agents} if self.placement == 'neighbor' else set()
births = deaths = 0
order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
for index in order:
agent = agents[int(index)]
if not agent.alive:
continue
born, died = self._act(agent, occupied, system)
births, deaths = births + born, deaths + died
system.report('births', births)
system.report('deaths', deaths)
system.report('arrivals', self._arrive(system))
def _get_birth_death_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the rule of the process.
Args:
namespace:
The namespace of the symbols the laws can use.
Returns:
laws:
The rule that removes and creates agents every step.
"""
if self.schedule == 'member':
return [UpdateLaw(self._get_member(namespace, 'target'), self._live_member, phase=self.phase)]
return [UpdateLaw(namespace, self._live, phase=self.phase)]