Skip to content

Hegselmann-Krause

The Hegselmann-Krause system.

  • Class: HegselmannKrauseSystem
  • Import: from skcomplex.systems.social.opinion_dynamics import HegselmannKrauseSystem
  • Field: social/opinion_dynamics
  • Topics: opinion, bounded confidence, clusters, network, synchronous
  • References:
    • Hegselmann and Krause 2002
    • Castellano, Fortunato, and Loreto 2009

The hegselmann_krause example

Example

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 HegselmannKrauseSystem

trajectory = HegselmannKrauseSystem().prepare().simulate()

Parameters

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

Parameter Default
n_agents 200
confidence 0.15
graph None
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 deterministic
Domains real
Structure fixed

Class

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

class HegselmannKrauseSystem(BaseSystem):
    """The Hegselmann-Krause system.

    Its opinions freeze within a few steps into clusters about `2 ε` apart. Every step every agent moves at once to the
    mean opinion of its neighbours, itself included, whose opinions lie within the confidence `ε` of its own. On the
    complete graph the opinions settle into about `1 / (2 ε)` clusters. The system has the group `people` on the nodes
    of the network.

    Args:
        n_agents:
            The number of agents, the nodes of the complete graph when no graph is given.

        confidence:
            The confidence `ε`.

        graph:
            The network of the agents, or `None` for the complete graph.

        random_state:
            The seed or generator of the uniform initial opinions.

        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:
        >>> import numpy as np
        >>> from skcomplex.systems.social.opinion_dynamics import HegselmannKrauseSystem
        >>> trajectory = HegselmannKrauseSystem(50, confidence=0.3).prepare().simulate(until=20, random_state=0)
        >>> len(np.unique(np.round(trajectory.get_values('people.opinion')[-1], 6))) <= 3
        True
    """

    field = 'social/opinion_dynamics'
    topics = ('opinion', 'bounded confidence', 'clusters', 'network', 'synchronous')
    references = ('Hegselmann and Krause 2002', 'Castellano, Fortunato, and Loreto 2009')
    until = 30

    def __init__(
        self,
        n_agents: int = 200,
        *,
        confidence: float = 0.15,
        graph: nx.Graph | None = None,
        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.confidence = confidence
        self.graph = graph
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the components built from the model parameters."""
        super()._prepare(context)
        space = NetworkSpace(self.graph if self.graph is not None else nx.complete_graph(self.n_agents)).prepare()
        opinions = np.random.default_rng(self.random_state).random(space.size_)
        people = ConfidentElement('people', opinion=opinions, confidence=self.confidence, space=space)
        coupling = ConfidenceCouplingInteraction('compromise', target='people')
        self.system_ = System(self.label, elements=[people], interactions=[coupling])

Components

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

Elements:

Interactions:

  • ConfidenceCouplingInteraction, from Interaction
class ConfidentElement(Element):
    """Agent of the Hegselmann-Krause system.

    It holds an opinion and the confidence within which it trusts neighbours. `ConfidenceCouplingInteraction` moves
    every agent each step to the mean opinion of the neighbours, itself included, whose opinions differ from its own by
    less than `confidence`.

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

        opinion:
            The opinion, between 0 and 1.

        confidence:
            The largest opinion difference of a neighbour an agent still listens to.

        space:
            The space with one member per site, or `None` for one member.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import ConfidentElement
        >>> ConfidentElement('people', confidence=0.1).confidence
        0.1
    """

    visual = VisualSpec('histograms', {'color_range': (0.0, 1.0), 'histogram_first': True})

    def __init__(
        self,
        label: str,
        *,
        opinion: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
        confidence: Annotated[object, RealSet.closed_open(0, oo)] = 0.2,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.opinion = opinion
        self.confidence = confidence

class ConfidenceCouplingInteraction(Interaction):
    """Hegselmann-Krause coupling of the opinions of agents.

    Every step every agent takes at once the mean opinion of its neighbours, itself included, whose opinions differ from
    its own by less than its parameter `confidence`. It is the map form of coupling with the normalized mean over the
    neighbours of the network weighted by the indicator of the confidence.

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

        target:
            The path of the group of agents, on the nodes of a network.

        state:
            The name of the state that holds the opinions.

    Examples:
        >>> import networkx as nx
        >>> import numpy as np
        >>> from skcomplex.core.components.spaces import NetworkSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.social.opinion_dynamics import ConfidenceCouplingInteraction, ConfidentElement
        >>> network = NetworkSpace(nx.complete_graph(3))
        >>> people = ConfidentElement('people', opinion=[0.1, 0.2, 0.9], confidence=0.2, space=network)
        >>> coupling = ConfidenceCouplingInteraction('compromise', target='people')
        >>> system = System(elements=[people], interactions=[coupling])
        >>> opinions = system.prepare().simulate(until=1).get_values('people.opinion')
        >>> np.round(opinions[-1], 6).tolist()
        [0.15, 0.15, 0.9]
    """

    law_classes = (UpdateLaw,)

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

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the next opinion, the mean of the trusted opinions of the agent and its neighbours, as the law.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        member = context.target
        opinion, other = getattr(member, self.state), getattr(member.other, self.state)
        trust = where(abs(other - opinion) < member.confidence, 1, 0)
        mean = neighbors(other, over=AdjacencyNeighborhood(center=True), reduce='normalized-mean', weight=trust)
        self.laws_: list[BaseLaw] = [UpdateLaw(opinion, mean)]