Agents
Define the agent rules that the systems of several fields share.
Agents move, give birth and die, choose among options, imitate their neighbours, and evolve their strategies.
BirthDeathInteraction(label, *, target, birth=None, death=None, rate=None, offspring=1, placement='here', inherit=(), split=(), mutate=None, schedule='random-sequential', phase=None, group=None, values=None, keep=None, reset=None, replace=False, renew=False, cull=None, kin=None, arrival=None, pick='first')
Bases: 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label of the interaction, unique among the components of its system. |
required |
target
|
Role
|
The path of the variable group whose agents give birth and die. |
required |
birth
|
Chance | None
|
The probability that an agent gives birth in a step, or |
None
|
death
|
Chance | None
|
The probability that an agent dies in a step, or |
None
|
rate
|
Chance | None
|
The mean number of births of an agent in a step, a number or a function, or |
None
|
offspring
|
Count
|
The number of new agents of a birth. |
1
|
placement
|
Placement
|
Where a new agent stands, |
'here'
|
inherit
|
Sequence[str]
|
The names of the states a new agent copies from its parent. |
()
|
split
|
Sequence[str]
|
The names of the states the parent shares with its offspring. |
()
|
mutate
|
Mutation | None
|
A function of the values of a new agent and the system view that returns its values, or |
None
|
schedule
|
str
|
The order of the agents, |
'random-sequential'
|
phase
|
str | None
|
The phase of the step the process runs in, or |
None
|
group
|
Role | None
|
The path of the variable group the new agents join, or |
None
|
values
|
Values | None
|
A function of the parent, |
None
|
keep
|
Chance | None
|
The share of every split state the parent keeps, a number or a function, or |
None
|
reset
|
Mapping[str, object] | None
|
The values a parent takes after it gives birth, by state name, or |
None
|
replace
|
bool
|
Whether a parent that gives birth is removed. |
False
|
renew
|
bool
|
Whether an agent that dies is renewed in place instead of removed. |
False
|
cull
|
Chance | None
|
The probability that an agent removes one member of |
None
|
kin
|
Kinship | None
|
A function of an agent and a member of |
None
|
arrival
|
Arrival | None
|
The mean number of new agents that arrive in a step without a parent, or |
None
|
pick
|
str
|
Which member of |
'first'
|
Raises:
| Type | Description |
|---|---|
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 |
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]
Source code in src/skcomplex/systems/general/agents/_birth_death.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
ChoiceInteraction(label, *, target, state, options, utility, rule='logit', intensity=1.0, schedule=None, activity=1.0, phase=None, proposal='others', ties='random')
Bases: Interaction
An interaction by which members of a group choose among options by utility.
At every step each member revises its choice with the probability activity and keeps it otherwise. The rule
draws the new option from the utilities u_k of the options:
'logit': optionkwith probabilityexp(beta u_k) / sum_j exp(beta u_j), wherebetais the intensity of choice.'metropolis'and'fermi': a proposed option, accepted with probabilitymin(1, exp(beta (u_new - u_old)))or1 / (1 + exp(-beta (u_new - u_old))).'best': an option of largest utility, with ties broken byties.
Without a schedule it sets update laws: utility(namespace, option) returns an expression, and every member
draws at once. With a schedule it sets one rule of the whole system that walks the agents in that order with its
own draws: utility(agent, system, option) returns a number, and an option of utility -inf is never drawn.
Unlike a JumpLaw, which moves a state between values by given rates, it draws the new value from the utilities of
all options at once. Choose it when members pick the option that pays best, with noise.
It appears in many fields. Commuters choose a mode of transport, consumers choose a brand, farmers choose a crop, and voters choose a party by a logit model of discrete choice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label of the interaction, unique among the components of its system. |
required |
target
|
Role
|
The path of the element or group whose members choose. |
required |
state
|
str
|
The name of the discrete state of the members that holds the chosen option. |
required |
options
|
Sequence[float]
|
The values the state can take, at least two. |
required |
utility
|
Callable[..., float | Expression]
|
The function |
required |
rule
|
str
|
The rule of the draw, |
'logit'
|
intensity
|
Annotated[float, closed_open(0, oo)]
|
The intensity of choice |
1.0
|
schedule
|
str | None
|
The order in which a rule walks the agents, |
None
|
activity
|
Annotated[float, closed(0, 1)]
|
The probability that a member revises its choice in a step. |
1.0
|
phase
|
str | None
|
The phase of the step the rule of a schedule runs in, or |
None
|
proposal
|
str
|
The options the rules |
'others'
|
ties
|
str
|
The option the rule |
'random'
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The rule, the schedule, the proposal, or the ties are unknown, there are fewer than two options, or the utility is not callable. |
Examples:
>>> from skcomplex.systems.general.agents import ChoiceInteraction
>>> from skcomplex.core.components.laws.utils import mean
>>> choice = ChoiceInteraction(
... 'choice', target='spins', state='spin', options=(-1, 1), utility=lambda s, o: o * mean(s.target.spin)
... )
>>> choice.rule
'logit'
>>> agents = ChoiceInteraction(
... 'choice', target='traders', state='plan', options=(0, 1), utility=lambda a, m, o: o,
... schedule='synchronous',
... )
>>> type(agents.prepare(SimpleNamespace(target=SimpleNamespace())).laws_[0]).__name__
'UpdateLaw'
>>> ChoiceInteraction(
... 'heat-bath', target='spins', state='spin', options=(-1, 0, 1), utility=lambda s, o: o, rule='fermi',
... proposal='all'
... ).proposal
'all'
Source code in src/skcomplex/systems/general/agents/_choice.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
choose(system)
Set the state of every revising agent to the option it draws, by the schedule.
An agent revises in this step. Without a schedule every agent draws at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
SystemViewProtocol
|
The system view of the interaction. |
required |
Source code in src/skcomplex/systems/general/agents/_choice.py
319 320 321 322 323 324 325 326 327 328 | |
EvolutionInteraction(label, *, target, strategy='strategy', fitness='fitness', selection='tournament', replacement='generational', crossover=0.7, mutation=0.01, elite=0, tournament=2, alphabet=2, scale=0.1, death=0.1, change='other', parents='survivors', fraction=0.1, period=1, evaluate=None, reset=None, phase=None)
Bases: Interaction
An interaction that breeds the strategies of a group by selection and mutation.
Every period steps the interaction selects parents by their fitness and replaces strategies by offspring. The
selection picks parents by tournaments, by roulette, in proportion to fitness, or by rank. The replacement says
how offspring take their places:
'generational': every member is replaced by an offspring of a pair of parents, which exchange the tails of their strategies with probabilitycrossover, and theelitefittest pass unchanged.'moran': one birth and death at a time, a selected parent copying onto a random member.'death-birth': members die with probabilitydeathand the offspring of survivors fill their places.'truncation': thefractionleast fit are replaced by the offspring of the others.'best-mutant': every member draws a mutant, and the fittest mutant spreads when it beats the fittest strategy.
Each gene of an offspring mutates with probability mutation by the rule change, or a function
mutation(strategy, rng) returns the mutated copy. The fitness is a state of the members, or the function
evaluate(strategies, system), which the replacement writes into the fitness state.
Unlike ImitationInteraction, by which members copy neighbours, it replaces strategies by the offspring of the
fittest across the group. Choose it when strategies evolve by selection, crossover, and mutation.
It appears in many fields. Genetic algorithms search for designs, strategies of the iterated prisoner's dilemma evolve in tournaments, and genotypes evolve on a fitness landscape in population genetics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label of the interaction, unique among the components of its system. |
required |
target
|
Role
|
The path of the agent group whose strategies evolve. |
required |
strategy
|
str | Sequence[str]
|
The name of the state of the members that holds the strategy, a sequence of genes, or the names of several states, one gene each. |
'strategy'
|
fitness
|
str | None
|
The name of the state of the members that holds the fitness, or |
'fitness'
|
selection
|
str
|
The selection of parents, |
'tournament'
|
replacement
|
str
|
The replacement of strategies, |
'generational'
|
crossover
|
Annotated[float, closed(0, 1)]
|
The probability that a pair of parents exchanges the tails of their strategies, in the generational replacement. |
0.7
|
mutation
|
float | Callable[[Array, Generator], Array]
|
The probability that a gene mutates, or a function |
0.01
|
elite
|
int
|
The number of fittest strategies copied unchanged, in the generational replacement. |
0
|
tournament
|
int
|
The number of entrants of every tournament. |
2
|
alphabet
|
int | None
|
The number of symbols of a discrete strategy, or |
2
|
scale
|
float
|
The standard deviation of the mutation of a real strategy. |
0.1
|
death
|
Annotated[float, closed(0, 1)]
|
The probability that a member is replaced in a step, in the death-birth replacement. |
0.1
|
change
|
str
|
How a gene mutates, |
'other'
|
parents
|
str
|
The members the death-birth replacement selects parents among, |
'survivors'
|
fraction
|
Annotated[float, closed(0, 1)]
|
The fraction of least fit members that the truncation replacement replaces. |
0.1
|
period
|
int
|
The number of steps, or rounds of the phase, between two replacements. |
1
|
evaluate
|
Callable[[Array, SystemViewProtocol], Array] | None
|
The function |
None
|
reset
|
Mapping[str, float] | None
|
The values of states that every replaced member takes, or |
None
|
phase
|
str | None
|
The phase of the step the generation runs in, or |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
A variant is unknown, a probability is outside |
Examples:
>>> from types import SimpleNamespace
>>> from skcomplex.systems.general.agents import EvolutionInteraction
>>> evolution = EvolutionInteraction('evolution', target='agents', selection='roulette', phase='breeding')
>>> evolution.prepare(SimpleNamespace(target=SimpleNamespace())).laws_[0].phase
'breeding'
>>> EvolutionInteraction('evolution', target='agents', selection='rank', replacement='moran').selection
'rank'
>>> EvolutionInteraction(
... 'evolution', target='agents', replacement='truncation', fraction=0.2, change='any', period=50
... ).period
50
Source code in src/skcomplex/systems/general/agents/_evolution.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
ImitationInteraction(label, *, target, state='state', payoff='payoff', options=(0.0, 1.0), rate=1.0, rule='random', intensity=1.0, probability=None, layer=None, phase=None, schedule=None, ties='first')
Bases: Interaction
An interaction by which members copy a discrete state from their neighbours.
The rule says whom a member copies:
'random': a random neighbour.'majority': the option that more of its neighbours hold than any other.'best': the neighbour with the largest payoff, when it beats its own.'better': a random neighbour, when its payoff beats its own, with a schedule only.'fermi': a random neighbour, with probability1 / (1 + exp(-beta (P_j - P_i))), whereP_jandP_iare the payoffs of the neighbour and the member.
Without a schedule it sets symbolic laws: jumps at the rate rate in continuous time, or, when probability is
given, updates with that probability per step for every member at once. With a schedule it sets one rule of the
whole system that walks the agents in that order with its own draws. A member without such a neighbour keeps its
state.
Unlike a sum of neighbors in a RateLaw, which averages numeric states of neighbours, it copies one discrete
value from them. Choose it when members adopt the choices of those around them.
It appears in many fields. Voters copy their friends in the voter model, players copy successful strategies in evolutionary games on networks, and farmers adopt the crops of their neighbours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label of the interaction, unique among the components of its system. |
required |
target
|
Role
|
The path of the group on the nodes or sites. |
required |
state
|
str
|
The name of the discrete state of the members. |
'state'
|
payoff
|
str
|
The name of the state that holds the payoff of the members, which the rules |
'payoff'
|
options
|
Sequence[float]
|
The values the state takes. |
(0.0, 1.0)
|
rate
|
Annotated[float, closed_open(0, oo)]
|
The rate at which every member imitates in continuous time. |
1.0
|
rule
|
str
|
|
'random'
|
intensity
|
Annotated[float, closed_open(0, oo)]
|
The intensity |
1.0
|
probability
|
Annotated[float, closed(0, 1)] | None
|
The probability that a member imitates in a step, or |
None
|
layer
|
str | None
|
The layer of the network whose edges the interaction runs on, or |
None
|
phase
|
str | None
|
The phase of the step the updates of a probability or the rule of a schedule run in, or |
None
|
schedule
|
str | None
|
The order in which a rule walks the agents, |
None
|
ties
|
str
|
The neighbour the rule |
'first'
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The rule, the schedule, or the ties are unknown, the rule |
Examples:
>>> from skcomplex.systems.general.agents import ImitationInteraction
>>> ImitationInteraction('imitation', target='voters', rule='majority').options
(0.0, 1.0)
>>> ImitationInteraction('imitation', target='players', rule='fermi', probability=0.5).probability
0.5
>>> ImitationInteraction('imitation', target='traders', rule='better', schedule='synchronous').rule
'better'
Source code in src/skcomplex/systems/general/agents/_imitation.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
MovementInteraction(label, *, target, step='neighbor', probability=1.0, rate=None, condition=None, accept=None, exclusive=False, score=None, scale=1.0, exponent=1.5, cost=None, vision=None, schedule='random-sequential', phase=None, ties=None)
Bases: 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 deviationscale, in a continuous space.'levy': a random direction and a Pareto length of least valuescaleand tailexponent, in a continuous space.'best': the next cell with the highestscore(agent, cell, system), or with avisionthe best cell along each direction up to that many cells, with ties broken byties.- A function
step(agent, system)that returns the destination, orNoneto 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label of the interaction, unique among the components of its system. |
required |
target
|
Role
|
The path of the group whose agents move. |
required |
step
|
Step
|
The kind of step, |
'neighbor'
|
probability
|
Annotated[float, closed(0, 1)]
|
The probability that an agent takes an attempted step. |
1.0
|
rate
|
float | None
|
The mean number of attempted steps of an agent in one unit of time, or |
None
|
condition
|
Callable[[AgentViewProtocol, SystemViewProtocol], bool] | None
|
A function of the agent and the system view that returns whether the agent moves, or |
None
|
accept
|
Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None
|
A function of the agent, its destination, and the system view that returns the probability of taking the
step, or |
None
|
exclusive
|
bool
|
Whether an agent moves only to cells or nodes no other agent of the group holds. |
False
|
score
|
Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None
|
The function of the agent, a neighbouring cell, and the system view that the step |
None
|
scale
|
Annotated[float, open(0, oo)]
|
The standard deviation of every component of a Gaussian step, or the least length of a Lévy step. |
1.0
|
exponent
|
Annotated[float, open(0, oo)]
|
The tail exponent of the length of a Lévy step. |
1.5
|
cost
|
Cost | None
|
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, |
None
|
vision
|
Vision | None
|
The number of cells the step |
None
|
schedule
|
str
|
The order of the agents, |
'random-sequential'
|
phase
|
str | None
|
The phase of the step the movement runs in, or |
None
|
ties
|
str | None
|
The cell the step |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable, or
the step |
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]
Source code in src/skcomplex/systems/general/agents/_movement.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |