Voter variants
Voter system variants on a network.
- Class:
VoterVariantsSystem - Import:
from skcomplex.systems.social.opinion_dynamics import VoterVariantsSystem - Field:
social/opinion_dynamics - Topics:
opinion,agents,network,voting,contrarians - References:
- Thurner, Hanel, and Klimek 2018
- Galam 2004
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 VoterVariantsSystem
trajectory = VoterVariantsSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
graph |
None |
threshold |
0.5 |
contrarians |
0.1 |
share |
0.5 |
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 | boolean, integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class VoterVariantsSystem(BaseSystem):
"""Voter system variants on a network.
They have threshold voters and a share of contrarians. The system has the group `voters`.
Args:
graph:
The NetworkX graph, or `None` for a ring of 50 nodes each linked to its four nearest neighbours.
threshold:
The share of disagreeing neighbours above which a voter changes its opinion, 0.5 for the majority rule, or
0 to copy a random neighbour.
contrarians:
The share of voters that are contrarians.
share:
The share of voters with opinion 1.
random_state:
The seed or generator of the opinions and of the contrarians.
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 networkx as nx
>>> from skcomplex.systems.social.opinion_dynamics import VoterVariantsSystem
>>> VoterVariantsSystem(nx.cycle_graph(8), random_state=0).prepare().system_.elements[0].size
8
"""
field = 'social/opinion_dynamics'
topics = ('opinion', 'agents', 'network', 'voting', 'contrarians')
references = ('Thurner, Hanel, and Klimek 2018', 'Galam 2004')
until = 100
def __init__(
self,
graph: object = None,
*,
threshold: float = 0.5,
contrarians: float = 0.1,
share: float = 0.5,
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.graph = graph
self.threshold = threshold
self.contrarians = contrarians
self.share = share
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)
graph = self.graph
rng = np.random.default_rng(self.random_state)
graph = nx.watts_strogatz_graph(50, 4, 0.0) if graph is None else graph
size = nx.number_of_nodes(graph)
voters = VariantVoterElement(
'voters',
opinion=(rng.random(size) < self.share).astype(float),
contrarian=(rng.random(size) < self.contrarians).astype(float),
threshold=self.threshold,
size=size,
)
self.system_ = System(
self.label,
elements=[voters],
interactions=[VariantVotingInteraction('voting', target='voters')],
space=NetworkSpace(graph),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
VariantVoterElement, fromElement
Interactions:
VariantVotingInteraction, fromInteraction
class VariantVoterElement(Element):
"""Agent of the voter system variants.
It is an imitator, a threshold voter, or a contrarian. With a threshold of 0 the voting copies a random neighbour
into the agent, as in the voter system. With a positive threshold it gives the agent the opinion opposite to its own
when the share of neighbours that hold it exceeds the threshold, so a threshold of 0.5 gives the majority rule. A
contrarian adopts the opposite of what it would otherwise adopt.
Args:
label:
The label of the agent or group.
opinion:
The initial opinion, 0 or 1.
contrarian:
Whether the agent is a contrarian, 1, or not, 0.
threshold:
The share of disagreeing neighbours above which the agent changes its opinion, or 0 to copy a random
neighbour.
size:
The number of members, or `None` for one.
Examples:
>>> from skcomplex.systems.social.opinion_dynamics import VariantVoterElement
>>> group = VariantVoterElement('voters', threshold=0.5, size=10)
>>> group.label, type(group).__name__, group.size
('voters', 'VariantVoterElement', 10)
"""
visual = VisualSpec('agents', {'color_by': 'opinion', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
opinion: Annotated[object, NN] = 0.0,
contrarian: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
threshold: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
size: int | None = None,
) -> None:
super().__init__(label, size=size)
self.opinion = opinion
self.contrarian = contrarian
self.threshold = threshold
class VariantVotingInteraction(Interaction):
"""Voting of the voter system variants.
Every voter in turn takes the opinion of its variant. A voter of threshold 0 copies a random neighbour. A voter of
positive threshold adopts the opinion opposite to its own when the share of neighbours that hold it exceeds the
threshold. A contrarian adopts the opposite of what it would otherwise adopt. The voters update one after the other
in a new random order every step, each reading the opinions the voters before it set, and 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.systems.social.opinion_dynamics import VariantVotingInteraction
>>> VariantVotingInteraction('voting', target='voters').target
'voters'
"""
law_classes = (UpdateLaw,)
draws = True
def __init__(self, label: str, *, target: Role) -> None:
super().__init__(label)
self.target = target
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the opinion of the agents, one after the other in a new random order, as the rule of the system.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self._update)]
def _update(self, system: SystemView) -> None:
"""Set the opinion of the agents one after the other in a new random order."""
agents = cast(list[VariantVoterView], system.get_agents('target'))
for index in system.rng.permutation(len(agents)):
agent = agents[int(index)]
if agent.alive:
agent.opinion = float(self._get_opinion(agent, system))
def _get_choice(
self,
agent: VariantVoterView,
neighbors: list[VariantVoterView],
system: SystemViewProtocol,
) -> float:
"""Return the opinion a voter that conforms would take."""
if agent.threshold <= 0:
return float(neighbors[int(system.rng.integers(len(neighbors)))].opinion)
disagreeing = sum(neighbor.opinion != agent.opinion for neighbor in neighbors) / len(neighbors)
return float(1 - agent.opinion) if disagreeing > agent.threshold else float(agent.opinion)
def _get_opinion(self, agent: VariantVoterView, system: SystemViewProtocol) -> float:
"""Return the opinion of the voter's variant, inverted for a contrarian."""
neighbors = cast(list[VariantVoterView], [item for item in agent.get_neighbors() if item.group == agent.group])
if not neighbors:
return float(agent.opinion)
choice = self._get_choice(agent, neighbors, system)
return 1 - choice if agent.contrarian else choice