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 print self.steps 89 else:# Serial 90 self.res = array(map(dispatch,[self]*reps)) 91 92 elif method == 'SSAct': 93 pass 94 95 self.time = tvec 96 self.series = self.res
97 #self.steps=steps 98
99 - def GSSA(self):
100 ''' 101 Gillespie Direct algorithm 102 ''' 103 tmax = self.tmax 104 ini = copy.deepcopy(self.inits) 105 r = self.rates 106 pvi = self.pv #propensity functions 107 tm = self.tm 108 pv = self.pv0 #actual propensity values for each time step 109 tc = 0 110 self.steps = 0 111 self.res[0,:]= ini 112 for tim in xrange(1,tmax): 113 while tc < tim: 114 i=0 115 a0=0.0 116 for p in pvi: 117 pv[i] = p(r,ini) 118 a0+=pv[i] 119 i+=1 120 tau = (-1/a0)*log(random()) 121 if pv.any():#no change in state is pv is all zeros 122 try: 123 event = multinomial(1,pv/a0) # event which will happen on this iteration 124 except ValueError:# as inst:#2.6 syntax 125 #print inst 126 print "pv: ",pv 127 print "Rates: ", r 128 print "State: ", ini 129 print "Time Step: ",tim 130 raise ValueError() 131 ini += tm[:,event.nonzero()[0][0]] 132 #print tc, ini 133 tc += tau 134 self.steps +=1 135 if a0 == 0: break 136 self.res[tim,:] = ini 137 # if a0 == 0: break 138 if self.viz: 139 self.ser.clearFig() 140 self.ser.plotlines(self.res.T,names=self.vn) 141 return self.res
142 143
144 -def p1(r,ini): return r[0]*ini[0]*ini[1]
145 -def p2(r,ini): return r[1]*ini[1]
146
147 -def main():
148 vnames = ['S','I','R'] 149 ini= [500,1,0] 150 rates = [.001,.1] 151 tm = array([[-1,0],[1,-1],[0,1]]) 152 #prop=[lambda r, ini:r[0]*ini[0]*ini[1],lambda r,ini:r[0]*ini[1]] 153 M = Model(vnames = vnames,rates = rates,inits=ini, tmat=tm,propensity=[p1,p2]) 154 t0=time.time() 155 M.run(tmax=80,reps=100,viz=False,serial=False) 156 print 'total time: ',time.time()-t0 157 #print res 158 t,series,steps = M.getStats() 159 ser = series.mean(axis=0) 160 from pylab import plot , show, legend 161 plot(t,ser,'-.') 162 legend(M.vn,loc=0) 163 show()
164 165 166 if __name__=="__main__": 167 #import cProfile 168 #cProfile.run('main()',sort=1,filename='gillespie.profile') 169 main() 170