-
Notifications
You must be signed in to change notification settings - Fork 17
/
patchsim.py
902 lines (762 loc) · 27.5 KB
/
patchsim.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
"""PatchSim: A system for doing metapopulation SEIR* models."""
import time
import os
import logging
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
## Check if we should use CuPy or NumPy
USE_CUPY = os.getenv("PATCHSIM_USE_GPU", "False").lower()
if USE_CUPY in ("false", "f", "0", "no", "n"):
USE_CUPY = False
elif USE_CUPY in ("true", "t", "1", "yes", "y"):
USE_CUPY = True
else:
logger.warning(f"Invalid value `{USE_CUPY}` for PATCHSIM_USE_GPU. Not using GPU")
USE_CUPY = False
# Use numpy as default
cx = np
if USE_CUPY:
try:
import cupy
except ImportError:
logger.exception("Unable to import CuPy. Not using GPU")
USE_CUPY = False
else:
# Use cupy
logger.info("Using CuPy. %s", cupy.__version__)
cx = cupy
else:
logger.info("Using NumPy")
def read_config(config_file):
"""Read configuration.
Configuration files contain one key=value pair per line.
The following is an example of the contents of a config file::
PatchFile=test_pop.txt
NetworkFile=test_net.txt
NetworkType=Static
ExposureRate=0.65
InfectionRate=0.67
RecoveryRate=0.4
ScalingFactor=1
SeedFile=test_seed.txt
VaxFile=test_vax.txt
VaxDelay=4
VaxEfficacy=0.5
StartDate=1
Duration=30
LoadState=False
SaveState=True
SaveFile=checkpoint1.npy
OutputFile=test1.out
OutputFormat=Whole
LogFile=test1.log
Parameters
----------
config_file : str
Path to the configuration file.
Returns
-------
dict (str -> str)
The configuration key value pairs.
"""
config_df = pd.read_csv(config_file, delimiter="=", names=["key", "val"])
configs = dict(zip(config_df.key, config_df.val))
configs.setdefault("Model", "Mobility")
return configs
def load_patch(configs):
"""Load the patch file.
A patch file contains the population size of a patch.
The file has two space separated columns.
Following is an example of a patch file::
A 10000
B 10000
C 10000
Parameters
----------
configs : dict
The configuration dictionary.
Must contain the "PatchFile" pointing to location of patch file.
Returns
-------
DataFrame (names=(id, pops), dtypes=(str, float))
A dataframe containing populations of patches.
"""
patch_df = pd.read_csv(
configs["PatchFile"],
names=["id", "pops"],
delimiter=" ",
dtype={"id": str, "pops": float},
)
patch_df.sort_values("id", inplace=True)
logger.info("Loaded patch attributes")
return patch_df
def load_param_file(configs):
"""Load the parameter file.
A parameter file contains one row per patch.
Each row must have two or more columns.
Following is an example of a paremter file::
B 0 0 0.54 0.54 0.54 0.54 0 0 0 0
A 0.72
Parameters
----------
configs : dict
The configuration dictionary.
Must contain the "ParamFile" pointing to location of parameter file.
patch_df : DataFrame
A dataframe containing populations of patches.
Returns
-------
DataFrame
A dataframe with one column per patch.
The column names are IDs of the patches.
Each column contains the "beta" value of the patch over time.
"""
param_df = pd.read_csv(
configs["ParamFile"], delimiter=" ", dtype={0: str}, header=None
)
param_df = param_df.set_index(0)
param_df = param_df.fillna(method="ffill", axis=1)
param_df = param_df.T
return param_df
def load_params(configs, patch_df):
"""Load the simulation parameters.
Parameters
----------
configs : dict
The configuration key value pairs.
patch_df : DataFrame
A dataframe containing populations of patches.
Returns
-------
dict (str -> float or ndarray)
A dictionary of model parameters.
The "beta" parameter is a ndarray
with shape=(NumPatches x NumTimesteps)
and dtype=float.
"""
params = {}
params["T"] = int(configs["Duration"])
beta = float(configs.get("ExposureRate", 0.0))
params["beta"] = np.full((len(patch_df), params["T"]), beta)
params["alpha"] = float(configs.get("InfectionRate", 0.0))
params["gamma"] = float(configs.get("RecoveryRate", 0.0))
logger.info(
"Parameter: alpha=%e, beta=%e, gamma=%e", params["alpha"], beta, params["gamma"]
)
if "ParamFile" in configs:
param_df = load_param_file(configs)
for i, id_ in enumerate(patch_df["id"]):
if id_ in param_df.columns:
xs = param_df[id_]
params["beta"][i, 0 : len(xs)] = xs
logger.info("Loaded disease parameters from ParamFile")
else:
logger.info("No ParamFile loaded")
### Optional parameters
params["scaling"] = float(configs.get("ScalingFactor", 1.0))
params["vaxeff"] = float(configs.get("VaxEfficacy", 1.0))
params["delta"] = float(configs.get("WaningRate", 0.0))
params["vaxdelta"] = float(configs.get("VaxWaningRate", 0.0))
params["kappa"] = float(configs.get("AsymptomaticReduction", 1.0))
params["symprob"] = float(configs.get("SymptomaticProbability", 1.0))
params["epsilon"] = float(configs.get("PresymptomaticReduction", 1.0))
# if params["delta"]:
# logger.info("Found WaningRate. Running SEIRS model.")
return params
def load_seed(configs, params, patch_df):
"""Load the disease seeding schedule file.
A seed file contains the disease seeding schedule.
Following is an example of the contents of a seed file::
0 A 20
0 B 20
1 C 20
2 C 30
Parameters
----------
configs : dict
The configuration dictionary.
params: dict (str -> float or ndarray)
A dictionary of model parameters.
patch_df : DataFrame
A dataframe containing populations of patches.
Returns
-------
ndarray shape=(NumTimsteps x NumPatches)
A seeding schedule matrix
"""
if "SeedFile" not in configs:
logger.info("Continuing without seeding")
return np.zeros((params["T"], len(patch_df)))
seed_df = pd.read_csv(
configs["SeedFile"],
delimiter=" ",
names=["Day", "Id", "Count"],
dtype={"Id": str},
)
seed_mat = np.zeros((params["T"], len(patch_df)))
seed_df = seed_df[
seed_df.Day < params["T"]
] ### Skipping seeds after end of simulation
patch_idx = {id_: i for i, id_ in enumerate(patch_df["id"])}
for day, id_, count in seed_df.itertuples(index=False, name=None):
idx = patch_idx[id_]
seed_mat[day, idx] = count
logger.info("Loaded seeding schedule")
return seed_mat
def load_vax(configs, params, patch_df):
"""Load the vaccination schedule file.
A vax file contains the vaccination schedule.
Following is an example of the contents of the vax file::
0 A 10
2 B 10
5 C 10
Parameters
----------
configs : dict
The configuration dictionary.
params: dict (str -> float or ndarray)
A dictionary of model parameters.
patch_df : DataFrame
A dataframe containing populations of patches.
Returns
-------
ndarray shape=(NumTimsteps x NumPatches)
A vaccination schedule matrix (NumTimsteps x NumPatches)
"""
vax_mat = np.zeros((params["T"], len(patch_df)), dtype=int)
if "VaxFile" not in configs:
return vax_mat
vax_df = pd.read_csv(
configs["VaxFile"],
delimiter=" ",
names=["Day", "Id", "Count"],
dtype={"Id": str, "Count": int},
)
vax_delay = int(configs.get("VaxDelay", 0))
vax_df = vax_df[
vax_df.Day < params["T"] - vax_delay
] ### Skipping vaxs which get applied after end of simulation
patch_idx = {id_: i for i, id_ in enumerate(patch_df["id"])}
for day, id_, count in vax_df.itertuples(index=False, name=None):
idx = patch_idx[id_]
day = day + vax_delay
vax_mat[day, idx] = count
return vax_mat
def load_Theta(configs, patch_df):
"""Load the patch connectivity network.
This function loads the dynamic network connectity file.
The following is an example of the network connectity file::
A A 0 1
B B 0 1
C C 0 1
Parameters
----------
configs : dict
The configuration dictionary.
Must contain keys "NetworkFile" and "NetworkType".
patch_df : DataFrame
A dataframe containing populations of patches.
Returns
-------
ndarray shape=(NumThetaIndices x NumPatches x NumPatches)
The dynamic patch connectivity network
"""
theta_df = pd.read_csv(
configs["NetworkFile"],
names=["src_Id", "dest_Id", "theta_index", "flow"],
delimiter=" ",
dtype={"src_Id": str, "dest_Id": str},
)
if configs["NetworkType"] == "Static":
if not np.all(theta_df.theta_index == 0):
raise ValueError("Theta indices mismatch. Ensure NetworkType=Static.")
elif configs["NetworkType"] == "Weekly":
if not list(sorted(set(theta_df.theta_index))) == list(range(53)):
raise ValueError("Theta indices mismatch. Ensure NetworkType=Weekly.")
elif configs["NetworkType"] == "Monthly":
if not list(sorted(set(theta_df.theta_index))) == list(range(12)):
raise ValueError("Theta indices mismatch. Ensure NetworkType=Monthly.")
else:
raise ValueError("Unknown NetworkType=%s" % configs["NetworkType"])
Theta_indices = theta_df.theta_index.unique()
Theta = np.zeros((len(Theta_indices), len(patch_df), len(patch_df)))
patch_idx = {id_: i for i, id_ in enumerate(patch_df["id"])}
for src_Id, dest_Id, theta_index, flow in theta_df.itertuples(
index=False, name=None
):
try:
src_Idx = patch_idx[src_Id]
dest_Idx = patch_idx[dest_Id]
Theta[theta_index, src_Idx, dest_Idx] = flow
except KeyError:
logger.warning(
"Ignoring flow entries for missing patches. Ensure all patches listed in PatchFile."
)
logger.info("Loaded temporal travel matrix")
return Theta
def do_patchsim_stoch_mobility_step(
State_Array, N, params, beta, theta, seeds, vaxs, t
):
"""Do step of the stochastic (mobility) simulation."""
# FIXME: This method doesn't work at all
# as populate new_inf
# which is what gets written out.
S, E, I, R, V, new_inf = State_Array ## Aliases for the State Array
## seeding for day t (seeding implies S->I)
actual_seed = cx.minimum(seeds[t], S[t])
S[t] = S[t] - actual_seed
I[t] = I[t] + actual_seed
## vaccination for day t
max_SV = cx.minimum(vaxs[t], S[t])
actual_SV = cx.random.binomial(max_SV.astype(int), params["vaxeff"])
S[t] = S[t] - actual_SV
V[t] = V[t] + actual_SV
# Effective population after movement step
N_eff = theta.T @ N
I_eff = theta.T @ I[t]
E_eff = theta.T @ E[t]
# Force of infection from symp/asymptomatic individuals
beta_j_eff = I_eff
beta_j_eff = beta_j_eff / N_eff
beta_j_eff = beta_j_eff * beta[:, t]
beta_j_eff = beta_j_eff * (
(1 - params["kappa"]) * (1 - params["symprob"]) + params["symprob"]
)
beta_j_eff = cx.nan_to_num(beta_j_eff)
# Force of infection from presymptomatic individuals
E_beta_j_eff = E_eff
E_beta_j_eff = E_beta_j_eff / N_eff
E_beta_j_eff = E_beta_j_eff * beta[:, t]
E_beta_j_eff = E_beta_j_eff * (1 - params["epsilon"])
E_beta_j_eff = cx.nan_to_num(E_beta_j_eff)
# Infection force
inf_force = theta.dot(beta_j_eff + E_beta_j_eff)
# New exposures during day t
actual_SE = cx.random.binomial(S[t], inf_force)
actual_EI = cx.random.binomial(E[t], params["alpha"])
actual_IR = cx.random.binomial(I[t], params["gamma"])
actual_RS = cx.random.binomial(R[t], params["delta"])
actual_VS = cx.random.binomial(V[t], params["vaxdelta"])
# Update to include presymptomatic and asymptomatic terms
S[t + 1] = S[t] - actual_SE + actual_RS + actual_VS
E[t + 1] = E[t] + actual_SE - actual_EI
I[t + 1] = I[t] + actual_EI - actual_IR
R[t + 1] = R[t] + actual_IR - actual_RS
V[t + 1] = V[t] - actual_VS
new_inf[t] = actual_SE
## Earlier computation of force of infection included network sampling.
## Now only implementing only disease progression stochasticity
# N = patch_df.pops.values
# S_edge = np.concatenate(
# [
# np.random.multinomial(
# S[t][x], theta[x] / (theta[x].sum() + 10 ** -12)
# ).reshape(1, len(N))
# for x in range(len(N))
# ],
# axis=0,
# )
# E_edge = np.concatenate(
# [
# np.random.multinomial(
# E[t][x], theta[x] / (theta[x].sum() + 10 ** -12)
# ).reshape(1, len(N))
# for x in range(len(N))
# ],
# axis=0,
# )
# I_edge = np.concatenate(
# [
# np.random.multinomial(
# I[t][x], theta[x] / (theta[x].sum() + 10 ** -12)
# ).reshape(1, len(N))
# for x in range(len(N))
# ],
# axis=0,
# )
# R_edge = np.concatenate(
# [
# np.random.multinomial(
# R[t][x], theta[x] / (theta[x].sum() + 10 ** -12)
# ).reshape(1, len(N))
# for x in range(len(N))
# ],
# axis=0,
# )
# V_edge = np.concatenate(
# [
# np.random.multinomial(
# V[t][x], theta[x] / (theta[x].sum() + 10 ** -12)
# ).reshape(1, len(N))
# for x in range(len(N))
# ],
# axis=0,
# )
# N_edge = S_edge + E_edge + I_edge + R_edge + V_edge
# N_eff = N_edge.sum(axis=0)
# I_eff = I_edge.sum(axis=0)
# beta_j_eff = np.nan_to_num(params["beta"][:, t] * (I_eff / N_eff))
# actual_SE = np.concatenate(
# [
# np.random.binomial(S_edge[:, x], beta_j_eff[x]).reshape(len(N), 1)
# for x in range(len(N))
# ],
# axis=1,
# ).sum(axis=1)
# actual_EI = np.random.binomial(E[t], params["alpha"])
# actual_IR = np.random.binomial(I[t], params["gamma"])
# actual_RS = np.random.binomial(R[t], params["delta"])
# ### Update to include presymptomatic and asymptomatic terms
# S[t + 1] = S[t] - actual_SE + actual_RS
# E[t + 1] = E[t] + actual_SE - actual_EI
# I[t + 1] = I[t] + actual_EI - actual_IR
# R[t + 1] = R[t] + actual_IR - actual_RS
# V[t + 1] = V[t]
def do_patchsim_det_mobility_step(State_Array, N, params, beta, theta, seeds, vaxs, t):
"""Do step of the deterministic simulation."""
S, E, I, R, V, new_inf = State_Array ## Aliases for the State Array
# seeding for day t (seeding implies S->I)
actual_seed = cx.minimum(seeds[t], S[t])
S[t] = S[t] - actual_seed
I[t] = I[t] + actual_seed
# vaccination for day t
actual_vax = cx.minimum(vaxs[t] * params["vaxeff"], S[t])
S[t] = S[t] - actual_vax
V[t] = V[t] + actual_vax
# Effective population after movement step
N_eff = theta.T @ N
I_eff = theta.T @ I[t]
E_eff = theta.T @ E[t]
# Force of infection from symp/asymptomatic individuals
beta_j_eff = I_eff
beta_j_eff = beta_j_eff / N_eff
beta_j_eff = beta_j_eff * beta[:, t]
beta_j_eff = beta_j_eff * (
(1 - params["kappa"]) * (1 - params["symprob"]) + params["symprob"]
)
beta_j_eff = cx.nan_to_num(beta_j_eff)
# Force of infection from presymptomatic individuals
E_beta_j_eff = E_eff
E_beta_j_eff = E_beta_j_eff / N_eff
E_beta_j_eff = E_beta_j_eff * beta[:, t]
E_beta_j_eff = E_beta_j_eff * (1 - params["epsilon"])
E_beta_j_eff = cx.nan_to_num(E_beta_j_eff)
# Infection force
beta_sum_eff = beta_j_eff + E_beta_j_eff
inf_force = theta @ beta_sum_eff
# New exposures during day t
new_inf[t] = inf_force * S[t]
new_inf[t] = cx.minimum(new_inf[t], S[t])
# Update to include presymptomatic and asymptomatic terms
S[t + 1] = S[t] - new_inf[t] + params["delta"] * R[t] + params["vaxdelta"] * V[t]
E[t + 1] = new_inf[t] + (1 - params["alpha"]) * E[t]
I[t + 1] = params["alpha"] * E[t] + (1 - params["gamma"]) * I[t]
R[t + 1] = params["gamma"] * I[t] + (1 - params["delta"]) * R[t]
V[t + 1] = (1 - params["vaxdelta"]) * V[t]
def do_patchsim_det_force_step(State_Array, N, params, beta, theta, seeds, vaxs, t):
"""Do step of the deterministic simulation."""
S, E, I, R, V, new_inf = State_Array ## Aliases for the State Array
# seeding for day t (seeding implies S->I)
actual_seed = cx.minimum(seeds[t], S[t])
S[t] = S[t] - actual_seed
I[t] = I[t] + actual_seed
# vaccination for day t
actual_vax = cx.minimum(vaxs[t] * params["vaxeff"], S[t])
S[t] = S[t] - actual_vax
V[t] = V[t] + actual_vax
# Effective beta
beta_j_eff = I[t]
beta_j_eff = beta_j_eff / N
beta_j_eff = beta_j_eff * beta[:, t]
beta_j_eff = cx.nan_to_num(beta_j_eff)
# Infection force
inf_force = theta.T @ beta_j_eff
# New exposures during day t
new_inf[t] = inf_force * S[t]
new_inf[t] = cx.minimum(new_inf[t], S[t])
# Update to include presymptomatic and asymptomatic terms
S[t + 1] = S[t] - new_inf[t] + params["delta"] * R[t] + params["vaxdelta"] * V[t]
E[t + 1] = new_inf[t] + (1 - params["alpha"]) * E[t]
I[t + 1] = params["alpha"] * E[t] + (1 - params["gamma"]) * I[t]
R[t + 1] = params["gamma"] * I[t] + (1 - params["delta"]) * R[t]
V[t + 1] = (1 - params["vaxdelta"]) * V[t]
def patchsim_step(State_Array, N, configs, params, beta, theta, seeds, vaxs, t, stoch):
"""Do step of the simulation."""
if stoch:
if configs["Model"] == "Mobility":
return do_patchsim_stoch_mobility_step(
State_Array, N, params, beta, theta, seeds, vaxs, t
)
else:
raise ValueError(
"Unknown Model %s for stochastic simulation" % configs["Model"]
)
else:
if configs["Model"] == "Mobility":
return do_patchsim_det_mobility_step(
State_Array, N, params, beta, theta, seeds, vaxs, t
)
elif configs["Model"] == "Force":
return do_patchsim_det_force_step(
State_Array, N, params, beta, theta, seeds, vaxs, t
)
else:
raise ValueError(
"Unknown Model %s for deterministic simulation" % configs["Model"]
)
def epicurves_todf(configs, params, patch_df, State_Array):
"""Convert the epicurve (new infection over time) into a dataframe.
Parameters
----------
configs : dict
The configuration dictionary.
params : dict
A dictionary of model parameters.
patch_df : dict
A dataframe containing populations of patches.
State_Array : 5 tuple
A tuple of disease state information.
Returns
-------
DataFrame
A dataframe containing the new infections.
There is one row per patch.
There is one column per timestep.
"""
new_inf = State_Array[-1]
data = new_inf[:-1, :].T
data = data * float(params["scaling"])
if configs["OutputFormat"] == "Whole":
data = data.round().astype(int)
index = patch_df.id
columns = np.arange(int(configs["Duration"]))
if USE_CUPY:
# We have cupy array, need to copy to cpu
data = data.get()
out_df = pd.DataFrame(index=index, columns=columns, data=data)
return out_df
def write_epicurves(configs, params, patch_df, State_Array, write_epi, return_epi):
"""Write the epicurve into the output file.
Parameters
----------
configs : dict
The configuration dictionary.
params : dict
A dictionary of model parameters.
patch_df : dict
A dataframe containing populations of patches.
State_Array : 5 tuple
A tuple of disease state information.
write_epi : bool
If true write the epicurve to configs[OutputFile]
return_epi : bool
If true return the whole epicurve dataframe.
Otherwise return the total number of people infected.
Returns
-------
number or DataFrame
If return_epi is true return the whole epicurve dataframe.
Otherwise return the total number of people infected.
"""
out_df = epicurves_todf(configs, params, patch_df, State_Array)
if write_epi:
out_df.to_csv(configs["OutputFile"], header=None, sep=" ")
if return_epi:
return out_df
else:
return out_df.sum().sum()
def dummy_intervene_step(
configs, patch_df, params, Theta, seeds, vaxs, t, State_Array=None
):
"""Run a dummy intervention step.
configs : dict
The configuration dictionary.
patch_df : dict
A dataframe containing populations of patches.
params : dict
A dictionary of model parameters.
Theta : ndarray shape=(NumThetaIndices x NumPatches x NumPatches)
The dynamic patch connectivity network
seeds : ndarray shape=(NumTimsteps x NumPatches)
A seeding schedule matrix
vaxs : ndarray shape=(NumTimsteps x NumPatches)
A vaccination schedule matrix (NumTimsteps x NumPatches)
t : int
The timestep that was just finished.
"""
def run_disease_simulation(
configs,
patch_df=None,
params=None,
Theta=None,
seeds=None,
vaxs=None,
return_epi=False,
write_epi=False,
log_to_file=True,
intervene_step=None,
):
"""Run the disease simulation.
Parameters
----------
configs : dict
The configuration dictionary.
patch_df : dict, optional
A dataframe containing populations of patches.
params : dict, optional
A dictionary of model parameters.
Theta : ndarray shape=(NumThetaIndices x NumPatches x NumPatches), optional
The dynamic patch connectivity network
seeds : ndarray shape=(NumTimsteps x NumPatches), optional
A seeding schedule matrix
vaxs : ndarray shape=(NumTimsteps x NumPatches), optional
A vaccination schedule matrix (NumTimsteps x NumPatches)
write_epi : bool
If true write the epicurve to configs[OutputFile]
return_epi : bool
If true return the whole epicurve dataframe.
Otherwise return the total number of people infected.
log_to_file : bool
If true register a new logging handler to configs[LogFile]
Also removes any other file handler previously registered.
intervene_step : function, optional
If intervene_step step is not None,
it is called after every step.
It is expected to have the same signature as dummy_intervene_step.
Returns
-------
DataFrame
A dataframe containing the new infections.
There is one row per patch.
There is one column per timestep.
"""
if log_to_file:
handler = logging.FileHandler(configs["LogFile"], mode="a")
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
handler.setFormatter(formatter)
# remove the existing file handlers
for hdlr in logger.handlers[:]:
if isinstance(hdlr, logging.FileHandler):
logger.removeHandler(hdlr)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info("Starting PatchSim")
start = time.time()
logger.info("Operating PatchSim under %s Model", configs["Model"])
if patch_df is None:
patch_df = load_patch(configs)
if params is None:
params = load_params(configs, patch_df)
if Theta is None:
Theta = load_Theta(configs, patch_df)
if seeds is None:
seeds = load_seed(configs, params, patch_df)
if vaxs is None:
vaxs = load_vax(configs, params, patch_df)
logger.info("Initializing simulation run...")
if "RandomSeed" in configs:
np.random.seed(int(configs["RandomSeed"]))
stoch = True
logger.info("Found RandomSeed. Running in stochastic mode...")
else:
stoch = False
logger.info("No RandomSeed found. Running in deterministic mode...")
# Number of states (SEIRV) + One for tracking new infections
dim = 5 + 1
shape = (dim, params["T"] + 1, len(patch_df))
if stoch:
State_Array = np.zeros(shape, dtype=int)
else:
State_Array = np.zeros(shape, dtype=float)
if configs["LoadState"] == "True":
# Load all
State_Array[:, 0, :] = np.load(configs["LoadFile"])
else:
# Load only the Succeptiables
State_Array[0, :, :] = patch_df.pops.to_numpy()
N = patch_df.pops.to_numpy().astype(np.float32)
beta = params["beta"]
if USE_CUPY:
State_Array = cupy.asarray(State_Array)
N = cupy.asarray(N)
beta = cupy.asarray(beta)
seeds = cupy.asarray(seeds)
vaxs = cupy.asarray(vaxs)
Theta = cupy.asarray(Theta)
if configs["NetworkType"] == "Static":
for t in range(params["T"]):
patchsim_step(
State_Array,
N,
configs,
params,
beta,
Theta[0],
seeds,
vaxs,
t,
stoch,
)
if intervene_step is not None:
intervene_step(
configs, patch_df, params, Theta, seeds, vaxs, t, State_Array
)
elif configs["NetworkType"] == "Weekly":
ref_date = datetime.strptime("Jan 1 2017", "%b %d %Y") # is a Sunday
for t in range(params["T"]):
curr_date = ref_date + timedelta(days=t + int(configs["StartDate"]))
curr_week = int(curr_date.strftime("%U"))
patchsim_step(
State_Array,
N,
configs,
params,
beta,
Theta[curr_week - 1],
seeds,
vaxs,
t,
stoch,
)
if intervene_step is not None:
intervene_step(
configs, patch_df, params, Theta, seeds, vaxs, t, State_Array
)
elif configs["NetworkType"] == "Monthly":
ref_date = datetime.strptime("Jan 1 2017", "%b %d %Y") # is a Sunday
for t in range(params["T"]):
curr_date = ref_date + timedelta(days=t + int(configs["StartDate"]))
curr_month = int(curr_date.strftime("%m"))
patchsim_step(
State_Array,
N,
configs,
params,
beta,
Theta[curr_month - 1],
seeds,
vaxs,
t,
stoch,
)
if intervene_step is not None:
intervene_step(
configs, patch_df, params, Theta, seeds, vaxs, t, State_Array
)
else:
raise ValueError("Unknown NetworkType=%s" % configs["NetworkType"])
if configs["SaveState"] == "True":
logger.info("Saving StateArray to File")
np.save(configs["SaveFile"], State_Array[:, -1, :])
elapsed = time.time() - start
logger.info("Simulation complete. Time elapsed: %s seconds.", elapsed)
if not write_epi and not return_epi:
return 0
else:
return write_epicurves(
configs, params, patch_df, State_Array, write_epi, return_epi
)