Skip to content

Bilateral two-good trade on complete, isolated, and small-world networks

Wilhite's bilateral barter of two goods among traders on a trade network.

  • Class: WilhiteTradeNetworksSystem
  • Import: from skcomplex.systems.economics.markets import WilhiteTradeNetworksSystem
  • Field: economics/markets
  • Topics: barter, trade, network, small world, agents
  • References:
    • Wilhite 2001
    • Gooding 2019

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 WilhiteTradeNetworksSystem

trajectory = WilhiteTradeNetworksSystem().prepare().simulate()

Parameters

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

Parameter Default
n_agents 500
topology 'small_world'
n_groups 10
shortcuts 5
endowment 100.0
units 100
random_state 0
solver 'auto'
backend 'auto'

Tags

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

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

Class

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

class WilhiteTradeNetworksSystem(BaseSystem):
    """Wilhite's bilateral barter of two goods among traders on a trade network.

    The network is one of four. Traders start with random bundles of two goods and the utility `good1 good2`. Every
    step, each trader searches its neighbours and trades with the one whose marginal rate of substitution differs the
    most, single units at a price between their rates, while both gain. Trade drives the rates of every connected set of
    traders towards one price. On the complete network every trader searches every other, so it needs the most searches,
    and traders crowd onto the most extreme partners, so prices converge slowly. Isolated groups settle on different
    prices. Groups chained by shared end traders, or a small world with some long links, bring the prices together with
    far fewer searches.

    The system has the group `traders` on the network, the reporters `barter.trades` and `barter.searches`, and the
    observables `dispersion`, the spread of the logarithms of the rates, and `utility`, the mean utility.

    Args:
        n_agents:
            The number of traders.

        topology:
            `'complete'`, `'isolated'` groups, groups `'linked'` in a ring by shared end traders, or `'small_world'`,
            the linked groups with random long links.

        n_groups:
            The number of groups of the isolated, linked, and small-world networks.

        shortcuts:
            The number of random long links between groups of the small world.

        endowment:
            The largest initial holding of each good, drawn uniformly from 1 to it.

        units:
            The most units one pair trades in a step.

        random_state:
            The seed or generator of the bundles and the long links.

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

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

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

    Raises:
        ValueError:
            The topology is unknown.

    Examples:
        >>> from skcomplex.systems.economics.markets import WilhiteTradeNetworksSystem
        >>> system = WilhiteTradeNetworksSystem(40, topology='isolated', n_groups=4).prepare().system_
        >>> system.elements[0].size
        40
    """

    field = 'economics/markets'
    topics = ('barter', 'trade', 'network', 'small world', 'agents')
    references = ('Wilhite 2001', 'Gooding 2019')
    until = 60
    observables = (
        Observable('dispersion', group='traders', variable='mrs', reduce=_log_spread),
        Observable('utility', _get_utility, group='traders'),
    )

    def __init__(
        self,
        n_agents: int = 500,
        *,
        topology: str = 'small_world',
        n_groups: int = 10,
        shortcuts: int = 5,
        endowment: float = 100.0,
        units: int = 100,
        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_agents = n_agents
        self.topology = topology
        self.n_groups = n_groups
        self.shortcuts = shortcuts
        self.endowment = endowment
        self.units = units
        self.random_state = random_state

    @staticmethod
    def _trade_network(
        topology: str,
        n_agents: int,
        n_groups: int,
        shortcuts: int,
        rng: np.random.Generator,
    ) -> nx.Graph:
        """Return the trade network of one of Wilhite's four topologies.

        Its nodes are numbered from zero.
        """
        if topology not in TOPOLOGIES:
            error_msg = f'Unknown topology {topology!r}. Use one of {TOPOLOGIES}.'
            raise ValueError(error_msg)
        if topology == 'complete':
            return nx.complete_graph(n_agents)
        groups = np.array_split(np.arange(n_agents), n_groups)
        graph = nx.Graph()
        graph.add_nodes_from(range(n_agents))
        for members in groups:
            graph.add_edges_from((int(a), int(b)) for index, a in enumerate(members) for b in members[index + 1 :])
        if topology == 'isolated':
            return graph
        for index, members in enumerate(groups):
            following = groups[(index + 1) % n_groups]
            graph.add_edges_from((int(members[-1]), int(other)) for other in following if other != members[-1])
        if topology == 'linked':
            return graph
        for _ in range(shortcuts):
            first, second = rng.choice(n_groups, size=2, replace=False)
            graph.add_edge(int(rng.choice(groups[first])), int(rng.choice(groups[second])))
        return graph

    @staticmethod
    def _appraise(system: SystemView) -> None:
        """Set the marginal rate of substitution `good2 / good1` of the bundle of every trader."""
        for trader in cast(list[BarterTraderView], system.get_agents('target')):
            trader.mrs = trader.good2 / trader.good1

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        graph = self._trade_network(self.topology, self.n_agents, self.n_groups, self.shortcuts, rng)
        goods = rng.integers(1, int(self.endowment) + 1, size=(2, self.n_agents)).astype(float)
        space = NetworkSpace(graph)
        traders = BarterTraderElement(
            'traders',
            good1=goods[0],
            good2=goods[1],
            mrs=goods[1] / goods[0],
            links=np.array([graph.degree(node) for node in range(self.n_agents)], dtype=float),
            values={'node': np.arange(self.n_agents)},
            size=self.n_agents,
            space=space,
        )
        self.system_ = System(
            self.label,
            elements=[traders],
            interactions=[
                Interaction(
                    'appraisal',
                    roles={'target': 'traders'},
                    laws=lambda s: [UpdateLaw(s, WilhiteTradeNetworksSystem._appraise)],
                ),
                BilateralBarterInteraction(
                    'barter',
                    requesters='traders',
                    providers='traders',
                    rule=PartnerMatchingSpec(choice='score', score=BarterTraderElement.get_rate_gap, value='provider'),
                    quantity=('quantity', 'partners'),
                    units=self.units,
                ),
            ],
            space=space,
        )

Components

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

Elements:

  • BarterTraderElement, from Element

Interactions:

  • Interaction
  • BilateralBarterInteraction, from Interaction, through the shared recipe MatchingInteraction
class BarterTraderElement(Element):
    """Trader with a bundle of two goods and the Cobb-Douglas utility `good1 good2`.

    It records its rate. Its marginal rate of substitution `good2 / good1` is the price of the first good, in units of
    the second, at which it is indifferent to trade. Every step it records the rate of its current bundle.

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

        good1:
            The holding of the first good.

        good2:
            The holding of the second good.

        mrs:
            The marginal rate of substitution of the bundle.

        links:
            The number of trading partners the trader can search.

        partners:
            The number of partners that can match with the trader in a step, without limit.

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

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

        space:
            The network whose nodes hold the members, or `None` for none.

    Examples:
        >>> from skcomplex.systems.economics.markets import BarterTraderElement
        >>> BarterTraderElement('traders', size=4).size
        4
    """

    def __init__(
        self,
        label: str,
        *,
        good1: Annotated[object, RealSet.open(0, oo)] = 10.0,
        good2: Annotated[object, RealSet.open(0, oo)] = 10.0,
        mrs: Annotated[object, RealSet.open(0, oo)] = 1.0,
        links: Annotated[object, NN] = 0.0,
        partners: object = math.inf,
        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.good1 = good1
        self.good2 = good2
        self.mrs = mrs
        self.links = links
        self.partners = partners

    @staticmethod
    def is_partner(trader: object, other: object) -> bool:
        """Return whether another trader is a trading partner of a trader.

        A partner is a neighbour on the trade network.

        Args:
            trader:
                The trader that searches.

            other:
                Another trader.

        Returns:
            partner:
                Whether the other trader is in a node next to the trader's node.
        """
        if not isinstance(trader, BarterTraderView) or not isinstance(other, BarterTraderView):
            return False
        return other.id != trader.id and other.location in trader.get_neighbor_cells()

    @staticmethod
    def get_rate_gap(trader: object, other: object) -> float:
        """Return the gap between the logarithms of the rates of substitution.

        The rates are those of a trader and a trading partner. The gap is minus infinity for a trader that is not a
        partner, so a trader takes a partner whenever it has one.

        Args:
            trader:
                The trader that searches.

            other:
                Another trader.

        Returns:
            gap:
                The absolute difference of the logarithms of the two rates.
        """
        if not BarterTraderElement.is_partner(trader, other):
            return -math.inf
        if not isinstance(trader, BarterTraderView) or not isinstance(other, BarterTraderView):
            return -math.inf
        return abs(math.log(other.good2 / other.good1) - math.log(trader.good2 / trader.good1))

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 BilateralBarterInteraction(MatchingInteraction[SystemView]):
    """Barter in which every trader trades with the neighbour it matched.

    A greedy matching pairs every trader, in random order, with the neighbour whose marginal rate of substitution
    differs the most in logarithm, and a neighbour takes any number of partners. The score of a trader that is not a
    neighbour is minus infinity, and a trader without neighbours trades with no one. Each pair trades single units of
    the first good at the price `(g2 + g2') / (g1 + g1')` of their pooled bundles, which lies between their rates, while
    the trade raises the utility of both. Besides the reporters of a matching, the reporters `trades` and `searches`
    count the units traded and the neighbours searched in a step.

    Args:
        label:
            The label of the interaction.

        requesters:
            The path of the group of traders that search for a partner.

        providers:
            The path of the group of traders that can be found, the same group.

        rule:
            The spec of the algorithm that pairs the traders, such as `PartnerMatchingSpec('local', value='provider')`.

        reserve:
            The state with the reserve value of both sides, missing for traders, which then accept any partner.

        quantity:
            The states of the partners a requester wants and a provider takes, one and without limit for traders.

        cap:
            The state of a requester with the most value it can give, missing for traders.

        transfers:
            The states every match moves, none for traders, whose trades move the goods.

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

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

        units:
            The most units one pair trades in a step.

    Examples:
        >>> from skcomplex.systems.economics.markets import BilateralBarterInteraction
        >>> BilateralBarterInteraction('barter', requesters='traders', providers='traders').units
        100
    """

    reports: ClassVar[tuple[str, ...]] = (*MatchingInteraction.reports, 'trades', 'searches')

    def __init__(
        self,
        label: str,
        *,
        requesters: Role,
        providers: Role,
        rule: MatchingRule = 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, SystemView], None] | None = None,
        units: Annotated[int, NN] = 100,
    ) -> None:
        super().__init__(
            label,
            requesters=requesters,
            providers=providers,
            rule=rule,
            reserve=reserve,
            quantity=quantity,
            cap=cap,
            transfers=transfers,
            phase=phase,
            on_match=on_match,
        )
        self.units = units

    @staticmethod
    def _barter(first: BarterTraderView, second: BarterTraderView, units: int) -> int:
        """Trade single units of the first good at the bundle price while both gain.

        It returns the units.
        """
        buyer, seller = (first, second) if first.good2 * second.good1 > second.good2 * first.good1 else (second, first)
        price = (buyer.good2 + seller.good2) / (buyer.good1 + seller.good1)
        traded = 0
        while traded < units:
            buyer_gains = (buyer.good1 + 1) * (buyer.good2 - price) > buyer.good1 * buyer.good2
            seller_gains = (seller.good1 - 1) * (seller.good2 + price) > seller.good1 * seller.good2
            if not (buyer_gains and seller_gains):
                break
            transfer(seller, buyer, 1.0, 'good1')
            transfer(buyer, seller, price, 'good2')
            traded += 1
        return traded

    def _settle(self, match: MatchSpec, system: SystemView) -> None:
        """Trade along a pair of partners, count the units traded, and settle the match."""
        first, second = match.requester, match.provider
        if not isinstance(first, BarterTraderView) or not isinstance(second, BarterTraderView):
            super()._settle(match, system)
            return
        if BarterTraderElement.is_partner(first, second):
            traded = self._barter(first, second, int(system.get_parameter('units')))
            system.storage['trades'] = self._get_trades(system) + traded
        super()._settle(match, system)

    @staticmethod
    def _get_trades(system: SystemView) -> float:
        """Return the units traded so far in the step, kept in the storage of the barter."""
        trades = system.storage.get('trades')
        return float(trades) if isinstance(trades, int | float) else 0.0

    def match(self, system: SystemView) -> None:
        """Pair and trade, and report the units traded and the neighbours searched.

        The report comes besides the matching reporters.

        Args:
            system:
                The system view of the interaction.
        """
        system.storage['trades'] = 0.0
        super().match(system)
        system.report('trades', self._get_trades(system))
        traders = cast(list[BarterTraderView], system.get_agents('requesters'))
        system.report('searches', float(sum(trader.links for trader in traders)))