Skip to content

Instantly share code, notes, and snippets.

@Sietesoles
Created September 6, 2014 15:53
Show Gist options
  • Save Sietesoles/e5f9eb4126f58ca6feb5 to your computer and use it in GitHub Desktop.
Save Sietesoles/e5f9eb4126f58ca6feb5 to your computer and use it in GitHub Desktop.
Stochastic simulation of Patient and Virus population dynamics
import numpy
import random
import pylab
from VirusClasses import *
def simulationDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 1.
Runs numTrials simulations to show the relationship between delayed
treatment and patient outcome using a histogram.
Histograms of final total virus populations are displayed for delays of 300,
150, 75, 0 timesteps (followed by an additional 150 timesteps of
simulation).
numTrials: number of simulation runs to execute (an integer)
"""
cured = 0
x = 75
virusList = []
for trial in range(1, numTrials+1):
viruses = []
virusTotals = []
for i in range(1, numTrials + 1):
virus = ResistantVirus(0.1, 0.05, {'guttagonol': False}, 0.005)
viruses.append(virus)
treatedPatient = TreatedPatient(viruses, 1000)
for i in range(1, x+1):
treatedPatient.update()
y = treatedPatient.getTotalPop()
virusTotals.append(y)
treatedPatient.addPrescription('guttagonol')
for i in range(1, 151):
treatedPatient.update()
y = treatedPatient.getTotalPop()
virusTotals.append(y)
result = virusTotals[-1]
virusList.append(result)
if result <=50:
cured +=1
print cured
pylab.hist(virusList, bins =20)
pylab.show()
def simulationTwoDrugsDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 2.
Runs numTrials simulations to show the relationship between administration
of multiple drugs and patient outcome.
Histograms of final total virus populations are displayed for lag times of
300, 150, 75, 0 timesteps between adding drugs (followed by an additional
150 timesteps of simulation).
numTrials: number of simulation runs to execute (an integer)
"""
cured = 0
x = 150
virusList = []
for trial in range(numTrials):
viruses = []
virusTotals = []
for i in range(100):
virus = ResistantVirus(0.1, 0.05,
{'guttagonol': False, 'grimpex': False},
0.01)
viruses.append(virus)
treatedPatient = TreatedPatient(viruses, 1000)
for i in range(150):
treatedPatient.update()
y = treatedPatient.getTotalPop()
virusTotals.append(y)
treatedPatient.addPrescription('guttagonol')
for i in range(x):
treatedPatient.update()
y = treatedPatient.getTotalPop()
virusTotals.append(y)
treatedPatient.addPrescription('grimpex')
for i in range(150):
treatedPatient.update()
y = treatedPatient.getTotalPop()
virusTotals.append(y)
result = virusTotals[-1]
virusList.append(result)
if result <=50:
cured +=1
print cured
pylab.hist(virusList, bins =20)
pylab.show()
simulationTwoDrugsDelayedTreatment(100)
import numpy
import random
import pylab
class NoChildException(Exception):
"""
NoChildException is raised by the reproduce() method in the SimpleVirus
and ResistantVirus classes to indicate that a virus particle does not
reproduce.
"""
class SimpleVirus(object):
"""
Representation of a simple virus (does not model drug effects/resistance).
"""
def __init__(self, maxBirthProb, clearProb):
"""
Initialize a SimpleVirus instance, saves all parameters as attributes
of the instance.
maxBirthProb: Maximum reproduction probability (a float between 0-1)
clearProb: Maximum clearance probability (a float between 0-1).
"""
self.maxBirthProb = maxBirthProb
self.clearProb = clearProb
def getMaxBirthProb(self):
"""
Returns the max birth probability.
"""
return self.maxBirthProb
def getClearProb(self):
"""
Returns the clear probability.
"""
return self.clearProb
def doesClear(self):
""" Stochastically determines whether this virus particle is cleared from the
patient's body at a time step.
returns: True with probability self.getClearProb and otherwise returns
False.
"""
if random.random()<self.getClearProb():
return True
return False
def reproduce(self, popDensity):
"""
Stochastically determines whether this virus particle reproduces at a
time step. Called by the update() method in the Patient and
TreatedPatient classes. The virus particle reproduces with probability
self.getMaxBirthProb * (1 - popDensity).
If this virus particle reproduces, then reproduce() creates and returns
the instance of the offspring SimpleVirus (which has the same
maxBirthProb and clearProb values as its parent).
popDensity: the population density (a float), defined as the current
virus population divided by the maximum population.
returns: a new instance of the SimpleVirus class representing the
offspring of this virus particle. The child should have the same
maxBirthProb and clearProb values as this virus. Raises a
NoChildException if this virus particle does not reproduce.
"""
if random.random()<=(self.getMaxBirthProb()*(1-popDensity)):
simplevirus = SimpleVirus(self.getMaxBirthProb(), self.getClearProb())
return simplevirus
else:
raise NoChildException
class Patient(object):
"""
Representation of a simplified patient. The patient does not take any drugs
and his/her virus populations have no drug resistance.
"""
def __init__(self, viruses, maxPop):
"""
Initialization function, saves the viruses and maxPop parameters as
attributes.
viruses: the list representing the virus population (a list of
SimpleVirus instances)
maxPop: the maximum virus population for this patient (an integer)
"""
self.viruses = viruses
self.maxPop = maxPop
def getViruses(self):
"""
Returns the viruses in this Patient.
"""
return self.viruses
def getMaxPop(self):
"""
Returns the max population.
"""
return self.maxPop
def getTotalPop(self):
"""
Gets the size of the current total virus population.
returns: The total virus population (an integer)
"""
return len(self.getViruses())
def update(self):
"""
Update the state of the virus population in this patient for a single
time step. update() should execute the following steps in this order:
- Determine whether each virus particle survives and updates the list
of virus particles accordingly.
- The current population density is calculated. This population density
value is used until the next call to update()
- Based on this value of population density, determine whether each
virus particle should reproduce and add offspring virus particles to
the list of viruses in this patient.
returns: The total virus population at the end of the update (an
integer)
"""
virusesCopy = self.viruses[:]
for virus in virusesCopy:
if virus.doesClear() == True:
self.viruses.remove(virus)
popDensity = (float(self.getTotalPop())/float(self.getMaxPop()))
virusesCopy2 = self.viruses[:]
for virus in virusesCopy2:
if self.getTotalPop() >= self.getMaxPop():
break
try: self.viruses.append(virus.reproduce(popDensity))
except NoChildException:
pass
return self.viruses
def simulationWithoutDrug(numViruses, maxPop, maxBirthProb, clearProb,
numTrials):
"""
Run the simulation and plot the graph for problem 3 (no drugs are used,
viruses do not have any drug resistance).
For each of numTrials trial, instantiates a patient, runs a simulation
for 300 timesteps, and plots the average virus population size as a
function of time.
numViruses: number of SimpleVirus to create for patient (an integer)
maxPop: maximum virus population for patient (an integer)
maxBirthProb: Maximum reproduction probability (a float between 0-1)
clearProb: Maximum clearance probability (a float between 0-1)
numTrials: number of simulation runs to execute (an integer)
"""
virusTotals = [0 for i in range(300)]
viruses = []
virusAvgs = []
for x in range(numViruses):
virus = SimpleVirus(maxBirthProb, clearProb)
viruses.append(virus)
patient = Patient(viruses, maxPop)
for e in range(numTrials):
virusPops = []
for i in range(300):
patient.update()
x = patient.getTotalPop()
virusTotals[i] += x
for i in range(300):
virusAvgs.append((float(virusTotals[i])/float(numTrials)))
pylab.plot(range(300), virusAvgs)
pylab.title('SimpleVirus simulation')
pylab.xlabel('Time step')
pylab.ylabel('Average Virus Population')
pylab.legend()
pylab.figure(1)
pylab.show()
class ResistantVirus(SimpleVirus):
"""
Representation of a virus which can have drug resistance.
"""
def __init__(self, maxBirthProb, clearProb, resistances, mutProb):
"""
Initialize a ResistantVirus instance, saves all parameters as attributes
of the instance.
maxBirthProb: Maximum reproduction probability (a float between 0-1)
clearProb: Maximum clearance probability (a float between 0-1).
resistances: A dictionary of drug names (strings) mapping to the state
of this virus particle's resistance (either True or False) to each drug.
e.g. {'guttagonol':False, 'srinol':False}, means that this virus
particle is resistant to neither guttagonol nor srinol.
mutProb: Mutation probability for this virus particle (a float). This is
the probability of the offspring acquiring or losing resistance to a drug.
"""
SimpleVirus.__init__(self, maxBirthProb, clearProb)
self.resistances = resistances
self.mutProb = mutProb
def getResistances(self):
"""
Returns the resistances for this virus.
"""
return self.resistances
def getMutProb(self):
"""
Returns the mutation probability for this virus.
"""
return self.mutProb
def isResistantTo(self, drug):
"""
Get the state of this virus particle's resistance to a drug. This method
is called by getResistPop() in TreatedPatient to determine how many virus
particles have resistance to a drug.
drug: The drug (a string)
returns: True if this virus instance is resistant to the drug, False
otherwise.
"""
if drug not in self.resistances.keys():
return False
return self.resistances[drug]
def reproduce(self, popDensity, activeDrugs):
"""
"""
for drug in activeDrugs:
if self.isResistantTo(drug)==False:
raise NoChildException
if random.random() < self.getMaxBirthProb()*(1-popDensity):
newResistances = self.resistances.copy()
for drug in self.resistances.keys():
if self.resistances[drug]==True:
if random.random() > (1-self.mutProb):
newResistances[drug] = False
else:
if random.random() < self.mutProb:
newResistances[drug] = True
newVirus = ResistantVirus(self.maxBirthProb, self.clearProb, newResistances, self.mutProb)
return newVirus
else:
raise NoChildException
class TreatedPatient(Patient):
"""
Representation of a patient. The patient is able to take drugs and his/her
virus population can acquire resistance to the drugs he/she takes.
"""
def __init__(self, viruses, maxPop):
"""
Initialization function, saves the viruses and maxPop parameters as
attributes. Also initializes the list of drugs being administered
(which should initially include no drugs).
viruses: The list representing the virus population (a list of
virus instances)
maxPop: The maximum virus population for this patient (an integer)
"""
Patient.__init__(self, viruses, maxPop)
self.listOfDrugs = []
def addPrescription(self, newDrug):
"""
Administer a drug to this patient. After a prescription is added, the
drug acts on the virus population for all subsequent time steps. If the
newDrug is already prescribed to this patient, the method has no effect.
newDrug: The name of the drug to administer to the patient (a string).
postcondition: The list of drugs being administered to a patient is updated
"""
if newDrug in self.listOfDrugs:
pass
else:
self.listOfDrugs.append(newDrug)
def getPrescriptions(self):
"""
Returns the drugs that are being administered to this patient.
returns: The list of drug names (strings) being administered to this
patient.
"""
return self.listOfDrugs
def getResistPop(self, drugResist):
"""
Get the population of virus particles resistant to the drugs listed in
drugResist.
drugResist: Which drug resistances to include in the population (a list
of strings - e.g. ['guttagonol'] or ['guttagonol', 'srinol'])
returns: The population of viruses (an integer) with resistances to all
drugs in the drugResist list.
"""
count = 0
for virus in self.viruses:
for drug in drugResist:
hasResistance = 1
if virus.isResistantTo(drug):
hasResistance *= 1
else:
hasResistance = 0
break
count += hasResistance
return count
def removePresciption(newDrug):
if newDrug not in self.listOfDrugs:
pass
else:
self.listOfDrugs.remove(newDrug)
def update(self):
"""
Update the state of the virus population in this patient for a single
time step. update() should execute these actions in order:
- Determine whether each virus particle survives and update the list of
virus particles accordingly
- The current population density is calculated. This population density
value is used until the next call to update().
- Based on this value of population density, determine whether each
virus particle should reproduce and add offspring virus particles to
the list of viruses in this patient.
The list of drugs being administered should be accounted for in the
determination of whether each virus particle reproduces.
returns: The total virus population at the end of the update (an
integer)
"""
virusesCopy = self.viruses[:]
for virus in virusesCopy:
if virus.doesClear() == True:
self.viruses.remove(virus)
popDensity = (float(self.getTotalPop())/float(self.getMaxPop()))
virusesCopy2 = self.viruses[:]
for virus in virusesCopy2:
try: self.viruses.append(virus.reproduce(popDensity, self.listOfDrugs))
except NoChildException:
pass
return self.getTotalPop()
def simulationWithDrug(numViruses, maxPop, maxBirthProb, clearProb, resistances,
mutProb, numTrials):
"""
Runs simulations and plots graphs.
For each of numTrials trials, instantiates a patient, runs a simulation for
150 timesteps, adds guttagonol, and runs the simulation for an additional
150 timesteps. At the end plots the average virus population size
(for both the total virus population and the guttagonol-resistant virus
population) as a function of time.
numViruses: number of ResistantVirus to create for patient (an integer)
maxPop: maximum virus population for patient (an integer)
maxBirthProb: Maximum reproduction probability (a float between 0-1)
clearProb: maximum clearance probability (a float between 0-1)
resistances: a dictionary of drugs that each ResistantVirus is resistant to
(e.g., {'guttagonol': False})
mutProb: mutation probability for each ResistantVirus particle
(a float between 0-1).
numTrials: number of simulation runs to execute (an integer)
"""
viruses = []
virusTotals = [0 for i in range(300)]
virusResPop = [0 for i in range(300)]
virusAvgs = []
virusResAvgs = []
for virus in range(numViruses):
virus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb)
viruses.append(virus)
for e in range(numTrials):
treatedPatient = TreatedPatient(viruses, maxPop)
for i in range(150):
treatedPatient.update()
x = treatedPatient.getTotalPop()
virusTotals[i] += x
y = treatedPatient.getResistPop(['guttagonol'])
virusResPop[i] += y
treatedPatient.addPrescription('guttagonol')
for i in range(150, 300):
treatedPatient.update()
x = treatedPatient.getTotalPop()
virusTotals[i] += x
y = treatedPatient.getResistPop(['guttagonol'])
virusResPop[i] += y
for i in range(300):
virusAvgs.append((float(virusTotals[i])/float(numTrials)))
virusResAvgs.append((float(virusResPop[i])/float(numTrials)))
pylab.plot(range(300), virusAvgs, label = 'total pop')
pylab.plot(range(300), virusResAvgs, label = 'resistant pop')
pylab.title('ResistantVirus simulation')
pylab.xlabel('time step')
pylab.ylabel('# viruses')
pylab.legend()
pylab.figure(1)
pylab.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment