Fundamentalists and chartists in an order book
A stock market of fundamentalists and chartists on a grid.
- Class:
OrderBookSystem - Import:
from skcomplex.systems.economics.finance import OrderBookSystem - Field:
economics/finance - Topics:
stock market,agents,order book,imitation,fundamentalists,chartists - References:
- Lux and Marchesi 1999
- Caiani et al. 2016 §3.2.1
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.finance import OrderBookSystem
trajectory = OrderBookSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
width |
20 |
height |
20 |
chartists |
0.3 |
fundamental |
100.0 |
reversion |
0.2 |
extrapolation |
1.0 |
noise |
0.02 |
imitation |
0.1 |
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 OrderBookSystem(BaseSystem):
"""A stock market of fundamentalists and chartists on a grid.
They trade in a limit order book and imitate. Every step every trader forecasts the price, as a fundamentalist who
expects it to revert to the fundamental value or as a chartist who expects the last change to go on, and quotes a
limit order for one share at its forecast. The order book matches the orders with price-time priority, and every
trade moves money and a share between the two traders. Then traders copy the strategy of a neighbour whose wealth
grew more. Fundamentalists hold the price near the fundamental value, chartists amplify its swings, and imitation
lets the share of chartists wander, so the returns come in bursts with fat tails.
The two strategies are the fundamentalists and chartists of Lux and Marchesi (1999), and imitating a wealthier
neighbour on the grid stands in for their switching between strategies. The order book is the order-driven market of
Caiani et al. (2016, section 3.2.1). The traders of Caiani's chapter 3, noise traders who follow gurus of an
evolving network, are a different model. The system has the group `traders` and the book `book`, whose reporters are
`book.price` and `book.volume`, and the imitation `imitation` of the strategies of more successful neighbours.
Args:
width:
The number of columns of the grid, with one trader per cell.
height:
The number of rows of the grid.
chartists:
The initial share of chartists.
fundamental:
The fundamental value of the share.
reversion:
The share of the gap to the fundamental value a fundamentalist expects to close.
extrapolation:
The share of the last change of the price a chartist expects to repeat.
noise:
The standard deviation of the relative noise of a forecast.
imitation:
The probability that a trader looks at a neighbour in a step.
random_state:
The seed or generator of the initial strategies.
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.finance import OrderBookSystem
>>> OrderBookSystem(5, 5).prepare().system_.elements[0].size
25
"""
field = 'economics/finance'
topics = ('stock market', 'agents', 'order book', 'imitation', 'fundamentalists', 'chartists')
references = ('Lux and Marchesi 1999', 'Caiani et al. 2016 §3.2.1')
until = 200
invariants: ClassVar[Mapping[str, float]] = {f'total_{name}': 1e-6 for name in HOLDINGS}
observables = (
Observable('chartists', group='traders', variable='strategy', reduce='mean'),
Observable('mean_wealth', group='traders', variable='wealth', reduce='mean'),
*(Observable(f'total_{name}', group='traders', variable=name, reduce='sum') for name in HOLDINGS),
)
def __init__(
self,
width: int = 20,
height: int = 20,
*,
chartists: float = 0.3,
fundamental: float = 100.0,
reversion: float = 0.2,
extrapolation: float = 1.0,
noise: float = 0.02,
imitation: float = 0.1,
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.width = width
self.height = height
self.chartists = chartists
self.fundamental = fundamental
self.reversion = reversion
self.extrapolation = extrapolation
self.noise = noise
self.imitation = imitation
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the components built from the model parameters."""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
cells = [(x, y) for x in range(self.width) for y in range(self.height)]
space = LatticeSpace((self.width, self.height), boundary='periodic', metric='manhattan')
x, y = np.array(cells).T
traders = StockTraderElement(
'traders',
strategy=(rng.random(len(cells)) < self.chartists).astype(float),
money=10 * self.fundamental,
shares=10.0,
wealth=20 * self.fundamental,
fundamental=self.fundamental,
reversion=self.reversion,
extrapolation=self.extrapolation,
noise=self.noise,
values={'x': x, 'y': y},
size=len(cells),
space=space,
)
self.system_ = System(
self.label,
elements=[traders],
interactions=[
LimitOrderInteraction('quotes', target='traders'),
BookInteraction(
'book',
requesters='traders',
providers='traders',
rule=ContinuousMatchingSpec(),
opening=self.fundamental,
),
AccountingInteraction('accounts', target='traders'),
ImitationInteraction(
'imitation',
target='traders',
state='strategy',
payoff='gain',
rule='better',
schedule='synchronous',
probability=self.imitation,
phase='imitation',
),
],
space=space,
solver=MesaSolver(
phases=[
PhaseSpec('quote'),
PhaseSpec('trade'),
PhaseSpec('account'),
PhaseSpec('imitation', activation='simultaneous'),
],
),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
StockTraderElement, fromElement
Interactions:
LimitOrderInteraction, fromInteractionBookInteraction, fromInteraction, through the shared recipeMatchingInteractionAccountingInteraction, fromInteractionImitationInteraction, fromInteraction, through the shared recipeImitationInteraction
class StockTraderElement(Element):
"""Trader who forecasts the price, quotes a limit order, and imitates.
It forecasts as a fundamentalist or a chartist. A fundamentalist expects the price `p` to revert to the fundamental
value `F`, `p + reversion (F - p)`, and a chartist expects the last change to go on, `p + extrapolation (p - p')`,
both with a relative noise. The trader bids its expectation for one share when it is above the price and it can pay,
and asks its expectation for one share when it is below and it holds one. After trading, an `ImitationInteraction`
of rule `'better'` lets a trader whose wealth grew less than that of a random neighbour copy the neighbour's
strategy.
Args:
label:
The label of the agent or group.
strategy:
0 for a fundamentalist, 1 for a chartist.
money:
The money of the trader.
shares:
The shares of the trader.
bid:
The limit price of a buy order.
ask:
The limit price of a sell order.
demand:
The shares wanted in the step.
supply:
The shares offered in the step.
wealth:
The money plus the shares at the last price.
gain:
The change of the wealth in the last step.
fundamental:
The fundamental value of the share.
reversion:
The share of the gap to the fundamental value a fundamentalist expects to close.
extrapolation:
The share of the last change of the price a chartist expects to repeat.
noise:
The standard deviation of the relative noise of a forecast.
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.finance import StockTraderElement
>>> StockTraderElement('traders', strategy=1.0, size=4).size
4
"""
visual = VisualSpec('agents', {'color_by': 'strategy', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
strategy: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
money: object = 1000.0,
shares: object = 10.0,
bid: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
ask: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
demand: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
supply: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
wealth: object = 0.0,
gain: object = 0.0,
fundamental: Annotated[object, RealSet.open(0, oo)] = 100.0,
reversion: Annotated[object, RealSet.closed_open(0, oo)] = 0.2,
extrapolation: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
noise: Annotated[object, RealSet.closed_open(0, oo)] = 0.02,
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.strategy = strategy
self.money = money
self.shares = shares
self.bid = bid
self.ask = ask
self.demand = demand
self.supply = supply
self.wealth = wealth
self.gain = gain
self.fundamental = fundamental
self.reversion = reversion
self.extrapolation = extrapolation
self.noise = noise
class LimitOrderInteraction(Interaction):
"""Limit orders of the traders of the order book.
Every trader forecasts the price and quotes a limit order for one share. A fundamentalist expects the price to close
the share `reversion` of its gap to the fundamental value, and a chartist expects the last change of the price to
repeat by the share `extrapolation`, both with a relative normal noise of standard deviation `noise`.
Args:
label:
The label of the interaction.
target:
The path of the group of traders.
phase:
The phase the traders quote in.
Examples:
>>> from skcomplex.systems.economics.finance import LimitOrderInteraction
>>> LimitOrderInteraction('quotes', target='traders').phase
'quote'
"""
law_classes = (UpdateLaw,)
draws = True
def __init__(self, label: str, *, target: Role, phase: str | None = 'quote') -> None:
super().__init__(label)
self.target = target
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the quote of every trader as its rule.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self.quote, phase=self.phase)]
@staticmethod
def get_prices(agent: StockTraderView, system: SystemView) -> tuple[float, float]:
"""Return the last two prices of the book, the fundamental value before the first.
Args:
agent:
The trader.
system:
The system view of the rule.
Returns:
prices:
The last price and the one before it.
"""
history = system.get_history('book.price', 2)
prices = [value for value in history if math.isfinite(value)] or [agent.fundamental]
return prices[-1], prices[0]
def quote(self, agent: StockTraderView, system: SystemView) -> None:
"""Forecast the price and quote a limit order for one share.
Args:
agent:
The trader.
system:
The system.
"""
price, previous = self.get_prices(agent, system)
if agent.strategy:
expected = heuristics.trend([previous, price], strength=agent.extrapolation)
else:
reversion = 1 - agent.reversion
expected = heuristics.fundamental(
[price],
fundamental=agent.fundamental,
reversion=reversion,
)
expected = max(LOWEST_PRICE, expected * (1 + agent.noise * system.rng.normal()))
buying = expected > price
new_bid, new_ask = (expected, 0.0) if buying else (0.0, expected)
agent.bid = new_bid
agent.ask = new_ask
agent.demand = float(buying and agent.money >= expected)
agent.supply = float(not buying and agent.shares >= 1)
class BookInteraction(MatchingInteraction[SystemView]):
"""Limit order book that matches the orders of the traders.
It reports the last traded price. The book is a matching of the traders with themselves, which binds the requesters'
limit to their `bid` and the providers' to their `ask`, and every trade is two transfers, money from buyer to seller
and shares from seller to buyer, so the total money and the total shares stay the same, which the default run checks
as invariants. The book reports the last traded `price`, the previous price when nothing trades, and the traded
`volume`.
Args:
label:
The label of the book.
requesters:
The path of the group of buying traders.
providers:
The path of the group of selling traders.
rule:
The spec of the algorithm that matches the orders, such as `ContinuousMatchingSpec()`.
reserve:
The states with the limit prices of the buyers and of the sellers.
quantity:
The states with the quantities the buyers want and the sellers offer.
cap:
The state of a buyer with the money it can spend.
transfers:
The states every trade moves, money paid by the buyer and shares delivered to it.
phase:
The phase the book clears in.
on_match:
A function of every trade and the system view, run after the transfers, or `None`.
opening:
The price before the first trade.
Examples:
>>> from skcomplex.systems.economics.finance import BookInteraction
>>> BookInteraction('book', requesters='traders', providers='traders').reports
('price', 'volume')
"""
reports: ClassVar[tuple[str, ...]] = ('price', 'volume')
def __init__(
self,
label: str,
*,
requesters: Role,
providers: Role,
rule: MatchingRule = RandomSearchSpec(),
reserve: str | tuple[str, str] = ('bid', 'ask'),
quantity: str | tuple[str, str] = ('demand', 'supply'),
cap: str = 'money',
transfers: Sequence[tuple[str, int]] = (('money', -1), ('shares', 1)),
phase: str | None = 'trade',
on_match: Callable[[MatchSpec, SystemView], None] | None = None,
opening: float = 100.0,
) -> None:
super().__init__(
label,
requesters=requesters,
providers=providers,
rule=rule,
reserve=reserve,
quantity=quantity,
cap=cap,
transfers=transfers,
phase=phase,
on_match=on_match,
)
self.opening = opening
def _report_matches(self, matches: list[MatchSpec], unmatched: float, system: SystemView) -> None:
"""Report the last traded price and the traded volume.
When nothing trades, it reports the previous price.
Args:
matches:
The trades of the clearing.
unmatched:
The quantity of both sides left after the clearing, which the book does not report.
system:
The system view of the book.
"""
del unmatched
last = system.get_history('price', 1)
price = matches[-1].value if matches else (float(last[-1]) if len(last) else self.opening)
system.report('price', price)
system.report('volume', sum(match.quantity for match in matches))
class AccountingInteraction(Interaction):
"""Accounts of the traders of the order book after every step of trade.
Every trader values its money and shares at the last price, and its gain is the change of this wealth in the step.
Args:
label:
The label of the interaction.
target:
The path of the group of traders.
phase:
The phase the accounts run in.
Examples:
>>> from skcomplex.systems.economics.finance import AccountingInteraction
>>> AccountingInteraction('accounts', target='traders').phase
'account'
"""
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, target: Role, phase: str | None = 'account') -> None:
super().__init__(label)
self.target = target
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the accounts of every step as the rule of the system.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self.account, phase=self.phase)]
def account(self, system: SystemView) -> None:
"""Set the gain of every trader, and then its wealth at the last price.
Args:
system:
The system view of the accounts.
"""
traders = cast(list[StockTraderView], system.get_agents('target'))
for trader in traders:
trader.gain = self.get_gain(trader, system)
for trader in traders:
trader.wealth = self.get_wealth(trader, system)
@staticmethod
def get_gain(agent: StockTraderView, system: SystemView) -> float:
"""Return the change of the wealth valued at the last price.
It is zero before the first valuation.
Args:
agent:
The trader.
system:
The system view of the accounting.
Returns:
gain:
The change of the wealth in the step.
"""
return AccountingInteraction.get_wealth(agent, system) - agent.wealth if agent.wealth else 0.0
@staticmethod
def get_wealth(agent: StockTraderView, system: SystemView) -> float:
"""Return the money plus the shares valued at the last price.
Args:
agent:
The trader.
system:
The system view of the accounting.
Returns:
wealth:
The wealth of the trader.
"""
price, _ = LimitOrderInteraction.get_prices(agent, system)
return agent.money + agent.shares * price
class ImitationInteraction(Interaction):
"""An interaction by which members copy a discrete state from their neighbours.
The `rule` says whom a member copies:
- `'random'`: a random neighbour.
- `'majority'`: the option that more of its neighbours hold than any other.
- `'best'`: the neighbour with the largest payoff, when it beats its own.
- `'better'`: a random neighbour, when its payoff beats its own, with a schedule only.
- `'fermi'`: a random neighbour, with probability `1 / (1 + exp(-beta (P_j - P_i)))`, where `P_j` and `P_i` are the
payoffs of the neighbour and the member.
Without a `schedule` it sets symbolic laws: jumps at the rate `rate` in continuous time, or, when `probability` is
given, updates with that probability per step for every member at once. With a `schedule` it sets one rule of the
whole system that walks the agents in that order with its own draws. A member without such a neighbour keeps its
state.
Unlike a sum of `neighbors` in a `RateLaw`, which averages numeric states of neighbours, it copies one discrete
value from them. Choose it when members adopt the choices of those around them.
It appears in many fields. Voters copy their friends in the voter model, players copy successful strategies in
evolutionary games on networks, and farmers adopt the crops of their neighbours.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the group on the nodes or sites.
state:
The name of the discrete state of the members.
payoff:
The name of the state that holds the payoff of the members, which the rules `'best'` and `'fermi'` read.
options:
The values the state takes.
rate:
The rate at which every member imitates in continuous time.
rule:
`'random'`, `'majority'`, `'best'`, or `'fermi'`.
intensity:
The intensity `beta` of the Fermi rule.
probability:
The probability that a member imitates in a step, or `None` for imitation in continuous time without a
schedule and for every agent in every step with one.
layer:
The layer of the network whose edges the interaction runs on, or `None` for the graph of the network.
phase:
The phase of the step the updates of a probability or the rule of a schedule run in, or `None` for the
default phase.
schedule:
The order in which a rule walks the agents, `'synchronous'` for every agent at once, `'sequential'` or
`'random-sequential'` for one agent after the other, or `'member'` for every agent in its own activation,
or `None` for symbolic laws.
ties:
The neighbour the rule `'best'` copies among ties with a schedule, `'first'` or `'random'`.
Raises:
ValidationError:
The rule, the schedule, or the ties are unknown, the rule `'better'` or ties other than `'first'` are given
without a schedule, or the options are not distinct.
Examples:
>>> from skcomplex.systems.general.agents import ImitationInteraction
>>> ImitationInteraction('imitation', target='voters', rule='majority').options
(0.0, 1.0)
>>> ImitationInteraction('imitation', target='players', rule='fermi', probability=0.5).probability
0.5
>>> ImitationInteraction('imitation', target='traders', rule='better', schedule='synchronous').rule
'better'
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (JumpLaw, UpdateLaw)
draws = True
def _get_tags(self) -> Tags:
"""Return the tags of the rule, the updates, or the jumps of the imitation.
A schedule sets the rule, and a probability sets updates that draw.
"""
if self._get_argument('schedule') is not None:
return self._get_variant_tags((UpdateLaw,))
if self._get_argument('probability') is not None:
return self._get_variant_tags((UpdateLaw,), stochastic=True)
return self._get_variant_tags((JumpLaw,))
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'state',
payoff: str = 'payoff',
options: Sequence[float] = (0.0, 1.0),
rate: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
rule: str = 'random',
intensity: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
probability: Annotated[float, RealSet.closed(0, 1)] | None = None,
layer: str | None = None,
phase: str | None = None,
schedule: str | None = None,
ties: str = 'first',
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.payoff = payoff
self.options = options
self.rate = rate
self.rule = rule
self.intensity = intensity
self.probability = probability
self.phase = phase
self.schedule = schedule
self.ties = ties
self.layer = layer
def _runs_on_edges(self) -> bool:
"""Return that the laws run once for every edge of the network or lattice."""
return True
def _get_layer(self) -> str | None:
"""Return the layer whose edges the laws run on, or `None` for the space."""
return self.layer
def _check_agent_options(self) -> None:
"""Raise an error for unknown schedule or ties.
It also raises it for ties other than first without a schedule.
"""
self._check_variant('schedule', self.schedule, (None, *ScheduleKind))
self._check_variant('ties', self.ties, TIES)
if self.schedule is None and self.ties != 'first':
error_msg = (
f'The imitation {self.label!r} has the ties {self.ties!r}, which only a rule of a schedule runs. Give '
'a schedule, such as schedule="synchronous", or ties="first".'
)
raise ValidationError(error_msg)
def _check_arguments(self) -> None:
"""Raise an error for unknown rule, schedule, or ties, or repeated options.
Raises:
ValidationError:
The rule, the schedule, or the ties are unknown, the rule `'better'` or ties other than `'first'` are
given without a schedule, or the options are not distinct.
"""
super()._check_arguments()
self._check_variant('rule', self.rule, RULES, (BaseSpec,))
if self.rule == 'better' and self.schedule is None:
error_msg = f'The rule of imitation {self.rule!r} runs with a schedule only, such as `"synchronous"`.'
raise ValidationError(error_msg)
self._check_agent_options()
if len(set(self.options)) < max(len(self.options), 2):
error_msg = f'The options of imitation are {self.options!r}. Give at least two distinct values.'
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_imitation_laws(context)
def _get_neighborhood(self) -> AdjacencyNeighborhood | None:
"""Return the neighbourhood of the layer.
It returns `None` for the neighbourhood of the space.
"""
return None if self.layer is None else AdjacencyNeighborhood(layer=self.layer)
def _get_fermi(self, member: SimpleNamespace, other: SimpleNamespace, intensity: Expression) -> Expression:
"""Return the Fermi probability that a member copies another of a different payoff."""
return 1 / (1 + exp(-intensity * (getattr(other, self.payoff) - getattr(member, self.payoff))))
def _get_counts(self, namespace: SimpleNamespace) -> dict[float, Expression]:
"""Return the number of the neighbours of the target that hold every option."""
source, over = self._get_member(namespace, 'source'), self._get_neighborhood()
return {
option: neighbors(where(getattr(source, self.state) == option, 1, 0), over=over) for option in self.options
}
def _get_majority(self, namespace: SimpleNamespace) -> dict[float, Expression]:
"""Return the indicator of every option most neighbours of the target hold.
More of the neighbours hold that option than any other.
"""
counts = self._get_counts(namespace)
leads = {}
for option, count in counts.items():
lead = SR(1)
for other, other_count in counts.items():
if other != option:
lead = lead * where(count > other_count, 1, 0)
leads[option] = lead
return leads
def _get_best(self, namespace: SimpleNamespace) -> tuple[Expression, Expression]:
"""Return the option of the neighbour of largest payoff and if it beats the target.
It returns whether that payoff is larger than the target's.
"""
source, over = self._get_member(namespace, 'source'), self._get_neighborhood()
payoff = getattr(source, self.payoff)
best = neighbors(getattr(source, self.state), over=over, reduce='argmax', weight=payoff)
largest = neighbors(payoff, over=over, reduce='max')
return best, where(largest > getattr(self._get_member(namespace, 'target'), self.payoff), 1, 0)
def _switches(self, value: Expression, rate: Expression, chosen: Expression) -> list[BaseLaw]:
"""Return the jumps of a state from every option to the chosen option.
A jump happens at a rate when the option is chosen.
"""
return [
JumpLaw(rate * where(value == first, 1, 0) * where(chosen == second, 1, 0), {value: second - first})
for first, second in itertools.permutations(self.options, 2)
]
def _get_copies(self, member: SimpleNamespace, other: SimpleNamespace, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the copies by a member of the state of the other end of an edge.
The other end is chosen among its neighbours.
"""
value, rate = getattr(member, self.state), self._get_parameter_symbol('rate', namespace) / member.degree
if self.rule == 'fermi':
rate = rate * self._get_fermi(member, other, self._get_parameter_symbol('intensity', namespace))
return self._switches(value, rate, getattr(other, self.state))
def _get_jumps(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the jumps of the state at the rate of imitation, in continuous time."""
value = getattr(self._get_member(namespace, 'target'), self.state)
if self.rule == 'majority':
leads = self._get_majority(namespace)
return [
JumpLaw(
self._get_parameter_symbol('rate', namespace) * where(value == first, 1, 0) * leads[second],
{value: second - first},
)
for first, second in itertools.permutations(self.options, 2)
]
if self.rule == 'best':
best, better = self._get_best(namespace)
return self._switches(value, self._get_parameter_symbol('rate', namespace) * better, best)
if self.rule not in ('random', 'fermi'):
raise self._get_variant_error(self.rule, 'rule', '_get_jumps')
source, target = self._get_member(namespace, 'source'), self._get_member(namespace, 'target')
return [*self._get_copies(target, source, namespace), *self._get_copies(source, target, namespace)]
@staticmethod
def _get_draw_name(state: Expression, kind: str) -> str:
"""Return the name of a draw of a state, such as `x_activity`.
A state read as a function of time, `x(t)`, names its draws after `x`.
"""
name = str(state.operator()) if state.operator() is not None else str(state)
return f'{name}_{kind}'
def _draw_copy(self, namespace: SimpleNamespace) -> Expression:
"""Return the next state of the target by the random or the Fermi rule.
It comes from the option it copies or its own.
"""
source, target = self._get_member(namespace, 'source'), self._get_member(namespace, 'target')
value = getattr(target, self.state)
probability, over = self._get_parameter_symbol('probability', namespace), self._get_neighborhood()
counts = self._get_counts(namespace)
degree = sum(counts.values(), SR(0))
if self.rule == 'fermi':
fermi = self._get_fermi(target, source, self._get_parameter_symbol('intensity', namespace))
weights = [
probability * neighbors(where(getattr(source, self.state) == option, 1, 0) * fermi, over=over)
for option in self.options
]
else:
weights = [probability * counts[option] for option in self.options]
stay = degree - sum(weights, SR(0)) + where(degree == 0, 1, 0)
index = categorical(self._get_draw_name(value, 'imitation'), [stay, *weights])
return value + sum(
(where(index == position + 1, option - value, 0) for position, option in enumerate(self.options)),
SR(0),
)
def _get_update(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the update of the state of the target with the probability of imitation.
It is for discrete time.
"""
value = getattr(self._get_member(namespace, 'target'), self.state)
if self.rule in ('random', 'fermi'):
return [UpdateLaw(value, self._draw_copy(namespace), phase=self.phase)]
if self.rule == 'majority':
leads = self._get_majority(namespace)
imitated = value + sum((lead * (option - value) for option, lead in leads.items()), SR(0))
elif self.rule != 'best':
raise self._get_variant_error(self.rule, 'rule', '_get_update')
else:
best, better = self._get_best(namespace)
imitated = where(better == 1, best, value)
return [
UpdateLaw(
value,
where(
uniform(self._get_draw_name(value, 'imitation'))
< self._get_parameter_symbol('probability', namespace),
imitated,
value,
),
phase=self.phase,
),
]
def _get_imitation_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the jumps or the update of the state by the rule of the imitation.
Args:
namespace:
The namespace of an edge.
Returns:
laws:
The jumps of the state between every pair of options, or the update of the state of every member.
"""
if self.schedule == 'member':
return [UpdateLaw(self._get_member(namespace, 'target'), self._imitate_member, phase=self.phase)]
if self.schedule is not None:
return [UpdateLaw(namespace, self._imitate, phase=self.phase)]
if self._get_argument('probability') is not None:
return self._get_update(namespace)
return self._get_jumps(namespace)
def _choose(
self,
agent: AgentViewProtocol,
neighbours: Sequence[AgentViewProtocol],
system: SystemViewProtocol,
) -> float | None:
"""Return the option an agent copies from its neighbours by the rule.
It returns `None` for the agent to keep its own.
"""
rng = system.rng
if self.rule == 'majority':
counts = [sum(getattr(other, self.state) == option for other in neighbours) for option in self.options]
leaders = np.flatnonzero(np.asarray(counts) == max(counts))
return float(self.options[int(leaders[0])]) if len(leaders) == 1 else None
if self.rule == 'random':
return float(getattr(neighbours[int(rng.integers(len(neighbours)))], self.state))
own = float(getattr(agent, self.payoff))
if self.rule == 'best':
payoffs = np.array([getattr(other, self.payoff) for other in neighbours], dtype=float)
best = self._pick_best(payoffs, self.ties, system)
return float(getattr(neighbours[best], self.state)) if payoffs[best] > own else None
other = neighbours[int(rng.integers(len(neighbours)))]
difference = float(getattr(other, self.payoff)) - own
if self.rule == 'better':
return float(getattr(other, self.state)) if difference > 0 else None
if self.rule != 'fermi':
raise self._get_variant_error(self.rule, 'rule', '_choose')
fermi = 1 / (1 + np.exp(-self._get_parameter_value('intensity', system) * difference))
return float(getattr(other, self.state)) if rng.random() < fermi else None
def _get_choice(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> float | None:
"""Return the option an agent copies with the probability of imitation.
It returns `None` for the agent to keep its own.
"""
groups = set(system.get_groups(self._get_role('target')))
neighbours = [other for other in agent.get_neighbors(layer=self.layer) if other.group in groups]
given = self._get_argument('probability') is not None
probability = self._get_parameter_value('probability', system) if given else 1.0
if not neighbours or system.rng.random() >= probability:
return None
return self._choose(agent, neighbours, system)
def _set_choice(self, agent: AgentViewProtocol, choice: float | None) -> None:
"""Set the state of an agent to the option it copies, if any."""
if choice is not None:
setattr(agent, self.state, choice)
def _imitate_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Let one agent imitate its neighbours with the probability of imitation.
This happens in its own activation.
"""
if agent.alive:
self._set_choice(agent, self._get_choice(agent, system))
def _imitate(self, system: SystemViewProtocol) -> None:
"""Let every agent imitate its neighbours with the probability of imitation.
The agents follow the schedule, or imitate at once without one.
"""
self._update_agents(system, self.schedule or 'synchronous', self._get_choice, self._set_choice)