Skip to content

Matching

Define the matching of requesters with providers that several fields share.

A matching pairs requesters with providers by a rule spec, through the pairs of the core.

BatchMatchingSpec() dataclass

Bases: BaseSpec

A spec of a batch matching of the largest quantity at one clearing value.

It collects every offer, then matches. Requesters are sorted by decreasing and providers by increasing limit, and they pair while the limit of the requester covers that of the provider. The value is the midpoint of the last paired limits, and every pair matches at it.

Unlike ContinuousMatchingSpec, which matches offers as they arrive, it clears all offers at once at one value. Choose it when a market clears in rounds, as a call auction does.

It appears in many fields. Stock exchanges open with a call auction, electricity markets clear once per hour, and markets for emission permits clear in rounds.

Examples:

>>> from skcomplex.systems.general.matching import BatchMatchingSpec
>>> BatchMatchingSpec()
BatchMatchingSpec()

ContinuousMatchingSpec(arrival='random') dataclass

Bases: BaseSpec

A spec of a continuous matching, where arriving offers take the best resting.

Every participant submits one offer, in random order or in order of creation. An arriving offer matches the best resting offers of the other side, the oldest first among equal limits, at their limits, as long as the limits cross, and its remainder rests. The resting offers are dropped at the end of every matching, as in Caiani et al. (2016, chapter 3).

Unlike BatchMatchingSpec, which clears at one value, it matches at many values in order of arrival. Choose it when offers meet as they come, as in a limit order book.

It appears in many fields. Stock exchanges trade continuously through a limit order book, and agent-based models of macroeconomics match firms and banks this way.

Parameters:

Name Type Description Default
arrival str

The order of arrival, 'random' or 'sequential'.

'random'

Raises:

Type Description
ValidationError

The order of arrival is unknown, raised when its owner checks it.

Examples:

>>> from skcomplex.systems.general.matching import ContinuousMatchingSpec
>>> ContinuousMatchingSpec().arrival
'random'

IterativeMatchingSpec(adjustment=0.1, iterations=500, tolerance=0.001) dataclass

Bases: BaseSpec

A spec of an iterative matching that moves a value until supply meets demand.

Starting from the last clearing value, or the median of the limits, the value moves by p <- p (1 + adjustment (D - S) / (D + S)) until the relative excess of requests falls below tolerance. Here D is the quantity requested at a limit of at least p and S the quantity offered at a limit of at most p. The members then match at that value, and the long side is rationed in random order, as in Hamill and Gilbert (2016, chapter 5).

Unlike BatchMatchingSpec, which reads the value off sorted offers, it searches for it by small steps. Choose it when a value adjusts to balance supply and demand, as in a tâtonnement of Walras.

It appears in many fields. Prices adjust in models of general equilibrium, wages adjust in labour markets, and interest rates adjust in models of credit.

Parameters:

Name Type Description Default
adjustment float

The speed of the value adjustment.

0.1
iterations int

The largest number of adjustments per clearing.

500
tolerance float

The relative excess of requests at which the adjustment stops.

0.001

Examples:

>>> from skcomplex.systems.general.matching import IterativeMatchingSpec
>>> IterativeMatchingSpec(adjustment=0.05).iterations
500

MatchSpec(requester, provider, quantity, value) dataclass

Bases: BaseSpec

A spec of one match, a quantity at a value per unit between two members.

Unlike the rule specs, which say how members match, it records one match that a rule made. Choose it when an on_match function of a MatchingInteraction reads the match it receives.

It appears in many fields. A buyer pays a seller for goods, a worker takes a job at a wage, and a borrower takes a loan at a rate.

Parameters:

Name Type Description Default
requester object

The agent view of the requester.

required
provider object

The agent view of the provider.

required
quantity float

The matched quantity.

required
value float

The clearing value per unit.

required

Examples:

>>> from skcomplex.systems.general.matching import MatchSpec
>>> MatchSpec('a', 'b', 2.0, 5.0).quantity
2.0

MatchingInteraction(label, *, requesters, providers, rule=RandomSearchSpec(), reserve='reserve', quantity='quantity', cap='cap', transfers=(), phase=None, on_match=None)

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

Parameters:

Name Type Description Default
label str

The label of the matching.

required
requesters Role

The path of the group of requesters.

required
providers Role

The path of the group of providers.

required
rule MatchingRule | Pairing

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.

RandomSearchSpec()
reserve str | tuple[str, str]

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.

'reserve'
quantity str | tuple[str, str]

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.

'quantity'
cap str

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.

'cap'
transfers Sequence[tuple[str, int]]

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 str | None

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

None
on_match Callable[[MatchSpec, SystemT], None] | None

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

None

Raises:

Type Description
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')
Source code in src/skcomplex/systems/general/matching/_matching.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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

match(system)

Match the members, settle the matches, and report the results.

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

Parameters:

Name Type Description Default
system SystemT

The system view of the matching.

required
Source code in src/skcomplex/systems/general/matching/_matching.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
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)

PartnerMatchingSpec(candidates='all', choice='uniform', fallback=None, capacity=None, score=None, value='midpoint') dataclass

Bases: PartnerSpec

A spec of a choice of partners that a matching settles at a value.

It is a PartnerSpec with the value of a pair, which only a matching reads.

Unlike PartnerSpec, which only pairs members, it also says the value at which each pair settles. Choose it when members pick partners by distance or score and then trade.

