Metaphoria mortal hunter-gatherer and monetary economies
Gooding's Metaphoria.
- Class:
MetaphoriaSystem - Import:
from skcomplex.systems.economics.macroeconomics import MetaphoriaSystem - Field:
economics/macroeconomics - Topics:
agents,mortality,evolution,money,hunter-gatherers,stock-flow consistent - References:
- Gooding 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.economics.macroeconomics import MetaphoriaSystem
trajectory = MetaphoriaSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_people |
100 |
mode |
'hunter_gatherer' |
shape |
(20, 20) |
max_food |
15.0 |
max_resistance |
5.0 |
regrowth |
1.0 |
need |
2.0 |
labour |
5.0 |
interest |
0.003 |
repayment |
0.004 |
n_firms |
5 |
random_state |
0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | 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 MetaphoriaSystem(BaseSystem):
"""Gooding's Metaphoria.
It is a mortal population of hunter-gatherers or of a monetary economy. Patches of a periodic lattice hold food that
grows back to a random capacity and resist harvesting with a random resistance. People need food every step, age,
die of starvation or old age, and have children who inherit their propensities to breed, explore, found firms, and
quit jobs, with mutations, so the propensities evolve under the test of survival. Hunter-gatherers pool the labour
of the adults on a patch and share the harvest. In the monetary economy firms harvest with paid workers, sell the
food in shops, and borrow the wages from a bank that creates money as loans, so the money of all holders sums to
zero at every step. Gooding found the hunter-gatherers stable, and the monetary population smaller and less healthy,
with money concentrating to a Gini coefficient near 0.5. On land where the hunter-gatherers thrive the monetary
population dwindles towards extinction, and with abundant food it lives on with persistent starvation.
The system has the group `patches`, one per cell, the variable group `people`, the reporters `census.births`,
`census.starvations`, and `census.old_age`, and the observables `population` and `money_gini`. The monetary economy
adds the variable group `businesses`, the group `bank`, and the reporter `shops.gdp`.
Args:
n_people:
The initial number of adults.
mode:
`'hunter_gatherer'` or `'monetary'`.
shape:
The number of patches along each axis.
max_food:
The largest capacity of a patch, drawn uniformly from 0.
max_resistance:
The largest resistance of a patch, drawn uniformly from 0.
regrowth:
The share of the capacity that grows back in a step.
need:
The food a person eats in a step.
labour:
The labour of an adult in a step.
interest:
The interest rate of loans per step.
repayment:
The share of the principal repaid per step.
n_firms:
The number of firms of the monetary economy at the start, each without an owner until it has a worker.
random_state:
The seed or generator of the patches, the places, ages, and propensities of the people.
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.
Raises:
ValueError:
The mode is unknown.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import MetaphoriaSystem
>>> [group.label for group in MetaphoriaSystem(10, mode='monetary', shape=(5, 5)).prepare().system_.elements]
['patches', 'people', 'businesses', 'bank']
"""
field = 'economics/macroeconomics'
topics = ('agents', 'mortality', 'evolution', 'money', 'hunter-gatherers', 'stock-flow consistent')
references = ('Gooding 2019',)
until = 300
@staticmethod
def _get_bank_balance(bank: SimpleNamespace) -> float:
"""Return the money the bank has issued plus the loans it holds.
It is zero when every unit of money is a loan.
"""
return float(bank.money + bank.loans)
@staticmethod
def _get_living(fates: object) -> float:
"""Return the number of living people from their fates."""
return float(np.sum(np.asarray(fates) == ALIVE))
@staticmethod
def _get_money_gini(money: object) -> float:
"""Return the Gini coefficient of the money of people."""
gini = distribution(np.asarray(money, dtype=float), kind='gini').gini
return 0.0 if gini is None else gini
@staticmethod
def _get_metaphoria_observables(system: System) -> list[Observable]:
"""Return the population, the Gini coefficient of money, and the bank balance.
The population is the living one, of a monetary economy.
"""
observables = [
Observable('population', group='people', variable='fate', reduce=MetaphoriaSystem._get_living),
Observable('money_gini', group='people', variable='money', reduce=MetaphoriaSystem._get_money_gini),
]
if any(element.label == 'bank' for element in system.elements):
observables.append(
Observable('bank_balance', MetaphoriaSystem._get_bank_balance, group='bank', reduce='sum'),
)
return observables
def __init__(
self,
n_people: int = 100,
*,
mode: str = 'hunter_gatherer',
shape: Sequence[int] = (20, 20),
max_food: float = 15.0,
max_resistance: float = 5.0,
regrowth: float = 1.0,
need: float = 2.0,
labour: float = 5.0,
interest: float = 0.003,
repayment: float = 0.004,
n_firms: int = 5,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_people = n_people
self.mode = mode
self.shape = shape
self.max_food = max_food
self.max_resistance = max_resistance
self.regrowth = regrowth
self.need = need
self.labour = labour
self.interest = interest
self.repayment = repayment
self.n_firms = n_firms
self.random_state = random_state
@staticmethod
def _pay_dividends(system: SystemView) -> None:
"""Pay the income of the bank, its money plus its loans, to a random person, or firm when nobody lives."""
banks = cast(list[CentralBankView], system.get_agents('bank'))
holders: list[SettlerView] | list[BusinessView] = cast(list[SettlerView], system.get_agents('people'))
if not any(holder.alive for holder in holders):
holders = cast(list[BusinessView], system.get_agents('businesses'))
found = cast(Dividends, list(pairs(banks, holders, system.rng, PartnerSpec('all', 'uniform'))))
for index in system.rng.permutation(len(found)):
bank, holder = found[int(index)]
income = bank.money + bank.loans
if bank.alive and holder.alive and income > 0:
bank.money -= income
holder.money += income
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the components built from the model parameters."""
super()._prepare(context)
shape = self.shape
if self.mode not in MODES:
error_msg = f'Unknown mode {self.mode!r}. Use one of {MODES}.'
raise ValueError(error_msg)
rng = np.random.default_rng(self.random_state)
shape = tuple(int(item) for item in shape)
space = LatticeSpace(shape)
sites = list(np.ndindex(*shape))
capacity = rng.uniform(0.0, self.max_food, len(sites))
axes = space.prepare().axes_
patches = PlotElement(
'patches',
food=capacity,
capacity=capacity,
resistance=rng.uniform(0.0, self.max_resistance, len(sites)),
regrowth=self.regrowth,
values=dict(zip(axes, np.array(sites).T, strict=True)),
size=len(sites),
space=space,
)
cells = rng.integers(0, shape, size=(self.n_people, len(shape)))
traits: dict[str, Array] = {
name: rng.uniform(0.0, bound, self.n_people) for name, bound in PROPENSITIES.items()
}
people = SettlerElement(
'people',
age=rng.integers(15, 40, self.n_people).astype(float),
need=self.need,
labour=self.labour,
monetary=float(self.mode == 'monetary'),
sight=SIGHT,
**traits,
values=dict(zip(axes, cells.T, strict=True)),
size=self.n_people,
space=space,
)
firms = rng.integers(0, shape, size=(self.n_firms, len(shape)))
businesses = BusinessElement(
'businesses',
interest=self.interest,
repayment=self.repayment,
values=dict(zip(axes, firms.T, strict=True)),
size=self.n_firms,
space=space,
)
bank = CentralBankElement('bank', values=dict.fromkeys(axes, 0), size=1, space=space)
economy = [businesses, bank] if self.mode == 'monetary' else []
jobs = LabourMarketInteraction(
'jobs',
requesters='people',
providers='businesses',
rule=PartnerMatchingSpec(SIGHT, 'score', score=LabourMarketInteraction.score, value='provider'),
reserve=('hireable', 'reserve'),
quantity=('quantity', 'vacancies'),
phase='hiring',
on_match=LabourMarketInteraction.hire,
)
shops = FoodMarketInteraction(
'shops',
requesters='people',
providers='businesses',
rule=PartnerMatchingSpec(SIGHT, 'score', score=FoodMarketInteraction.score, value='provider'),
reserve=('reserve', 'price'),
quantity=('shortfall', 'stock'),
cap='money',
transfers=(('money', -1),),
phase='market',
on_match=FoodMarketInteraction.sell,
)
dividends = Interaction(
'dividends',
roles={'bank': 'bank', 'people': 'people', 'businesses': 'businesses'},
laws=lambda s: [UpdateLaw(s, MetaphoriaSystem._pay_dividends, phase='banking')],
)
exchange: list[BaseInteraction] = (
[CommonsInteraction('commons', people='people')]
if self.mode == 'hunter_gatherer'
else [jobs, dividends, shops]
)
self.system_ = System(
self.label,
elements=[patches, people, *economy],
interactions=[
RegrowthInteraction(
'regrowth',
target='patches',
state='food',
growth='regrowth',
relative=True,
phase='growth',
),
LivingInteraction('living', phase='living'),
*([ProductionInteraction('production', phase='work')] if self.mode == 'monetary' else []),
*exchange,
EstateInteraction('census', people='people'),
],
space=space,
solver=MesaSolver(phases=[PhaseSpec(name) for name in PHASES]),
)
self.observables_ = tuple(MetaphoriaSystem._get_metaphoria_observables(self.system_))
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
RegrowthInteraction, fromInteractionLivingInteraction, fromInteractionCommonsInteraction, fromInteractionEstateInteraction, fromInteraction
class PlotElement(Element):
"""Patch of land whose food grows back by a share of its capacity every step.
It is harvested against a resistance. The regrowth is a `RegrowthInteraction` of the group of patches, relative to
the capacity.
Args:
label:
The label of the patch or the site group.
food:
The food on the patch.
capacity:
The most food the patch holds.
resistance:
The labour lost to the resistance of the patch before any food is harvested.
regrowth:
The share of the capacity that grows back in a step.
values:
Further values by name, such as the cells `x` and `y` of the members on the land.
size:
The number of patches, or `None` for one.
space:
The land the patches live on, whose axes `x` and `y` place them, or `None`.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import PlotElement
>>> PlotElement('patch').regrowth
1.0
"""
def __init__(
self,
label: str,
*,
food: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
capacity: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
resistance: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
regrowth: Annotated[object, RealSet.closed_open(0, oo)] = 1.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.food = food
self.capacity = capacity
self.resistance = resistance
self.regrowth = regrowth
class SettlerElement(Element):
"""Mortal person who eats, ages, raises children, and moves.
In the monetary economy, the person also works and founds firms. Every step a person eats `need` food and starves
when its food runs out, and past `lifespan` it dies of old age with probability 1/7. A child takes `need` food from
its parent and follows it. A fed adult has a child with the probability `fertility`, at most once every `spacing`
steps, and gives it `endowment` food. The child inherits the four propensities, each moved by a normal mutation and
kept in [0, 1]. A person that harvested too little and holds less than `reserve` steps of food moves, far with the
probability `exploration`. In the monetary economy an unemployed adult on a patch with food but no firm founds one
with the probability `enterprise`, and a worker quits with the probability `restlessness`.
Args:
label:
The label of the person or the group.
food:
The food the person holds.
money:
The money the person holds.
loans:
The loans the person holds, negative for a debt taken over from a firm.
age:
The age in steps.
parent:
The parent among the people, or -1.
employer:
The firm that employs the person among the firms, or -1.
harvested:
The food the person harvested or earned in the step.
born:
The step of the person's last child.
fate:
0 while alive, 1 after starving, and 2 after dying of old age, until the census removes the person.
fertility:
The probability of a child in a step.
exploration:
The probability of moving far.
enterprise:
The probability of founding a firm.
restlessness:
The probability of quitting a job.
labour:
The labour of an adult in a step.
need:
The food a person eats in a step.
maturity:
The age of adulthood.
lifespan:
The age after which death by old age is possible.
spacing:
The fewest steps between two children.
endowment:
The food a parent gives a newborn child.
mutation:
The standard deviation of the mutation of a propensity.
sight:
The distance within which a person sees firms and explores.
reserve:
The steps of food a person buys up to, and below which a person that harvests too little moves.
monetary:
One in the monetary economy, zero among hunter-gatherers.
values:
Further values by name, such as the cells `x` and `y` of the members on the land.
size:
The number of people, or `None` for one.
space:
The land the people live on, whose axes `x` and `y` place them, or `None`.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import SettlerElement
>>> SettlerElement('people', size=3).size
3
"""
def __init__(
self,
label: str,
*,
food: object = 10.0,
money: Annotated[object, Quantity('money')] = 0.0,
loans: Annotated[object, Quantity('credit')] = 0.0,
age: Annotated[object, NN] = 20.0,
parent: Annotated[object, Member('people')] = -1.0,
employer: Annotated[object, Member('businesses')] = -1.0,
harvested: object = 0.0,
born: object = -100.0,
fate: object = ALIVE,
fertility: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
exploration: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
enterprise: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
restlessness: Annotated[object, RealSet.closed_open(0, oo)] = 0.1,
labour: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
need: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
maturity: Annotated[object, RealSet.closed_open(0, oo)] = 15.0,
lifespan: Annotated[object, RealSet.closed_open(0, oo)] = 85.0,
spacing: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
endowment: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
mutation: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
sight: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
reserve: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
monetary: Annotated[object, RealSet.closed_open(0, oo)] = 0.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.food = food
self.money = money
self.loans = loans
self.age = age
self.parent = parent
self.employer = employer
self.harvested = harvested
self.born = born
self.fate = fate
self.fertility = fertility
self.exploration = exploration
self.enterprise = enterprise
self.restlessness = restlessness
self.labour = labour
self.need = need
self.maturity = maturity
self.lifespan = lifespan
self.spacing = spacing
self.endowment = endowment
self.mutation = mutation
self.sight = sight
self.reserve = reserve
self.monetary = monetary
@staticmethod
def _get_patch_here(agent: AgentViewProtocol) -> PlotView:
"""Return the patch of the cell of an agent."""
return next(patch for patch in agent.get_agents_here('patches') if isinstance(patch, PlotView))
@staticmethod
def _get_cell(agent: AgentViewProtocol) -> tuple[int, ...]:
"""Return the cell of an agent of the lattice."""
location = agent.location
if not isinstance(location, tuple):
error_msg = f'The agent {agent.id} is not on a lattice cell.'
raise TypeError(error_msg)
return tuple(int(item) for item in location)
@staticmethod
def _wander(agent: SettlerView, system: SystemView, sight: float) -> None:
"""Move to a random cell within sight with the propensity to explore.
Otherwise move to a neighbouring cell.
"""
if system.rng.random() < agent.exploration:
width, height = system.dimensions or (1, 1)
reach = int(sight)
dx, dy = system.rng.integers(-reach, reach + 1, size=2)
x, y = SettlerElement._get_cell(agent)
agent.move_to(((x + int(dx)) % int(width), (y + int(dy)) % int(height)))
return
cells = agent.get_neighbor_cells()
agent.move_to(cells[int(system.rng.integers(len(cells)))])
class RegrowthInteraction(Interaction):
"""Linear regrowth of a resource held by the agents of a group.
It grows by a fixed amount a step up to their capacity. Every step the resource `x` of an agent grows by the amount
`g` its parameter `growth` names, `x = min(K, x + g)`, or by that share of its capacity `K` when the regrowth is
relative, `x = min(K, x + g K)`. It is a rule of the system that grows every agent, such as the sugar of a patch of
Sugarscape or the food of a plot of land.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the group whose resource grows back.
state:
The name of the state that holds the resource.
capacity:
The name of the state or parameter of an agent that holds its capacity.
growth:
The name of the parameter of an agent that holds its regrowth in a step.
relative:
Whether the regrowth is a share of the capacity rather than an amount.
phase:
The phase of the step the regrowth runs in, or `None` for the default phase.
Examples:
>>> from skcomplex.systems.economics.common.resources import RegrowthInteraction
>>> regrowth = RegrowthInteraction('regrowth', target='patches', state='sugar', growth='growback')
>>> regrowth.growth
'growback'
"""
law_classes = (UpdateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
state: str,
capacity: str = 'capacity',
growth: str = 'growth',
relative: bool = False,
phase: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.capacity = capacity
self.growth = growth
self.relative = relative
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the regrowth of every agent of the target as a rule of the system, in its phase.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self._regrow, phase=self.phase)]
def _regrow(self, system: SystemViewProtocol) -> None:
"""Grow the resource of every agent back, at most to its capacity."""
for agent in system.get_agents('target'):
capacity = float(getattr(agent, self.capacity))
growth = float(getattr(agent, self.growth)) * (capacity if self.relative else 1.0)
setattr(agent, self.state, min(capacity, float(getattr(agent, self.state)) + growth))
class LivingInteraction(Interaction):
"""Life of every person: ageing, eating, dying, having children, and moving or working.
It is the rule of `SettlerElement` in the phase of living, run by each person in turn.
Args:
label:
The label of the interaction.
target:
The people who live.
phase:
The phase the people live in, or `None` for the default phase.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import LivingInteraction
>>> LivingInteraction('living', phase='living').phase
'living'
"""
draws = True
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, target: Role = 'people', phase: str | None = None) -> None:
super().__init__(label)
self.target = target
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rule of living of every person.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self.live, phase=self.phase)]
def _feed_child(self, agent: SettlerView, system: SystemView) -> None:
"""Take food from the living parent and follow it."""
parent = agent.get_referenced('parent')
if not isinstance(parent, SettlerView):
return
given = min(agent.need, max(parent.food - parent.need, 0.0))
parent.food -= given
agent.food += given
agent.move_to(parent.location)
def _breed(self, agent: SettlerView, system: SystemView) -> None:
"""Have a child with mutated propensities at the probability of fertility."""
fed = agent.food >= agent.endowment + agent.need
spaced = system.time - agent.born >= agent.spacing
if not (fed and spaced and system.rng.random() < agent.fertility):
return
traits = {
name: float(np.clip(getattr(agent, name) + system.rng.normal(0.0, agent.mutation), 0.0, 1.0))
for name in PROPENSITIES
}
agent.food -= agent.endowment
agent.born = system.time
agent.create(None, None, food=agent.endowment, age=0.0, parent=float(agent.id), born=system.time, **traits)
def _work_or_found(self, agent: SettlerView, system: SystemView) -> bool:
"""Quit a job at the restlessness, or found a firm on a free patch with food.
It returns whether the person is employed.
"""
if agent.employer >= 0:
if system.rng.random() < agent.restlessness:
agent.employer = -1.0
return agent.employer >= 0
if agent.get_agents_here('businesses') or SettlerElement._get_patch_here(agent).food <= 0:
return False
if system.rng.random() >= agent.enterprise:
return False
firm = agent.create('businesses', owner=float(agent.id))
agent.employer = float(firm.id)
return True
def live(self, agent: SettlerView, system: SystemView) -> None:
"""Age, eat, die, have children, and move or work.
Args:
agent:
The person.
system:
The system.
"""
agent.age += 1
adult = agent.age >= agent.maturity
if not adult:
self._feed_child(agent, system)
agent.food -= agent.need
if agent.food < 0:
agent.fate = STARVED
return
if agent.age > agent.lifespan and system.rng.random() < OLD_AGE_DEATH:
agent.fate = AGED
return
if not adult:
return
self._breed(agent, system)
employed = agent.monetary > 0 and self._work_or_found(agent, system)
if not employed and agent.harvested < agent.need and agent.food < agent.reserve * agent.need:
SettlerElement._wander(agent, system, agent.sight)
agent.harvested = 0.0
class CommonsInteraction(Interaction):
"""Harvest of the hunter-gatherers.
The adults of a patch harvest `min(food, labour - resistance)`, and everyone on the patch, child or adult, gets an
equal share.
Args:
label:
The label of the interaction.
people:
The path of the group of people.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import CommonsInteraction
>>> CommonsInteraction('commons', people='people').people
'people'
"""
law_classes = (UpdateLaw,)
def __init__(
self,
label: str,
*,
people: Role,
) -> None:
super().__init__(label)
self.people = people
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rule of the system in the phase `work`.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self.harvest, phase='work')]
def harvest(self, system: SystemView) -> None:
"""Harvest every occupied patch and share the food among the people on it.
Args:
system:
The system view of the interaction.
"""
cells: dict[tuple[int, ...], list[SettlerView]] = {}
for person in cast(list[SettlerView], system.get_agents('people')):
cells.setdefault(SettlerElement._get_cell(person), []).append(person)
for group in cells.values():
patch = SettlerElement._get_patch_here(group[0])
labour = sum(person.labour for person in group if person.age >= person.maturity)
harvest = min(patch.food, max(labour - patch.resistance, 0.0))
patch.food -= harvest
for person in group:
person.food += harvest / len(group)
person.harvested = harvest / len(group)
class EstateInteraction(Interaction):
"""Settlement of the estates of the dead, with a census of the step.
The dead leave their money and loans to an heir. The money and the loans of a dead person go to a random living
person of its patch, or of anywhere. When nobody lives to inherit them, the dead person stays as an estate that
holds them. The reporters `births`, `starvations`, and `old_age` count the events of a step.
Args:
label:
The label of the interaction.
people:
The path of the group of people.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import EstateInteraction
>>> EstateInteraction('census', people='people').reports
('births', 'starvations', 'old_age')
"""
draws = True
law_classes = (UpdateLaw,)
reports: ClassVar[tuple[str, ...]] = ('births', 'starvations', 'old_age')
def __init__(
self,
label: str,
*,
people: Role,
) -> None:
super().__init__(label)
self.people = people
def _settle(self, dead: SettlerView, living: list[SettlerView], system: SystemView) -> None:
"""Leave the money and the loans of a dead person to an heir.
Then remove the person.
"""
near = [person for person in living if person.location == dead.location] or living
if near:
heir = near[int(system.rng.integers(len(near)))]
transfer(dead, heir, dead.money, 'money')
transfer(dead, heir, dead.loans, 'loans')
if dead.money == 0 and dead.loans == 0:
dead.remove()
def count(self, system: SystemView) -> None:
"""Count the births and deaths of the step and remove the dead.
Args:
system:
The system view of the interaction.
"""
people = cast(list[SettlerView], system.get_agents('people'))
living = [person for person in people if person.fate == ALIVE]
dead = [person for person in people if person.fate != ALIVE]
system.report('births', float(sum(person.age == 0 for person in living)))
system.report('starvations', float(sum(person.fate == STARVED for person in dead)))
system.report('old_age', float(sum(person.fate == AGED for person in dead)))
for person in dead:
self._settle(person, living, system)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rule of the system in the phase `census`.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self.count, phase='census')]