Skip to content

Opinion dynamics

Opinion dynamics: voting, coevolving networks, persuasion, and more.

It also holds bounded confidence, conventions, and diffusion.

AdopterElement(label, *, adopted=0.0, threshold=50.0, reach=15.0, values=None, size=None, space=None)

Bases: Element

Agent of the threshold adoption system, who adopts an innovation for good.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
adopted Annotated[object, FiniteEnumeratedSet([0, 1])]

Whether the agent starts as an adopter.

0.0
threshold Annotated[object, closed_open(0, oo)]

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

50.0
reach Annotated[object, open(0, oo)]

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

15.0
values Mapping[str, object] | None

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

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

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

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)
Source code in src/skcomplex/systems/social/opinion_dynamics/_diffusion.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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

AdopterView

Bases: AgentViewProtocol, Protocol

View of an agent of the threshold adoption system.

Its states and parameters are attributes.

AdoptionInteraction(label, *, target, mode='infection')

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of adopters.

required
mode str

'infection' or 'influence'.

'infection'

Raises:

Type Description
ValidationError

The mode is unknown.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import AdoptionInteraction
>>> AdoptionInteraction('adoption', target='people', mode='influence').mode
'influence'
Source code in src/skcomplex/systems/social/opinion_dynamics/_diffusion.py
199
200
201
202
203
204
205
206
207
208
def __init__(
    self,
    label: str,
    *,
    target: Role,
    mode: str = 'infection',
) -> None:
    super().__init__(label)
    self.target = target
    self.mode = mode

adopt(system)

Let every agent that has not adopted adopt, from the adoptions at the start of the step.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the adoptions.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_diffusion.py
232
233
234
235
236
237
238
239
240
241
242
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

AxelrodSystem(width=20, height=20, *, features=5, traits=10, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Axelrod's culture dissemination system on a full grid.

The grid has von Neumann neighbourhoods. Every village starts with random traits. For few traits per feature the villages converge to one culture, and for many traits they freeze into many small cultural regions, an order-disorder transition at a critical q. The system has the group villages and the influence influence. culture_observables gives the share of the largest cultural region and the number of cultures.

Parameters:

Name Type Description Default
width int

The number of columns.

20
height int

The number of rows.

20
features int

The number of cultural features F.

5
traits int

The number of traits q of every feature.

10
random_state int | Generator | None

The seed or generator of the initial cultures.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import AxelrodSystem
>>> AxelrodSystem(5, 4).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def __init__(
    self,
    width: int = 20,
    height: int = 20,
    *,
    features: int = 5,
    traits: int = 10,
    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.features = features
    self.traits = traits
    self.random_state = random_state

BelieverElement(label, *, belief=0.0, caring=0.0, influence=1.0, learning=1.0, values=None, size=None, space=None)

Bases: Element

Agent of the belief diffusion system.

It holds the weights it gives to four levels of caring about an issue. The levels are not caring at all, caring less, caring a bit, and caring passionately. An agent cares at the level of its largest weight. In InfluentialsSystem, an agent rule adds every step learning times the influence of every neighbour to the weight of the level the neighbour cares at, a tie broken at random, and a second one sets the level of caring.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
belief ArrayLike

The initial weights of the four levels.

0.0
caring Annotated[object, NN]

The initial level of caring, the index of the largest weight.

0.0
influence Annotated[object, open(0, oo)]

The weight of the agent's own level in the beliefs of its neighbours.

1.0
learning Annotated[object, closed_open(0, oo)]

The increment per neighbour and step.

1.0
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import BelieverElement
>>> group = BelieverElement('people', belief=[1.0, 0.0, 0.0, 0.0], size=4)
>>> group.label, type(group).__name__, group.size
('people', 'BelieverElement', 4)
Source code in src/skcomplex/systems/social/opinion_dynamics/_diffusion.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __init__(
    self,
    label: str,
    *,
    belief: npt.ArrayLike = 0.0,
    caring: Annotated[object, NN] = 0.0,
    influence: Annotated[object, RealSet.open(0, oo)] = 1.0,
    learning: Annotated[object, RealSet.closed_open(0, oo)] = 1.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.belief = belief
    self.caring = caring
    self.influence = influence
    self.learning = learning

BelieverView

Bases: AgentViewProtocol, Protocol

View of an agent of the influentials system.

Its states and parameters are attributes.

CitizenElement(label, *, opinion=0.0, size=None)

Bases: Element

Agent of the Galam majority system, who holds a binary opinion.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, NN]

The initial opinion, 0 or 1.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import CitizenElement
>>> group = CitizenElement('citizens', opinion=1.0, size=10)
>>> group.label, type(group).__name__, group.size
('citizens', 'CitizenElement', 10)
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
109
110
111
112
113
114
115
116
117
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, NN] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion

CitizenView

Bases: AgentViewProtocol, Protocol

View of an agent of the Galam majority system.

Its states and parameters are attributes.

ClubMemberElement(label, *, opinion=0.0, degree=0.0, beta=1.0, appeal=0.0, deciding=0.1, activity=0.5, rewiring=0.5, space=None)

Bases: Element

Agent that is in a club (spin 1) or out of it (spin 0).

A heat bath aligns it with the agents it knows. Every step an agent reconsiders with probability deciding and then joins with probability 1 / (1 + exp(-2 β h)), where the field h counts the acquaintances in the club minus those out of it, plus the appeal of the club. The interaction SeparationInteraction dissolves acquaintances between a member and an outsider and reforms them towards an agent of the same side.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, closed_open(0, oo)]

1 for a member of the club and 0 for an outsider.

0.0
degree Annotated[object, closed_open(0, oo)]

The number of acquaintances, read at the start of every step.

0.0
beta Annotated[object, closed_open(0, oo)]

The inverse temperature of the heat bath.

1.0
appeal object

The field of the club on every agent, positive for an attractive club.

0.0
deciding Annotated[object, closed_open(0, oo)]

The probability that an agent reconsiders its choice in a step.

0.1
activity Annotated[object, closed_open(0, oo)]

The probability that an acquaintance is reconsidered in a step.

0.5
rewiring Annotated[object, closed_open(0, oo)]

The probability that a reconsidered acquaintance across the club boundary dissolves and reforms.

0.5
space BaseSpace | None

The network whose nodes hold one agent each, or None for one agent.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ClubMemberElement
>>> ClubMemberElement('agents', beta=2.0).beta
2.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_coevolution.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    degree: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    beta: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    appeal: object = 0.0,
    deciding: Annotated[object, RealSet.closed_open(0, oo)] = 0.1,
    activity: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    rewiring: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.opinion = opinion
    self.degree = degree
    self.beta = beta
    self.appeal = appeal
    self.deciding = deciding
    self.activity = activity
    self.rewiring = rewiring

CoevolvingVoterElement(label, *, opinion=0.0, degree=0.0, activity=0.5, rewiring=0.3, space=None)

Bases: Element

Voter of a coevolving network, with a binary opinion and its degree.

It also holds its number of discordant neighbours. Every step a voter is active with probability activity and picks a random neighbour. When the neighbour disagrees, the voter copies its opinion with probability 1 - rewiring, and otherwise the interaction SeparationInteraction moves the edge to a random voter who agrees with it.

Parameters:

Name Type Description Default
label str

The label of the voter or the group.

required
opinion Annotated[object, closed_open(0, oo)]

The opinion, 0 or 1.

0.0
degree Annotated[object, closed_open(0, oo)]

The number of neighbours, read at the start of every step.

0.0
activity Annotated[object, closed_open(0, oo)]

The probability that a voter acts in a step.

0.5
rewiring Annotated[object, closed_open(0, oo)]

The probability that an active voter with a discordant neighbour rewires instead of copying.

0.3
space BaseSpace | None

The network whose nodes hold the voters, or None for one voter.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import CoevolvingVoterElement
>>> CoevolvingVoterElement('voters', rewiring=0.3).rewiring
0.3
Source code in src/skcomplex/systems/social/opinion_dynamics/_coevolution.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    degree: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    activity: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    rewiring: Annotated[object, RealSet.closed_open(0, oo)] = 0.3,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.opinion = opinion
    self.degree = degree
    self.activity = activity
    self.rewiring = rewiring

