Tragedy of the meadow commons
Herders whose cows graze a shared meadow, until the grass collapses.
- Class:
TragedyOfTheCommonsSystem - Import:
from skcomplex.systems.economics.resources import TragedyOfTheCommonsSystem - Field:
economics/resources - Topics:
commons,agents,overgrazing,regulation,grid - References:
- Hamill and Gilbert 2016 sec. 10.2
- Hardin 1968
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.economics.resources import TragedyOfTheCommonsSystem
trajectory = TragedyOfTheCommonsSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_herders |
20 |
width |
20 |
height |
20 |
cows |
1 |
quota |
None |
regrowth |
0.2 |
capacity |
2.0 |
upkeep |
0.3 |
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 | integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class TragedyOfTheCommonsSystem(BaseSystem):
"""Herders whose cows graze a shared meadow, until the grass collapses.
Each herder adds cows while a cow pays. Every step every cow moves to the richest pasture it can reach, eats, and
earns its herder milk, and the grass grows back logistically. Every herder adds a cow whenever a cow earned more
than its upkeep, since the gain of a cow goes to its herder while the cost of the grass it eats falls on all. With
more herders than the meadow carries, the herd grows past what the grass sustains, the grass collapses below a tenth
of its capacity, and the cows starve, so the herd shrinks after it. A regulator with an adaptive quota of cows per
herder, lowered when the grass runs short and raised when it recovers, keeps the meadow from collapse (Hamill and
Gilbert 2016 sec. 10.2).
The system has the groups `meadow`, `cows`, and `herders`, whose adaptive parameter `quota` the regulator
`regulator` changes, and the grazing `grazing`.
Args:
n_herders:
The number of herders.
width:
The number of columns of the meadow.
height:
The number of rows of the meadow.
cows:
The initial number of cows of every herder.
quota:
The initial quota of cows per herder of a regulator that adapts it, or `None` for no regulation.
regrowth:
The logistic growth rate of the grass.
capacity:
The most grass a cell holds.
upkeep:
The cost of keeping a cow for a step.
random_state:
The seed or generator of the cells of the cows.
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.economics.resources import TragedyOfTheCommonsSystem
>>> [group.size for group in TragedyOfTheCommonsSystem(4, width=5, height=5).prepare().system_.elements]
[25, 4, 4]
"""
field = 'economics/resources'
topics = ('commons', 'agents', 'overgrazing', 'regulation', 'grid')
references = ('Hamill and Gilbert 2016 sec. 10.2', 'Hardin 1968')
until = 100
observables = (
Observable('grass', group='meadow', variable='grass', reduce='sum'),
Observable('herd', group='cows', variable='energy', reduce='count'),
Observable('quota', group='herders', variable='quota', reduce='mean'),
)
@staticmethod
def _get_pays(herder: AgentViewProtocol, system: SystemViewProtocol) -> bool:
"""Return whether a cow of a herder earned more than its upkeep in the last step.
The herd must also be below quota.
"""
del system
if not isinstance(herder, HerderView):
return False
earning = herder.income / herder.herd if herder.herd else herder.upkeep + 1
return earning > herder.upkeep and herder.herd < herder.quota
@staticmethod
def _get_exceeds(herder: AgentViewProtocol, system: SystemViewProtocol) -> bool:
"""Return whether the herd of a herder in the last step exceeds its quota.
The herder then sells a cow.
"""
del system
return isinstance(herder, HerderView) and herder.herd > herder.quota
@staticmethod
def _get_owns(herder: AgentViewProtocol, cow: AgentViewProtocol) -> bool:
"""Return whether a herder owns a cow.
The value `owner` of the cow names the herder.
"""
return cow.get_referenced('owner') is herder
@staticmethod
def _get_calf(herder: AgentViewProtocol | None, system: SystemViewProtocol) -> dict[str, object]:
"""Return the owner and the energy of a new cow of a herder."""
del system
if not isinstance(herder, HerderView):
return {}
return {'owner': float(herder.id), 'energy': herder.newborn}
@staticmethod
def _get_cell(herder: AgentViewProtocol | None, system: SystemViewProtocol) -> tuple[int, ...]:
"""Return a random cell of the meadow, where a new cow starts."""
del herder
return tuple(int(system.rng.integers(int(size))) for size in system.dimensions or ())
@staticmethod
def _clear(herder: HerderView, system: SystemView) -> None:
"""Clear the income and the herd a herder starts a step with."""
del system
herder.income = 0.0
herder.herd = 0.0
def __init__(
self,
n_herders: int = 20,
*,
width: int = 20,
height: int = 20,
cows: int = 1,
quota: float | None = None,
regrowth: float = 0.2,
capacity: float = 2.0,
upkeep: float = 0.3,
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.n_herders = n_herders
self.width = width
self.height = height
self.cows = cows
self.quota = quota
self.regrowth = regrowth
self.capacity = capacity
self.upkeep = upkeep
self.random_state = random_state
@staticmethod
def _get_investment() -> list[BirthDeathInteraction | Interaction]:
"""Return the member interactions of a herder.
They buy or sell a cow, then clear its income and herd, one herder after the other.
"""
return [
BirthDeathInteraction(
'investment',
target='herders',
group='cows',
birth=TragedyOfTheCommonsSystem._get_pays,
values=TragedyOfTheCommonsSystem._get_calf,
placement=TragedyOfTheCommonsSystem._get_cell,
cull=TragedyOfTheCommonsSystem._get_exceeds,
kin=TragedyOfTheCommonsSystem._get_owns,
schedule='member',
phase='herding',
),
Interaction(
'clearing',
roles={'target': 'herders'},
laws=lambda s: [UpdateLaw(s.target, TragedyOfTheCommonsSystem._clear, phase='herding')],
),
]
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the components built from the model parameters."""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
cells = [(x, y) for x in range(self.width) for y in range(self.height)]
space = LatticeSpace((self.width, self.height), boundary='periodic', metric='chebyshev')
xs, ys = np.array(cells).T
meadow = PastureElement(
'meadow',
grass=self.capacity,
capacity=self.capacity,
regrowth=self.regrowth,
values={'x': xs, 'y': ys},
size=len(cells),
space=space,
)
herders = HerderElement(
'herders',
upkeep=self.upkeep,
quota=UNLIMITED if self.quota is None else self.quota,
values={'x': 0, 'y': 0},
size=self.n_herders,
space=space,
)
n_cows = self.n_herders * self.cows
places = rng.integers(len(cells), size=n_cows)
herd = CowElement(
'cows',
owner=np.repeat(np.arange(self.n_herders), self.cows),
values={'x': xs[places], 'y': ys[places]},
size=n_cows,
space=space,
)
regulator = QuotaRegulatorInteraction('regulator', phase='herding', regulated=float(self.quota is not None))
grazing = GrazingInteraction(
'grazing',
requesters='cows',
providers='meadow',
rule=PartnerMatchingSpec('local', 'score', score=GrazingInteraction.score, value='provider'),
herders='herders',
)
self.system_ = System(
self.label,
elements=[meadow, herd, herders],
interactions=[
grazing,
RegrassingInteraction('regrowth', phase='growth'),
*self._get_investment(),
regulator,
],
space=space,
solver=MesaSolver(phases=[PhaseSpec('grazing'), PhaseSpec('growth'), PhaseSpec('herding')]),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
GrazingInteraction, fromInteraction, through the shared recipeMatchingInteractionRegrassingInteraction, fromInteractionBirthDeathInteraction, fromInteraction, through the shared recipeBirthDeathInteractionInteractionQuotaRegulatorInteraction, fromInteraction
class PastureElement(Element):
"""Cell of the meadow whose grass grows back logistically by `RegrassingInteraction`.
When it is grazed bare, the grass grows from a seed bank.
Args:
label:
The label of the agent or group.
grass:
The grass on the cell.
capacity:
The most grass the cell holds.
regrowth:
The logistic growth rate of the grass.
seed:
The share of the capacity that grows back as if it stood on a bare cell.
values:
Further values by name, such as the cells `x` and `y` of the members on the meadow.
size:
The number of pastures, or `None` for one.
space:
The meadow the pastures live on, whose axes `x` and `y` place them, or `None`.
Examples:
>>> from skcomplex.systems.economics.resources import PastureElement
>>> PastureElement('meadow', capacity=2.0, size=4).size
4
"""
visual = VisualSpec('agents', {'color_by': 'grass', 'color_range': (0.0, 2.0)})
def __init__(
self,
label: str,
*,
grass: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
capacity: Annotated[object, RealSet.open(0, oo)] = 2.0,
regrowth: Annotated[object, RealSet.closed_open(0, oo)] = 0.2,
seed: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.grass = grass
self.capacity = capacity
self.regrowth = regrowth
self.seed = seed
class CowElement(Element):
"""Cow of a herder that gains the energy of the grass it eats.
It burns its metabolism, and starves without food.
Args:
label:
The label of the agent or group.
owner:
The herder that owns the cow among the herders.
energy:
The energy of the cow.
values:
Further values by name, such as the cells `x` and `y` of the members on the meadow.
size:
The number of cows, or `None` for one.
space:
The meadow the cows live on, whose axes `x` and `y` place them, or `None`.
Examples:
>>> from skcomplex.systems.economics.resources import CowElement
>>> CowElement('cows', energy=4.0, size=3).size
3
"""
visual = VisualSpec('agents', {'color_by': 'energy'})
def __init__(
self,
label: str,
*,
owner: Annotated[object, Member('herders')] = -1.0,
energy: object = 4.0,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.owner = owner
self.energy = energy
class HerderElement(Element):
"""Herder who adds a cow whenever a cow earned more than its upkeep.
It sells one when the herd exceeds its quota. The life cycle `investment` of the system buys a cow, at a random
cell, or sells the first cow the herder owns, and two maps clear the income and the herd the grazing tallies, all
member interactions in the phase of herding.
Args:
label:
The label of the agent or group.
income:
The milk income of the herder in the last step.
herd:
The number of cows of the herder in the last step.
upkeep:
The cost of keeping a cow for a step.
newborn:
The energy of a new cow.
quota:
The largest herd of a herder, which a regulator may change.
values:
Further values by name, such as the cells `x` and `y` of the members on the meadow.
size:
The number of herders, or `None` for one.
space:
The meadow the herders live on, whose axes `x` and `y` place them, or `None`.
Examples:
>>> from skcomplex.systems.economics.resources import HerderElement
>>> HerderElement('herders', size=5).size
5
"""
def __init__(
self,
label: str,
*,
income: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
herd: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
upkeep: Annotated[object, RealSet.closed_open(0, oo)] = 0.3,
newborn: Annotated[object, RealSet.open(0, oo)] = 4.0,
quota: Annotated[object, RealSet.open(0, oo)] = UNLIMITED,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.income = income
self.herd = herd
self.upkeep = upkeep
self.newborn = newborn
self.quota = quota
class GrazingInteraction(MatchingInteraction[SystemView]):
"""Grazing of the meadow, a matching of the cows with the pastures.
After the matching every cow eats and burns energy. The rule of the matching pairs the cows with the pastures, such
as `PartnerMatchingSpec('local', 'score', score=GrazingInteraction.score, value='provider')`, which pairs every cow,
in random order, with the free pasture of most grass in its cell or the cells around it, ties broken at random. A
pasture takes one cow, its default quantity of one unit. Every matched cow moves to its pasture and eats up to its
appetite as a transfer of grass to its energy, and its herder earns milk for what it ate. Then every cow burns its
metabolism and counts in the herd of its herder, and a cow whose energy runs out dies.
Args:
label:
The label of the grazing.
requesters:
The path of the group of cows.
providers:
The path of the group of pastures.
rule:
The spec of the algorithm that pairs the cows with the pastures.
phase:
The phase the grazing runs in.
herders:
The path of the group of herders.
appetite:
The most grass a cow eats in a step.
metabolism:
The energy a cow burns in a step.
milk:
The income of a herder per unit of grass its cows eat.
Examples:
>>> from skcomplex.systems.economics.resources import GrazingInteraction
>>> GrazingInteraction('grazing', requesters='cows', providers='meadow', herders='herders').appetite
1.0
"""
def __init__(
self,
label: str,
*,
requesters: Role,
providers: Role,
rule: MatchingRule = RandomSearchSpec(),
phase: str | None = 'grazing',
herders: Role,
appetite: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
metabolism: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
milk: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
) -> None:
super().__init__(label, requesters=requesters, providers=providers, rule=rule, phase=phase)
self.herders = herders
self.appetite = appetite
self.metabolism = metabolism
self.milk = milk
@staticmethod
def score(cow: object, pasture: object) -> float:
"""Return the score of a pasture for a cow, the grass on the pasture.
Args:
cow:
The agent view of the cow.
pasture:
The agent view of the pasture.
Returns:
score:
The grass on the pasture, or minus infinity for an agent that is not a pasture.
"""
del cow
return float(pasture.grass) if isinstance(pasture, PastureView) else -np.inf
@staticmethod
def _get_herder(cow: CowView) -> HerderView:
"""Return the herder that owns a cow, which its value `owner` names."""
herder = cow.get_referenced('owner')
if not isinstance(herder, HerderView):
error_msg = f'Cow {cow.id} names no herder as its owner.'
raise SimulationError(error_msg)
return herder
def _settle(self, match: MatchSpec, system: SystemView) -> None:
"""Move the cow of a match to its pasture and feed it.
Its herder is paid for what it ate.
Args:
match:
The match of a cow with a pasture.
system:
The system view of the grazing.
"""
cow, pasture = match.requester, match.provider
if not isinstance(cow, CowView) or not isinstance(pasture, PastureView):
return
cow.move_to(pasture.location)
eaten = min(pasture.grass, system.get_parameter('appetite'))
transfer(pasture, cow, eaten, 'grass', 'energy')
self._get_herder(cow).income += system.get_parameter('milk') * eaten
def match(self, system: SystemView) -> None:
"""Pair and feed the cows, then let every cow burn its metabolism.
Every cow is counted in its herd, and it starves.
Args:
system:
The system view of the grazing.
"""
super().match(system)
for cow in cast(list[CowView], system.get_agents('requesters')):
cow.energy -= system.get_parameter('metabolism')
self._get_herder(cow).herd += 1
if cow.energy < 0:
cow.remove()
class RegrassingInteraction(Interaction):
"""Logistic regrowth of the grass of every pasture, from a seed bank when it is bare.
The grass `G` of a pasture of capacity `K` grows by `r S (1 - S / K)` up to `K`, with the stand `S` the larger of
`G` and the seed share of the capacity, so a bare cell grows back. The rates `r` and the seed share are the values
`regrowth` and `seed` of each pasture.
Args:
label:
The label of the interaction.
target:
The pastures whose grass grows.
phase:
The phase the grass grows in, or `None` for the default phase.
Examples:
>>> from skcomplex.systems.economics.resources import RegrassingInteraction
>>> RegrassingInteraction('regrowth', phase='growth').phase
'growth'
"""
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, target: Role = 'meadow', phase: str | None = None) -> None:
super().__init__(label)
self.target = target
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the regrowth rule of every pasture.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self.grow, phase=self.phase)]
def grow(self, agent: PastureView, system: SystemView) -> None:
"""Grow the grass logistically up to the capacity.
Args:
agent:
The pasture.
system:
The system.
"""
stand = max(agent.grass, agent.seed * agent.capacity)
growth = agent.regrowth * stand * (1 - stand / agent.capacity)
agent.grass = min(agent.capacity, agent.grass + growth)
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)]
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 QuotaRegulatorInteraction(PolicyRuleInteraction[SystemView]):
"""Regulator of the quota of cows per herder.
It halves the quota when the grass runs short and raises it when it recovers. The quota is the value `quota` of
every herder. It halves, down to one cow, when the grass falls below the share `low` of the capacity of
the meadow, and grows by one cow when the grass is above the share `high`. Without regulation it stays as it is.
Args:
label:
The label of the regulator.
rule:
Unused, since the regulator overrides `act`.
phase:
The phase the regulator acts in.
regulated:
One when the regulator changes the quota, zero otherwise.
low:
The share of the capacity of the meadow below which the quota halves.
high:
The share of the capacity of the meadow above which the quota rises by one cow.
Examples:
>>> from skcomplex.systems.economics.resources import QuotaRegulatorInteraction
>>> QuotaRegulatorInteraction('regulator', regulated=1.0).regulated
1.0
"""
def __init__(
self,
label: str,
*,
rule: Callable[[SystemView], None] | None = None,
phase: str | None = None,
regulated: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
low: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
high: Annotated[float, RealSet.closed_open(0, oo)] = 0.8,
) -> None:
super().__init__(label, rule=rule, phase=phase)
self.regulated = regulated
self.low = low
self.high = high
def act(self, system: SystemView) -> None:
"""Change the quota with the share of grass left on the meadow.
Args:
system:
The system view of the regulator.
"""
if not system.get_parameter('regulated'):
return
pastures = cast(list[PastureView], system.get_agents('meadow'))
share = sum(pasture.grass for pasture in pastures) / sum(pasture.capacity for pasture in pastures)
for herder in cast(list[HerderView], system.get_agents('herders')):
if share < system.get_parameter('low'):
herder.quota = max(1.0, float(np.floor(herder.quota / 2)))
elif share > system.get_parameter('high'):
herder.quota += 1