Shops and digital markets
Shops on a grid that compete for the shoppers on every cell.
- Class:
ShopsSystem - Import:
from skcomplex.systems.economics.markets import ShopsSystem - Field:
economics/markets - Topics:
market,agents,retail,digital market,grid - References:
- Hamill and Gilbert 2016 sec. 6.3-6.4
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.markets import ShopsSystem
trajectory = ShopsSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_shops |
16 |
width |
20 |
height |
20 |
online |
0.0 |
distance_cost |
1.0 |
capacity |
1000.0 |
fixed_cost |
20.0 |
value |
20.0 |
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 ShopsSystem(BaseSystem):
"""Shops on a grid that compete for the shoppers on every cell.
The shoppers buy in person or in a digital market. Every step every shopper wants one unit and shops online with
probability `online`, and in person otherwise, when it pays a travel cost for the distance to the shop. The shoppers
choose in random order the shops they prefer by price plus travel cost, within the shops' capacities, a greedy
matching that pays the shop's ask for a unit. Shops search for the price of the largest profit by trial and error,
pay a fixed cost every step, and close when their money runs out. Distance gives every shop a local market, so many
shops survive with high prices. In the digital market the cheapest shop takes every shopper, the others undercut it,
prices fall toward the unit cost, and most shops close (Hamill and Gilbert 2016 sec. 6.3-6.4).
The system has the groups `shoppers` and `shops` and the market `shopping`, whose reporters are the
`shopping.value`, `shopping.volume`, and `shopping.unmatched` of the purchases.
Args:
n_shops:
The initial number of shops.
width:
The number of columns of the grid, with one shopper per cell.
height:
The number of rows of the grid.
online:
The probability that a shopper shops online in a step.
distance_cost:
The travel cost per cell of shopping in person.
capacity:
The units every shop can sell in a step.
fixed_cost:
The cost of running a shop for a step.
value:
The highest price a shopper pays.
random_state:
The seed or generator of the cells and initial prices of the shops.
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.markets import ShopsSystem
>>> [group.size for group in ShopsSystem(4, width=5, height=5).prepare().system_.elements]
[25, 4]
"""
field = 'economics/markets'
topics = ('market', 'agents', 'retail', 'digital market', 'grid')
references = ('Hamill and Gilbert 2016 sec. 6.3-6.4',)
until = 100
observables = (
Observable('open_shops', group='shops', variable='price', reduce='count'),
Observable('mean_price', group='shops', variable='price', reduce='mean'),
Observable('concentration', group='shops', variable='sales', reduce=_get_largest_share),
)
def __init__(
self,
n_shops: int = 16,
*,
width: int = 20,
height: int = 20,
online: float = 0.0,
distance_cost: float = 1.0,
capacity: float = 1000.0,
fixed_cost: float = 20.0,
value: float = 20.0,
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_shops = n_shops
self.width = width
self.height = height
self.online = online
self.distance_cost = distance_cost
self.capacity = capacity
self.fixed_cost = fixed_cost
self.value = value
self.random_state = random_state
@staticmethod
def _open(system: SystemView) -> None:
"""Open the market, where every shopper wants one unit and every shop offers its capacity.
A shopper shops online, at no travel cost, with its probability `online`, and in person otherwise.
"""
shoppers = cast(list[ResidentView], system.get_agents('shoppers'))
for shopper in shoppers:
shopper.demand = 1.0
for shopper in shoppers:
shopper.travel = 0.0 if system.rng.random() < shopper.online else float(shopper.distance_cost)
shops = cast(list[StoreView], system.get_agents('shops'))
for shop in shops:
shop.supply = float(shop.capacity)
for shop in shops:
shop.ask = float(shop.price)
for shop in shops:
shop.sales = 0.0
@staticmethod
def _settle(system: SystemView) -> None:
"""Settle the accounts of every shop.
A shop turns its price back when its profit falls, records the profit, and pays its costs. The pricing then
steps the price by the sign of the direction.
"""
shops = cast(list[StoreView], system.get_agents('shops'))
for shop in shops:
shop.direction = float(-shop.direction if StoreElement.get_profit(shop) < shop.profit else shop.direction)
for shop in shops:
shop.profit = float(StoreElement.get_profit(shop))
for shop in shops:
shop.money = float(shop.money - shop.sales * shop.unit_cost - shop.fixed_cost)
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)]
places = rng.choice(len(cells), size=min(self.n_shops, len(cells)), replace=False)
space = LatticeSpace((self.width, self.height), boundary='fixed', metric='chebyshev')
xs, ys = np.array(cells).T
shoppers = ResidentElement(
'shoppers',
bid=self.value,
online=self.online,
distance_cost=self.distance_cost,
values={'x': xs, 'y': ys},
size=len(cells),
space=space,
)
stores = StoreElement(
'shops',
price=rng.uniform(0.25 * self.value, 0.75 * self.value, len(places)),
capacity=self.capacity,
fixed_cost=self.fixed_cost,
values={'x': xs[places], 'y': ys[places]},
size=len(places),
space=space,
)
plan = [
Interaction(
'opening',
roles={'shoppers': 'shoppers', 'shops': 'shops'},
laws=lambda s: [UpdateLaw(s, ShopsSystem._open, phase='market')],
),
]
settlement = [
Interaction(
'settlement',
roles={'shops': 'shops'},
laws=lambda s: [UpdateLaw(s, ShopsSystem._settle, phase='accounts')],
),
PriceAdjustmentInteraction(
'settlement_price',
target='shops',
state='price',
signal=lambda agent, system: agent.direction,
step=lambda agent, system: agent.adjustment,
lower=lambda agent, system: agent.unit_cost,
schedule='synchronous',
phase='accounts',
),
BirthDeathInteraction(
'closure',
target='shops',
death=lambda agent, system: agent.money < 0,
phase='accounts',
),
]
shopping = MatchingInteraction[SystemView](
'shopping',
requesters='shoppers',
providers='shops',
rule=PartnerMatchingSpec(choice='score', score=ResidentElement.get_preference, value='provider'),
reserve=('bid', 'ask'),
quantity=('demand', 'supply'),
transfers=(('money', -1),),
phase='market',
on_match=StoreElement.record_sale,
)
self.system_ = System(
self.label,
elements=[shoppers, stores],
interactions=[*plan, shopping, *settlement],
space=space,
solver=MesaSolver(phases=[PhaseSpec('market'), PhaseSpec('accounts')]),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
InteractionMatchingInteraction, fromInteraction, through the shared recipeMatchingInteractionPriceAdjustmentInteraction, fromInteractionBirthDeathInteraction, fromInteraction, through the shared recipeBirthDeathInteraction
class ResidentElement(Element):
"""Shopper who wants one unit a step.
It shops in person, paying for travel, or online, where distance is free.
Args:
label:
The label of the agent or group.
bid:
The highest price the shopper pays.
demand:
The units still wanted in the step.
money:
The money of the shopper.
travel:
The travel cost per cell of the current step, zero online.
distance_cost:
The travel cost per cell of shopping in person.
online:
The probability of shopping online in a step.
values:
Further values by name, such as the cell `x` and `y` of every member.
size:
The number of members, or `None` for one.
space:
The grid whose axes `x` and `y` place the members, or `None` for none.
Examples:
>>> from skcomplex.systems.economics.markets import ResidentElement
>>> ResidentElement('shoppers', online=1.0, size=3).size
3
"""
visual = VisualSpec('agents', {'color_by': 'travel', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
bid: Annotated[object, RealSet.closed_open(0, oo)] = 20.0,
demand: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
money: object = 1000.0,
travel: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
distance_cost: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
online: 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.bid = bid
self.demand = demand
self.money = money
self.travel = travel
self.distance_cost = distance_cost
self.online = online
@staticmethod
def get_preference(shopper: object, shop: object) -> float:
"""Return the preference of a shopper for a shop.
It is the opposite of the delivered price. The delivered price is the shop's ask plus the shopper's travel cost
per cell times the distance to the shop.
Args:
shopper:
The shopper.
shop:
The shop.
Returns:
preference:
The opposite of the delivered price, higher for a preferred shop.
"""
if not isinstance(shopper, ResidentView) or not isinstance(shop, StoreView):
return -math.inf
return -(shop.ask + shopper.travel * shopper.get_distance_to(shop))
class StoreElement(Element):
"""Shop that offers its capacity at its price.
It searches for the price of the largest profit, and may close. The shop searches for its price by trial and error:
it moves the price by `adjustment` in the same direction as long as its profit grows, and turns back when the profit
falls, never below the unit cost. It pays the unit cost of every unit sold and the fixed cost every step, and closes
when its money runs out.
Args:
label:
The label of the agent or group.
price:
The price of a unit.
ask:
The price offered in the current step.
supply:
The units still offered in the step.
sales:
The units sold in the last step.
money:
The money of the shop.
profit:
The profit of the last step.
direction:
The direction of the last change of the price, 1 up or -1 down.
capacity:
The units the shop can sell in a step.
unit_cost:
The cost of a unit sold.
fixed_cost:
The cost of running the shop for a step.
adjustment:
The relative change of the price in a step.
values:
Further values by name, such as the cell `x` and `y` of every member.
size:
The number of members, or `None` for one.
space:
The grid whose axes `x` and `y` place the members, or `None` for none.
Examples:
>>> from skcomplex.systems.economics.markets import StoreElement
>>> StoreElement('shops', price=10.0, size=4).size
4
"""
visual = VisualSpec('agents', {'color_by': 'price'})
def __init__(
self,
label: str,
*,
price: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
ask: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
supply: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
sales: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
money: object = 100.0,
profit: object = 0.0,
direction: object = 1.0,
capacity: Annotated[object, RealSet.open(0, oo)] = 1000.0,
unit_cost: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
fixed_cost: Annotated[object, RealSet.closed_open(0, oo)] = 20.0,
adjustment: 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.price = price
self.ask = ask
self.supply = supply
self.sales = sales
self.money = money
self.profit = profit
self.direction = direction
self.capacity = capacity
self.unit_cost = unit_cost
self.fixed_cost = fixed_cost
self.adjustment = adjustment
@staticmethod
def get_profit(agent: StoreView) -> float:
"""Return the profit of the step, the margin on the units sold less the fixed cost.
Args:
agent:
The shop.
Returns:
profit:
The profit of the step.
"""
return agent.sales * (agent.ask - agent.unit_cost) - agent.fixed_cost
@staticmethod
def record_sale(match: MatchSpec, system: SystemView) -> None:
"""Count the units of a purchase in the sales of the shop.
Args:
match:
The purchase of a shopper, the requester, from a shop, the provider.
system:
The system view of the market.
"""
shop = match.provider
if isinstance(shop, StoreView):
shop.sales += match.quantity
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 MatchingInteraction[SystemT: SystemViewProtocol](Interaction):
"""An interaction that matches requesters with providers and settles every match.
Requesters state in their states the highest value they accept, `reserve`, the quantity they want, `quantity`, and
the most value they can give, `cap`. Providers state the lowest value they accept and the quantity they offer. A
name given as a pair names the state of the requesters first and of the providers second. The `rule` is a spec of
the algorithm that pairs the offers, such as `RandomSearchSpec`, `QueueSpec`, `BatchMatchingSpec`, or
`StableMatchingSpec`.
Every match lowers the quantities of both sides and moves every state of `transfers`: a negative sign moves `value *
quantity` from the requester to the provider, and a positive sign moves `quantity` from the provider to the
requester, so the totals stay the same. `on_match(match, system)` adds any other effect. The matching runs once per
round of its phase and reports `<label>.value`, the clearing value weighted by quantity, `<label>.volume`, and
`<label>.unmatched`.
Unlike a labelled `RateLaw` flow, which moves amounts between given pairs, it first forms the pairs by a rule,
through `pairs` of the core, and then transfers. Choose it when who trades with whom and at what value are part of
the model.
It appears in many fields. Buyers and sellers trade goods, workers and firms agree on wages, borrowers and banks
agree on loans, and patients and hospitals are matched.
Args:
label:
The label of the matching.
requesters:
The path of the group of requesters.
providers:
The path of the group of providers.
rule:
The spec of the algorithm that matches the members, such as `ContinuousMatchingSpec()`, or a function
`rule(requesters, providers, rng, capacity)` of the agents with a positive quantity that returns their
pairs, which match at the midpoint of both reserves. A `PartnerSpec` picks among the providers that still
offer a quantity at a reserve the requester accepts, in random order of the requesters, and settles at
the midpoint, or at the value of a `PartnerMatchingSpec`.
reserve:
The state with the reserve of both sides, or a pair of the requesters' and the providers' states. An agent
without the default state `'reserve'` has no reserve as a requester and the reserve 0 as a provider.
quantity:
The state with the quantity of both sides, or a pair of the requesters' and the providers' states. An
agent without the default state `'quantity'` offers the quantity 1.
cap:
The state of a requester with the most value it can give. A requester without the default state
`'cap'` has no reserve on what it gives.
transfers:
The states every match moves, each with the sign `-1` for a move from the requester to the provider or
`1` for a move from the provider to the requester.
phase:
The phase the matching runs in, or `None` for the default phase.
on_match:
A function of every match and the system view, run after the transfers, or `None`.
Raises:
ValidationError:
A transfer has a sign other than `-1` or `1`, or the rule is neither a matching spec nor a function, or
it is invalid, raised by `prepare`, or an agent lacks a state other than a default one that names its
reserve, quantity, or cap, raised by `run`.
Examples:
>>> from skcomplex.systems.general.matching import MatchingInteraction
>>> from skcomplex.systems.general.matching import ContinuousMatchingSpec
>>> matching = MatchingInteraction(
... 'exchange',
... requesters='traders',
... providers='traders',
... rule=ContinuousMatchingSpec(),
... reserve=('bid', 'ask'),
... )
>>> matching.reports
('value', 'volume', 'unmatched')
"""
reports: ClassVar[tuple[str, ...]] = ('value', 'volume', 'unmatched')
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def _get_draws(self) -> bool:
"""Return whether the rule draws.
Every rule draws but a queue served in a fixed order.
"""
return super()._get_draws() or not (isinstance(self.rule, QueueSpec) and self.rule.order != 'random')
def __init__(
self,
label: str,
*,
requesters: Role,
providers: Role,
rule: MatchingRule | Pairing = RandomSearchSpec(),
reserve: str | tuple[str, str] = 'reserve',
quantity: str | tuple[str, str] = 'quantity',
cap: str = 'cap',
transfers: Sequence[tuple[str, int]] = (),
phase: str | None = None,
on_match: Callable[[MatchSpec, SystemT], None] | None = None,
) -> None:
super().__init__(label)
self.requesters = requesters
self.providers = providers
self.rule = rule
self.reserve = reserve
self.quantity = quantity
self.cap = cap
self.transfers = transfers
self.phase = phase
self.on_match = on_match
@staticmethod
def _get_sides(name: str | tuple[str, str]) -> tuple[str, str]:
"""Return the state of the requesters and of the providers of a name.
The name is given once or as a pair.
"""
return (name, name) if isinstance(name, str) else name
def _read(self, agent: AgentViewProtocol, name: str, default: float) -> float:
"""Return a state of an agent.
It returns a default when the agent lacks a state of a default name.
"""
if hasattr(agent, name):
return float(getattr(agent, name))
if name in DEFAULT_STATES:
return default
error_msg = (
f'The agents of {agent.group!r} have no state {name!r}, which the matching {self.label!r} reads. Declare '
f'the state on their element, or name one of their states.'
)
raise ValidationError(error_msg)
@staticmethod
def _get_affordable(offer: SimpleNamespace, value: float) -> float:
"""Return the quantity a participant can still match at a value.
The value is within its cap.
"""
if value <= 0:
return float(offer.quantity)
return max(0.0, min(offer.quantity, offer.cap / value))
@staticmethod
def _record_match(
trades: list[MatchSpec],
requester: SimpleNamespace,
provider: SimpleNamespace,
value: float,
) -> None:
"""Record a match of the largest quantity both sides can match at a value.
It also lowers both offers.
"""
quantity = min(MatchingInteraction._get_affordable(requester, value), provider.quantity)
if quantity <= 0:
return
requester.quantity -= quantity
requester.cap -= quantity * value
provider.quantity -= quantity
trades.append(MatchSpec(requester.agent, provider.agent, quantity, value))
@staticmethod
def _get_value(requester: SimpleNamespace, provider: SimpleNamespace, clearing: str) -> float:
"""Return the value of a match under a clearing rule."""
if clearing == 'requester':
return requester.reserve
if clearing == 'provider':
return provider.reserve
return (requester.reserve + provider.reserve) / 2
@staticmethod
def _get_order(offers: list[SimpleNamespace], order: str, rng: np.random.Generator) -> list[SimpleNamespace]:
"""Return offers in random order, by decreasing reserve, or in order of creation."""
if order == 'reserve':
return sorted(offers, key=lambda item: (-item.reserve, item.agent.id))
if order == 'sequential':
return sorted(offers, key=lambda item: item.agent.id)
return [offers[index] for index in rng.permutation(len(offers))]
def _get_offers(self, system: SystemT) -> tuple[list[SimpleNamespace], list[SimpleNamespace]]:
"""Return the offers of the requesters and providers with a positive quantity.
Matches lower the quantity.
"""
reserves, quantities = self._get_sides(self.reserve), self._get_sides(self.quantity)
requesters = [
SimpleNamespace(
agent=agent,
reserve=self._read(agent, reserves[0], math.inf),
quantity=self._read(agent, quantities[0], 1.0),
cap=self._read(agent, self.cap, math.inf),
)
for agent in system.get_agents(self._get_role('requesters'))
]
providers = [
SimpleNamespace(
agent=agent,
reserve=self._read(agent, reserves[1], 0.0),
quantity=self._read(agent, quantities[1], 1.0),
cap=math.inf,
)
for agent in system.get_agents(self._get_role('providers'))
]
return [offer for offer in requesters if offer.quantity > 0], [
offer for offer in providers if offer.quantity > 0
]
def _match_random_search(
self,
rule: RandomSearchSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches of requesters in random order that meet random providers.
They match on crossing reserves.
"""
trades: list[MatchSpec] = []
for index in rng.permutation(len(requesters)):
requester = requesters[index]
for _ in range(rule.tries):
available = [provider for provider in providers if provider.quantity > 0]
if requester.quantity <= 0 or not available:
break
provider = available[int(rng.integers(len(available)))]
if provider.reserve <= requester.reserve:
self._record_match(trades, requester, provider, self._get_value(requester, provider, rule.value))
return trades
@staticmethod
def _choose_partner(
rule: PartnerSwitchSpec,
best: SimpleNamespace,
current: SimpleNamespace | None,
rng: np.random.Generator,
) -> SimpleNamespace:
"""Return the provider a requester matches with.
It is its current partner or the best of its sample.
"""
if current is None or current.quantity <= 0:
return best
if best.reserve >= current.reserve:
return current
if best.reserve <= 0:
return best
switching = 1 - math.exp(rule.intensity * (best.reserve - current.reserve) / best.reserve)
return best if rng.random() < switching else current
def _match_partner_switch(
self,
rule: PartnerSwitchSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches of every requester with its kept or new partner.
The matches are at the partner's reserve.
"""
trades: list[MatchSpec] = []
by_id = {provider.agent.id: provider for provider in providers}
for index in rng.permutation(len(requesters)):
requester = requesters[index]
available = [provider for provider in providers if provider.quantity > 0]
if not available:
break
picks = rng.choice(len(available), size=min(rule.sample, len(available)), replace=False)
best = min((available[int(pick)] for pick in picks), key=lambda provider: provider.reserve)
current = by_id.get(int(getattr(requester.agent, rule.partner, -1)))
chosen = self._choose_partner(rule, best, current, rng)
if hasattr(requester.agent, rule.partner):
setattr(requester.agent, rule.partner, chosen.agent.id)
if chosen.reserve <= requester.reserve:
self._record_match(trades, requester, chosen, chosen.reserve)
return trades
def _match_queue(
self,
rule: QueueSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches of the queue of requesters served by the lowest providers.
The providers serve at their reserves.
"""
queue = self._get_order(requesters, rule.order, rng)
stock = sorted(providers, key=lambda provider: provider.reserve)
trades: list[MatchSpec] = []
for requester in queue:
for provider in stock:
if requester.quantity <= 0 or provider.reserve > requester.reserve:
break
if provider.quantity > 0:
self._record_match(trades, requester, provider, provider.reserve)
return trades
@staticmethod
def _adjust(
rule: IterativeMatchingSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
start: float,
) -> float:
"""Return the value the tâtonnement reaches from a start."""
value = start
for _ in range(rule.iterations):
requested = sum(
MatchingInteraction._get_affordable(requester, value)
for requester in requesters
if requester.reserve >= value
)
provided = sum(provider.quantity for provider in providers if provider.reserve <= value)
total = requested + provided
if not total or abs(requested - provided) / total < rule.tolerance:
break
value *= 1 + rule.adjustment * (requested - provided) / total
return value
def _match_at(
self,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
value: float,
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches at one value between the willing requesters and providers.
They match in random order.
"""
trades: list[MatchSpec] = []
willing_requesters = self._get_order([item for item in requesters if item.reserve >= value], 'random', rng)
willing_providers = self._get_order([item for item in providers if item.reserve <= value], 'random', rng)
pairs = iter(willing_providers)
provider = next(pairs, None)
for requester in willing_requesters:
while provider is not None and MatchingInteraction._get_affordable(requester, value) > 0:
self._record_match(trades, requester, provider, value)
if provider.quantity <= 0:
provider = next(pairs, None)
return trades
def _match_iterative(
self,
rule: IterativeMatchingSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
storage: MutableMapping[str, object],
) -> list[MatchSpec]:
"""Return the matches at the value of the tâtonnement.
The tâtonnement starts from the value of the last clearing.
"""
reserves = [offer.reserve for offer in requesters + providers if offer.reserve > 0]
if not reserves:
return []
last = storage.get('value')
start = last if isinstance(last, float) and math.isfinite(last) and last > 0 else float(np.median(reserves))
value = self._adjust(rule, requesters, providers, start)
storage['value'] = value
return self._match_at(requesters, providers, value, rng)
@staticmethod
def _arrange(
rule: ContinuousMatchingSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[tuple[SimpleNamespace, bool]]:
"""Return the offers in their order of arrival, each with whether it is a request."""
offers = [(offer, True) for offer in requesters] + [(offer, False) for offer in providers]
if rule.arrival == 'sequential':
return sorted(offers, key=lambda item: item[0].agent.id)
return [offers[index] for index in rng.permutation(len(offers))]
def _match_continuous(
self,
rule: ContinuousMatchingSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches of every arriving offer with the best resting offers.
The resting offers are those of the other side.
"""
requests: list[tuple[float, int, SimpleNamespace]] = []
provisions: list[tuple[float, int, SimpleNamespace]] = []
trades: list[MatchSpec] = []
for time, (offer, is_request) in enumerate(self._arrange(rule, requesters, providers, rng)):
if is_request:
while (
provisions
and provisions[0][0] <= offer.reserve
and MatchingInteraction._get_affordable(offer, provisions[0][0]) > 0
):
resting = provisions[0][2]
self._record_match(trades, offer, resting, resting.reserve)
if resting.quantity <= 0:
heapq.heappop(provisions)
if MatchingInteraction._get_affordable(offer, offer.reserve) > 0:
heapq.heappush(requests, (-offer.reserve, time, offer))
continue
while requests and -requests[0][0] >= offer.reserve and offer.quantity > 0:
resting = requests[0][2]
self._record_match(trades, resting, offer, resting.reserve)
if MatchingInteraction._get_affordable(resting, resting.reserve) <= 0:
heapq.heappop(requests)
if offer.quantity > 0:
heapq.heappush(provisions, (offer.reserve, time, offer))
return trades
@staticmethod
def _get_requested(offer: SimpleNamespace) -> float:
"""Return the quantity a requester can match at its own reserve."""
return (
offer.quantity
if not math.isfinite(offer.cap)
else MatchingInteraction._get_affordable(offer, offer.reserve)
)
def _get_pair(
self,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
) -> tuple[list[tuple[SimpleNamespace, SimpleNamespace]], float]:
"""Return the pairs of crossing offers in order of their reserves.
It also returns the value of the last pair.
"""
ranked_requesters = sorted(requesters, key=lambda offer: (-offer.reserve, offer.agent.id))
ranked_providers = sorted(providers, key=lambda offer: (offer.reserve, offer.agent.id))
left = {id(offer): self._get_requested(offer) for offer in ranked_requesters}
offered = {id(offer): offer.quantity for offer in ranked_providers}
pairs: list[tuple[SimpleNamespace, SimpleNamespace]] = []
marginal = math.nan
requester_iter, provider_iter = iter(ranked_requesters), iter(ranked_providers)
requester, provider = next(requester_iter, None), next(provider_iter, None)
while requester is not None and provider is not None and requester.reserve >= provider.reserve:
pairs.append((requester, provider))
marginal = (requester.reserve + provider.reserve) / 2
quantity = min(left[id(requester)], offered[id(provider)])
left[id(requester)] -= quantity
offered[id(provider)] -= quantity
if left[id(requester)] <= 0:
requester = next(requester_iter, None)
if offered[id(provider)] <= 0:
provider = next(provider_iter, None)
return pairs, marginal
def _match_batch(self, requesters: list[SimpleNamespace], providers: list[SimpleNamespace]) -> list[MatchSpec]:
"""Return the matches of the crossing offers at the midpoint of the last pair.
The last pair is the last crossing pair.
"""
pairs, marginal = self._get_pair(requesters, providers)
trades: list[MatchSpec] = []
for requester, provider in pairs:
self._record_match(trades, requester, provider, marginal)
return trades
@staticmethod
def _score_provider(rule: StableMatchingSpec, requester: SimpleNamespace, provider: SimpleNamespace) -> float:
"""Return the score of a provider for a requester, higher for a preferred provider."""
if rule.requester_preference is None:
return -provider.reserve
return rule.requester_preference(requester.agent, provider.agent)
@staticmethod
def _score_requester(rule: StableMatchingSpec, provider: SimpleNamespace, requester: SimpleNamespace) -> float:
"""Return the score of a requester for a provider.
The score is higher for a preferred requester.
"""
if rule.provider_preference is None:
return requester.reserve
return rule.provider_preference(provider.agent, requester.agent)
def _rank_providers(
self,
rule: StableMatchingSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
) -> dict[int, list[int]]:
"""Return the ids of the acceptable providers of every requester.
The preferred come first.
"""
capacities = {provider.agent.id for provider in providers if int(provider.quantity) > 0}
ranks = {}
for requester in requesters:
acceptable = [
provider
for provider in providers
if provider.agent.id in capacities and provider.reserve <= requester.reserve
]
ranked = sorted(
(-self._score_provider(rule, requester, provider), provider.agent.id) for provider in acceptable
)
if ranked:
ranks[requester.agent.id] = [identity for _, identity in ranked]
return ranks
def _rank_requesters(
self,
rule: StableMatchingSpec,
ranks: dict[int, list[int]],
providers: list[SimpleNamespace],
by_id: dict[int, SimpleNamespace],
) -> dict[int, list[int]]:
"""Return the ids of the requesters that rank every provider, the preferred first."""
provider_ranks = {}
for provider in providers:
suitors = sorted(
(-self._score_requester(rule, provider, by_id[requester_id]), requester_id)
for requester_id, ranked in ranks.items()
if provider.agent.id in ranked
)
if suitors:
provider_ranks[provider.agent.id] = [identity for _, identity in suitors]
return provider_ranks
@staticmethod
def _defer_acceptance(
requester_ranks: dict[int, list[int]],
provider_ranks: dict[int, list[int]],
capacities: dict[int, int],
) -> dict[int, list[int]]:
"""Return the requesters of every provider in the stable matching.
The matching is the requester-optimal one, and the preferred requesters come first.
Every free requester proposes to its next provider, which holds its preferred proposals up to its capacity and
rejects the rest. The result does not depend on the order of the proposals.
"""
held: dict[int, list[int]] = {provider: [] for provider in provider_ranks}
proposals = {requester: iter(ranked) for requester, ranked in requester_ranks.items()}
free = list(requester_ranks)
while free:
requester = free.pop()
provider = next(proposals[requester], None)
if provider is None:
continue
held[provider].append(requester)
if len(held[provider]) > capacities[provider]:
rejected = max(held[provider], key=provider_ranks[provider].index)
held[provider].remove(rejected)
free.append(rejected)
return {provider: sorted(held[provider], key=ranked.index) for provider, ranked in provider_ranks.items()}
def _match_stable(
self,
rule: StableMatchingSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
) -> list[MatchSpec]:
"""Return the matches of the requester-optimal stable matching, one unit per pair."""
by_id = {offer.agent.id: offer for offer in itertools.chain(requesters, providers)}
requester_ranks = self._rank_providers(rule, requesters, providers)
if not requester_ranks:
return []
provider_ranks = self._rank_requesters(rule, requester_ranks, providers, by_id)
capacities = {provider_id: int(by_id[provider_id].quantity) for provider_id in provider_ranks}
trades: list[MatchSpec] = []
for provider_id, requester_ids in self._defer_acceptance(requester_ranks, provider_ranks, capacities).items():
provider = by_id[provider_id]
for requester_id in requester_ids:
requester = by_id[requester_id]
value = self._get_value(requester, provider, rule.value)
quantity = min(1.0, MatchingInteraction._get_affordable(requester, value), provider.quantity)
if quantity > 0:
requester.quantity -= quantity
requester.cap -= quantity * value
provider.quantity -= quantity
trades.append(MatchSpec(requester.agent, provider.agent, quantity, value))
return trades
def _match_partners(
self,
rule: PartnerSpec,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches of every requester with the feasible partners its rule picks.
The requesters go in random order.
"""
wanting = {id(offer.agent): offer for offer in requesters}
offering = {id(offer.agent): offer for offer in providers}
def is_feasible(requester: AgentViewProtocol, provider: AgentViewProtocol) -> bool:
"""Return whether a provider still offers a quantity at an acceptable reserve.
The requester accepts the reserve.
"""
offer = offering[id(provider)]
return offer.quantity > 0 and offer.reserve <= wanting[id(requester)].reserve
trades: list[MatchSpec] = []
left, right = [offer.agent for offer in requesters], [offer.agent for offer in providers]
for requester, provider in pairs(left, right, rng, rule, feasible=is_feasible):
first, second = wanting[id(requester)], offering[id(provider)]
value = rule.value if isinstance(rule, PartnerMatchingSpec) else 'midpoint'
self._record_match(trades, first, second, self._get_value(first, second, value))
return trades
def _match_function(
self,
rule: Pairing,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
rng: np.random.Generator,
) -> list[MatchSpec]:
"""Return the matches of the pairs of a function.
Each is at the midpoint of the reserves.
"""
wanting = {id(offer.agent): offer for offer in requesters}
offering = {id(offer.agent): offer for offer in providers}
trades: list[MatchSpec] = []
left = [offer.agent for offer in requesters]
right = left if self.requesters == self.providers else [offer.agent for offer in providers]
for requester, provider in pairs(left, right, rng, rule):
first, second = wanting[id(requester)], offering[id(provider)]
self._record_match(trades, first, second, self._get_value(first, second, 'midpoint'))
return trades
def _get_matches(
self,
requesters: list[SimpleNamespace],
providers: list[SimpleNamespace],
system: SystemT,
) -> list[MatchSpec]:
"""Return the matches of the offers by the algorithm the rule names.
There are none when a side has no offers.
"""
if not requesters or not providers:
return []
rule, rng = self.rule, system.rng
match rule:
case RandomSearchSpec():
matches = self._match_random_search(rule, requesters, providers, rng)
case PartnerSwitchSpec():
matches = self._match_partner_switch(rule, requesters, providers, rng)
case QueueSpec():
matches = self._match_queue(rule, requesters, providers, rng)
case IterativeMatchingSpec():
matches = self._match_iterative(rule, requesters, providers, rng, system.storage)
case ContinuousMatchingSpec():
matches = self._match_continuous(rule, requesters, providers, rng)
case BatchMatchingSpec():
matches = self._match_batch(requesters, providers)
case StableMatchingSpec():
matches = self._match_stable(rule, requesters, providers)
case PartnerSpec():
matches = self._match_partners(rule, requesters, providers, rng)
case _:
matches = self._match_function(rule, requesters, providers, rng)
return matches
def _settle(self, match: MatchSpec, system: SystemT) -> None:
"""Move the transfers of a match, lower both quantities, and run `on_match`.
It lowers the quantities of both sides.
"""
for state, sign in self.transfers:
if sign < 0:
transfer(match.requester, match.provider, match.quantity * match.value, state)
else:
transfer(match.provider, match.requester, match.quantity, state)
for agent, name in zip((match.requester, match.provider), self._get_sides(self.quantity), strict=True):
if hasattr(agent, name):
setattr(agent, name, getattr(agent, name) - match.quantity)
if self.on_match is not None:
self.on_match(match, system)
def _report_matches(self, matches: list[MatchSpec], unmatched: float, system: SystemT) -> None:
"""Report the value, the matched volume, and the unmatched quantity of a clearing.
The value is weighted by quantity.
Args:
matches:
The matches of the clearing.
unmatched:
The quantity of both sides left after the clearing.
system:
The system view of the matching.
"""
volume = sum(match.quantity for match in matches)
value = sum(match.quantity * match.value for match in matches) / volume if volume else math.nan
system.report('value', value)
system.report('volume', volume)
system.report('unmatched', unmatched)
def _check_space(self, space: BaseSpace | None) -> None:
"""Raise an error for candidates in neighbouring cells or nodes.
The error is for a continuous space.
"""
self._check_partners(self.rule, space)
def _check_arguments(self) -> None:
"""Raise an error for a bad declaration, an unsigned transfer, or a bad rule.
Raises:
ValidationError:
A transfer has a sign other than `-1` or `1`, the rule is neither a matching spec nor a function, or
it is invalid.
"""
super()._check_arguments()
for state, sign in self.transfers:
if sign not in SIGNS:
error_msg = f'The transfer of {state!r} has the sign {sign!r}. Use one of {SIGNS}.'
raise ValidationError(error_msg)
self._check_variant('rule', self.rule, (), RULES, functions=True)
if isinstance(self.rule, RULES):
self.rule._check()
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_: Sequence[BaseLaw] = self._get_matching_laws(context)
def _get_matching_laws(self, namespace: SimpleNamespace) -> Sequence[BaseLaw]:
"""Return the rule that matches the members in the matching's phase.
Args:
namespace:
The namespace of the symbols the laws can use.
Returns:
laws:
The laws of the interaction.
"""
return [UpdateLaw(namespace, self.match, phase=self.phase)]
def match(self, system: SystemT) -> None:
"""Match the members, settle the matches, and report the results.
It reports the value, the volume, and the unmatched quantity.
Args:
system:
The system view of the matching.
"""
requesters, providers = self._get_offers(system)
matches = self._get_matches(requesters, providers, system)
for match in matches:
self._settle(match, system)
unmatched = sum(offer.quantity for offer in requesters + providers)
self._report_matches(matches, unmatched, system)
class PriceAdjustmentInteraction(Interaction):
"""Price adjustment of a state of discrete time by the sign of a signal, kept within bounds.
Economics names it a price adjustment by trial and error, as a shop that raises its price while demand exceeds its
supply and lowers it otherwise. With the stepping `'multiplicative'` the next value of the state `x` is
`x (1 + step sign(signal))`, and with the stepping `'additive'` it is `x + step sign(signal)`, so the state rises
while the signal is positive, falls while it is negative, and stays while it is zero, by trial and error rather
than by the size of the signal. The next value is then limited to `[lower, upper]`.
Without a `schedule` it sets an update law, and the signal, the step, and the bounds are numbers or functions of the
namespace, where `namespace.target` holds the states and parameters of the target. With a `schedule` it sets one
rule that walks the agents of the target in that order, and they are numbers or functions `f(agent, system)` that
return numbers. Under the schedule `'synchronous'` every agent steps from the values at the start of the rule,
under `'sequential'` or `'random-sequential'` one after the other, in their order or in a new random order, and
under `'member'` each in its own activation.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the element or group whose state steps.
state:
The name of the state of the target.
signal:
The function of the signal whose sign sets the direction of the step.
step:
The size of the step, relative with the stepping `'multiplicative'`, a number or a function.
stepping:
`'multiplicative'` or `'additive'`.
lower:
The lowest next value, a number or a function, or `None` for none.
upper:
The highest next value, a number or a function, or `None` for none.
phase:
The phase of the step the rule of a schedule runs in, or `None` for the default phase.
schedule:
The order in which a rule walks the agents, `'synchronous'`, `'sequential'`, `'random-sequential'`, or
`'member'`, or `None` for an update law of the state of the target.
Raises:
ValidationError:
The stepping or the schedule is unknown, or the signal is not callable, raised by `prepare`.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.economics.markets import PriceAdjustmentInteraction
>>> search = PriceAdjustmentInteraction(
... 'search', target='quote', state='x', signal=lambda s: 2 - s.target.x, step=0.5, upper=2.0
... )
>>> system = System(elements=[Element('quote', values={'x': 1.0})], interactions=[search])
>>> system.prepare().simulate(until=3).get_values('quote.x').tolist()
[1.0, 1.5, 2.0, 2.0]
"""
law_classes = (UpdateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
state: str,
signal: Callable[..., object],
step: float | Callable[..., object] = 0.1,
stepping: str = 'multiplicative',
lower: float | Callable[..., object] | None = None,
upper: float | Callable[..., object] | None = None,
phase: str | None = None,
schedule: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.signal = signal
self.step = step
self.stepping = stepping
self.lower = lower
self.upper = upper
self.phase = phase
self.schedule = schedule
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The stepping or the schedule is unknown, or the signal is not callable.
"""
super()._check_arguments()
if self.schedule not in SCHEDULES:
error_msg = f'The schedule of {self.label!r} is {self.schedule!r}. Use one of {SCHEDULES}.'
raise ValidationError(error_msg)
if self.stepping not in STEPPINGS:
error_msg = f'The stepping of {self.label!r} is {self.stepping!r}. Use one of {", ".join(STEPPINGS)}.'
raise ValidationError(error_msg)
if not callable(self.signal):
error_msg = f'The signal of {self.label!r} must be callable, but it is {self.signal!r}.'
raise ValidationError(error_msg)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the step of the state, or the rule of the agents, as the laws.
Args:
context:
The namespace of the target.
"""
super()._prepare(context)
if self.schedule == 'member':
self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self._step_member, phase=self.phase)]
elif self.schedule is not None:
self.laws_ = [UpdateLaw(context, self.step_agents, phase=self.phase)]
else:
self.laws_ = [UpdateLaw(getattr(context.target, self.state), self._get_next(context))]
def _read(self, item: float | Callable[..., object] | None, *arguments: object) -> object:
"""Return a number, the value of a function at the arguments, or `None`."""
return item(*arguments) if callable(item) else item
def _get_number(
self,
item: float | Callable[..., object] | None,
agent: AgentViewProtocol,
system: SystemViewProtocol,
) -> float | None:
"""Return a number or the value of a function of an agent as a number, or `None`."""
found = self._read(item, agent, system)
if found is None:
return None
if not isinstance(found, SupportsFloat):
error_msg = f'A function of {self.label!r} returns {found!r} for an agent. Return a number.'
raise ValidationError(error_msg)
return float(found)
def _get_agent_next(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> float:
"""Return the next value of the state of an agent."""
direction = float(np.sign(self._get_number(self.signal, agent, system) or 0.0))
step = self._get_number(self.step, agent, system) or 0.0
current = float(getattr(agent, self.state))
value = current + step * direction if self.stepping == 'additive' else current * (1 + step * direction)
lower, upper = self._get_number(self.lower, agent, system), self._get_number(self.upper, agent, system)
if upper is not None:
value = min(upper, value)
if lower is not None:
value = max(lower, value)
return value
def _step_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Step the state of one agent, in its own activation."""
if agent.alive:
setattr(agent, self.state, self._get_agent_next(agent, system))
def step_agents(self, system: SystemViewProtocol) -> None:
"""Step the state of every agent by the schedule.
Args:
system:
The system view of the adjustment.
"""
agents = list(system.get_agents('target'))
if self.schedule == 'synchronous':
values = [self._get_agent_next(agent, system) for agent in agents]
for agent, value in zip(agents, values, strict=True):
setattr(agent, self.state, value)
return
order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
for index in order:
self._step_member(agents[int(index)], system)
def _get_next(self, namespace: SimpleNamespace) -> object:
"""Return the next value of the state of the update law."""
value = SR(getattr(namespace.target, self.state))
direction = sign(self._read(self.signal, namespace))
step = SR(self._read(self.step, namespace))
stepped = value + step * direction if self.stepping == 'additive' else value * (1 + step * direction)
return clip(stepped, self._read(self.lower, namespace), self._read(self.upper, namespace))
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)]