forked from ArtPoon/kamphir
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrcolgem.py
More file actions
384 lines (310 loc) · 16.9 KB
/
rcolgem.py
File metadata and controls
384 lines (310 loc) · 16.9 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
import sys
from rpy2.rinterface import set_readconsole
set_readconsole(None)
import rpy2.robjects as robjects # R is instantiated upon load module
class Rcolgem ():
def __init__ (self, ncores, nreps, t0=0, fgy_resolution=500., integration_method='rk4'):
# load Rcolgem package
robjects.r("require(rcolgem, quietly=TRUE)")
# default settings
robjects.r('n.cores=%d; nreps=%d; fgyResolution=%d; integrationMethod="%s"; t0=%f' % (
ncores, nreps, fgy_resolution, integration_method, t0))
# set up parallelization environment
robjects.r("require(parallel, quietly=TRUE)")
robjects.r("cl <- makeCluster(%d, 'FORK')" % (ncores,))
def init_SI_model (self):
"""
Defines a susceptible-infected-recovered model in rcolgem.
:return:
"""
# define ODE system - as strings, these will be evaluated with new parameters
robjects.r('demes <- c("I")')
robjects.r('births <- rbind(c("parms$beta*S*I / (S+I)"))')
robjects.r('rownames(births) <- colnames(births) <- demes')
robjects.r('migrations <- rbind(c("0"))')
robjects.r('rownames(migrations)=colnames(migrations) <- demes')
robjects.r("deaths <- c('(parms$mu+parms$gamma)*I')")
robjects.r('names(deaths) <- demes')
robjects.r("nonDemeDynamics <- paste(sep='', '-parms$mu*S + parms$lambd*S + "
"(parms$mu+parms$gamma)*I', '-S*(parms$beta*I) / (S+I)')")
robjects.r("names(nonDemeDynamics) <- 'S'")
def simulate_SI_trees (self, params, tree_height, tip_heights, post=False):
"""
Simulate coalescent trees under the SI model.
:param tip_heights:
:return: List of trees; if post=True, then a tuple of ([trees], tfgy)
"""
# set parameters
robjects.r('N=%f; beta=%f; gamma=%f' % (params['N'], params['beta'], params['gamma']))
robjects.r('mu=%f; lambd=%f' % (params['mu'], params.get('lambd', params['mu'])))
robjects.r('S = N-1')
robjects.r('I = 1')
robjects.r('x0 <- c(I=I, S=S)')
robjects.r('parms <- list(beta=beta, gamma=gamma, mu=mu, lambd=lambd)')
robjects.r("n.tips <- %d" % len(tip_heights))
robjects.r("tip.heights <- c(%s)" % ','.join(map(str, tip_heights)))
robjects.r("t_end <- %f" % (tree_height,))
robjects.r("sampleTimes <- t_end - tip.heights")
robjects.r("sampleStates <- matrix(1, nrow=n.tips, ncol=length(demes))")
robjects.r("colnames(sampleStates) <- demes")
robjects.r("rownames(sampleStates) <- 1:n.tips")
robjects.r("m <- nrow(births)")
robjects.r("maxSampleTime <- max(sampleTimes)")
# solve ODE
robjects.r("tfgy <- make.fgy( t0, maxSampleTime, births, deaths, nonDemeDynamics, x0, migrations=migrations, "
"parms=parms, fgyResolution = fgyResolution, integrationMethod = integrationMethod)")
n_inf = robjects.r("tfgy[[4]][[1]]")[0]
if n_inf < len(tip_heights):
# number of infected at end of simulation is less than number of tips
return []
# simulate trees
try:
robjects.r("trees <- simulate.binary.dated.tree.fgy( tfgy[[1]], tfgy[[2]], tfgy[[3]], tfgy[[4]], "
"sampleTimes, sampleStates, integrationMethod = integrationMethod, "
"n.reps=nreps, cluster=cl)")
except:
return []
robjects.r("'multiPhylo' -> class(trees)")
try:
retval = robjects.r("lapply(trees, write.tree)")
except:
return []
trees = map(lambda x: str(x).split()[-1].strip('" '), retval)
if post:
return (trees, robjects.r("tfgy[[5]]"))
else:
return trees
def simulate_SI2_trees(self, params, tree_height, tip_heights, post=False):
"""
Simulate coalescent trees under a two-phase SI model.
:param params:
:param tip_heights:
:return:
"""
# set parameters
robjects.r('N=%f; beta1=%f; beta2=%f' % (params['N'], params['beta1'], params['beta2']))
robjects.r('gamma=%f; mu=%f; lambd=%f' % (params['gamma'], params['mu'], params.get('lambd', params['mu'])))
robjects.r('t_end=%f; t_break=%f' % (tree_height, params['t_break']))
# adjust fgyResolution for t_break
robjects.r("times <- seq(t0, t_end, length.out=fgyResolution)")
robjects.r("fgyRes.1 <- round(fgyResolution * t_break)")
robjects.r("fgyRes.2 <- fgyResolution - fgyRes.1")
# if break is too close to either limit, return single ODE solution
tp1, tp2 = robjects.r("c(fgyRes.1, fgyRes.2)")
if tp1 < 3:
params2 = dict((k, v) for k, v in params.iteritems()) # deep copy
params2.update({'beta': params['beta2']})
return self.simulate_SI_trees(params2, tree_height, tip_heights, post)
if tp2 < 3:
params2 = dict((k, v) for k, v in params.iteritems()) # deep copy
params2.update({'beta': params['beta1']})
return self.simulate_SI_trees(params2, tree_height, tip_heights, post)
# set model parameters
robjects.r('S = N-1')
robjects.r('I = 1')
robjects.r('x0 <- c(I=I, S=S)')
robjects.r('parms <- list(beta=beta1, gamma=gamma, mu=mu, lambd=lambd)')
robjects.r("n.tips <- %d" % len(tip_heights))
robjects.r("tip.heights <- c(%s)" % ','.join(map(str, tip_heights)))
robjects.r("sampleTimes <- t_end - tip.heights")
robjects.r("sampleStates <- matrix(1, nrow=n.tips, ncol=length(demes))")
robjects.r("colnames(sampleStates) <- demes")
robjects.r("rownames(sampleStates) <- 1:n.tips")
robjects.r("m <- nrow(births)")
robjects.r("maxSampleTime <- max(sampleTimes)")
# solve first ODE
robjects.r("tfgy.1 <- make.fgy( t0, times[fgyRes.1], births, deaths, nonDemeDynamics, x0, "
"migrations=migrations, parms=parms, fgyResolution = fgyRes.1, "
"integrationMethod = integrationMethod )")
# update model parameter with second beta
robjects.r("x1 <- tfgy.1[[5]][fgyRes.1, 2:3]")
robjects.r("parms$beta <- beta2")
# solve second ODE
robjects.r("tfgy.2 <- make.fgy( times[fgyRes.1+1], maxSampleTime, births, deaths, nonDemeDynamics, x1, "
"migrations=migrations, parms=parms, fgyResolution = fgyRes.2, "
"integrationMethod = integrationMethod)")
n_inf = robjects.r("tfgy.2[[4]][[1]]")[0]
if n_inf < len(tip_heights):
# number of infected at end of simulation is less than number of tips
return []
# reconstitute the entire tfgy
robjects.r("y.times <- c(tfgy.2[[1]], tfgy.1[[1]])")
robjects.r("y.births <- c(tfgy.2[[2]], tfgy.1[[2]])")
robjects.r("y.migrations <- c(tfgy.2[[3]], tfgy.1[[3]])")
robjects.r("y.demeSizes <- c(tfgy.2[[4]], tfgy.1[[4]])")
# simulate trees
try:
robjects.r("trees <- simulate.binary.dated.tree.fgy(y.times, y.births, y.migrations, y.demeSizes, "
"sampleTimes, sampleStates, integrationMethod=integrationMethod, "
"n.reps=nreps, cluster=cl)")
except:
return []
# convert R objects into Python strings in Newick format
robjects.r("class(trees) <- 'multiPhylo'")
try:
retval = robjects.r("lapply(trees, write.tree)")
except:
# error converting trees
return []
trees = map(lambda x: str(x).split()[-1].strip('" '), retval)
if post:
return (trees, robjects.r("rbind(tfgy.1[[5]], tfgy.2[[5]])"))
else:
return trees
def init_DiffRisk_model(self):
"""
Define ODE system for differential risk SI model.
"""
robjects.r("demes <- c('I1', 'I2')")
robjects.r("p11 <- '(parms$rho + (1-parms$rho) * parms$c1*(S1+I1) / (parms$c1*(S1+I1) + parms$c2*(S2+I2)))'")
robjects.r("p12 <- '(1-parms$rho) * parms$c2*(S2+I2) / (parms$c1*(S1+I1) + parms$c2*(S2+I2))'")
robjects.r("p21 <- '(1-parms$rho) * parms$c1*(S1+I1) / (parms$c1*(S1+I1) + parms$c2*(S2+I2))'")
robjects.r("p22 <- '(parms$rho + (1-parms$rho) * parms$c2*(S2+I2) / (parms$c1*(S1+I1) + parms$c2*(S2+I2)))'")
robjects.r("births <- rbind(c(paste(sep='*', 'parms$beta*parms$c1', p11, 'I1/(S1+I1)*S1'),"
"paste(sep='*', 'parms$beta*parms$c2', p21, 'I1/(S1+I1)*S2')),"
"c(paste(sep='*', 'parms$beta*parms$c1', p12, 'I2/(S2+I2)*S1'),"
"paste(sep='*', 'parms$beta*parms$c2', p22, 'I2/(S2+I2)*S2')))")
robjects.r("rownames(births)=colnames(births) <- demes")
robjects.r("migrations <- rbind(c('0', '0'), c('0', '0'))")
robjects.r("rownames(migrations)=colnames(migrations) <- demes")
robjects.r("deaths <- c('(parms$mu+parms$gamma)*I1', '(parms$mu+parms$gamma)*I2')")
robjects.r("names(deaths) <- demes")
robjects.r("nonDemeDynamics <- c(paste(sep='', '-parms$mu*S1 + parms$mu*S1 + (parms$mu+parms$gamma)*I1', "
"paste(sep='*', '-S1*(parms$beta*parms$c1', p11, 'I1/(S1+I1) + parms$beta*parms$c1', p12, "
"'I2/(S2+I2))')), paste(sep='', '-parms$mu*S2 + parms$mu*S2 + (parms$mu+parms$gamma)*I2', "
"paste(sep='*', '-S2*(parms$beta*parms$c2', p21, 'I1/(S1+I1) + parms$beta*parms$c2', p22, "
"'I2/(S2+I2))')))")
robjects.r("names(nonDemeDynamics) <- c('S1', 'S2')")
def simulate_DiffRisk_trees(self, params, tree_height, tip_heights, post=False):
"""
:param params:
:param tip_heights:
:return:
"""
# set parameters
robjects.r('N=%f; beta=%f; c1=%f; c2=%f' % (params['N'], params['beta'], params['c1'], params['c2']))
robjects.r('rho=%f; p=%f; gamma=%f; mu=%f' % (params['rho'], params['p'], params['gamma'], params['mu']))
robjects.r('t_end=%f' % (tree_height,))
# update model parameters
robjects.r("S1=p*N-1; S2=(1-p)*N; I1=1; I2=0")
robjects.r("x0 <- c(I1=I1, I2=I2, S1=S1, S2=S2)")
robjects.r("parms <- list(beta=beta, gamma=gamma, mu=mu, c1=c1, c2=c2, rho=rho)")
robjects.r("n.tips <- %d" % len(tip_heights))
robjects.r("tip.heights <- c(%s)" % ','.join(map(str, tip_heights)))
robjects.r("sampleTimes <- t_end - tip.heights")
robjects.r("sampleStates <- matrix(1, nrow=n.tips, ncol=length(demes))")
robjects.r("colnames(sampleStates) <- demes")
robjects.r("rownames(sampleStates) <- 1:n.tips")
robjects.r("m <- nrow(births)")
robjects.r("maxSampleTime <- max(sampleTimes)")
# solve ODE
robjects.r("tfgy <- make.fgy( t0, maxSampleTime, births, deaths, nonDemeDynamics, x0, migrations=migrations, "
"parms=parms, fgyResolution = fgyResolution, integrationMethod = integrationMethod)")
# use prevalence of respective infected classes at end of simulation to determine sample states
robjects.r("demes.t.end <- tfgy[[4]][[1]]")
if robjects.r("sum(demes.t.end)")[0] < len(tip_heights):
# number of infected individuals at end of simulation is less than number of tips
return []
robjects.r("demes.sample <- sample(rep(1:length(demes), times=round(demes.t.end)), size=n.tips)")
robjects.r("sampleStates <- matrix(0, nrow=n.tips, ncol=length(demes))")
robjects.r("colnames(sampleStates) <- demes")
robjects.r("for (i in 1:n.tips) { sampleStates[i, demes.sample[i]] <- 1 }")
robjects.r("rownames(sampleStates) <- paste(1:n.tips, demes.sample, sep='_')")
# simulate trees
try:
robjects.r("trees <- simulate.binary.dated.tree.fgy( tfgy[[1]], tfgy[[2]], tfgy[[3]], tfgy[[4]], "
"sampleTimes, sampleStates, integrationMethod = integrationMethod, "
"n.reps=nreps, cluster=cl)")
except:
return []
# convert R objects into Python strings in Newick format
robjects.r("class(trees) <- 'multiPhylo'")
try:
retval = robjects.r("lapply(trees, write.tree)")
except:
# error converting trees
return []
trees = map(lambda x: str(x).split()[-1].strip('" '), retval)
if post:
return (trees, robjects.r("tfgy[[5]]"))
else:
return trees
def init_stages_model (self):
"""
Defines an ODE system (by string expressions) for an SIR model where
the infected class moves through three stages: acute, asymptomatic, and chronic.
:return:
"""
robjects.r("demes <- c('I1', 'I2', 'I3')")
# transition from susceptible by infection (from any stage) to stage one only
robjects.r("births <- rbind(c('parms$beta1*S*I1 / (S+I1+I2+I3)', '0', '0'), "
"c('parms$beta2*S*I2 / (S+I1+I2+I3)', '0', '0'), "
"c('parms$beta3*S*I3 / (S+I1+I2+I3)', '0', '0'))")
robjects.r("rownames(births)=colnames(births) <- demes")
# transition between stages of infection by "migration"
robjects.r("migrations <- rbind(c('0', 'parms$alpha1 * I1', '0'), "
"c('0', '0', 'parms$alpha2 * I2'),"
"c('0', '0', '0'))")
robjects.r("rownames(migrations)=colnames(migrations) <- demes")
# assume that increased death rate only at final stage
robjects.r("deaths <- c('(parms$mu)*I1', '(parms$mu)*I2', '(parms$mu+parms$gamma)*I3')")
robjects.r("names(deaths) <- demes")
# dynamics of susceptible class (replacement of deaths, loss to infection)
robjects.r("nonDemeDynamics <- paste(sep='', '-parms$mu*S + parms$mu*(S+I1+I2) + (parms$mu+parms$gamma)*I3', "
"'-S*(parms$beta1*I1 + parms$beta2*I2 + parms$beta3*I3) / (S+I1+I2+I3)')")
robjects.r("names(nonDemeDynamics) <- 'S'")
def simulate_stages_trees(self, params, tree_height, tip_heights, post=False):
"""
:return:
"""
# set parameters
robjects.r('N=%f; beta1=%f; beta2=%f; beta3=%f' % (params['N'], params['beta1'], params['beta2'],
params['beta3']))
robjects.r('alpha1=%f; alpha2=%f' % (params['alpha1'], params['alpha2']))
robjects.r('gamma=%f; mu=%f' % (params['gamma'], params['mu']))
robjects.r('t_end=%f' % (tree_height,))
# update model parameters
robjects.r("S=N-1; I1=1; I2=0; I3=0")
robjects.r("x0 <- c(I1=I1, I2=I2, I3=I3, S=S)")
robjects.r("parms <- list(beta1=beta1, beta2=beta2, beta3=beta3, alpha1=alpha1, alpha2=alpha2, "
"gamma=gamma, mu=mu)")
robjects.r("n.tips <- %d" % len(tip_heights))
robjects.r("tip.heights <- c(%s)" % ','.join(map(str, tip_heights)))
robjects.r("sampleTimes <- t_end - tip.heights")
robjects.r("sampleStates <- matrix(1, nrow=n.tips, ncol=length(demes))")
robjects.r("colnames(sampleStates) <- demes")
robjects.r("rownames(sampleStates) <- 1:n.tips")
robjects.r("m <- nrow(births)")
robjects.r("maxSampleTime <- max(sampleTimes)")
# solve ODE
robjects.r("tfgy <- make.fgy( t0, maxSampleTime, births, deaths, nonDemeDynamics, x0, migrations=migrations, "
"parms=parms, fgyResolution = fgyResolution, integrationMethod = integrationMethod)")
# use prevalence of respective infected classes at end of simulation to determine sample states
robjects.r("demes.t.end <- tfgy[[4]][[1]]")
if robjects.r("sum(demes.t.end)")[0] < len(tip_heights):
# number of infected individuals at end of simulation is less than number of tips
return []
robjects.r("demes.sample <- sample(rep(1:length(demes), times=round(demes.t.end)), size=n.tips)")
robjects.r("sampleStates <- matrix(0, nrow=n.tips, ncol=length(demes))")
robjects.r("colnames(sampleStates) <- demes")
robjects.r("for (i in 1:n.tips) { sampleStates[i, demes.sample[i]] <- 1 }")
robjects.r("rownames(sampleStates) <- paste(1:n.tips, demes.sample, sep='_')")
# simulate trees
try:
robjects.r("trees <- simulate.binary.dated.tree.fgy( tfgy[[1]], tfgy[[2]], tfgy[[3]], tfgy[[4]], "
"sampleTimes, sampleStates, integrationMethod = integrationMethod, "
"n.reps=nreps, cluster=cl)")
except:
return []
# convert R objects into Python strings in Newick format
robjects.r("class(trees) <- 'multiPhylo'")
try:
retval = robjects.r("lapply(trees, write.tree)")
except:
# error converting trees
return []
trees = map(lambda x: str(x).split()[-1].strip('" '), retval)
if post:
return (trees, robjects.r("tfgy[[5]]"))
else:
return trees