Skip to content

Beer distribution game

Sterman's beer distribution game.

  • Class: BeerGameSystem
  • Import: from skcomplex.systems.economics.markets import BeerGameSystem
  • Field: economics/markets
  • Topics: supply chain, bullwhip effect, delay, stocks and flows, system dynamics, ode
  • References:
    • Sterman 1989

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 BeerGameSystem

trajectory = BeerGameSystem().prepare().simulate()

Parameters

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

Parameter Default
inventory 12.0
demand 4.0
demand_step 4.0
step_time 5.0
theta 0.36
alpha 0.26
beta 0.34
dispatch_time 1.0
mail_delay 2.0
shipping_delay 2.0
production_delay 3.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 none
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 BeerGameSystem(BaseSystem):
    """Sterman's beer distribution game.

    Its orders swing wider at every echelon upstream. A retailer, a wholesaler, a distributor, and a factory each hold
    an inventory of beer and a backlog of orders waiting to ship. Each ships its backlog over the dispatch time, limited
    by its inventory, and the beer reaches the next echelon downstream after the shipping delay. Orders reach the next
    echelon upstream after the mail delay, and the factory brews its orders over the production delay. Customer demand
    steps from 4 to 8 cases a week in week 5. Every echelon orders by Sterman's anchoring and adjustment rule, its
    expected demand plus `alpha` times the gap between its desired stock `S'` and its effective inventory, the inventory
    less the backlog, plus `beta` times its supply line, the beer it ordered and has not received. The expected demand
    adapts to incoming orders at the rate `theta`. The defaults of `theta`, `alpha`, and `beta` are the median estimates
    of Sterman 1989, and `S'` is set so the chain starts in equilibrium at 4 cases a week. The game is weekly and its
    delays are fixed, while this system is a continuous approximation in which third-order delays stand in for the fixed
    ones. The amplitude of the orders grows from the retailer to the factory, the bullwhip effect.

    The system has the stocks `<echelon>.inventory`, `<echelon>.in_transit`, `<echelon>.backlog`, `<echelon>.expected`,
    and `<echelon>.supply_line` of the echelons `retailer`, `wholesaler`, `distributor`, and `factory`, and the flows
    `<upstream>_to_<downstream>.shipments` between the echelons, `<downstream>.arrivals` at every echelon a link
    supplies, `retailer.sales`, and `factory.starts` and `factory.completions`. The interactions `<echelon>_shipping`
    ship the backlog of every echelon and decay its expectation, the rates `<echelon>_backlog` and `<echelon>_expected`
    add the orders that reach every echelon and adapt its expectation, and the rates `<echelon>_supply_line` keep its
    supply line. The observables of the system are the orders `<echelon>.orders` and the shipments `<echelon>.shipments`
    of every echelon, and the orders of the customers `customers.orders`.

    Args:
        inventory:
            The initial inventory of every echelon, in cases.

        demand:
            The customer demand, in cases a week.

        demand_step:
            The permanent change of the customer demand.

        step_time:
            The week of the change of the customer demand.

        theta:
            The rate at which the expected demand adapts to incoming orders.

        alpha:
            The fraction of the stock gap ordered per week.

        beta:
            The weight of the supply line in the stock gap.

        dispatch_time:
            The time over which an echelon ships its backlog.

        mail_delay:
            The average time an order takes to reach the next echelon upstream.

        shipping_delay:
            The average time a shipment takes to reach the next echelon downstream.

        production_delay:
            The average time the factory takes to brew its orders.

        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 BeerGameSystem
        >>> [element.label for element in BeerGameSystem().prepare().system_.elements]
        ['retailer', 'wholesaler', 'distributor', 'factory']
    """

    field = 'economics/markets'
    topics = ('supply chain', 'bullwhip effect', 'delay', 'stocks and flows', 'system dynamics', 'ode')
    references = ('Sterman 1989',)
    until = 36.0
    dt = 0.5
    observables = (
        *(Observable('orders', BreweryInteraction._get_orders, element=label) for label in ECHELONS),
        *(Observable('shipments', EchelonElement._get_shipments, element=label) for label in ECHELONS),
        Observable('customers.orders', _get_customer_orders),
    )

    @staticmethod
    def _get_received(downstream: SimpleNamespace) -> Expression:
        """Return the orders of the downstream echelon that reach its supplier.

        They arrive after a third-order mail delay.
        """
        return distributed_delay(BreweryInteraction._get_orders(downstream), order=3, time=downstream.mail_delay)

    def __init__(
        self,
        inventory: float = 12.0,
        *,
        demand: float = 4.0,
        demand_step: float = 4.0,
        step_time: float = 5.0,
        theta: float = 0.36,
        alpha: float = 0.26,
        beta: float = 0.34,
        dispatch_time: float = 1.0,
        mail_delay: float = 2.0,
        shipping_delay: float = 2.0,
        production_delay: float = 3.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.inventory = inventory
        self.demand = demand
        self.demand_step = demand_step
        self.step_time = step_time
        self.theta = theta
        self.alpha = alpha
        self.beta = beta
        self.dispatch_time = dispatch_time
        self.mail_delay = mail_delay
        self.shipping_delay = shipping_delay
        self.production_delay = production_delay

    @staticmethod
    def _get_link_rates(downstream: str, upstream: str) -> list[Interaction]:
        """Return the rates of a link.

        They are the supply line of the downstream echelon and the incoming orders upstream.
        """
        return [
            Interaction(
                f'{downstream}_supply_line',
                roles={'target': downstream, 'source': upstream},
                laws=lambda s: [
                    RateLaw(
                        s.target.supply_line,
                        BreweryInteraction._get_orders(s.target)
                        - SupplyLinkInteraction._get_arrivals(s.source, s.target),
                    ),
                ],
            ),
            Interaction(
                f'{upstream}_backlog',
                roles={'target': upstream, 'source': downstream},
                laws=lambda s: [RateLaw(s.target.backlog, BeerGameSystem._get_received(s.source))],
            ),
            Interaction(
                f'{upstream}_expected',
                roles={'target': upstream, 'source': downstream},
                laws=lambda s: [RateLaw(s.target.expected, s.target.theta * BeerGameSystem._get_received(s.source))],
            ),
        ]

    @staticmethod
    def _get_customer_rates() -> list[Interaction]:
        """Return the rates of the customers.

        They are the demand that reaches the retailer and its expectation.
        """
        return [
            Interaction(
                'retailer_backlog',
                roles={'target': 'retailer'},
                laws=lambda s: [RateLaw(s.target.backlog, _get_demand(s.target, s.t))],
            ),
            Interaction(
                'retailer_expected',
                roles={'target': 'retailer'},
                laws=lambda s: [RateLaw(s.target.expected, s.target.theta * _get_demand(s.target, s.t))],
            ),
        ]

    @staticmethod
    def _get_brewery_rate() -> Interaction:
        """Return the rate of the supply line of the factory.

        It is its orders less the brews completed.
        """
        return Interaction(
            'factory_supply_line',
            roles={'target': 'factory'},
            laws=lambda s: [
                RateLaw(
                    s.target.supply_line,
                    BreweryInteraction._get_orders(s.target) - BreweryInteraction._get_completions(s.target),
                ),
            ],
        )

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        throughput = self.demand * self.dispatch_time
        echelons: list[EchelonElement] = []
        for label in ECHELONS:
            pipeline = self.production_delay if label == 'factory' else self.shipping_delay
            lead_time = pipeline if label == 'factory' else self.mail_delay + self.shipping_delay
            supply_line = self.demand * lead_time
            values = {
                'inventory': self.inventory,
                'in_transit': self.demand * pipeline,
                'backlog': throughput,
                'expected': self.demand,
                'supply_line': supply_line,
                'desired': self.inventory - throughput + self.beta * supply_line,
                'theta': self.theta,
                'alpha': self.alpha,
                'beta': self.beta,
                'dispatch_time': self.dispatch_time,
                'mail_delay': self.mail_delay,
                'shipping_delay': self.shipping_delay,
            }
            if label == 'retailer':
                values.update(demand=self.demand, demand_step=self.demand_step, step_time=self.step_time)
            elif label == 'factory':
                values.update(production_delay=self.production_delay)
            kind = {'retailer': RetailerElement, 'factory': FactoryElement}.get(label, EchelonElement)
            echelons.append(kind(label).set_params(**values))
        shipping = [EchelonInteraction(f'{label}_shipping', target=label) for label in ECHELONS]
        links = [
            interaction
            for downstream, upstream in pairwise(ECHELONS)
            for interaction in (
                *self._get_link_rates(downstream, upstream),
                SupplyLinkInteraction(f'{upstream}_to_{downstream}', downstream=downstream, upstream=upstream),
            )
        ]
        customers = [*self._get_customer_rates(), RetailDemandInteraction('customers', retailer='retailer')]
        brewery = [self._get_brewery_rate(), BreweryInteraction('brewery', factory='factory')]
        self.system_ = System(self.label, elements=echelons, interactions=[*shipping, *links, *customers, *brewery])

Components

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

Elements:

Interactions:

  • EchelonInteraction, from Interaction
  • Interaction
  • SupplyLinkInteraction, from Interaction
  • RetailDemandInteraction, from Interaction
  • BreweryInteraction, from Interaction
class RetailerElement(EchelonElement):
    """Retailer of a supply chain.

    It is an echelon whose customers order their demand, which steps once.

    Args:
        label:
            The label of the retailer.

        inventory:
            The initial inventory, in cases.

        in_transit:
            The initial beer on its way to the echelon.

        backlog:
            The initial orders waiting to ship.

        expected:
            The initial expected demand.

        supply_line:
            The initial beer ordered and not received.

        desired:
            The desired stock `S'`.

        theta:
            The rate at which the expected demand adapts to incoming orders.

        alpha:
            The fraction of the stock gap ordered per week.

        beta:
            The weight of the supply line in the stock gap.

        dispatch_time:
            The time over which the echelon ships its backlog.

        mail_delay:
            The average time an order of the echelon takes to reach its supplier.

        shipping_delay:
            The average time a shipment takes to reach the echelon from its supplier.

        demand:
            The customer demand, in cases a week.

        demand_step:
            The permanent change of the demand.

        step_time:
            The week of the change of the demand.

    Examples:
        >>> from skcomplex.systems.economics.markets import RetailerElement
        >>> RetailerElement('retailer').demand
        4.0
    """

    def __init__(
        self,
        label: str,
        *,
        inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 12.0,
        in_transit: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 8.0,
        backlog: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        expected: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        supply_line: Annotated[float, RealSet.closed_open(0, oo)] = 16.0,
        desired: float = 13.44,
        theta: Annotated[float, RealSet.closed_open(0, oo)] = 0.36,
        alpha: Annotated[float, RealSet.closed_open(0, oo)] = 0.26,
        beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.34,
        dispatch_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
        mail_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
        shipping_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
        demand: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        demand_step: float = 4.0,
        step_time: Annotated[float, RealSet.closed_open(0, oo)] = 5.0,
    ) -> None:
        super().__init__(
            label,
            inventory=inventory,
            in_transit=in_transit,
            backlog=backlog,
            expected=expected,
            supply_line=supply_line,
            desired=desired,
            theta=theta,
            alpha=alpha,
            beta=beta,
            dispatch_time=dispatch_time,
            mail_delay=mail_delay,
            shipping_delay=shipping_delay,
        )
        self.demand = demand
        self.demand_step = demand_step
        self.step_time = step_time

class EchelonElement(Element):
    """Echelon of a supply chain.

    It ships its backlog from its inventory and orders by anchoring and adjustment, by the laws of `EchelonInteraction`.
    It ships its backlog over the dispatch time, limited by its inventory. Its expected demand adapts to incoming orders
    at the rate `theta`, and it orders its expected demand plus `alpha` times the gap between its desired stock and its
    effective inventory, the inventory less the backlog, less `beta` times its supply line, never negative. Its orders
    reach its supplier after the mail delay, and the beer its supplier ships arrives after the shipping delay.

    Args:
        label:
            The label of the echelon.

        inventory:
            The initial inventory, in cases.

        in_transit:
            The initial beer on its way to the echelon.

        backlog:
            The initial orders waiting to ship.

        expected:
            The initial expected demand.

        supply_line:
            The initial beer ordered and not received.

        desired:
            The desired stock `S'`.

        theta:
            The rate at which the expected demand adapts to incoming orders.

        alpha:
            The fraction of the stock gap ordered per week.

        beta:
            The weight of the supply line in the stock gap.

        dispatch_time:
            The time over which the echelon ships its backlog.

        mail_delay:
            The average time an order of the echelon takes to reach its supplier.

        shipping_delay:
            The average time a shipment takes to reach the echelon from its supplier.

    Examples:
        >>> from skcomplex.systems.economics.markets import EchelonElement
        >>> EchelonElement('retailer', inventory=10.0).inventory
        10.0
    """

    def __init__(
        self,
        label: str,
        *,
        inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 12.0,
        in_transit: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 8.0,
        backlog: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        expected: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        supply_line: Annotated[float, RealSet.closed_open(0, oo)] = 16.0,
        desired: float = 13.44,
        theta: Annotated[float, RealSet.closed_open(0, oo)] = 0.36,
        alpha: Annotated[float, RealSet.closed_open(0, oo)] = 0.26,
        beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.34,
        dispatch_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
        mail_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
        shipping_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
    ) -> None:
        super().__init__(label)
        self.inventory = inventory
        self.in_transit = in_transit
        self.backlog = backlog
        self.expected = expected
        self.supply_line = supply_line
        self.desired = desired
        self.theta = theta
        self.alpha = alpha
        self.beta = beta
        self.dispatch_time = dispatch_time
        self.mail_delay = mail_delay
        self.shipping_delay = shipping_delay

    @staticmethod
    def _get_shipments(echelon: SimpleNamespace) -> Expression:
        """Return the shipments of an echelon.

        They are its backlog limited by its inventory over the dispatch time.
        """
        return minimum(echelon.backlog, echelon.inventory) / echelon.dispatch_time

class FactoryElement(EchelonElement):
    """Factory of a supply chain.

    It is an echelon whose orders a brewery brews over the production delay.

    Args:
        label:
            The label of the factory.

        inventory:
            The initial inventory, in cases.

        in_transit:
            The initial beer on its way to the echelon.

        backlog:
            The initial orders waiting to ship.

        expected:
            The initial expected demand.

        supply_line:
            The initial beer ordered and not received.

        desired:
            The desired stock `S'`.

        theta:
            The rate at which the expected demand adapts to incoming orders.

        alpha:
            The fraction of the stock gap ordered per week.

        beta:
            The weight of the supply line in the stock gap.

        dispatch_time:
            The time over which the echelon ships its backlog.

        mail_delay:
            The average time an order of the echelon takes to reach its supplier.

        shipping_delay:
            The average time a shipment takes to reach the echelon from its supplier.

        production_delay:
            The average time the brewery takes to brew an order, through a third-order delay.

    Examples:
        >>> from skcomplex.systems.economics.markets import FactoryElement
        >>> FactoryElement('factory').production_delay
        3.0
    """

    def __init__(
        self,
        label: str,
        *,
        inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 12.0,
        in_transit: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 8.0,
        backlog: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        expected: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
        supply_line: Annotated[float, RealSet.closed_open(0, oo)] = 16.0,
        desired: float = 13.44,
        theta: Annotated[float, RealSet.closed_open(0, oo)] = 0.36,
        alpha: Annotated[float, RealSet.closed_open(0, oo)] = 0.26,
        beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.34,
        dispatch_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
        mail_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
        shipping_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
        production_delay: Annotated[float, RealSet.open(0, oo)] = 3.0,
    ) -> None:
        super().__init__(
            label,
            inventory=inventory,
            in_transit=in_transit,
            backlog=backlog,
            expected=expected,
            supply_line=supply_line,
            desired=desired,
            theta=theta,
            alpha=alpha,
            beta=beta,
            dispatch_time=dispatch_time,
            mail_delay=mail_delay,
            shipping_delay=shipping_delay,
        )
        self.production_delay = production_delay

class EchelonInteraction(Interaction):
    """Shipping of the backlog of an echelon of a supply chain and the decay of its expected demand.

    The echelon ships its backlog over the dispatch time, limited by its inventory, and its expected demand decays at
    the rate `theta`, while the orders that reach it raise both.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the echelon.

    Examples:
        >>> from skcomplex.systems.economics.markets import EchelonInteraction
        >>> EchelonInteraction('retailer_shipping', target='retailer').target
        'retailer'
    """

    law_classes = (RateLaw,)

    def __init__(self, label: str, *, target: Role) -> None:
        super().__init__(label)
        self.target = target

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the shipping of the backlog and the decay of the expectation as the laws.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        echelon = context.target
        self.laws_: list[BaseLaw] = [
            RateLaw(echelon.backlog, -EchelonElement._get_shipments(echelon)),
            RateLaw(echelon.expected, -echelon.theta * echelon.expected),
        ]

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 SupplyLinkInteraction(Interaction):
    """Link of a supply chain.

    It ships beer from the upstream echelon to the downstream echelon. The shipments flow from the inventory of the
    upstream echelon to the beer in transit to the downstream echelon, and the arrivals, after a third-order delay of
    the shipping delay of the downstream echelon, flow on to its inventory.

    Args:
        label:
            The label of the link.

        downstream:
            The path of the echelon that orders.

        upstream:
            The path of the echelon that ships.

    Examples:
        >>> from skcomplex.systems.economics.markets import SupplyLinkInteraction
        >>> SupplyLinkInteraction('link', downstream='retailer', upstream='wholesaler').upstream
        'wholesaler'
    """

    def __init__(
        self,
        label: str,
        *,
        downstream: Role,
        upstream: Role,
    ) -> None:
        super().__init__(label)
        self.downstream = downstream
        self.upstream = upstream

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the shipments and their arrivals as the flows.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        upstream, downstream = context.upstream, context.downstream
        self.laws_: list[BaseLaw] = [
            RateLaw(
                {upstream.inventory: -1, downstream.in_transit: +1},
                EchelonElement._get_shipments(upstream),
                label='shipments',
            ),
            RateLaw(
                {downstream.in_transit: -1, downstream.inventory: +1},
                SupplyLinkInteraction._get_arrivals(upstream, downstream),
                label='arrivals',
            ),
        ]

    @staticmethod
    def _get_arrivals(upstream: SimpleNamespace, downstream: SimpleNamespace) -> Expression:
        """Return the arrivals at the downstream echelon.

        They are the shipments after a third-order shipping delay.
        """
        return distributed_delay(EchelonElement._get_shipments(upstream), order=3, time=downstream.shipping_delay)

class RetailDemandInteraction(Interaction):
    """Customers of a supply chain, who take the shipments of the retailer.

    The sales are a flow out of the inventory of the retailer.

    Args:
        label:
            The label of the customers.

        retailer:
            The path of the retailer.

    Examples:
        >>> from skcomplex.systems.economics.markets import RetailDemandInteraction
        >>> RetailDemandInteraction('customers', retailer='retailer').retailer
        'retailer'
    """

    def __init__(
        self,
        label: str,
        *,
        retailer: Role,
    ) -> None:
        super().__init__(label)
        self.retailer = retailer

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the sales out of the inventory of the retailer as the flow.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        retailer = context.retailer
        self.laws_: list[BaseLaw] = [
            RateLaw({retailer.inventory: -1}, EchelonElement._get_shipments(retailer), label='sales'),
        ]

class BreweryInteraction(Interaction):
    """Brewery of a supply chain.

    It brews the orders of the factory over its production delay. The brewing is a flow `starts` into the beer in
    production at the factory and a flow `completions` on to its inventory.

    Args:
        label:
            The label of the brewery.

        factory:
            The path of the factory.

    Examples:
        >>> from skcomplex.systems.economics.markets import BreweryInteraction
        >>> BreweryInteraction('brewery', factory='factory').factory
        'factory'
    """

    def __init__(
        self,
        label: str,
        *,
        factory: Role,
    ) -> None:
        super().__init__(label)
        self.factory = factory

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the starts and the completions of the brews as the flows.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        factory = context.factory
        self.laws_: list[BaseLaw] = [
            RateLaw({factory.in_transit: +1}, BreweryInteraction._get_orders(factory), label='starts'),
            RateLaw(
                {factory.in_transit: -1, factory.inventory: +1},
                BreweryInteraction._get_completions(factory),
                label='completions',
            ),
        ]

    @staticmethod
    def _get_orders(echelon: SimpleNamespace) -> Expression:
        """Return the orders of an echelon by Sterman's anchoring and adjustment rule.

        They are never negative.
        """
        effective = echelon.inventory - echelon.backlog
        orders = echelon.expected + echelon.alpha * (echelon.desired - effective - echelon.beta * echelon.supply_line)
        return maximum(orders, 0)

    @staticmethod
    def _get_completions(factory: SimpleNamespace) -> Expression:
        """Return the brews completed for the factory.

        They are its orders after a third-order production delay.
        """
        return distributed_delay(BreweryInteraction._get_orders(factory), order=3, time=factory.production_delay)

Equations

The equations are those that symbolic returns for the system with its default parameters.

retailer.inventory: diff(inventory_retailer(t), t) == 3*_material_delay3_0_wholesaler_to_retailer_2/shipping_delay_retailer - where(inventory_retailer(t) < backlog_retailer(t), inventory_retailer(t), backlog_retailer(t))/dispatch_time_retailer
retailer.in_transit: diff(in_transit_retailer(t), t) == -3*_material_delay3_0_wholesaler_to_retailer_2/shipping_delay_retailer + where(inventory_wholesaler(t) < backlog_wholesaler(t), inventory_wholesaler(t), backlog_wholesaler(t))/dispatch_time_wholesaler
retailer.backlog: diff(backlog_retailer(t), t) == demand_retailer - where(inventory_retailer(t) < backlog_retailer(t), inventory_retailer(t), backlog_retailer(t))/dispatch_time_retailer + where(t >= step_time_retailer, demand_step_retailer, 0)
retailer.expected: diff(expected_retailer(t), t) == (demand_retailer + where(t >= step_time_retailer, demand_step_retailer, 0))*theta_retailer - theta_retailer*expected_retailer(t)
retailer.supply_line: diff(supply_line_retailer(t), t) == -3*_material_delay3_0_retailer_supply_line_2/shipping_delay_retailer + where(0 > -(beta_retailer*supply_line_retailer(t) - desired_retailer - backlog_retailer(t) + inventory_retailer(t))*alpha_retailer + expected_retailer(t), 0, -(beta_retailer*supply_line_retailer(t) - desired_retailer - backlog_retailer(t) + inventory_retailer(t))*alpha_retailer + expected_retailer(t))
wholesaler.inventory: diff(inventory_wholesaler(t), t) == 3*_material_delay3_0_distributor_to_wholesaler_2/shipping_delay_wholesaler - where(inventory_wholesaler(t) < backlog_wholesaler(t), inventory_wholesaler(t), backlog_wholesaler(t))/dispatch_time_wholesaler
wholesaler.in_transit: diff(in_transit_wholesaler(t), t) == -3*_material_delay3_0_distributor_to_wholesaler_2/shipping_delay_wholesaler + where(inventory_distributor(t) < backlog_distributor(t), inventory_distributor(t), backlog_distributor(t))/dispatch_time_distributor
wholesaler.backlog: diff(backlog_wholesaler(t), t) == 3*_material_delay3_0_wholesaler_backlog_2/mail_delay_retailer - where(inventory_wholesaler(t) < backlog_wholesaler(t), inventory_wholesaler(t), backlog_wholesaler(t))/dispatch_time_wholesaler
wholesaler.expected: diff(expected_wholesaler(t), t) == -theta_wholesaler*expected_wholesaler(t) + 3*_material_delay3_0_wholesaler_expected_2*theta_wholesaler/mail_delay_retailer
wholesaler.supply_line: diff(supply_line_wholesaler(t), t) == -3*_material_delay3_0_wholesaler_supply_line_2/shipping_delay_wholesaler + where(0 > -(beta_wholesaler*supply_line_wholesaler(t) - desired_wholesaler - backlog_wholesaler(t) + inventory_wholesaler(t))*alpha_wholesaler + expected_wholesaler(t), 0, -(beta_wholesaler*supply_line_wholesaler(t) - desired_wholesaler - backlog_wholesaler(t) + inventory_wholesaler(t))*alpha_wholesaler + expected_wholesaler(t))
distributor.inventory: diff(inventory_distributor(t), t) == 3*_material_delay3_0_factory_to_distributor_2/shipping_delay_distributor - where(inventory_distributor(t) < backlog_distributor(t), inventory_distributor(t), backlog_distributor(t))/dispatch_time_distributor
distributor.in_transit: diff(in_transit_distributor(t), t) == -3*_material_delay3_0_factory_to_distributor_2/shipping_delay_distributor + where(inventory_factory(t) < backlog_factory(t), inventory_factory(t), backlog_factory(t))/dispatch_time_factory
distributor.backlog: diff(backlog_distributor(t), t) == 3*_material_delay3_0_distributor_backlog_2/mail_delay_wholesaler - where(inventory_distributor(t) < backlog_distributor(t), inventory_distributor(t), backlog_distributor(t))/dispatch_time_distributor
distributor.expected: diff(expected_distributor(t), t) == -theta_distributor*expected_distributor(t) + 3*_material_delay3_0_distributor_expected_2*theta_distributor/mail_delay_wholesaler
distributor.supply_line: diff(supply_line_distributor(t), t) == -3*_material_delay3_0_distributor_supply_line_2/shipping_delay_distributor + where(0 > -(beta_distributor*supply_line_distributor(t) - desired_distributor - backlog_distributor(t) + inventory_distributor(t))*alpha_distributor + expected_distributor(t), 0, -(beta_distributor*supply_line_distributor(t) - desired_distributor - backlog_distributor(t) + inventory_distributor(t))*alpha_distributor + expected_distributor(t))
factory.inventory: diff(inventory_factory(t), t) == 3*_material_delay3_0_brewery_2/production_delay_factory - where(inventory_factory(t) < backlog_factory(t), inventory_factory(t), backlog_factory(t))/dispatch_time_factory
factory.in_transit: diff(in_transit_factory(t), t) == -3*_material_delay3_0_brewery_2/production_delay_factory + where(0 > -(beta_factory*supply_line_factory(t) - desired_factory - backlog_factory(t) + inventory_factory(t))*alpha_factory + expected_factory(t), 0, -(beta_factory*supply_line_factory(t) - desired_factory - backlog_factory(t) + inventory_factory(t))*alpha_factory + expected_factory(t))
factory.backlog: diff(backlog_factory(t), t) == 3*_material_delay3_0_factory_backlog_2/mail_delay_distributor - where(inventory_factory(t) < backlog_factory(t), inventory_factory(t), backlog_factory(t))/dispatch_time_factory
factory.expected: diff(expected_factory(t), t) == -theta_factory*expected_factory(t) + 3*_material_delay3_0_factory_expected_2*theta_factory/mail_delay_distributor
factory.supply_line: diff(supply_line_factory(t), t) == -3*_material_delay3_0_factory_supply_line_2/production_delay_factory + where(0 > -(beta_factory*supply_line_factory(t) - desired_factory - backlog_factory(t) + inventory_factory(t))*alpha_factory + expected_factory(t), 0, -(beta_factory*supply_line_factory(t) - desired_factory - backlog_factory(t) + inventory_factory(t))*alpha_factory + expected_factory(t))