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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""revolutions_exploration.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1omNn2hrbDL_s1qwCOr7ViaIjrRW61YDt
|
8 |
+
"""
|
9 |
+
|
10 |
+
!pip install gradio
|
11 |
+
|
12 |
+
# Commented out IPython magic to ensure Python compatibility.
|
13 |
+
#
|
14 |
+
# %%capture
|
15 |
+
# import multiprocessing
|
16 |
+
#
|
17 |
+
# multiprocessing.cpu_count()
|
18 |
+
#
|
19 |
+
# !pip install cmocean
|
20 |
+
# !pip install git+https://github.com/MNoichl/mesa
|
21 |
+
#
|
22 |
+
# !pip install compress-pickle --quiet
|
23 |
+
|
24 |
+
import random
|
25 |
+
import pandas as pd
|
26 |
+
from mesa import Agent, Model
|
27 |
+
from mesa.space import MultiGrid
|
28 |
+
import networkx as nx
|
29 |
+
from mesa.time import RandomActivation
|
30 |
+
from mesa.datacollection import DataCollector
|
31 |
+
import numpy as np
|
32 |
+
import seaborn as sns
|
33 |
+
import matplotlib.pyplot as plt
|
34 |
+
import matplotlib as mpl
|
35 |
+
|
36 |
+
import cmocean
|
37 |
+
|
38 |
+
import tqdm
|
39 |
+
|
40 |
+
import scipy as sp
|
41 |
+
|
42 |
+
from compress_pickle import dump, load
|
43 |
+
|
44 |
+
from scipy.stats import beta
|
45 |
+
|
46 |
+
# Commented out IPython magic to ensure Python compatibility.
|
47 |
+
# %%capture
|
48 |
+
# !pip install git+https://github.com/MNoichl/opinionated.git#egg=opinionated
|
49 |
+
# import opinionated
|
50 |
+
# plt.style.use("opinionated_rc")
|
51 |
+
|
52 |
+
experiences = {
|
53 |
+
'dissident_experiences': [1,0,0],
|
54 |
+
'supporter_experiences': [1,1,1],
|
55 |
+
}
|
56 |
+
|
57 |
+
def apply_half_life_decay(data_list, half_life, decay_factors=None):
|
58 |
+
steps = len(data_list)
|
59 |
+
|
60 |
+
# Check if decay_factors are provided and are of the correct length
|
61 |
+
if decay_factors is None or len(decay_factors) < steps:
|
62 |
+
decay_factors = [0.5 ** (i / half_life) for i in range(steps)]
|
63 |
+
decayed_list = [data_list[i] * decay_factors[steps - 1 - i] for i in range(steps)]
|
64 |
+
|
65 |
+
|
66 |
+
return decayed_list
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
half_life=20
|
71 |
+
decay_factors = [0.5 ** (i / half_life) for i in range(200)]
|
72 |
+
|
73 |
+
def get_beta_mean_from_experience_dict(experiences, half_life=20,decay_factors=None): #note: precomputed decay supersedes halflife!
|
74 |
+
eta = 1e-10
|
75 |
+
return beta.mean(sum(apply_half_life_decay(experiences['dissident_experiences'], half_life,decay_factors))+eta,
|
76 |
+
sum(apply_half_life_decay(experiences['supporter_experiences'], half_life,decay_factors))+eta)
|
77 |
+
|
78 |
+
|
79 |
+
def get_beta_sample_from_experience_dict(experiences, half_life=20,decay_factors=None):
|
80 |
+
eta = 1e-10
|
81 |
+
|
82 |
+
# print(sum(apply_half_life_decay(experiences['dissident_experiences'], half_life)))
|
83 |
+
# print(sum(apply_half_life_decay(experiences['supporter_experiences'], half_life)))
|
84 |
+
return beta.rvs(sum(apply_half_life_decay(experiences['dissident_experiences'], half_life,decay_factors))+eta,
|
85 |
+
sum(apply_half_life_decay(experiences['supporter_experiences'], half_life,decay_factors))+eta, size=1)[0]
|
86 |
+
|
87 |
+
|
88 |
+
print(get_beta_mean_from_experience_dict(experiences,half_life,decay_factors))
|
89 |
+
print(get_beta_sample_from_experience_dict(experiences,half_life))
|
90 |
+
|
91 |
+
#@title Load network functionality
|
92 |
+
|
93 |
+
def generate_community_points(num_communities, total_nodes, powerlaw_exponent=2.0, sigma=0.05, plot=False):
|
94 |
+
"""
|
95 |
+
This function generates points in 2D space, where points are grouped into communities.
|
96 |
+
Each community is represented by a Gaussian distribution.
|
97 |
+
|
98 |
+
Args:
|
99 |
+
num_communities (int): Number of communities (gaussian distributions).
|
100 |
+
total_nodes (int): Total number of points to be generated.
|
101 |
+
powerlaw_exponent (float): The power law exponent for the powerlaw sequence.
|
102 |
+
sigma (float): The standard deviation for the gaussian distributions.
|
103 |
+
plot (bool): If True, the function plots the generated points.
|
104 |
+
|
105 |
+
Returns:
|
106 |
+
numpy.ndarray: An array of generated points.
|
107 |
+
"""
|
108 |
+
|
109 |
+
# Sample from a powerlaw distribution
|
110 |
+
sequence = nx.utils.powerlaw_sequence(num_communities, powerlaw_exponent)
|
111 |
+
|
112 |
+
# Normalize sequence to represent probabilities
|
113 |
+
probabilities = sequence / np.sum(sequence)
|
114 |
+
|
115 |
+
# Assign nodes to communities based on probabilities
|
116 |
+
community_assignments = np.random.choice(num_communities, size=total_nodes, p=probabilities)
|
117 |
+
|
118 |
+
# Calculate community_sizes from community_assignments
|
119 |
+
community_sizes = np.bincount(community_assignments)
|
120 |
+
# Ensure community_sizes has length equal to num_communities
|
121 |
+
if len(community_sizes) < num_communities:
|
122 |
+
community_sizes = np.pad(community_sizes, (0, num_communities - len(community_sizes)), 'constant')
|
123 |
+
|
124 |
+
points = []
|
125 |
+
community_centers = []
|
126 |
+
|
127 |
+
# For each community
|
128 |
+
for i in range(num_communities):
|
129 |
+
# Create a random center for this community
|
130 |
+
center = np.random.rand(2)
|
131 |
+
community_centers.append(center)
|
132 |
+
|
133 |
+
# Sample from Gaussian distributions with the center and sigma
|
134 |
+
community_points = np.random.normal(center, sigma, (community_sizes[i], 2))
|
135 |
+
|
136 |
+
points.append(community_points)
|
137 |
+
|
138 |
+
points = np.concatenate(points)
|
139 |
+
|
140 |
+
# Optional plotting
|
141 |
+
if plot:
|
142 |
+
plt.figure(figsize=(8,8))
|
143 |
+
plt.scatter(points[:, 0], points[:, 1], alpha=0.5)
|
144 |
+
# for center in community_centers:
|
145 |
+
sns.kdeplot(x=points[:, 0], y=points[:, 1], levels=5, color="k", linewidths=1)
|
146 |
+
# plt.xlim(0, 1)
|
147 |
+
# plt.ylim(0, 1)
|
148 |
+
plt.show()
|
149 |
+
|
150 |
+
return points
|
151 |
+
|
152 |
+
|
153 |
+
def graph_from_coordinates(coords, radius):
|
154 |
+
"""
|
155 |
+
This function creates a random geometric graph from an array of coordinates.
|
156 |
+
|
157 |
+
Args:
|
158 |
+
coords (numpy.ndarray): An array of coordinates.
|
159 |
+
radius (float): A radius of circles or spheres.
|
160 |
+
|
161 |
+
Returns:
|
162 |
+
networkx.Graph: The created graph.
|
163 |
+
"""
|
164 |
+
|
165 |
+
# Create a KDTree for efficient query
|
166 |
+
kdtree = sp.spatial.cKDTree(coords)
|
167 |
+
edge_indexes = kdtree.query_pairs(radius)
|
168 |
+
g = nx.Graph()
|
169 |
+
g.add_nodes_from(list(range(len(coords))))
|
170 |
+
g.add_edges_from(edge_indexes)
|
171 |
+
|
172 |
+
return g
|
173 |
+
|
174 |
+
|
175 |
+
def plot_graph(graph, positions):
|
176 |
+
"""
|
177 |
+
This function plots a graph with the given positions.
|
178 |
+
|
179 |
+
Args:
|
180 |
+
graph (networkx.Graph): The graph to be plotted.
|
181 |
+
positions (dict): A dictionary of positions for the nodes.
|
182 |
+
"""
|
183 |
+
|
184 |
+
plt.figure(figsize=(8,8))
|
185 |
+
pos_dict = {i: positions[i] for i in range(len(positions))}
|
186 |
+
nx.draw_networkx_nodes(graph, pos_dict, node_size=30, node_color="#1a2340", alpha=0.7)
|
187 |
+
nx.draw_networkx_edges(graph, pos_dict, edge_color="grey", width=1, alpha=1)
|
188 |
+
plt.show()
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
def ensure_neighbors(graph):
|
193 |
+
"""
|
194 |
+
Ensure that all nodes in a NetworkX graph have at least one neighbor.
|
195 |
+
|
196 |
+
Parameters:
|
197 |
+
graph (networkx.Graph): The NetworkX graph to check.
|
198 |
+
|
199 |
+
Returns:
|
200 |
+
networkx.Graph: The updated NetworkX graph where all nodes have at least one neighbor.
|
201 |
+
"""
|
202 |
+
nodes = list(graph.nodes())
|
203 |
+
for node in nodes:
|
204 |
+
if len(list(graph.neighbors(node))) == 0:
|
205 |
+
# The node has no neighbors, so select another node to connect it with
|
206 |
+
other_node = random.choice(nodes)
|
207 |
+
while other_node == node: # Make sure we don't connect the node to itself
|
208 |
+
other_node = random.choice(nodes)
|
209 |
+
graph.add_edge(node, other_node)
|
210 |
+
return graph
|
211 |
+
|
212 |
+
|
213 |
+
def compute_homophily(G,attr_name='attr'):
|
214 |
+
same_attribute_edges = sum(G.nodes[n1][attr_name] == G.nodes[n2][attr_name] for n1, n2 in G.edges())
|
215 |
+
total_edges = G.number_of_edges()
|
216 |
+
return same_attribute_edges / total_edges if total_edges > 0 else 0
|
217 |
+
|
218 |
+
def assign_initial_attributes(G, ratio,attr_name='attr'):
|
219 |
+
nodes = list(G.nodes)
|
220 |
+
random.shuffle(nodes)
|
221 |
+
attr_boundary = int(ratio * len(nodes))
|
222 |
+
for i, node in enumerate(nodes):
|
223 |
+
G.nodes[node][attr_name] = 0 if i < attr_boundary else 1
|
224 |
+
return G
|
225 |
+
|
226 |
+
def distribute_attributes(G, target_homophily, seed=None, max_iter=10000, cooling_factor=0.9995,attr_name='attr'):
|
227 |
+
random.seed(seed)
|
228 |
+
current_homophily = compute_homophily(G,attr_name)
|
229 |
+
temp = 1.0
|
230 |
+
|
231 |
+
for i in range(max_iter):
|
232 |
+
# pick two random nodes with different attributes and swap their attributes
|
233 |
+
nodes = list(G.nodes)
|
234 |
+
random.shuffle(nodes)
|
235 |
+
for node1, node2 in zip(nodes[::2], nodes[1::2]):
|
236 |
+
if G.nodes[node1][attr_name] != G.nodes[node2][attr_name]:
|
237 |
+
G.nodes[node1][attr_name], G.nodes[node2][attr_name] = G.nodes[node2][attr_name], G.nodes[node1][attr_name]
|
238 |
+
break
|
239 |
+
|
240 |
+
new_homophily = compute_homophily(G,attr_name)
|
241 |
+
delta_homophily = new_homophily - current_homophily
|
242 |
+
dir_factor = np.sign(target_homophily - current_homophily)
|
243 |
+
|
244 |
+
# if the new homophily is closer to the target, or if the simulated annealing condition is met, accept the swap
|
245 |
+
if abs(new_homophily - target_homophily) < abs(current_homophily - target_homophily) or \
|
246 |
+
(delta_homophily / temp < 700 and random.random() < np.exp(dir_factor * delta_homophily / temp)):
|
247 |
+
current_homophily = new_homophily
|
248 |
+
else: # else, undo the swap
|
249 |
+
G.nodes[node1][attr_name], G.nodes[node2][attr_name] = G.nodes[node2][attr_name], G.nodes[node1][attr_name]
|
250 |
+
|
251 |
+
temp *= cooling_factor # cool down
|
252 |
+
|
253 |
+
return G
|
254 |
+
|
255 |
+
|
256 |
+
def reindex_graph_to_match_attributes(G1, G2, attr_name):
|
257 |
+
# Get a sorted list of nodes in G1 based on the attribute
|
258 |
+
G1_sorted_nodes = sorted(G1.nodes(data=True), key=lambda x: x[1][attr_name])
|
259 |
+
|
260 |
+
# Get a sorted list of nodes in G2 based on the attribute
|
261 |
+
G2_sorted_nodes = sorted(G2.nodes(data=True), key=lambda x: x[1][attr_name])
|
262 |
+
|
263 |
+
# Create a mapping from the G2 node IDs to the G1 node IDs
|
264 |
+
mapping = {G2_node[0]: G1_node[0] for G2_node, G1_node in zip(G2_sorted_nodes, G1_sorted_nodes)}
|
265 |
+
|
266 |
+
# Generate the new graph with the updated nodes
|
267 |
+
G2_updated = nx.relabel_nodes(G2, mapping)
|
268 |
+
|
269 |
+
return G2_updated
|
270 |
+
|
271 |
+
##########################
|
272 |
+
|
273 |
+
def compute_mean(model):
|
274 |
+
agent_estimations = [agent.estimation for agent in model.schedule.agents]
|
275 |
+
return np.mean(agent_estimations)
|
276 |
+
|
277 |
+
def compute_median(model):
|
278 |
+
agent_estimations = [agent.estimation for agent in model.schedule.agents]
|
279 |
+
return np.median(agent_estimations)
|
280 |
+
|
281 |
+
def compute_std(model):
|
282 |
+
agent_estimations = [agent.estimation for agent in model.schedule.agents]
|
283 |
+
return np.std(agent_estimations)
|
284 |
+
|
285 |
+
|
286 |
+
|
287 |
+
|
288 |
+
class PoliticalAgent(Agent):
|
289 |
+
"""An agent in the political model.
|
290 |
+
|
291 |
+
Attributes:
|
292 |
+
estimation (float): Agent's current expectation of political change.
|
293 |
+
dissident (bool): True if the agent supports a regime change, False otherwise.
|
294 |
+
networks_estimations (dict): A dictionary storing the estimations of the agent for each network.
|
295 |
+
"""
|
296 |
+
|
297 |
+
def __init__(self, unique_id, model, dissident):
|
298 |
+
super().__init__(unique_id, model)
|
299 |
+
self.experiences = {
|
300 |
+
'dissident_experiences': [1],
|
301 |
+
'supporter_experiences': [1],
|
302 |
+
}
|
303 |
+
# self.estimation = estimation
|
304 |
+
self.estimations = []
|
305 |
+
self.estimation = .5 #hardcoded_mean, will change in first step if agent interacts.
|
306 |
+
|
307 |
+
self.experiments = []
|
308 |
+
|
309 |
+
|
310 |
+
self.dissident = dissident
|
311 |
+
# self.historical_estimations = []
|
312 |
+
|
313 |
+
def update_estimation(self, network_id):
|
314 |
+
"""Update the agent's estimation for a given network."""
|
315 |
+
# Get the neighbors from the network
|
316 |
+
potential_partners = [self.model.schedule.agents[n] for n in self.model.networks[network_id]['network'].neighbors(self.unique_id)]
|
317 |
+
|
318 |
+
|
319 |
+
|
320 |
+
|
321 |
+
current_estimate =get_beta_mean_from_experience_dict(self.experiences,half_life=self.model.half_life,decay_factors=self.model.decay_factors)
|
322 |
+
self.estimations.append(current_estimate)
|
323 |
+
self.estimation =current_estimate
|
324 |
+
current_experiment = get_beta_sample_from_experience_dict(self.experiences,half_life=self.model.half_life, decay_factors=self.model.decay_factors)
|
325 |
+
self.experiments.append(current_experiment)
|
326 |
+
|
327 |
+
if potential_partners:
|
328 |
+
partner = random.choice(potential_partners)
|
329 |
+
if self.model.networks[network_id]['type'] == 'physical':
|
330 |
+
if current_experiment >= self.model.threshold:
|
331 |
+
|
332 |
+
if partner.dissident: # removed division by 100?
|
333 |
+
self.experiences['dissident_experiences'].append(1)
|
334 |
+
self.experiences['supporter_experiences'].append(0)
|
335 |
+
else:
|
336 |
+
self.experiences['dissident_experiences'].append(0)
|
337 |
+
self.experiences['supporter_experiences'].append(1)
|
338 |
+
|
339 |
+
partner.experiences['dissident_experiences'].append(1 * self.model.social_learning_factor)
|
340 |
+
partner.experiences['supporter_experiences'].append(0)
|
341 |
+
|
342 |
+
else:
|
343 |
+
partner.experiences['dissident_experiences'].append(0)
|
344 |
+
partner.experiences['supporter_experiences'].append(1 * self.model.social_learning_factor)
|
345 |
+
|
346 |
+
|
347 |
+
# else:
|
348 |
+
# pass
|
349 |
+
# Only one network for the moment!
|
350 |
+
elif self.model.networks[network_id]['type'] == 'social_media':
|
351 |
+
if partner.dissident: # removed division by 100?
|
352 |
+
self.experiences['dissident_experiences'].append(1 * self.model.social_media_factor)
|
353 |
+
self.experiences['supporter_experiences'].append(0)
|
354 |
+
else:
|
355 |
+
self.experiences['dissident_experiences'].append(0)
|
356 |
+
self.experiences['supporter_experiences'].append(1 * self.model.social_media_factor)
|
357 |
+
|
358 |
+
# self.networks_estimations[network_id] = self.estimation
|
359 |
+
|
360 |
+
def combine_estimations(self):
|
361 |
+
# """Combine the estimations from all networks using a bounded confidence model."""
|
362 |
+
values = [list(d.values())[0] for d in self.current_estimations]
|
363 |
+
|
364 |
+
if len(values) > 0:
|
365 |
+
# Filter the network estimations based on the bounded confidence range
|
366 |
+
within_range = [value for value in values if abs(self.estimation - value) <= self.model.bounded_confidence_range]
|
367 |
+
|
368 |
+
# If there are any estimations within the range, update the estimation
|
369 |
+
if len(within_range) > 0:
|
370 |
+
self.estimation = np.mean(within_range)
|
371 |
+
|
372 |
+
|
373 |
+
|
374 |
+
|
375 |
+
def step(self):
|
376 |
+
"""Agent step function which updates the estimation for each network and then combines the estimations."""
|
377 |
+
if not hasattr(self, 'current_estimations'): # agents might already have this attribute because they were partnered up in the past.
|
378 |
+
self.current_estimations = []
|
379 |
+
|
380 |
+
for network_id in self.model.networks.keys():
|
381 |
+
self.update_estimation(network_id)
|
382 |
+
|
383 |
+
self.combine_estimations()
|
384 |
+
# self.historical_estimations.append(self.current_estimations)
|
385 |
+
del self.current_estimations
|
386 |
+
|
387 |
+
|
388 |
+
class PoliticalModel(Model):
|
389 |
+
"""A model of a political system with multiple interacting agents.
|
390 |
+
|
391 |
+
Attributes:
|
392 |
+
networks (dict): A dictionary of networks with network IDs as keys and NetworkX Graph objects as values.
|
393 |
+
"""
|
394 |
+
|
395 |
+
def __init__(self, n_agents, networks, share_regime_supporters,
|
396 |
+
# initial_expectation_of_change,
|
397 |
+
threshold,
|
398 |
+
social_learning_factor=1,social_media_factor=1, # one for equal learning, lower gets discounted
|
399 |
+
half_life=20, print_agents=False, print_frequency=30,
|
400 |
+
early_stopping_steps=20, early_stopping_range=0.01, agent_reporters=True,intervention_list=[],randomID=False):
|
401 |
+
self.num_agents = n_agents
|
402 |
+
self.threshold = threshold
|
403 |
+
self.social_learning_factor = social_learning_factor
|
404 |
+
self.social_media_factor = social_media_factor
|
405 |
+
self.print_agents_state = print_agents
|
406 |
+
self.half_life = half_life
|
407 |
+
self.intervention_list = intervention_list
|
408 |
+
self.model_id = randomID
|
409 |
+
|
410 |
+
self.print_frequency = print_frequency
|
411 |
+
self.early_stopping_steps = early_stopping_steps
|
412 |
+
self.early_stopping_range = early_stopping_range
|
413 |
+
|
414 |
+
|
415 |
+
self.mean_estimations = []
|
416 |
+
self.decay_factors = [0.5 ** (i / self.half_life) for i in range(500)] # Nte this should be larger than
|
417 |
+
|
418 |
+
# we could use this for early stopping!
|
419 |
+
self.running = True
|
420 |
+
self.share_regime_supporters = share_regime_supporters
|
421 |
+
self.schedule = RandomActivation(self)
|
422 |
+
self.networks = networks
|
423 |
+
|
424 |
+
# Assign dissident as argument to networks, compute homophilies, and match up the networks so that the same id leads to the same atrribute
|
425 |
+
for i, this_network in enumerate(self.networks):
|
426 |
+
self.networks[this_network]["network"] = assign_initial_attributes(self.networks[this_network]["network"],self.share_regime_supporters,attr_name='dissident')
|
427 |
+
if 'homophily' in self.networks[this_network]:
|
428 |
+
self.networks[this_network]["network"] = distribute_attributes(self.networks[this_network]["network"],
|
429 |
+
self.networks[this_network]['homophily'], max_iter=5000, cooling_factor=0.995,attr_name='dissident')
|
430 |
+
self.networks[this_network]['network_data_to_keep']['actual_homophily'] = compute_homophily(self.networks[this_network]["network"],attr_name='dissident')
|
431 |
+
if i>0:
|
432 |
+
self.networks[this_network]["network"] = reindex_graph_to_match_attributes(self.networks[next(iter(self.networks))]["network"], self.networks[this_network]["network"], 'dissident')
|
433 |
+
|
434 |
+
# print(self.networks)
|
435 |
+
|
436 |
+
for i in range(self.num_agents):
|
437 |
+
# estimation = random.normalvariate(initial_expectation_of_change, 0.2) We set a flat prior now
|
438 |
+
|
439 |
+
agent = PoliticalAgent(i, self, self.networks[next(iter(self.networks))]["network"].nodes(data=True)[i]['dissident'])
|
440 |
+
self.schedule.add(agent)
|
441 |
+
# Should we update to the real share here?!
|
442 |
+
####################
|
443 |
+
|
444 |
+
# Keep the attributes in the model and define model reporters
|
445 |
+
model_reporters = {
|
446 |
+
"Mean": compute_mean,
|
447 |
+
"Median": compute_median,
|
448 |
+
"STD": compute_std
|
449 |
+
}
|
450 |
+
|
451 |
+
for this_network in self.networks:
|
452 |
+
if 'network_data_to_keep' in self.networks[this_network]:
|
453 |
+
for key, value in self.networks[this_network]['network_data_to_keep'].items():
|
454 |
+
attr_name = this_network + '_' + key
|
455 |
+
setattr(self, attr_name, value)
|
456 |
+
|
457 |
+
# Define a reporter function for this attribute
|
458 |
+
def reporter(model, attr_name=attr_name):
|
459 |
+
return getattr(model, attr_name)
|
460 |
+
|
461 |
+
# Add the reporter function to the dictionary
|
462 |
+
model_reporters[attr_name] = reporter
|
463 |
+
|
464 |
+
# Initialize DataCollector with the dynamic model reporters
|
465 |
+
if agent_reporters:
|
466 |
+
self.datacollector = DataCollector(
|
467 |
+
model_reporters=model_reporters,
|
468 |
+
agent_reporters={"Estimation": "estimation", "Dissident": "dissident"}#, "Historical Estimations": "historical_estimations"}
|
469 |
+
)
|
470 |
+
else:
|
471 |
+
self.datacollector = DataCollector(
|
472 |
+
model_reporters=model_reporters
|
473 |
+
)
|
474 |
+
|
475 |
+
|
476 |
+
|
477 |
+
|
478 |
+
|
479 |
+
def step(self):
|
480 |
+
"""Model step function which activates the step function of each agent."""
|
481 |
+
|
482 |
+
self.datacollector.collect(self) # Collect data
|
483 |
+
|
484 |
+
# do interventions, if present:
|
485 |
+
for this_intervention in self.intervention_list:
|
486 |
+
# print(this_intervention)
|
487 |
+
if this_intervention['time'] == len(self.mean_estimations):
|
488 |
+
|
489 |
+
if this_intervention['type'] == 'threshold_adjustment':
|
490 |
+
self.threshold = max(0, min(1, self.threshold + this_intervention['strength']))
|
491 |
+
|
492 |
+
if this_intervention['type'] == 'share_adjustment':
|
493 |
+
target_supporter_share = max(0, min(1, self.share_regime_supporters + this_intervention['strength']))
|
494 |
+
agents = [self.schedule._agents[i] for i in self.schedule._agents]
|
495 |
+
current_supporters = sum(not agent.dissident for agent in agents)
|
496 |
+
total_agents = len(agents)
|
497 |
+
current_share = current_supporters / total_agents
|
498 |
+
|
499 |
+
# Calculate the number of agents to change
|
500 |
+
required_supporters = int(target_supporter_share * total_agents)
|
501 |
+
agents_to_change = abs(required_supporters - current_supporters)
|
502 |
+
|
503 |
+
if current_share < target_supporter_share:
|
504 |
+
# Not enough supporters, need to increase
|
505 |
+
dissidents = [agent for agent in agents if agent.dissident]
|
506 |
+
for agent in random.sample(dissidents, agents_to_change):
|
507 |
+
agent.dissident = False
|
508 |
+
elif current_share > target_supporter_share:
|
509 |
+
# Too many supporters, need to reduce
|
510 |
+
supporters = [agent for agent in agents if not agent.dissident]
|
511 |
+
for agent in random.sample(supporters, agents_to_change):
|
512 |
+
agent.dissident = True
|
513 |
+
# print(self.threshold)
|
514 |
+
if this_intervention['type'] == 'social_media_adjustment':
|
515 |
+
self.social_media_factor = max(0, min(1, self.social_media_factor + this_intervention['strength']))
|
516 |
+
|
517 |
+
|
518 |
+
self.schedule.step()
|
519 |
+
current_mean_estimation = compute_mean(self)
|
520 |
+
self.mean_estimations.append(current_mean_estimation)
|
521 |
+
|
522 |
+
# Implement the early stopping criteria
|
523 |
+
if len(self.mean_estimations) >= self.early_stopping_steps:
|
524 |
+
recent_means = self.mean_estimations[-self.early_stopping_steps:]
|
525 |
+
if max(recent_means) - min(recent_means) < self.early_stopping_range:
|
526 |
+
# if self.print_agents_state:
|
527 |
+
# print('Early stopping at: ', self.schedule.steps)
|
528 |
+
# self.print_agents()
|
529 |
+
self.running = False
|
530 |
+
|
531 |
+
# if self.print_agents_state and (self.schedule.steps % self.print_frequency == 0 or self.schedule.steps == 1):
|
532 |
+
# print(self.schedule.steps)
|
533 |
+
# self.print_agents()
|
534 |
+
|
535 |
+
|
536 |
+
|
537 |
+
|
538 |
+
|
539 |
+
|
540 |
+
def run_simulation(n_agents=300, share_regime_supporters=0.4, threshold=0.5, social_learning_factor=1, simulation_steps=400, half_life=20):
|
541 |
+
# Helper functions like graph_from_coordinates, ensure_neighbors should be defined outside this function
|
542 |
+
|
543 |
+
# Complete graph
|
544 |
+
G = nx.complete_graph(n_agents)
|
545 |
+
|
546 |
+
# Networks dictionary
|
547 |
+
networks = {
|
548 |
+
"physical": {"network": G, "type": "physical", "positions": nx.circular_layout(G)}#kamada_kawai
|
549 |
+
}
|
550 |
+
|
551 |
+
# Intervention list
|
552 |
+
intervention_list = [ ]
|
553 |
+
|
554 |
+
# Initialize the model
|
555 |
+
model = PoliticalModel(n_agents, networks, share_regime_supporters, threshold,
|
556 |
+
social_learning_factor, half_life=half_life, print_agents=False, print_frequency=50, agent_reporters=True, intervention_list=intervention_list)
|
557 |
+
|
558 |
+
# Run the model
|
559 |
+
for _ in tqdm.tqdm_notebook(range(simulation_steps)): # Run for specified number of steps
|
560 |
+
model.step()
|
561 |
+
return model
|
562 |
+
|
563 |
+
# Example usage
|
564 |
+
|
565 |
+
def run_and_plot_simulation(n_agents=300, share_regime_supporters=0.4, threshold=0.5, social_learning_factor=1, simulation_steps=40, half_life=20):
|
566 |
+
model =run_simulation(n_agents=n_agents, share_regime_supporters=share_regime_supporters, threshold=threshold, social_learning_factor=social_learning_factor, simulation_steps=simulation_steps, half_life=half_life)
|
567 |
+
# Get data and reset index
|
568 |
+
agent_df = model.datacollector.get_agent_vars_dataframe().reset_index()
|
569 |
+
|
570 |
+
# Pivot the dataframe
|
571 |
+
agent_df_pivot = agent_df.pivot(index='Step', columns='AgentID', values='Estimation')
|
572 |
+
|
573 |
+
# Create the plot
|
574 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
575 |
+
for column in agent_df_pivot.columns:
|
576 |
+
plt.plot(agent_df_pivot.index, agent_df_pivot[column], color='gray', alpha=0.1)
|
577 |
+
|
578 |
+
# Compute and plot the mean estimation
|
579 |
+
mean_estimation = agent_df_pivot.mean(axis=1)
|
580 |
+
plt.plot(mean_estimation.index, mean_estimation, color='black', linewidth=2)
|
581 |
+
|
582 |
+
# Set the plot title and labels
|
583 |
+
plt.title('Agent Estimation Over Time')
|
584 |
+
plt.xlabel('Time step')
|
585 |
+
plt.ylabel('Estimation')
|
586 |
+
return fig
|
587 |
+
|
588 |
+
|
589 |
+
# run_and_plot_simulation(n_agents=300, share_regime_supporters=0.4, threshold=0.5, social_learning_factor=1, simulation_steps=40, half_life=20)
|
590 |
+
|
591 |
+
import gradio as gr
|
592 |
+
import matplotlib.pyplot as plt
|
593 |
+
|
594 |
+
|
595 |
+
# Gradio interface
|
596 |
+
with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
|
597 |
+
with gr.Column():
|
598 |
+
gr.Markdown("# Simulation Visualization Interface")
|
599 |
+
with gr.Row():
|
600 |
+
with gr.Column():
|
601 |
+
|
602 |
+
|
603 |
+
# Sliders for each parameter
|
604 |
+
n_agents_slider = gr.Slider(minimum=100, maximum=500, step=10, label="Number of Agents", value=150)
|
605 |
+
share_regime_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Share of Regime Supporters", value=0.4)
|
606 |
+
threshold_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Threshold", value=0.5)
|
607 |
+
social_learning_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.1, label="Social Learning Factor", value=1.0)
|
608 |
+
steps_slider = gr.Slider(minimum=10, maximum=100, step=5, label="Simulation Steps", value=40)
|
609 |
+
half_life_slider = gr.Slider(minimum=5, maximum=50, step=5, label="Half-Life", value=20)
|
610 |
+
|
611 |
+
with gr.Column():
|
612 |
+
# Button to trigger the simulation
|
613 |
+
button = gr.Button("Run Simulation")
|
614 |
+
plot_output = gr.Plot(label="Simulation Result")
|
615 |
+
|
616 |
+
# Function to call when button is clicked
|
617 |
+
def run_simulation_and_plot(*args):
|
618 |
+
fig = run_and_plot_simulation(*args)
|
619 |
+
return fig
|
620 |
+
|
621 |
+
# Setting up the button click event
|
622 |
+
button.click(
|
623 |
+
run_simulation_and_plot,
|
624 |
+
inputs=[n_agents_slider, share_regime_slider, threshold_slider, social_learning_slider, steps_slider, half_life_slider],
|
625 |
+
outputs=[plot_output]
|
626 |
+
)
|
627 |
+
|
628 |
+
# Launch the interface
|
629 |
+
if __name__ == "__main__":
|
630 |
+
demo.launch(debug=True)
|
631 |
+
|