-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmodels.py
2643 lines (2151 loc) · 133 KB
/
models.py
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
370
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from settings import *
TRACK_TIME_SINCE_VARIABLES = False
import copy
from scipy.stats import norm
import gc
import math
def measure_property(network_intervention_dataset, property='avg_clustering', sample_size=None):
if sample_size is not None:
assert sample_size <= len(network_intervention_dataset), \
"not enough samples to do measurements on network_intervention_dataset, sample_size: " + str(sample_size) \
+ "len(network_intervention_dataset): " + str(len(network_intervention_dataset))
network_intervention_dataset = network_intervention_dataset[0:sample_size-1]
property_samples = []
for network_intervention in network_intervention_dataset:
if property is 'avg_clustering':
property_sample = NX.average_clustering(network_intervention)
elif property is 'average_shortest_path_length':
property_sample = NX.average_shortest_path_length(network_intervention)
elif property is 'diameter':
property_sample = NX.diameter(network_intervention)
elif property is 'size_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
property_sample = sample_2_core.number_of_nodes()
elif property is 'avg_degree':
degree_sequence = [d for n, d in network_intervention.degree()]
sum_of_edges = sum(degree_sequence)
property_sample = sum_of_edges/network_intervention.number_of_nodes()
elif property is 'diam_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = float('Inf')
else:
property_sample = NX.diameter(sample_2_core)
elif property is 'max_degree':
degree_sequence = sorted([d for n, d in network_intervention.degree()], reverse=True)
property_sample = max(degree_sequence)
elif property is 'min_degree':
degree_sequence = sorted([d for n, d in network_intervention.degree()], reverse=True)
property_sample = min(degree_sequence)
elif property is 'max_degree_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = 0
else:
degree_sequence = sorted([d for n, d in sample_2_core.degree()], reverse=True)
property_sample = max(degree_sequence)
elif property is 'min_degree_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = 0
else:
degree_sequence = sorted([d for n, d in sample_2_core.degree()], reverse=True)
property_sample = min(degree_sequence)
elif property is 'avg_degree_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = 0
else:
degree_sequence = [d for n, d in sample_2_core.degree()]
sum_of_edges = sum(degree_sequence)
property_sample = sum_of_edges / sample_2_core.number_of_nodes()
elif property is 'number_edges':
property_sample = network_intervention.number_of_edges()
elif property is 'number_edges_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = 0
else:
property_sample = sample_2_core.number_of_edges()
elif property is 'avg_clustering_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = float('NaN')
else:
property_sample = NX.average_clustering(sample_2_core)
elif property is 'transitivity':
property_sample = NX.transitivity(network_intervention)
elif property is 'transitivity_2_core':
sample_2_core = NX.k_core(network_intervention, k=2)
if sample_2_core.number_of_nodes() == 0:
property_sample = float('NaN')
else:
property_sample = NX.transitivity(sample_2_core)
elif property is 'num_leaves':
degree_sequence = sorted([d for n, d in network_intervention.degree()], reverse=True)
property_sample = degree_sequence.count(int(1))
else:
assert False, property + ' property not supported.'
property_samples += [property_sample]
return property_samples
def random_factor_pair(value):
"""
Returns a random pair that factor value.
It is used to set the number of columns and rows in 2D grid with a given size such that
size = num_columns*num_rows
"""
factors = []
for i in range(1, int(value**0.5)+1):
if value % i == 0:
factors.append((int(i), value // i))
return RD.choice(factors)
def newman_watts_add_fixed_number_graph(n, k=2, p=2, seed=None):
""" Returns a Newman-Watts-Strogatz small-world graph. With a fixed - p - (not random)
number of edges added to each node. Modified newman_watts_strogatzr_graph() in NetworkX. """
if seed is not None:
RD.seed(seed)
if k >= n:
raise NX.NetworkXError("k>=n, choose smaller k or larger n")
G = NX.connected_watts_strogatz_graph(n, k, 0)
all_nodes = G.nodes()
for u in all_nodes:
count_added_edges = 0 # track number of edges added to node u
while count_added_edges < p:
w = np.random.choice(all_nodes)
# no self-loops and reject if edge u-w exists
# is that the correct NWS model?
while w == u or G.has_edge(u, w):
w = np.random.choice(all_nodes)
# print('re-drawn w', w)
if G.degree(u) >= n-1:
break # skip this rewiring
G.add_edge(u, w)
count_added_edges += 1
return G
def cycle_union_Erdos_Renyi(n, k=4, c=2, seed=None,
color_the_edges=False,
cycle_edge_color='k',
random_edge_color='b',
weight_the_edges=False,
cycle_edge_weights=4,
random_edge_weights=4):
"""Returns a cycle C_k union G(n,c/n) graph by composing
NX.connected_watts_strogatz_graph(n, k, 0) and
NX.erdos_renyi_graph(n, c/n, seed=None, directed=False)"""
if seed is not None:
RD.seed(seed)
if k >= n:
raise NX.NetworkXError("k>=n, choose smaller k or larger n")
C_k = NX.connected_watts_strogatz_graph(n, k, 0)
if color_the_edges:
# cycle_edge_colors = dict.fromkeys(C_k.edges(), cycle_edge_color)
NX.set_edge_attributes(C_k, cycle_edge_color, 'color')
if weight_the_edges:
NX.set_edge_attributes(C_k, cycle_edge_weights, 'weight')
G_npn = NX.erdos_renyi_graph(n, c/n, seed=None, directed=False)
if color_the_edges:
# random_edge_colors = dict.fromkeys(G_npn.edges(), random_edge_color)
NX.set_edge_attributes(G_npn, random_edge_color, 'color')
if weight_the_edges:
NX.set_edge_attributes(G_npn, random_edge_weights, 'weight')
assert G_npn.nodes() == C_k.nodes(), "node sets are not the same"
composed = NX.compose(G_npn, C_k)
# print(composed.edges.data())
return composed
def two_d_lattice_union_Erdos_Renyi(n, c=4, seed=None,
color_the_edges=False,
square_edge_color='k',
square_edge_weights=4,
random_edge_color='b',
weight_the_edges=False,
random_edge_weights=4):
if seed is not None:
NX.seed(seed)
root_n = int(math.sqrt(n))
S_k = NX.generators.grid_2d_graph(root_n, root_n)
mapping = {node: i for i, node in enumerate(S_k.nodes())}
S_k = NX.relabel_nodes(S_k, mapping)
if color_the_edges:
NX.set_edge_attributes(S_k, square_edge_color, 'color')
if weight_the_edges:
NX.set_edge_attributes(S_k, square_edge_weights, 'weight')
G_npn = NX.generators.random_graphs.erdos_renyi_graph(n, c / n)
if color_the_edges:
NX.set_edge_attributes(G_npn, random_edge_color, 'color')
if weight_the_edges:
NX.set_edge_attributes(G_npn, random_edge_weights, 'weight')
composed = NX.compose(G_npn, S_k)
return composed
def two_d_lattice_union_diagonals(n, seed=None,
color_the_edges=False,
square_edge_color='k',
square_edge_weights=4,
weight_the_edges=False):
if seed is not None:
NX.seed(seed)
root_n = int(math.sqrt(n))
S_k = NX.grid_2d_graph(root_n, root_n)
mapping = {node: i for i, node in enumerate(S_k.nodes())}
S_k = NX.relabel_nodes(S_k, mapping)
for i in range(root_n - 1):
for j in range(root_n - 1):
nodes = [(i + j * root_n, i + (j + 1) * root_n + 1),
(i + 1 + j * root_n, i + 1 + (j + 1) * root_n - 1)]
S_k.add_edges_from([node for node in nodes])
if color_the_edges:
NX.set_edge_attributes(S_k, square_edge_color, 'color')
if weight_the_edges:
NX.set_edge_attributes(S_k, square_edge_weights, 'weight')
return S_k
def c_1_c_2_interpolation(n, eta, add_long_ties_exp, remove_cycle_edges_exp,seed=None):
"""Return graph that interpolates C_1 and C_2.
Those edges having add_long_ties_exp < eta are added.
Those edges having remove_cycle_edges_exp < eta are removed.
len(add_long_ties_exp) = n*(n-1)//2
len(remove_cycle_edges_exp) = n
"""
if seed is not None:
RD.seed(seed)
assert len(add_long_ties_exp) == n*(n-1)//2, "add_long_ties_exp has the wrong size"
assert len(remove_cycle_edges_exp) == n, "remove_cycle_edges_exp has the wrong size"
C_2 = NX.connected_watts_strogatz_graph(n, 4, 0)
C_2_minus_C_1_edge_index = 0
removal_list = []
for edge in C_2.edges():
# print(edge)
if abs(edge[0] - edge[1]) == 2 or abs(edge[0] - edge[1]) == n-2: # it is a C_2\C_1 edge
if remove_cycle_edges_exp[C_2_minus_C_1_edge_index] < eta:
removal_list += [edge]
C_2_minus_C_1_edge_index += 1 # index the next C_2\C_1 edge
C_2.remove_edges_from(removal_list)
addition_list = []
K_n = NX.complete_graph(n)
random_add_edge_index = 0
for edge in K_n.edges():
if add_long_ties_exp[random_add_edge_index] < eta:
addition_list += [edge]
random_add_edge_index += 1 # index the next edge to be considered for addition
C_2.add_edges_from(addition_list)
return C_2
def add_edges(G, number_of_edges_to_be_added=10, mode='random', seed=None):
"""Add number_of_edges_to_be_added edges to the NetworkX object G.
Two modes: 'random' or 'triadic_closures'
"""
if seed is not None:
RD.seed(seed)
number_of_edges_to_be_added = int(np.floor(number_of_edges_to_be_added))
assert type(G) is NX.classes.graph.Graph, "input should be a NetworkX graph object"
fat_network = copy.deepcopy(G)
unformed_edges = list(NX.non_edges(fat_network))
if len(unformed_edges) < number_of_edges_to_be_added:
print("There are not that many edges left ot be added")
fat_network.add_edges_from(unformed_edges) # add all the edges that are left
return fat_network
if mode is 'random':
addition_list = RD.sample(unformed_edges, number_of_edges_to_be_added)
fat_network.add_edges_from(addition_list)
return fat_network
if mode is 'triadic_closures':
weights = []
for non_edge in unformed_edges:
weights += [1.0*len(list(NX.common_neighbors(G, non_edge[0], non_edge[1])))]
total_sum = sum(weights)
normalized_weights = [weight/total_sum for weight in weights]
addition_list = np.random.choice(range(len(unformed_edges)),
number_of_edges_to_be_added,
replace=False,
p=normalized_weights)
addition_list = addition_list.astype(int)
addition_list = [unformed_edges[ii] for ii in list(addition_list)]
fat_network.add_edges_from(addition_list)
return fat_network
class NetworkModel(object):
"""
implement the initializations and parameter set methods
"""
def __init__(self):
pass
def init_network(self):
"""
initializes the network interconnections based on the params
"""
if 'network' in self.fixed_params:
self.params['network'] = self.fixed_params['network']
elif 'network' not in self.fixed_params:
if self.params['network_model'] == 'erdos_renyi':
if 'linkProbability' not in self.fixed_params: # erdos-renyi link probability
self.params['linkProbability'] = 2 * np.log(self.params['size']) / self.params[
'size'] # np.random.beta(1, 1, None)*20*np.log(self.params['size'])/self.params['size']
self.params['network'] = NX.erdos_renyi_graph(self.params['size'], self.params['linkProbability'])
if not NX.is_connected(self.params['network']):
self.params['network'] = NX.erdos_renyi_graph(self.params['size'], self.params['linkProbability'])
elif self.params['network_model'] == 'watts_strogatz':
if 'nearest_neighbors' not in self.fixed_params:
self.params['nearest_neighbors'] = 3
if 'rewiring_probability' not in self.fixed_params:
self.params['rewiring_probability'] = 0.000000005
self.params['network'] = NX.connected_watts_strogatz_graph(self.params['size'],
self.params['nearest_neighbors'],
self.params['rewiring_probability'])
elif self.params['network_model'] == 'grid':
if 'number_grid_rows' not in self.fixed_params:
if 'number_grid_columns' not in self.fixed_params:
(self.params['number_grid_columns'],self.params['number_grid_rows']) = \
random_factor_pair(self.params['size'])
else:
self.params['number_grid_rows'] = self.params['size'] // self.params['number_grid_columns']
self.params['number_grid_columns'] = self.params['size'] // self.params['number_grid_rows']
elif 'number_grid_columns' in self.fixed_params:
assert self.params['number_grid_columns']*self.params['number_grid_rows'] == self.params['size'], \
'incompatible size and grid dimensions'
else:
self.params['number_grid_columns'] = self.params['size'] // self.params['number_grid_rows']
self.params['number_grid_rows'] = self.params['size'] // self.params['number_grid_columns']
self.params['network'] = NX.grid_2d_graph(self.params['number_grid_rows'],
self.params['number_grid_columns'])
elif self.params['network_model'] == 'random_regular':
if 'degree' not in self.fixed_params:
self.params['degree'] = np.random.randint(1, 6)
self.params['network'] = NX.random_regular_graph(self.params['degree'], self.params['size'], seed=None)
elif self.params['network_model'] == 'newman_watts_fixed_number':
if 'fixed_number_edges_added' not in self.fixed_params:
self.params['fixed_number_edges_added'] = 2
if 'nearest_neighbors' not in self.fixed_params:
self.params['nearest_neighbors'] = 2
self.params['network'] = newman_watts_add_fixed_number_graph(self.params['size'],
self.params['nearest_neighbors'],
self.params['fixed_number_edges_added'])
elif self.params['network_model'] == 'cycle_union_Erdos_Renyi':
if 'c' not in self.fixed_params:
self.params['c'] = 2
if 'nearest_neighbors' not in self.fixed_params:
self.params['nearest_neighbors'] = 2
self.params['network'] = cycle_union_Erdos_Renyi(self.params['size'], self.params['nearest_neighbors'],
self.params['c'])
elif self.params['network_model'] == 'two_d_lattice_union_Erdos_Renyi':
if 'c' not in self.fixed_params:
self.params['c'] = 2
if 'nearest_neighbors' not in self.fixed_params:
self.params['nearest_neighbors'] = 2
self.params['network'] = two_d_lattice_union_Erdos_Renyi(self.params['size'], self.params['nearest_neighbors'])
elif self.params['network_model'] == 'two_d_lattice_union_diagonals':
if 'c' not in self.fixed_params:
self.params['c'] = 2
if 'nearest_neighbors' not in self.fixed_params:
self.params['nearest_neighbors'] = 2
self.params['network'] = two_d_lattice_union_diagonals(self.params['size'])
elif self.params['network_model'] == 'c_1_c_2_interpolation':
if 'c' not in self.fixed_params:
self.params['c'] = 2
if 'nearest_neighbors' not in self.fixed_params:
self.params['nearest_neighbors'] = 2
if 'add_long_ties_exp' not in self.fixed_params:
self.params['add_long_ties_exp'] = np.random.exponential(scale=self.params['size'] ** 2,
size=int(1.0 * self.params['size']
* (self.params['size'] - 1)) // 2)
self.params['remove_cycle_edges_exp'] = np.random.exponential(scale=2 * self.params['size'],
size=self.params['size'])
self.params['network'] = c_1_c_2_interpolation(self.params['size'],self.params['eta'],
self.params['add_long_ties_exp'],
self.params['remove_cycle_edges_exp'])
else:
assert False, 'undefined network type'
# when considering real network and interventions on them we may need to record the original network.
# This is currently only used in SimpleOnlyAlongOriginalEdges(ContagionModel)
if 'original_network' in self.fixed_params:
self.params['original_network'] = self.fixed_params['original_network']
else:
self.params['original_network'] = None
# additional modifications / structural interventions to the network topology which include rewiring
# and edge additions
if 'rewire' not in self.fixed_params:
self.params['rewire'] = False
print('warning: the network will not be rewired!')
if self.params['rewire']:
if 'rewiring_mode' not in self.fixed_params:
self.params['rewiring_mode'] = 'maslov_sneppen'
print('warning: the rewiring mode is set to maslov_sneppen')
if self.params['rewiring_mode'] == 'maslov_sneppen':
if 'num_steps_for_maslov_sneppen_rewiring' not in self.fixed_params:
self.params['num_steps_for_maslov_sneppen_rewiring'] = \
0.1 * self.params['network'].number_of_edges() # rewire 10% of edges
print('Warning: num_steps_for_maslov_sneppen_rewiring is set to default 10%')
rewired_network = \
self.maslov_sneppen_rewiring(
num_steps=int(np.floor(self.params['num_steps_for_maslov_sneppen_rewiring'])))
elif self.params['rewiring_mode'] == 'random_random':
if 'num_edges_for_random_random_rewiring' not in self.fixed_params:
self.params['num_edges_for_random_random_rewiring'] = \
0.1 * self.params['network'].number_of_edges() # rewire 10% of edges
print('warning: num_edges_for_random_random_rewiring is set to default 10%')
rewired_network = \
self.random_random_rewiring(
num_edges=int(np.floor(self.params['num_edges_for_random_random_rewiring'])))
self.params['network'] = rewired_network
if 'add_edges' not in self.fixed_params:
self.params['add_edges'] = False
if self.params['add_edges']:
if 'edge_addition_mode' not in self.fixed_params:
self.params['edge_addition_mode'] = 'triadic_closures'
if 'number_of_edges_to_be_added' not in self.fixed_params:
self.params['number_of_edges_to_be_added'] = \
int(np.floor(0.15 * self.params['network'].number_of_edges())) # add 15% more edges
fattened_network = add_edges(self.params['network'],
self.params['number_of_edges_to_be_added'],
self.params['edge_addition_mode'])
self.params['network'] = fattened_network
self.node_list = list(self.params['network']) # used for indexing nodes in cases where
# node attributes are available in a list. A typical application is as follows: self.node_list.index(i)
# for i in self.params['network'].nodes():
def init_network_states(self):
"""
initializes the node states (infected/susceptible) and other node attributes such as number of infected neighbors
and time since infection
"""
# when performing state transitions the following eight flags should be updated:
# self.number_of_active_infected_neighbors_is_updated
# self.time_since_infection_is_updated
# self.time_since_activation_is_updated
# self.list_of_susceptible_agents_is_updated
# self.list_of_active_infected_agents_is_updated
# self.list_of_inactive_infected_agents_is_updated
# self.list_of_exposed_agents_is_updated
# self.list_of_most_recent_activations_is_updated
self.number_of_active_infected_neighbors_is_updated = False
self.time_since_infection_is_updated = False
self.time_since_activation_is_updated = False
self.list_of_susceptible_agents = []
self.list_of_susceptible_agents_is_updated = False
self.list_of_active_infected_agents = []
self.list_of_active_infected_agents_is_updated = False
self.list_of_inactive_infected_agents = []
self.list_of_inactive_infected_agents_is_updated = False
self.list_of_exposed_agents = []
self.list_of_exposed_agents_is_updated = False
self.list_of_most_recent_activations = []
self.list_of_most_recent_activations_is_updated = False
# list of most recent activations is useful for speeding up pure (0,1)
# complex contagion computations by shortening the loop over exposed agents.
if 'initial_states' in self.fixed_params:
for i in range(NX.number_of_nodes(self.params['network'])):
if self.params['initial_states'][i] not in [susceptible, infected*active, infected*inactive]:
self.params['initial_states'][i] = infected*active
print('warning: states put to 0.5 for infected*active')
elif 'initial_states' not in self.fixed_params:
if 'initialization_mode' not in self.fixed_params:
self.params['initialization_mode'] = 'fixed_probability_initial_infection'
print('warning: The initialization_mode not supplied, '
'set to default fixed_probability_initial_infection')
if self.params['initialization_mode'] is 'fixed_probability_initial_infection':
# 'initial_infection_probability' should be specified.
if 'initial_infection_probability' not in self.fixed_params:
self.params['initial_infection_probability'] = 0.1
print('warning: The initial_infection_probability not supplied, set to default 0.1')
self.params['initial_states'] = active*\
np.random.binomial(1,
[self.params['initial_infection_probability']]*
self.params['size'])
elif self.params['initialization_mode'] is 'fixed_number_initial_infection':
if 'initial_infection_number' not in self.fixed_params:
self.params['initial_infection_number'] = 2
print('warning: The initial_infection_not supplied, set to default 2.')
initially_infected_node_indexes = np.random.choice(range(self.params['size']),
self.params['initial_infection_number'],
replace=False)
self.params['initial_states'] = 1.0*np.zeros(self.params['size'])
self.params['initial_states'][initially_infected_node_indexes] = infected * active
# all nodes are initially active by default
self.params['initial_states'] = list(self.params['initial_states'])
# new mode to start from the center
elif self.params['initialization_mode'] is 'fixed_number_initial_infection_at_center':
if 'initial_infection_number' not in self.fixed_params:
self.params['initial_infection_number'] = 2
print('warning: The initial_infection_not supplied, set to default 2.')
network_size = self.params['size']
print("we have the network size:"+network_size)
print(network_size)
initially_infected_node_indexes = [int(network_size/2 + int(math.sqrt(network_size))/2), int(network_size/2 - int(math.sqrt(network_size))/2)]
self.params['initial_states'] = 1.0 * np.zeros(self.params['size'])
self.params['initial_states'][initially_infected_node_indexes] = infected * active
# all nodes are initially active by default
self.params['initial_states'] = list(self.params['initial_states'])
else:
assert False, "undefined initialization_mode"
for i in self.params['network'].nodes():
self.params['network'].node[i]['number_of_active_infected_neighbors'] = 0
self.params['network'].node[i]['time_since_infection'] = 0
self.params['network'].node[i]['time_since_activation'] = 0
self.params['network'].node[i]['threshold'] = self.params['thresholds'][self.node_list.index(i)]
self.time_since_infection_is_updated = True
self.time_since_activation_is_updated = True
for i in self.params['network'].nodes():
self.params['network'].node[i]['state'] = self.params['initial_states'][self.node_list.index(i)]
if self.params['network'].node[i]['state'] == infected * active:
self.list_of_active_infected_agents.append(i)
self.list_of_most_recent_activations.append(i)
# for j in self.params['network'].neighbors(i):
# self.params['network'].node[j]['number_of_active_infected_neighbors'] += 1
# if ((j not in self.list_of_exposed_agents) and
# (self.params['network'].node[j]['state'] == susceptible)):
# self.list_of_exposed_agents.append(j)
elif self.params['network'].node[i]['state'] == infected * inactive:
self.list_of_inactive_infected_agents.append(i)
elif self.params['network'].node[i]['state'] == susceptible:
self.list_of_susceptible_agents.append(i)
else:
print('nodes', i)
print('state', self.params['network'].node[i]['state'])
print('state initialization miss-handled')
exit()
self.list_of_susceptible_agents_is_updated = True
self.list_of_active_infected_agents_is_updated = True
self.list_of_inactive_infected_agents_is_updated = True
self.list_of_most_recent_activations_is_updated = True
for i in self.list_of_active_infected_agents + self.list_of_inactive_infected_agents:
for j in self.params['network'].neighbors(i):
self.params['network'].node[j]['number_of_active_infected_neighbors'] += 1
if ((j not in self.list_of_exposed_agents) and
(self.params['network'].node[j]['state'] == susceptible)):
self.list_of_exposed_agents.append(j)
self.number_of_active_infected_neighbors_is_updated = True
self.list_of_exposed_agents_is_updated = True
assert self.number_of_active_infected_neighbors_is_updated and \
self.time_since_infection_is_updated and \
self.time_since_activation_is_updated and \
self.list_of_susceptible_agents_is_updated and \
self.list_of_active_infected_agents_is_updated and\
self.list_of_inactive_infected_agents_is_updated and \
self.list_of_exposed_agents_is_updated and \
self.list_of_most_recent_activations_is_updated, \
'error: state lists miss handled in the initializations'
self.updated_list_of_susceptible_agents = []
self.updated_list_of_active_infected_agents = []
self.updated_list_of_inactive_infected_agents = []
self.updated_list_of_exposed_agents = []
self.updated_list_of_most_recent_activations = []
def maslov_sneppen_rewiring(self, num_steps = SENTINEL, return_connected = True):
"""
Rewire the network graph according to the Maslov and
Sneppen method for degree-preserving random rewiring of a complex network,
as described on
`Maslov's webpage <http://www.cmth.bnl.gov/~maslov/matlab.htm>`_.
Return the resulting graph.
If a positive integer ``num_steps`` is given, then perform ``num_steps``
number of steps of the method.
Otherwise perform the default number of steps of the method, namely
``4*graph.num_edges()`` steps.
The code is adopted from: https://github.com/araichev/graph_dynamics/blob/master/graph_dynamics.py
"""
assert 'network' in self.params, 'error: network is not yet not set.'
if num_steps is SENTINEL:
num_steps = 10 * self.params['network'].number_of_edges()
# completely rewire everything
rewired_network = copy.deepcopy(self.params['network'])
for i in range(num_steps):
chosen_edges = RD.sample(rewired_network.edges(), 2)
e1 = chosen_edges[0]
e2 = chosen_edges[1]
new_e1 = (e1[0], e2[1])
new_e2 = (e2[0], e1[1])
if new_e1[0] == new_e1[1] or new_e2[0] == new_e2[1] or \
rewired_network.has_edge(*new_e1) or rewired_network.has_edge(*new_e2):
# Not allowed to rewire e1 and e2. Skip.
continue
rewired_network.remove_edge(*e1)
rewired_network.remove_edge(*e2)
rewired_network.add_edge(*new_e1)
rewired_network.add_edge(*new_e2)
if return_connected:
while not NX.is_connected(rewired_network):
rewired_network = copy.deepcopy(self.params['network'])
for i in range(num_steps):
chosen_edges = RD.sample(rewired_network.edges(), 2)
e1 = chosen_edges[0]
e2 = chosen_edges[1]
new_e1 = (e1[0], e2[1])
new_e2 = (e2[0], e1[1])
if new_e1[0] == new_e1[1] or new_e2[0] == new_e2[1] or \
rewired_network.has_edge(*new_e1) or rewired_network.has_edge(*new_e2):
# Not allowed to rewire e1 and e2. Skip.
continue
rewired_network.remove_edge(*e1)
rewired_network.remove_edge(*e2)
rewired_network.add_edge(*new_e1)
rewired_network.add_edge(*new_e2)
return rewired_network
def random_random_rewiring(self, num_edges=SENTINEL, return_connected=True):
"""
Rewire the network graph.
Choose num_edges randomly from the existing edges and remove them.
Choose num_edges randomly from the non-existing edges and add them.
"""
assert 'network' in self.params, 'error: network is not yet not set.'
if num_edges is SENTINEL:
num_edges = self.params['network'].number_of_edges()
print('Warning: number of edges to rewire not supplied, all edges will be rewired.')
# completely rewire everything
rewired_network = copy.deepcopy(self.params['network'])
unformed_edges = list(NX.non_edges(rewired_network))
formed_edges = list(NX.edges(rewired_network))
addition_list = np.random.choice(range(len(unformed_edges)),
num_edges,
replace=False)
addition_list = addition_list.astype(int)
addition_list = [unformed_edges[ii] for ii in list(addition_list)]
rewired_network.add_edges_from(addition_list)
removal_list = np.random.choice(range(len(formed_edges)),
num_edges,
replace=False)
removal_list = removal_list.astype(int)
removal_list = [formed_edges[ii] for ii in list(removal_list)]
rewired_network.remove_edges_from(removal_list)
if return_connected:
while not NX.is_connected(rewired_network):
rewired_network = copy.deepcopy(self.params['network'])
unformed_edges = list(NX.non_edges(rewired_network))
formed_edges = list(NX.edges(rewired_network))
addition_list = np.random.choice(range(len(unformed_edges)),
num_edges,
replace=False)
addition_list = addition_list.astype(int)
addition_list = [unformed_edges[ii] for ii in list(addition_list)]
rewired_network.add_edges_from(addition_list)
removal_list = np.random.choice(range(len(formed_edges)),
num_edges,
replace=False)
removal_list = removal_list.astype(int)
removal_list = [formed_edges[ii] for ii in list(removal_list)]
rewired_network.remove_edges_from(removal_list)
return rewired_network
def setRandomParams(self):
"""
the parameters that are provided when the class is being initialized are treated as fixed. The missing parameters
are set randomly. In an inference framework the distributions that determine the random draws are priors are those
parameters which are not fixed.
"""
assert self.missing_params_not_set, 'error: missing parameters are already set.'
# no spontaneous adoptions
if 'zero_at_zero' not in self.fixed_params:
self.params['zero_at_zero'] = True
# below threshold adoption rate is divided by the self.params['multiplier']
if 'multiplier' not in self.fixed_params:
self.params['multiplier'] = 5
# the high probability in complex contagion
if 'fixed_prob_high' not in self.fixed_params:
self.params['fixed_prob_high'] = 1.0
# the low probability in complex contagion
if 'fixed_prob' not in self.fixed_params:
self.params['fixed_prob'] = 0.0
# SI infection rate
if 'beta' not in self.fixed_params: # SIS infection rate parameter
self.params['beta'] = RD.choice([0.2, 0.3, 0.4, 0.5]) # 0.1 * np.random.beta(1, 1, None)#0.2 * np.random.beta(1, 1, None)
if 'sigma' not in self.fixed_params: # logit and probit parameter
self.params['sigma'] = RD.choice([0.1, 0.3, 0.5, 0.7, 1])
# complex contagion threshold
if 'theta' not in self.fixed_params: # complex contagion threshold parameter
self.params['theta'] = RD.choice([1, 2, 3, 4]) # np.random.randint(1, 4)
if 'theta_distribution' not in self.fixed_params: # complex contagion probability distribution of thresholds parameter
self.params['threshold'] = [0.25, 0.25, 0.25, 0.25] #default to equally likely to choose each number
# The default values gamma = 0 and alpha = 1 ensure that all infected nodes always remain active
if 'gamma' not in self.fixed_params: # rate of transition from active to inactive
self.params['gamma'] = 0.0 # RD.choice([0.2,0.3,0.4,0.5])
if 'alpha' not in self.fixed_params: # rate of transition from inactive to active
self.params['alpha'] = 1.0 # RD.choice([0.02,0.03,0.04,0.05])
if 'size' not in self.fixed_params:
if 'network' in self.fixed_params:
self.params['size'] = NX.number_of_nodes(self.params['network'])
else:
self.params['size'] = 100 # np.random.randint(50, 500)
if 'network_model' not in self.fixed_params:
self.params['network_model'] = RD.choice(['erdos_renyi', 'watts_strogatz', 'grid', 'random_regular'])
if 'thresholds' not in self.params:
assert not hasattr(self, 'isLinearThresholdModel'), \
"Thresholds should have been already set in the linear threshold model!"
if 'thresholds' in self.fixed_params:
self.params['thresholds'] = self.fixed_params['thresholds']
else:
self.params['thresholds'] = [self.params['theta']] * self.params['size']
self.init_network()
self.init_network_states()
self.missing_params_not_set = False
self.spread_stopped = False
class ContagionModel(NetworkModel):
"""
implements data generation
"""
def __init__(self, params):
super(ContagionModel, self).__init__()
self.fixed_params = copy.deepcopy(params)
self.params = params
self.missing_params_not_set = True
self.number_of_active_infected_neighbors_is_updated = False
self.time_since_infection_is_updated = False
self.time_since_activation_is_updated = False
self.list_of_susceptible_agents_is_updated = False
self.list_of_active_infected_agents_is_updated = False
self.list_of_inactive_infected_agents_is_updated = False
self.number_of_active_infected_neighbors_is_updated = False
self.list_of_most_recent_activations_is_updated = False
def time_the_total_spread(self, cap=1,
get_time_series=False,
verbose=False):
time = 0
network_time_series = []
fractions_time_series = []
self.missing_params_not_set = True
self.setRandomParams()
if hasattr(self, 'isActivationModel'):
self.set_activation_functions()
# record the values at time zero:
dummy_network = self.params['network'].copy()
all_nodes_states = list(
map(lambda node_pointer: 1.0 * self.params['network'].node[node_pointer]['state'],
self.params['network'].nodes()))
total_number_of_infected = 2*np.sum(abs(np.asarray(all_nodes_states)))
fraction_of_infected = total_number_of_infected / self.params['size']
if get_time_series:
network_time_series.append(dummy_network)
fractions_time_series.append(fraction_of_infected)
if verbose:
print('time is', time)
print('total_number_of_infected is', total_number_of_infected)
print('total size is', self.params['size'])
while (total_number_of_infected < cap*self.params['size']) and (not self.spread_stopped):
self.outer_step()
dummy_network = self.params['network'].copy()
time += 1
all_nodes_states = list(
map(lambda node_pointer: 1.0 * self.params['network'].node[node_pointer]['state'],
self.params['network'].nodes()))
total_number_of_infected = 2 * np.sum(abs(np.asarray(all_nodes_states)))
fraction_of_infected = total_number_of_infected / self.params['size']
if get_time_series:
network_time_series.append(dummy_network)
fractions_time_series.append(fraction_of_infected)
if verbose:
print('time is', time)
print('total_number_of_infected is', total_number_of_infected)
print('total size is', self.params['size'])
if time > self.params['size']*10:
time = float('Inf')
print('It is taking too long (10x size) to spread totally.')
break
del dummy_network
if get_time_series:
return time, total_number_of_infected, network_time_series, fractions_time_series
else:
return time, total_number_of_infected
def generate_network_intervention_dataset(self, dataset_size=200):
interventioned_networks = []
del interventioned_networks[:]
for i in range(dataset_size):
self.missing_params_not_set = True
self.setRandomParams()
interventioned_networks += [self.params['network']]
return interventioned_networks
def avg_speed_of_spread(self, dataset_size, cap=0.9, mode='max'):
# avg time to spread over the dataset.
# The time to spread is measured in one of the modes:
# integral, max, and total.
if mode == 'integral':
integrals = []
sum_of_integrals = 0
for i in range(dataset_size):
_, _, _, infected_fraction_timeseries = self.time_the_total_spread(cap=cap, get_time_series=True)
integral = sum(infected_fraction_timeseries)
sum_of_integrals += integral
integrals += [integral]
avg_speed = sum_of_integrals/dataset_size
speed_std = np.std(integrals)
speed_max = np.max(integrals)
speed_min = np.min(integrals)
speed_samples = np.asarray(integrals)
elif mode == 'max':
cap_times = []
sum_of_cap_times = 0
infection_sizes = []
sum_of_infection_sizes = 0
global fraction_evolution
fraction_evolution = []
for i in range(dataset_size):
print('dataset_counter_index is:', i)
time, infection_size,l1,l2 = self.time_the_total_spread(cap=cap, get_time_series=True)
cap_time = time
if cap_time == float('Inf'):
#dataset_size += -1
cap_times += [float('Inf')]
fraction_evolution += [l2]
continue
sum_of_cap_times += cap_time
cap_times += [cap_time]
sum_of_infection_sizes += infection_size
infection_sizes += [infection_size]
fraction_evolution += [l2]
gc.collect()
if dataset_size == 0:
avg_speed = float('Inf')
speed_std = float('NaN')
speed_max = float('Inf')
speed_min = float('Inf')
speed_samples = np.asarray([float('Inf')])
avg_infection_size = float('Inf')
infection_size_std = float('NaN')
infection_size_max = float('Inf')
infection_size_min = float('Inf')
infection_size_samples = np.asarray([float('Inf')])
else:
avg_speed = sum_of_cap_times/dataset_size
speed_std = np.ma.std(cap_times) # masked entries are ignored
speed_max = np.max(cap_times)
speed_min = np.min(cap_times)
speed_samples = np.asarray(cap_times)
avg_infection_size = sum_of_infection_sizes / dataset_size
infection_size_std = np.ma.std(infection_sizes) # masked entries are ignored
infection_size_max = np.max(infection_sizes)
infection_size_min = np.min(infection_sizes)
infection_size_samples = np.asarray(infection_sizes)
gc.collect()
elif mode == 'total':
fraction_evolution = []
total_spread_times = []
sum_of_total_spread_times = 0
infection_sizes = []
sum_of_infection_sizes = 0
count = 1
while count <= dataset_size:
total_spread_time, infection_size,l1,l2 = self.time_the_total_spread(cap=1, get_time_series=True)
if total_spread_time == float('Inf'):
dataset_size += -1
total_spread_times += [float('Inf')]
infection_size += [float('Inf')]
print('The contagion hit the time limit.')
continue
total_spread_times += [total_spread_time]
sum_of_total_spread_times += total_spread_time
sum_of_infection_sizes += infection_size
infection_sizes += [infection_size]
fraction_evolution += [l2]
count += 1