Skip to content

Customers choosing between two shops of perishable goods

Customers who choose between two shops of perishable goods.

  • Class: PerishableGoodsDuopolySystem
  • Import: from skcomplex.systems.economics.markets import PerishableGoodsDuopolySystem
  • Field: economics/markets
  • Topics: agents, discrete choice, symmetry breaking, phase transition, retail
  • References:
    • Bertin 2021
    • Bouchaud 2013

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.economics.markets import PerishableGoodsDuopolySystem

trajectory = PerishableGoodsDuopolySystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
customers 200
stock 0.5
T 0.1
alpha 0.9
tau_a 1.0
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space network
Laws update
Randomness stochastic
Domains boolean, integer, real
Structure variable membership

Class

The source of the class shows how it builds its components from its model parameters.

class PerishableGoodsDuopolySystem(BaseSystem):
    """Customers who choose between two shops of perishable goods.

    They prefer the one that sold fresher goods. Each shop holds `stock` products per customer, and every sale replaces
    a product with a fresh one, so the shop with more customers sells fresher goods and attracts more customers. With
    the control parameter `R = 2 stock / tau_a`, the symmetric state `m = p_1 - p_2 = 0` loses its stability below the
    temperature `T_c = R / (1 + R)^2`, and one shop takes most customers. The transition is continuous for
    `R > sqrt(3) - 1` and discontinuous below. One unit of time is `N` visits by customers drawn with replacement. A
    visited customer chooses a shop with the probability `1 / (1 + exp(-(S_1 - S_2) / T))` for the first one, moves to
    it, buys a random product of age `tau`, of freshness `h = exp(-tau / tau_a)`, which the shop replaces with a fresh
    one, and updates its satisfaction with that shop alone to `alpha S + (1 - alpha) h`. The shops are the two nodes of
    a network on which their products stand.

    The system has the groups `customers` and `products`, and the asymmetry `m` of the probabilities of visiting the two
    shops.

    Args:
        customers:
            The number of customers `N`.

        stock:
            The number of products of each shop per customer.

        T:
            The temperature of the choice, the randomness of the customers.

        alpha:
            The memory of the satisfaction, between 0 and 1.

        tau_a:
            The time over which the products age.

        random_state:
            The seed or generator of the initial satisfactions, which scatter by 0.01 around 0.5.

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

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

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

    Examples:
        >>> from skcomplex.systems.economics.markets import PerishableGoodsDuopolySystem
        >>> PerishableGoodsDuopolySystem(20).prepare().system_.elements[0].size
        20
    """

    field = 'economics/markets'
    topics = ('agents', 'discrete choice', 'symmetry breaking', 'phase transition', 'retail')
    references = ('Bertin 2021', 'Bouchaud 2013')
    until = 300
    observables = (Observable('m', group='customers', expression=CustomerElement.get_preference),)

    def __init__(
        self,
        customers: int = 200,
        *,
        stock: float = 0.5,
        T: float = 0.1,
        alpha: float = 0.9,
        tau_a: float = 1.0,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.customers = customers
        self.stock = stock
        self.T = T
        self.alpha = alpha
        self.tau_a = tau_a
        self.random_state = random_state

    @staticmethod
    def _buy(customer: CustomerView, system: SystemView) -> None:
        """Buy a random product of the shop of a customer, which the shop replaces with a fresh one.

        The customer takes the freshness `exp(-(t - shelved) / tau_a)` of the product, and the shelving time of the
        product is reset to the time of the sale.
        """
        groups = set(system.get_groups('products'))
        products = [other for other in customer.get_agents_here() if other.group in groups]
        if len(products) > 1:
            products = [products[int(index)] for index in system.rng.permutation(len(products))[:1]]
        for product in products:
            if customer.alive and product.alive and isinstance(product, ProductView):
                restock = float(product.shelved - system.time)
                fresh = float(np.exp(-(system.time - product.shelved) / product.tau_a)) - customer.freshness
                product.shelved -= restock
                customer.freshness += fresh

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        shelf = max(round(self.stock * self.customers), 1)
        space = NetworkSpace(nx.empty_graph(N_SHOPS))
        satisfaction = 0.5 + 0.01 * rng.standard_normal((N_SHOPS, self.customers))
        choice = ChoiceInteraction(
            'choice',
            target='customers',
            state='shop',
            options=tuple(float(shop) for shop in range(N_SHOPS)),
            utility=CustomerElement.get_utility,
            schedule='member',
            phase=PHASE,
        )
        movement = MovementInteraction(
            'movement',
            target='customers',
            step=CustomerElement.get_destination,
            schedule='member',
            phase=PHASE,
        )
        purchase = Interaction(
            'purchase',
            roles={'target': 'customers', 'products': 'products'},
            laws=lambda s: [UpdateLaw(s.target, PerishableGoodsDuopolySystem._buy, phase=PHASE)],
        )
        satisfaction_update = PayoffLearningInteraction(
            'satisfaction',
            target='customers',
            scores=('s1', 's2'),
            payoff=CustomerElement.get_payoff,
            rate=1 - self.alpha,
            chosen='shop',
            schedule='member',
            phase=PHASE,
        )
        self.system_ = System(
            self.label,
            elements=[
                CustomerElement('customers', s1=satisfaction[0], s2=satisfaction[1], T=self.T, size=self.customers),
                ProductElement(
                    'products',
                    tau_a=self.tau_a,
                    values={'node': np.repeat(np.arange(N_SHOPS), shelf)},
                    size=N_SHOPS * shelf,
                    space=space,
                ),
            ],
            interactions=[choice, movement, purchase, satisfaction_update],
            space=space,
            solver=MesaSolver(phases=[PhaseSpec(PHASE, activation='visits', groups=('customers',))]),
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • ChoiceInteraction, from Interaction, through the shared recipe ChoiceInteraction
  • MovementInteraction, from Interaction, through the shared recipe MovementInteraction
  • Interaction
  • PayoffLearningInteraction, from Interaction
class CustomerElement(Element):
    """Customer who remembers how satisfied it was with each of two shops.

    The satisfaction is with the products of the shops. The customer visits the shop `k` of larger satisfaction `S_k`
    more often, with the logit utility `S_k / T`, and holds the freshness of the product it bought last.

    Args:
        label:
            The label of the agent or group.

        s1:
            The satisfaction with the first shop.

        s2:
            The satisfaction with the second shop.

        shop:
            The index of the shop the customer visits, 0 or 1.

        freshness:
            The freshness of the product the customer bought last.

        T:
            The temperature of the choice, the randomness of the customer.

        size:
            The number of members, or `None` for one.

    Examples:
        >>> from skcomplex.systems.economics.markets import CustomerElement
        >>> CustomerElement('customers', s1=0.5, s2=0.5, size=10).size
        10
    """

    def __init__(
        self,
        label: str,
        *,
        s1: object = 0.5,
        s2: object = 0.5,
        shop: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
        freshness: Annotated[object, RealSet.closed(0, 1)] = 1.0,
        T: Annotated[object, RealSet.open(0, oo)] = 0.1,
        size: int | None = None,
    ) -> None:
        super().__init__(label, size=size)
        self.s1 = s1
        self.s2 = s2
        self.shop = shop
        self.freshness = freshness
        self.T = T

    @staticmethod
    def get_utility(agent: CustomerView, system: SystemView, option: float) -> float:
        """Return the utility `S_k / T` of visiting shop `k`.

        Args:
            agent:
                The customer.

            system:
                The system view of the choice.

            option:
                The index of the shop.

        Returns:
            utility:
                The satisfaction with the shop divided by the temperature.
        """
        return (agent.s1 if option == 0 else agent.s2) / agent.T

    @staticmethod
    def get_destination(agent: AgentViewProtocol, system: SystemViewProtocol) -> int | None:
        """Return the node of the shop the customer chose.

        Args:
            agent:
                The customer.

            system:
                The system view of the movement.

        Returns:
            node:
                The node of the shop, or `None` to stay for an agent that is not a customer.
        """
        return int(agent.shop) if isinstance(agent, CustomerView) else None

    @staticmethod
    def get_payoff(agent: CustomerView, system: SystemView, option: int) -> float:
        """Return the freshness of the product the customer bought last.

        It is the payoff of the shop it visited.

        Args:
            agent:
                The customer.

            system:
                The system view of the reinforcement.

            option:
                The index of the shop the customer visited.

        Returns:
            freshness:
                The freshness of the product.
        """
        return agent.freshness

    @staticmethod
    def get_preference(agent: CustomerView) -> float:
        """Return `p_1 - p_2 = tanh((S_1 - S_2) / 2T)`.

        It is how much more likely the customer visits the first shop.

        Args:
            agent:
                The customer.

        Returns:
            preference:
                The difference of the probabilities of visiting the first and the second shop.
        """
        return float(np.tanh((agent.s1 - agent.s2) / (2 * agent.T)))

class ProductElement(Element):
    """Product on the shelf of a shop, which ages from the time it was shelved.

    Its freshness is `exp(-age / tau_a)`.

    Args:
        label:
            The label of the agent or group.

        shelved:
            The time at which the product was put on the shelf.

        tau_a:
            The time over which the product ages.

        values:
            Further values by name, such as the `node` of the shop of every member.

        size:
            The number of members, or `None` for one.

        space:
            The network whose nodes are the shops, or `None` for none.

    Examples:
        >>> from skcomplex.systems.economics.markets import ProductElement
        >>> ProductElement('products', values={'node': [0, 0, 1, 1]}, size=4).size
        4
    """

    def __init__(
        self,
        label: str,
        *,
        shelved: object = 0.0,
        tau_a: Annotated[object, RealSet.open(0, oo)] = 1.0,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, values=values, size=size, space=space)
        self.shelved = shelved
        self.tau_a = tau_a

class ChoiceInteraction(Interaction):
    """An interaction by which members of a group choose among options by utility.

    At every step each member revises its choice with the probability `activity` and keeps it otherwise. The `rule`
    draws the new option from the utilities `u_k` of the options:

    - `'logit'`: option `k` with probability `exp(beta u_k) / sum_j exp(beta u_j)`, where `beta` is the intensity of
      choice.
    - `'metropolis'` and `'fermi'`: a proposed option, accepted with probability `min(1, exp(beta (u_new - u_old)))` or
      `1 / (1 + exp(-beta (u_new - u_old)))`.
    - `'best'`: an option of largest utility, with ties broken by `ties`.

    Without a `schedule` it sets update laws: `utility(namespace, option)` returns an expression, and every member
    draws at once. With a `schedule` it sets one rule of the whole system that walks the agents in that order with its
    own draws: `utility(agent, system, option)` returns a number, and an option of utility `-inf` is never drawn.

    Unlike a `JumpLaw`, which moves a state between values by given rates, it draws the new value from the utilities of
    all options at once. Choose it when members pick the option that pays best, with noise.

    It appears in many fields. Commuters choose a mode of transport, consumers choose a brand, farmers choose a crop,
    and voters choose a party by a logit model of discrete choice.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        target:
            The path of the element or group whose members choose.

        state:
            The name of the discrete state of the members that holds the chosen option.

        options:
            The values the state can take, at least two.

        utility:
            The function `utility(namespace, option)` without a schedule, or `utility(agent, system, option)` with one,
            that returns the utility of an option.

        rule:
            The rule of the draw, `'logit'`, `'metropolis'`, `'fermi'`, or `'best'`.

        intensity:
            The intensity of choice `beta`, zero for uniform choice.

        schedule:
            The order in which a rule walks the agents, `'synchronous'` for every agent at once, `'sequential'` or
            `'random-sequential'` for one agent after the other, or `'member'` for every agent in its own activation,
            or `None` for update laws of the states of every member.

        activity:
            The probability that a member revises its choice in a step.

        phase:
            The phase of the step the rule of a schedule runs in, or `None` for the default phase.

        proposal:
            The options the rules `'metropolis'` and `'fermi'` propose from, `'others'` for the options other than the
            current one, or `'all'` for every option.

        ties:
            The option the rule `'best'` takes among options of equal largest utility, `'random'` for one drawn
            uniformly or `'first'` for the first in the order of the options.

    Raises:
        ValidationError:
            The rule, the schedule, the proposal, or the ties are unknown, there are fewer than two options, or the
            utility is not callable.

    Examples:
        >>> from skcomplex.systems.general.agents import ChoiceInteraction
        >>> from skcomplex.core.components.laws.utils import mean
        >>> choice = ChoiceInteraction(
        ...     'choice', target='spins', state='spin', options=(-1, 1), utility=lambda s, o: o * mean(s.target.spin)
        ... )
        >>> choice.rule
        'logit'
        >>> agents = ChoiceInteraction(
        ...     'choice', target='traders', state='plan', options=(0, 1), utility=lambda a, m, o: o,
        ...     schedule='synchronous',
        ... )
        >>> type(agents.prepare(SimpleNamespace(target=SimpleNamespace())).laws_[0]).__name__
        'UpdateLaw'
        >>> ChoiceInteraction(
        ...     'heat-bath', target='spins', state='spin', options=(-1, 0, 1), utility=lambda s, o: o, rule='fermi',
        ...     proposal='all'
        ... ).proposal
        'all'
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)

    def _get_draws(self) -> bool:
        """Return whether the choice draws.

        Every rule draws but the best option with the first of ties every step.
        """
        fixed = self.rule == 'best' and self.ties == 'first' and self.activity == 1
        return super()._get_draws() or not fixed

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str,
        options: Sequence[float],
        utility: Callable[..., float | Expression],
        rule: str = 'logit',
        intensity: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        schedule: str | None = None,
        activity: Annotated[float, RealSet.closed(0, 1)] = 1.0,
        phase: str | None = None,
        proposal: str = 'others',
        ties: str = 'random',
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.options = options
        self.utility = utility
        self.rule = rule
        self.intensity = intensity
        self.schedule = schedule
        self.activity = activity
        self.phase = phase
        self.proposal = proposal
        self.ties = ties

    def _check_variants(self) -> None:
        """Raise an error for an unknown variant."""
        self._check_variant('rule', self.rule, RULES, (BaseSpec,))
        for name, value, variants in (
            ('schedule', self.schedule, (None, *ScheduleKind)),
            ('proposal', self.proposal, PROPOSALS),
            ('ties', self.ties, TIES),
        ):
            if value not in variants:
                error_msg = f'Unknown {name} {value!r} of {self.label!r}. Use one of {variants}.'
                raise ValidationError(error_msg)

    def _check_arguments(self) -> None:
        """Raise an error for an unknown variant, fewer than two options, or a bad utility.

        Raises:
            ValidationError:
                The type declares states, the rule, the schedule, the proposal, or the ties are unknown, there are fewer
                than two options, or the utility is not callable.
        """
        super()._check_arguments()
        self._check_variants()
        if len(self.options) < MIN_OPTIONS:
            error_msg = f'{self.label!r} chooses among {list(self.options)}. Give at least {MIN_OPTIONS} options.'
            raise ValidationError(error_msg)
        if not callable(self.utility):
            error_msg = f'The utility of {self.label!r} must be callable, but it is {self.utility!r}.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = self._get_choice_laws(context)

    @staticmethod
    def _get_draw_name(state: Expression, kind: str) -> str:
        """Return the name of a draw of a state, such as `x_activity`.

        A state read as a function of time, `x(t)`, names its draws after `x`.
        """
        name = str(state.operator()) if state.operator() is not None else str(state)
        return f'{name}_{kind}'

    def _select(self, index: Expression, values: Sequence[Expression]) -> Expression:
        """Return the value at a symbolic index."""
        return sum((where(index == position, value, 0) for position, value in enumerate(values)), SR(0))

    def _draw_softmax(self, state: Expression, utilities: Sequence[Expression], intensity: Expression) -> Expression:
        """Return the option drawn with probabilities proportional to `exp(beta u_k)`."""
        index = categorical(self._get_draw_name(state, 'option'), [exp(intensity * utility) for utility in utilities])
        return self._select(index, [SR(option) for option in self.options])

    def _draw_best(self, state: Expression, utilities: Sequence[Expression]) -> Expression:
        """Return an option drawn uniformly among the options of largest utility."""
        largest = utilities[0]
        for utility in utilities[1:]:
            largest = where(utility > largest, utility, largest)
        weights = [where(utility >= largest, 1, 0) for utility in utilities]
        if self.ties == 'first':
            weights = [
                weight * where(sum(weights[:position], SR(0)) > 0, 0, 1) for position, weight in enumerate(weights)
            ]
        index = categorical(self._get_draw_name(state, 'best'), weights)
        return self._select(index, [SR(option) for option in self.options])

    def _draw_proposal(self, state: Expression, utilities: Sequence[Expression], intensity: Expression) -> Expression:
        """Return a uniform proposal of an option.

        The proposal is accepted by the Metropolis or the Fermi probability.
        """
        weights = [SR(1) if self.proposal == 'all' else where(state == option, 0, 1) for option in self.options]
        index = categorical(self._get_draw_name(state, 'proposal'), weights)
        proposal = self._select(index, [SR(option) for option in self.options])
        gain = self._select(index, utilities) - sum(
            (where(state == option, utility, 0) for option, utility in zip(self.options, utilities, strict=True)),
            SR(0),
        )
        if self.rule == 'metropolis':
            acceptance = where(gain >= 0, 1, exp(intensity * gain))
        else:
            acceptance = 1 / (1 + exp(-intensity * gain))
        return where(uniform(self._get_draw_name(state, 'acceptance')) < acceptance, proposal, state)

    def _draw_symbolic(self, namespace: SimpleNamespace) -> Expression:
        """Return the option a member draws, as a symbolic expression of the namespace."""
        state = getattr(self._get_member(namespace, 'target'), self.state)
        utilities = [SR(self.utility(namespace, option)) for option in self.options]
        if self.rule == 'logit':
            return self._draw_softmax(state, utilities, self._get_parameter_symbol('intensity', namespace))
        if self.rule == 'best':
            return self._draw_best(state, utilities)
        if self.rule in ('metropolis', 'fermi'):
            return self._draw_proposal(state, utilities, self._get_parameter_symbol('intensity', namespace))
        raise self._get_variant_error(self.rule, 'rule', '_draw_symbolic')

    def _get_utilities(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> np.ndarray:
        """Return the utility of every option for an agent."""
        return np.array([float(self.utility(agent, system, option)) for option in self.options])

    def _draw_agent_proposal(self, agent: AgentViewProtocol, system: SystemViewProtocol, intensity: float) -> float:
        """Return a uniform proposal of an option of an agent if accepted.

        Otherwise it returns its current option.
        """
        current = float(getattr(agent, self.state))
        others = [option for option in self.options if self.proposal == 'all' or option != current]
        proposal = float(others[int(system.rng.integers(len(others)))])
        before = float(self.utility(agent, system, current)) if current in self.options else 0.0
        gain = float(self.utility(agent, system, proposal)) - before
        if self.rule == 'metropolis':
            acceptance = 1.0 if gain >= 0 else math.exp(intensity * gain)
        else:
            acceptance = float(expit(intensity * gain))
        return proposal if system.rng.random() < acceptance else current

    def _draw_agent(self, agent: AgentViewProtocol, system: SystemViewProtocol, intensity: float) -> float:
        """Return the option an agent draws by the rule."""
        if self.rule in ('metropolis', 'fermi'):
            return self._draw_agent_proposal(agent, system, intensity)
        utilities = self._get_utilities(agent, system)
        if self.rule == 'best':
            return float(self.options[self._pick_best(utilities, self.ties, system)])
        if self.rule != 'logit':
            raise self._get_variant_error(self.rule, 'rule', '_draw_agent')
        scaled = np.where(np.isneginf(utilities), -np.inf, intensity * utilities)
        probabilities = softmax(scaled)
        return float(self.options[int(system.rng.choice(len(self.options), p=probabilities))])

    def _is_active(self, system: SystemViewProtocol, activity: float) -> bool:
        """Return whether a member revises its choice in this step."""
        return activity >= 1 or bool(system.rng.random() < activity)

    def _get_choice(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> float | None:
        """Return the option an agent draws if it revises in this step.

        It returns `None` for the agent to keep its own.
        """
        if not self._is_active(system, self._get_parameter_value('activity', system)):
            return None
        return self._draw_agent(agent, system, self._get_parameter_value('intensity', system))

    def _set_choice(self, agent: AgentViewProtocol, option: float | None) -> None:
        """Set the state of an agent to the option it draws, if any."""
        if option is not None:
            setattr(agent, self.state, option)

    def _choose_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Set the state of one agent to the option it draws if it revises.

        This happens in its own activation.
        """
        if agent.alive:
            self._set_choice(agent, self._get_choice(agent, system))

    def choose(self, system: SystemViewProtocol) -> None:
        """Set the state of every revising agent to the option it draws, by the schedule.

        An agent revises in this step. Without a schedule every agent draws at once.

        Args:
            system:
                The system view of the interaction.
        """
        self._update_agents(system, self.schedule or 'synchronous', self._get_choice, self._set_choice)

    def _get_choice_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the update of the state of every revising member.

        With a schedule it returns the rule that walks the agents instead.

        Args:
            namespace:
                The namespace of the symbols the laws can use, with `namespace.target`, `namespace.intensity`, and
                `namespace.activity`.

        Returns:
            laws:
                The update law of the state, or the rule that runs the choice of the agents.
        """
        if self.schedule == 'member':
            return [UpdateLaw(self._get_member(namespace, 'target'), self._choose_member, phase=self.phase)]
        if self.schedule is not None:
            return [UpdateLaw(namespace, self.choose, phase=self.phase)]
        state = getattr(self._get_member(namespace, 'target'), self.state)
        revised = where(
            uniform(self._get_draw_name(state, 'activity')) < self._get_parameter_symbol('activity', namespace),
            self._draw_symbolic(namespace),
            state,
        )
        return [UpdateLaw(state, revised)]

class MovementInteraction(Interaction):
    """An interaction that moves the agents of a group by steps at every discrete step.

    The `step` says where an agent goes:

    - `'neighbor'`: a random cell or node next to its own, on a lattice or a network.
    - `'gaussian'`: its position plus a normal vector of deviation `scale`, in a continuous space.
    - `'levy'`: a random direction and a Pareto length of least value `scale` and tail `exponent`, in a continuous
      space.
    - `'best'`: the next cell with the highest `score(agent, cell, system)`, or with a `vision` the best cell along each
      direction up to that many cells, with ties broken by `ties`.
    - A function `step(agent, system)` that returns the destination, or `None` to stay.

    An agent for which `condition` holds attempts one step, or a Poisson number of mean `rate`, takes it with the
    probability `probability`, and then with the probability `accept(agent, destination, system)`. An exclusive movement
    never enters a cell held by another agent of the group. The agents move one after another by `schedule`, and every
    step charges its `cost`.

    Unlike an `UpdateLaw` on the edges of a network, which changes the space, it changes where agents stand in it.
    Choose it when agents walk, forage, or relocate.

    It appears in many fields. Sheep wander a pasture, foragers follow Lévy flights, ants climb a pheromone gradient,
    and residents move house in the segregation model of Schelling.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        target:
            The path of the group whose agents move.

        step:
            The kind of step, `'neighbor'`, `'gaussian'`, `'levy'`, or `'best'`, or a function of the agent and the
            system view that returns the destination.

        probability:
            The probability that an agent takes an attempted step.

        rate:
            The mean number of attempted steps of an agent in one unit of time, or `None` for one attempt every step.

        condition:
            A function of the agent and the system view that returns whether the agent moves, or `None` for every agent.

        accept:
            A function of the agent, its destination, and the system view that returns the probability of taking the
            step, or `None` to take every step.

        exclusive:
            Whether an agent moves only to cells or nodes no other agent of the group holds.

        score:
            The function of the agent, a neighbouring cell, and the system view that the step `'best'` maximizes.

        scale:
            The standard deviation of every component of a Gaussian step, or the least length of a Lévy step.

        exponent:
            The tail exponent of the length of a Lévy step.

        cost:
            A function of the agent and the system view run for every step taken, such as one that takes the energy a
            step costs from the agent, `def pay(agent, system): agent.energy -= 1.0`, or `None`.

        vision:
            The number of cells the step `'best'` looks along every direction of a lattice, a number or a function of
            the agent and the system view, or `None` for the cells next to the agent.

        schedule:
            The order of the agents, `'sequential'`, `'random-sequential'`, or `'member'`.

        phase:
            The phase of the step the movement runs in, or `None` for the default phase.

        ties:
            The cell the step `'best'` takes among cells of equal highest score, `'random'`, `'first'`, or `'nearest'`,
            or `None` for `'random'` without a vision and `'nearest'` with one.

    Raises:
        ValidationError:
            The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable, or
            the step `'best'` has no score, raised by `prepare`.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.agents import MovementInteraction
        >>> space = LatticeSpace((5, 5), metric='manhattan')
        >>> walkers = Element('walkers', values={'x': [2, 2], 'y': [2, 2]}, size=2, space=space)
        >>> walk = MovementInteraction('walk', target='walkers', step='neighbor')
        >>> trajectory = System(elements=[walkers], interactions=[walk]).prepare().simulate(until=1, random_state=0)
        >>> [bool(abs(cell - 2).sum() == 1) for cell in trajectory.get_agents('walkers', 1).locations]
        [True, True]
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)

    def _get_draws(self) -> bool:
        """Return whether the movement draws.

        It draws by its order, a random step, a probability or rate, or random ties.
        """
        ties = self.ties or ('random' if self.vision is None else 'nearest')
        drawn = self.step in ('neighbor', 'gaussian', 'levy') or (self.step == 'best' and ties == 'random')
        return (
            super()._get_draws() or drawn or self.probability != 1 or self.rate is not None or self.accept is not None
        )

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        step: Step = 'neighbor',
        probability: Annotated[float, RealSet.closed(0, 1)] = 1.0,
        rate: float | None = None,
        condition: Callable[[AgentViewProtocol, SystemViewProtocol], bool] | None = None,
        accept: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
        exclusive: bool = False,
        score: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
        scale: Annotated[float, RealSet.open(0, oo)] = 1.0,
        exponent: Annotated[float, RealSet.open(0, oo)] = 1.5,
        cost: Cost | None = None,
        vision: Vision | None = None,
        schedule: str = 'random-sequential',
        phase: str | None = None,
        ties: str | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.step = step
        self.probability = probability
        self.rate = rate
        self.condition = condition
        self.accept = accept
        self.exclusive = exclusive
        self.score = score
        self.scale = scale
        self.exponent = exponent
        self.cost = cost
        self.vision = vision
        self.schedule = schedule
        self.phase = phase
        self.ties = ties

    def _check_functions(self) -> None:
        """Raise an error for a condition, acceptance, score, or cost that is not callable."""
        for name in ('condition', 'accept', 'score', 'cost'):
            value = getattr(self, name)
            if value is not None and not callable(value):
                error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function, or None.'
                raise ValidationError(error_msg)

    def _check_space(self, space: BaseSpace | None) -> None:
        """Raise an error for a step to a neighbouring cell or node in a continuous space."""
        if isinstance(self.step, str) and self.step in GRID_STEPS:
            self._check_grid('step', self.step, space, "step='gaussian' or step='levy', or a step function")

    def _check_arguments(self) -> None:
        """Raise an error for an unknown step, a rate not positive, or a bad function.

        Raises:
            ValidationError:
                The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable,
                or the step `'best'` has no score.
        """
        super()._check_arguments()
        self._check_variant('step', self.step, STEPS, functions=True)
        if self.rate is not None and (isinstance(self.rate, bool) or not self.rate > 0):
            error_msg = f'The rate of {self.label!r} is {self.rate!r}. Give a positive number, or None.'
            raise ValidationError(error_msg)
        if self.schedule not in SCHEDULES:
            error_msg = f'Unknown schedule {self.schedule!r} of {self.label!r}. Use one of {", ".join(SCHEDULES)}.'
            raise ValidationError(error_msg)
        if self.ties is not None:
            self._check_variant('ties', self.ties, TIES)
        if self.vision is not None and not callable(self.vision) and not isinstance(self.vision, int | float):
            error_msg = f'The vision of {self.label!r} is {self.vision!r}. Give a number, a function, or None.'
            raise ValidationError(error_msg)
        if self.step == 'best' and self.score is None:
            error_msg = f'The step `best` of {self.label!r} maximizes a score. Pass `score(agent, cell, system)`.'
            raise ValidationError(error_msg)
        self._check_functions()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = self._get_movement_laws(context)

    def _count_attempts(self, system: SystemViewProtocol) -> int:
        """Return the number of steps an agent attempts in one step of time."""
        return 1 if self.rate is None else int(system.rng.poisson(self.rate))

    def _get_cells(self, agent: AgentViewProtocol, occupied: set[object]) -> list[object]:
        """Return the cells or nodes around an agent that it may move to."""
        cells = agent.get_neighbor_cells()
        if not self.exclusive:
            return cells
        return [cell for cell in cells if cell not in occupied]

    def _get_best(
        self,
        agent: AgentViewProtocol,
        cells: list[object],
        system: SystemViewProtocol,
        distances: list[int] | None = None,
    ) -> object:
        """Return the cell of the highest score, chosen among ties by the tie rule."""
        if self.score is None or not cells:
            return None
        scores = [self.score(agent, cell, system) for cell in cells]
        ties = self.ties or ('random' if distances is None else 'nearest')
        if ties != 'nearest':
            return cells[self._pick_best(scores, ties, system)]
        values = np.asarray(scores, dtype=float)
        best = np.flatnonzero(values == values.max())
        near = np.asarray([1 if distances is None else distances[int(index)] for index in best])
        return cells[int(best[near == near.min()][0])]

    @staticmethod
    def _shift(here: tuple[int, ...], cell: tuple[int, ...], system: SystemViewProtocol) -> tuple[int, ...]:
        """Return the unit step from a cell to a neighbouring cell.

        The step goes across the wrapped edge of a torus.
        """
        shift = [b - a for a, b in zip(here, cell, strict=True)]
        if system.torus:
            sizes = [int(item) for item in system.dimensions or ()]
            shift = [d - round(d / n) * n for d, n in zip(shift, sizes, strict=True)]
        return tuple(shift)

    def _get_sight(
        self,
        agent: AgentViewProtocol,
        occupied: set[object],
        system: SystemViewProtocol,
    ) -> tuple[list[object], list[int]]:
        """Return the cells in sight of an agent along every direction of a lattice.

        Its own cell comes first, with the distances.
        """
        vision = self.vision(agent, system) if callable(self.vision) else self.vision
        reach = int(vision or 0)
        here = tuple(int(item) for item in np.atleast_1d(np.asarray(agent.location_key)))
        sizes = [int(item) for item in system.dimensions or ()]
        cells: list[object] = [agent.location_key]
        distances = [0]
        shifts = [
            self._shift(here, tuple(int(item) for item in np.atleast_1d(np.asarray(neighbor))), system)
            for neighbor in agent.get_neighbor_cells()
        ]
        for shift in sorted(shifts, key=lambda step: tuple((item == 0, -item) for item in step)):
            for distance in range(1, reach + 1):
                point = [a + distance * d for a, d in zip(here, shift, strict=True)]
                if system.torus:
                    point = [item % size for item, size in zip(point, sizes, strict=True)]
                elif any(not 0 <= item < size for item, size in zip(point, sizes, strict=True)):
                    break
                cell = tuple(point)
                if not self.exclusive or cell not in occupied:
                    cells.append(cell)
                    distances.append(distance)
        return cells, distances

    def _get_destination(self, agent: AgentViewProtocol, system: SystemViewProtocol, occupied: set[object]) -> object:
        """Return the location a step of an agent leads to, or `None` to stay."""
        rng = system.rng
        if callable(self.step):
            return self.step(agent, system)
        if self.step == 'best' and self.vision is not None:
            cells, distances = self._get_sight(agent, occupied, system)
            return self._get_best(agent, cells, system, distances)
        if self.step in ('neighbor', 'best'):
            cells = self._get_cells(agent, occupied)
            if self.step == 'best':
                return self._get_best(agent, cells, system)
            return cells[int(rng.integers(len(cells)))] if cells else None
        position = np.asarray(agent.location, dtype=float)
        if self.step == 'gaussian':
            return position + rng.normal(0.0, self._get_parameter_value('scale', system), position.shape)
        direction = rng.normal(size=position.shape)
        length = self._get_parameter_value('scale', system) * (
            1.0 + rng.pareto(self._get_parameter_value('exponent', system))
        )
        return position + length * direction / np.linalg.norm(direction)

    def _charge(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Charge the cost of one step taken to an agent."""
        if self.cost is not None:
            self.cost(agent, system)

    def _take(self, agent: AgentViewProtocol, destination: object, occupied: set[object]) -> bool:
        """Move an agent to a destination unless an exclusive movement finds it held.

        It returns whether it moved.
        """
        if not self.exclusive:
            agent.move_to(destination)
            return True
        if destination == agent.location_key:
            return True
        if destination in occupied:
            return False
        occupied.discard(agent.location_key)
        agent.move_to(destination)
        occupied.add(agent.location_key)
        return True

    def _move(
        self,
        agent: AgentViewProtocol,
        system: SystemViewProtocol,
        probability: float,
        occupied: set[object],
    ) -> None:
        """Take the attempted steps of one agent.

        Each step has its probability and acceptance, and every step is charged.
        """
        for _ in range(self._count_attempts(system)):
            if probability < 1.0 and system.rng.random() >= probability:
                continue
            destination = self._get_destination(agent, system, occupied)
            if destination is None:
                continue
            if self.accept is not None and system.rng.random() >= self.accept(agent, destination, system):
                continue
            if self._take(agent, destination, occupied):
                self._charge(agent, system)

    def _move_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Move one agent whose condition holds, in its own activation."""
        if agent.alive and (self.condition is None or self.condition(agent, system)):
            occupied = (
                {other.location_key for other in system.get_agents(self._get_role('target'))}
                if self.exclusive
                else set()
            )
            self._move(agent, system, self._get_parameter_value('probability', system), occupied)

    def _move_all(self, system: SystemViewProtocol) -> None:
        """Move every agent of the group whose condition holds.

        They move in their order or in random order.
        """
        agents = system.get_agents(self._get_role('target'))
        occupied = {agent.location_key for agent in agents} if self.exclusive else set()
        probability = self._get_parameter_value('probability', system)
        order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
        for index in order:
            agent = agents[int(index)]
            if agent.alive and (self.condition is None or self.condition(agent, system)):
                self._move(agent, system, probability, occupied)

    def _get_movement_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the rule of the movement.

        Args:
            namespace:
                The namespace of the symbols the laws can use.

        Returns:
            laws:
                The rule that moves the agents every step.
        """
        if self.schedule == 'member':
            return [UpdateLaw(self._get_member(namespace, 'target'), self._move_member, phase=self.phase)]
        return [UpdateLaw(namespace, self._move_all, phase=self.phase)]

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None

class PayoffLearningInteraction(Interaction):
    """Payoff learning of the scores of options.

    Economics names it reinforcement learning of payoffs, as in fictitious play and the attractions of
    experience-weighted learning. Each score moves towards the payoff its option realized in the step. Every step, the
    score `s_k` of option `k` of every member moves towards the realized payoff `P_k` at the rate `a`, `s_k <- s_k + a
    (P_k - s_k)`, so a score is an exponentially weighted mean of past payoffs, and the last payoff at the rate 1, by
    the rule `'average'`. By the rule `'cumulative'` the score adds the payoff, `s_k <- s_k + P_k`, so it is the sum of
    past payoffs, such as a virtual score. Without a `schedule` it sets update laws, and `payoff(namespace, k)` returns
    the payoff of option `k` as a symbolic expression, where `namespace.target` holds the states and parameters of the
    group. With a `schedule` it sets one rule that walks the agents of the group in that order, and `payoff(agent,
    system, k)` returns the payoff as a number, so it can read the agent and the history and storage of the system view.
    Its scores may then be the components of one vector state, one per option, and a group of one member holds scores
    that several groups share. With `chosen`, the name of a state that holds the index of the option a member chose,
    only the score of that option moves, and the payoff of the other options is not read. Every agent reinforces at
    once under the schedule `'synchronous'`, one after the other in their order or in a new random order every step
    under `'sequential'` or `'random-sequential'`, and each in its own activation under `'member'`, together with the
    rules of its element and the other member interactions, in the order the system lists them, such as after a choice
    and a transfer in one visit.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        target:
            The path of the element or group whose members hold the scores.

        scores:
            The names of the states that hold the score of every option, in the order of the options, or with a
            schedule the name of one vector state whose components are the scores.

        payoff:
            The function `payoff(namespace, k)` without a schedule, or `payoff(agent, system, k)` with one, that
            returns the realized payoff of option `k`.

        rate:
            The rate `a` at which the scores move towards the payoffs, between 0 and 1, by the rule `'average'`.

        rule:
            `'average'` to move the scores towards the payoffs, or `'cumulative'` to add the payoffs to the scores.

        phase:
            The phase of the step the rule of a schedule runs in, or `None` for the default phase.

        chosen:
            The name of the state that holds the index of the option a member chose, so only its score moves, or
            `None` to move every score.

        schedule:
            The order in which a rule walks the agents, `'synchronous'` for every agent at once, `'sequential'` or
            `'random-sequential'` for one agent after the other, or `'member'` for every agent in its own activation,
            or `None` for update laws of the scores of every member.

    Raises:
        ValidationError:
            The rule or the schedule is unknown, there are no scores, or the payoff is not callable.

    Examples:
        >>> from skcomplex.systems.economics.common.learning import PayoffLearningInteraction
        >>> reinforcement = PayoffLearningInteraction(
        ...     'reinforcement', target='learners', scores=('first', 'second'), payoff=lambda s, k: k, rate=0.5
        ... )
        >>> reinforcement.rate
        0.5
        >>> PayoffLearningInteraction(
        ...     'virtual', target='players', scores='scores', payoff=lambda a, m, k: k, rule='cumulative',
        ...     schedule='synchronous',
        ... ).rule
        'cumulative'
        >>> PayoffLearningInteraction(
        ...     'satisfaction', target='customers', scores=('s1', 's2'), payoff=lambda a, m, k: 1.0, chosen='shop',
        ...     schedule='member',
        ... ).chosen
        'shop'
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        scores: str | Sequence[str],
        payoff: Callable[..., float | Expression],
        rate: Annotated[float, RealSet.closed(0, 1)] = 0.1,
        rule: str = 'average',
        phase: str | None = None,
        chosen: str | None = None,
        schedule: str | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.scores = scores
        self.payoff = payoff
        self.rate = rate
        self.rule = rule
        self.chosen = chosen
        self.phase = phase
        self.schedule = schedule

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The rule or the schedule is unknown, there are no scores, or the payoff is not callable.
        """
        super()._check_arguments()
        self._check()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the update of the scores, or the rule of the agents, as the laws.

        Args:
            context:
                The namespace of the members it binds.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = self._get_learning_laws(context)

    def _check(self) -> None:
        """Raise an error for an unknown variant, no scores, or an uncallable payoff."""
        if self.schedule not in SCHEDULES:
            error_msg = f'Unknown schedule {self.schedule!r} of {self.label!r}. Use one of {SCHEDULES}.'
            raise ValidationError(error_msg)
        if self.rule not in RULES:
            error_msg = f'Unknown rule {self.rule!r} of {self.label!r}. Use one of {RULES}.'
            raise ValidationError(error_msg)
        vector = isinstance(self.scores, str) and bool(self.scores) and self.schedule is not None
        if not vector and (isinstance(self.scores, str) or not self.scores):
            error_msg = (
                f'{self.label!r} has the scores {self.scores!r}. Give a sequence of state names, one per option, or '
                'with a schedule the name of a vector state.'
            )
            raise ValidationError(error_msg)
        if not callable(self.payoff):
            error_msg = f'The payoff of {self.label!r} must be callable, but it is {self.payoff!r}.'
            raise ValidationError(error_msg)

    def _read_scores(self, agent: AgentViewProtocol) -> Array:
        """Return the scores of an agent, one per option."""
        if isinstance(self.scores, str):
            return np.array(getattr(agent, self.scores), dtype=float).ravel()
        return np.array([getattr(agent, name) for name in self.scores], dtype=float)

    def _get_scores(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> Array:
        """Return the new scores of an agent.

        Every score, or only that of its chosen option, moves by its payoff.
        """
        old = self._read_scores(agent)
        options = range(len(old)) if self.chosen is None else [int(getattr(agent, self.chosen))]
        rate = 1.0 if self.rule == 'cumulative' else self.rate
        change = np.zeros_like(old)
        for k in options:
            payoff = float(self.payoff(agent, system, k))
            change[k] = payoff if self.rule == 'cumulative' else rate * (payoff - old[k])
        return old + change

    def _set_value(self, agent: AgentViewProtocol, value: object) -> None:
        """Set the scores of an agent."""
        scores = np.asarray(value, dtype=float)
        if isinstance(self.scores, str):
            setattr(agent, self.scores, scores)
            return
        for name, score in zip(self.scores, scores, strict=True):
            setattr(agent, name, float(score))

    def _update_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Move the scores of one agent, in its own activation."""
        if agent.alive:
            self._set_value(agent, self._get_scores(agent, system))

    def update(self, system: SystemViewProtocol) -> None:
        """Move the scores of every agent by the schedule.

        Under `'synchronous'` every agent reads the scores at the start of the rule, and otherwise the agents move one
        after the other, in their order or in a new random order.

        Args:
            system:
                The system view of the learning.
        """
        agents = list(system.get_agents('target'))
        if self.schedule == 'synchronous':
            values = [self._get_scores(agent, system) for agent in agents]
            for agent, value in zip(agents, values, strict=True):
                self._set_value(agent, value)
            return
        order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
        for index in order:
            self._update_member(agents[int(index)], system)

    def _get_learning_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the update of every score towards its payoff, or the rule of the schedule."""
        if self.schedule == 'member':
            return [UpdateLaw(namespace.target, self._update_member, phase=self.phase)]
        if self.schedule is not None:
            return [UpdateLaw(namespace, self.update, phase=self.phase)]
        laws: list[BaseLaw] = []
        for index, name in enumerate(self.scores):
            score = getattr(namespace.target, name)
            payoff = self.payoff(namespace, index)
            change = payoff if self.rule == 'cumulative' else namespace.rate * (payoff - score)
            if self.chosen is not None:
                change = where(getattr(namespace.target, self.chosen) == index, change, 0)
            laws.append(UpdateLaw(score, score + change))
        return laws