Skip to content

Econophysics

Econophysics: wealth exchange between agents.

BoltzmannWealthSystem(n_agents=100, *, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A Boltzmann wealth exchange system where every agent starts with one unit.

Every step, every agent with any wealth gives one unit to another agent drawn at random, in random order. The system has the group traders and the transfer gifts.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

100
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.economics.econophysics import BoltzmannWealthSystem
>>> BoltzmannWealthSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/econophysics/_exchange.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(
    self,
    n_agents: int = 100,
    *,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_agents = n_agents

CoalitionBarInteraction(label, *, rule=None, phase=None, patrons, strategies=(), capacity=60.0, smoothing=0.1, coalitions=True)

Bases: PolicyRuleInteraction[SystemView]

El Farol bar of Rand and Wilensky with coalitions of patrons.

The patrons share strategies within coalitions that split and merge. A strategy s in [-1, 1]^(m + 1) predicts the attendance n s_1 + sum_j s_(j + 1) h_j from the last m attendances h, and its error is the total absolute error of its predictions over the last m nights. Every night every coalition uses the strategy of the lowest error among the strategies of its members, and every member goes when the prediction is at most the capacity. Every member's return moves by smoothing towards 1 after a good night and towards 0 after a bad one. With coalitions, after every night (Collins 2019, Section 3.2), every coalition in random order that attended an overcrowded night within the memory, when the smallest excess x of those nights is below its size N, splits off a random subgroup of at most N - x members that holds the owner of its best strategy. Then, at most once per coalition and night, two coalitions that attended an uncrowded night merge unless their joint size would have overcrowded an uncrowded night either attended within the memory. A merged coalition keeps the longer history.

Parameters:

Name Type Description Default
label str

The label of the bar.

required
rule None

Unused, since the bar overrides act.

None
phase str | None

The phase the bar acts in, or None for the default phase.

None
patrons Role

The path of the group of patrons.

required
strategies tuple[tuple[tuple[float, ...], ...], ...]

The strategies of every patron, strategies[i][k] the m + 1 weights of strategy k of patron i.

()
capacity Annotated[float, open(0, oo)]

The attendance above which the bar is overcrowded.

60.0
smoothing Annotated[float, closed(0, 1)]

The weight lambda of the last night in the return.

0.1
coalitions bool

Whether patrons form coalitions.

True

Examples:

>>> from skcomplex.systems.economics.econophysics import CoalitionBarInteraction
>>> CoalitionBarInteraction('bar', patrons='patrons').reports[:2]
('attendance', 'coalitions')
Source code in src/skcomplex/systems/economics/econophysics/_coalitions.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    patrons: Role,
    strategies: tuple[tuple[tuple[float, ...], ...], ...] = (),
    capacity: Annotated[float, RealSet.open(0, oo)] = 60.0,
    smoothing: Annotated[float, RealSet.closed(0, 1)] = 0.1,
    coalitions: bool = True,
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.patrons = patrons
    self.strategies = strategies
    self.capacity = capacity
    self.smoothing = smoothing
    self.coalitions = coalitions

act(system)

Decide the night, score the patrons, and let the coalitions split and merge.

Parameters:

Name Type Description Default
system SystemView

The system view of the bar.

required
Source code in src/skcomplex/systems/economics/econophysics/_coalitions.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def act(self, system: SystemView) -> None:
    """Decide the night, score the patrons, and let the coalitions split and merge.

    Args:
        system:
            The system view of the bar.
    """
    patrons = sorted(cast(list[CoalitionPatronView], system.get_agents('patrons')), key=lambda patron: patron.id)
    strategies = np.asarray(self.strategies, dtype=float)
    memory, size, capacity = strategies.shape[-1] - 1, len(patrons), system.get_parameter('capacity')
    stored = system.storage.get('history')
    history = np.asarray(stored) if isinstance(stored, np.ndarray) else system.rng.integers(0, size + 1, 2 * memory)
    records = system.storage.get('records')
    records = records if isinstance(records, dict) else {}
    labels = np.array([int(patron.coalition) for patron in patrons])
    if not self.coalitions:
        labels = np.arange(size)
    errors = self._get_errors(strategies, history.astype(float))
    best: dict[int, int] = {}
    attends = np.zeros(size, dtype=bool)
    for label in np.unique(labels):
        members = np.flatnonzero(labels == label)
        owner, strategy = np.unravel_index(np.argmin(errors[members]), errors[members].shape)
        best[int(label)] = int(members[owner])
        weights = strategies[members[owner], strategy]
        attends[members] = size * weights[0] + weights[1:] @ history[:memory] <= capacity
    attendance = float(attends.sum())
    crowded = attendance > capacity
    good = np.where(attends, not crowded, crowded)
    smoothing = system.get_parameter('smoothing')
    scores = np.array([patron.score for patron in patrons]) * (1 - smoothing) + smoothing * good
    for label in np.unique(labels[attends]):
        records.setdefault(int(label), []).append((attendance, float(np.sum(labels == label))))
    for label in list(records):
        records[label] = records[label][-memory:]
    splits = joins = 0
    if self.coalitions:
        splits = self._split(system, labels, best, records)
        joins = 0 if crowded else self._join(system, labels, attends, records)
    system.storage.update(history=np.concatenate(([attendance], history[:-1])), records=records)
    for patron, label, went, score in zip(patrons, labels, attends, scores, strict=True):
        patron.coalition, patron.attends, patron.score = float(label), float(went), float(score)
    system.report('attendance', attendance)
    system.report('coalitions', float(len(np.unique(labels))))
    system.report('mean_score', float(scores.mean()))
    system.report('splits', float(splits))
    system.report('joins', float(joins))

CoalitionPatronElement(label, *, coalition=0.0, attends=0.0, score=0.0, size=None)

Bases: Element

Patron of the El Farol bar who belongs to a coalition.

It keeps a smoothed return of its nights.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
coalition Annotated[object, NN]

The label of the coalition of the patron.

0.0
attends Annotated[object, closed(0, 1)]

1 when the patron went to the bar on the last night, 0 otherwise.

0.0
score Annotated[object, closed(0, 1)]

The exponentially smoothed share of good nights, a night at the bar that was not overcrowded or a night away from an overcrowded bar.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import CoalitionPatronElement
>>> CoalitionPatronElement('patrons', size=3).size
3
Source code in src/skcomplex/systems/economics/econophysics/_coalitions.py
64
65
66
67
68
69
70
71
72
73
74
75
76
def __init__(
    self,
    label: str,
    *,
    coalition: Annotated[object, NN] = 0.0,
    attends: Annotated[object, RealSet.closed(0, 1)] = 0.0,
    score: Annotated[object, RealSet.closed(0, 1)] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.coalition = coalition
    self.attends = attends
    self.score = score

CrowdAvoidanceInteraction(label, *, target, options, state='restaurant', intensity=1.0, activity=1.0, phase=None)

Bases: ChoiceInteraction

Stochastic crowd avoidance of diners, who leave crowded restaurants.

A diner returns to last evening's restaurant with probability 1 / n, with n the crowd it found there, and otherwise moves to one of the other restaurants at random, which raises the utilization to about 0.8. It is a Metropolis choice of intensity 1 where every other restaurant has utility 0 and staying has the utility -log(1 - 1 / n), so a proposed move is accepted with probability 1 - 1 / n.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target str

The path of the group of diners.

required
options Sequence[float]

The restaurants, from 0 to their number minus one.

required
state str

The state of the diners that holds their restaurant.

'restaurant'
intensity float

The intensity of choice, 1 for the stay probability 1 / n.

1.0
activity float

The probability that a diner revises its choice in an evening.

1.0
phase str | None

The phase the choice runs in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import CrowdAvoidanceInteraction
>>> CrowdAvoidanceInteraction('choice', target='diners', options=(0.0, 1.0)).rule
'metropolis'
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __init__(
    self,
    label: str,
    *,
    target: str,
    options: Sequence[float],
    state: str = 'restaurant',
    intensity: float = 1.0,
    activity: float = 1.0,
    phase: str | None = None,
) -> None:
    super().__init__(
        label,
        target=target,
        state=state,
        options=options,
        utility=self._get_utility,
        rule='metropolis',
        intensity=intensity,
        activity=activity,
        schedule='synchronous',
        phase=phase,
    )

DebtExchangeInteraction(label, *, target, debt=0.0, amount=1.0, phase=None)

Bases: Interaction

Random pairwise trades of Dragulescu and Yakovenko of a fixed amount.

Debt is allowed down to a limit. In every trade an agent pays a fixed amount to another agent drawn at random, unless its wealth would fall below minus the debt limit. Every step, every agent pays once, in random order. The stationary wealth distribution is the exponential P(w) = exp(-(w + d) / T) / T shifted to the debt limit d, with temperature T = <w> + d.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of traders.

required
debt Annotated[float, closed_open(0, oo)]

The debt limit d, the largest debt an agent can have.

0.0
amount Annotated[float, open(0, oo)]

The amount paid in every trade.

1.0
phase str | None

The phase the trades run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import DebtExchangeInteraction
>>> DebtExchangeInteraction('trades', target='traders', debt=5.0).debt
5.0
Source code in src/skcomplex/systems/economics/econophysics/_kinetic.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    label: str,
    *,
    target: Role,
    debt: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
    amount: Annotated[float, RealSet.open(0, oo)] = 1.0,
    phase: str | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.debt = debt
    self.amount = amount
    self.phase = phase

trade(system)

Let every trader pay the amount to a random trader, in random order, while it stays above the limit.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the trades.

required
Source code in src/skcomplex/systems/economics/econophysics/_kinetic.py
124
125
126
127
128
129
130
131
132
133
134
135
136
def trade(self, system: SystemViewProtocol) -> None:
    """Let every trader pay the amount to a random trader, in random order, while it stays above the limit.

    Args:
        system:
            The system view of the trades.
    """
    traders = system.get_agents('target')
    found = cast(Pairs, list(pairs(traders, traders, system.rng, PartnerSpec('all', 'uniform'))))
    for index in system.rng.permutation(len(found)):
        payer, payee = found[int(index)]
        if payer.alive and payee.alive and payer.wealth - self.amount >= -self.debt:
            transfer(payer, payee, self.amount, 'wealth')

DinerElement(label, *, restaurant=0.0, crowd=0.0, served=0.0, size=None)

Bases: Element

Diner of the Kolkata Paise Restaurant problem.

It goes to one restaurant every evening.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
restaurant Annotated[object, NN]

The restaurant chosen last, from 0 to the number of restaurants minus one.

0.0
crowd Annotated[object, NN]

The number of diners at that restaurant, 0 before the first evening.

0.0
served Annotated[object, FiniteEnumeratedSet([0, 1])]

Whether the diner got a meal, 1 or 0.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import DinerElement
>>> DinerElement('diners', size=10).size
10
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(
    self,
    label: str,
    *,
    restaurant: Annotated[object, NN] = 0.0,
    crowd: Annotated[object, NN] = 0.0,
    served: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.restaurant = restaurant
    self.crowd = crowd
    self.served = served

ElFarolCoalitionsSystem(n_agents=100, *, capacity=60.0, memory=5, n_strategies=10, smoothing=0.1, coalitions=True, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Collins' El Farol bar with strategic group formation.

Its coalitions share their best strategy. Patrons of Rand and Wilensky's El Farol model predict the attendance with linear strategies of the last memory attendances and go when they predict room. In Collins' version (Carmichael et al. 2019, chapter 9) patrons form coalitions that use the best strategy of all their members, so a larger coalition has better predictions but adds more to the crowd. Coalitions split off the members with the best strategy after overcrowded nights, the core condition that no subgroup gains by leaving, and coalitions that attended together merge when it would not have crowded an earlier good night. Without coalitions the mean attendance stays near the capacity and patrons enjoy about half their nights, while coalitions make the attendance swing and lower the returns of all, because the patrons are boundedly rational. The return of a patron is exponentially smoothed with the weight smoothing, which the source leaves open.

The system has the group patrons and the bar bar, whose reporters are bar.attendance, the number of coalitions bar.coalitions, the mean return bar.mean_score, and the splits bar.splits and joins bar.joins of the night.

Parameters:

Name Type Description Default
n_agents int

The number of patrons.

100
capacity float

The attendance above which the bar is overcrowded.

60.0
memory int

The number of past attendances a strategy reads.

5
n_strategies int

The number of strategies of every patron.

10
smoothing float

The weight of the last night in the return.

0.1
coalitions bool

Whether patrons form coalitions.

True
random_state int | Generator | None

The seed or generator of the strategies.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.economics.econophysics import ElFarolCoalitionsSystem
>>> ElFarolCoalitionsSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/econophysics/_coalitions.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def __init__(
    self,
    n_agents: int = 100,
    *,
    capacity: float = 60.0,
    memory: int = 5,
    n_strategies: int = 10,
    smoothing: float = 0.1,
    coalitions: bool = True,
    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.capacity = capacity
    self.memory = memory
    self.n_strategies = n_strategies
    self.smoothing = smoothing
    self.coalitions = coalitions
    self.random_state = random_state

ElFarolSystem(n_agents=100, *, capacity=60.0, n_predictors=6, discount=0.9, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Arthur's El Farol bar problem.

Its attendance self-organizes around the capacity. Every patron holds a random set of predictors of next week's attendance, drawn from a pool of 46, and acts on its currently most accurate one, going when it forecasts room in the bar. The attendance is random-looking, yet its mean settles near the capacity. The patrons read the past attendances from the observable attendance of the run, which the catalog lists, so a run passes it in observables.

The system has the group patrons, the one-member group pool of the forecasts and the errors of the predictors, the reinforcement scoring of the errors, and the choice choice to go when the forecast is below the capacity of the patrons.

Parameters:

Name Type Description Default
n_agents int

The number of patrons.

100
capacity float

The attendance above which the bar is too crowded to enjoy.

60.0
n_predictors int

The number of predictors every patron holds.

6
discount float

The weight of past errors in the accuracy of a predictor.

0.9
random_state int | Generator | None

The seed or generator of the predictors that every patron holds.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.economics.econophysics import ElFarolSystem
>>> ElFarolSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def __init__(
    self,
    n_agents: int = 100,
    *,
    capacity: float = 60.0,
    n_predictors: int = 6,
    discount: float = 0.9,
    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.capacity = capacity
    self.n_predictors = n_predictors
    self.discount = discount
    self.random_state = random_state

ForecastingInteraction(label, *, target, phase='forecast')

Bases: Interaction

Forecasts of next week's attendance by every predictor of the pool of the El Farol bar.

Every week the pool forecasts the attendance with every predictor, from ten random weeks it draws at the first week followed by the attendances of the observable attendance of the run.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the pool.

required
phase str | None

The phase the pool forecasts in.

'forecast'

Examples:

>>> from skcomplex.systems.economics.econophysics import ForecastingInteraction
>>> ForecastingInteraction('forecasting', target='pool').phase
'forecast'
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
177
178
179
180
def __init__(self, label: str, *, target: Role, phase: str | None = 'forecast') -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

forecast(agent, system)

Forecast next week's attendance with every predictor of the pool.

Parameters:

Name Type Description Default
agent PredictorPoolView

The pool.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
200
201
202
203
204
205
206
207
208
209
210
def forecast(self, agent: PredictorPoolView, system: SystemView) -> None:
    """Forecast next week's attendance with every predictor of the pool.

    Args:
        agent:
            The pool.

        system:
            The system.
    """
    agent.forecasts = forecasts(self._get_history(system))

get_error(agent, system, index) staticmethod

Return the absolute error of a predictor last week.

Before the first attendance, it is its error so far.

Parameters:

Name Type Description Default
agent PredictorPoolView

The pool.

required
system SystemView

The system view of the rule that reads the error.

required
index int

The index of the predictor in the pool.

required

Returns:

Name Type Description
error float

The absolute error of the forecast of the predictor.

Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@staticmethod
def get_error(agent: PredictorPoolView, system: SystemView, index: int) -> float:
    """Return the absolute error of a predictor last week.

    Before the first attendance, it is its error so far.

    Args:
        agent:
            The pool.

        system:
            The system view of the rule that reads the error.

        index:
            The index of the predictor in the pool.

    Returns:
        error:
            The absolute error of the forecast of the predictor.
    """
    attendance = system.get_history(ForecastingInteraction.attendance)
    if not len(attendance):
        return float(np.ravel(agent.errors)[index])
    return float(abs(np.ravel(agent.forecasts)[index] - attendance[-1]))

KineticWealthExchangeSystem(n_agents=500, *, saving=0.0, debt=None, wealth=1.0, amount=0.1, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A kinetic wealth exchange system with a saving propensity or a debt limit.

Without a debt limit, agents trade random shares of their pooled wealth after saving a fraction saving of it, as in Chakraborti and Chakrabarti. With a debt limit, they pay a fixed amount in every trade and may go into debt down to the limit, as in Dragulescu and Yakovenko. The system has the group traders, the interaction trades, and the variance of wealth variance.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

500
saving float

The saving propensity lambda, between 0 and 1, of the trades without a debt limit.

0.0
debt float | None

The debt limit of the fixed-amount trades, or None for trades of random shares with saving.

None
wealth float

The initial wealth of every agent, the mean wealth.

1.0
amount float

The amount paid in every fixed-amount trade.

0.1
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Raises:

Type Description
ValueError

Both a saving propensity and a debt limit are given, or the saving propensity is not below 1.

Examples:

>>> from skcomplex.systems.economics.econophysics import KineticWealthExchangeSystem
>>> type(KineticWealthExchangeSystem(10, debt=2.0).prepare().system_.interactions[0]).__name__
'DebtExchangeInteraction'
Source code in src/skcomplex/systems/economics/econophysics/_kinetic.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def __init__(
    self,
    n_agents: int = 500,
    *,
    saving: float = 0.0,
    debt: float | None = None,
    wealth: float = 1.0,
    amount: float = 0.1,
    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.saving = saving
    self.debt = debt
    self.wealth = wealth
    self.amount = amount

KineticWealthWelfareSystem(classes=9, *, cooperation=0.2, competition=0.3, eta=1.0, tax=0.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The kinetic theory of wealth classes.

A positive tax adds a welfare policy. The population is a distribution over wealth classes, a site group on a lattice of the classes. Encounters between classes move particles one class up or down, with cooperation narrowing the gaps and competition widening them, so the total density stays constant. When competition wins, wealth polarises toward the poorest and the richest classes, and the Gini coefficient grows. A welfare policy is an encounter with a group of fixed density, which moves the richest third of the classes down and the poorest third up and lowers the stationary Gini coefficient.

The system has the distribution wealth, the encounters exchange, and with a tax the group state and the policy welfare. Its standard observables are the density, the mean wealth, and the Gini coefficient of wealth.

Parameters:

Name Type Description Default
classes int

The number of wealth classes.

9
cooperation float

The probability of the move that narrows the gap between the classes of an encounter.

0.2
competition float

The probability of the move that widens it.

0.3
eta float

The encounter rate.

1.0
tax float

The rate of the welfare policy, 0 for none.

0.0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.economics.econophysics import KineticWealthWelfareSystem
>>> [item.label for item in KineticWealthWelfareSystem(tax=0.2).prepare().system_.interactions]
['exchange', 'welfare']
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def __init__(
    self,
    classes: int = 9,
    *,
    cooperation: float = 0.2,
    competition: float = 0.3,
    eta: float = 1.0,
    tax: float = 0.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.classes = classes
    self.cooperation = cooperation
    self.competition = competition
    self.eta = eta
    self.tax = tax

KolkataRestaurantSystem(n_agents=100, *, n_restaurants=None, strategy='random', random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Kolkata Paise Restaurant problem.

Diners spread over restaurants that serve one meal each. With random choice the expected utilization of N restaurants by N diners is 1 - 1/e, about 0.632, and with the stochastic crowd avoiding strategy it settles near 0.8. The system has the group diners, the choice choice of a restaurant every evening, uniform or by crowd avoidance, and the interaction restaurants, which reports the fraction of restaurants that serve a meal restaurants.utilization.

Parameters:

Name Type Description Default
n_agents int

The number of diners.

100
n_restaurants int | None

The number of restaurants, or None for as many as diners.

None
strategy str

'random' or 'crowd_avoiding'.

'random'
random_state int | Generator | None

The seed or generator of the first choices.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Raises:

Type Description
ValueError

The strategy is unknown.

Examples:

>>> from skcomplex.systems.economics.econophysics import KolkataRestaurantSystem
>>> type(KolkataRestaurantSystem(10, strategy='crowd_avoiding').prepare().system_.interactions[0]).__name__
'CrowdAvoidanceInteraction'
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def __init__(
    self,
    n_agents: int = 100,
    *,
    n_restaurants: int | None = None,
    strategy: str = 'random',
    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.n_restaurants = n_restaurants
    self.strategy = strategy
    self.random_state = random_state

MinorityGameInteraction(label, *, players, memory=3, phase=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
players Role

The path of the group of agents.

required
memory int

The memory m, the number of past winning sides the strategies read.

3
phase str | None

The phase the rounds run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import MinorityGameInteraction
>>> MinorityGameInteraction('game', players='players', memory=4).memory
4
Source code in src/skcomplex/systems/economics/econophysics/_minority.py
185
186
187
188
189
190
191
192
193
194
195
196
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

get_payoff(agent, system, option)

Return the virtual payoff of a strategy of an agent in the last round.

It is +1 if it played the winning side.

Parameters:

Name Type Description Default
agent MinorityPlayerView

The agent.

required
system SystemView

The system view of the rule that reads the payoff.

required
option int

The strategy, 0 for the first and 1 for the second.

required

Returns:

Name Type Description
payoff float

+1 when the strategy would have played the winning side, or -1.

Source code in src/skcomplex/systems/economics/econophysics/_minority.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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)

play(system)

Play one round, pay the agents, and update and report the history.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/econophysics/_minority.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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))

MinorityGameSystem(n_agents=101, *, memory=3, evolutionary=False, period=50, fraction=0.1, random_state=0, label='system', solver='auto', backend='auto')

Bases: 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.

Parameters:

Name Type Description Default
n_agents int

The number of agents, odd so that there is always a minority.

101
memory int

The memory m of the strategies, so alpha = 2^m / N.

3
evolutionary bool

Whether every period rounds the poorest agents take new random strategies.

False
period int

The number of rounds between two evolutions of the evolutionary version.

50
fraction float

The fraction of poorest agents that take new strategies at an evolution.

0.1
random_state int | Generator | None

The seed or generator of the strategies.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Raises:

Type Description
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
Source code in src/skcomplex/systems/economics/econophysics/_minority.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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

MinorityPlayerElement(label, *, first=0.0, second=1.0, first_score=0.0, second_score=0.0, strategy=0.0, action=0.0, wealth=0.0, size=None)

Bases: Element

Agent of the minority game, who holds two strategies and plays the one it chose.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
first Annotated[object, NN]

The code of the first strategy.

0.0
second Annotated[object, NN]

The code of the second strategy.

1.0
first_score object

The virtual score of the first strategy, the number of times it would have been in the minority.

0.0
second_score object

The virtual score of the second strategy.

0.0
strategy Annotated[object, FiniteEnumeratedSet([0, 1])]

The strategy played, 0 for the first and 1 for the second.

0.0
action Annotated[object, ZZ]

The last action, +1 or -1.

0.0
wealth object

The net number of times the agent was in the minority.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import MinorityPlayerElement
>>> MinorityPlayerElement('players', first=3, second=5, size=11).size
11
Source code in src/skcomplex/systems/economics/econophysics/_minority.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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

PatronElement(label, *, predictors=1, forecast=0.0, attends=0.0, capacity=60.0, size=None)

Bases: Element

Patron of the El Farol bar.

It forecasts the attendance with its most accurate predictor, by the rule of PredictingInteraction. Every patron holds a few predictors of the pool, the set bits of predictors. A choice then sends the patron to the bar when the forecast is below the capacity.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
predictors Annotated[object, NN]

The bit mask of the predictors of the pool that the patron holds.

1
forecast Annotated[object, closed_open(0, oo)]

The last forecast of the patron's most accurate predictor.

0.0
attends Annotated[object, FiniteEnumeratedSet([0, 1])]

Whether the patron went to the bar this week, 1 or 0.

0.0
capacity Annotated[object, closed_open(0, oo)]

The attendance above which the bar is too crowded to enjoy.

60.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import PatronElement
>>> PatronElement('patrons', predictors=7, size=100).size
100
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def __init__(
    self,
    label: str,
    *,
    predictors: Annotated[object, NN] = 1,
    forecast: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    attends: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
    capacity: Annotated[object, RealSet.closed_open(0, oo)] = 60.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.predictors = predictors
    self.forecast = forecast
    self.attends = attends
    self.capacity = capacity

PredictingInteraction(label, *, target, pool, phase='predict')

Bases: Interaction

Forecast of every patron of the El Farol bar with its most accurate predictor.

Every patron forecasts with the predictor of smallest error in the pool among those it holds.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of patrons.

required
pool Role

The path of the pool of predictors.

required
phase str | None

The phase the patrons predict in.

'predict'

Examples:

>>> from skcomplex.systems.economics.econophysics import PredictingInteraction
>>> PredictingInteraction('predicting', target='patrons', pool='pool').pool
'pool'
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
313
314
315
316
317
def __init__(self, label: str, *, target: Role, pool: Role, phase: str | None = 'predict') -> None:
    super().__init__(label)
    self.target = target
    self.pool = pool
    self.phase = phase

predict(agent, system)

Forecast the attendance with the most accurate predictor held.

Parameters:

Name Type Description Default
agent PatronView

The patron.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def predict(self, agent: PatronView, system: SystemView) -> None:
    """Forecast the attendance with the most accurate predictor held.

    Args:
        agent:
            The patron.

        system:
            The system.
    """
    pool = cast(list[PredictorPoolView], system.get_agents('pool'))[0]
    errors, predicted = np.ravel(pool.errors), np.ravel(pool.forecasts)
    mask = int(agent.predictors)
    held = [index for index in range(len(PREDICTORS)) if mask >> index & 1]
    agent.forecast = float(predicted[held[int(np.argmin(errors[held]))]])

PredictorPoolElement(label, *, forecasts=0.0, errors=0.0, size=None)

Bases: Element

Pool of Arthur's predictors that the patrons share.

It holds the forecast and the accuracy of every predictor. The accuracy of a predictor depends only on the history of attendance, the observable attendance of the run, so one member holds it for every patron. Every week ForecastingInteraction forecasts the attendance with every predictor, and a PayoffLearningInteraction moves the error of every predictor towards its last absolute error, a discounted mean of the errors.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
forecasts ArrayLike

The forecast of next week's attendance by every predictor of the pool.

0.0
errors ArrayLike

The discounted mean absolute error of every predictor of the pool.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import PredictorPoolElement
>>> PredictorPoolElement('pool', size=1).size
1
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
137
138
139
140
141
142
143
144
145
146
147
def __init__(
    self,
    label: str,
    *,
    forecasts: npt.ArrayLike = 0.0,
    errors: npt.ArrayLike = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.forecasts = forecasts
    self.errors = errors

RestaurantsInteraction(label, *, target, n_restaurants=100, by='restaurant', phase=None)

Bases: Interaction

Restaurants that each serve one meal every evening.

The meal goes to one of the diners who come, chosen at random. The diners are grouped by their restaurant. Every diner learns the crowd at its restaurant, and the first of the group in a random order is served. The interaction reports the fraction of restaurants that serve a meal.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of diners.

required
n_restaurants int

The number of restaurants.

100
by str

The state of the diners that holds their restaurant.

'restaurant'
phase str | None

The phase the restaurants serve in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import RestaurantsInteraction
>>> RestaurantsInteraction('restaurants', target='diners', n_restaurants=5).by
'restaurant'
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def __init__(
    self,
    label: str,
    *,
    target: Role,
    n_restaurants: int = 100,
    by: str = 'restaurant',
    phase: str | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.n_restaurants = n_restaurants
    self.by = by
    self.phase = phase

act_on(members, system)

Tell every diner of a restaurant its crowd and serve the first diner.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The diners at one restaurant, in random order.

required
system SystemViewProtocol

The system view of the restaurants.

required
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def act_on(self, members: list[AgentViewProtocol], system: SystemViewProtocol) -> None:
    """Tell every diner of a restaurant its crowd and serve the first diner.

    Args:
        members:
            The diners at one restaurant, in random order.

        system:
            The system view of the restaurants.
    """
    diners = [member for member in members if isinstance(member, DinerView)]
    for position, member in enumerate(diners):
        member.crowd = float(len(diners))
        member.served = float(position == 0)

report(system)

Report the fraction of restaurants with at least one diner.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the restaurants.

required
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
254
255
256
257
258
259
260
261
262
def report(self, system: SystemViewProtocol) -> None:
    """Report the fraction of restaurants with at least one diner.

    Args:
        system:
            The system view of the restaurants.
    """
    visited = {float(getattr(agent, self.by)) for agent in system.get_agents('target')}
    system.report('utilization', len(visited) / self.n_restaurants)

serve(system)

Group the diners by their restaurant and serve every restaurant, in random order.

The diners of a restaurant come in a random order, and the restaurants are visited in a random order.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the restaurants.

required
Source code in src/skcomplex/systems/economics/econophysics/_kolkata.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def serve(self, system: SystemViewProtocol) -> None:
    """Group the diners by their restaurant and serve every restaurant, in random order.

    The diners of a restaurant come in a random order, and the restaurants are visited in a random order.

    Args:
        system:
            The system view of the restaurants.
    """
    shared: dict[float, list[AgentViewProtocol]] = {}
    for agent in system.get_agents('target'):
        if agent.alive:
            shared.setdefault(float(getattr(agent, self.by)), []).append(agent)
    groups = []
    for value in sorted(shared):
        members = shared[value]
        groups.append([members[int(index)] for index in system.rng.permutation(len(members))])
    for index in system.rng.permutation(len(groups)):
        self.act_on(groups[int(index)], system)

SavingExchangeInteraction(label, *, target, saving=0.0, phase=None)

Bases: Interaction

Random pairwise trades of Chakraborti and Chakrabarti.

Every agent saves a fraction of its wealth. A trade between agents i and j keeps total wealth and gives w_i' = lambda w_i + eps (1 - lambda) (w_i + w_j) and w_j' = lambda w_j + (1 - eps) (1 - lambda) (w_i + w_j) with eps uniform on [0, 1], so i transfers (1 - lambda) (w_i - eps (w_i + w_j)) to j, an amount of either sign. Every step, every agent trades once with another agent drawn at random, in random order. Without saving the stationary wealth distribution is exponential, and with saving propensity lambda it is close to a Gamma distribution of shape n = 1 + 3 lambda / (1 - lambda).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of traders.

required
saving Annotated[float, closed_open(0, oo)]

The saving propensity lambda, the fraction of its wealth that an agent keeps out of a trade.

0.0
phase str | None

The phase the trades run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import SavingExchangeInteraction
>>> SavingExchangeInteraction('trades', target='traders').saving
0.0
Source code in src/skcomplex/systems/economics/econophysics/_kinetic.py
170
171
172
173
174
175
176
177
178
179
180
181
def __init__(
    self,
    label: str,
    *,
    target: Role,
    saving: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
    phase: str | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.saving = saving
    self.phase = phase

trade(system)

Let every trader trade a random share of the pooled wealth with a random trader, in random order.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the trades.

required
Source code in src/skcomplex/systems/economics/econophysics/_kinetic.py
193
194
195
196
197
198
199
200
201
202
203
204
205
def trade(self, system: SystemViewProtocol) -> None:
    """Let every trader trade a random share of the pooled wealth with a random trader, in random order.

    Args:
        system:
            The system view of the trades.
    """
    traders = system.get_agents('target')
    found = cast(Pairs, list(pairs(traders, traders, system.rng, PartnerSpec('all', 'uniform'))))
    for index in system.rng.permutation(len(found)):
        first, second = found[int(index)]
        if first.alive and second.alive:
            transfer(first, second, self._get_amount(first, second, system), 'wealth')

SavingTraderElement(label, *, wealth=1.0, size=None)

Bases: Element

Agent of the kinetic wealth exchange systems.

Its wealth changes only in pairwise trades.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
wealth float

The initial wealth, negative down to the debt limit.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import SavingTraderElement
>>> group = SavingTraderElement('traders', wealth=2.0, size=10)
>>> group.label, group.size
('traders', 10)
Source code in src/skcomplex/systems/economics/econophysics/_kinetic.py
62
63
64
def __init__(self, label: str, *, wealth: float = 1.0, size: int | None = None) -> None:
    super().__init__(label, size=size)
    self.wealth = wealth

TraderElement(label, *, wealth=1.0, size=None)

Bases: Element

Agent of the Boltzmann wealth system.

Its wealth in whole units changes only by gifts of one unit.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
wealth Annotated[object, NN]

The initial wealth.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.econophysics import TraderElement
>>> group = TraderElement('traders', size=100)
>>> group.label, group.size
('traders', 100)
Source code in src/skcomplex/systems/economics/econophysics/_exchange.py
50
51
52
53
54
55
56
57
58
def __init__(
    self,
    label: str,
    *,
    wealth: Annotated[object, NN] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.wealth = wealth

WealthDensityElement(label, *, x=0.0, size=None, space=None)

Bases: NonnegativeElement

Value x of the density of agents at one wealth class.

A wealth distribution is this element on a lattice of wealth classes, with one value per class, and the exchanges and the welfare policy change it. The element has no laws of its own.

Parameters:

Name Type Description Default
label str

The label of the element, unique among the components of its system.

required
x Annotated[object, closed_open(0, oo)]

The initial density, a nonnegative number.

0.0
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The space with one member per site, such as a lattice of classes, or None for none.

None

Examples:

>>> from skcomplex.core.components.spaces import LatticeSpace
>>> from skcomplex.systems.economics.econophysics import WealthDensityElement
>>> classes = LatticeSpace(5, boundary='fixed')
>>> WealthDensityElement('wealth', x=[0.2] * 5, space=classes).x
[0.2, 0.2, 0.2, 0.2, 0.2]
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
59
60
61
62
63
64
65
66
67
def __init__(
    self,
    label: str,
    *,
    x: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, x=x, size=size, space=space)

WealthExchangeInteraction(label, *, candidate, field, classes=9, eta=1.0, cooperation=0.2, competition=0.3)

Bases: EncounterInteraction

Conservative encounters between wealth classes.

They include cooperation and competition. A candidate of class h meets a field particle of class k at the rate eta and moves by the transition table of exchange_table.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
candidate str

The path of the distribution over wealth classes whose particles move.

required
field str

The path of the distribution over wealth classes they meet, the candidate again.

required
classes Annotated[int, open(0, oo)]

The number of wealth classes.

9
eta Annotated[float, closed_open(0, oo)]

The encounter rate.

1.0
cooperation Annotated[float, closed_open(0, oo)]

The probability of the move that narrows the gap between the classes of an encounter.

0.2
competition Annotated[float, closed_open(0, oo)]

The probability of the move that widens it.

0.3

Examples:

>>> from skcomplex.systems.economics.econophysics import WealthExchangeInteraction
>>> WealthExchangeInteraction('exchange', candidate='wealth', field='wealth').competition
0.3
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def __init__(
    self,
    label: str,
    *,
    candidate: str,
    field: str,
    classes: Annotated[int, RealSet.open(0, oo)] = 9,
    eta: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    cooperation: Annotated[float, RealSet.closed_open(0, oo)] = 0.2,
    competition: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
) -> None:
    super().__init__(label, candidate=candidate, field=field, rate=self._get_rate, kernel=self._get_kernel)
    self.classes = classes
    self.eta = eta
    self.cooperation = cooperation
    self.competition = competition

WelfarePolicyInteraction(label, *, candidate, field, classes=9, tax=0.1)

Bases: EncounterInteraction

Welfare policy that taxes the richest classes and helps the poorest.

It is a micro-scale external action. The policy is an encounter whose field role binds a group with a fixed density, so it acts on the transitions of the population at the rate tax times that density, by the pattern and the table of policy_table.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
candidate str

The path of the distribution over wealth classes.

required
field str

The path of the group of one member whose fixed density is the strength of the policy.

required
classes Annotated[int, open(0, oo)]

The number of wealth classes.

9
tax Annotated[float, closed_open(0, oo)]

The rate at which the policy moves the richest classes down and the poorest up.

0.1

Examples:

>>> from skcomplex.systems.economics.econophysics import WelfarePolicyInteraction
>>> WelfarePolicyInteraction('welfare', candidate='wealth', field='state').tax
0.1
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
233
234
235
236
237
238
239
240
241
242
243
244
def __init__(
    self,
    label: str,
    *,
    candidate: str,
    field: str,
    classes: Annotated[int, RealSet.open(0, oo)] = 9,
    tax: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
) -> None:
    super().__init__(label, candidate=candidate, field=field, rate=self._get_rate, kernel=self._get_kernel)
    self.classes = classes
    self.tax = tax

exchange_table(classes, cooperation, competition)

Return the transition table of encounters between wealth classes, A[h, k, i].

A candidate of class h that meets a richer field particle moves one class up with probability cooperation and one class down with probability competition. One that meets a poorer field particle moves one class up with probability competition and one class down with probability cooperation. So competition makes the rich richer and the poor poorer, and cooperation does the opposite. A move past the poorest or the richest class is not made.

Parameters:

Name Type Description Default
classes int

The number of wealth classes.

required
cooperation object

The probability of the move that narrows the gap between the two classes, a number or a parameter.

required
competition object

The probability of the move that widens it, a number or a parameter.

required

Returns:

Name Type Description
table NDArray[object_]

The transition probabilities, which sum to one over the outcomes.

Examples:

>>> from skcomplex.systems.economics.econophysics import exchange_table
>>> exchange_table(3, 0.2, 0.3)[0, 2].astype(float).tolist()
[0.8, 0.2, 0.0]
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def exchange_table(classes: int, cooperation: object, competition: object) -> npt.NDArray[np.object_]:
    """Return the transition table of encounters between wealth classes, `A[h, k, i]`.

    A candidate of class `h` that meets a richer field particle moves one class up with probability `cooperation`
    and one class down with probability `competition`. One that meets a poorer field particle moves one class up with
    probability `competition` and one class down with probability `cooperation`. So competition makes the rich richer
    and the poor poorer, and cooperation does the opposite. A move past the poorest or the richest class is not made.

    Args:
        classes:
            The number of wealth classes.

        cooperation:
            The probability of the move that narrows the gap between the two classes, a number or a parameter.

        competition:
            The probability of the move that widens it, a number or a parameter.

    Returns:
        table:
            The transition probabilities, which sum to one over the outcomes.

    Examples:
        >>> from skcomplex.systems.economics.econophysics import exchange_table
        >>> exchange_table(3, 0.2, 0.3)[0, 2].astype(float).tolist()
        [0.8, 0.2, 0.0]
    """
    table = np.zeros((classes, classes, classes), dtype=object)
    for candidate in range(classes):
        for field in range(classes):
            gap = int(np.sign(field - candidate))
            moves = {candidate + gap: cooperation, candidate - gap: competition} if gap else {}
            for outcome, probability in moves.items():
                if 0 <= outcome < classes:
                    table[candidate, field, outcome] += probability
            table[candidate, field, candidate] += 1.0 - table[candidate, field].sum()
    return table

forecasts(history)

Return the forecast of next week's attendance of every predictor of the pool.

It lies between 0 and 100.

Parameters:

Name Type Description Default
history ArrayLike

The past attendances, the last one last, at least ten of them.

required

Returns:

Name Type Description
forecasts Array

One forecast per predictor of the pool.

Examples:

>>> from skcomplex.systems.economics.econophysics import forecasts
>>> forecasts([60.0] * 10)[:3].tolist()
[60.0, 60.0, 60.0]
Source code in src/skcomplex/systems/economics/econophysics/_el_farol.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def forecasts(history: npt.ArrayLike) -> Array:
    """Return the forecast of next week's attendance of every predictor of the pool.

    It lies between 0 and 100.

    Args:
        history:
            The past attendances, the last one last, at least ten of them.

    Returns:
        forecasts:
            One forecast per predictor of the pool.

    Examples:
        >>> from skcomplex.systems.economics.econophysics import forecasts
        >>> forecasts([60.0] * 10)[:3].tolist()
        [60.0, 60.0, 60.0]
    """
    values = np.asarray(history, dtype=float)
    predicted = [function(values, **arguments) for function, arguments in PREDICTORS]
    return np.clip(predicted, 0.0, MAX_ATTENDANCE)

gini_coefficient(s, wealth)

Return the Gini coefficient of a distribution over wealth classes.

Every member of its group reads it. The coefficient is sum_ij f_i f_j |w_i - w_j| / (2 F M), with the density F and the total wealth M.

Parameters:

Name Type Description Default
s SimpleNamespace

The namespace of one member of the distribution.

required
wealth NDArray[float64]

The wealth of every class.

required

Returns:

Name Type Description
gini Expression

The coefficient as an expression of reductions.

Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def gini_coefficient(s: SimpleNamespace, wealth: npt.NDArray[np.float64]) -> Expression:
    """Return the Gini coefficient of a distribution over wealth classes.

    Every member of its group reads it. The coefficient is `sum_ij f_i f_j |w_i - w_j| / (2 F M)`, with the density `F`
    and the total wealth `M`.

    Args:
        s:
            The namespace of one member of the distribution.

        wealth:
            The wealth of every class.

    Returns:
        gini:
            The coefficient as an expression of reductions.
    """
    spread = total(s.x, weights=np.abs(wealth[:, None] - wealth[None, :]))
    return total(s.x * spread) / (2 * moment(s.x, 0, wealth) * moment(s.x, 1, wealth))

mean_wealth(s, wealth)

Return the mean wealth of a distribution over wealth classes.

Parameters:

Name Type Description Default
s SimpleNamespace

The namespace of one member of the distribution.

required
wealth NDArray[float64]

The wealth of every class.

required

Returns:

Name Type Description
mean Expression

The normalized first moment.

Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def mean_wealth(s: SimpleNamespace, wealth: npt.NDArray[np.float64]) -> Expression:
    """Return the mean wealth of a distribution over wealth classes.

    Args:
        s:
            The namespace of one member of the distribution.

        wealth:
            The wealth of every class.

    Returns:
        mean:
            The normalized first moment.
    """
    return moment(s.x, 1, wealth, normalized=True)

policy_table(classes)

Return the rate pattern and the transition table of a welfare policy.

The policy taxes the rich and helps the poor. The policy moves a candidate of the richest third of the classes one class down, and a candidate of the poorest third one class up, and leaves the middle classes alone.

Parameters:

Name Type Description Default
classes int

The number of wealth classes.

required

Returns:

Name Type Description
pattern NDArray[float64]

The rate pattern eta[h, 0], 1 for the classes the policy acts on and 0 for the others.

table NDArray[float64]

The transition table A[h, 0, i] of the policy.

Examples:

>>> from skcomplex.systems.economics.econophysics import policy_table
>>> policy_table(3)[0].ravel().tolist()
[1.0, 0.0, 1.0]
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def policy_table(classes: int) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Return the rate pattern and the transition table of a welfare policy.

    The policy taxes the rich and helps the poor. The policy moves a candidate of the richest third of the classes one
    class down, and a candidate of the poorest third one class up, and leaves the middle classes alone.

    Args:
        classes:
            The number of wealth classes.

    Returns:
        pattern:
            The rate pattern `eta[h, 0]`, 1 for the classes the policy acts on and 0 for the others.

        table:
            The transition table `A[h, 0, i]` of the policy.

    Examples:
        >>> from skcomplex.systems.economics.econophysics import policy_table
        >>> policy_table(3)[0].ravel().tolist()
        [1.0, 0.0, 1.0]
    """
    pattern = np.zeros((classes, 1))
    table = np.zeros((classes, 1, classes))
    third = max(1, classes // 3)
    for candidate in range(classes):
        outcome = candidate + 1 if candidate < third else candidate - 1 if candidate >= classes - third else candidate
        pattern[candidate, 0] = float(outcome != candidate)
        table[candidate, 0, outcome] = 1.0
    return pattern, table

strategy_table(code, memory)

Return the table of a minority game strategy.

It holds the bit the strategy plays after each of the 2^m histories. A table has 2^m bits, too many to store as one number beyond small memories, so a strategy is stored as the integer code that seeds a generator of its table.

Parameters:

Name Type Description Default
code float

The integer code of the strategy.

required
memory int

The memory m, the number of past outcomes the strategy reads.

required

Returns:

Name Type Description
table IntArray

The bit of the strategy for every history, from 0 to 2^m - 1.

Examples:

>>> from skcomplex.systems.economics.econophysics import strategy_table
>>> strategy_table(7, 2).shape
(4,)
Source code in src/skcomplex/systems/economics/econophysics/_minority.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def strategy_table(code: float, memory: int) -> IntArray:
    """Return the table of a minority game strategy.

    It holds the bit the strategy plays after each of the `2^m` histories. A table has `2^m` bits, too many to store as
    one number beyond small memories, so a strategy is stored as the integer code that seeds a generator of its table.

    Args:
        code:
            The integer code of the strategy.

        memory:
            The memory `m`, the number of past outcomes the strategy reads.

    Returns:
        table:
            The bit of the strategy for every history, from 0 to `2^m - 1`.

    Examples:
        >>> from skcomplex.systems.economics.econophysics import strategy_table
        >>> strategy_table(7, 2).shape
        (4,)
    """
    return np.random.default_rng(int(code)).integers(0, 2, 2**memory)

wealth_classes(classes)

Return the wealth of every class.

The wealth is evenly spaced from 0 for the poorest to 1 for the richest.

Parameters:

Name Type Description Default
classes int

The number of wealth classes.

required

Returns:

Name Type Description
wealth NDArray[float64]

The wealth of every class.

Examples:

>>> from skcomplex.systems.economics.econophysics import wealth_classes
>>> wealth_classes(3).tolist()
[0.0, 0.5, 1.0]
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def wealth_classes(classes: int) -> npt.NDArray[np.float64]:
    """Return the wealth of every class.

    The wealth is evenly spaced from 0 for the poorest to 1 for the richest.

    Args:
        classes:
            The number of wealth classes.

    Returns:
        wealth:
            The wealth of every class.

    Examples:
        >>> from skcomplex.systems.economics.econophysics import wealth_classes
        >>> wealth_classes(3).tolist()
        [0.0, 0.5, 1.0]
    """
    return np.linspace(0.0, 1.0, classes)

wealth_density(s, wealth)

Return the density of a distribution over wealth classes, its order-0 moment.

Parameters:

Name Type Description Default
s SimpleNamespace

The namespace of one member of the distribution.

required
wealth NDArray[float64]

The wealth of every class.

required

Returns:

Name Type Description
density Expression

The order-0 moment.

Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def wealth_density(s: SimpleNamespace, wealth: npt.NDArray[np.float64]) -> Expression:
    """Return the density of a distribution over wealth classes, its order-0 moment.

    Args:
        s:
            The namespace of one member of the distribution.

        wealth:
            The wealth of every class.

    Returns:
        density:
            The order-0 moment.
    """
    return moment(s.x, 0, wealth)

wealth_observables(classes)

Return the density, the mean wealth, and the Gini coefficient of a distribution.

The distribution is wealth, over wealth classes.

Parameters:

Name Type Description Default
classes int

The number of wealth classes.

required

Returns:

Name Type Description
observables list[Observable]

The observables, each reading the moments of the distribution.

Examples:

>>> from skcomplex.systems.economics.econophysics import wealth_observables
>>> [item.label for item in wealth_observables(9)]
['density', 'mean_wealth', 'gini']
Source code in src/skcomplex/systems/economics/econophysics/_welfare.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def wealth_observables(classes: int) -> list[Observable]:
    """Return the density, the mean wealth, and the Gini coefficient of a distribution.

    The distribution is `wealth`, over wealth classes.

    Args:
        classes:
            The number of wealth classes.

    Returns:
        observables:
            The observables, each reading the moments of the distribution.

    Examples:
        >>> from skcomplex.systems.economics.econophysics import wealth_observables
        >>> [item.label for item in wealth_observables(9)]
        ['density', 'mean_wealth', 'gini']
    """
    wealth = wealth_classes(classes)
    return [
        Observable('density', partial(wealth_density, wealth=wealth), group='wealth'),
        Observable('mean_wealth', partial(mean_wealth, wealth=wealth), group='wealth'),
        Observable('gini', partial(gini_coefficient, wealth=wealth), group='wealth'),
    ]