Skip to content

Instantly share code, notes, and snippets.

@CnrLwlss
Last active December 10, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CnrLwlss/4431230 to your computer and use it in GitHub Desktop.
Save CnrLwlss/4431230 to your computer and use it in GitHub Desktop.
Python function for carrying out discrete stochastic simulations of the logistic population model. http://cnr.lwlss.net/DiscreteStochasticLogistic/
import numpy as np
def simDSLogistic(K,r,N0):
'''Discrete stochastic logistic model simulation. Carrying capacity K,
intrinsic growth rate r, initial population size (inoculum) N0. Returns an
array with a (continuous) time column and a (discrete) population size column.'''
# Unusually, for this model, we know the number of events a priori
eventNo=K-N0
# So we can just generate all required random numbers (quickly) in one go
unifs=np.random.uniform(size=eventNo)
# Every event produces one cell and consumes one unit of nutrients
simres=np.zeros((eventNo+1,2),np.float)
simres[:,1]=range(N0,K+1)
# Simulate time between events by generating
# exponential random numbers using the inversion method
dts=-np.log(1-unifs)/(r*simres[1:,1]*(1-simres[1:,1]/K))
simres[1:,0]=np.cumsum(dts)
return(simres)
@CnrLwlss
Copy link
Author

CnrLwlss commented Jan 3, 2013

Updated function to avoid slow concatenation of initial conditions onto arrays. Can now simulate a population or culture with a carrying capacity of 1.6M, starting from a single member or cell in 0.37s.

python #logistic #discrete #stochastic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment