Skip to content

netechos.core

Core functionality for the network echos model.

NetworkModel(number_of_nodes, interaction_type, alpha=1, beta=0.001)

Object containing network model parameters and methods.

Parameters:

Name Type Description Default
number_of_nodes int

Number of nodes to add to the network model.

required
interaction_type Literal['symmetric', 'asymmetric']

Type of interaction between nodes. If "symmetric" interactions will be reciprocated. If "asymmetric", interactions may be one-directional.

required
alpha float

Exponent of the adjacency matrix during attitude reinforcement.

1
beta float

Factor governing the rate of attitude change. Smaller values slow attitude change.

0.001

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def __init__(
    self: Self,
    number_of_nodes: int,
    interaction_type: Literal["symmetric", "asymmetric"],
    alpha: float = 1,
    beta: float = 1e-3,
) -> Self:
    """Object storing network model data and methods.

    Parameters
    ----------
    number_of_nodes : int
        Number of nodes to add to the network model.
    interaction_type : Literal["symmetric", "asymmetric"]
        Type of interaction between nodes. If "symmetric"
        interactions will be reciprocated. If "asymmetric",
        interactions may be one-directional.
    alpha : float
        Exponent of the adjacency matrix during attitude
        reinforcement.
    beta : float
        Factor governing the rate of attitude change. Smaller
        values slow attitude change.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """
    allowed_types = ["symmetric", "asymmetric"]
    if interaction_type not in allowed_types:
        msg = f"interaction_type must be one of: {allowed_types}."
        raise ValueError(msg)
    if number_of_nodes < 1:
        msg = "number_of_nodes must be greater than one."
        raise ValueError(msg)
    self.number_of_nodes = number_of_nodes
    self.interaction_type = interaction_type
    self.adjacency_exponent = alpha
    self.attitude_change_speed = beta

compute_attitude_difference_matrix()

Construct matrix of differences between node attitudes.

Source code in src/netechos/core.py
253
254
255
256
257
258
259
def compute_attitude_difference_matrix(self: Self) -> Self:
    """Construct matrix of differences between node attitudes."""
    self.attitude_diffs = np.subtract(
        self.attitudes,
        self.attitudes.transpose(),
    )
    return self

create_network(network_type, p=0.1, k=2, m=1.0)

Create initial social network.

Parameters:

Name Type Description Default
network_type Literal['complete', 'erdos_renyi', 'watts_strogatz', 'newman_watts_strogatz', 'barabasi_albert']

Type of network to create.

required
p float

Required if network_type is one of 'erdos_renyi', 'watts_strogatz', 'newman_watts_strogatz'. Probability for edge creation.

0.1
k int

Required if network_type is one of 'watts_strogatz', 'newman_watts_strogatz'. Each node is joined with its k nearest neighbors in a ring topology.

2
m float

Required if network_type is 'barabasi_albert'. Number of edges to attach from a new node to existing nodes.

1.0

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
 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
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def create_network(
    self: Self,
    network_type: Literal[
        "complete",
        "erdos_renyi",
        "watts_strogatz",
        "newman_watts_strogatz",
        "barabasi_albert",
    ],
    p: float = 0.1,
    k: int = 2,
    m: float = 1.0,
) -> Self:
    """Create initial social network.

    Parameters
    ----------
    network_type: Literal["complete", "erdos_renyi", "watts_strogatz", "newman_watts_strogatz", "barabasi_albert"]
        Type of network to create.
    p : float, optional, default: 0.1
        Required if network_type is one of 'erdos_renyi',
        'watts_strogatz', 'newman_watts_strogatz'. Probability for
        edge creation.
    k : int, optional, default: 2
        Required if network_type is one of 'watts_strogatz',
        'newman_watts_strogatz'. Each node is joined with its `k`
        nearest neighbors in a ring topology.
    m : float, optional, default: 1.0
        Required if network_type is 'barabasi_albert'. Number
        of edges to attach from a new node to existing nodes.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """  # noqa: E501
    if network_type == "complete":
        g_initial = nx.complete_graph(n=self.number_of_nodes)
    if network_type == "erdos_renyi":
        g_initial = nx.erdos_renyi_graph(n=self.number_of_nodes, p=p)
        self.p_edge = p
    if network_type == "watts_strogatz":
        g_initial = nx.watts_strogatz_graph(
            n=self.number_of_nodes,
            k=k,
            p=p,
        )
        self.k_neighbors = k
        self.p_edge = p
    if network_type == "newman_watts_strogatz":
        g_initial = nx.newman_watts_strogatz_graph(
            n=self.number_of_nodes,
            k=k,
            p=p,
        )
        self.k_neighbors = k
        self.p_edge = p
    if network_type == "barabasi_albert":
        g_initial = nx.barabasi_albert_graph(n=self.number_of_nodes, m=m)
        self.m_new_node_edges = m
    self.social_network = g_initial
    self.network_type = network_type
    return self

initialize_attitude_tracker()

Initialize attitude tracking table.

