-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtask4.py
More file actions
317 lines (236 loc) · 10.4 KB
/
task4.py
File metadata and controls
317 lines (236 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
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
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
120
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
151
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
class Node:
def __init__(self, value, number, connections=None):
self.index = number
self.connections = connections
self.value = value
class Network:
def __init__(self, nodes=None):
if nodes is None:
self.nodes = []
else:
self.nodes = nodes
def get_mean_degree(self):
# Your code for task 3 goes here
pass
def get_mean_clustering(self):
# Your code for task 3 goes here
pass
def get_mean_path_length(self):
# Your code for task 3 goes here
pass
def make_random_network(self, N, connection_probability=0.5):
'''
This function makes a *random* network of size N.
Each node is connected to each other node with probability p
'''
self.nodes = []
for node_number in range(N):
value = np.random.random()
connections = [0 for _ in range(N)]
self.nodes.append(Node(value, node_number, connections))
for (index, node) in enumerate(self.nodes):
for neighbour_index in range(index + 1, N):
if np.random.random() < connection_probability:
node.connections[neighbour_index] = 1
self.nodes[neighbour_index].connections[index] = 1
def make_ring_network(self, N, neighbour_range=1):
self.nodes = []
for node_number in range(N):
value = np.random.random()
connections = [0 for _ in range(N)]
self.nodes.append(Node(value, node_number, connections))
for (index, node) in enumerate(self.nodes):
cursor = index
for forward in range(neighbour_range):
cursor += 1
if cursor == N:
cursor = 0
node.connections[cursor] = 1
self.nodes[cursor].connections[index] = 1
cursor = index
for backward in range(neighbour_range):
cursor -= 1
if cursor == -1:
cursor = N - 1
node.connections[cursor] = 1
self.nodes[cursor].connections[index] = 1
def make_small_world_network(self, N, re_wire_prob=0.2):
self.make_ring_network(N, 2)
for (index, node) in enumerate(self.nodes):
# edge_blacklist = []
for edge_index, edge in enumerate(node.connections):
if edge == 1: # and not edge_index in edge_blacklist:
if np.random.random() < re_wire_prob:
while True:
new_connection_index = np.random.randint(0, N)
if new_connection_index != index and new_connection_index != edge_index and \
node.connections[new_connection_index] != 1 and \
self.nodes[new_connection_index].connections[
index] != 1: # and not new_connection_index in edge_blacklist:
print("Rewiring edge...")
node.connections[new_connection_index] = 1
self.nodes[new_connection_index].connections[index] = 1
node.connections[edge_index] = 0
self.nodes[edge_index].connections[index] = 0
# edge_blacklist.append(new_connection_index)
break
def plot(self):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_axis_off()
num_nodes = len(self.nodes)
network_radius = num_nodes * 10
ax.set_xlim([-1.5 * network_radius, 1.5 * network_radius])
ax.set_ylim([-1.5 * network_radius, 1.5 * network_radius])
for (i, node) in enumerate(self.nodes):
node_angle = i * 2 * np.pi / num_nodes
node_x = network_radius * np.cos(node_angle)
node_y = network_radius * np.sin(node_angle)
circle = plt.Circle((node_x, node_y), 30, color=cm.hot(node.value))
ax.add_patch(circle)
for neighbour_index in range(i + 1, num_nodes):
if node.connections[neighbour_index]:
neighbour_angle = neighbour_index * 2 * np.pi / num_nodes
neighbour_x = network_radius * np.cos(neighbour_angle)
neighbour_y = network_radius * np.sin(neighbour_angle)
ax.plot((node_x, neighbour_x), (node_y, neighbour_y), color='black')
def test_networks():
# Ring network
nodes = []
num_nodes = 10
for node_number in range(num_nodes):
connections = [0 for val in range(num_nodes)]
connections[(node_number - 1) % num_nodes] = 1
connections[(node_number + 1) % num_nodes] = 1
new_node = Node(0, node_number, connections=connections)
nodes.append(new_node)
network = Network(nodes)
print("Testing ring network")
assert (network.get_mean_degree() == 2), network.get_mean_degree()
assert (network.get_clustering() == 0), network.get_clustering()
assert (network.get_path_length() == 2.777777777777778), network.get_path_length()
nodes = []
num_nodes = 10
for node_number in range(num_nodes):
connections = [0 for val in range(num_nodes)]
connections[(node_number + 1) % num_nodes] = 1
new_node = Node(0, node_number, connections=connections)
nodes.append(new_node)
network = Network(nodes)
print("Testing one-sided network")
assert (network.get_mean_degree() == 1), network.get_mean_degree()
assert (network.get_clustering() == 0), network.get_clustering()
assert (network.get_path_length() == 5), network.get_path_length()
nodes = []
num_nodes = 10
for node_number in range(num_nodes):
connections = [1 for val in range(num_nodes)]
connections[node_number] = 0
new_node = Node(0, node_number, connections=connections)
nodes.append(new_node)
network = Network(nodes)
print("Testing fully connected network")
assert (network.get_mean_degree() == num_nodes - 1), network.get_mean_degree()
assert (network.get_clustering() == 1), network.get_clustering()
assert (network.get_path_length() == 1), network.get_path_length()
print("All tests passed")
'''
==============================================================================================================
This section contains code for the Ising Model - task 1 in the assignment
==============================================================================================================
'''
def calculate_agreement(population, row, col, external=0.0):
'''
This function should return the extent to which a cell agrees with its neighbours.
Inputs: population (numpy array)
row (int)
col (int)
external (float)
Returns:
change_in_agreement (float)
'''
# Your code for task 1 goes here
return np.random.random() * population
def ising_step(population, external=0.0):
'''
This function will perform a single update of the Ising model
Inputs: population (numpy array)
external (float) - optional - the magnitude of any external "pull" on opinion
'''
n_rows, n_cols = population.shape
row = np.random.randint(0, n_rows)
col = np.random.randint(0, n_cols)
agreement = calculate_agreement(population, row, col, external=0.0)
if agreement < 0:
population[row, col] *= -1
# Your code for task 1 goes here
def plot_ising(im, population):
'''
This function will display a plot of the Ising model
'''
new_im = np.array([[255 if val == -1 else 1 for val in rows] for rows in population], dtype=np.int8)
im.set_data(new_im)
plt.pause(0.1)
def test_ising():
'''
This function will test the calculate_agreement function in the Ising model
'''
print("Testing ising model calculations")
population = -np.ones((3, 3))
assert (calculate_agreement(population, 1, 1) == 4), "Test 1"
population[1, 1] = 1.
assert (calculate_agreement(population, 1, 1) == -4), "Test 2"
population[0, 1] = 1.
assert (calculate_agreement(population, 1, 1) == -2), "Test 3"
population[1, 0] = 1.
assert (calculate_agreement(population, 1, 1) == 0), "Test 4"
population[2, 1] = 1.
assert (calculate_agreement(population, 1, 1) == 2), "Test 5"
population[1, 2] = 1.
assert (calculate_agreement(population, 1, 1) == 4), "Test 6"
"Testing external pull"
population = -np.ones((3, 3))
assert (calculate_agreement(population, 1, 1, 1) == 3), "Test 7"
assert (calculate_agreement(population, 1, 1, -1) == 5), "Test 8"
assert (calculate_agreement(population, 1, 1, 10) == -6), "Test 9"
assert (calculate_agreement(population, 1, 1, -10) == 14), "Test 10"
print("Tests passed")
def ising_main(population, alpha=None, external=0.0):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_axis_off()
im = ax.imshow(population, interpolation='none', cmap='RdPu_r')
# Iterating an update 100 times
for frame in range(100):
# Iterating single steps 1000 times to form an update
for step in range(1000):
ising_step(population, external)
print('Step:', frame, end='\r')
plot_ising(im, population)
'''
==============================================================================================================
This section contains code for the Defuant Model - task 2 in the assignment
==============================================================================================================
'''
def defuant_main():
# Your code for task 2 goes here
pass
def test_defuant():
# Your code for task 2 goes here
pass
'''
==============================================================================================================
This section contains code for the main function- you should write some code for handling flags here
==============================================================================================================
'''
def main():
# You should write some code for handling flags here
network = Network()
network.make_small_world_network(20, 0.2)
network.plot()
plt.show()
if __name__ == "__main__":
main()