-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo_experiment.py
More file actions
1656 lines (1375 loc) · 70.3 KB
/
Copy pathdo_experiment.py
File metadata and controls
1656 lines (1375 loc) · 70.3 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
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
import hashlib
import os
import pickle
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
import matplotlib as mpl
from globals import *
from net import Net
from tqdm import tqdm
import cycler
import random
random.seed(12345)
# Direct input
plt.rcParams['text.latex.preamble'] = r"\usepackage{bm} \usepackage{amsmath}"
# plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]
# Options
params = {'text.usetex': True,
'font.size': 10,
'font.family': 'serif'
# 'font.family' : 'lmodern',
}
plt.rcParams.update(params)
columwidth = 251.8 / 72.27 # 251.80688[pt] / 72.27[pt/inch]
def estimateQuotientCI(ax, xvalues, mean1, sd1, mean2, sd2, color, mccount, p=95):
iters = 2000
lowers = list()
uppers = list()
percs = [(100 - p) / 2, 100 - (100 - p) / 2]
"""
Monte Carlo mean 1/N*sum(X_i) implies:
V(1/N*sum(X_i))=1/(N^2)*sum(V(X_i))=1/(N^2)*N*V(X)=V(X)/N
=> Variance of monte carlo mean is 1/N times variance of single model result
=> SD is 1/sqrt(N) times SD of model result
"""
sd11 = sd1 / (mccount ** 0.5)
sd21 = sd2 / (mccount ** 0.5)
for m1, s1, m2, s2 in zip(mean1, sd11, mean2, sd21):
quotients = list()
for i in range(iters):
"""
since (sum(X_i)-mu)/(sqrt(N)*sigma) converges towards Normal(0,1) we may
assume 1/N*sum(X_i) approx ~ Normal(mu,sigma/sqrt(N))
"""
denom = random.normalvariate(m2, s2)
if denom <= 0: # truncate normal dist - negative values dont make sense
continue
nom = random.normalvariate(m1, s1)
if nom < 0: # truncate normal dist - negative values dont make sense
continue
quotients.append(nom / denom)
ps = np.percentile(quotients, percs)
lowers.append(ps[0])
uppers.append(ps[1])
ax.fill_between(xvalues, lowers, uppers, color=color, alpha=0.2, zorder=-1)
# pickling disabled for now, uncomment plot lines for that
def simple_experiment_old(n, p, p_i, mc_iterations, max_t, seed=0, mode=None, force_recompute=False, path=None,
clustering: float = None, dispersion=None):
# this creates the net, runs monte carlo on it and saves the resulting timeseries plot, as well as pickles for net and counts
assert not (dispersion and clustering), "Cannot set a dispersion target and " \
"a clustering target at the same time"
if dispersion:
chosen_epsilon = epsilon_disp
else:
chosen_epsilon = epsilon_clustering
if path:
dirname = path
else:
dirname_parent = os.path.dirname(__file__)
dirname = os.path.join(dirname_parent, 'Experiments')
# the cache is now tagged with a hash from all important parameters instead of the above.
# Any change to the model parameters will certainly trigger a recompute now
id_params = (
n, p, p_i, mc_iterations, max_t, seed, mode, clustering, dispersion, t_i, t_c, t_r, t_d, t_t, p_q, p_t,
quarantine_time, resolution, chosen_epsilon)
# normal hashes are salted between runs -> use something that is persistent
tag = str(hashlib.md5(str(id_params).encode('utf8')).hexdigest())
# disables loading pickled results
if force_recompute:
# if false, it looks at saved experiments and reuses those
net = Net(n=n, p=p, p_i=p_i, max_t=max_t, seed=seed, clustering_target=clustering, dispersion_target=dispersion)
counts, sd, achieved_clustering, achieved_disp = net.monte_carlo(mc_iterations, mode=mode)
with open(os.path.join(dirname, tag + '_net.p'), 'wb') as f:
pickle.dump((net, achieved_clustering, achieved_disp), f)
with open(os.path.join(dirname, tag + '_counts.p'), 'wb') as f:
pickle.dump((counts, sd), f)
else:
try:
with open(os.path.join(dirname, tag + "_counts.p"), 'rb') as f:
counts, sd = pickle.load(f)
with open(os.path.join(dirname, tag + "_net.p"), 'rb') as f:
net, achieved_clustering, achieved_disp = pickle.load(f)
print('Experiment results have been loaded from history.')
except FileNotFoundError:
net = Net(n=n, p=p, p_i=p_i, max_t=max_t, seed=seed, clustering_target=clustering,
dispersion_target=dispersion)
counts, sd, achieved_clustering, achieved_disp = net.monte_carlo(mc_iterations, mode=mode)
with open(os.path.join(dirname, tag + '_net.p'), 'wb') as f:
pickle.dump((net, achieved_clustering, achieved_disp), f)
with open(os.path.join(dirname, tag + '_counts.p'), 'wb') as f:
pickle.dump((counts, sd), f)
exposed = counts[EXP_STATE, :]
infected = counts[INF_STATE, :]
ep_curve = exposed + infected
# compute when the peak happens and what the ratio of infected is then
t_peak = np.argmax(ep_curve, axis=0)
peak_height = ep_curve[t_peak] / n
# compute the ratio of all exposed people at end of sim to the number of indiv.
# (also check heuristically whether an equilibrium has been reached
recovered = counts[REC_STATE, :]
virus_contacts = ep_curve + recovered
sensitivity = max(1, n / 100) # increasing divisor makes this more sensitive
equilib_flag = abs(
virus_contacts[-1] - virus_contacts[-2]) < sensitivity # just a heuristic, see whether roc is low
period_prevalence = virus_contacts[-1] / n
return net, counts, sd, t_peak, peak_height, equilib_flag, period_prevalence, achieved_clustering, achieved_disp
from do_experiment_parallel import \
simple_experiment # this is the new, parallel version of the above function. By Martin!
def vary_p(res, n, p_i, mc_iterations, max_t, interval=(0, 1), seed=0, mode=None, force_recompute=False, path=None):
# here I want to systematically check what varying the edge probability does. Should return something like a 1d heatmap?
# return value should use one of the values t_peak, peak_height, equilib_flag, period_prevalence
peak_times = np.ndarray(res)
mean_peak_heights = np.ndarray(res)
mean_period_prevalences = np.ndarray(res)
sd_peak_heights = np.ndarray(res)
sd_period_prevalences = np.ndarray(res)
ps = np.linspace(interval[0], interval[1], endpoint=True, num=res)
for i, p in enumerate(ps):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, clustering, dispersion = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i, mode=mode,
force_recompute=force_recompute, path=path)
peak_times[i] = t_peak
mean_peak_heights[i] = mean_peak
sd_peak_heights[i] = sd_peak
mean_period_prevalences[i] = mean_prevalence
sd_period_prevalences[i] = sd_prevalence
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(16 * 1.5, 9 * 1.5))
ax1, ax2, ax3 = axes
if mode:
ax1.set_title(mode)
else:
ax1.set_title('vanilla')
ax1.plot(ps, peak_times)
# ax1.set_xlabel('p')
ax1.set_ylabel('Peak time')
ax2.plot(ps, mean_peak_heights)
# ax2.set_xlabel('p')
ax2.set_ylabel('Peak prevalence')
ax3.plot(ps, mean_period_prevalences)
ax3.set_ylabel('Fraction of affected')
ax3.set_xlabel('p')
# labels = [interval[0],] + list(['' for i in range(len(ps)-2)]) + [interval[1],]
ax3.set_xticks(ps[1:-2], minor=True)
ax3.set_xticks([interval[0], interval[1]])
plt.tick_params(
axis='x', # changes apply to the x-axis
which='minor', # both major and minor ticks are affected
# bottom=False, # ticks along the bottom edge are off
# top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
# plt.xticks([interval[0],interval[1]])
if mode:
fig.savefig(os.path.join(path, 'pvaried_n{}_p{}_{}'.format(
n, str(interval[0]) + 'to' + str(interval[1]), mode) + '.png'))
else:
fig.savefig(os.path.join(path, 'pvaried_n{}_p{}'.format(
n, str(interval[0]) + 'to' + str(interval[1])) + '.png'))
def vary_p_plot_cache(res, n, p_i, mc_iterations, max_t, interval=(0, 1), seed=0, force_recompute=False, path=None):
# utility function that loads all the pickles (or runs them first) and plots the three scenarios
# is a modified copy of vary_p !
peak_times = np.ndarray(res)
peak_heights = np.ndarray(res)
period_prevalences = np.ndarray(res)
peak_times_q = np.ndarray(res)
peak_heights_q = np.ndarray(res)
period_prevalences_q = np.ndarray(res)
peak_times_t = np.ndarray(res)
peak_heights_t = np.ndarray(res)
period_prevalences_t = np.ndarray(res)
peak_heights_sd = np.ndarray(res)
peak_heights_q_sd = np.ndarray(res)
peak_heights_t_sd = np.ndarray(res)
period_prevalences_sd = np.ndarray(res)
period_prevalences_q_sd = np.ndarray(res)
period_prevalences_t_sd = np.ndarray(res)
ps = np.linspace(interval[0], interval[1], endpoint=True, num=res)
# all 3 modes
for i, p in tqdm(enumerate(ps), total=res, desc='Vanilla'):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i + res, mode=None,
force_recompute=force_recompute, path=path)
peak_times[i] = t_peak
peak_heights[i] = mean_peak
peak_heights_sd[i] = sd_peak
period_prevalences[i] = mean_prevalence
period_prevalences_sd[i] = sd_prevalence
for i, p in tqdm(enumerate(ps), total=res, desc='Quarantine'):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i + 2 * res, mode='quarantine',
force_recompute=force_recompute,
path=path)
peak_times_q[i] = t_peak
peak_heights_q[i] = mean_peak
peak_heights_q_sd[i] = sd_peak
period_prevalences_q[i] = mean_prevalence
period_prevalences_q_sd[i] = sd_prevalence
for i, p in tqdm(enumerate(ps), total=res, desc='Tracing'):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i + 3 * res, mode='tracing',
force_recompute=force_recompute,
path=path)
peak_times_t[i] = t_peak
peak_heights_t[i] = mean_peak
peak_heights_t_sd[i] = sd_peak
period_prevalences_t[i] = mean_prevalence
period_prevalences_t_sd[i] = sd_prevalence
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(14, 14 / 16 * 9))
ax1, ax2, ax3 = axes
ax1.plot(ps, peak_times, ps, peak_times_q, ps, peak_times_t)
ax1.set_ylabel('Peak time')
ax2.plot(ps, peak_heights, ps, peak_heights_q, ps, peak_heights_t)
ax2.set_ylabel('Peak prevalence')
ax3.plot(ps, period_prevalences, ps, period_prevalences_q, ps, period_prevalences_t)
ax3.set_ylabel('Fraction of affected')
ax3.set_xlabel('p')
ax3.set_xticks(ps[1:-2], minor=True)
ax3.set_xticks([interval[0], interval[1]])
plt.legend(['Vanilla', 'Quarantine', 'Tracing'])
plt.tick_params(
axis='x',
which='minor',
# bottom=False, # ticks along the bottom edge are off
# top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
# plt.xticks([interval[0],interval[1]])
parent = os.path.dirname(path)
fig.savefig(os.path.join(parent, 'Pics', 'pvaried_n{}_mc{}_{}'.format(n, mc_iterations, 'comp') + '.png'),
bbox_inches='tight')
# this feels pretty uninteresting:
def vary_p_i(res, n, p, mc_iterations, max_t, seed=0, mode=None, force_recompute=False, path=None):
# here I want to systematically check what varying the edge probability does. Should return something like a 1d heatmap?
# return value should use one of the values t_peak, peak_height, equilib_flag, period_prevalence
peak_times = np.ndarray(res)
peak_heights = np.ndarray(res)
peak_heights_sd = np.ndarray(res)
# flags = np.ndarray(res)
period_prevalences = np.ndarray(res)
period_prevalences_sd = np.ndarray(res)
p_is = np.linspace(0, 1, endpoint=True, num=res)
for i, p_inf in enumerate(p_is):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_inf, mc_iterations, max_t, seed=seed + i, mode=mode,
force_recompute=force_recompute, path=path)
# TODO seed inside simple_experiment is constant, think about whether that's ok!
peak_times[i] = t_peak
peak_heights[i] = mean_peak
peak_heights_sd[i] = sd_peak
period_prevalences[i] = mean_prevalence
period_prevalences_sd[i] = sd_prevalence
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(16 * 1.5, 9 * 1.5))
# fig.subplots_adjust(wspace = 0.5)
ax1, ax2, ax3 = axes
ax1.plot(p_is, peak_times)
# ax1.set_xlabel('p')
ax1.set_ylabel('peak-times')
ax2.plot(p_is, peak_heights)
# ax2.set_xlabel('p')
ax2.set_ylabel('peak-height')
ax3.plot(p_is, period_prevalences)
# ax3.set_xlabel('p')
ax3.set_ylabel('percentage of affected')
ax3.set_xlabel('infection probability')
ax3.set_xticks(p_is)
# plt.show()
if mode:
fig.savefig(os.path.join(path, 'pivaried_n{}_p{}_{}'.format(n, p, mode) + '.png'))
else:
fig.savefig(os.path.join(path, 'pivaried_n{}_p{}'.format(n, p) + '.png'))
def vary_C(res, n, p, p_i, mc_iterations, max_t, interval=None, seed=0, mode=None, force_recompute=False, path=None):
# measure effect of clustering coeff on tracing effectiveness
if not interval:
# THEORY: the average clustering coeff of erdos renyi networks is p!
# so I test around that to see what changed
interval = (0.5 * p, 10 * p)
peak_times = np.ndarray(res)
peak_heights = np.ndarray(res)
peak_heights_sd = np.ndarray(res)
period_prevalences = np.ndarray(res)
period_prevalences_sd = np.ndarray(res)
Cs = np.linspace(interval[0], interval[1], endpoint=True, num=res)
unsuccessful_flag = []
for i, C in tqdm(enumerate(Cs), total=res):
try:
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i, mode=mode,
force_recompute=force_recompute,
path=path, clustering=C)
peak_times[i] = t_peak
peak_heights[i] = mean_peak
peak_heights_sd[i] = sd_peak
period_prevalences[i] = mean_prevalence
period_prevalences_sd[i] = sd_prevalence
# Cs[i] = net.final_cluster_coeff # in the end I want to plot the actual coeff, not the target
# should specify this in the paper
except AssertionError:
print('Clustering target not reached')
unsuccessful_flag.append(i)
peak_times[i] = np.nan
peak_heights[i] = np.nan
peak_heights_sd[i] = np.nan
period_prevalences[i] = np.nan
period_prevalences_sd[i] = np.nan
dirname_parent = os.path.dirname(__file__)
dirname = os.path.join(dirname_parent, 'Experiments', 'Paper', 'Cache')
id_params = (
n, p, p_i, mc_iterations, max_t, seed, mode, interval, t_i, t_c, t_r, t_d, t_t, p_q, p_t, quarantine_time,
resolution,
epsilon_disp, 'disp')
# normal hashes are salted between runs -> use something that is persistent
tag = str(hashlib.md5(str(id_params).encode('utf8')).hexdigest())
with open(os.path.join(dirname, tag + '_metrics.p'), 'wb') as f:
out = [Cs, unsuccessful_flag, peak_times, peak_heights, period_prevalences]
pickle.dump(out, f)
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(14, 14 / 16 * 9))
# fig.subplots_adjust(wspace = 0.5)
ax1, ax2, ax3 = axes
colordict = {'vanilla': 'C0', 'quarantine': 'C1', 'tracing': 'C2'}
if mode:
ax1.set_title(mode)
else:
ax1.set_title('Vanilla')
ax1.plot(Cs, peak_times, colordict[mode])
ax1.set_ylabel('Peak time')
ax2.plot(Cs, peak_heights, colordict[mode])
ax2.set_ylabel('Peak prevalence')
ax3.plot(Cs, period_prevalences, colordict[mode])
ax3.set_ylabel('Fraction of affected')
ax3.set_xlabel('C(g)')
# labels = [interval[0],] + list(['' for i in range(len(ps)-2)]) + [interval[1],]
ax3.set_xticks(Cs[1:-1], minor=True)
ax3.set_xticks([interval[0], interval[1]])
# plt.tick_params(
# axis='x', # changes apply to the x-axis
# which='minor', # both major and minor ticks are affected
# # bottom=False, # ticks along the bottom edge are off
# # top=False, # ticks along the top edge are off
# labelbottom=False) # labels along the bottom edge are off
# plt.xticks([interval[0],interval[1]])
if mode:
parent = os.path.dirname(path)
fig.savefig(os.path.join(parent, 'Pics', 'Cvaried_n{}_p{}_{}'.format(
n, str(interval[0]) + 'to' + str(interval[1]), mode) + '.png'), bbox_inches='tight')
else:
parent = os.path.dirname(path)
fig.savefig(os.path.join(parent, 'Pics', 'Cvaried_n{}_C{}'.format(
n, str(interval[0]) + 'to' + str(interval[1])) + '.png'), bbox_inches='tight')
return out # Cs, unsuccessful_flags, times, peaks, period_prev
def vary_disp(res, n, p, p_i, mc_iterations, max_t, interval=None, seed=0, mode=None, force_recompute=False, path=None):
# measure effect of clustering coeff on tracing effectiveness
if not interval:
# THEORY: the average clustering coeff of erdos renyi networks is p!
# so I test around that to see what changed
interval = (0.5 * p, 10 * p)
peak_times = np.ndarray(res)
peak_heights = np.ndarray(res)
peak_heights_sd = np.ndarray(res)
period_prevalences = np.ndarray(res)
period_prevalences_sd = np.ndarray(res)
Ds = np.linspace(interval[0], interval[1], endpoint=True, num=res)
unsuccessful_flag = []
for i, D in tqdm(enumerate(Ds), total=res, desc='Varying dispersion values'):
try:
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i, mode=mode,
force_recompute=force_recompute,
path=path, dispersion=D)
peak_times[i] = t_peak
peak_heights[i] = mean_peak
peak_heights_sd[i] = sd_peak
period_prevalences[i] = mean_prevalence
period_prevalences_sd[i] = sd_prevalence
print('last_disp{}, target_disp{}'.format(net.final_dispersion, D))
# Cs[i] = net.final_cluster_coeff # in the end I want to plot the actual coeff, not the target
# should specify this in the paper
except AssertionError:
print('Dispersion target not reached')
unsuccessful_flag.append(i)
peak_times[i] = np.nan
peak_heights[i] = np.nan
peak_heights_sd[i] = np.nan
period_prevalences[i] = np.nan
period_prevalences_sd[i] = np.nan
dirname_parent = os.path.dirname(__file__)
dirname = os.path.join(dirname_parent, 'Experiments', 'Paper', 'Cache')
id_params = (
n, p, p_i, mc_iterations, max_t, mode, seed, interval, t_i, t_c, t_r, t_d, t_t, p_q, p_t, quarantine_time,
resolution,
epsilon_disp)
# normal hashes are salted between runs -> use something that is persistent
tag = str(hashlib.md5(str(id_params).encode('utf8')).hexdigest())
with open(os.path.join(dirname, tag + '_metrics.p'), 'wb') as f:
out = [Ds, unsuccessful_flag, peak_times, peak_heights, period_prevalences]
pickle.dump(out, f)
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(14, 14 / 16 * 9))
# fig.subplots_adjust(wspace = 0.5)
ax1, ax2, ax3 = axes
colordict = {'vanilla': 'C0', 'quarantine': 'C1', 'tracing': 'C2'}
if mode:
ax1.set_title(mode)
else:
ax1.set_title('Vanilla')
ax1.plot(Ds, peak_times, colordict[mode])
ax1.set_ylabel('Peak time')
ax2.plot(Ds, peak_heights, colordict[mode])
ax2.set_ylabel('Peak prevalence')
ax3.plot(Ds, period_prevalences, colordict[mode])
ax3.set_ylabel('Fraction of affected')
ax3.set_xlabel('C(g)')
# labels = [interval[0],] + list(['' for i in range(len(ps)-2)]) + [interval[1],]
ax3.set_xticks(Ds[1:-1], minor=True)
ax3.set_xticks([interval[0], interval[1]])
# plt.tick_params(
# axis='x', # changes apply to the x-axis
# which='minor', # both major and minor ticks are affected
# # bottom=False, # ticks along the bottom edge are off
# # top=False, # ticks along the top edge are off
# labelbottom=False) # labels along the bottom edge are off
# plt.xticks([interval[0],interval[1]])
if mode:
parent = os.path.dirname(path)
fig.savefig(os.path.join(parent, 'Pics', 'dispvaried_n{}_p{}_{}'.format(
n, str(interval[0]) + 'to' + str(interval[1]), mode) + '.png'), bbox_inches='tight')
else:
parent = os.path.dirname(path)
fig.savefig(os.path.join(parent, 'Pics', 'dispvaried_n{}_C{}'.format(
n, str(interval[0]) + 'to' + str(interval[1])) + '.png'), bbox_inches='tight')
return out # Cs, unsuccessful_flags, times, peaks, period_prev
def vary_C_comp(res, n, p, p_i, mc_iterations, max_t, interval=None, seed=0, force_recompute=False, path=None):
# measure effect of clustering coeff on tracing effectiveness
if not interval:
# THEORY: the average clustering coeff of erdos renyi networks is p!
# so I test around that to see what changed
interval = (0.5 * p, 10 * p)
Cs = np.linspace(interval[0], interval[1], endpoint=True, num=res)
peak_times_1 = np.ndarray(res)
peak_heights_1 = np.ndarray(res)
peak_heights_sd_1 = np.ndarray(res)
period_prevalences_1 = np.ndarray(res)
period_prevalences_sd_1 = np.ndarray(res)
unsuccessful_flags_1 = []
for i, C in tqdm(enumerate(Cs), total=res, desc='Vanilla'):
try:
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i, mode='vanilla',
force_recompute=force_recompute,
path=path, clustering=C)
peak_times_1[i] = t_peak
peak_heights_1[i] = mean_peak
peak_heights_sd_1[i] = sd_peak
period_prevalences_1[i] = mean_prevalence
period_prevalences_sd_1[i] = sd_prevalence
# Cs[i] = net.final_cluster_coeff # in the end I want to plot the actual coeff, not the target
# should specify this in the paper
except AssertionError:
print('Clustering target not reached')
unsuccessful_flags_1.append(i)
peak_times_1[i] = np.nan
peak_heights_1[i] = np.nan
peak_heights_sd_1[i] = np.nan
period_prevalences_1[i] = np.nan
period_prevalences_sd_1[i] = np.nan
peak_times_2 = np.ndarray(res)
peak_heights_2 = np.ndarray(res)
peak_heights_sd_2 = np.ndarray(res)
period_prevalences_2 = np.ndarray(res)
period_prevalences_sd_2 = np.ndarray(res)
unsuccessful_flags_2 = []
for i, C in tqdm(enumerate(Cs), total=res, desc='Quarantine'):
try:
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i + res, mode='quarantine',
force_recompute=force_recompute,
path=path, clustering=C)
peak_times_2[i] = t_peak
peak_heights_2[i] = mean_peak
peak_heights_sd_2[i] = sd_peak
period_prevalences_2[i] = mean_prevalence
period_prevalences_sd_2[i] = sd_prevalence
# Cs[i] = net.final_cluster_coeff # in the end I want to plot the actual coeff, not the target
# should specify this in the paper
except AssertionError:
print('Clustering target not reached')
unsuccessful_flags_2.append(i)
peak_times_2[i] = np.nan
peak_heights_2[i] = np.nan
peak_heights_sd_2[i] = np.nan
period_prevalences_2[i] = np.nan
period_prevalences_sd_2[i] = np.nan
peak_times_3 = np.ndarray(res)
peak_heights_3 = np.ndarray(res)
peak_heights_sd_3 = np.ndarray(res)
period_prevalences_3 = np.ndarray(res)
period_prevalences_sd_3 = np.ndarray(res)
unsuccessful_flags_3 = []
for i, C in tqdm(enumerate(Cs), total=res, desc='Tracing'):
try:
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i + 2 * res, mode='tracing',
force_recompute=force_recompute,
path=path, clustering=C)
peak_times_3[i] = t_peak
peak_heights_3[i] = mean_peak
peak_heights_sd_3[i] = sd_peak
period_prevalences_3[i] = mean_prevalence
period_prevalences_sd_3[i] = sd_prevalence
# Cs[i] = net.final_cluster_coeff # in the end I want to plot the actual coeff, not the target
# should specify this in the paper
except AssertionError:
print('Clustering target not reached')
unsuccessful_flags_3.append(i)
peak_times_3[i] = np.nan
peak_heights_3[i] = np.nan
peak_heights_sd_3[i] = np.nan
period_prevalences_3[i] = np.nan
period_prevalences_sd_3[i] = np.nan
dirname_parent = os.path.dirname(__file__)
dirname = os.path.join(dirname_parent, 'Experiments', 'Paper', 'Cache')
id_params = (
n, p, p_i, mc_iterations, max_t, interval, seed, t_i, t_c, t_r, t_d, t_t, p_q, p_t, quarantine_time, resolution,
epsilon_clustering)
# normal hashes are salted between runs -> use something that is persistent
tag = str(hashlib.md5(str(id_params).encode('utf8')).hexdigest())
with open(os.path.join(dirname, tag + '_metrics.p'), 'wb') as f:
out = [Cs, unsuccessful_flags_1, peak_times_1, peak_heights_1, period_prevalences_1,
Cs, unsuccessful_flags_2, peak_times_2, peak_heights_2, period_prevalences_2,
Cs, unsuccessful_flags_3, peak_times_3, peak_heights_3, period_prevalences_3]
pickle.dump(out, f)
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(14, 14 / 16 * 9))
# fig.subplots_adjust(wspace = 0.5)
ax1, ax2, ax3 = axes
ax1.plot(Cs, peak_times_1, Cs, peak_times_2, Cs, peak_times_3)
ax1.set_ylabel('Peak time')
ax2.plot(Cs, peak_heights_1, Cs, peak_heights_2, Cs, peak_heights_3)
ax2.set_ylabel('Peak prevalence')
ax3.plot(Cs, period_prevalences_1, Cs, period_prevalences_2, Cs, period_prevalences_3)
ax3.set_ylabel('Fraction of affected')
ax3.set_xlabel('C(g)')
# labels = [interval[0],] + list(['' for i in range(len(ps)-2)]) + [interval[1],]
ax3.set_xticks(Cs[1:-1], minor=True)
ax3.set_xticks([interval[0], interval[1]])
# plt.tick_params(
# axis='x', # changes apply to the x-axis
# which='minor', # both major and minor ticks are affected
# # bottom=False, # ticks along the bottom edge are off
# # top=False, # ticks along the top edge are off
# labelbottom=False) # labels along the bottom edge are off
# plt.xticks([interval[0],interval[1]])
plt.legend(['Vanilla', 'Quarantine', 'Tracing'])
parent = os.path.dirname(path)
fig.savefig(os.path.join(parent, 'Pics', 'Cvaried_n{}_C{}_comp'.format(
n, str(interval[0]) + 'to' + str(interval[1])) + '.png'), bbox_inches='tight')
return out # Cs, unsuccessful_flags, times, peaks, period_prev
# OLD, now this is in vary_C_pi_comp_corrected
# def vary_C_comp_corrected(res, n, p, p_i, mc_iterations, max_t, interval=None, seed=0, force_recompute=False,
# path=None):
# # BROKEN! Since martin's commit?
#
# # measure effect of clustering coeff on tracing effectiveness. Here we scale according to the vanilla outcome
#
# if not interval:
# # THEORY: the average clustering coeff of erdos renyi networks is p!
# # so I test around that to see what changed
# interval = (0.5 * p, 10 * p)
#
# Cs = np.linspace(interval[0], interval[1], endpoint=True, num=res)
#
# # the following two variables save the actual values that were achieved by the heuristic.
# # In theory, these should be approximately the same in each net
# achieved_clusterings = np.zeros((3, res))
# achieved_disps = np.zeros((3, res))
#
# # vanilla
# peak_times_1 = np.ndarray(res)
# peak_heights_1 = np.ndarray(res)
# peak_heights_sd_1 = np.ndarray(res)
# period_prevalences_1 = np.ndarray(res)
# period_prevalences_sd_1 = np.ndarray(res)
# unsuccessful_flags_1 = []
# for i, C in tqdm(enumerate(Cs), total=res,desc='Vanilla'):
# net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag , achieved_clustering, achieved_disp = \
# simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i, mode='vanilla',
# force_recompute=force_recompute,
# path=path, clustering=C)
#
# assert equilib_flag, 'Sim not complete?'
#
# peak_times_1[i] = t_peak
# peak_heights_1[i] = mean_peak
# peak_heights_sd_1[i] = sd_peak
# period_prevalences_1[i] = mean_prevalence
# period_prevalences_sd_1[i] = sd_prevalence
#
# achieved_clusterings[0, i] = achieved_clustering
# achieved_disps[0, i] = achieved_disp
#
#
# # exposed = counts[EXP_STATE, :]
# # infected = counts[INF_STATE, :]
# # ep_curve = exposed + infected
# #
# # exposed_sd = sd[EXP_STATE, :]
# # infected_sd = sd[INF_STATE, :]
# # ep_curve_sd = exposed_sd + infected_sd
# #
# # # these are the point prevalence +- sd
# # upper_alpha = (ep_curve[t_peak] + ep_curve_sd[t_peak])/n
# # lower_alpha = (ep_curve[t_peak] - ep_curve_sd[t_peak])/n
# #
# # recovered = counts[REC_STATE, :]
# # recovered_sd = sd[REC_STATE, :]
# #
# #
# # upper_beta = recovered[-1]-recovered_sd/n
#
#
# # quarantine
# peak_times_2 = np.ndarray(res)
# peak_heights_2 = np.ndarray(res)
# peak_heights_sd_2 = np.ndarray(res)
# period_prevalences_2 = np.ndarray(res)
# period_prevalences_sd_2 = np.ndarray(res)
# unsuccessful_flags_2 = []
# for i, C in tqdm(enumerate(Cs), total=res,desc='Quarantine'):
# net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag , achieved_clustering, achieved_disp = \
# simple_experiment(n, p, p_i, mc_iterations, max_t, seed=seed + i + res, mode='quarantine',
# force_recompute=force_recompute,
# path=path, clustering=C)
#
# assert equilib_flag, 'Sim not complete?'
#
# peak_times_2[i] = t_peak
# peak_heights_2[i] = mean_peak / peak_heights_1[i]
# peak_heights_sd_2[i] = sd_peak
# period_prevalences_2[i] = mean_prevalence / period_prevalences_1[i]
# period_prevalences_sd_2[i] = sd_prevalence
#
# achieved_clusterings[1, i] = achieved_clustering
# achieved_disps[1, i] = achieved_disp
#
#
#
#
# # tracing
# peak_times_3 = np.ndarray(res)
# peak_heights_3 = np.ndarray(res)
# peak_heights_sd_3 = np.ndarray(res)
# period_prevalences_3 = np.ndarray(res)
# period_prevalences_sd_3 = np.ndarray(res)
# unsuccessful_flags_3 = []
# for i, C in tqdm(enumerate(Cs), total=res,desc='Tracing'):
# net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag , achieved_clustering, achieved_disp = \
# simple_experiment(n, p, p_i, 2*mc_iterations, max_t, seed=seed + i + 2 * res, mode='tracing',
# force_recompute=force_recompute,
# path=path, clustering=C)
#
# assert equilib_flag, 'Sim not complete?'
#
# peak_times_3[i] = t_peak
# peak_heights_3[i] = mean_peak / peak_heights_1[i]
# peak_heights_sd_3[i] = sd_peak
# period_prevalences_3[i] = mean_prevalence / period_prevalences_1[i]
# period_prevalences_3_sd_2[i] = sd_prevalencea
#
# achieved_clusterings[2, i] = achieved_clustering
# achieved_disps[2, i] = achieved_disp
#
# dirname_parent = os.path.dirname(__file__)
# dirname = os.path.join(dirname_parent, 'Experiments', 'Paper', 'Cache')
#
# id_params = (
# n, p, p_i, mc_iterations, max_t, interval, seed, t_i, t_c, t_r, t_d, t_t, p_q, p_t, quarantine_time, resolution,
# epsilon_clustering)
# # normal hashes are salted between runs -> use something that is persistent
# tag = str(hashlib.md5(str(id_params).encode('utf8')).hexdigest())
#
# with open(os.path.join(dirname, tag + '_metrics_corrected.p'), 'wb') as f:
# out = [Cs, unsuccessful_flags_1, peak_times_1, peak_heights_1, period_prevalences_1,
# Cs, unsuccessful_flags_2, peak_times_2, peak_heights_2, period_prevalences_2,
# Cs, unsuccessful_flags_3, peak_times_3, peak_heights_3, period_prevalences_3,
# achieved_clusterings, achieved_disps]
#
# pickle.dump(out, f)
#
# # two modes for visualization
# show_both = False
# if show_both:
# fig, axes = plt.subplots(2, 1, sharex=True, figsize=(14, 14 / 16 * 9))
#
# # fig.subplots_adjust(wspace = 0.5)
# ax2, ax3 = axes
#
# # ax1.plot(Cs, peak_times_1,Cs, peak_times_2,Cs, peak_times_3)
# # ax1.set_ylabel('Peak time')
#
# ax2.plot(Cs, peak_heights_2, 'C1')
# ax2.plot(Cs, peak_heights_3, 'C2')
# ax2.set_ylabel('Scaled peak height')
#
# ax3.plot(Cs, period_prevalences_2, 'C1')
# ax3.plot(Cs, period_prevalences_3, 'C2')
# ax3.set_ylabel('Scaled period prevalence')
# ax3.set_xlabel('C(g)')
# # labels = [interval[0],] + list(['' for i in range(len(ps)-2)]) + [interval[1],]
# ax3.set_xticks(Cs, minor=False)
# ax3.xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
#
# # ax3.set_xticks([interval[0], interval[1]])
#
# # plt.tick_params(
# # axis='x', # changes apply to the x-axis
# # which='minor', # both major and minor ticks are affected
# # # bottom=False, # ticks along the bottom edge are off
# # # top=False, # ticks along the top edge are off
# # labelbottom=False) # labels along the bottom edge are off
#
# ax_upper_axis = ax2.twiny()
#
# ax_upper_axis.set_xlim(ax3.get_xlim())
# ax_upper_axis.set_xticks(Cs)
# ax_upper_axis.set_xticklabels(["{:.3f}".format(a) for a in achieved_disps.mean(axis=0)])
# # ax_upper_axis.xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
# ax_upper_axis.set_xlabel('D(g)')
#
# # plt.xticks([interval[0],interval[1]])
# ax3.legend(['Quarantine', 'Tracing'])
#
# parent = os.path.dirname(path)
# fig.savefig(os.path.join(parent, 'Pics', 'Cvaried_n{}_C{}_comp_corrected'.format(
# n, str(interval[0]) + 'to' + str(interval[1])) + '.png'), bbox_inches='tight')
# else:
# fig, axes = plt.subplots(2, 1, sharex=True, figsize=(14, 14 / 16 * 9))
#
# # fig.subplots_adjust(wspace = 0.5)
# ax2, ax3 = axes
#
# # ax1.plot(Cs, peak_times_1,Cs, peak_times_2,Cs, peak_times_3)
# # ax1.set_ylabel('Peak time')
#
# ax2.plot(Cs, peak_heights_3, 'C2')
# ax2.set_ylabel('Scaled peak height')
#
# ax3.plot(Cs, period_prevalences_3, 'C2')
# ax3.set_ylabel('Scaled period prevalence')
# ax3.set_xlabel('C(g)')
# ax3.set_xticks(Cs, minor=False)
# ax3.xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
#
# # ax3.set_xticks(Cs[1:-1], minor=True)
# # ax3.set_xticks([interval[0], interval[1]])
# # ax3.set_xticks(Cs, minor=True)
#
# ax_upper_axis = ax2.twiny()
#
# ax_upper_axis.set_xlim(ax3.get_xlim())
# ax_upper_axis.set_xticks(Cs)
# ax_upper_axis.set_xticklabels(["{:.3f}".format(a) for a in achieved_disps.mean(axis=0)])
# # ax_upper_axis.xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
# ax_upper_axis.set_xlabel('D(g)')
#
# # plt.legend(['Quarantine', 'Tracing'])
# ax3.legend(['Tracing', ])
#
# parent = os.path.dirname(path)
# fig.savefig(os.path.join(parent, 'Pics', 'Cvaried_n{}_C{}_comp_corrected_tracing'.format(
# n, str(interval[0]) + 'to' + str(interval[1])) + '.png'), bbox_inches='tight')
#
# return out
def vary_C_pi_comp_corrected(res, n, p, p_is: tuple, mc_iterations, max_t, interval=None, seed=0, force_recompute=False,
path=None):
# measure effect of clustering coeff on tracing effectiveness. Here we scale according to the vanilla outcome
# Several values for infectvity p_i are used
Cs = np.linspace(interval[0], interval[1], endpoint=True, num=res)
n_p_i = len(p_is)
assert n_p_i <= 5, 'Less values for p_i should be selected for visibility'
# the following two variables save the actual values that were achieved by the heuristic.
# In theory, these should be approximately the same in each net
achieved_clusterings = np.zeros((3 * n_p_i, res))
achieved_disps = np.zeros((3 * n_p_i, res))
# vanilla
peak_times_1 = np.ndarray((res, n_p_i))
peak_heights_1 = np.ndarray((res, n_p_i))
peak_heights_sd_1 = np.ndarray((res, n_p_i))
period_prevalences_1 = np.ndarray((res, n_p_i))
period_prevalences_sd_1 = np.ndarray((res, n_p_i))
for i, C in tqdm(enumerate(Cs), total=res, desc='Vanilla'):
for j, p_inf in enumerate(p_is):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_inf, mc_iterations, max_t, seed=j * 156484 + seed + i, mode='vanilla',
force_recompute=force_recompute,
path=path, clustering=C)
assert equilib_flag, 'Sim not complete?'
peak_times_1[i, j] = t_peak
peak_heights_1[i, j] = mean_peak
peak_heights_sd_1[i, j] = sd_peak
period_prevalences_1[i, j] = mean_prevalence
period_prevalences_sd_1[i, j] = sd_prevalence
achieved_clusterings[j, i] = achieved_clustering
achieved_disps[j, i] = achieved_disp
# quarantine
peak_times_2 = np.ndarray((res, n_p_i))
peak_heights_2 = np.ndarray((res, n_p_i))
peak_heights_sd_2 = np.ndarray((res, n_p_i))
period_prevalences_2 = np.ndarray((res, n_p_i))
period_prevalences_sd_2 = np.ndarray((res, n_p_i))
for i, C in tqdm(enumerate(Cs), total=res, desc='Quarantine'):
for j, p_inf in enumerate(p_is):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \
simple_experiment(n, p, p_inf, mc_iterations, max_t, seed=j * 84265 + seed + i + res, mode='quarantine',
force_recompute=force_recompute,
path=path, clustering=C)
assert equilib_flag, 'Sim not complete?'
peak_times_2[i, j] = t_peak
peak_heights_2[i, j] = mean_peak
peak_heights_sd_2[i, j] = sd_peak
period_prevalences_2[i, j] = mean_prevalence
period_prevalences_sd_2[i, j] = sd_prevalence
achieved_clusterings[n_p_i + j, i] = achieved_clustering
achieved_disps[n_p_i + j, i] = achieved_disp
# tracing
peak_times_3 = np.ndarray((res, n_p_i))
peak_heights_3 = np.ndarray((res, n_p_i))
peak_heights_sd_3 = np.ndarray((res, n_p_i))
period_prevalences_3 = np.ndarray((res, n_p_i))
period_prevalences_sd_3 = np.ndarray((res, n_p_i))
for i, C in tqdm(enumerate(Cs), total=res, desc='Tracing'):
for j, p_inf in enumerate(p_is):
net, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag, achieved_clustering, achieved_disp = \