Minority game and its evolutionary version
The minority game of an odd number of agents with two random strategies each.
- Class:
MinorityGameSystem - Import:
from skcomplex.systems.economics.econophysics import MinorityGameSystem - Field:
economics/econophysics - Topics:
minority game,agents,inductive reasoning,evolution - References:
- Challet and Zhang 1997
- Yakovenko and Rosser 2009
- Carmichael and Hadzikadic 2019 ch. 9
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.econophysics import MinorityGameSystem
trajectory = MinorityGameSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_agents |
101 |
memory |
3 |
evolutionary |
False |
period |
50 |
fraction |
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 | none |
| Laws | update |
| Randomness | stochastic |
| Domains | boolean, integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class MinorityGameSystem(BaseSystem):
"""The minority game of an odd number of agents with two random strategies each.
The system has the group `players`, the choice `choice` of the strategy of higher virtual score, the interaction
`game`, which reports the attendance `game.attendance`, the cumulative reinforcement `scoring` of the virtual
scores, and in the evolutionary version the truncation `evolution`, which gives the poorest agents new random
strategies and no wealth every `period` rounds.
Args:
n_agents:
The number of agents, odd so that there is always a minority.
memory:
The memory `m` of the strategies, so `alpha = 2^m / N`.
evolutionary:
Whether every `period` rounds the poorest agents take new random strategies.
period:
The number of rounds between two evolutions of the evolutionary version.
fraction:
The fraction of poorest agents that take new strategies at an evolution.
random_state:
The seed or generator of the 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.
Raises:
ValueError:
The number of agents is even.
Examples:
>>> from skcomplex.systems.economics.econophysics import MinorityGameSystem
>>> MinorityGameSystem(11, memory=2).prepare().system_.interactions[1].memory
2
"""
field = 'economics/econophysics'
topics = ('minority game', 'agents', 'inductive reasoning', 'evolution')
references = ('Challet and Zhang 1997', 'Yakovenko and Rosser 2009', 'Carmichael and Hadzikadic 2019 ch. 9')
until = 500
def __init__(
self,
n_agents: int = 101,
*,
memory: int = 3,
evolutionary: bool = False,
period: int = 50,
fraction: 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.n_agents = n_agents
self.memory = memory
self.evolutionary = evolutionary
self.period = period
self.fraction = fraction
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)
if self.n_agents % 2 == 0:
error_msg = f'The minority game needs an odd number of agents, got {self.n_agents}.'
raise ValueError(error_msg)
codes = np.random.default_rng(self.random_state).integers(MAX_SEED, size=(2, self.n_agents)).astype(float)
players = MinorityPlayerElement('players', first=codes[0], second=codes[1], size=self.n_agents)
choice = ChoiceInteraction(
'choice',
target='players',
state='strategy',
options=(0.0, 1.0),
utility=lambda agent, system, option: agent.second_score if option else agent.first_score,
rule='best',
schedule='synchronous',
phase='choose',
)
game = MinorityGameInteraction('game', players='players', memory=self.memory, phase='play')
scoring = PayoffLearningInteraction(
'scoring',
target='players',
scores=('first_score', 'second_score'),
payoff=game.get_payoff,
rule='cumulative',
schedule='synchronous',
phase='score',
)
evolution = EvolutionInteraction(
'evolution',
target='players',
strategy=('first', 'second'),
fitness='wealth',
replacement='truncation',
fraction=self.fraction,
mutation=1.0,
change='any',
alphabet=MAX_SEED,
period=self.period,
reset={'first_score': 0.0, 'second_score': 0.0, 'wealth': 0.0},
phase='score',
)
self.system_ = System(
self.label,
elements=[players],
interactions=[choice, game, scoring, *([evolution] if self.evolutionary else [])],
solver=MesaSolver(phases=[PhaseSpec('choose'), PhaseSpec('play'), PhaseSpec('score')]),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
MinorityPlayerElement, fromElement
Interactions:
ChoiceInteraction, fromInteraction, through the shared recipeChoiceInteractionMinorityGameInteraction, fromInteractionPayoffLearningInteraction, fromInteraction
class MinorityPlayerElement(Element):
"""Agent of the minority game, who holds two strategies and plays the one it chose.
Args:
label:
The label of the agent or group.
first:
The code of the first strategy.
second:
The code of the second strategy.
first_score:
The virtual score of the first strategy, the number of times it would have been in the minority.
second_score:
The virtual score of the second strategy.
strategy:
The strategy played, 0 for the first and 1 for the second.
action:
The last action, `+1` or `-1`.
wealth:
The net number of times the agent was in the minority.
size:
The number of members, or `None` for one.
Examples:
>>> from skcomplex.systems.economics.econophysics import MinorityPlayerElement
>>> MinorityPlayerElement('players', first=3, second=5, size=11).size
11
"""
def __init__(
self,
label: str,
*,
first: Annotated[object, NN] = 0.0,
second: Annotated[object, NN] = 1.0,
first_score: object = 0.0,
second_score: object = 0.0,
strategy: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
action: Annotated[object, ZZ] = 0.0,
wealth: object = 0.0,
size: int | None = None,
) -> None:
super().__init__(label, size=size)
self.first = first
self.second = second
self.first_score = first_score
self.second_score = second_score
self.strategy = strategy
self.action = action
self.wealth = wealth
class ChoiceInteraction(Interaction):
"""An interaction by which members of a group choose among options by utility.
At every step each member revises its choice with the probability `activity` and keeps it otherwise. The `rule`
draws the new option from the utilities `u_k` of the options:
- `'logit'`: option `k` with probability `exp(beta u_k) / sum_j exp(beta u_j)`, where `beta` is the intensity of
choice.
- `'metropolis'` and `'fermi'`: a proposed option, accepted with probability `min(1, exp(beta (u_new - u_old)))` or
`1 / (1 + exp(-beta (u_new - u_old)))`.
- `'best'`: an option of largest utility, with ties broken by `ties`.
Without a `schedule` it sets update laws: `utility(namespace, option)` returns an expression, and every member
draws at once. With a `schedule` it sets one rule of the whole system that walks the agents in that order with its
own draws: `utility(agent, system, option)` returns a number, and an option of utility `-inf` is never drawn.
Unlike a `JumpLaw`, which moves a state between values by given rates, it draws the new value from the utilities of
all options at once. Choose it when members pick the option that pays best, with noise.
It appears in many fields. Commuters choose a mode of transport, consumers choose a brand, farmers choose a crop,
and voters choose a party by a logit model of discrete choice.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the element or group whose members choose.
state:
The name of the discrete state of the members that holds the chosen option.
options:
The values the state can take, at least two.
utility:
The function `utility(namespace, option)` without a schedule, or `utility(agent, system, option)` with one,
that returns the utility of an option.
rule:
The rule of the draw, `'logit'`, `'metropolis'`, `'fermi'`, or `'best'`.
intensity:
The intensity of choice `beta`, zero for uniform choice.
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 update laws of the states of every member.
activity:
The probability that a member revises its choice in a step.
phase:
The phase of the step the rule of a schedule runs in, or `None` for the default phase.
proposal:
The options the rules `'metropolis'` and `'fermi'` propose from, `'others'` for the options other than the
current one, or `'all'` for every option.
ties:
The option the rule `'best'` takes among options of equal largest utility, `'random'` for one drawn
uniformly or `'first'` for the first in the order of the options.
Raises:
ValidationError:
The rule, the schedule, the proposal, or the ties are unknown, there are fewer than two options, or the
utility is not callable.
Examples:
>>> from skcomplex.systems.general.agents import ChoiceInteraction
>>> from skcomplex.core.components.laws.utils import mean
>>> choice = ChoiceInteraction(
... 'choice', target='spins', state='spin', options=(-1, 1), utility=lambda s, o: o * mean(s.target.spin)
... )
>>> choice.rule
'logit'
>>> agents = ChoiceInteraction(
... 'choice', target='traders', state='plan', options=(0, 1), utility=lambda a, m, o: o,
... schedule='synchronous',
... )
>>> type(agents.prepare(SimpleNamespace(target=SimpleNamespace())).laws_[0]).__name__
'UpdateLaw'
>>> ChoiceInteraction(
... 'heat-bath', target='spins', state='spin', options=(-1, 0, 1), utility=lambda s, o: o, rule='fermi',
... proposal='all'
... ).proposal
'all'
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def _get_draws(self) -> bool:
"""Return whether the choice draws.
Every rule draws but the best option with the first of ties every step.
"""
fixed = self.rule == 'best' and self.ties == 'first' and self.activity == 1
return super()._get_draws() or not fixed
def __init__(
self,
label: str,
*,
target: Role,
state: str,
options: Sequence[float],
utility: Callable[..., float | Expression],
rule: str = 'logit',
intensity: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
schedule: str | None = None,
activity: Annotated[float, RealSet.closed(0, 1)] = 1.0,
phase: str | None = None,
proposal: str = 'others',
ties: str = 'random',
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.options = options
self.utility = utility
self.rule = rule
self.intensity = intensity
self.schedule = schedule
self.activity = activity
self.phase = phase
self.proposal = proposal
self.ties = ties
def _check_variants(self) -> None:
"""Raise an error for an unknown variant."""
self._check_variant('rule', self.rule, RULES, (BaseSpec,))
for name, value, variants in (
('schedule', self.schedule, (None, *ScheduleKind)),
('proposal', self.proposal, PROPOSALS),
('ties', self.ties, TIES),
):
if value not in variants:
error_msg = f'Unknown {name} {value!r} of {self.label!r}. Use one of {variants}.'
raise ValidationError(error_msg)
def _check_arguments(self) -> None:
"""Raise an error for an unknown variant, fewer than two options, or a bad utility.
Raises:
ValidationError:
The type declares states, the rule, the schedule, the proposal, or the ties are unknown, there are fewer
than two options, or the utility is not callable.
"""
super()._check_arguments()
self._check_variants()
if len(self.options) < MIN_OPTIONS:
error_msg = f'{self.label!r} chooses among {list(self.options)}. Give at least {MIN_OPTIONS} options.'
raise ValidationError(error_msg)
if not callable(self.utility):
error_msg = f'The utility of {self.label!r} must be callable, but it is {self.utility!r}.'
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_choice_laws(context)
@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 _select(self, index: Expression, values: Sequence[Expression]) -> Expression:
"""Return the value at a symbolic index."""
return sum((where(index == position, value, 0) for position, value in enumerate(values)), SR(0))
def _draw_softmax(self, state: Expression, utilities: Sequence[Expression], intensity: Expression) -> Expression:
"""Return the option drawn with probabilities proportional to `exp(beta u_k)`."""
index = categorical(self._get_draw_name(state, 'option'), [exp(intensity * utility) for utility in utilities])
return self._select(index, [SR(option) for option in self.options])
def _draw_best(self, state: Expression, utilities: Sequence[Expression]) -> Expression:
"""Return an option drawn uniformly among the options of largest utility."""
largest = utilities[0]
for utility in utilities[1:]:
largest = where(utility > largest, utility, largest)
weights = [where(utility >= largest, 1, 0) for utility in utilities]
if self.ties == 'first':
weights = [
weight * where(sum(weights[:position], SR(0)) > 0, 0, 1) for position, weight in enumerate(weights)
]
index = categorical(self._get_draw_name(state, 'best'), weights)
return self._select(index, [SR(option) for option in self.options])
def _draw_proposal(self, state: Expression, utilities: Sequence[Expression], intensity: Expression) -> Expression:
"""Return a uniform proposal of an option.
The proposal is accepted by the Metropolis or the Fermi probability.
"""
weights = [SR(1) if self.proposal == 'all' else where(state == option, 0, 1) for option in self.options]
index = categorical(self._get_draw_name(state, 'proposal'), weights)
proposal = self._select(index, [SR(option) for option in self.options])
gain = self._select(index, utilities) - sum(
(where(state == option, utility, 0) for option, utility in zip(self.options, utilities, strict=True)),
SR(0),
)
if self.rule == 'metropolis':
acceptance = where(gain >= 0, 1, exp(intensity * gain))
else:
acceptance = 1 / (1 + exp(-intensity * gain))
return where(uniform(self._get_draw_name(state, 'acceptance')) < acceptance, proposal, state)
def _draw_symbolic(self, namespace: SimpleNamespace) -> Expression:
"""Return the option a member draws, as a symbolic expression of the namespace."""
state = getattr(self._get_member(namespace, 'target'), self.state)
utilities = [SR(self.utility(namespace, option)) for option in self.options]
if self.rule == 'logit':
return self._draw_softmax(state, utilities, self._get_parameter_symbol('intensity', namespace))
if self.rule == 'best':
return self._draw_best(state, utilities)
if self.rule in ('metropolis', 'fermi'):
return self._draw_proposal(state, utilities, self._get_parameter_symbol('intensity', namespace))
raise self._get_variant_error(self.rule, 'rule', '_draw_symbolic')
def _get_utilities(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> np.ndarray:
"""Return the utility of every option for an agent."""
return np.array([float(self.utility(agent, system, option)) for option in self.options])
def _draw_agent_proposal(self, agent: AgentViewProtocol, system: SystemViewProtocol, intensity: float) -> float:
"""Return a uniform proposal of an option of an agent if accepted.
Otherwise it returns its current option.
"""
current = float(getattr(agent, self.state))
others = [option for option in self.options if self.proposal == 'all' or option != current]
proposal = float(others[int(system.rng.integers(len(others)))])
before = float(self.utility(agent, system, current)) if current in self.options else 0.0
gain = float(self.utility(agent, system, proposal)) - before
if self.rule == 'metropolis':
acceptance = 1.0 if gain >= 0 else math.exp(intensity * gain)
else:
acceptance = float(expit(intensity * gain))
return proposal if system.rng.random() < acceptance else current
def _draw_agent(self, agent: AgentViewProtocol, system: SystemViewProtocol, intensity: float) -> float:
"""Return the option an agent draws by the rule."""
if self.rule in ('metropolis', 'fermi'):
return self._draw_agent_proposal(agent, system, intensity)
utilities = self._get_utilities(agent, system)
if self.rule == 'best':
return float(self.options[self._pick_best(utilities, self.ties, system)])
if self.rule != 'logit':
raise self._get_variant_error(self.rule, 'rule', '_draw_agent')
scaled = np.where(np.isneginf(utilities), -np.inf, intensity * utilities)
probabilities = softmax(scaled)
return float(self.options[int(system.rng.choice(len(self.options), p=probabilities))])
def _is_active(self, system: SystemViewProtocol, activity: float) -> bool:
"""Return whether a member revises its choice in this step."""
return activity >= 1 or bool(system.rng.random() < activity)
def _get_choice(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> float | None:
"""Return the option an agent draws if it revises in this step.
It returns `None` for the agent to keep its own.
"""
if not self._is_active(system, self._get_parameter_value('activity', system)):
return None
return self._draw_agent(agent, system, self._get_parameter_value('intensity', system))
def _set_choice(self, agent: AgentViewProtocol, option: float | None) -> None:
"""Set the state of an agent to the option it draws, if any."""
if option is not None:
setattr(agent, self.state, option)
def _choose_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Set the state of one agent to the option it draws if it revises.
This happens in its own activation.
"""
if agent.alive:
self._set_choice(agent, self._get_choice(agent, system))
def choose(self, system: SystemViewProtocol) -> None:
"""Set the state of every revising agent to the option it draws, by the schedule.
An agent revises in this step. Without a schedule every agent draws at once.
Args:
system:
The system view of the interaction.
"""
self._update_agents(system, self.schedule or 'synchronous', self._get_choice, self._set_choice)
def _get_choice_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the update of the state of every revising member.
With a schedule it returns the rule that walks the agents instead.
Args:
namespace:
The namespace of the symbols the laws can use, with `namespace.target`, `namespace.intensity`, and
`namespace.activity`.
Returns:
laws:
The update law of the state, or the rule that runs the choice of the agents.
"""
if self.schedule == 'member':
return [UpdateLaw(self._get_member(namespace, 'target'), self._choose_member, phase=self.phase)]
if self.schedule is not None:
return [UpdateLaw(namespace, self.choose, phase=self.phase)]
state = getattr(self._get_member(namespace, 'target'), self.state)
revised = where(
uniform(self._get_draw_name(state, 'activity')) < self._get_parameter_symbol('activity', namespace),
self._draw_symbolic(namespace),
state,
)
return [UpdateLaw(state, revised)]
class MinorityGameInteraction(Interaction):
"""Rounds of the minority game of Challet and Zhang.
The agents on the minority side win. Every round each agent plays the action, `+1` or `-1`, that its chosen strategy
assigns to the last `m` winning sides, the strategy of higher virtual score that a `ChoiceInteraction` of rule
`'best'` chooses before. The side with fewer agents wins, and every agent on it gains one point and every other
loses one. The game reports the attendance `A = sum_i a_i` and the code of the history the strategies read, so a
cumulative `PayoffLearningInteraction` gives every strategy one virtual point when it would have played the winning
side, by the payoff `payoff`. The volatility `sigma^2 / N` of the attendance has a minimum below the value of random
play near `alpha = 2^m / N ~ 0.34`.
Args:
label:
The label of the interaction.
players:
The path of the group of agents.
memory:
The memory `m`, the number of past winning sides the strategies read.
phase:
The phase the rounds run in, or `None` for the default phase.
Examples:
>>> from skcomplex.systems.economics.econophysics import MinorityGameInteraction
>>> MinorityGameInteraction('game', players='players', memory=4).memory
4
"""
law_classes = (UpdateLaw,)
reports: ClassVar[tuple[str, ...]] = ('attendance', 'history')
def __init__(
self,
label: str,
*,
players: Role,
memory: int = 3,
phase: str | None = None,
) -> None:
super().__init__(label)
self.players = players
self.memory = memory
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rules of the system as the laws.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self.play, phase=self.phase)]
def _get_table(self, code: float, system: SystemView) -> IntArray:
"""Return the table of a strategy, cached for the run in the state of the game."""
state = self._get_state(system)
if code not in state.tables:
state = replace(state, tables={**state.tables, code: strategy_table(code, self.memory)})
system.storage['game'] = state
return state.tables[code]
def _get_state(self, system: SystemView) -> _GameStateSpec:
"""Return the state of the game in the storage of the system.
The first round starts a random history.
"""
state = system.storage.get('game')
if not isinstance(state, _GameStateSpec):
state = _GameStateSpec(int(system.rng.integers(2**self.memory)))
system.storage['game'] = state
return state
def play(self, system: SystemView) -> None:
"""Play one round, pay the agents, and update and report the history.
Args:
system:
The system.
"""
agents = cast(list[MinorityPlayerView], system.get_agents('players'))
history = self._get_state(system).history
for agent in agents:
code = agent.second if agent.strategy else agent.first
agent.action = float(2 * int(self._get_table(code, system)[history]) - 1)
attendance = sum(agent.action for agent in agents)
winner = -1 if attendance > 0 else 1
for agent in agents:
agent.wealth += agent.action * winner
state = self._get_state(system)
system.storage['game'] = replace(state, history=(2 * history + (winner > 0)) % 2**self.memory)
system.report('attendance', attendance)
system.report('history', float(history))
def get_payoff(self, agent: MinorityPlayerView, system: SystemView, option: int) -> float:
"""Return the virtual payoff of a strategy of an agent in the last round.
It is `+1` if it played the winning side.
Args:
agent:
The agent.
system:
The system view of the rule that reads the payoff.
option:
The strategy, 0 for the first and 1 for the second.
Returns:
payoff:
`+1` when the strategy would have played the winning side, or `-1`.
"""
history = int(system.get_history(f'{self.label}.history')[-1])
winner = -1 if system.get_history(f'{self.label}.attendance')[-1] > 0 else 1
code = agent.second if option else agent.first
return float((2 * int(strategy_table(code, self.memory)[history]) - 1) * winner)
class PayoffLearningInteraction(Interaction):
"""Payoff learning of the scores of options.
Economics names it reinforcement learning of payoffs, as in fictitious play and the attractions of
experience-weighted learning. Each score moves towards the payoff its option realized in the step. Every step, the
score `s_k` of option `k` of every member moves towards the realized payoff `P_k` at the rate `a`, `s_k <- s_k + a
(P_k - s_k)`, so a score is an exponentially weighted mean of past payoffs, and the last payoff at the rate 1, by
the rule `'average'`. By the rule `'cumulative'` the score adds the payoff, `s_k <- s_k + P_k`, so it is the sum of
past payoffs, such as a virtual score. Without a `schedule` it sets update laws, and `payoff(namespace, k)` returns
the payoff of option `k` as a symbolic expression, where `namespace.target` holds the states and parameters of the
group. With a `schedule` it sets one rule that walks the agents of the group in that order, and `payoff(agent,
system, k)` returns the payoff as a number, so it can read the agent and the history and storage of the system view.
Its scores may then be the components of one vector state, one per option, and a group of one member holds scores
that several groups share. With `chosen`, the name of a state that holds the index of the option a member chose,
only the score of that option moves, and the payoff of the other options is not read. Every agent reinforces at
once under the schedule `'synchronous'`, one after the other in their order or in a new random order every step
under `'sequential'` or `'random-sequential'`, and each in its own activation under `'member'`, together with the
rules of its element and the other member interactions, in the order the system lists them, such as after a choice
and a transfer in one visit.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the element or group whose members hold the scores.
scores:
The names of the states that hold the score of every option, in the order of the options, or with a
schedule the name of one vector state whose components are the scores.
payoff:
The function `payoff(namespace, k)` without a schedule, or `payoff(agent, system, k)` with one, that
returns the realized payoff of option `k`.
rate:
The rate `a` at which the scores move towards the payoffs, between 0 and 1, by the rule `'average'`.
rule:
`'average'` to move the scores towards the payoffs, or `'cumulative'` to add the payoffs to the scores.
phase:
The phase of the step the rule of a schedule runs in, or `None` for the default phase.
chosen:
The name of the state that holds the index of the option a member chose, so only its score moves, or
`None` to move every score.
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 update laws of the scores of every member.
Raises:
ValidationError:
The rule or the schedule is unknown, there are no scores, or the payoff is not callable.
Examples:
>>> from skcomplex.systems.economics.common.learning import PayoffLearningInteraction
>>> reinforcement = PayoffLearningInteraction(
... 'reinforcement', target='learners', scores=('first', 'second'), payoff=lambda s, k: k, rate=0.5
... )
>>> reinforcement.rate
0.5
>>> PayoffLearningInteraction(
... 'virtual', target='players', scores='scores', payoff=lambda a, m, k: k, rule='cumulative',
... schedule='synchronous',
... ).rule
'cumulative'
>>> PayoffLearningInteraction(
... 'satisfaction', target='customers', scores=('s1', 's2'), payoff=lambda a, m, k: 1.0, chosen='shop',
... schedule='member',
... ).chosen
'shop'
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
scores: str | Sequence[str],
payoff: Callable[..., float | Expression],
rate: Annotated[float, RealSet.closed(0, 1)] = 0.1,
rule: str = 'average',
phase: str | None = None,
chosen: str | None = None,
schedule: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.scores = scores
self.payoff = payoff
self.rate = rate
self.rule = rule
self.chosen = chosen
self.phase = phase
self.schedule = schedule
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The rule or the schedule is unknown, there are no scores, or the payoff is not callable.
"""
super()._check_arguments()
self._check()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the update of the scores, or the rule of the agents, as the laws.
Args:
context:
The namespace of the members it binds.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = self._get_learning_laws(context)
def _check(self) -> None:
"""Raise an error for an unknown variant, no scores, or an uncallable payoff."""
if self.schedule not in SCHEDULES:
error_msg = f'Unknown schedule {self.schedule!r} of {self.label!r}. Use one of {SCHEDULES}.'
raise ValidationError(error_msg)
if self.rule not in RULES:
error_msg = f'Unknown rule {self.rule!r} of {self.label!r}. Use one of {RULES}.'
raise ValidationError(error_msg)
vector = isinstance(self.scores, str) and bool(self.scores) and self.schedule is not None
if not vector and (isinstance(self.scores, str) or not self.scores):
error_msg = (
f'{self.label!r} has the scores {self.scores!r}. Give a sequence of state names, one per option, or '
'with a schedule the name of a vector state.'
)
raise ValidationError(error_msg)
if not callable(self.payoff):
error_msg = f'The payoff of {self.label!r} must be callable, but it is {self.payoff!r}.'
raise ValidationError(error_msg)
def _read_scores(self, agent: AgentViewProtocol) -> Array:
"""Return the scores of an agent, one per option."""
if isinstance(self.scores, str):
return np.array(getattr(agent, self.scores), dtype=float).ravel()
return np.array([getattr(agent, name) for name in self.scores], dtype=float)
def _get_scores(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> Array:
"""Return the new scores of an agent.
Every score, or only that of its chosen option, moves by its payoff.
"""
old = self._read_scores(agent)
options = range(len(old)) if self.chosen is None else [int(getattr(agent, self.chosen))]
rate = 1.0 if self.rule == 'cumulative' else self.rate
change = np.zeros_like(old)
for k in options:
payoff = float(self.payoff(agent, system, k))
change[k] = payoff if self.rule == 'cumulative' else rate * (payoff - old[k])
return old + change
def _set_value(self, agent: AgentViewProtocol, value: object) -> None:
"""Set the scores of an agent."""
scores = np.asarray(value, dtype=float)
if isinstance(self.scores, str):
setattr(agent, self.scores, scores)
return
for name, score in zip(self.scores, scores, strict=True):
setattr(agent, name, float(score))
def _update_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""Move the scores of one agent, in its own activation."""
if agent.alive:
self._set_value(agent, self._get_scores(agent, system))
def update(self, system: SystemViewProtocol) -> None:
"""Move the scores of every agent by the schedule.
Under `'synchronous'` every agent reads the scores at the start of the rule, and otherwise the agents move one
after the other, in their order or in a new random order.
Args:
system:
The system view of the learning.
"""
agents = list(system.get_agents('target'))
if self.schedule == 'synchronous':
values = [self._get_scores(agent, system) for agent in agents]
for agent, value in zip(agents, values, strict=True):
self._set_value(agent, value)
return
order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
for index in order:
self._update_member(agents[int(index)], system)
def _get_learning_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the update of every score towards its payoff, or the rule of the schedule."""
if self.schedule == 'member':
return [UpdateLaw(namespace.target, self._update_member, phase=self.phase)]
if self.schedule is not None:
return [UpdateLaw(namespace, self.update, phase=self.phase)]
laws: list[BaseLaw] = []
for index, name in enumerate(self.scores):
score = getattr(namespace.target, name)
payoff = self.payoff(namespace, index)
change = payoff if self.rule == 'cumulative' else namespace.rate * (payoff - score)
if self.chosen is not None:
change = where(getattr(namespace.target, self.chosen) == index, change, 0)
laws.append(UpdateLaw(score, score + change))
return laws
Equations
The equations are those that symbolic returns for the system with its default parameters.