Package BIP :: Package SDE :: Module gillespie
[hide private]
[frames] | no frames]

Source Code for Module BIP.SDE.gillespie

  1  # -*- coding:utf-8 -*- 
  2  #----------------------------------------------------------------------------- 
  3  # Name:        gillespie.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  from numpy.random import uniform, multinomial, exponential,random 
 15  from numpy import arange, array, empty,zeros,log, isnan, nanmax 
 16  import time 
 17  import copy 
 18  from multiprocessing import Pool 
 19  from BIP.Viz.realtime import RTplot 
 20  import psyco 
 21  psyco.full() 
 22  ser = RTplot() 
 23  #global ini 
 24  #ini=[500,1,0] 
25 -def dispatch(model):
26 '''this function is necessary for paralelization''' 27 model.ser = ser 28 return model.GSSA()
29
30 -class Model:
31 - def __init__(self,vnames,rates,inits, tmat,propensity):
32 ''' 33 * vnames: list of strings 34 * rates: list of fixed rate parameters 35 * inits: list of initial values of variables 36 * propensity: list of lambda functions of the form: 37 lambda r,ini: some function of rates ans inits. 38 ''' 39 self.vn = vnames 40 self.rates = rates 41 self.inits = inits 42 self.tm = tmat 43 self.pv = propensity#[compile(eq,'errmsg','eval') for eq in propensity] 44 self.pvl = len(self.pv) #length of propensity vector 45 self.pv0 = zeros(self.pvl,dtype=float) 46 self.nvars = len(self.inits) #number of variables 47 self.time=None 48 self.tmax = None 49 self.series=None 50 self.steps=0 51 self.viz = False #if intermediate vizualization should be on
52 # self.ser = RTplot() 53
54 - def getStats(self):
55 return self.time,self.series,self.steps
56
57 - def run(self, method='SSA', tmax=10, reps=1, viz=False, serial=False):
58 ''' 59 Runs the model. 60 61 :Parameters: 62 - `method`: String specifying the solving algorithm. Currently only 'SSA' 63 - `tmax`: duration of the simulation. 64 - `reps`: Number of replicates. 65 - `viz`: Boolean. Whether to show graph of each replicate during simulation 66 - `serial`: Boolean. False to run replicate in parallel when more than one core is a vailable. True to run them serially (easier to debug). 67 68 :Return: 69 a numpy array of shape (reps,tmax,nvars) 70 ''' 71 self.viz = viz 72 self.tmax = tmax 73 #self.res = zeros((tmax,self.nvars,reps),dtype=float) 74 self.res = zeros((tmax,self.nvars),dtype=float) 75 tvec = arange(tmax, dtype=int) 76 77 if method =='SSA': 78 if not serial:# Parallel version 79 pool = Pool() 80 self.res = array(pool.map(dispatch,[(self) for i in xrange(reps)],chunksize=10)) 81 pool.close() 82 pool.join() 83 else:# Serial 84 self.res = array([dispatch(self) for i in xrange(reps)]) 85 86 elif method == 'SSAct': 87 pass 88 89 self.time = tvec 90 self.series = self.res
91 #self.steps=steps 92
93 - def GSSA(self):
94 ''' 95 Gillespie Direct algorithm 96 ''' 97 tmax = self.tmax 98 ini = copy.deepcopy(self.inits) 99 r = self.rates 100 pvi = self.pv #propensity functions 101 tm = self.tm 102 pv = self.pv0 #actual propensity values for each time step 103 tc = 0 104 self.steps = 0 105 self.res[0,:]= ini 106 for tim in xrange(1,tmax): 107 while tc < tim: 108 i=0 109 a0=0 110 for p in pvi: 111 pv[i] = p(r,ini) 112 a0+=pv[i] 113 i+=1 114 tau = (-1/a0)*log(random()) 115 if pv.any():#no change in state is pv is all zeros 116 try: 117 event = multinomial(1,pv/a0) # event which will happen on this iteration 118 except ValueError as inst: 119 print inst 120 print "pv: ",pv 121 print "Rates: ", r 122 print "State: ", ini 123 print "Time Step: ",tim 124 raise ValueError() 125 ini += tm[:,event.nonzero()[0][0]] 126 #print tc, ini 127 tc += tau 128 self.steps +=1 129 if a0 == 0: break 130 self.res[tim,:] = ini 131 if a0 == 0: break 132 if self.viz: 133 self.ser.clearFig() 134 self.ser.plotlines(self.res.T,names=self.vn) 135 return self.res
136 137
138 -def p1(r,ini): return r[0]*ini[0]*ini[1]
139 -def p2(r,ini): return r[0]*ini[1]
140
141 -def main():
142 vnames = ['S','I','R'] 143 ini= [500,1,0] 144 rates = [.001,.1] 145 tm = array([[-1,0],[1,-1],[0,1]]) 146 #prop=[lambda r, ini:r[0]*ini[0]*ini[1],lambda r,ini:r[0]*ini[1]] 147 M = Model(vnames = vnames,rates = rates,inits=ini, tmat=tm,propensity=[p1,p2]) 148 t0=time.time() 149 M.run(tmax=80,reps=1000,viz=False,serial=False) 150 print 'total time: ',time.time()-t0
151 #print res 152 153 # from pylab import plot , show, legend 154 # plot(t,res,'-.') 155 # legend(M.vn,loc=0) 156 # show() 157 158 159 if __name__=="__main__": 160 #import cProfile 161 #cProfile.run('main()',sort=1,filename='gillespie.profile') 162 main() 163