CoevolvingVoterSystem(n_voters=200, *, mean_degree=4.0, rewiring=0.3, activity=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The coevolving voter system.

It fragments into consensual components when rewiring is fast. Voters on an Erdős-Rényi graph copy discordant neighbours or rewire the discordant edges to like-minded voters. Below a critical rewiring probability, near 0.38 for mean degree 4, the network stays connected and discordant edges survive for long times, and above it the network splits into components of one opinion. The system has the groups voters and ties and the interaction separation.

Parameters:

Name Type Description Default
n_voters int

The number of voters.

200
mean_degree float

The mean degree of the initial random graph.

4.0
rewiring float

The probability that an active voter with a discordant neighbour rewires instead of copying.

0.3
activity float

The probability that a voter acts in a step.

0.5
random_state int | Generator | None

The seed or generator of the graph and of the uniform random opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import CoevolvingVoterSystem
>>> trajectory = CoevolvingVoterSystem(30).prepare().simulate(until=5, random_state=0)
>>> int(trajectory.get_network(-1).sources.size) == int(trajectory.get_network(0).sources.size)
True
Source code in src/skcomplex/systems/social/opinion_dynamics/_coevolution.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def __init__(
    self,
    n_voters: int = 200,
    *,
    mean_degree: float = 4.0,
    rewiring: float = 0.3,
    activity: 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.n_voters = n_voters
    self.mean_degree = mean_degree
    self.rewiring = rewiring
    self.activity = activity
    self.random_state = random_state

CognitiveConsistencySystem(graph=None, *, positive=0.7, decay=0.05, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Agents whose attitudes spread by conversation and settle in a belief network.

The belief network seeks consistency. The system has the group thinkers.

Parameters:

Name Type Description Default
graph object

The NetworkX graph, or None for a complete graph of 40 agents.

None
positive float

The share of agents that start in the positive state, F1 = X = 1 and F2 = -1, the others starting in the negative state.

0.7
decay float

The fraction of every valence lost per update of the belief network.

0.05
random_state int | Generator | None

The seed or generator of the initial states.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> import networkx as nx
>>> from skcomplex.systems.social.opinion_dynamics import CognitiveConsistencySystem
>>> system = CognitiveConsistencySystem(nx.complete_graph(6), random_state=0).prepare().system_
>>> system.elements[0].size
6
Source code in src/skcomplex/systems/social/opinion_dynamics/_cognition.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def __init__(
    self,
    graph: object = None,
    *,
    positive: float = 0.7,
    decay: float = 0.05,
    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.positive = positive
    self.decay = decay
    self.random_state = random_state

ComplexAgentElement(label, *, configuration=2.0, spin=0.0, size=None)

Bases: Element

Agent with many internal configurations.

Two of them show a characteristic with the spin 1 or -1. Configuration 0 has the spin S = 1, configuration 1 the spin S = -1, and the configurations from 2 to H + 1 the spin 0. In StandardizedAgentsSystem, an agent rule sets the spin after every change of configuration.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
configuration Annotated[object, NN]

The internal configuration, from 0 to H + 1.

2.0
spin Annotated[object, ZZ]

The spin of the configuration.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ComplexAgentElement
>>> ComplexAgentElement('agents', configuration=5.0, spin=0.0, size=10).size
10
Source code in src/skcomplex/systems/social/opinion_dynamics/_standardization.py
68
69
70
71
72
73
74
75
76
77
78
def __init__(
    self,
    label: str,
    *,
    configuration: Annotated[object, NN] = 2.0,
    spin: Annotated[object, ZZ] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.configuration = configuration
    self.spin = spin

ComplexAgentView

Bases: AgentViewProtocol, Protocol

View of an agent of the standardization system.

Its states and parameters are attributes.

ConfidenceCouplingInteraction(label, *, target, state='opinion')

Bases: 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.

Parameters:

Name Type Description Default
label str

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

required
target Role

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

required
state str

The name of the state that holds the opinions.

'opinion'

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]
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
164
165
166
167
def __init__(self, label: str, *, target: Role, state: str = 'opinion') -> None:
    super().__init__(label)
    self.target = target
    self.state = state

ConfidentElement(label, *, opinion=0.5, confidence=0.2, space=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, closed_open(0, oo)]

The opinion, between 0 and 1.

0.5
confidence Annotated[object, closed_open(0, oo)]

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

0.2
space BaseSpace | None

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

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ConfidentElement
>>> ConfidentElement('people', confidence=0.1).confidence
0.1
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
63
64
65
66
67
68
69
70
71
72
73
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

ConnectionElement(label, *, A=0.0, space=None, on=None)

Bases: Element

Edge of a network with a connection A, the phase an agent transports along it.

Parameters:

Name Type Description Default
label str

The label of the edge or the group on the edges.

required
A object

The connection along the direction of the edge.

0.0
space BaseSpace | None

The network whose edges hold the connections, or None for one edge.

None
on str | None

'edges' for one connection per edge of a network space, or None for one per site.

None

Attributes:

Name Type Description
default_visual_

How the edge is drawn by default, the visual of its class.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ConnectionElement
>>> ConnectionElement('edge', A=0.5).A
0.5
Source code in src/skcomplex/systems/social/opinion_dynamics/_gauge_agents.py
135
136
137
138
139
140
141
142
143
144
def __init__(
    self,
    label: str,
    *,
    A: object = 0.0,
    space: BaseSpace | None = None,
    on: str | None = None,
) -> None:
    super().__init__(label, space=space, on=on)
    self.A = A

ConversationsInteraction(label, *, target, phase=None)

Bases: NeighborhoodsInteraction

Conversations of the cognitive consistency system.

There is one per agent and step, the agents speaking in random order. A speaker talks to a random neighbour about F1 or F2. The hearer averages its valence of the topic with the speaker's and settles its belief network, and its attitude is its valence of X.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of thinkers.

required
phase str | None

The phase of the step the conversations run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ConversationsInteraction
>>> ConversationsInteraction('talks', target='thinkers').target
'thinkers'
Source code in src/skcomplex/systems/social/opinion_dynamics/_cognition.py
157
158
159
160
161
162
163
164
def __init__(
    self,
    label: str,
    *,
    target: Role,
    phase: str | None = None,
) -> None:
    super().__init__(label, target=target, phase=phase)

act_on(members, system)

Let the first member speak to a random neighbour.

The neighbour averages the topic and settles its beliefs.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The speaker, followed by its neighbours.

required
system SystemView

The system view of the rule.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_cognition.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def act_on(self, members: list[AgentViewProtocol], system: SystemView) -> None:
    """Let the first member speak to a random neighbour.

    The neighbour averages the topic and settles its beliefs.

    Args:
        members:
            The speaker, followed by its neighbours.

        system:
            The system view of the rule.
    """
    speaker, *neighbors = cast(list[ThinkerView], members)
    if not neighbors:
        return
    hearer = neighbors[int(system.rng.integers(len(neighbors)))]
    topic = TOPICS[int(system.rng.integers(len(TOPICS)))]
    valences = np.array(hearer.valences, dtype=np.float64)
    valences[topic] = (valences[topic] + np.asarray(speaker.valences, dtype=np.float64)[topic]) / 2
    settled = settle(valences, hearer.decay)
    hearer.valences, hearer.attitude = settled, float(settled[1])

CulturalInfluenceInteraction(label, *, target, phase=None)

Bases: NeighborhoodsInteraction

Cultural influence of Axelrod's system.

Every step every village, in random order, picks a random neighbour and, with probability equal to the fraction of features they share, copies the trait of one feature on which they differ.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of villages.

required
phase str | None

The phase of the step the influence runs in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import CulturalInfluenceInteraction
>>> CulturalInfluenceInteraction('influence', target='villages').target
'villages'
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
145
146
147
148
149
150
151
152
def __init__(
    self,
    label: str,
    *,
    target: Role,
    phase: str | None = None,
) -> None:
    super().__init__(label, target=target, phase=phase)

act_on(members, system)

Copy one differing trait of a random neighbour.

The probability is equal to the cultural overlap.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The village, followed by its neighbours.

required
system SystemView

The system view of the rule.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def act_on(self, members: list[AgentViewProtocol], system: SystemView) -> None:
    """Copy one differing trait of a random neighbour.

    The probability is equal to the cultural overlap.

    Args:
        members:
            The village, followed by its neighbours.

        system:
            The system view of the rule.
    """
    agent, *neighbors = cast(list[VillageView], members)
    if not neighbors:
        return
    neighbor = neighbors[int(system.rng.integers(len(neighbors)))]
    features, traits = int(agent.features), int(agent.traits)
    own = cultural_traits(agent.culture, features, traits)
    other = cultural_traits(neighbor.culture, features, traits)
    different = np.flatnonzero(own != other)
    if len(different) and system.rng.random() < 1 - len(different) / features:
        feature = int(different[int(system.rng.integers(len(different)))])
        agent.culture += float((int(other[feature]) - int(own[feature])) * traits**feature)

DeffuantSystem(n_agents=200, *, confidence=0.2, convergence=0.5, steepness=None, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Deffuant bounded confidence system.

Its opinions settle into about 1 / (2 * confidence) clusters. The system has the group people.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

200
confidence float

The largest opinion difference at which two agents compromise.

0.2
convergence float

The fraction of the difference by which each agent of a compromising pair moves.

0.5
steepness float | None

The steepness of the probability that a pair compromises, after Lenti et al. (2023), or None for the deterministic threshold of the confidence.

None
random_state int | Generator | None

The seed or generator of the uniform initial opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import DeffuantSystem
>>> DeffuantSystem(20, random_state=0).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def __init__(
    self,
    n_agents: int = 200,
    *,
    confidence: float = 0.2,
    convergence: float = 0.5,
    steepness: float | 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.convergence = convergence
    self.steepness = steepness
    self.random_state = random_state

DiscussantElement(label, *, opinion=0.5, confidence=0.2, convergence=0.5, size=None)

Bases: Element

Agent of the Deffuant system, with a continuous opinion and a confidence bound.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, closed_open(0, oo)]

The initial opinion, between 0 and 1.

0.5
confidence Annotated[object, closed_open(0, oo)]

The largest opinion difference at which two agents still compromise.

0.2
convergence Annotated[object, closed_open(0, oo)]

The fraction of the opinion difference by which each agent of a compromising pair moves.

0.5
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import DiscussantElement
>>> group = DiscussantElement('people', opinion=0.5, size=10)
>>> group.label, type(group).__name__, group.size
('people', 'DiscussantElement', 10)
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
115
116
117
118
119
120
121
122
123
124
125
126
127
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,
    convergence: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion
    self.confidence = confidence
    self.convergence = convergence

DiscussantView

Bases: AgentViewProtocol, Protocol

View of an agent of the Deffuant bounded confidence system.

Its states and parameters are attributes.

DiscussionsInteraction(label, *, among, along=TRIPLES)

Bases: Interaction

Discussions of the Galam system.

They split the citizens into random groups that adopt their majority opinion, drawn again at every step. A tie in a group of even size goes to opinion 0, the status quo.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
among Role

The path of the group of citizens.

required
along RandomPartition

The random groups of the discussions, such as RandomPartition(3) for groups of three citizens, the last group holding the remainder.

TRIPLES

Examples:

>>> from skcomplex.core.components.interactions import RandomPartition
>>> from skcomplex.systems.social.opinion_dynamics import DiscussionsInteraction
>>> DiscussionsInteraction('talks', among='citizens', along=RandomPartition(4)).along
RandomPartition(size=4)
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
227
228
def __init__(self, label: str, *, among: Role, along: RandomPartition = TRIPLES) -> None:
    super().__init__(label, among=among, along=along)

EchoChamberRadicalizationSystem(n_agents=200, *, strength=3.0, controversy=3.0, homophily=3.0, contacts=10, reciprocity=0.5, exponent=2.1, least_activity=0.01, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The radicalization model of echo chambers of Baumann and coauthors.

It runs on an activity-driven network. Opinions follow dx_i/dt = -x_i + K sum_j A_ij(t) tanh(alpha x_j), where the controversialness alpha shapes the influence and A_ij(t) is an activity-driven temporal network redrawn at every integration step dt = 0.01: agent i is active with the probability a_i, drawn from F(a) ~ a^-gamma on [epsilon, 1], and contacts m others with the homophilic probability |x_i - x_j|^-beta / sum_j |x_i - x_j|^-beta, and a contact is reciprocated with the probability r (arXiv 1906.12325 Eqs. 1 and 2). Opinions start uniformly spaced on [-1, 1]. For small K alpha they reach the neutral consensus, above alpha_c = 1 / ((1 + r) K m <a>) they radicalize, all to one side without homophily (beta = 0), and into two opposite echo chambers with it. The defaults are the polarized case of Fig. 1(c), K = 3, alpha = 3, beta = 3, r = 0.5, m = 10, and gamma = 2.1, with fewer agents than the 1000 of the paper so a step is fast. Every step of the system is ten integration steps.

The system has the group agents.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

200
strength float

The social interaction strength K.

3.0
controversy float

The controversialness alpha.

3.0
homophily float

The exponent beta of the homophily of the contacts.

3.0
contacts int

The number m of distinct agents an active agent contacts.

10
reciprocity float

The probability r that a contact is reciprocated.

0.5
exponent float

The exponent gamma of the power law of the activities.

2.1
least_activity float

The least activity epsilon.

0.01
random_state int | Generator | None

The seed or generator of the activities.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import EchoChamberRadicalizationSystem
>>> EchoChamberRadicalizationSystem(50).prepare().system_.elements[0].size
50
Source code in src/skcomplex/systems/social/opinion_dynamics/_echo_chambers.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def __init__(
    self,
    n_agents: int = 200,
    *,
    strength: float = 3.0,
    controversy: float = 3.0,
    homophily: float = 3.0,
    contacts: int = 10,
    reciprocity: float = 0.5,
    exponent: float = 2.1,
    least_activity: float = 0.01,
    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.strength = strength
    self.controversy = controversy
    self.homophily = homophily
    self.contacts = contacts
    self.reciprocity = reciprocity
    self.exponent = exponent
    self.least_activity = least_activity
    self.random_state = random_state

EncountersInteraction(label, *, target, phase=None, steepness=None)

Bases: RandomPairsInteraction

Random binary encounters of the Deffuant system.

There are as many per step as there are agents. In every encounter two random agents move towards each other by the convergence fraction of their difference when a Bernoulli outcome, drawn by the name outcome, is 1. Without a steepness the outcome is 1 when their opinions differ by less than the confidence bound. With a steepness rho it is 1 with the probability 1 / (1 + exp(-rho * (confidence - |x_u - x_v|))) of Lenti et al. (2023), which approaches the threshold as rho grows. Runs record and replay the outcomes.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of discussants.

required
phase str | None

The phase of the step the encounters run in, or None for the default phase.

None
steepness float | None

The steepness rho of the probability of a compromise, or None for the deterministic threshold.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import EncountersInteraction
>>> EncountersInteraction('meetings', target='people', steepness=20.0).steepness
20.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
212
213
214
215
216
217
218
219
220
221
def __init__(
    self,
    label: str,
    *,
    target: Role,
    phase: str | None = None,
    steepness: float | None = None,
) -> None:
    super().__init__(label, target=target, phase=phase)
    self.steepness = steepness

act_on(members, system)

Move the opinions of a pair towards each other when their drawn outcome is 1.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The two discussants of the encounter.

required
system SystemView

The system view of the rule.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def act_on(self, members: list[AgentViewProtocol], system: SystemView) -> None:
    """Move the opinions of a pair towards each other when their drawn outcome is 1.

    Args:
        members:
            The two discussants of the encounter.

        system:
            The system view of the rule.
    """
    first, second = cast(list[DiscussantView], members)
    difference = second.opinion - first.opinion
    gap = first.confidence - abs(difference)
    probability = float(gap > 0) if self.steepness is None else float(expit(self.steepness * gap))
    if system.draw('outcome', 'bernoulli', p=probability):
        first.opinion += first.convergence * difference
        second.opinion -= first.convergence * difference

GalamMajoritySystem(n_agents=300, *, group_size=3, share=0.4, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Galam majority system.

Random groups adopt their majority until one opinion wins. The system has the group citizens.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

300
group_size int

The number of agents in each discussion group.

3
share float

The share of agents with opinion 1.

0.4
random_state int | Generator | None

The seed or generator of the opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import GalamMajoritySystem
>>> GalamMajoritySystem(30, random_state=0).prepare().system_.elements[0].size
30
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
def __init__(
    self,
    n_agents: int = 300,
    *,
    group_size: int = 3,
    share: float = 0.4,
    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.group_size = group_size
    self.share = share
    self.random_state = random_state

GaugeNetworkAgentsSystem(n_agents=12, *, flux=0.0, K=1.0, spread=1.0, connections=None, graph=None, seed=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Agent phases on the nodes of a network.

They relax towards the transported phases of their neighbours. Agent i follows theta_i' = K sum_j sin(theta_j - theta_i - A_ij) over its neighbours. A connection whose oriented sum around a loop is not a multiple of 2 pi frustrates the loop: the transported differences cannot all vanish, so the agents keep a residual energy sum (1 - cos(theta_j - theta_i - A_ij)) and a twist around the loop.

Parameters:

Name Type Description Default
n_agents int

The number of agents on a ring, when no graph is given.

12
flux float

The oriented sum of the connection around the first face of the minimum cycle basis, spread evenly over the edges of that face.

0.0
K float

The coupling strength.

1.0
spread float

The largest absolute initial phase.

1.0
connections Sequence[float] | None

The connection of every edge, in place of flux, or None.

None
graph Graph | None

The network, or None for a ring of n_agents.

None
seed int

The seed of the initial phases.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Raises:

Type Description
ValidationError

A flux is given on a network without faces.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import GaugeNetworkAgentsSystem
>>> [element.label for element in GaugeNetworkAgentsSystem(4).prepare().system_.elements]
['agents', 'links']
Source code in src/skcomplex/systems/social/opinion_dynamics/_gauge_agents.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def __init__(
    self,
    n_agents: int = 12,
    *,
    flux: float = 0.0,
    K: float = 1.0,
    spread: float = 1.0,
    connections: Sequence[float] | None = None,
    graph: nx.Graph | None = None,
    seed: int = 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.flux = flux
    self.K = K
    self.spread = spread
    self.connections = connections
    self.graph = graph
    self.seed = seed

HegselmannKrauseSystem(n_agents=200, *, confidence=0.15, graph=None, random_state=0, label='system', solver='auto', backend='auto')

Bases: 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.

Parameters:

Name Type Description Default
n_agents int

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

200
confidence float

The confidence ε.

0.15
graph Graph | None

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

None
random_state int | Generator | None

The seed or generator of the uniform initial opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

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
Source code in src/skcomplex/systems/social/opinion_dynamics/_bounded_confidence.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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

HypergraphConsensusSystem(n_nodes=30, *, triangles=0.05, reinforcement=-1.0, period=2.0, seed=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The nonlinear three-body consensus system on a random hypergraph of triangles.

The triangles switch on and off. Every triple of nodes is a triangle with probability triangles, and every triangle is active in alternate half periods from a random phase. On an active triangle ijk, node i follows x_i' = s(|x_j - x_k|) (x_j + x_k - 2 x_i) with s(d) = exp(reinforcement * d). Without reinforcement the pulls of a triangle on its three members sum to zero, so the mean opinion stays fixed whatever the schedules. With reinforcement the pull depends on the member it acts on, and the mean opinion drifts towards the pairs that agree, for a negative reinforcement, while the opinions still reach a consensus on a connected hypergraph.

The system has the opinions nodes.x, the mean opinion mean_opinion, and the mean squared opinion spread.

Parameters:

Name Type Description Default
n_nodes int

The number of nodes.

30
triangles float

The probability that a triple of nodes is a triangle.

0.05
reinforcement float

The exponent of the modulating function s.

-1.0
period float

The period of the schedules of the triangles.

2.0
seed int

The seed of the hypergraph, the phases, and the opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import HypergraphConsensusSystem
>>> system = HypergraphConsensusSystem(8, triangles=0.5).prepare().system_
>>> system.elements[0].x.size
8
Source code in src/skcomplex/systems/social/opinion_dynamics/_hypergraph_consensus.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def __init__(
    self,
    n_nodes: int = 30,
    *,
    triangles: float = 0.05,
    reinforcement: float = -1.0,
    period: float = 2.0,
    seed: int = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_nodes = n_nodes
    self.triangles = triangles
    self.reinforcement = reinforcement
    self.period = period
    self.seed = seed

InfluenceeElement(label, *, opinion=1.0, persuasiveness=1.0, supportiveness=1.0, exponent=2.0, noise=0.0, x=0, y=0, size=None, space=None)

Bases: Element

Agent of the social impact system.

It holds an opinion of -1 or 1, a persuasiveness, and a supportiveness.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, ZZ]

The initial opinion, -1 or 1.

1.0
persuasiveness Annotated[object, closed_open(0, oo)]

The strength with which the agent persuades agents of the other opinion.

1.0
supportiveness Annotated[object, closed_open(0, oo)]

The strength with which the agent supports agents of its opinion.

1.0
exponent Annotated[object, open(0, oo)]

The exponent of the distance by which impact decays.

2.0
noise Annotated[object, closed_open(0, oo)]

The half-width of the uniform random field added to the impact on every agent and step.

0.0
x object

The column of the cell of the agent on a lattice, one per agent or shared.

0
y object

The row of the cell of the agent on a lattice, one per agent or shared.

0
size int | None

The number of agents, or None for one.

None
space BaseSpace | None

The lattice the agents live on, whose axes x and y make x and y their cell, or None.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import InfluenceeElement
>>> group = InfluenceeElement('people', opinion=-1.0, size=4)
>>> group.label, type(group).__name__, group.size
('people', 'InfluenceeElement', 4)
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, ZZ] = 1.0,
    persuasiveness: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    supportiveness: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    exponent: Annotated[object, RealSet.open(0, oo)] = 2.0,
    noise: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    x: object = 0,
    y: object = 0,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, size=size, space=space)
    self.opinion = opinion
    self.persuasiveness = persuasiveness
    self.supportiveness = supportiveness
    self.exponent = exponent
    self.noise = noise
    self.x = x
    self.y = y

InfluenceeView

Bases: AgentViewProtocol, Protocol

View of an agent of the social impact system.

Its states and parameters are attributes.

InfluentialsSystem(width=20, height=20, *, n_influentials=10, influence=3.0, news_report=False, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The belief diffusion system with influentials.

The influentials care passionately and weigh more with their neighbours. Every cell of a torus holds one agent whose weights start uniform on 0 to 4. Every agent in turn, in a random order, learns from its neighbours and then sets its level of caring. The system has the group people.

Parameters:

Name Type Description Default
width int

The number of columns.

20
height int

The number of rows.

20
n_influentials int

The number of influentials, chosen at random.

10
influence float

The influence of an influential, the others having influence 1.

3.0
news_report bool

Whether a news report adds one to every agent's weight of caring passionately at the start.

False
random_state int | Generator | None

The seed or generator of the initial beliefs and of the influentials.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import InfluentialsSystem
>>> InfluentialsSystem(5, 4, n_influentials=2, random_state=0).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/social/opinion_dynamics/_diffusion.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def __init__(
    self,
    width: int = 20,
    height: int = 20,
    *,
    n_influentials: int = 10,
    influence: float = 3.0,
    news_report: bool = False,
    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.n_influentials = n_influentials
    self.influence = influence
    self.news_report = news_report
    self.random_state = random_state

JoinAClubSystem(n_agents=200, *, mean_degree=6.0, beta=0.5, appeal=0.0, rewiring=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Join-a-club spins.

Agents join a club with their acquaintances while acquaintances follow the club. Agents of an Erdős-Rényi graph are in or out of a club, a spin, and choose by a heat bath with the inverse temperature beta in the field of their acquaintances and of the appeal of the club. Acquaintances across the club boundary dissolve and reform among agents on the same side. Without coupling the choices stay random and many acquaintances cross the boundary, and with strong coupling the members and the outsiders separate into communities with few acquaintances between them. The system has the groups voters and ties and the interaction separation.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

200
mean_degree float

The mean number of acquaintances.

6.0
beta float

The inverse temperature of the heat bath.

0.5
appeal float

The field of the club on every agent.

0.0
rewiring float

The probability that a reconsidered acquaintance across the club boundary reforms on one side.

0.5
random_state int | Generator | None

The seed or generator of the graph and of the uniform random choices.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import JoinAClubSystem
>>> type(JoinAClubSystem(30).prepare().system_.elements[0]).__name__
'ClubMemberElement'
Source code in src/skcomplex/systems/social/opinion_dynamics/_coevolution.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def __init__(
    self,
    n_agents: int = 200,
    *,
    mean_degree: float = 6.0,
    beta: float = 0.5,
    appeal: float = 0.0,
    rewiring: 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.n_agents = n_agents
    self.mean_degree = mean_degree
    self.beta = beta
    self.appeal = appeal
    self.rewiring = rewiring
    self.random_state = random_state

KineticOpinionSystem(levels=7, *, confidence=2, persuasion=0.3, repulsion=0.1, eta=1.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The kinetic system of opinion formation over a discrete grid of opinions.

The population is a distribution over opinion levels from -1 to 1, a site group on a lattice of the levels, which starts almost uniform with a slight lean toward positive opinions. Encounters between levels move an opinion one level toward a close opinion and one level away from a distant one, and keep the total density. With a wide confidence the opinions reach a consensus around the mean, and with a narrow confidence and repulsion they polarise into the two extremes.

The system has the distribution opinions and the encounters encounters. Its standard observables are the mean opinion and the variance of the opinions.

Parameters:

Name Type Description Default
levels int

The number of opinion levels.

7
confidence int

The largest distance in levels at which encounters persuade.

2
persuasion float

The probability of moving toward a close opinion.

0.3
repulsion float

The probability of moving away from a distant opinion.

0.1
eta float

The encounter rate.

1.0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import KineticOpinionSystem
>>> KineticOpinionSystem(levels=5).prepare().system_.elements[0].x.size
5
Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def __init__(
    self,
    levels: int = 7,
    *,
    confidence: int = 2,
    persuasion: float = 0.3,
    repulsion: float = 0.1,
    eta: float = 1.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.levels = levels
    self.confidence = confidence
    self.persuasion = persuasion
    self.repulsion = repulsion
    self.eta = eta

MajorityRuleInteraction(label, *, target='voters')

Bases: Interaction

Majority rule of voters on a lattice: every voter takes the opinion of most of its Moore neighbourhood.

The neighbourhood holds the voter and its eight neighbours, so it has no ties, and a voter takes opinion 1 when at least five of the nine hold it.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The voters whose state opinion the rule updates.

'voters'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import MajorityRuleInteraction
>>> MajorityRuleInteraction('majority', target='voters').target
'voters'
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
312
313
314
def __init__(self, label: str, *, target: Role = 'voters') -> None:
    super().__init__(label)
    self.target = target

MajorityRuleSystem(shape=(100, 100), *, density=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Voters that take the majority opinion of their neighbourhood.

The opinions coarsen into domains. Every step every voter takes the opinion of the majority of its eight Moore neighbours and keeps its own when they tie, the majority rule of Argun et al. (2021, section 4.3). The system has the opinions voters.opinion.

Parameters:

Name Type Description Default
shape Sequence[int]

The number of rows and columns.

(100, 100)
density float

The probability that a voter starts with opinion 1.

0.5
random_state int | Generator | None

The seed or generator of the initial opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import MajorityRuleSystem
>>> MajorityRuleSystem((10, 10)).prepare().system_.elements[0].opinion.size
100
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def __init__(
    self,
    shape: Sequence[int] = (100, 100),
    *,
    density: 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.shape = shape
    self.density = density
    self.random_state = random_state

MajorityVoterElement(label, *, opinion=0, space=None)

Bases: Element

Cell that takes the majority opinion of its Moore neighbourhood.

The neighbourhood includes the cell itself. The majority rule is a MajorityRuleInteraction of the lattice, which MajorityRuleSystem adds.

Parameters:

Name Type Description Default
label str

The label of the cell or the lattice group.

required
opinion Annotated[object, FiniteEnumeratedSet([0, 1])]

The initial opinion, 0 or 1.

0
space BaseSpace | None

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

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import MajorityVoterElement
>>> MajorityVoterElement('cell', opinion=1).opinion
1
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
54
55
56
57
58
59
60
61
62
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.opinion = opinion

MeetingsInteraction(label, *, target, phase=None)

Bases: Interaction

Rule of the system that lets groups of agents act together at every step.

Every step the groups that _get_groups returns act in random order through act_on, which a subclass overrides, such as the pairs of a naming game or the neighbourhoods of Axelrod's cultures.

Parameters:

Name Type Description Default
label str

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

required
target Role

The path of the group whose agents meet.

required
phase str | None

The phase of the step the meetings run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import MeetingsInteraction
>>> MeetingsInteraction('meetings', target='people').target
'people'
Source code in src/skcomplex/systems/social/opinion_dynamics/_random_pairs.py
47
48
49
50
def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

act_on(members, system)

Act on the members of one group, which a subclass does.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The agents of the group.

required
system SystemView

The system view of the rule.

required

Raises:

Type Description
ValidationError

The class does not override act_on.

Source code in src/skcomplex/systems/social/opinion_dynamics/_random_pairs.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def act_on(self, members: list[AgentViewProtocol], system: SystemView) -> None:
    """Act on the members of one group, which a subclass does.

    Args:
        members:
            The agents of the group.

        system:
            The system view of the rule.

    Raises:
        ValidationError:
            The class does not override `act_on`.
    """
    del members, system
    error_msg = f'The interaction {self.label!r} has no action. Override `act_on` in a subclass.'
    raise ValidationError(error_msg)

NamerElement(label, *, words=0.0, size=None)

Bases: Element

Agent of the naming game, with an inventory of the words it knows.

The words name one object. The inventory is an indicator vector over the lexicon, with one slot per agent for the word that agent invents when it first speaks with an empty inventory.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
words ArrayLike

The initial inventory, 1 for every known word and 0 otherwise.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> import numpy as np
>>> from skcomplex.systems.social.opinion_dynamics import NamerElement
>>> group = NamerElement('namers', words=np.zeros((5, 5)), size=5)
>>> group.label, type(group).__name__, group.size
('namers', 'NamerElement', 5)
Source code in src/skcomplex/systems/social/opinion_dynamics/_conventions.py
55
56
57
58
59
60
61
62
63
def __init__(
    self,
    label: str,
    *,
    words: npt.ArrayLike = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.words = words

NamerView

Bases: AgentViewProtocol, Protocol

View of an agent of the naming game.

Its states and parameters are attributes.

NamingGameSystem(n_agents=50, *, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The minimal naming game, where agents with empty inventories agree on one word.

The system has the group namers.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

50
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import NamingGameSystem
>>> NamingGameSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/social/opinion_dynamics/_conventions.py
155
156
157
158
159
160
161
162
163
164
def __init__(
    self,
    n_agents: int = 50,
    *,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_agents = n_agents

NamingGamesInteraction(label, *, target, phase=None)

Bases: RandomPairsInteraction

Pairwise games of the minimal naming game, as many per step as there are agents.

A random speaker says a random word of its inventory to a random hearer. When the hearer knows it, both keep that word alone, and otherwise the hearer adds it. A speaker with an empty inventory first invents a word that no agent knows.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of namers.

required
phase str | None

The phase of the step the games run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import NamingGamesInteraction
>>> NamingGamesInteraction('games', target='namers').target
'namers'
Source code in src/skcomplex/systems/social/opinion_dynamics/_random_pairs.py
47
48
49
50
def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

act_on(members, system)

Play one naming game between the first member and the second.

The first member is the speaker, and the second the hearer.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The speaker and the hearer.

required
system SystemView

The system view of the rule.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_conventions.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def act_on(self, members: list[AgentViewProtocol], system: SystemView) -> None:
    """Play one naming game between the first member and the second.

    The first member is the speaker, and the second the hearer.

    Args:
        members:
            The speaker and the hearer.

        system:
            The system view of the rule.
    """
    speaker, hearer = cast(list[NamerView], members)
    spoken = np.array(speaker.words, dtype=np.float64)
    heard = np.array(hearer.words, dtype=np.float64)
    if not spoken.any():
        self._invent(spoken, system)
    known = np.flatnonzero(spoken)
    name = known[int(system.rng.integers(len(known)))]
    if heard[name]:
        spoken[:] = heard[:] = 0.0
        spoken[name] = heard[name] = 1.0
    else:
        heard[name] = 1.0
    speaker.words, hearer.words = spoken, heard

NeighborhoodsInteraction(label, *, target, phase=None)

Bases: MeetingsInteraction

Rule of the system that groups every agent with the agents in the cells or nodes around it.

Every step the groups act in random order through act_on, which a subclass overrides, with the agent first and its neighbours after it, as in the cultural influence of Axelrod or the persuasion of social impact.

Parameters:

Name Type Description Default
label str

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

required
target Role

The path of the group whose agents meet their neighbours.

required
phase str | None

The phase of the step the encounters run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import NeighborhoodsInteraction
>>> NeighborhoodsInteraction('meetings', target='villages').target
'villages'
Source code in src/skcomplex/systems/social/opinion_dynamics/_random_pairs.py
47
48
49
50
def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

OpinionElement(label, *, x=0.0, space=None)

Bases: Element

Node of a consensus process with a continuous opinion.

Parameters:

Name Type Description Default
label str

The label of the node or the group.

required
x object

The initial opinion.

0.0
space BaseSpace | None

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

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import OpinionElement
>>> OpinionElement('node', x=0.5).x
0.5
Source code in src/skcomplex/systems/social/opinion_dynamics/_hypergraph_consensus.py
55
56
57
58
59
60
61
62
63
def __init__(
    self,
    label: str,
    *,
    x: object = 0.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.x = x

OpinionEncountersInteraction(label, *, candidate, field, levels=7, confidence=2, eta=1.0, persuasion=0.3, repulsion=0.1)

Bases: EncounterInteraction

Conservative encounters between opinion levels.

They persuade close opinions and repel distant ones.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
candidate Role

The path of the distribution over opinion levels whose members move.

required
field Role

The path of the distribution over opinion levels they meet, usually the same distribution.

required
levels Annotated[int, open(0, oo)]

The number of opinion levels.

7
confidence Annotated[int, closed_open(0, oo)]

The largest distance in levels at which encounters persuade.

2
eta Annotated[float, closed_open(0, oo)]

The encounter rate.

1.0
persuasion Annotated[float, closed_open(0, oo)]

The probability of moving toward a close opinion.

0.3
repulsion Annotated[float, closed_open(0, oo)]

The probability of moving away from a distant opinion.

0.1

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import OpinionEncountersInteraction
>>> OpinionEncountersInteraction('encounters', candidate='opinions', field='opinions').confidence
2
Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def __init__(
    self,
    label: str,
    *,
    candidate: Role,
    field: Role,
    levels: Annotated[int, RealSet.open(0, oo)] = 7,
    confidence: Annotated[int, RealSet.closed_open(0, oo)] = 2,
    eta: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    persuasion: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
    repulsion: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
) -> None:
    super().__init__(label, candidate=candidate, field=field, rate=self._get_rate, kernel=self._get_kernel)
    self.levels = levels
    self.confidence = confidence
    self.eta = eta
    self.persuasion = persuasion
    self.repulsion = repulsion

PersuaderElement(label, *, opinion=0.0, size=None)

Bases: Element

Agent of the Sznajd system, who convinces the neighbours of an agreeing pair.

A step of an agent picks a random neighbour, and when both share an opinion every neighbour of either adopts it. On a ring this is the original one-dimensional rule, where the pair convinces the two agents beside it.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, NN]

The initial opinion, 0 or 1.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import PersuaderElement
>>> group = PersuaderElement('people', opinion=1.0, size=10)
>>> group.label, type(group).__name__, group.size
('people', 'PersuaderElement', 10)
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, NN] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion

PersuaderView

Bases: AgentViewProtocol, Protocol

View of an agent of the Sznajd system.

Its states and parameters are attributes.

PersuasionInteraction(label, *, target, phase=None)

Bases: NeighborhoodsInteraction

Persuasion of the Sznajd system.

An agreeing pair of neighbours convinces the neighbours of both. Every step every agent, in random order, picks a random neighbour, and when both share an opinion every neighbour of either adopts it. On a ring this is the original one-dimensional rule, where the pair convinces the two agents beside it.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of persuaders.

required
phase str | None

The phase of the step the persuasion runs in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import PersuasionInteraction
>>> PersuasionInteraction('persuasion', target='people').target
'people'
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
335
336
337
338
339
340
341
342
def __init__(
    self,
    label: str,
    *,
    target: Role,
    phase: str | None = None,
) -> None:
    super().__init__(label, target=target, phase=phase)

act_on(members, system)

Convince the neighbours of the first member and of a random neighbour of it.

This happens when the two agree.

Parameters:

Name Type Description Default
members list[AgentViewProtocol]

The persuader, followed by its neighbours.

required
system SystemView

The system view of the rule.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def act_on(self, members: list[AgentViewProtocol], system: SystemView) -> None:
    """Convince the neighbours of the first member and of a random neighbour of it.

    This happens when the two agree.

    Args:
        members:
            The persuader, followed by its neighbours.

        system:
            The system view of the rule.
    """
    agent, *neighbors = cast(list[PersuaderView], members)
    if not neighbors:
        return
    partner = neighbors[int(system.rng.integers(len(neighbors)))]
    if partner.opinion != agent.opinion:
        return
    for other in [*neighbors, *partner.get_neighbors()]:
        if isinstance(other, PersuaderView):
            other.opinion = agent.opinion

PhaseAgentElement(label, *, theta=0.0, space=None)

Bases: Element

Agent with a phase theta.

Parameters:

Name Type Description Default
label str

The label of the agent or the group on the nodes.

required
theta Annotated[object, Period(2 * pi)]

The initial phase.

0.0
space BaseSpace | None

The network whose nodes hold one agent each, or None for one agent.

None

Attributes:

Name Type Description
default_visual_

How the agent is drawn by default, the visual of its class.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import PhaseAgentElement
>>> PhaseAgentElement('agent', theta=0.5).theta
0.5
Source code in src/skcomplex/systems/social/opinion_dynamics/_gauge_agents.py
 98
 99
100
101
102
103
104
105
106
def __init__(
    self,
    label: str,
    *,
    theta: Annotated[object, Period(2 * np.pi)] = 0.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.theta = theta

RadicalElement(label, *, opinion=0.0, activity=0.1, size=None)

Bases: Element

Agent with an unbounded opinion and an activity.

The sign of the opinion is its stance and its size is its conviction.

Parameters:

Name Type Description Default
label str

The label of the agent or the group.

required
opinion object

The opinion x.

0.0
activity Annotated[object, closed(0, 1)]

The probability a that the agent contacts others in an integration step.

0.1
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import RadicalElement
>>> RadicalElement('agent', activity=0.1).activity
0.1
Source code in src/skcomplex/systems/social/opinion_dynamics/_echo_chambers.py
63
64
65
66
67
68
69
70
71
72
73
def __init__(
    self,
    label: str,
    *,
    opinion: object = 0.0,
    activity: Annotated[object, RealSet.closed(0, 1)] = 0.1,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion
    self.activity = activity

RadicalView

Bases: AgentViewProtocol, Protocol

View of an agent of the echo chamber system, with its states as attributes.

RadicalizationInteraction(label, *, target, strength=3.0, controversy=3.0, homophily=3.0, contacts=10, reciprocity=0.5, dt=0.01, substeps=10)

Bases: Interaction

Opinion dynamics of Baumann and coauthors.

The opinions follow dx_i/dt = -x_i + K sum_j A_ij(t) tanh(alpha x_j). Every step of the system integrates the opinions with substeps Euler steps of length dt, and draws a new temporal network for every one of them. In a draw, every agent is active with the probability of its activity and contacts contacts distinct others, each chosen with the probability |x_i - x_j|^-beta normalized over the others. A contacted agent receives the influence of the agent that contacts it, which receives the influence back when the contact is reciprocated, with the probability reciprocity.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of agents.

required
strength Annotated[float, closed_open(0, oo)]

The social interaction strength K.

3.0
controversy Annotated[float, closed_open(0, oo)]

The controversialness alpha of the issue, the steepness of the influence tanh(alpha x).

3.0
homophily Annotated[float, closed_open(0, oo)]

The exponent beta of the homophily of the contacts.

3.0
contacts Annotated[int, NN]

The number m of distinct agents an active agent contacts.

10
reciprocity Annotated[float, closed(0, 1)]

The probability r that a contact is reciprocated.

0.5
dt Annotated[float, open(0, oo)]

The length of an Euler step.

0.01
substeps Annotated[int, NN]

The number of Euler steps per step of the system.

10

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import RadicalizationInteraction
>>> RadicalizationInteraction('influence', target='agents').contacts
10
Source code in src/skcomplex/systems/social/opinion_dynamics/_echo_chambers.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(
    self,
    label: str,
    *,
    target: Role,
    strength: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
    controversy: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
    homophily: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
    contacts: Annotated[int, NN] = 10,
    reciprocity: Annotated[float, RealSet.closed(0, 1)] = 0.5,
    dt: Annotated[float, RealSet.open(0, oo)] = 0.01,
    substeps: Annotated[int, NN] = 10,
) -> None:
    super().__init__(label)
    self.target = target
    self.strength = strength
    self.controversy = controversy
    self.homophily = homophily
    self.contacts = contacts
    self.reciprocity = reciprocity
    self.dt = dt
    self.substeps = substeps

influence(system)

Integrate the opinions over the Euler steps of one step of the system.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_echo_chambers.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def influence(self, system: SystemView) -> None:
    """Integrate the opinions over the Euler steps of one step of the system.

    Args:
        system:
            The system.
    """
    agents = cast(list[RadicalView], system.get_agents(self.target))
    if len(agents) < PAIR:
        return
    opinions = np.array([agent.opinion for agent in agents])
    activities = np.array([agent.activity for agent in agents])
    for _ in range(int(self.substeps)):
        inputs = self._get_inputs(opinions, activities, system.rng)
        opinions = opinions + self.dt * (-opinions + self.strength * inputs)
    for agent, opinion in zip(agents, opinions.tolist(), strict=True):
        agent.opinion = opinion

RandomPairsInteraction(label, *, target, phase=None)

Bases: MeetingsInteraction

Rule of the system that draws random ordered pairs of distinct agents.

It draws as many pairs per step as there are agents. The pairs are drawn independently, so an agent can meet several partners in one step, and every pair acts in random order through act_on, which a subclass overrides. One unit of time holds one encounter per agent, as in the random sequential encounters of mean-field opinion and convention systems.

Parameters:

Name Type Description Default
label str

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

required
target Role

The path of the group whose agents meet in pairs.

required
phase str | None

The phase of the step the encounters run in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import RandomPairsInteraction
>>> RandomPairsInteraction('meetings', target='people').target
'people'
Source code in src/skcomplex/systems/social/opinion_dynamics/_random_pairs.py
47
48
49
50
def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

ScheduleElement(label, *, phase=0.0, space=None, on=None)

Bases: Element

Triangle of a temporal hypergraph.

It is active in every other half of a period from its own phase.

Parameters:

Name Type Description Default
label str

The label of the triangle or the group.

required
phase object

The phase of the schedule, in radians, one per triangle or shared.

0.0
space BaseSpace | None

The network whose hyperedges hold one triangle each, or None for one triangle.

None
on str | None

'hyperedges' for one triangle per hyperedge of the network, or None.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ScheduleElement
>>> ScheduleElement('triangle', phase=1.0).phase
1.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_hypergraph_consensus.py
90
91
92
93
94
95
96
97
98
99
def __init__(
    self,
    label: str,
    *,
    phase: object = 0.0,
    space: BaseSpace | None = None,
    on: str | None = None,
) -> None:
    super().__init__(label, space=space, on=on)
    self.phase = phase

SeparationInteraction(label, *, among, keep='source', opinion=1.0, along=True)

Bases: Interaction

Rewiring of discordant edges by one end.

It keeps the edge and moves its other end to a like-minded node, a request to rewire the edges of the voters. The end keep acts on an edge with probability activity / degree per step, and when it holds the opinion opinion and the other end does not, it rewires the edge with probability rewiring, drawing a new end among the voters of the opinion opinion.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
among Role

The path of the voters on the nodes, whose edges the laws run on.

required
keep str

The end of an edge that acts and keeps the edge, 'source' or 'target'.

'source'
opinion float

The opinion of the end that acts, 0 or 1.

1.0
along bool | str

The edges the laws run on, True for the edges of the network of the voters.

True

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import SeparationInteraction
>>> SeparationInteraction('separation', among='voters', keep='target', opinion=0).keep
'target'
Source code in src/skcomplex/systems/social/opinion_dynamics/_coevolution.py
185
186
187
188
189
190
191
192
193
194
195
196
def __init__(
    self,
    label: str,
    *,
    among: Role,
    keep: str = 'source',
    opinion: float = 1.0,
    along: bool | str = True,
) -> None:
    super().__init__(label, among=among, along=along)
    self.keep = keep
    self.opinion = opinion

SocialImpactInteraction(label, *, target)

Bases: Interaction

Synchronous update of the social impact system.

Every agent takes the opinion of the stronger impact. The impact on agent i is I_i = sum_j t_j (1 - o_i o_j) / d_ij^a - sum_j s_j (1 + o_i o_j) / d_ij^a, with the persuasiveness t, the supportiveness s, and the distance d on the grid, where an agent supports itself from distance 1. The impact is the net pressure to change, whatever the opinion, so an agent flips its opinion when I_i + h_i > 0, with a uniform random field h_i. Every agent decides from the opinions at the start of the step.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of agents.

required

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import SocialImpactInteraction
>>> SocialImpactInteraction('impact', target='people').target
'people'
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
267
268
269
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

SocialImpactSystem(width=15, height=15, *, share=0.5, exponent=2.0, noise=0.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The social impact system on a full grid.

The persuasiveness and the supportiveness are random. The system has the group people.

Parameters:

Name Type Description Default
width int

The number of columns.

15
height int

The number of rows.

15
share float

The share of agents with opinion 1, the others holding -1.

0.5
exponent float

The exponent of the distance by which impact decays.

2.0
noise float

The half-width of the uniform random field.

0.0
random_state int | Generator | None

The seed or generator of the opinions and strengths.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import SocialImpactSystem
>>> SocialImpactSystem(4, 5, random_state=0).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def __init__(
    self,
    width: int = 15,
    height: int = 15,
    *,
    share: float = 0.5,
    exponent: float = 2.0,
    noise: 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.width = width
    self.height = height
    self.share = share
    self.exponent = exponent
    self.noise = noise
    self.random_state = random_state

StandardizationInteraction(label, *, target, K=10.0, J=1.0, H=50, intensity=2.0, activity=1.0, phase=None)

Bases: ChoiceInteraction

Changes of configuration of random agents.

They are accepted with the logistic probability of their gain in utility. The utility of agent i is u_i = K / N sum_j |S_i| |S_j| + J / N sum_j S_i S_j over the other agents. An agent proposes a configuration drawn uniformly from the H + 2 configurations, its own included, and takes it with the probability 1 / (1 + exp(-beta (u_i' - u_i))) of the rule 'fermi', so the agents sample P ~ exp(beta E). The utilities read the counts of the configurations of the group, so every proposal sees the changes accepted before it. In StandardizedAgentsSystem, a phase of visits draws N agents with replacement every unit of time.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of agents.

required
K Annotated[float, closed_open(0, oo)]

The coupling of the characteristics |S_i|, which standardizes the agents.

10.0
J float

The coupling of the spins S_i, which orders the standardized agents.

1.0
H int

The number of configurations without the characteristic.

50
intensity float

The intensity of choice beta, the inverse of the temperature.

2.0
activity float

The probability that a visited agent proposes a configuration.

1.0
phase str | None

The phase of the step the choice runs in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import StandardizationInteraction
>>> StandardizationInteraction('standardization', target='agents', H=100).options[-1]
101.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_standardization.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def __init__(
    self,
    label: str,
    *,
    target: Role,
    K: Annotated[float, RealSet.closed_open(0, oo)] = 10.0,
    J: float = 1.0,
    H: int = 50,
    intensity: float = 2.0,
    activity: float = 1.0,
    phase: str | None = None,
) -> None:
    super().__init__(
        label,
        target=target,
        state='configuration',
        options=tuple(float(option) for option in range(H + MARKED)),
        utility=self._get_utility,
        rule='fermi',
        intensity=intensity,
        schedule='member',
        activity=activity,
        phase=phase,
        proposal='all',
    )
    self.K = K
    self.J = J
    self.H = H

StandardizedAgentsSystem(agents=100, *, K=10.0, J=1.0, T=0.5, H=50, standardized=1.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Complex agents whose interactions make them standardized.

They all show one characteristic, and are ordered. Below the temperature T_S = K / (2 ln(H / 2)) the most probable share of agents with the characteristic jumps from q ~ 0 to q ~ 1, a discontinuous transition, and below T_M = J the standardized agents order, with a magnetization m of either sign. Both states are long-lived on either side of T_S in large groups, so the initial share standardized selects the branch that the run follows. The system has the group agents, the share q of agents with the characteristic, and the magnetization m, the mean spin.

Parameters:

Name Type Description Default
agents int

The number of agents N.

100
K float

The coupling of the characteristics |S_i|, which standardizes the agents.

10.0
J float

The coupling of the spins S_i, which orders the standardized agents.

1.0
T float

The temperature, the randomness of the choices.

0.5
H int

The number of configurations without the characteristic.

50
standardized float

The initial share of agents with the characteristic, each with a random spin. The others start in random configurations without it.

1.0
random_state int | Generator | None

The seed or generator of the initial configurations.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import StandardizedAgentsSystem
>>> StandardizedAgentsSystem(10, standardized=0.0).prepare().system_.elements[0].spin.tolist()
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
Source code in src/skcomplex/systems/social/opinion_dynamics/_standardization.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def __init__(
    self,
    agents: int = 100,
    *,
    K: float = 10.0,
    J: float = 1.0,
    T: float = 0.5,
    H: int = 50,
    standardized: float = 1.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.agents = agents
    self.K = K
    self.J = J
    self.T = T
    self.H = H
    self.standardized = standardized
    self.random_state = random_state

SznajdSystem(graph=None, *, share=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Sznajd system, where agreeing pairs of agents convince their neighbours.

The system has the group people and the persuasion persuasion.

Parameters:

Name Type Description Default
graph object

The NetworkX graph, or None for a ring of 50 agents.

None
share float

The share of agents with opinion 1.

0.5
random_state int | Generator | None

The seed or generator of the opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> import networkx as nx
>>> from skcomplex.systems.social.opinion_dynamics import SznajdSystem
>>> SznajdSystem(nx.cycle_graph(8), random_state=0).prepare().system_.elements[0].size
8
Source code in src/skcomplex/systems/social/opinion_dynamics/_persuasion.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def __init__(
    self,
    graph: object = None,
    *,
    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.share = share
    self.random_state = random_state

ThinkerElement(label, *, valences=0.0, attitude=0.0, decay=0.05, size=None)

Bases: Element

Agent of the cognitive consistency system.

It holds the valences of the concepts of its belief network.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
valences ArrayLike

The initial valences of the concepts F1, X, and F2, between -1 and 1.

0.0
attitude object

The attitude of the agent, the valence of the concept X once the belief network settles.

0.0
decay Annotated[object, closed_open(0, oo)]

The fraction of every valence lost per update of the belief network.

0.05
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ThinkerElement
>>> group = ThinkerElement('thinkers', valences=[1.0, 1.0, -1.0], size=5)
>>> group.label, type(group).__name__, group.size
('thinkers', 'ThinkerElement', 5)
Source code in src/skcomplex/systems/social/opinion_dynamics/_cognition.py
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    label: str,
    *,
    valences: npt.ArrayLike = 0.0,
    attitude: object = 0.0,
    decay: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.valences = valences
    self.attitude = attitude
    self.decay = decay

ThinkerView

Bases: AgentViewProtocol, Protocol

View of an agent of the cognitive consistency system.

Its states and parameters are attributes.

ThreeBodyConsensusInteraction(label, *, among, reinforcement=0.0, period=1.0, along='hyperedges')

Bases: Interaction

Nonlinear three-body consensus of Neuhäuser, Mellor, and Lambiotte.

It acts on the triangles active at the time. The focal node i of an active triangle ijk moves towards the two others at the rate s(|x_j - x_k|) (x_j + x_k - 2 x_i), with s(d) = exp(reinforcement * d), so a pair that agrees pulls harder for a negative reinforcement. A triangle is active when sin(2 pi t / period + phase) > 0, with the phase of the triangle member of the group on hyperedges.

Parameters:

Name Type Description Default
label str

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

required
among Role

The path of the group of nodes.

required
reinforcement float

The exponent of the modulating function s.

0.0
period Annotated[float, open(0, oo)]

The period of the schedules.

1.0
along str

The links the laws run on, 'hyperedges' for the triangles of the network.

'hyperedges'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ThreeBodyConsensusInteraction
>>> ThreeBodyConsensusInteraction('consensus', among='nodes').along
'hyperedges'
Source code in src/skcomplex/systems/social/opinion_dynamics/_hypergraph_consensus.py
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(
    self,
    label: str,
    *,
    among: Role,
    reinforcement: float = 0.0,
    period: Annotated[float, RealSet.open(0, oo)] = 1.0,
    along: str = 'hyperedges',
) -> None:
    super().__init__(label, among=among, along=along)
    self.reinforcement = reinforcement
    self.period = period

ThreeStateOpinionSystem(n_agents=200, *, degree=4, sensitivity=2.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The three-state opinion system on a random regular network.

The agents are against, undecided, or for. Every step the agents redraw their opinions one after the other in random order, each from the sum x of the opinions of its neighbours: against with the probability f(-beta x), for with f(beta x), and undecided otherwise, where f(t) = 1 / (2 (1 + exp(-t))) (Jensen 2023 section 11.5, Project 1). Since f(t) + f(-t) = 1 / 2, half of the draws are undecided. In mean field, with every agent seeing q <x>, the mean opinion solves <x> = tanh(beta q <x> / 2) / 2, which has a non-zero solution only above beta_c = 4 / q. On the sparse network, domains of both signs and the undecided half keep the order weaker than in mean field.

The system has the group voters.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

200
degree int

The number q of neighbours of every agent.

4
sensitivity float

The sensitivity beta of the opinion to the sum of the opinions of the neighbours.

2.0
random_state int | Generator | None

The seed or generator of the network and of the initial opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ThreeStateOpinionSystem
>>> ThreeStateOpinionSystem(20).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/social/opinion_dynamics/_undecided.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def __init__(
    self,
    n_agents: int = 200,
    *,
    degree: int = 4,
    sensitivity: float = 2.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.degree = degree
    self.sensitivity = sensitivity
    self.random_state = random_state

ThresholdAdoptionSystem(n_agents=300, *, size=175.0, reach=15.0, mode='infection', thresholds='uniform', shifting=0.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: 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.

Parameters:

Name Type Description Default
n_agents int

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

300
size float

The side of the torus.

175.0
reach float

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

15.0
mode str

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

'infection'
thresholds str

'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.

'uniform'
shifting float

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

0.0
random_state int | Generator | None

The seed or generator of the positions and thresholds.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import ThresholdAdoptionSystem
>>> ThresholdAdoptionSystem(40, size=60.0, random_state=0).prepare().system_.elements[0].size
40
Source code in src/skcomplex/systems/social/opinion_dynamics/_diffusion.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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

TransportedCouplingInteraction(label, *, among, K=1.0, along=True)

Bases: Interaction

Relaxation of agent phases towards the phases of their neighbours.

It adds theta_i' += K sin(theta_j - theta_i - A_ij). The connection A_ij lives on the edge of the network from i to j, read as A of the element on the edges, and A_ji = -A_ij. The laws run once for every edge.

Parameters:

Name Type Description Default
label str

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

required
among Role

The path of the group of agents on the nodes.

required
K float

The coupling strength.

1.0
along bool | str

The edges the laws run on, True for the edges of the network the agents live on.

True

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import TransportedCouplingInteraction
>>> TransportedCouplingInteraction('coupling', among='agents', K=0.5).K
0.5
Source code in src/skcomplex/systems/social/opinion_dynamics/_gauge_agents.py
58
59
60
def __init__(self, label: str, *, among: Role, K: float = 1.0, along: bool | str = True) -> None:
    super().__init__(label, among=among, along=along)
    self.K = K

UndecidedElement(label, *, opinion=0.0, sensitivity=2.0, size=None)

Bases: Element

Voter who is against, undecided, or for, at -1, 0, or 1.

It redraws its opinion from its neighbours.

Parameters:

Name Type Description Default
label str

The label of the voter or the group.

required
opinion Annotated[object, FiniteEnumeratedSet([-1, 0, 1])]

The opinion, -1, 0, or 1.

0.0
sensitivity Annotated[object, closed_open(0, oo)]

The sensitivity beta of the opinion to the sum of the opinions of the neighbours.

2.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import UndecidedElement
>>> UndecidedElement('voter').sensitivity
2.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_undecided.py
67
68
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, FiniteEnumeratedSet([-1, 0, 1])] = 0.0,
    sensitivity: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion
    self.sensitivity = sensitivity

UndecidedFlowsElement(label, *, against=0.0, undecided=100.0, support=0.0, omega=1.0, gamma=0.05, eta=0.02, drive=1.0)

Bases: Element

Population split into the numbers A against, B for, and C undecided.

Parameters:

Name Type Description Default
label str

The label of the element.

required
against Annotated[object, closed_open(0, oo), Quantity(agents)]

The number A of agents against.

0.0
undecided Annotated[object, closed_open(0, oo), Quantity(agents)]

The number C of undecided agents.

100.0
support Annotated[object, closed_open(0, oo), Quantity(agents)]

The number B of agents for.

0.0
omega Annotated[object, closed_open(0, oo)]

The rate omega at which an undecided agent joins either side.

1.0
gamma Annotated[object, closed_open(0, oo)]

The rate gamma at which an agent against becomes undecided.

0.05
eta Annotated[object, closed_open(0, oo)]

The rate eta at which an agent for becomes undecided.

0.02
drive Annotated[object, FiniteEnumeratedSet([0, 1])]

The exponent of C in the flows into the undecided group, 0 for constant rates and 1 for rates in proportion to the undecided.

1.0

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import UndecidedFlowsElement
>>> UndecidedFlowsElement('population').omega
1.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_undecided.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def __init__(
    self,
    label: str,
    *,
    against: Annotated[object, RealSet.closed_open(0, oo), Quantity('agents')] = 0.0,
    undecided: Annotated[object, RealSet.closed_open(0, oo), Quantity('agents')] = 100.0,
    support: Annotated[object, RealSet.closed_open(0, oo), Quantity('agents')] = 0.0,
    omega: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    gamma: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
    eta: Annotated[object, RealSet.closed_open(0, oo)] = 0.02,
    drive: Annotated[object, FiniteEnumeratedSet([0, 1])] = 1.0,
) -> None:
    super().__init__(label)
    self.against = against
    self.undecided = undecided
    self.support = support
    self.omega = omega
    self.gamma = gamma
    self.eta = eta
    self.drive = drive

UndecidedFlowsSystem(n_agents=100.0, *, omega=1.0, gamma=0.05, eta=0.02, driven=True, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The mean-field flows between agents against, A, undecided, C, and for, B.

Undecided agents join either side at the rate omega, and agents against and for become undecided at the rates gamma and eta, with no direct flow between the sides, so N = A + B + C is conserved (Jensen 2023 section 11.5, Project 1). With constant rates, driven=False, dA/dt = omega C - gamma A, and the population settles at the attractive fixed point A : B : C = omega / gamma : omega / eta : 1. When the undecided drive the doubt, driven=True, the flows into the undecided grow with their number, dA/dt = omega C - gamma A C, and the dynamics change at N_c = omega (1 / gamma + 1 / eta): above it A = omega / gamma, B = omega / eta, and N - N_c agents never make up their mind, and below it every agent ends on one side.

The system has the numbers population.against, population.undecided, and population.support, and the flows population.joining_against, population.joining_support, population.doubting_against, and population.doubting_support. The observable of the system is population.critical_size.

Parameters:

Name Type Description Default
n_agents float

The number of agents, all undecided at the start.

100.0
omega float

The rate at which an undecided agent joins either side.

1.0
gamma float

The rate at which an agent against becomes undecided.

0.05
eta float

The rate at which an agent for becomes undecided.

0.02
driven bool

Whether the flows into the undecided are in proportion to their number.

True
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import UndecidedFlowsSystem
>>> UndecidedFlowsSystem(driven=False).prepare().system_.elements[0].drive
0.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_undecided.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def __init__(
    self,
    n_agents: float = 100.0,
    *,
    omega: float = 1.0,
    gamma: float = 0.05,
    eta: float = 0.02,
    driven: bool = True,
    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.omega = omega
    self.gamma = gamma
    self.eta = eta
    self.driven = driven

UndecidedView

Bases: AgentViewProtocol, Protocol

View of a voter of the three-state opinion system.

Its states and parameters are attributes.

VariantVoterElement(label, *, opinion=0.0, contrarian=0.0, threshold=0.0, size=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, NN]

The initial opinion, 0 or 1.

0.0
contrarian Annotated[object, FiniteEnumeratedSet([0, 1])]

Whether the agent is a contrarian, 1, or not, 0.

0.0
threshold Annotated[object, closed_open(0, oo)]

The share of disagreeing neighbours above which the agent changes its opinion, or 0 to copy a random neighbour.

0.0
size int | None

The number of members, or None for one.

None

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)
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
110
111
112
113
114
115
116
117
118
119
120
121
122
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

VariantVoterView

Bases: AgentViewProtocol, Protocol

View of an agent of the voter system variants.

Its states and parameters are attributes.

VariantVotingInteraction(label, *, target)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of voters.

required

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import VariantVotingInteraction
>>> VariantVotingInteraction('voting', target='voters').target
'voters'
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
194
195
196
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

VillageElement(label, *, culture=0, features=5.0, traits=10.0, x=0, y=0, size=None, space=None)

Bases: Element

Village of Axelrod's system, with a culture of F features of q traits each.

The culture is stored as one integer.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
culture Annotated[object, NN]

The culture code, the traits of the features as the digits of a number in base q.

0
features Annotated[float, open(0, oo)]

The number of features F.

5.0
traits Annotated[float, open(0, oo)]

The number of traits q of every feature.

10.0
x object

The column of the cell of the village on a lattice, one per village or shared.

0
y object

The row of the cell of the village on a lattice, one per village or shared.

0
size int | None

The number of villages, or None for one.

None
space BaseSpace | None

The lattice the villages live on, whose axes x and y make x and y their cell, or None.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import VillageElement
>>> VillageElement('villages', culture=0, features=3, traits=5, size=4).size
4
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def __init__(
    self,
    label: str,
    *,
    culture: Annotated[object, NN] = 0,
    features: Annotated[float, RealSet.open(0, oo)] = 5.0,
    traits: Annotated[float, RealSet.open(0, oo)] = 10.0,
    x: object = 0,
    y: object = 0,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, size=size, space=space)
    self.culture = culture
    self.features = features
    self.traits = traits
    self.x = x
    self.y = y

VillageView

Bases: AgentViewProtocol, Protocol

View of a village of the Axelrod culture system.

Its states and parameters are attributes.

VoterElement(label, *, opinion=0.0, size=None)

Bases: Element

Agent of the voter system on a network.

The imitation sets its opinion to that of a random neighbour.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
opinion Annotated[object, NN]

The initial opinion, 0 or 1.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import VoterElement
>>> group = VoterElement('voters', opinion=1.0, size=20)
>>> group.label, type(group).__name__, group.size
('voters', 'VoterElement', 20)
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
158
159
160
161
162
163
164
165
166
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, NN] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion

VoterImitationInteraction(label, *, target)

Bases: Interaction

Imitation of the voter system.

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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of voters.

required

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import VoterImitationInteraction
>>> VoterImitationInteraction('imitation', target='voters').target
'voters'
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
260
261
262
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

VoterSystem(graph=None, *, share=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A voter system with one voter per node of a network.

The system has the group voters.

Parameters:

Name Type Description Default
graph object

The NetworkX graph, or None for a ring of 50 nodes each linked to its four nearest neighbours.

None
share float

The share of voters with opinion 1.

0.5
random_state int | Generator | None

The seed or generator of the opinions.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> import networkx as nx
>>> from skcomplex.systems.social.opinion_dynamics import VoterSystem
>>> VoterSystem(nx.cycle_graph(8), random_state=0).prepare().system_.elements[0].size
8
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
def __init__(
    self,
    graph: object = None,
    *,
    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.share = share
    self.random_state = random_state

VoterVariantsSystem(graph=None, *, threshold=0.5, contrarians=0.1, share=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Voter system variants on a network.

They have threshold voters and a share of contrarians. The system has the group voters.

Parameters:

Name Type Description Default
graph object

The NetworkX graph, or None for a ring of 50 nodes each linked to its four nearest neighbours.

None
threshold float

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.

0.5
contrarians float

The share of voters that are contrarians.

0.1
share float

The share of voters with opinion 1.

0.5
random_state int | Generator | None

The seed or generator of the opinions and of the contrarians.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

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
Source code in src/skcomplex/systems/social/opinion_dynamics/_voters.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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

VoterView

Bases: AgentViewProtocol, Protocol

View of an agent of the voter system.

Its states and parameters are attributes.

WillingMajorityInteraction(label, *, target, group_size=3)

Bases: Interaction

Majority rule with willingness.

A random agent adopts the majority opinion of a random group. Every step has one update per agent. An update chooses an agent uniformly, then an odd number group_size of other agents uniformly, and the agent adopts the majority opinion of the group with the probability of its willingness.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of voters.

required
group_size Annotated[int, NN]

The odd number of other agents an agent consults.

3

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import WillingMajorityInteraction
>>> WillingMajorityInteraction('majority', target='voters').group_size
3
Source code in src/skcomplex/systems/social/opinion_dynamics/_willing_majority.py
104
105
106
107
108
109
110
111
112
113
def __init__(
    self,
    label: str,
    *,
    target: Role,
    group_size: Annotated[int, NN] = 3,
) -> None:
    super().__init__(label)
    self.target = target
    self.group_size = group_size

follow(system)

Update as many random agents as there are agents.

Each agent follows the majority of a random group.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/social/opinion_dynamics/_willing_majority.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def follow(self, system: SystemView) -> None:
    """Update as many random agents as there are agents.

    Each agent follows the majority of a random group.

    Args:
        system:
            The system.
    """
    voters = cast(list[WillingVoterView], system.get_agents(self.target))
    size = len(voters)
    group_size = int(self.group_size)
    if size <= group_size:
        return
    opinions = np.array([voter.opinion for voter in voters])
    willingness = np.array([voter.willingness for voter in voters])
    rng = system.rng
    for chosen in rng.integers(size, size=size).tolist():
        others = rng.choice(size - 1, group_size, replace=False)
        others = others + (others >= chosen)
        if rng.random() < willingness[chosen]:
            opinions[chosen] = float(2 * opinions[others].sum() > group_size)
    for voter, opinion in zip(voters, opinions.tolist(), strict=True):
        voter.opinion = opinion

WillingMajoritySystem(n_agents=200, *, group_size=3, zealots=0.0, zealot_opinion=None, willingness=1.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The majority rule with willingness.

Zealots of willingness 0 never change their opinion. Every agent holds opinion A or B, drawn with probability 1/2, and a willingness w_i. An update chooses an agent and an odd number n of other agents at random, and the agent adopts the majority opinion of the group with the probability w_i (Jensen 2023 section 11.5, Exercise 4). Every agent has w_i = willingness, except a fraction zealots of them with w_i = 0. With every agent willing, the population reaches consensus. Zealots of both opinions prevent it, while a small group of zealots of one opinion, zealot_opinion, wins over everyone. The system has the group voters.

Parameters:

Name Type Description Default
n_agents int

The number of agents.

200
group_size int

The odd number n of other agents an agent consults.

3
zealots float

The fraction f of agents with willingness 0.

0.0
zealot_opinion float | None

The opinion, 1 for A or 0 for B, every zealot starts with, or None for random opinions.

None
willingness float

The willingness of the other agents.

1.0
random_state int | Generator | None

The seed or generator of the opinions and of the zealots.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import WillingMajoritySystem
>>> WillingMajoritySystem(30).prepare().system_.elements[0].size
30
Source code in src/skcomplex/systems/social/opinion_dynamics/_willing_majority.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def __init__(
    self,
    n_agents: int = 200,
    *,
    group_size: int = 3,
    zealots: float = 0.0,
    zealot_opinion: float | None = None,
    willingness: float = 1.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.group_size = group_size
    self.zealots = zealots
    self.zealot_opinion = zealot_opinion
    self.willingness = willingness
    self.random_state = random_state

WillingVoterElement(label, *, opinion=0.0, willingness=1.0, size=None)

Bases: Element

Voter with a binary opinion and a willingness to follow the majority.

It is a zealot at willingness 0.

Parameters:

Name Type Description Default
label str

The label of the voter or the group.

required
opinion Annotated[object, NN]

The opinion, 0 for B or 1 for A.

0.0
willingness Annotated[object, closed(0, 1)]

The probability that the voter adopts the majority opinion of the group it consults.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import WillingVoterElement
>>> WillingVoterElement('voter').willingness
1.0
Source code in src/skcomplex/systems/social/opinion_dynamics/_willing_majority.py
64
65
66
67
68
69
70
71
72
73
74
def __init__(
    self,
    label: str,
    *,
    opinion: Annotated[object, NN] = 0.0,
    willingness: Annotated[object, RealSet.closed(0, 1)] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.opinion = opinion
    self.willingness = willingness

WillingVoterView

Bases: AgentViewProtocol, Protocol

View of a voter of the majority rule with willingness.

Its states are attributes.

cultural_traits(culture, features, traits)

Return the traits of a culture vector stored as one integer.

They are its digits in base q.

Parameters:

Name Type Description Default
culture float

The integer code of the culture vector.

required
features int

The number of features F.

required
traits int

The number of traits q of every feature.

required

Returns:

Name Type Description
traits IntArray

The trait of every feature, the first feature first.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import cultural_traits
>>> cultural_traits(7, 3, 2).tolist()
[1, 1, 1]
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def cultural_traits(culture: float, features: int, traits: int) -> IntArray:
    """Return the traits of a culture vector stored as one integer.

    They are its digits in base `q`.

    Args:
        culture:
            The integer code of the culture vector.

        features:
            The number of features `F`.

        traits:
            The number of traits `q` of every feature.

    Returns:
        traits:
            The trait of every feature, the first feature first.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import cultural_traits
        >>> cultural_traits(7, 3, 2).tolist()
        [1, 1, 1]
    """
    return (int(culture) // traits ** np.arange(features, dtype=np.int64)) % traits

culture_observables(width, height)

Return the share of the largest cultural region and the number of cultures.

They are read from a full grid of villages.

Parameters:

Name Type Description Default
width int

The number of columns of the grid.

required
height int

The number of rows of the grid.

required

Returns:

Name Type Description
observables list[Observable]

The observables largest_region and cultures, each reducing the cultures of the group villages.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import culture_observables
>>> [item.label for item in culture_observables(5, 4)]
['largest_region', 'cultures']
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def culture_observables(width: int, height: int) -> list[Observable]:
    """Return the share of the largest cultural region and the number of cultures.

    They are read from a full grid of villages.

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

        height:
            The number of rows of the grid.

    Returns:
        observables:
            The observables `largest_region` and `cultures`, each reducing the cultures of the group `villages`.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import culture_observables
        >>> [item.label for item in culture_observables(5, 4)]
        ['largest_region', 'cultures']
    """
    locations = [(x, y) for x in range(width) for y in range(height)]
    region = partial(largest_region, locations, width=width, height=height)
    return [
        Observable('largest_region', group='villages', variable='culture', reduce=region),
        Observable('cultures', group='villages', variable='culture', reduce=_count_cultures),
    ]

largest_region(locations, cultures, width, height)

Return the fraction of the cells in the largest connected region of one culture.

Parameters:

Name Type Description Default
locations ArrayLike

The cell of every agent, one (x, y) row per agent.

required
cultures ArrayLike

The culture code of every agent.

required
width int

The number of columns of the grid.

required
height int

The number of rows of the grid.

required

Returns:

Name Type Description
fraction float

The size of the largest region of adjacent cells with the same culture over the number of cells.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import largest_region
>>> largest_region([(0, 0), (1, 0), (0, 1), (1, 1)], [1, 1, 2, 3], 2, 2)
0.5
Source code in src/skcomplex/systems/social/opinion_dynamics/_axelrod.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def largest_region(locations: npt.ArrayLike, cultures: npt.ArrayLike, width: int, height: int) -> float:
    """Return the fraction of the cells in the largest connected region of one culture.

    Args:
        locations:
            The cell of every agent, one `(x, y)` row per agent.

        cultures:
            The culture code of every agent.

        width:
            The number of columns of the grid.

        height:
            The number of rows of the grid.

    Returns:
        fraction:
            The size of the largest region of adjacent cells with the same culture over the number of cells.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import largest_region
        >>> largest_region([(0, 0), (1, 0), (0, 1), (1, 1)], [1, 1, 2, 3], 2, 2)
        0.5
    """
    cells = np.asarray(locations, dtype=np.int64).reshape(-1, 2)
    grid = np.full((width, height), -1.0)
    grid[cells[:, 0], cells[:, 1]] = np.asarray(cultures, dtype=float)
    largest = 0
    for culture in np.unique(grid[grid >= 0]):
        labels, count = ndimage.label(grid == culture)
        if count:
            largest = max(largest, int(np.bincount(labels.ravel())[1:].max()))
    return largest / (width * height)

mean_opinion(s, opinions)

Return the mean opinion of a distribution over opinion levels.

Parameters:

Name Type Description Default
s SimpleNamespace

The namespace of one member of the distribution.

required
opinions NDArray[float64]

The opinion of every level.

required

Returns:

Name Type Description
mean Expression

The normalized first moment.

Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def mean_opinion(s: SimpleNamespace, opinions: npt.NDArray[np.float64]) -> Expression:
    """Return the mean opinion of a distribution over opinion levels.

    Args:
        s:
            The namespace of one member of the distribution.

        opinions:
            The opinion of every level.

    Returns:
        mean:
            The normalized first moment.
    """
    return moment(s.x, 1, opinions, normalized=True)

opinion_grid(levels)

Return the opinion of every level, evenly spaced from -1 to 1.

Parameters:

Name Type Description Default
levels int

The number of opinion levels.

required

Returns:

Name Type Description
opinions NDArray[float64]

The opinion of every level.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import opinion_grid
>>> opinion_grid(5).tolist()
[-1.0, -0.5, 0.0, 0.5, 1.0]
Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def opinion_grid(levels: int) -> npt.NDArray[np.float64]:
    """Return the opinion of every level, evenly spaced from -1 to 1.

    Args:
        levels:
            The number of opinion levels.

    Returns:
        opinions:
            The opinion of every level.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import opinion_grid
        >>> opinion_grid(5).tolist()
        [-1.0, -0.5, 0.0, 0.5, 1.0]
    """
    return np.linspace(-1.0, 1.0, levels)

opinion_observables(levels)

Return the mean opinion and the variance of the opinions of a distribution.

The distribution is opinions.

Parameters:

Name Type Description Default
levels int

The number of opinion levels.

required

Returns:

Name Type Description
observables list[Observable]

The observables, each reading the moments of the distribution.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import opinion_observables
>>> [item.label for item in opinion_observables(7)]
['mean_opinion', 'opinion_variance']
Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def opinion_observables(levels: int) -> list[Observable]:
    """Return the mean opinion and the variance of the opinions of a distribution.

    The distribution is `opinions`.

    Args:
        levels:
            The number of opinion levels.

    Returns:
        observables:
            The observables, each reading the moments of the distribution.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import opinion_observables
        >>> [item.label for item in opinion_observables(7)]
        ['mean_opinion', 'opinion_variance']
    """
    opinions = opinion_grid(levels)
    return [
        Observable('mean_opinion', partial(mean_opinion, opinions=opinions), group='opinions'),
        Observable('opinion_variance', partial(opinion_variance, opinions=opinions), group='opinions'),
    ]

opinion_variance(s, opinions)

Return the variance of the opinions of a distribution.

It grows as opinions polarise.

Parameters:

Name Type Description Default
s SimpleNamespace

The namespace of one member of the distribution.

required
opinions NDArray[float64]

The opinion of every level.

required

Returns:

Name Type Description
variance Expression

The central second moment.

Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def opinion_variance(s: SimpleNamespace, opinions: npt.NDArray[np.float64]) -> Expression:
    """Return the variance of the opinions of a distribution.

    It grows as opinions polarise.

    Args:
        s:
            The namespace of one member of the distribution.

        opinions:
            The opinion of every level.

    Returns:
        variance:
            The central second moment.
    """
    return moment(s.x, 2, opinions, central=True)

persuasion_table(levels, confidence, persuasion, repulsion)

Return the transition table of encounters between opinion levels, A[h, k, i].

A candidate at level h that meets a field particle at level k within confidence levels moves one level toward it with probability persuasion. One that meets a field particle further away moves one level away from it with probability repulsion, unless it holds an extreme opinion already.

Parameters:

Name Type Description Default
levels int

The number of opinion levels.

required
confidence int

The largest distance in levels at which encounters persuade.

required
persuasion object

The probability of moving toward a close opinion, a number or a parameter.

required
repulsion object

The probability of moving away from a distant opinion, a number or a parameter.

required

Returns:

Name Type Description
table NDArray[object_]

The transition probabilities, which sum to one over the outcomes.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import persuasion_table
>>> persuasion_table(3, 1, 0.4, 0.1)[0, 1].astype(float).tolist()
[0.6, 0.4, 0.0]
Source code in src/skcomplex/systems/social/opinion_dynamics/_kinetic_opinion.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def persuasion_table(levels: int, confidence: int, persuasion: object, repulsion: object) -> npt.NDArray[np.object_]:
    """Return the transition table of encounters between opinion levels, `A[h, k, i]`.

    A candidate at level `h` that meets a field particle at level `k` within `confidence` levels moves one level
    toward it with probability `persuasion`. One that meets a field particle further away moves one level away from it
    with probability `repulsion`, unless it holds an extreme opinion already.

    Args:
        levels:
            The number of opinion levels.

        confidence:
            The largest distance in levels at which encounters persuade.

        persuasion:
            The probability of moving toward a close opinion, a number or a parameter.

        repulsion:
            The probability of moving away from a distant opinion, a number or a parameter.

    Returns:
        table:
            The transition probabilities, which sum to one over the outcomes.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import persuasion_table
        >>> persuasion_table(3, 1, 0.4, 0.1)[0, 1].astype(float).tolist()
        [0.6, 0.4, 0.0]
    """
    table = np.zeros((levels, levels, levels), dtype=object)
    for candidate in range(levels):
        for field in range(levels):
            toward = int(np.sign(field - candidate))
            outcome, probability = (
                (candidate + toward, persuasion)
                if abs(field - candidate) <= confidence
                else (candidate - toward, repulsion)
            )
            if toward and 0 <= outcome < levels:
                table[candidate, field, outcome] += probability
            table[candidate, field, candidate] += 1 - table[candidate, field].sum()
    return table

settle(valences, decay=0.05)

Return the valences of a belief network updated until they settle.

The updates stop when no valence changes by more than 0.01.

The network links the first concept to the second with weight 0.05 and the second to the third with weight -0.05. Every update decays a valence by decay and moves it towards 1 or -1 by its net input.

Parameters:

Name Type Description Default
valences ArrayLike

The valences of the three concepts, between -1 and 1.

required
decay float

The fraction of every valence lost per update.

0.05

Returns:

Name Type Description
valences Array

The settled valences.

Examples:

>>> from skcomplex.systems.social.opinion_dynamics import settle
>>> settle([1.0, 1.0, -1.0]).round(2).tolist()
[0.48, 0.57, -0.48]
Source code in src/skcomplex/systems/social/opinion_dynamics/_cognition.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def settle(valences: npt.ArrayLike, decay: float = 0.05) -> Array:
    """Return the valences of a belief network updated until they settle.

    The updates stop when no valence changes by more than 0.01.

    The network links the first concept to the second with weight 0.05 and the second to the third with weight
    -0.05. Every update decays a valence by `decay` and moves it towards 1 or -1 by its net input.

    Args:
        valences:
            The valences of the three concepts, between -1 and 1.

        decay:
            The fraction of every valence lost per update.

    Returns:
        valences:
            The settled valences.

    Examples:
        >>> from skcomplex.systems.social.opinion_dynamics import settle
        >>> settle([1.0, 1.0, -1.0]).round(2).tolist()
        [0.48, 0.57, -0.48]
    """
    current = np.asarray(valences, dtype=float)
    for _ in range(MAX_SETTLING):
        following = _settle_once(current, decay)
        if np.abs(following - current).max() < SETTLED:
            return following
        current = following
    return current