It appears in many fields. Buyers visit the nearest shops, workers apply to the best paying firms within reach, and traders deal with partners they trust.

Parameters:

Name Type Description Default
candidates str | float

The agents an agent considers, as in PartnerSpec.

'all'
choice str

How an agent picks among its candidates, as in PartnerSpec.

'uniform'
fallback str | None

The partner of an agent without candidates, as in PartnerSpec.

None
capacity str | float | None

The largest number of pairs of an agent in one step, as in PartnerSpec.

None
score Preference | None

The function score(agent, candidate) the choice 'score' reads, as in PartnerSpec.

None
value str

The value of a pair that a matching settles, 'midpoint' of both reserves, 'provider', or 'requester'.

'midpoint'

Raises:

Type Description
ValidationError

The value rule is unknown, or a setting of the partners is invalid, raised when its owner checks it.

Examples:

>>> from skcomplex.systems.general.matching import PartnerMatchingSpec
>>> PartnerMatchingSpec('local', value='provider').value
'provider'

PartnerSwitchSpec(sample=3, intensity=1.0, partner='partner') dataclass

Bases: BaseSpec

A spec of a choice of partner that may switch to a cheaper provider.

Every requester, in random order, samples sample providers that still offer something. When the lowest limit among them is below that of its current partner, it switches with the probability 1 - exp(intensity * (p_new - p_old) / p_new), and stays otherwise. It matches with its partner at the limit of the partner, and its state partner holds the id of the partner across steps. The rule follows Caiani et al. (2016, chapter 2).

Unlike RandomSearchSpec, which meets new providers each time, it keeps a partner and switches with friction. Choose it when relations persist, such as customers loyal to a supplier.

It appears in many fields. Households keep their shops, firms keep their banks, and workers keep their employers unless a better offer comes, in agent-based models of macroeconomics.

Parameters:

Name Type Description Default
sample int

The number of providers every requester samples.

3
intensity float

The intensity of switching.

1.0
partner str

The name of the requester state that holds the id of its partner.

'partner'

Examples:

>>> from skcomplex.systems.general.matching import PartnerSwitchSpec
>>> PartnerSwitchSpec(sample=2, intensity=4.0).intensity
4.0

QueueSpec(order='random') dataclass

Bases: BaseSpec

A spec of a queue of requesters served by the cheapest providers.

Requesters queue in random order, by decreasing reserve, or in order of creation, and each matches at the reserve of the cheapest providers whose reserve it accepts. The last requesters may get nothing.

Unlike IterativeMatchingSpec, which finds one value for all, it serves requesters one by one at the prices of the providers. Choose it when members are served in order, first come first served.

It appears in many fields. Customers queue at a shop, patients wait for organs, and households queue for housing.

Parameters:

Name Type Description Default
order str

The order of the queue, 'random', 'reserve', or 'sequential'.

'random'

Raises:

Type Description
ValidationError

The order is unknown, raised when its owner checks it.

Examples:

>>> from skcomplex.systems.general.matching import QueueSpec
>>> QueueSpec(order='reserve').order
'reserve'

RandomSearchSpec(tries=1, value='midpoint') dataclass

Bases: BaseSpec

A spec of a random search, where requesters meet random providers and match.

Every requester, in random order, makes up to tries meetings with providers that still offer something, and matches when the limits cross, at the midpoint of the two limits or at the limit of one side. It is the decentralised exchange of Hamill and Gilbert (2016, chapter 5).

Unlike BatchMatchingSpec, which sees every offer, it lets each requester see only a few. Choose it when information is local and search is costly.

It appears in many fields. Buyers search among sellers in a bazaar, job seekers meet a few firms, and animals search for mates.

Parameters:

Name Type Description Default
tries int

The number of providers every requester meets.

1
value str

The value of a match, 'midpoint', 'requester', or 'provider'.

'midpoint'

Raises:

Type Description
ValidationError

The value rule is unknown, raised when its owner checks it.

Examples:

>>> from skcomplex.systems.general.matching import RandomSearchSpec
>>> RandomSearchSpec(tries=3).tries
3

StableMatchingSpec(requester_preference=None, provider_preference=None, value='provider') dataclass

Bases: BaseSpec

A spec of the stable matching of Gale and Shapley, by mutual preferences.

Requesters propose to providers, which take as many as they offer units. Requesters rank the providers by requester_preference(requester, provider), by default the lower reserve, and providers rank the requesters by provider_preference(provider, requester), by default the higher reserve. The stable matching that favours the requesters, from the hospital and resident solver of the matching library, pairs every requester with at most one provider, and each pair matches one unit at the value of value. No requester and provider then prefer each other to their partners.

Unlike BatchMatchingSpec, which pairs by price alone, it pairs by preferences on both sides. Choose it when both sides rank each other and stability matters.

It appears in many fields. Medical residents match with hospitals, students match with schools, and donors match with patients in kidney exchange.

Parameters:

Name Type Description Default
requester_preference Preference | None

The score of a provider for a requester, a function of their agent views, higher for preferred providers, or None for the lower reserve.

None
provider_preference Preference | None

The score of a requester for a provider, a function of their agent views, higher for preferred requesters, or None for the higher reserve.

None
value str

The value of a match, 'provider', 'requester', or 'midpoint'.

'provider'

Raises:

Type Description
ValidationError

The value rule is unknown, raised when its owner checks it.

Examples:

>>> from skcomplex.systems.general.matching import StableMatchingSpec
>>> StableMatchingSpec(value='requester').value
'requester'