Multilevel selection of cooperators, defectors, and punishers on the simplex
The density of groups of cooperators, defectors, and altruistic punishers.
- Class:
TrimorphicMultilevelSelectionSystem - Import:
from skcomplex.systems.social.cooperation import TrimorphicMultilevelSelectionSystem - Field:
social/cooperation - Topics:
field,multilevel selection,punishment,simplex,integral operator,pde - References:
- Cooney 2024
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.social.cooperation import TrimorphicMultilevelSelectionSystem
trajectory = TrimorphicMultilevelSelectionSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
cells |
30 |
victory |
'defectors' |
group_strength |
4.0 |
benefit |
3.0 |
cost |
1.0 |
punishment |
0.5 |
interaction_cost |
0.1 |
fixed_cost |
0.0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | phase space |
| Laws | rate |
| Randomness | unknown |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class TrimorphicMultilevelSelectionSystem(BaseSystem):
"""The density of groups of cooperators, defectors, and altruistic punishers.
It lives on the 2-simplex. The density `f(x, y)` of groups with fractions `x` of cooperators, `y` of defectors, and
`1 - x - y` of punishers lives on the 2-simplex. The replicator dynamics within groups advect it, and groups win
pairwise conflicts at the rate `group_strength f(x, y) int (rho(x, y; u, v) - rho(u, v; x, y)) f(u, v) du dv` over
the simplex. The victory probability is `1/2 + (v - y) / 2` of the fraction of non-defectors (`'defectors'`), or the
difference of the average payoffs normalized by their largest difference on the simplex (`'payoff'`) (Cooney 2024,
arXiv 2405.18419 §3.2 and §7). The density starts uniform at two, so its integral is one, the cells along the
slanted face are half cells, and no flux leaves the simplex.
The system has the density `groups.x`.
Args:
cells:
The number of cells of each axis of the simplex.
victory:
The victory probability, `'defectors'` or `'payoff'`.
group_strength:
The relative strength `lambda` of between-group conflict.
benefit:
The benefit `b` of the donation game.
cost:
The cost `c` of cooperating.
punishment:
The punishment `p` of a defector by every punisher it meets.
interaction_cost:
The cost `k` a punisher pays per defector it meets.
fixed_cost:
The fixed cost `q` of being able to punish.
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:
ValidationError:
The victory probability is unknown.
Examples:
>>> from skcomplex.systems.social.cooperation import TrimorphicMultilevelSelectionSystem
>>> TrimorphicMultilevelSelectionSystem(10).prepare().system_.elements[0].x.size
100
"""
field = 'social/cooperation'
topics = ('field', 'multilevel selection', 'punishment', 'simplex', 'integral operator', 'pde')
references = REFERENCES
until = 30.0
dt = 1.0
@staticmethod
def _get_trimorphic_payoff(x: Fraction, y: Fraction, payoffs: tuple[float, ...]) -> Fraction:
"""Return the average payoff `G(x, y)` of a group of three kinds.
The kinds are cooperators `x`, defectors `y`, and punishers, and the payoff follows equation 2.5.
"""
benefit, cost, punishment, interaction, fixed = payoffs
strength = punishment + interaction
return (
benefit
- cost
- fixed
+ fixed * x
- (benefit - cost - fixed + strength) * y
+ strength * x * y
+ strength * y**2
)
@staticmethod
def _get_payoff_range(payoffs: tuple[float, ...]) -> float:
"""Return the largest difference `G* - G_*` of the average payoffs of two groups.
The groups lie on the simplex.
"""
grid = np.linspace(0.0, 1.0, SIMPLEX_SAMPLES)
x, y = np.meshgrid(grid, grid, indexing='ij')
values = np.asarray(TrimorphicMultilevelSelectionSystem._get_trimorphic_payoff(x, y, payoffs))[x + y <= 1]
return float(values.max() - values.min())
def __init__(
self,
cells: int = 30,
*,
victory: str = 'defectors',
group_strength: float = 4.0,
benefit: float = 3.0,
cost: float = 1.0,
punishment: float = 0.5,
interaction_cost: float = 0.1,
fixed_cost: float = 0.0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.cells = cells
self.victory = victory
self.group_strength = group_strength
self.benefit = benefit
self.cost = cost
self.punishment = punishment
self.interaction_cost = interaction_cost
self.fixed_cost = fixed_cost
@staticmethod
def _get_trimorphic_victory_gain(victory: str, payoffs: tuple[float, ...]) -> Expression:
"""Return `rho(x, y; u, v) - rho(u, v; x, y)` of the victory of a group.
The victory is over another group on the simplex.
"""
x, y = coordinate('x'), coordinate('y')
u, v = integration_variable('x'), integration_variable('y')
if victory == 'defectors':
return v - y
own, other = TrimorphicMultilevelSelectionSystem._get_trimorphic_payoff(
x,
y,
payoffs,
), TrimorphicMultilevelSelectionSystem._get_trimorphic_payoff(u, v, payoffs)
return (own - other) / TrimorphicMultilevelSelectionSystem._get_payoff_range(payoffs)
@staticmethod
def _get_simplex_drift(payoffs: tuple[float, ...]) -> list[Expression]:
"""Return the replicator dynamics of cooperators and defectors in a group.
It follows equation E.20.
"""
_, cost, punishment, interaction, fixed = payoffs
x, y = coordinate('x'), coordinate('y')
punished = fixed + interaction * y
exploited = cost + fixed - punishment + punishment * x + (punishment + interaction) * y
return [0, x * ((1 - x) * punished - y * exploited), y * ((1 - y) * exploited - x * punished)]
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components built from the model parameters."""
super()._prepare(context)
NonlinearPairwiseGroupConflictSystem._check_victory(self.victory, TRIMORPHIC_VICTORIES)
payoffs = (self.benefit, self.cost, self.punishment, self.interaction_cost, self.fixed_cost)
gain = self._get_trimorphic_victory_gain(self.victory, payoffs)
axes = [AxisSpec('x', self.cells, 0.0, 1.0), AxisSpec('y', self.cells, 0.0, 1.0)]
position = LatticeSpace((1,), discretization='finite-volume', scheme=FiniteVolumeSpec(limiter=None))
space = SimplexSpace(position, axes)
groups = GroupDensityElement('groups', x=2.0 * (space.prepare().volumes_ > 0), space=space)
drift = self._get_simplex_drift(payoffs)
within = SelectionDriftInteraction('within', target='groups', state='x', drift=lambda _: drift)
between = Interaction(
'between',
roles={'target': 'groups'},
laws=lambda s: [
RateLaw(
s.target.x,
self.group_strength * s.target.x * integral_transform(s.target.x, gain, ('x', 'y')),
),
],
)
self.system_ = System(self.label, elements=[groups], interactions=[within, between], solver=RK4Solver(dt=0.01))
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
GroupDensityElement, fromElement, through the shared recipeNonnegativeElement
Interactions:
SelectionDriftInteraction, fromInteractionInteraction
class GroupDensityElement(ActivityDensityElement):
"""Density of groups over their strategy fractions, drawn as a simplex."""
visual = VisualSpec('image', {'slices': {0: 0}})
class SelectionDriftInteraction(Interaction):
"""Selection drift `du/dt + divergence(a u) = source(ns)` of a density `u` over a trait.
Evolutionary game theory names it the selection within groups, the drift of a density of traits by selection.
The drift field is `a(ns)`. The flux of the conservation law is the drift times the state, written in conservative
form, so the total of the state on a periodic field stays constant and, on a spectral field, the dealiasing of
products applies to it. The drift is one expression for a field of one dimension, or one per dimension, of the
states and parameters of the field, and may read other states than the one it carries, such as the flow of a fluid
derived from a streamfunction, or the drift of a probability density in a Fokker-Planck equation. Its laws are
`RateLaw(u, -divergence(flux))` and, with a source, `RateLaw(u, source)`.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the field whose state is carried.
state:
The name of the carried state of the field.
drift:
A function of the namespace that returns the drift, or one drift per dimension.
source:
A function of the namespace that returns the source, or `None` for none.
Raises:
ValidationError:
The state is not a name, or a function is not callable.
Examples:
>>> import numpy as np
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.components.spaces import LatticeSpace
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.social.cooperation import SelectionDriftInteraction
>>> space = LatticeSpace((50,), spacing=0.1, boundary='periodic', discretization='finite-volume')
>>> values = {'u': np.exp(-((np.arange(50) - 25) / 5.0) ** 2)}
>>> drift = SelectionDriftInteraction('drift', target='tracer', state='u', drift=lambda s: 1.0)
>>> system = System(elements=[Element('tracer', values=values, space=space)], interactions=[drift])
>>> trajectory = system.prepare().simulate(until=1.0, dt=0.01)
>>> total = trajectory.get_values('tracer.u')[-1].sum()
>>> round(float(total), 6) == round(float(values['u'].sum()), 6)
True
"""
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'u',
drift: Callable[[SimpleNamespace], object] | None = None,
source: Callable[[SimpleNamespace], object] | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.drift = drift
self.source = source
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The state is not a name, or the drift or the source is not callable.
"""
super()._check_arguments()
if not isinstance(self.state, str):
error_msg = f'The state of {self.label!r} is {self.state!r}. Give the name of a state of the field.'
raise ValidationError(error_msg)
if not callable(self.drift) or (self.source is not None and not callable(self.source)):
error_msg = f'The drift and the source of {self.label!r} are functions of the namespace.'
raise ValidationError(error_msg)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rate of the divergence of the flux and of the source, after checking the functions.
Args:
context:
The namespace of the field.
"""
super()._prepare(context)
state = getattr(context.target, self.state)
flux = self._get_flux(context)
components = list(flux) if isinstance(flux, list) else [flux]
self.laws_ = [RateLaw(state, -divergence(components))]
if self.source is not None:
self.laws_.append(RateLaw(state, self.source(context)))
def _get_flux(self, namespace: SimpleNamespace) -> object:
"""Return the flux `a u`, one component per component of the drift.
Args:
namespace:
The namespace of the symbols the flux can use, with the namespace of the field.
Returns:
flux:
The flux, one expression or one per dimension.
"""
state = getattr(namespace.target, self.state)
drift = self.drift(namespace) if callable(self.drift) else None
if isinstance(drift, FreeModuleElement | list | tuple):
return [SR(component) * state for component in drift]
return SR(drift) * state
class Interaction(BaseInteraction):
"""An interaction whose laws run once for the elements its roles bind.
It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
`Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
populations, a reaction between two chemicals, and an infection along the contacts of a network.
Read more in the user guide, under Interactions.
Args:
label:
The name of the interaction, unique among the components of its system, such as `'predation'`.
roles:
The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
without a class, or `None`.
laws:
The function of the namespace that returns the laws of a rule written without a class, such as
`lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
`None`.
among:
The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.
along:
`True` for the edges of the network the group lives on, the name of a layer of a network with several, such
as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
`RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.
within:
A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
force `-dV/dx` on its position `x`.
See Also:
BaseInteraction: The base of every interaction.
RandomPartition: Groups the members of a group at random at every step.
TrainingInteraction: Trains the parameters of a nested system.
Examples:
>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
>>> birth.roles
{'target': 'fish'}
"""
def __init__(
self,
label: str,
*,
roles: Mapping[str, object] | None = None,
laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
among: str | None = None,
along: bool | str | tuple[str, int] | RandomPartition | None = None,
within: RadiusNeighborhood | None = None,
) -> None:
super().__init__(label)
self.roles = roles
self.laws = laws
self.among = among
self.along = along
self.within = within
def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
"""Return the numeric arguments as parameters, and `roles` and `among` as roles.
With `within`, `among` binds both members of a pair, `first` and `second`.
"""
declared = dict(super()._get_declared())
for name, binding in (self.roles or {}).items():
declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
if self.among is not None and self.within is not None:
for name in PAIR_ROLES:
declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
return declared
@classmethod
def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
"""Return the arguments that name the states a role reads.
The mapping `roles` of bindings names none.
"""
return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')
def _get_binding(self, role: str) -> object:
"""Return what a role binds, from `roles` or from the argument of its name.
Args:
role:
The name of the role.
Returns:
binding:
The label, labels, or entries the role binds, or `None` when it binds nothing.
"""
if self.roles is not None and role in self.roles:
return self.roles[role]
if self.among is not None and self.within is not None and role in PAIR_ROLES:
return self.among
return super()._get_binding(role)
def _check_arguments(self) -> None:
"""Raise an error for roles, laws, or groups the interaction cannot take.
Raises:
ValidationError:
A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
`along` names hyperedges of fewer than two members.
"""
clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
if clashes:
error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
raise ValidationError(error_msg)
if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
error_msg = (
f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
'`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
)
raise ValidationError(error_msg)
if isinstance(self.along, tuple) and not self._is_sized(self.along):
error_msg = (
f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
"more, such as `along=('hyperedges', 3)`."
)
raise ValidationError(error_msg)
if isinstance(self.along, RandomPartition):
self.along._check()
grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
if grouped and self.among is None:
error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
raise ValidationError(error_msg)
super()._check_arguments()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of `laws` for a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
if self.laws is not None:
self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)
@staticmethod
def _is_sized(along: tuple[object, ...]) -> bool:
"""Return whether `along` names hyperedges of a whole size of at least two."""
if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
return False
size = along[1]
return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE
def _get_draws(self) -> bool:
"""Return whether the interaction draws, as it does along random groups."""
return super()._get_draws() or isinstance(self.along, RandomPartition)
def _runs_on_edges(self) -> bool:
"""Return whether the interaction runs along edges."""
grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
return self.along is not None and self.along is not False and not grouped
def _runs_on_hyperedges(self) -> bool:
"""Return whether the interaction runs along the hyperedges of a network."""
return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)
def _get_hyperedge_size(self) -> int | None:
"""Return the size `along` gives the hyperedges, or `None` for every size."""
return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None
def _get_within(self) -> RadiusNeighborhood | None:
"""Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
return self.within
def _get_layer(self) -> str | None:
"""Return the layer `along` names, or `None` for no layer."""
if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
return None
return self.along
def _get_grouping(self) -> tuple[str, int, str] | None:
"""Return the kind, size, and reduction of the groups `along` names, or `None`."""
if isinstance(self.along, RandomPartition):
return ('partition', self.along.size, 'sum')
if self.along == NEIGHBORHOODS:
return ('neighborhood', 0, 'sum')
return None