Skip to content

Fair-trade food choice with peer influence

The choice between fair-trade and regular food of consumers.

  • Class: FairFoodSystem
  • Import: from skcomplex.systems.economics.markets import FairFoodSystem
  • Field: economics/markets
  • Topics: consumer choice, social influence, agents, grid
  • References:
    • Brock and Durlauf 2001

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 FairFoodSystem

trajectory = FairFoodSystem().prepare().simulate()

Parameters

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

Parameter Default
width 20
height 20
premium 0.3
ethics_weight 2.0
price_weight 5.0
social_weight 2.0
intensity 1.0
low_budget 1.0
high_budget 3.0
random_state 0
solver 'auto'
backend 'auto'

Tags

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

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

Class

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

class FairFoodSystem(BaseSystem):
    """The choice between fair-trade and regular food of consumers.

    The consumers influence their neighbours. Every consumer, of uniform ethical concern and budget, sits on a cell of a
    grid and every step buys fair or regular food, all at once from the choices of their neighbours in the last step.
    The share of fair food rises with the weight of ethics and falls with the premium, and social influence raises it.

    The choice is the binary logit choice with social interactions of Brock and Durlauf (2001), with a private utility
    of ethics and price and a social utility of the share of neighbours who buy fair food. Neither Ajani's Choice nor
    the Fair Food Program of Chesney (2021) is this model. The system has the group `consumers`, their logit choice
    `shopping`, and the share of fair food `fair_share`.

    Args:
        width:
            The number of columns of the grid.

        height:
            The number of rows of the grid.

        premium:
            The extra price of fair food over regular food, which costs one.

        ethics_weight:
            The weight of ethical concern in the utility of fair food.

        price_weight:
            The weight of the premium relative to the budget.

        social_weight:
            The weight of the share of neighbours who buy fair food.

        intensity:
            The intensity of the logit choice.

        low_budget:
            The lowest budget.

        high_budget:
            The highest budget.

        random_state:
            The seed or generator of the ethics and the budgets.

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

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

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

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

    field = 'economics/markets'
    topics = ('consumer choice', 'social influence', 'agents', 'grid')
    references = ('Brock and Durlauf 2001',)
    until = 50
    observables = (Observable('fair_share', group='consumers', variable='fair'),)

    def __init__(
        self,
        width: int = 20,
        height: int = 20,
        *,
        premium: float = 0.3,
        ethics_weight: float = 2.0,
        price_weight: float = 5.0,
        social_weight: float = 2.0,
        intensity: float = 1.0,
        low_budget: float = 1.0,
        high_budget: float = 3.0,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.width = width
        self.height = height
        self.premium = premium
        self.ethics_weight = ethics_weight
        self.price_weight = price_weight
        self.social_weight = social_weight
        self.intensity = intensity
        self.low_budget = low_budget
        self.high_budget = high_budget
        self.random_state = random_state

    @staticmethod
    def _get_utility(agent: ConsumerView, system: SystemView, option: float) -> float:
        """Return the utility of fair food, option 1, or regular food, option 0.

        It is `-inf` for fair food over budget.
        """
        if option == 0:
            return 0.0
        if agent.budget < 1 + agent.premium:
            return -math.inf
        neighbors = [neighbor for neighbor in agent.get_neighbors() if isinstance(neighbor, ConsumerView)]
        share = sum(neighbor.fair for neighbor in neighbors) / len(neighbors) if neighbors else 0.0
        return float(
            agent.ethics_weight * agent.ethics
            - agent.price_weight * agent.premium / agent.budget
            + agent.social_weight * share,
        )

    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)
        size = self.width * self.height
        space = LatticeSpace((self.width, self.height), boundary='periodic', capacity=1)
        x, y = np.array([(x, y) for x in range(self.width) for y in range(self.height)]).T
        consumers = ConsumerElement(
            'consumers',
            ethics=rng.random(size),
            budget=rng.uniform(self.low_budget, self.high_budget, size),
            premium=self.premium,
            ethics_weight=self.ethics_weight,
            price_weight=self.price_weight,
            social_weight=self.social_weight,
            values={'x': x, 'y': y},
            size=size,
            space=space,
        )
        choice = ChoiceInteraction(
            'shopping',
            target='consumers',
            state='fair',
            options=(0, 1),
            utility=self._get_utility,
            intensity=self.intensity,
            schedule='synchronous',
        )
        self.system_ = System(
            self.label,
            elements=[consumers],
            interactions=[choice],
            space=space,
        )

Components

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

Elements:

Interactions:

class ConsumerElement(Element):
    """Consumer who buys fair-trade or regular food.

    It holds an ethical concern, a budget, and the weights of its utility. The utility of fair food is
    `ethics_weight * ethics - price_weight * premium / budget + social_weight * share`, where `share` is the share of
    neighbours who bought fair food in the last step, and the utility of regular food is zero. A consumer whose budget
    does not cover the price `1 + premium` of fair food buys regular food.

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

        fair:
            One when the consumer bought fair food in the last step, zero otherwise.

        ethics:
            The ethical concern of the consumer, between zero and one.

        budget:
            The money the consumer can spend on one unit of food, regular food costing one.

        premium:
            The extra price of fair food over regular food.

        ethics_weight:
            The weight of ethical concern in the utility of fair food.

        price_weight:
            The weight of the premium relative to the budget.

        social_weight:
            The weight of the share of neighbours who buy fair food.

        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.economics.markets import ConsumerElement
        >>> ConsumerElement('consumers', ethics=0.5, size=4).size
        4
    """

    visual = VisualSpec('agents', {'color_by': 'fair', 'color_range': (0.0, 1.0)})

    def __init__(
        self,
        label: str,
        *,
        fair: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
        ethics: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
        budget: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
        premium: Annotated[object, RealSet.closed_open(0, oo)] = 0.3,
        ethics_weight: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
        price_weight: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
        social_weight: Annotated[object, RealSet.closed_open(0, oo)] = 2.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.fair = fair
        self.ethics = ethics
        self.budget = budget
        self.premium = premium
        self.ethics_weight = ethics_weight
        self.price_weight = price_weight
        self.social_weight = social_weight

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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