Skip to content

Ridesharing

Riders who request trips on a city grid and cabs sent to them.

  • Class: RidesharingSystem
  • Import: from skcomplex.systems.engineering.traffic import RidesharingSystem
  • Field: engineering/traffic
  • Topics: ridesharing, agents, matching, queues, grid
  • References:
    • Carmichael and Hadzikadic 2019 ch. 7

Use this system

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

from skcomplex.systems.engineering.traffic import RidesharingSystem

trajectory = RidesharingSystem().prepare().simulate()

Parameters

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

Parameter Default
n_cabs 30
demand 1.0
width 30
height 30
base_fare 2.0
block_fare 0.5
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 lattice
Laws update
Randomness stochastic
Domains integer, real
Structure variable membership

Class

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

class RidesharingSystem(BaseSystem):
    """Riders who request trips on a city grid and cabs sent to them.

    A stable matching sends the cabs. Every step new riders appear at random cells with random destinations, and the
    dispatch matches the waiting riders with the idle cabs by a stable matching in which riders prefer nearer cabs and
    cabs prefer riders who waited longer. Every cab drives one block a step to its rider, collects the fare, and drives
    the rider to its destination. While the demand stays below the trips the fleet can serve, riders wait about as long
    as a cab takes to reach them. As the demand approaches that capacity, every cab is busy, the queue of waiting riders
    grows, and the waiting time rises steeply, as in a queue near saturation.

    The system has the groups `riders` and `cabs`, the arrivals `arrival`, and the matching `dispatch`.

    Args:
        n_cabs:
            The number of cabs.

        demand:
            The mean number of new riders in a step.

        width:
            The number of columns of the grid.

        height:
            The number of rows of the grid.

        base_fare:
            The fare of every trip.

        block_fare:
            The fare per block of a trip.

        random_state:
            The seed or generator of the cells of the cabs.

        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 agent solver with the phases of arrivals, dispatch, and
            driving.

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

    Examples:
        >>> from skcomplex.systems.engineering.traffic import RidesharingSystem
        >>> [group.size for group in RidesharingSystem(5).prepare().system_.elements]
        [1, 5]
    """

    field = 'engineering/traffic'
    topics = ('ridesharing', 'agents', 'matching', 'queues', 'grid')
    references = ('Carmichael and Hadzikadic 2019 ch. 7',)
    until = 200
    observables = (
        Observable('queue', group='riders', variable='waited', reduce='count'),
        Observable('mean_wait', group='riders', variable='waited', reduce='mean'),
        Observable('utilisation', _get_busy, group='cabs', reduce='mean'),
    )

    def __init__(
        self,
        n_cabs: int = 30,
        *,
        demand: float = 1.0,
        width: int = 30,
        height: int = 30,
        base_fare: float = 2.0,
        block_fare: float = 0.5,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_cabs = n_cabs
        self.demand = demand
        self.width = width
        self.height = height
        self.base_fare = base_fare
        self.block_fare = block_fare
        self.random_state = random_state

    @staticmethod
    def _wait(agent: RiderView, system: SystemView) -> None:
        """Count one more step of waiting of a rider."""
        agent.waited += 1.0

    @staticmethod
    def _get_nearness(rider: object, cab: object) -> float:
        """Return the preference of a rider for a cab, higher for a cab fewer blocks away."""
        if not isinstance(rider, RiderView) or not isinstance(cab, CabView):
            error_msg = f'A rider ranks cabs, but got {rider!r} and {cab!r}.'
            raise ValidationError(error_msg)
        cells = CabDrivingInteraction._get_cell(rider.location), CabDrivingInteraction._get_cell(cab.location)
        return -float(CabDrivingInteraction._get_blocks(*cells))

    @staticmethod
    def _get_patience(cab: object, rider: object) -> float:
        """Return the preference of a cab for a rider.

        It is higher for a rider who waited longer.
        """
        if not isinstance(rider, RiderView):
            error_msg = f'A cab ranks riders, but got {rider!r}.'
            raise ValidationError(error_msg)
        return rider.waited

    @staticmethod
    def _dispatch(ride: MatchSpec, system: SystemView) -> None:
        """Send the cab of a ride to its rider."""
        del system
        rider, cab = ride.requester, ride.provider
        if not isinstance(rider, RiderView) or not isinstance(cab, CabView):
            error_msg = f'A ride matches a rider with a cab, but got {rider!r} and {cab!r}.'
            raise ValidationError(error_msg)
        new_target_x_value, new_target_y_value = CabDrivingInteraction._get_cell(rider.location)
        cab.target_x = new_target_x_value
        cab.target_y = new_target_y_value
        new_destination_x, new_destination_y = rider.destination_x, rider.destination_y
        cab.destination_x = new_destination_x
        cab.destination_y = new_destination_y
        cab.rider = float(rider.id)
        cab.task = PICKING_UP

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the components of the system built from its model parameters."""
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        cells = rng.integers((self.width, self.height), size=(self.n_cabs + 1, 2))
        grid = LatticeSpace((self.width, self.height), boundary='fixed', metric='manhattan')
        riders = RiderElement(
            'riders',
            destination_x=float(rng.integers(self.width)),
            destination_y=float(rng.integers(self.height)),
            values={'x': [int(cells[0, 0])], 'y': [int(cells[0, 1])]},
            size=1,
            space=grid,
        )
        cabs = CabElement(
            'cabs',
            values={'x': cells[1:, 0].astype(int), 'y': cells[1:, 1].astype(int)},
            size=self.n_cabs,
            space=grid,
        )
        self.system_ = System(
            self.label,
            elements=[riders, cabs],
            interactions=[
                ArrivalInteraction(
                    'arrival',
                    target='riders',
                    demand=self.demand,
                    width=self.width,
                    height=self.height,
                ),
                Interaction(
                    'waiting',
                    roles={'target': 'riders'},
                    laws=lambda s: [UpdateLaw(s.target, self._wait, phase='drive')],
                ),
                MatchingInteraction(
                    'dispatch',
                    requesters='riders',
                    providers='cabs',
                    rule=StableMatchingSpec(
                        requester_preference=self._get_nearness,
                        provider_preference=self._get_patience,
                    ),
                    quantity='seats',
                    phase='dispatch',
                    on_match=self._dispatch,
                ),
                CabDrivingInteraction(
                    'drive',
                    target='cabs',
                    riders='riders',
                    base_fare=self.base_fare,
                    block_fare=self.block_fare,
                ),
            ],
            space=grid,
            solver=MesaSolver(phases=[PhaseSpec('arrival'), PhaseSpec('dispatch'), PhaseSpec('drive')]),
        )

Components

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

Elements:

Interactions:

  • ArrivalInteraction, from Interaction, through the shared recipe BirthDeathInteraction
  • Interaction
  • MatchingInteraction, from Interaction, through the shared recipe MatchingInteraction
  • CabDrivingInteraction, from Interaction
class RiderElement(Element):
    """Rider who waits at a cell for a cab to a destination.

    It pays the fare when the cab picks it up.

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

        destination_x:
            The column of the destination.

        destination_y:
            The row of the destination.

        waited:
            The number of steps the rider has waited.

        seats:
            The seats the rider still requests, one until a cab is on its way and zero after.

        money:
            The money of the rider.

        values:
            Further values by name, such as the cell `x` and `y` of every member.

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

        space:
            The grid whose axes `x` and `y` place the members, or `None` for none.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import RiderElement
        >>> RiderElement('riders', money=50.0, size=2).size
        2
    """

    visual = VisualSpec('agents', {'color_by': 'waited'})

    def __init__(
        self,
        label: str,
        *,
        destination_x: Annotated[float, NN] = 0.0,
        destination_y: Annotated[float, NN] = 0.0,
        waited: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        seats: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        money: float = 100.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.destination_x = destination_x
        self.destination_y = destination_y
        self.waited = waited
        self.seats = seats
        self.money = money

class CabElement(Element):
    """Cab that drives a rider to its destination for a fare.

    It drives one block a step to its rider, collects the fare, and drives the rider to its destination, by the rule of
    `CabDrivingInteraction`.

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

        task:
            0 when idle, 1 on the way to a rider, and 2 on the way to a destination.

        target_x:
            The column of the cell the cab drives to.

        target_y:
            The row of the cell the cab drives to.

        destination_x:
            The column of the destination of the rider.

        destination_y:
            The row of the destination of the rider.

        rider:
            The id of the rider the cab is sent to.

        seats:
            The free seats of the cab, one when idle and zero on a trip.

        money:
            The fares the cab collected.

        values:
            Further values by name, such as the cell `x` and `y` of every member.

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

        space:
            The grid whose axes `x` and `y` place the members, or `None` for none.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import CabElement
        >>> CabElement('cabs', size=3).size
        3
    """

    visual = VisualSpec('agents', {'color_by': 'task', 'color_range': (0.0, 2.0)})

    def __init__(
        self,
        label: str,
        *,
        task: Annotated[float, NN] = IDLE,
        target_x: Annotated[float, NN] = 0.0,
        target_y: Annotated[float, NN] = 0.0,
        destination_x: Annotated[float, NN] = 0.0,
        destination_y: Annotated[float, NN] = 0.0,
        rider: float = -1.0,
        seats: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        money: float = 0.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.task = task
        self.target_x = target_x
        self.target_y = target_y
        self.destination_x = destination_x
        self.destination_y = destination_y
        self.rider = rider
        self.seats = seats
        self.money = money

class ArrivalInteraction(BirthDeathInteraction):
    """Arrival of new riders at random cells with random destinations.

    It is a life cycle of arrivals only. Every step a Poisson number of riders, with mean `demand`, appear at random
    cells with random destinations.

    Args:
        label:
            The label of the arrivals.

        target:
            The path of the group of riders.

        demand:
            The mean number of new riders in a step.

        width:
            The number of columns of the grid.

        height:
            The number of rows of the grid.

        phase:
            The phase the riders arrive in.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import ArrivalInteraction
        >>> ArrivalInteraction('arrival', target='riders').reports
        ('births', 'deaths', 'arrivals')
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        demand: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        width: int = 30,
        height: int = 30,
        phase: str | None = 'arrival',
    ) -> None:
        super().__init__(
            label,
            target=target,
            placement=self.place,
            values=self.destine,
            arrival=self.expect,
            phase=phase,
        )
        self.demand = demand
        self.width = width
        self.height = height

    def expect(self, system: SystemView) -> float:
        """Return the mean number of new riders in a step.

        Args:
            system:
                The system view of the arrivals.

        Returns:
            demand:
                The demand.
        """
        return system.get_parameter('demand')

    def place(self, agent: RiderView | None, system: SystemView) -> tuple[int, int]:
        """Return a random cell of the grid for a new rider.

        Args:
            agent:
                The parent, `None` for an arrival.

            system:
                The system view of the arrivals.

        Returns:
            cell:
                The coordinates of the cell.
        """
        x, y = system.rng.integers((self.width, self.height))
        return int(x), int(y)

    def destine(self, agent: RiderView | None, system: SystemView) -> dict[str, object]:
        """Return a random destination on the grid for a new rider.

        Args:
            agent:
                The parent, `None` for an arrival.

            system:
                The system view of the arrivals.

        Returns:
            values:
                The coordinates of the destination by state name.
        """
        to_x, to_y = system.rng.integers((self.width, self.height))
        return {'destination_x': float(to_x), 'destination_y': float(to_y)}

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 MatchingInteraction[SystemT: SystemViewProtocol](Interaction):
    """An interaction that matches requesters with providers and settles every match.

    Requesters state in their states the highest value they accept, `reserve`, the quantity they want, `quantity`, and
    the most value they can give, `cap`. Providers state the lowest value they accept and the quantity they offer. A
    name given as a pair names the state of the requesters first and of the providers second. The `rule` is a spec of
    the algorithm that pairs the offers, such as `RandomSearchSpec`, `QueueSpec`, `BatchMatchingSpec`, or
    `StableMatchingSpec`.

    Every match lowers the quantities of both sides and moves every state of `transfers`: a negative sign moves `value *
    quantity` from the requester to the provider, and a positive sign moves `quantity` from the provider to the
    requester, so the totals stay the same. `on_match(match, system)` adds any other effect. The matching runs once per
    round of its phase and reports `<label>.value`, the clearing value weighted by quantity, `<label>.volume`, and
    `<label>.unmatched`.

    Unlike a labelled `RateLaw` flow, which moves amounts between given pairs, it first forms the pairs by a rule,
    through `pairs` of the core, and then transfers. Choose it when who trades with whom and at what value are part of
    the model.

    It appears in many fields. Buyers and sellers trade goods, workers and firms agree on wages, borrowers and banks
    agree on loans, and patients and hospitals are matched.

    Args:
        label:
            The label of the matching.

        requesters:
            The path of the group of requesters.

        providers:
            The path of the group of providers.

        rule:
            The spec of the algorithm that matches the members, such as `ContinuousMatchingSpec()`, or a function
            `rule(requesters, providers, rng, capacity)` of the agents with a positive quantity that returns their
            pairs, which match at the midpoint of both reserves. A `PartnerSpec` picks among the providers that still
            offer a quantity at a reserve the requester accepts, in random order of the requesters, and settles at
            the midpoint, or at the value of a `PartnerMatchingSpec`.

        reserve:
            The state with the reserve of both sides, or a pair of the requesters' and the providers' states. An agent
            without the default state `'reserve'` has no reserve as a requester and the reserve 0 as a provider.

        quantity:
            The state with the quantity of both sides, or a pair of the requesters' and the providers' states. An
            agent without the default state `'quantity'` offers the quantity 1.

        cap:
            The state of a requester with the most value it can give. A requester without the default state
            `'cap'` has no reserve on what it gives.

        transfers:
            The states every match moves, each with the sign `-1` for a move from the requester to the provider or
            `1` for a move from the provider to the requester.

        phase:
            The phase the matching runs in, or `None` for the default phase.

        on_match:
            A function of every match and the system view, run after the transfers, or `None`.

    Raises:
        ValidationError:
            A transfer has a sign other than `-1` or `1`, or the rule is neither a matching spec nor a function, or
            it is invalid, raised by `prepare`, or an agent lacks a state other than a default one that names its
            reserve, quantity, or cap, raised by `run`.

    Examples:
        >>> from skcomplex.systems.general.matching import MatchingInteraction
        >>> from skcomplex.systems.general.matching import ContinuousMatchingSpec
        >>> matching = MatchingInteraction(
        ...     'exchange',
        ...     requesters='traders',
        ...     providers='traders',
        ...     rule=ContinuousMatchingSpec(),
        ...     reserve=('bid', 'ask'),
        ... )
        >>> matching.reports
        ('value', 'volume', 'unmatched')
    """

    reports: ClassVar[tuple[str, ...]] = ('value', 'volume', 'unmatched')

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

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

        Every rule draws but a queue served in a fixed order.
        """
        return super()._get_draws() or not (isinstance(self.rule, QueueSpec) and self.rule.order != 'random')

    def __init__(
        self,
        label: str,
        *,
        requesters: Role,
        providers: Role,
        rule: MatchingRule | Pairing = RandomSearchSpec(),
        reserve: str | tuple[str, str] = 'reserve',
        quantity: str | tuple[str, str] = 'quantity',
        cap: str = 'cap',
        transfers: Sequence[tuple[str, int]] = (),
        phase: str | None = None,
        on_match: Callable[[MatchSpec, SystemT], None] | None = None,
    ) -> None:
        super().__init__(label)
        self.requesters = requesters
        self.providers = providers
        self.rule = rule
        self.reserve = reserve
        self.quantity = quantity
        self.cap = cap
        self.transfers = transfers
        self.phase = phase
        self.on_match = on_match

    @staticmethod
    def _get_sides(name: str | tuple[str, str]) -> tuple[str, str]:
        """Return the state of the requesters and of the providers of a name.

        The name is given once or as a pair.
        """
        return (name, name) if isinstance(name, str) else name

    def _read(self, agent: AgentViewProtocol, name: str, default: float) -> float:
        """Return a state of an agent.

        It returns a default when the agent lacks a state of a default name.
        """
        if hasattr(agent, name):
            return float(getattr(agent, name))
        if name in DEFAULT_STATES:
            return default
        error_msg = (
            f'The agents of {agent.group!r} have no state {name!r}, which the matching {self.label!r} reads. Declare '
            f'the state on their element, or name one of their states.'
        )
        raise ValidationError(error_msg)

    @staticmethod
    def _get_affordable(offer: SimpleNamespace, value: float) -> float:
        """Return the quantity a participant can still match at a value.

        The value is within its cap.
        """
        if value <= 0:
            return float(offer.quantity)
        return max(0.0, min(offer.quantity, offer.cap / value))

    @staticmethod
    def _record_match(
        trades: list[MatchSpec],
        requester: SimpleNamespace,
        provider: SimpleNamespace,
        value: float,
    ) -> None:
        """Record a match of the largest quantity both sides can match at a value.

        It also lowers both offers.
        """
        quantity = min(MatchingInteraction._get_affordable(requester, value), provider.quantity)
        if quantity <= 0:
            return
        requester.quantity -= quantity
        requester.cap -= quantity * value
        provider.quantity -= quantity
        trades.append(MatchSpec(requester.agent, provider.agent, quantity, value))

    @staticmethod
    def _get_value(requester: SimpleNamespace, provider: SimpleNamespace, clearing: str) -> float:
        """Return the value of a match under a clearing rule."""
        if clearing == 'requester':
            return requester.reserve
        if clearing == 'provider':
            return provider.reserve
        return (requester.reserve + provider.reserve) / 2

    @staticmethod
    def _get_order(offers: list[SimpleNamespace], order: str, rng: np.random.Generator) -> list[SimpleNamespace]:
        """Return offers in random order, by decreasing reserve, or in order of creation."""
        if order == 'reserve':
            return sorted(offers, key=lambda item: (-item.reserve, item.agent.id))
        if order == 'sequential':
            return sorted(offers, key=lambda item: item.agent.id)
        return [offers[index] for index in rng.permutation(len(offers))]

    def _get_offers(self, system: SystemT) -> tuple[list[SimpleNamespace], list[SimpleNamespace]]:
        """Return the offers of the requesters and providers with a positive quantity.

        Matches lower the quantity.
        """
        reserves, quantities = self._get_sides(self.reserve), self._get_sides(self.quantity)
        requesters = [
            SimpleNamespace(
                agent=agent,
                reserve=self._read(agent, reserves[0], math.inf),
                quantity=self._read(agent, quantities[0], 1.0),
                cap=self._read(agent, self.cap, math.inf),
            )
            for agent in system.get_agents(self._get_role('requesters'))
        ]
        providers = [
            SimpleNamespace(
                agent=agent,
                reserve=self._read(agent, reserves[1], 0.0),
                quantity=self._read(agent, quantities[1], 1.0),
                cap=math.inf,
            )
            for agent in system.get_agents(self._get_role('providers'))
        ]
        return [offer for offer in requesters if offer.quantity > 0], [
            offer for offer in providers if offer.quantity > 0
        ]

    def _match_random_search(
        self,
        rule: RandomSearchSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches of requesters in random order that meet random providers.

        They match on crossing reserves.
        """
        trades: list[MatchSpec] = []
        for index in rng.permutation(len(requesters)):
            requester = requesters[index]
            for _ in range(rule.tries):
                available = [provider for provider in providers if provider.quantity > 0]
                if requester.quantity <= 0 or not available:
                    break
                provider = available[int(rng.integers(len(available)))]
                if provider.reserve <= requester.reserve:
                    self._record_match(trades, requester, provider, self._get_value(requester, provider, rule.value))
        return trades

    @staticmethod
    def _choose_partner(
        rule: PartnerSwitchSpec,
        best: SimpleNamespace,
        current: SimpleNamespace | None,
        rng: np.random.Generator,
    ) -> SimpleNamespace:
        """Return the provider a requester matches with.

        It is its current partner or the best of its sample.
        """
        if current is None or current.quantity <= 0:
            return best
        if best.reserve >= current.reserve:
            return current
        if best.reserve <= 0:
            return best
        switching = 1 - math.exp(rule.intensity * (best.reserve - current.reserve) / best.reserve)
        return best if rng.random() < switching else current

    def _match_partner_switch(
        self,
        rule: PartnerSwitchSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches of every requester with its kept or new partner.

        The matches are at the partner's reserve.
        """
        trades: list[MatchSpec] = []
        by_id = {provider.agent.id: provider for provider in providers}
        for index in rng.permutation(len(requesters)):
            requester = requesters[index]
            available = [provider for provider in providers if provider.quantity > 0]
            if not available:
                break
            picks = rng.choice(len(available), size=min(rule.sample, len(available)), replace=False)
            best = min((available[int(pick)] for pick in picks), key=lambda provider: provider.reserve)
            current = by_id.get(int(getattr(requester.agent, rule.partner, -1)))
            chosen = self._choose_partner(rule, best, current, rng)
            if hasattr(requester.agent, rule.partner):
                setattr(requester.agent, rule.partner, chosen.agent.id)
            if chosen.reserve <= requester.reserve:
                self._record_match(trades, requester, chosen, chosen.reserve)
        return trades

    def _match_queue(
        self,
        rule: QueueSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches of the queue of requesters served by the lowest providers.

        The providers serve at their reserves.
        """
        queue = self._get_order(requesters, rule.order, rng)
        stock = sorted(providers, key=lambda provider: provider.reserve)
        trades: list[MatchSpec] = []
        for requester in queue:
            for provider in stock:
                if requester.quantity <= 0 or provider.reserve > requester.reserve:
                    break
                if provider.quantity > 0:
                    self._record_match(trades, requester, provider, provider.reserve)
        return trades

    @staticmethod
    def _adjust(
        rule: IterativeMatchingSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        start: float,
    ) -> float:
        """Return the value the tâtonnement reaches from a start."""
        value = start
        for _ in range(rule.iterations):
            requested = sum(
                MatchingInteraction._get_affordable(requester, value)
                for requester in requesters
                if requester.reserve >= value
            )
            provided = sum(provider.quantity for provider in providers if provider.reserve <= value)
            total = requested + provided
            if not total or abs(requested - provided) / total < rule.tolerance:
                break
            value *= 1 + rule.adjustment * (requested - provided) / total
        return value

    def _match_at(
        self,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        value: float,
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches at one value between the willing requesters and providers.

        They match in random order.
        """
        trades: list[MatchSpec] = []
        willing_requesters = self._get_order([item for item in requesters if item.reserve >= value], 'random', rng)
        willing_providers = self._get_order([item for item in providers if item.reserve <= value], 'random', rng)
        pairs = iter(willing_providers)
        provider = next(pairs, None)
        for requester in willing_requesters:
            while provider is not None and MatchingInteraction._get_affordable(requester, value) > 0:
                self._record_match(trades, requester, provider, value)
                if provider.quantity <= 0:
                    provider = next(pairs, None)
        return trades

    def _match_iterative(
        self,
        rule: IterativeMatchingSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
        storage: MutableMapping[str, object],
    ) -> list[MatchSpec]:
        """Return the matches at the value of the tâtonnement.

        The tâtonnement starts from the value of the last clearing.
        """
        reserves = [offer.reserve for offer in requesters + providers if offer.reserve > 0]
        if not reserves:
            return []
        last = storage.get('value')
        start = last if isinstance(last, float) and math.isfinite(last) and last > 0 else float(np.median(reserves))
        value = self._adjust(rule, requesters, providers, start)
        storage['value'] = value
        return self._match_at(requesters, providers, value, rng)

    @staticmethod
    def _arrange(
        rule: ContinuousMatchingSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[tuple[SimpleNamespace, bool]]:
        """Return the offers in their order of arrival, each with whether it is a request."""
        offers = [(offer, True) for offer in requesters] + [(offer, False) for offer in providers]
        if rule.arrival == 'sequential':
            return sorted(offers, key=lambda item: item[0].agent.id)
        return [offers[index] for index in rng.permutation(len(offers))]

    def _match_continuous(
        self,
        rule: ContinuousMatchingSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches of every arriving offer with the best resting offers.

        The resting offers are those of the other side.
        """
        requests: list[tuple[float, int, SimpleNamespace]] = []
        provisions: list[tuple[float, int, SimpleNamespace]] = []
        trades: list[MatchSpec] = []
        for time, (offer, is_request) in enumerate(self._arrange(rule, requesters, providers, rng)):
            if is_request:
                while (
                    provisions
                    and provisions[0][0] <= offer.reserve
                    and MatchingInteraction._get_affordable(offer, provisions[0][0]) > 0
                ):
                    resting = provisions[0][2]
                    self._record_match(trades, offer, resting, resting.reserve)
                    if resting.quantity <= 0:
                        heapq.heappop(provisions)
                if MatchingInteraction._get_affordable(offer, offer.reserve) > 0:
                    heapq.heappush(requests, (-offer.reserve, time, offer))
                continue
            while requests and -requests[0][0] >= offer.reserve and offer.quantity > 0:
                resting = requests[0][2]
                self._record_match(trades, resting, offer, resting.reserve)
                if MatchingInteraction._get_affordable(resting, resting.reserve) <= 0:
                    heapq.heappop(requests)
            if offer.quantity > 0:
                heapq.heappush(provisions, (offer.reserve, time, offer))
        return trades

    @staticmethod
    def _get_requested(offer: SimpleNamespace) -> float:
        """Return the quantity a requester can match at its own reserve."""
        return (
            offer.quantity
            if not math.isfinite(offer.cap)
            else MatchingInteraction._get_affordable(offer, offer.reserve)
        )

    def _get_pair(
        self,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
    ) -> tuple[list[tuple[SimpleNamespace, SimpleNamespace]], float]:
        """Return the pairs of crossing offers in order of their reserves.

        It also returns the value of the last pair.
        """
        ranked_requesters = sorted(requesters, key=lambda offer: (-offer.reserve, offer.agent.id))
        ranked_providers = sorted(providers, key=lambda offer: (offer.reserve, offer.agent.id))
        left = {id(offer): self._get_requested(offer) for offer in ranked_requesters}
        offered = {id(offer): offer.quantity for offer in ranked_providers}
        pairs: list[tuple[SimpleNamespace, SimpleNamespace]] = []
        marginal = math.nan
        requester_iter, provider_iter = iter(ranked_requesters), iter(ranked_providers)
        requester, provider = next(requester_iter, None), next(provider_iter, None)
        while requester is not None and provider is not None and requester.reserve >= provider.reserve:
            pairs.append((requester, provider))
            marginal = (requester.reserve + provider.reserve) / 2
            quantity = min(left[id(requester)], offered[id(provider)])
            left[id(requester)] -= quantity
            offered[id(provider)] -= quantity
            if left[id(requester)] <= 0:
                requester = next(requester_iter, None)
            if offered[id(provider)] <= 0:
                provider = next(provider_iter, None)
        return pairs, marginal

    def _match_batch(self, requesters: list[SimpleNamespace], providers: list[SimpleNamespace]) -> list[MatchSpec]:
        """Return the matches of the crossing offers at the midpoint of the last pair.

        The last pair is the last crossing pair.
        """
        pairs, marginal = self._get_pair(requesters, providers)
        trades: list[MatchSpec] = []
        for requester, provider in pairs:
            self._record_match(trades, requester, provider, marginal)
        return trades

    @staticmethod
    def _score_provider(rule: StableMatchingSpec, requester: SimpleNamespace, provider: SimpleNamespace) -> float:
        """Return the score of a provider for a requester, higher for a preferred provider."""
        if rule.requester_preference is None:
            return -provider.reserve
        return rule.requester_preference(requester.agent, provider.agent)

    @staticmethod
    def _score_requester(rule: StableMatchingSpec, provider: SimpleNamespace, requester: SimpleNamespace) -> float:
        """Return the score of a requester for a provider.

        The score is higher for a preferred requester.
        """
        if rule.provider_preference is None:
            return requester.reserve
        return rule.provider_preference(provider.agent, requester.agent)

    def _rank_providers(
        self,
        rule: StableMatchingSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
    ) -> dict[int, list[int]]:
        """Return the ids of the acceptable providers of every requester.

        The preferred come first.
        """
        capacities = {provider.agent.id for provider in providers if int(provider.quantity) > 0}
        ranks = {}
        for requester in requesters:
            acceptable = [
                provider
                for provider in providers
                if provider.agent.id in capacities and provider.reserve <= requester.reserve
            ]
            ranked = sorted(
                (-self._score_provider(rule, requester, provider), provider.agent.id) for provider in acceptable
            )
            if ranked:
                ranks[requester.agent.id] = [identity for _, identity in ranked]
        return ranks

    def _rank_requesters(
        self,
        rule: StableMatchingSpec,
        ranks: dict[int, list[int]],
        providers: list[SimpleNamespace],
        by_id: dict[int, SimpleNamespace],
    ) -> dict[int, list[int]]:
        """Return the ids of the requesters that rank every provider, the preferred first."""
        provider_ranks = {}
        for provider in providers:
            suitors = sorted(
                (-self._score_requester(rule, provider, by_id[requester_id]), requester_id)
                for requester_id, ranked in ranks.items()
                if provider.agent.id in ranked
            )
            if suitors:
                provider_ranks[provider.agent.id] = [identity for _, identity in suitors]
        return provider_ranks

    @staticmethod
    def _defer_acceptance(
        requester_ranks: dict[int, list[int]],
        provider_ranks: dict[int, list[int]],
        capacities: dict[int, int],
    ) -> dict[int, list[int]]:
        """Return the requesters of every provider in the stable matching.

        The matching is the requester-optimal one, and the preferred requesters come first.

        Every free requester proposes to its next provider, which holds its preferred proposals up to its capacity and
        rejects the rest. The result does not depend on the order of the proposals.
        """
        held: dict[int, list[int]] = {provider: [] for provider in provider_ranks}
        proposals = {requester: iter(ranked) for requester, ranked in requester_ranks.items()}
        free = list(requester_ranks)
        while free:
            requester = free.pop()
            provider = next(proposals[requester], None)
            if provider is None:
                continue
            held[provider].append(requester)
            if len(held[provider]) > capacities[provider]:
                rejected = max(held[provider], key=provider_ranks[provider].index)
                held[provider].remove(rejected)
                free.append(rejected)
        return {provider: sorted(held[provider], key=ranked.index) for provider, ranked in provider_ranks.items()}

    def _match_stable(
        self,
        rule: StableMatchingSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
    ) -> list[MatchSpec]:
        """Return the matches of the requester-optimal stable matching, one unit per pair."""
        by_id = {offer.agent.id: offer for offer in itertools.chain(requesters, providers)}
        requester_ranks = self._rank_providers(rule, requesters, providers)
        if not requester_ranks:
            return []
        provider_ranks = self._rank_requesters(rule, requester_ranks, providers, by_id)
        capacities = {provider_id: int(by_id[provider_id].quantity) for provider_id in provider_ranks}
        trades: list[MatchSpec] = []
        for provider_id, requester_ids in self._defer_acceptance(requester_ranks, provider_ranks, capacities).items():
            provider = by_id[provider_id]
            for requester_id in requester_ids:
                requester = by_id[requester_id]
                value = self._get_value(requester, provider, rule.value)
                quantity = min(1.0, MatchingInteraction._get_affordable(requester, value), provider.quantity)
                if quantity > 0:
                    requester.quantity -= quantity
                    requester.cap -= quantity * value
                    provider.quantity -= quantity
                    trades.append(MatchSpec(requester.agent, provider.agent, quantity, value))
        return trades

    def _match_partners(
        self,
        rule: PartnerSpec,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches of every requester with the feasible partners its rule picks.

        The requesters go in random order.
        """
        wanting = {id(offer.agent): offer for offer in requesters}
        offering = {id(offer.agent): offer for offer in providers}

        def is_feasible(requester: AgentViewProtocol, provider: AgentViewProtocol) -> bool:
            """Return whether a provider still offers a quantity at an acceptable reserve.

            The requester accepts the reserve.
            """
            offer = offering[id(provider)]
            return offer.quantity > 0 and offer.reserve <= wanting[id(requester)].reserve

        trades: list[MatchSpec] = []
        left, right = [offer.agent for offer in requesters], [offer.agent for offer in providers]
        for requester, provider in pairs(left, right, rng, rule, feasible=is_feasible):
            first, second = wanting[id(requester)], offering[id(provider)]
            value = rule.value if isinstance(rule, PartnerMatchingSpec) else 'midpoint'
            self._record_match(trades, first, second, self._get_value(first, second, value))
        return trades

    def _match_function(
        self,
        rule: Pairing,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        rng: np.random.Generator,
    ) -> list[MatchSpec]:
        """Return the matches of the pairs of a function.

        Each is at the midpoint of the reserves.
        """
        wanting = {id(offer.agent): offer for offer in requesters}
        offering = {id(offer.agent): offer for offer in providers}
        trades: list[MatchSpec] = []
        left = [offer.agent for offer in requesters]
        right = left if self.requesters == self.providers else [offer.agent for offer in providers]
        for requester, provider in pairs(left, right, rng, rule):
            first, second = wanting[id(requester)], offering[id(provider)]
            self._record_match(trades, first, second, self._get_value(first, second, 'midpoint'))
        return trades

    def _get_matches(
        self,
        requesters: list[SimpleNamespace],
        providers: list[SimpleNamespace],
        system: SystemT,
    ) -> list[MatchSpec]:
        """Return the matches of the offers by the algorithm the rule names.

        There are none when a side has no offers.
        """
        if not requesters or not providers:
            return []
        rule, rng = self.rule, system.rng
        match rule:
            case RandomSearchSpec():
                matches = self._match_random_search(rule, requesters, providers, rng)
            case PartnerSwitchSpec():
                matches = self._match_partner_switch(rule, requesters, providers, rng)
            case QueueSpec():
                matches = self._match_queue(rule, requesters, providers, rng)
            case IterativeMatchingSpec():
                matches = self._match_iterative(rule, requesters, providers, rng, system.storage)
            case ContinuousMatchingSpec():
                matches = self._match_continuous(rule, requesters, providers, rng)
            case BatchMatchingSpec():
                matches = self._match_batch(requesters, providers)
            case StableMatchingSpec():
                matches = self._match_stable(rule, requesters, providers)
            case PartnerSpec():
                matches = self._match_partners(rule, requesters, providers, rng)
            case _:
                matches = self._match_function(rule, requesters, providers, rng)
        return matches

    def _settle(self, match: MatchSpec, system: SystemT) -> None:
        """Move the transfers of a match, lower both quantities, and run `on_match`.

        It lowers the quantities of both sides.
        """
        for state, sign in self.transfers:
            if sign < 0:
                transfer(match.requester, match.provider, match.quantity * match.value, state)
            else:
                transfer(match.provider, match.requester, match.quantity, state)
        for agent, name in zip((match.requester, match.provider), self._get_sides(self.quantity), strict=True):
            if hasattr(agent, name):
                setattr(agent, name, getattr(agent, name) - match.quantity)
        if self.on_match is not None:
            self.on_match(match, system)

    def _report_matches(self, matches: list[MatchSpec], unmatched: float, system: SystemT) -> None:
        """Report the value, the matched volume, and the unmatched quantity of a clearing.

        The value is weighted by quantity.

        Args:
            matches:
                The matches of the clearing.

            unmatched:
                The quantity of both sides left after the clearing.

            system:
                The system view of the matching.
        """
        volume = sum(match.quantity for match in matches)
        value = sum(match.quantity * match.value for match in matches) / volume if volume else math.nan
        system.report('value', value)
        system.report('volume', volume)
        system.report('unmatched', unmatched)

    def _check_space(self, space: BaseSpace | None) -> None:
        """Raise an error for candidates in neighbouring cells or nodes.

        The error is for a continuous space.
        """
        self._check_partners(self.rule, space)

    def _check_arguments(self) -> None:
        """Raise an error for a bad declaration, an unsigned transfer, or a bad rule.

        Raises:
            ValidationError:
                A transfer has a sign other than `-1` or `1`, the rule is neither a matching spec nor a function, or
                it is invalid.
        """
        super()._check_arguments()
        for state, sign in self.transfers:
            if sign not in SIGNS:
                error_msg = f'The transfer of {state!r} has the sign {sign!r}. Use one of {SIGNS}.'
                raise ValidationError(error_msg)
        self._check_variant('rule', self.rule, (), RULES, functions=True)
        if isinstance(self.rule, RULES):
            self.rule._check()

    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_: Sequence[BaseLaw] = self._get_matching_laws(context)

    def _get_matching_laws(self, namespace: SimpleNamespace) -> Sequence[BaseLaw]:
        """Return the rule that matches the members in the matching's phase.

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

        Returns:
            laws:
                The laws of the interaction.
        """
        return [UpdateLaw(namespace, self.match, phase=self.phase)]

    def match(self, system: SystemT) -> None:
        """Match the members, settle the matches, and report the results.

        It reports the value, the volume, and the unmatched quantity.

        Args:
            system:
                The system view of the matching.
        """
        requesters, providers = self._get_offers(system)
        matches = self._get_matches(requesters, providers, system)
        for match in matches:
            self._settle(match, system)
        unmatched = sum(offer.quantity for offer in requesters + providers)
        self._report_matches(matches, unmatched, system)

class CabDrivingInteraction(Interaction):
    """Driving rule of the cabs of the ridesharing system.

    A cab drives one block a step to its rider, collects the fare, and drives the rider to its destination. The fare is
    a base fare plus a fare per block of the trip, paid as a transfer from rider to cab.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of cabs.

        riders:
            The path of the group of riders.

        base_fare:
            The fare of every trip.

        block_fare:
            The fare per block of a trip.

        phase:
            The phase the cabs drive in.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import CabDrivingInteraction
        >>> CabDrivingInteraction('drive', target='cabs', riders='riders').block_fare
        0.5
    """

    law_classes = (UpdateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        riders: Role,
        base_fare: Annotated[float, RealSet.closed_open(0, oo)] = 2.0,
        block_fare: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
        phase: str | None = 'drive',
    ) -> None:
        super().__init__(label)
        self.target = target
        self.riders = riders
        self.base_fare = base_fare
        self.block_fare = block_fare
        self.phase = phase

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the driving rule of every cab.

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

    def _pick_up(self, agent: CabView, system: SystemView) -> None:
        """Collect the fare of the rider, take it on board, and head for its destination."""
        rider = next(
            item for item in cast(list[RiderView], system.get_agents(self.riders)) if item.id == int(agent.rider)
        )
        destination = (int(agent.destination_x), int(agent.destination_y))
        blocks = CabDrivingInteraction._get_blocks(CabDrivingInteraction._get_cell(agent.location), destination)
        fare = self.base_fare + self.block_fare * blocks
        transfer(rider, agent, fare, 'money')
        rider.remove()
        new_target_x_value, new_target_y_value = destination
        agent.target_x = new_target_x_value
        agent.target_y = new_target_y_value
        agent.task = DELIVERING

    def drive(self, agent: CabView, system: SystemView) -> None:
        """Drive one block toward the target, and pick up or drop off the rider there.

        Args:
            agent:
                The cab.

            system:
                The system.
        """
        if agent.task == IDLE:
            return
        x, y = CabDrivingInteraction._get_cell(agent.location)
        target = (int(agent.target_x), int(agent.target_y))
        if (x, y) != target:
            step = (int(np.sign(target[0] - x)), 0) if x != target[0] else (0, int(np.sign(target[1] - y)))
            agent.move_to((x + step[0], y + step[1]))
        if CabDrivingInteraction._get_cell(agent.location) != target:
            return
        if agent.task == PICKING_UP:
            self._pick_up(agent, system)
        else:
            agent.task = IDLE
            agent.seats = 1.0

    @staticmethod
    def _get_cell(location: object) -> tuple[int, int]:
        """Return the integer coordinates of a cell."""
        x, y = np.atleast_1d(np.asarray(location, dtype=float))[:2]
        return int(x), int(y)

    @staticmethod
    def _get_blocks(first: tuple[int, int], second: tuple[int, int]) -> int:
        """Return the number of blocks between two cells of the grid.

        It is the Manhattan distance.
        """
        return abs(first[0] - second[0]) + abs(first[1] - second[1])