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