Source code in src/netechos/core.py
330
331
332
333
334
335
def initialize_attitude_tracker(self: Self) -> Self:
    """Initialize attitude tracking table."""
    self.attitude_tracker = pl.DataFrame(
        schema={"time": int, "node": int, "attitude": float},
    )
    return self

initialize_attitudes(distribution='vonmises', a=0.0, b=5)

Set initial node attitudes.

Parameters:

Name Type Description Default
distribution Literal['normal', 'uniform', 'laplace', 'vonmises']

Type of probability distribution to sample attitudes from.

'vonmises'
a float

First parameter for distribution. If distribution is 'normal' or 'laplace' this is the loc parameter. If distribution is 'uniform', this is the lower bound. If distribution is 'vonmises' this is the mu parameter.

0.0
b float

Second parameter for distribution. If distribution is 'normal' or 'laplace' this is the scale parameter. If distribution is 'uniform', this is the upper bound. If distribution is 'vonmises' this is the kappa parameter.

5

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
213
214
215
216
217
218
219
220
221
222
def initialize_attitudes(
    self: Self,
    distribution: Literal[
        "normal",
        "uniform",
        "laplace",
        "vonmises",
    ] = "vonmises",
    a: float = 0.0,
    b: float = 5,
) -> Self:
    """Set initial node attitudes.

    Parameters
    ----------
    distribution : Literal['normal', 'uniform', 'laplace', 'vonmises'], default: 'vonmises'
        Type of probability distribution to sample attitudes from.
    a : float, default: 0.0
        First parameter for `distribution`. If `distribution` is
        'normal' or 'laplace' this is the `loc` parameter. If
        `distribution` is 'uniform', this is the lower bound. If
        `distribution` is 'vonmises' this is the `mu` parameter.
    b : float, default: 5
        Second parameter for `distribution`. If `distribution` is
        'normal' or 'laplace' this is the `scale` parameter. If
        `distribution` is 'uniform', this is the upper bound. If
        `distribution` is 'vonmises' this is the `kappa` parameter.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """  # noqa: E501
    rng = np.random.default_rng()
    if distribution == "normal":
        attitudes = rng.normal(
            loc=a,
            scale=b,
            size=(1, self.number_of_nodes),
        )
        self.attitude_distribution_loc = a
        self.attitude_distribution_scale = b
    if distribution == "laplace":
        attitudes = rng.laplace(
            loc=a,
            scale=b,
            size=(1, self.number_of_nodes),
        )
        self.attitude_distribution_loc = a
        self.attitude_distribution_scale = b
    if distribution == "vonmises":
        attitudes = rng.vonmises(
            mu=a,
            kappa=b,
            size=(1, self.number_of_nodes),
        )
        self.attitude_distribution_mu = a
        self.attitude_distribution_kappa = b
    if distribution == "uniform":
        attitudes = rng.uniform(
            low=a,
            high=b,
            size=(1, self.number_of_nodes),
        )
        self.attitude_distribution_low = a
        self.attitude_distribution_high = b
    attitudes = np.clip(attitudes, a_min=-np.pi / 2, a_max=np.pi / 2)
    self.attitudes = attitudes
    self.attitude_distribution = distribution
    return self

initialize_connections(neighbor_weight=1.0, non_neighbor_weight=0.0)

Set initial network edge weights.

Parameters:

Name Type Description Default
neighbor_weight float

The weight to assign to edges between nodes which have an existing edge in the intial network.

1.0
non_neighbor_weight float

The weight to assign to edges between nodes which don't have an existing edge in the intial network. If non-zero the network will technically become a complete network.

0.0

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
121
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
150
def initialize_connections(
    self: Self,
    neighbor_weight: float = 1.0,
    non_neighbor_weight: float = 0.0,
) -> Self:
    """Set initial network edge weights.

    Parameters
    ----------
    neighbor_weight : float
        The weight to assign to edges between nodes which have an
        existing edge in the intial network.
    non_neighbor_weight : float
        The weight to assign to edges between nodes which don't
        have an existing edge in the intial network. If non-zero
        the network will technically become a complete network.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """
    adjacency_mat = nx.to_numpy_array(self.social_network)
    adjacency_mat = neighbor_weight * adjacency_mat
    adjacency_mat[adjacency_mat == 0] = non_neighbor_weight
    self.connections = adjacency_mat
    self.neighbor_weight = neighbor_weight
    self.non_neighbor_weight = non_neighbor_weight
    return self

initialize_summary_table()

Initialize summary table.

Source code in src/netechos/core.py
290
291
292
293
294
295
296
297
298
299
300
301
def initialize_summary_table(self: Self) -> Self:
    """Initialize summary table."""
    self.summary_table = pl.DataFrame(
        schema={
            "time": int,
            "attitude_mean": float,
            "attitude_sd": float,
            "connection_mean": float,
            "connection_sd": float,
        },
    )
    return self

make_asymmetric_interactions()

Construct a random asymmetric adjacency matrix.

Source code in src/netechos/core.py
233
234
235
236
237
238
239
def make_asymmetric_interactions(self: Self) -> Self:
    """Construct a random asymmetric adjacency matrix."""
    rng = np.random.default_rng()
    rand_mat = rng.random(size=(self.number_of_nodes, self.number_of_nodes))
    interactions = np.where(rand_mat <= self.connections, 1, 0)
    self.interactions = interactions
    return self

