-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseir_fix01.py
175 lines (152 loc) · 6.5 KB
/
seir_fix01.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
import time, itertools, multiprocessing
from numba import jit, jitclass, int64, float64
import numpy as np
from rpy2 import robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
import pandas as pd
import warnings, random
from rpy2.rinterface import RRuntimeWarning
warnings.filterwarnings("ignore", category=RRuntimeWarning)
import rpy2.robjects as ro
from rpy2.robjects.conversion import localconverter
r_source = robjects.r['source']
r_assign = robjects.r['assign']
r_options = robjects.r['options']
r_options(warn=-1)
#from rpy2.rinterface_lib.callbacks import logger as rpy2_logger
import logging, scipy
rpy2_logger = logging.getLogger()
#rom COVIDScenarioPipeline.SEIR import setup
import setup_fix01 as setup
rpy2_logger.setLevel(logging.ERROR)
import uuid
"""
setup.parameters_quick_draw
"""
ncomp = 7
S, E, I1, I2, I3, R, cumI = np.arange(ncomp)
def onerun_SEIR(s, uid):
"""
main function for simulating
"""
scipy.random.seed()
#p = setup.COVID19Parameters(s)
r_assign('ti_str', str(s.ti))
r_assign('tf_str', str(s.tf))
r_assign('foldername', s.spatset.folder)
r_source(s.script_npi)
npi = robjects.r['NPI'].T
#p.addNPIfromR(npi)
importation = pd.read_csv('data/utah/UT_COVID19_Data_03202020.csv')
importation.drop('County', axis = 1,inplace=True)
importation = importation.pivot(index='Date', columns='GEOID', values='New Cases')
importation = importation.fillna(value = 0)
importation.columns = pd.to_numeric(importation.columns)
for col in s.spatset.data['geoid']:
if col not in importation.columns:
importation[col] = 0
importation = importation.reindex(sorted(importation.columns), axis=1)
idx = pd.date_range(s.ti, s.tf)
importation.index = pd.to_datetime(importation.index)
importation = importation.reindex(idx, fill_value=0)
importation = importation.to_numpy()
y0 = np.zeros((ncomp, s.nnodes))
y0[S,:] = s.popnodes
states = steps_SEIR_nb(setup.parameters_quick_draw(s, npi),
y0,
uid,
s.dt,
s.t_inter,
s.nnodes,
s.popnodes,
s.mobility,
s.dynfilter,
importation)
# Tidyup data for R, to save it:
if s.write_csv:
a = states.copy()[:,:,::int(1/s.dt)]
a = np.moveaxis(a, 1, 2)
a = np.moveaxis(a, 0, 1)
b = np.diff(a,axis = 0)
difI=np.zeros((s.t_span+1, s.nnodes))
difI[1:,:] = b[:,cumI,:]
na = np.zeros((s.t_span+1, ncomp+1, s.nnodes))
na[:,:-1,:] = a
na[:,-1,:] = difI
m,n,r = na.shape
out_arr = np.column_stack((np.tile(np.arange(n),m), na.reshape(n*m,-1)))
out_df = pd.DataFrame(out_arr, columns = ['comp'] + list(s.spatset.data['geoid'].astype(int)),
index = pd.date_range(s.ti, s.tf, freq='D').repeat(ncomp+1))
out_df['comp'].replace(S, 'S', inplace=True)
out_df['comp'].replace(E, 'E', inplace=True)
out_df['comp'].replace(I1, 'I1', inplace=True)
out_df['comp'].replace(I2, 'I2', inplace=True)
out_df['comp'].replace(I3, 'I3', inplace=True)
out_df['comp'].replace(R, 'R', inplace=True)
out_df['comp'].replace(cumI, 'cumI', inplace=True)
out_df['comp'].replace(ncomp, 'diffI', inplace=True)
str(uuid.uuid4())[:2]
ofp = f"{s.datadir}{s.timestamp}_{s.setup_name}_{str(uuid.uuid4())}.csv"
out_df.to_csv(ofp, index='time', index_label='time')
print(' saving %i entries to %s'%(len(out_df), ofp))
return 1
def run_parallel(s, processes=multiprocessing.cpu_count()): # set to 16 when running on server
tic = time.time()
uids = np.arange(s.nsim)
with multiprocessing.Pool(processes=processes) as pool:
result = pool.starmap(onerun_SEIR, zip(itertools.repeat(s),
#itertools.repeat(p),
uids))
print(f">>> {s.nsim} Simulations done in {time.time()-tic} seconds...")
return result
#@jit(float64[:,:,:](float64[:,:], float64[:], int64), nopython=True)
@jit(nopython=True)
def steps_SEIR_nb(p_vec, y0, uid, dt, t_inter, nnodes, popnodes,
mobility, dynfilter, importation):
"""
Made to run just-in-time-compiled by numba, hence very descriptive and using loop,
because loops are expanded by the compiler hence not a problem.
as there is very few authorized function. Needs the nopython option to be fast.
"""
#np.random.seed(uid)
t = 0
y = np.copy(y0)
states = np.zeros((ncomp, nnodes, len(t_inter)))
mv = np.empty(ncomp-1)
exposeCases = np.empty(nnodes)
incidentCases = np.empty(nnodes)
incident2Cases = np.empty(nnodes)
incident3Cases = np.empty(nnodes)
recoveredCases = np.empty(nnodes)
p_infect = 1 - np.exp(-dt*p_vec[1][0][0])
p_recover = 1 - np.exp(-dt*p_vec[2][0][0])
for it, t in enumerate(t_inter):
if (it%int(1/dt)==0):
y[E] = y[E] + importation[int(t)]
for ori in range(nnodes):
for dest in range(nnodes):
for c in range(ncomp-1):
mv[c] = np.random.binomial(y[c,ori], 1 - np.exp(-dt*mobility[ori, dest]/popnodes[ori]))
y[:-1,dest] += mv
y[:-1,ori] -= mv
p_expose = 1 - np.exp(-dt*p_vec[0][it]*(y[I1]+y[I2]+y[I3])/popnodes) # vector
for i in range(nnodes):
exposeCases[i] = np.random.binomial(y[S][i], p_expose[i])
incidentCases[i] = np.random.binomial(y[E][i], p_infect)
incident2Cases[i] = np.random.binomial(y[I1][i], p_recover)
incident3Cases[i] = np.random.binomial(y[I2][i], p_recover)
recoveredCases[i] = np.random.binomial(y[I3][i], p_recover)
y[S] += -exposeCases
y[E] += exposeCases - incidentCases
y[I1] += incidentCases - incident2Cases
y[I2] += incident2Cases - incident3Cases
y[I3] += incident3Cases - recoveredCases
y[R] += recoveredCases
y[cumI] += incidentCases
states[:,:,it] = y
if (it%int(1/dt)==0):
y[cumI] += importation[int(t)]
#if (it%(1/dt) == 0 and (y[cumI] <= dynfilter[int(it%(1/dt))]).any()):
# return -np.ones((ncomp, nnodes, len(t_inter)))
return states