Package trunk :: Package BIP :: Package SDE :: Module example
[hide private]

Source Code for Module trunk.BIP.SDE.example

 1  # -*- coding:utf-8 -*- 
 2  #----------------------------------------------------------------------------- 
 3  # Name:        example.py 
 4  # Project:  Bayesian-Inference 
 5  # Purpose:      
 6  # 
 7  # Author:      Flávio Codeço Coelho<fccoelho@gmail.com> 
 8  # 
 9  # Created:     2008-11-26 
10  # Copyright:   (c) 2008 by the Author 
11  # Licence:     GPL 
12  #----------------------------------------------------------------------------- 
13  __docformat__ = "restructuredtext en" 
14  """ 
15  Example of an SEIR model with two Infectious classes: subclinical(Is) and clinical(Ic) 
16            Is 
17           /  \ 
18  S -> E     R 
19           \  / 
20            Ic 
21           
22  States: 
23  S: Susceptible 
24  E: Exposed 
25  Is: Infectious subclinical 
26  Ic: Infectious clinical 
27  R: Recovered 
28   
29  Transition rates: 
30  b,ks,kc,rs,rc = (0.001, 0.1, 0.1, 0.01, .01) 
31  Transitions: 
32  S -> E : b*S*(Is+Ic) 
33  E -> Is : ks*E 
34  E -> Ic : kc*E 
35  Is -> R : rs*Is 
36  Ic -> R : rc*Ic 
37   
38  """ 
39  from cgillespie import Model as CModel 
40  from gillespie import Model 
41  import time 
42   
43  from numpy import array 
44  vnames = ['S','E','Is','Ic','R'] 
45  #rates: b,ks,kc,rs,rc 
46   
47  r = (0.001, 0.1, 0.1, 0.01, .01) 
48  ini = array((490,0,0,10,0)) #must be integers 
49  # propensity functions 
50 -def f1(r,ini):return r[0]*ini[0]*(ini[2]+ini[3])
51 -def f2(r,ini):return r[1]*ini[1]
52 -def f3(r,ini):return r[2]*ini[1]
53 -def f4(r,ini):return r[3]*ini[2]
54 -def f5(r,ini):return r[4]*ini[3]
55 56 propf = (f1,f2,f3,f4,f5) 57 # Transition matrix. Must be composed of integers 58 # Column are the events described by propensity functions, and lines are state variables 59 tmat = array([[-1, 0, 0, 0, 0],#S 60 [ 1,-1,-1, 0, 0],#E 61 [ 0, 1, 0,-1, 0],#Is 62 [ 0, 0, 1, 0,-1],#Ic 63 [ 0, 0, 0, 1, 1]])#R 64 M=Model(vnames=vnames,rates = r,inits=ini,tmat=tmat,propensity=propf) 65 CM = CModel(vnames=vnames,rates = r,inits=ini,tmat=tmat,propensity=propf) 66 67 # timing python gillespie 68 t0 = time.time() 69 M.run(tmax=80,reps=100,viz=0,serial=1) 70 pt = time.time()-t0 71 print 'Python total time: ',pt, ' seconds.' 72 t,series,steps,evts = M.getStats() 73 #print evts 74 print steps,'steps' 75 76 # timing cython gillespie 77 t0 = time.time() 78 CM.run(tmax=80,reps=100) 79 ct = time.time()-t0 80 print 'Cython total time: ',ct, ' seconds.' 81 t2,series2,steps2 = CM.getStats() 82 print steps2,' steps' 83 print "Cython speedup: %sx"%(pt/ct) 84 from pylab import plot , show, legend, errorbar, title, figure 85 print series.shape 86 #print cevts 87 plot(t,series.mean(axis=0),'-o') 88 title('Python curve') 89 legend(vnames,loc=0) 90 figure() 91 plot(t2,series2.mean(axis=2),'-o') 92 title('Cython curve') 93 legend(vnames,loc=0) 94 show() 95