make_interactions()

Construct interaction matrix.

Source code in src/netechos/core.py
241
242
243
244
245
246
247
248
249
250
251
def make_interactions(self: Self) -> Self:
    """Construct interaction matrix."""
    if self.interaction_type == "symmetric":
        self.make_symmetric_interactions()
    elif self.interaction_type == "asymmetric":
        self.make_asymmetric_interactions()
    else:
        msg = f"""self.interaction_type must be one of ["symmetric",
        "asymmetric"], got: {self.interaction_type}"""
        raise ValueError(msg)
    return self

make_symmetric_interactions()

Construct a random symmetric adjacency matrix.

Source code in src/netechos/core.py
224
225
226
227
228
229
230
231
def make_symmetric_interactions(self: Self) -> Self:
    """Construct a random symmetric adjacency matrix."""
    rng = np.random.default_rng()
    rand_mat = rng.random(size=(self.number_of_nodes, self.number_of_nodes))
    interactions = np.where(rand_mat <= self.connections, 1, 0)
    interactions = np.maximum(interactions, interactions.transpose())
    self.interactions = interactions
    return self

run_simulation(tmax)

Simulate interaction and attitude reinforcement over time.

Parameters:

Name Type Description Default
tmax int

Number of time steps to iterate over.

required

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def run_simulation(self: Self, tmax: int) -> Self:
    """Simulate interaction and attitude reinforcement over time.

    Parameters
    ----------
    tmax : int
        Number of time steps to iterate over.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """
    if tmax < 1:
        msg = "tmax must be greater than 1"
        raise ValueError(msg)
    self.initialize_summary_table()
    self.initialize_attitude_tracker()
    for t in tqdm(range(tmax)):
        self.compute_attitude_difference_matrix()
        self.make_interactions()
        self.update_connections()
        self.update_attitudes()
        self.update_summary_table(time=t)
        self.update_attitude_tracker(time=t)

update_attitude_tracker(time)

Construct attitude tracking table for one time.

Parameters:

Name Type Description Default
time int

Time index. Will be assigned to all rows of the time column being added to the summary table.

required

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def update_attitude_tracker(self: Self, time: int) -> Self:
    """Construct attitude tracking table for one time.

    Parameters
    ----------
    time : int
        Time index. Will be assigned to all rows of the `time`
        column being added to the summary table.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """
    attitudes_flat = self.attitudes.flatten()
    step_attitude_tracker = pl.DataFrame(
        {
            "time": np.full(
                shape=attitudes_flat.shape,
                fill_value=time,
                dtype="int64",
            ),
            "node": np.arange(self.number_of_nodes, dtype="int64").reshape(
                attitudes_flat.shape,
            ),
            "attitude": attitudes_flat,
        },
    )
    self.attitude_tracker = pl.concat(
        [self.attitude_tracker, step_attitude_tracker],
    )
    return self

update_attitudes()

Calculate change in attitude.

Source code in src/netechos/core.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def update_attitudes(self: Self) -> Self:
    """Calculate change in attitude."""
    connections_to_power = np.where(
        self.connections != 0,
        np.power(self.connections, self.adjacency_exponent),
        0,
    )
    d_attitudes = np.multiply(
        np.multiply(connections_to_power, self.interactions),
        np.sin(self.attitude_diffs),
    ).sum(axis=0)
    self.attitudes = self.attitudes + (self.attitude_change_speed * d_attitudes)
    self.attitudes = np.clip(
        self.attitudes,
        a_min=-np.pi / 2,
        a_max=np.pi / 2,
    )
    return self

update_connections()

Calculate change in connection strength.

Source code in src/netechos/core.py
261
262
263
264
265
266
267
268
269
def update_connections(self: Self) -> Self:
    """Calculate change in connection strength."""
    d_connections = np.multiply(
        self.interactions,
        np.sin(self.attitude_diffs),
    )
    self.connections = self.connections + d_connections
    self.connections = np.clip(self.connections, a_min=0, a_max=1)
    return self

update_summary_table(time)

Construct summary of the network at one time.

Parameters:

Name Type Description Default
time int

Time index. Will be assigned to all rows of the time column being added to the summary table.

required

Returns:

Name Type Description
self Self @ NetworkModel

An instance of the NetworkModel object.

Source code in src/netechos/core.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def update_summary_table(self: Self, time: int) -> Self:
    """Construct summary of the network at one time.

    Parameters
    ----------
    time : int
        Time index. Will be assigned to all rows of the `time`
        column being added to the summary table.

    Returns
    -------
    self : Self@NetworkModel
        An instance of the NetworkModel object.

    """
    step_summary_table = pl.DataFrame(
        {
            "time": time,
            "attitude_mean": np.mean(np.sin(self.attitudes)),
            "attitude_sd": np.std(np.sin(self.attitudes)),
            "connection_mean": np.mean(self.connections),
            "connection_sd": np.std(self.connections),
        },
    )
    self.summary_table = pl.concat([self.summary_table, step_summary_table])
    return self