Skip to content

Threshold adoption

The threshold adoption system in social circles.

  • Class: ThresholdAdoptionSystem
  • Import: from skcomplex.systems.social.opinion_dynamics import ThresholdAdoptionSystem
  • Field: social/opinion_dynamics
  • Topics: opinion, agents, innovation, threshold
  • References:
    • Granovetter 1978
    • Hamill and Gilbert 2016

Use this system

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

from skcomplex.systems.social.opinion_dynamics import ThresholdAdoptionSystem

trajectory = ThresholdAdoptionSystem().prepare().simulate()

Parameters

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

Parameter Default
n_agents 300
size 175.0
reach 15.0
mode 'infection'
thresholds 'uniform'
shifting 0.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 continuous
Laws update
Randomness stochastic
Domains boolean, real
Structure variable membership

Class

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

class ThresholdAdoptionSystem(BaseSystem):
    """The threshold adoption system in social circles.

    It is started by the 2.5% of agents with the lowest thresholds. The system has the group `people`.

    Args:
        n_agents:
            The number of agents, placed at random on a square torus.

        size:
            The side of the torus.

        reach:
            The distance within which other agents form an agent's social circle.

        mode:
            `'infection'` to adopt after one adopter in the circle, or `'influence'` to adopt above a threshold.

        thresholds:
            `'uniform'` for thresholds uniform on 1 to 100 percent, or `'normal'` for a normal distribution of mean 50
            and standard deviation 50 clipped to 1 to 100.

        shifting:
            The share of agents that move one unit in a random direction every step.

        random_state:
            The seed or generator of the positions and thresholds.

        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.social.opinion_dynamics import ThresholdAdoptionSystem
        >>> ThresholdAdoptionSystem(40, size=60.0, random_state=0).prepare().system_.elements[0].size
        40
    """

    field = 'social/opinion_dynamics'
    topics = ('opinion', 'agents', 'innovation', 'threshold')
    references = ('Granovetter 1978', 'Hamill and Gilbert 2016')
    until = 25

    def __init__(
        self,
        n_agents: int = 300,
        *,
        size: float = 175.0,
        reach: float = 15.0,
        mode: str = 'infection',
        thresholds: str = 'uniform',
        shifting: float = 0.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.n_agents = n_agents
        self.size = size
        self.reach = reach
        self.mode = mode
        self.thresholds = thresholds
        self.shifting = shifting
        self.random_state = random_state

    @staticmethod
    def _shift(agent: AgentViewProtocol, system: SystemViewProtocol, size: float) -> Array:
        """Return the position one unit away from an agent in a random direction.

        It is wrapped on a square torus.
        """
        angle = system.rng.uniform(0, 2 * np.pi)
        position = np.asarray(agent.location, dtype=float) + np.array([np.cos(angle), np.sin(angle)])
        return np.mod(position, size)

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the components built from the model parameters."""
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        drawn = (
            rng.uniform(1, 100, self.n_agents)
            if self.thresholds == 'uniform'
            else np.clip(rng.normal(50, 50, self.n_agents), 1, 100)
        )
        innovators = np.argsort(drawn)[: max(1, round(INNOVATORS * self.n_agents))]
        adopted = np.zeros(self.n_agents)
        adopted[innovators] = 1.0
        space = ContinuousSpace(extent=(self.size, self.size), boundary='periodic')
        x, y = rng.uniform(0, self.size, (self.n_agents, 2)).T
        people = AdopterElement(
            'people',
            adopted=adopted,
            threshold=drawn,
            reach=self.reach,
            values={'x': x, 'y': y},
            size=self.n_agents,
            space=space,
        )
        self.system_ = System(
            self.label,
            elements=[people],
            interactions=[
                MovementInteraction(
                    'shift',
                    target='people',
                    step=lambda agent, system: self._shift(agent, system, self.size),
                    probability=self.shifting,
                ),
                AdoptionInteraction('adoption', target='people', mode=self.mode),
            ],
            space=space,
        )

Components

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

Elements:

Interactions:

  • MovementInteraction, from Interaction, through the shared recipe MovementInteraction
  • AdoptionInteraction, from Interaction
class AdopterElement(Element):
    """Agent of the threshold adoption system, who adopts an innovation for good.

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

        adopted:
            Whether the agent starts as an adopter.

        threshold:
            The percentage of adopters in the agent's social circle above which it adopts in the influence mode.

        reach:
            The distance within which other agents form an agent's social circle.

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

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

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

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import AdopterElement
        >>> group = AdopterElement('people', threshold=50.0, size=10)
        >>> group.label, type(group).__name__, group.size
        ('people', 'AdopterElement', 10)
    """

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

    def __init__(
        self,
        label: str,
        *,
        adopted: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
        threshold: Annotated[object, RealSet.closed_open(0, oo)] = 50.0,
        reach: Annotated[object, RealSet.open(0, oo)] = 15.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.adopted = adopted
        self.threshold = threshold
        self.reach = reach

class MovementInteraction(Interaction):
    """An interaction that moves the agents of a group by steps at every discrete step.

    The `step` says where an agent goes:

    - `'neighbor'`: a random cell or node next to its own, on a lattice or a network.
    - `'gaussian'`: its position plus a normal vector of deviation `scale`, in a continuous space.
    - `'levy'`: a random direction and a Pareto length of least value `scale` and tail `exponent`, in a continuous
      space.
    - `'best'`: the next cell with the highest `score(agent, cell, system)`, or with a `vision` the best cell along each
      direction up to that many cells, with ties broken by `ties`.
    - A function `step(agent, system)` that returns the destination, or `None` to stay.

    An agent for which `condition` holds attempts one step, or a Poisson number of mean `rate`, takes it with the
    probability `probability`, and then with the probability `accept(agent, destination, system)`. An exclusive movement
    never enters a cell held by another agent of the group. The agents move one after another by `schedule`, and every
    step charges its `cost`.

    Unlike an `UpdateLaw` on the edges of a network, which changes the space, it changes where agents stand in it.
    Choose it when agents walk, forage, or relocate.

    It appears in many fields. Sheep wander a pasture, foragers follow Lévy flights, ants climb a pheromone gradient,
    and residents move house in the segregation model of Schelling.

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

        target:
            The path of the group whose agents move.

        step:
            The kind of step, `'neighbor'`, `'gaussian'`, `'levy'`, or `'best'`, or a function of the agent and the
            system view that returns the destination.

        probability:
            The probability that an agent takes an attempted step.

        rate:
            The mean number of attempted steps of an agent in one unit of time, or `None` for one attempt every step.

        condition:
            A function of the agent and the system view that returns whether the agent moves, or `None` for every agent.

        accept:
            A function of the agent, its destination, and the system view that returns the probability of taking the
            step, or `None` to take every step.

        exclusive:
            Whether an agent moves only to cells or nodes no other agent of the group holds.

        score:
            The function of the agent, a neighbouring cell, and the system view that the step `'best'` maximizes.

        scale:
            The standard deviation of every component of a Gaussian step, or the least length of a Lévy step.

        exponent:
            The tail exponent of the length of a Lévy step.

        cost:
            A function of the agent and the system view run for every step taken, such as one that takes the energy a
            step costs from the agent, `def pay(agent, system): agent.energy -= 1.0`, or `None`.

        vision:
            The number of cells the step `'best'` looks along every direction of a lattice, a number or a function of
            the agent and the system view, or `None` for the cells next to the agent.

        schedule:
            The order of the agents, `'sequential'`, `'random-sequential'`, or `'member'`.

        phase:
            The phase of the step the movement runs in, or `None` for the default phase.

        ties:
            The cell the step `'best'` takes among cells of equal highest score, `'random'`, `'first'`, or `'nearest'`,
            or `None` for `'random'` without a vision and `'nearest'` with one.

    Raises:
        ValidationError:
            The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable, or
            the step `'best'` has no score, raised by `prepare`.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.agents import MovementInteraction
        >>> space = LatticeSpace((5, 5), metric='manhattan')
        >>> walkers = Element('walkers', values={'x': [2, 2], 'y': [2, 2]}, size=2, space=space)
        >>> walk = MovementInteraction('walk', target='walkers', step='neighbor')
        >>> trajectory = System(elements=[walkers], interactions=[walk]).prepare().simulate(until=1, random_state=0)
        >>> [bool(abs(cell - 2).sum() == 1) for cell in trajectory.get_agents('walkers', 1).locations]
        [True, True]
    """

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

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

        It draws by its order, a random step, a probability or rate, or random ties.
        """
        ties = self.ties or ('random' if self.vision is None else 'nearest')
        drawn = self.step in ('neighbor', 'gaussian', 'levy') or (self.step == 'best' and ties == 'random')
        return (
            super()._get_draws() or drawn or self.probability != 1 or self.rate is not None or self.accept is not None
        )

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        step: Step = 'neighbor',
        probability: Annotated[float, RealSet.closed(0, 1)] = 1.0,
        rate: float | None = None,
        condition: Callable[[AgentViewProtocol, SystemViewProtocol], bool] | None = None,
        accept: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
        exclusive: bool = False,
        score: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
        scale: Annotated[float, RealSet.open(0, oo)] = 1.0,
        exponent: Annotated[float, RealSet.open(0, oo)] = 1.5,
        cost: Cost | None = None,
        vision: Vision | None = None,
        schedule: str = 'random-sequential',
        phase: str | None = None,
        ties: str | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.step = step
        self.probability = probability
        self.rate = rate
        self.condition = condition
        self.accept = accept
        self.exclusive = exclusive
        self.score = score
        self.scale = scale
        self.exponent = exponent
        self.cost = cost
        self.vision = vision
        self.schedule = schedule
        self.phase = phase
        self.ties = ties

    def _check_functions(self) -> None:
        """Raise an error for a condition, acceptance, score, or cost that is not callable."""
        for name in ('condition', 'accept', 'score', 'cost'):
            value = getattr(self, name)
            if value is not None and not callable(value):
                error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function, or None.'
                raise ValidationError(error_msg)

    def _check_space(self, space: BaseSpace | None) -> None:
        """Raise an error for a step to a neighbouring cell or node in a continuous space."""
        if isinstance(self.step, str) and self.step in GRID_STEPS:
            self._check_grid('step', self.step, space, "step='gaussian' or step='levy', or a step function")

    def _check_arguments(self) -> None:
        """Raise an error for an unknown step, a rate not positive, or a bad function.

        Raises:
            ValidationError:
                The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable,
                or the step `'best'` has no score.
        """
        super()._check_arguments()
        self._check_variant('step', self.step, STEPS, functions=True)
        if self.rate is not None and (isinstance(self.rate, bool) or not self.rate > 0):
            error_msg = f'The rate of {self.label!r} is {self.rate!r}. Give a positive number, or None.'
            raise ValidationError(error_msg)
        if self.schedule not in SCHEDULES:
            error_msg = f'Unknown schedule {self.schedule!r} of {self.label!r}. Use one of {", ".join(SCHEDULES)}.'
            raise ValidationError(error_msg)
        if self.ties is not None:
            self._check_variant('ties', self.ties, TIES)
        if self.vision is not None and not callable(self.vision) and not isinstance(self.vision, int | float):
            error_msg = f'The vision of {self.label!r} is {self.vision!r}. Give a number, a function, or None.'
            raise ValidationError(error_msg)
        if self.step == 'best' and self.score is None:
            error_msg = f'The step `best` of {self.label!r} maximizes a score. Pass `score(agent, cell, system)`.'
            raise ValidationError(error_msg)
        self._check_functions()

    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_movement_laws(context)

    def _count_attempts(self, system: SystemViewProtocol) -> int:
        """Return the number of steps an agent attempts in one step of time."""
        return 1 if self.rate is None else int(system.rng.poisson(self.rate))

    def _get_cells(self, agent: AgentViewProtocol, occupied: set[object]) -> list[object]:
        """Return the cells or nodes around an agent that it may move to."""
        cells = agent.get_neighbor_cells()
        if not self.exclusive:
            return cells
        return [cell for cell in cells if cell not in occupied]

    def _get_best(
        self,
        agent: AgentViewProtocol,
        cells: list[object],
        system: SystemViewProtocol,
        distances: list[int] | None = None,
    ) -> object:
        """Return the cell of the highest score, chosen among ties by the tie rule."""
        if self.score is None or not cells:
            return None
        scores = [self.score(agent, cell, system) for cell in cells]
        ties = self.ties or ('random' if distances is None else 'nearest')
        if ties != 'nearest':
            return cells[self._pick_best(scores, ties, system)]
        values = np.asarray(scores, dtype=float)
        best = np.flatnonzero(values == values.max())
        near = np.asarray([1 if distances is None else distances[int(index)] for index in best])
        return cells[int(best[near == near.min()][0])]

    @staticmethod
    def _shift(here: tuple[int, ...], cell: tuple[int, ...], system: SystemViewProtocol) -> tuple[int, ...]:
        """Return the unit step from a cell to a neighbouring cell.

        The step goes across the wrapped edge of a torus.
        """
        shift = [b - a for a, b in zip(here, cell, strict=True)]
        if system.torus:
            sizes = [int(item) for item in system.dimensions or ()]
            shift = [d - round(d / n) * n for d, n in zip(shift, sizes, strict=True)]
        return tuple(shift)

    def _get_sight(
        self,
        agent: AgentViewProtocol,
        occupied: set[object],
        system: SystemViewProtocol,
    ) -> tuple[list[object], list[int]]:
        """Return the cells in sight of an agent along every direction of a lattice.

        Its own cell comes first, with the distances.
        """
        vision = self.vision(agent, system) if callable(self.vision) else self.vision
        reach = int(vision or 0)
        here = tuple(int(item) for item in np.atleast_1d(np.asarray(agent.location_key)))
        sizes = [int(item) for item in system.dimensions or ()]
        cells: list[object] = [agent.location_key]
        distances = [0]
        shifts = [
            self._shift(here, tuple(int(item) for item in np.atleast_1d(np.asarray(neighbor))), system)
            for neighbor in agent.get_neighbor_cells()
        ]
        for shift in sorted(shifts, key=lambda step: tuple((item == 0, -item) for item in step)):
            for distance in range(1, reach + 1):
                point = [a + distance * d for a, d in zip(here, shift, strict=True)]
                if system.torus:
                    point = [item % size for item, size in zip(point, sizes, strict=True)]
                elif any(not 0 <= item < size for item, size in zip(point, sizes, strict=True)):
                    break
                cell = tuple(point)
                if not self.exclusive or cell not in occupied:
                    cells.append(cell)
                    distances.append(distance)
        return cells, distances

    def _get_destination(self, agent: AgentViewProtocol, system: SystemViewProtocol, occupied: set[object]) -> object:
        """Return the location a step of an agent leads to, or `None` to stay."""
        rng = system.rng
        if callable(self.step):
            return self.step(agent, system)
        if self.step == 'best' and self.vision is not None:
            cells, distances = self._get_sight(agent, occupied, system)
            return self._get_best(agent, cells, system, distances)
        if self.step in ('neighbor', 'best'):
            cells = self._get_cells(agent, occupied)
            if self.step == 'best':
                return self._get_best(agent, cells, system)
            return cells[int(rng.integers(len(cells)))] if cells else None
        position = np.asarray(agent.location, dtype=float)
        if self.step == 'gaussian':
            return position + rng.normal(0.0, self._get_parameter_value('scale', system), position.shape)
        direction = rng.normal(size=position.shape)
        length = self._get_parameter_value('scale', system) * (
            1.0 + rng.pareto(self._get_parameter_value('exponent', system))
        )
        return position + length * direction / np.linalg.norm(direction)

    def _charge(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Charge the cost of one step taken to an agent."""
        if self.cost is not None:
            self.cost(agent, system)

    def _take(self, agent: AgentViewProtocol, destination: object, occupied: set[object]) -> bool:
        """Move an agent to a destination unless an exclusive movement finds it held.

        It returns whether it moved.
        """
        if not self.exclusive:
            agent.move_to(destination)
            return True
        if destination == agent.location_key:
            return True
        if destination in occupied:
            return False
        occupied.discard(agent.location_key)
        agent.move_to(destination)
        occupied.add(agent.location_key)
        return True

    def _move(
        self,
        agent: AgentViewProtocol,
        system: SystemViewProtocol,
        probability: float,
        occupied: set[object],
    ) -> None:
        """Take the attempted steps of one agent.

        Each step has its probability and acceptance, and every step is charged.
        """
        for _ in range(self._count_attempts(system)):
            if probability < 1.0 and system.rng.random() >= probability:
                continue
            destination = self._get_destination(agent, system, occupied)
            if destination is None:
                continue
            if self.accept is not None and system.rng.random() >= self.accept(agent, destination, system):
                continue
            if self._take(agent, destination, occupied):
                self._charge(agent, system)

    def _move_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Move one agent whose condition holds, in its own activation."""
        if agent.alive and (self.condition is None or self.condition(agent, system)):
            occupied = (
                {other.location_key for other in system.get_agents(self._get_role('target'))}
                if self.exclusive
                else set()
            )
            self._move(agent, system, self._get_parameter_value('probability', system), occupied)

    def _move_all(self, system: SystemViewProtocol) -> None:
        """Move every agent of the group whose condition holds.

        They move in their order or in random order.
        """
        agents = system.get_agents(self._get_role('target'))
        occupied = {agent.location_key for agent in agents} if self.exclusive else set()
        probability = self._get_parameter_value('probability', system)
        order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
        for index in order:
            agent = agents[int(index)]
            if agent.alive and (self.condition is None or self.condition(agent, system)):
                self._move(agent, system, probability, occupied)

    def _get_movement_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the rule of the movement.

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

        Returns:
            laws:
                The rule that moves the agents every step.
        """
        if self.schedule == 'member':
            return [UpdateLaw(self._get_member(namespace, 'target'), self._move_member, phase=self.phase)]
        return [UpdateLaw(namespace, self._move_all, phase=self.phase)]

class AdoptionInteraction(Interaction):
    """Synchronous adoption of the threshold system.

    Every agent adopts for good from its social circle. In the infection mode an agent adopts once anyone in its social
    circle has adopted. In the influence mode it adopts once the percentage of adopters in its circle exceeds its
    threshold, or in society when its circle is empty. Every agent decides from the adoptions at the start of the step.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of adopters.

        mode:
            `'infection'` or `'influence'`.

    Raises:
        ValidationError:
            The mode is unknown.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import AdoptionInteraction
        >>> AdoptionInteraction('adoption', target='people', mode='influence').mode
        'influence'
    """

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

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The mode is unknown.
        """
        super()._check_arguments()
        if self.mode not in MODES:
            error_msg = f'Unknown adoption mode {self.mode!r}. Use one of {", ".join(MODES)}.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the adoptions of every step as the rule of the system.

        Args:
            context:
                The namespace of the adopters.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [UpdateLaw(context, self.adopt)]

    def adopt(self, system: SystemViewProtocol) -> None:
        """Let every agent that has not adopted adopt, from the adoptions at the start of the step.

        Args:
            system:
                The system view of the adoptions.
        """
        agents = [agent for agent in system.get_agents('target') if isinstance(agent, AdopterView)]
        adopting = [agent for agent in agents if float(agent.adopted) == 0.0 and self._adopts(agent, system)]
        for agent in adopting:
            agent.adopted = 1.0

    def _adopts(self, agent: AdopterView, system: SystemViewProtocol) -> bool:
        """Return whether an agent adopts from the adopters in its social circle.

        Without a circle, the adopters are those in society.
        """
        circle = [item for item in agent.get_neighbors(agent.reach) if isinstance(item, AdopterView)]
        adopters = sum(item.adopted for item in circle)
        if self.mode == 'infection':
            return adopters > 0
        if circle:
            return 100 * adopters / len(circle) > agent.threshold
        society = [item for item in system.get_agents('target') if isinstance(item, AdopterView)]
        return 100 * sum(item.adopted for item in society) / len(society) > agent.threshold