Voter model
A voter model with one voter per node of a network.
- Name:
voter_model - Field:
social/opinion_dynamics - Formalism: agent-based model
- References: Holley and Liggett 1975
Factory
@register_model(
field='social/opinion_dynamics',
tags=('opinion', 'agents', 'network'),
references=('Holley and Liggett 1975',),
defaults={'until': 100},
)
def voter_model(
graph: object = None,
*,
share: float = 0.5,
random_state: int | np.random.Generator | None = 0,
) -> System:
"""Return a voter model with one voter per node of a network.
Args:
graph:
The NetworkX graph, or `None` for a ring of 50 nodes each linked to its four nearest neighbours.
share:
The share of voters with opinion 1.
random_state:
The seed or generator of the opinions.
Returns:
system:
The model, with the group `voters`.
Examples:
>>> import networkx as nx
>>> from skcomplex.models.social.opinion_dynamics import voter_model
>>> voter_model(nx.cycle_graph(8), random_state=0).elements[0].check().prepare().size_
8
"""
rng = np.random.default_rng(random_state)
graph = nx.watts_strogatz_graph(50, 4, 0.0) if graph is None else graph
size = nx.number_of_nodes(graph)
opinions = (rng.random(size) < share).astype(float)
return System(
elements=[GroupElement('voters', element=VoterElement, size=size, values={'opinion': opinions})],
interactions=[VoterImitationInteraction('imitation', target='voters')],
space=NetworkSpace(graph),
)
Components
class VoterElement(Element):
"""Agent of the voter model, whose opinion the imitation sets to that of a random neighbour on a network.
Args:
label:
The label of the agent or group.
visual:
How the agent is drawn, or `None` for `default_visual_`.
opinion:
The initial opinion, 0 or 1.
Examples:
>>> from skcomplex.core.elements import GroupElement
>>> from skcomplex.models.social.opinion_dynamics import VoterElement
>>> group = GroupElement('voters', element=VoterElement, size=20, values={'opinion': 1.0})
>>> group.label, group.element.__name__, group.size
('voters', 'VoterElement', 20)
"""
def __init__(
self,
label: str,
visual: VisualSpec | None = VisualSpec('agents', {'color_by': 'opinion', 'color_range': (0.0, 1.0)}),
*,
opinion: Annotated[float, StateSpec(domain=NN)] = 0.0,
) -> None:
super().__init__(label, visual=visual)
self.opinion = opinion
@classmethod
def _get_view(cls) -> type[VoterView]:
"""Return the class of the views of the agents, whose attributes are the states and parameters."""
return VoterView
class VoterImitationInteraction(MapInteraction):
"""Imitation of the voter model, where every voter in turn adopts the opinion of a random neighbour.
The voters update one after the other in a new random order every step, each reading the opinions the voters before
it set. A voter without a neighbouring voter keeps its opinion.
Args:
label:
The label of the interaction.
target:
The path of the group of voters.
Examples:
>>> from skcomplex.models.social.opinion_dynamics import VoterImitationInteraction
>>> VoterImitationInteraction('imitation', target='voters').check().schedule
'random-sequential'
"""
def __init__(self, label: str, *, target: Annotated[str, RoleSpec()]) -> None:
super().__init__(
label,
target=target,
state='opinion',
function=self._get_opinion,
schedule='random-sequential',
form='agent',
)
def _get_opinion(self, agent: VoterView, model: ModelViewProtocol) -> float:
"""Return the opinion of a random neighbouring voter, or the voter's own without one."""
neighbors = [item for item in agent.neighbors() if isinstance(item, VoterView)]
if not neighbors:
return float(agent.opinion)
return float(neighbors[int(model.rng.integers(len(neighbors)))].opinion)