Skip to content

Instantly share code, notes, and snippets.

@kuanb
Created August 8, 2014 17:13
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 kuanb/2f75e66c8b7c827717c2 to your computer and use it in GitHub Desktop.
Save kuanb/2f75e66c8b7c827717c2 to your computer and use it in GitHub Desktop.
Example Homework Assignment from Introductory Python course 6.00
# Problem Set 7: Simulating the Spread of Disease, Body Temperature and Virus Population Dynamics
# Name: Kuan Butts
# Time: 22:00
import numpy
import random
import pylab
# for checking work from prob. 3, 4, 5, 6
#from ps7_precompiled_27 import *
#from ps7_temperature import *
#from ps7_precompiled_27 import *
'''
Begin helper code
'''
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. You should use NoChildException as is, you do not need to
modify/add any code.
"""
'''
End helper code
'''
#
# PROBLEM 2
#
class SimpleVirus(object):
"""
Representation of a simple virus (does not model drug effects/resistance).
"""
def __init__(self, max_birth_prob, clear_prob):
"""
Initialize a SimpleVirus instance, saves all parameters as attributes
of the instance.
max_birth_prob: Maximum reproduction probability (a float between 0-1)
clear_prob: Maximum clearance probability (a float between 0-1).
"""
self.max_birth_prob = max_birth_prob
self.clear_prob = clear_prob
def does_clear(self):
""" Stochastically determines whether this virus particle is cleared from the
patient's body at a time step.
returns: True with probability self.clear_prob and otherwise returns
False.
"""
if random.random() < self.clear_prob:
return True
else:
return False
def reproduce(self, pop_density):
"""
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.max_birth_prob * (1 - pop_density).
If this virus particle reproduces, then reproduce() creates and returns
the instance of the offspring SimpleVirus (which has the same
max_birth_prob and clear_prob values as its parent).
pop_density: 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
max_birth_prob and clear_prob values as this virus. Raises a
NoChildException if this virus particle does not reproduce.
"""
if random.random() < self.max_birth_prob * (1 - pop_density):
return SimpleVirus(self.max_birth_prob, self.clear_prob)
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, max_pop):
"""
Initialization function, saves the viruses and max_pop parameters as
attributes.
viruses: the list representing the virus population (a list of
SimpleVirus instances)
max_pop: the maximum virus population for this patient (an integer)
for Problem 4: temperature : the body temperature of the patient, which is initialized to 98 Fahrenheit.
"""
self.viruses = viruses
self.max_pop = max_pop
self.temperature = 98
def get_total_pop(self):
"""
Gets the size of the current total virus population.
returns: The total virus population (an integer)
"""
return len(self.viruses)
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)
- For Problem 4: Assign a value for the temperature. The value should be drawn
from a Gaussian Distribution that has a mean of 98 Fahrenheit and
a standard devaition of 1 Fahrenheit. You can use "random.gauss(98,1)"
- For Problem 4: check if the current temperature is greater than 100 Fahrenheit.
If the temperature is greater than 100 Fahrenheit then reduce the
virus population by 50%.
"""
survive_list = []
current_temp = self.temperature
current_temp = random.gauss(98, 1)
# for loop to append only viruses that clear .does_clear
for virus in self.viruses:
if virus.does_clear() == False:
survive_list.append(virus)
reproduce_list = []
pop_density = self.get_total_pop()/float(self.max_pop)
# for loop to add viruses that reproduce
for survived_virus in self.viruses:
try:
survived_virus.reproduce(pop_density)
reproduce_list.append(survived_virus)
except NoChildException:
pass
# add the survivors to the reproduced
self.viruses = survive_list + reproduce_list
temp_modify = []
# now a for loop to check for temperature level
if current_temp >= 100:
for i in range(int((len(self.viruses))/2)):
temp_modify.append(self.viruses[i])
self.viruses = temp_modify
return len(self.viruses)
#
# PROBLEM 3
#
def simulation_without_drug(num_viruses, max_pop, max_birth_prob, clear_prob,
num_trials):
"""
Run the simulation and plot the graph for problem 3 (no drugs are used,
viruses do not have any drug resistance).
For each of num_trials trials, instantiates a patient, runs a simulation
for 300 timesteps, and plots the average virus population size as a
function of time.
num_viruses: number of SimpleVirus to create for patient (an integer)
max_pop: maximum virus population for patient (an integer)
max_birth_prob: Maximum reproduction probability (a float between 0-1)
clear_prob: Maximum clearance probability (a float between 0-1)
num_trials: number of simulation runs to execute (an integer)
"""
# making a variable just in case we have to change later
num_timesteps = 300
# create a list that can have results added to it for averaging at end
trial_results = []
for values in range(num_timesteps):
trial_results.append(0)
# instantiate patients through list and run them through timesteps
for case in range(num_trials):
virus_init_list = []
for num in range(num_viruses):
virus_init_list.append(SimpleVirus(max_birth_prob, clear_prob))
instance_patient = Patient(virus_init_list, max_pop)
for update_instance in range(num_timesteps):
trial_results[update_instance] += instance_patient.update()
for step in range(len(trial_results)):
trial_results[step] = trial_results[step]/float(num_trials)
pylab.plot(range(num_timesteps), trial_results)
pylab.title("Average size of the virus population as a function of time")
pylab.legend(('Average size of virus population'))
pylab.xlabel("Time (Hours)")
pylab.ylabel("Average population")
pylab.show()
#
# PROBLEM 4
#
class ResistantVirus(SimpleVirus):
"""
Representation of a virus which can have drug resistance.
"""
def __init__(self, max_birth_prob, clear_prob, resistances, mut_prob):
"""
Initialize a ResistantVirus instance, saves all parameters as attributes
of the instance.
max_birth_prob: Maximum reproduction probability (a float between 0-1)
clear_prob: 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. {'fredonol':False, 'anadex':False}, means that this virus
particle is resistant to neither fredonol nor anadex.
mut_prob: Mutation probability for this virus particle (a float). This is
the probability of the offspring acquiring or losing resistance to a drug.
"""
# do I need to bring in simplevirus and then re-assosciate all variables? whats the pt?
SimpleVirus.__init__(self, max_birth_prob, clear_prob)
self.resistances = resistances
self.mut_prob = mut_prob
def is_resistant_to(self, drug):
"""
Get the state of this virus particle's resistance to a drug. This method
is called by get_resist_pop() 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.
"""
try:
return self.resistances[drug]
except KeyError:
return False
def reproduce(self, pop_density, active_drugs):
"""
Stochastically determines whether this virus particle reproduces at a
time step. Called by the update() method in the TreatedPatient class.
A virus particle will only reproduce if it is resistant to ALL the drugs
in the active_drugs list. For example, if there are 2 drugs in the
active_drugs list, and the virus particle is resistant to 1 or no drugs,
then it will NOT reproduce.
Hence, if the virus is resistant to all drugs
in active_drugs, then the virus reproduces with probability:
self.max_birth_prob * (1 - pop_density).
If this virus particle reproduces, then reproduce() creates and returns
the instance of the offspring ResistantVirus (which has the same
max_birth_prob and clear_prob values as its parent).
For each drug resistance trait of the virus (i.e. each key of
self.resistances), the offspring has probability 1-mut_prob of
inheriting that resistance trait from the parent, and probability
mut_prob of switching that resistance trait in the offspring.
For example, if a virus particle is resistant to fredonol but not
anadex, and self.mut_prob is 0.1, then there is a 10% chance that
that the offspring will lose resistance to fredonol and a 90%
chance that the offspring will be resistant to fredonol.
There is also a 10% chance that the offspring will gain resistance to
anadex and a 90% chance that the offspring will not be resistant to
anadex.
pop_density: the population density (a float), defined as the current
virus population divided by the maximum population
active_drugs: a list of the drug names acting on this virus particle
(a list of strings).
returns: a new instance of the ResistantVirus class representing the
offspring of this virus particle. The child should have the same
max_birth_prob and clear_prob values as this virus. Raises a
NoChildException if this virus particle does not reproduce.
"""
# check if resistant to all drugs in the active_drugs list
check_reproduce = 0
for drug in active_drugs:
if (self.is_resistant_to(drug) == True):
pass
else:
check_reproduce += 1
raise NoChildException()
if (check_reproduce == 0):
# reproduce with the below probability
if random.random() < (self.max_birth_prob * (1 - pop_density)):
passed_resistance = {}
for elem in self.resistances:
if (self.is_resistant_to(elem) == True):
if random.random() <= self.mut_prob:
passed_resistance[elem] = False
else:
passed_resistance[elem] = True
elif (self.is_resistant_to(elem) == False):
if random.random() <= self.mut_prob:
passed_resistance[elem] = True
else:
passed_resistance[elem] = False
return ResistantVirus(self.max_birth_prob, self.clear_prob, passed_resistance, self.mut_prob)
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, max_pop):
"""
Initialization function, saves the viruses and max_pop 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)
max_pop: The maximum virus population for this patient (an integer)
"""
### always do this? ...even if I am going to make all new classes for treatedpatient? why?
Patient.__init__(self, viruses, max_pop)
self.druglist = []
# why does druglist have to have "self." when it is not part of init entered vars?
def add_prescription(self, new_drug):
"""
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
new_drug is already prescribed to this patient, the method has no effect.
new_drug: 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 new_drug in self.druglist:
pass
else:
self.druglist.append(new_drug)
def get_prescriptions(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.druglist
def get_resist_pop(self, drug_resist):
"""
Get the population of virus particles resistant to the drugs listed in
drug_resist.
drug_resist: Which drug resistances to include in the population (a list
of strings - e.g. ['fredonol'] or ['fredonol', 'anadex'])
returns: The population of viruses (an integer) with resistances to all
drugs in the drug_resist list.
"""
resistant_pop = 0
for virus in self.viruses:
resist_check = 0
for drug in drug_resist:
if virus.is_resistant_to(drug):
resist_check += 1
if len(drug_resist) == resist_check:
resistant_pop += 1
return resistant_pop
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().
- 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)
"""
survive_list = []
# for loop to append only viruses that clear .does_clear
for virus in self.viruses:
if virus.does_clear() == False:
survive_list.append(virus)
reproduce_list = []
pop_density = (self.get_total_pop())/(float(self.max_pop))
# for loop to add viruses that reproduce
for survived_virus in survive_list:
try:
possible_v = survived_virus.reproduce(pop_density, self.druglist)
reproduce_list.append(possible_v)
except NoChildException:
pass
# add the survivors to the reproduced
self.viruses = survive_list + reproduce_list
return len(self.viruses)
#
# PROBLEM 5
#
def simulation_with_drug(num_viruses, max_pop, max_birth_prob, clear_prob, resistances,
mut_prob, num_trials):
"""
Runs simulations and plots graphs for problem 5.
For each of num_trials trials, instantiates a patient, runs a simulation for
120 timesteps, adds fredonol, and runs the simulation for an additional
180 timesteps. At the end plots the average virus population size
(for both the total virus population and the fredonol-resistant virus
population) as a function of time.
As mentioned above create ONE plot that has the following 2 curves on it.
(i) The average total virus population over time
(ii) The average population of ìfredonolî-resistant virus population over time.
Note: The 2 curves should be on the same plot.
num_viruses: number of ResistantVirus to create for patient (an integer)
max_pop: maximum virus population for patient (an integer)
max_birth_prob: Maximum reproduction probability (a float between 0-1)
clear_prob: maximum clearance probability (a float between 0-1)
resistances: a dictionary of drugs that each ResistantVirus is resistant to
(e.g., {'fredonol': False})
mut_prob: mutation probability for each ResistantVirus particle
(a float between 0-1).
num_trials: number of simulation runs to execute (an integer)
"""
# making a variable for timesteps
num_timesteps = 300
timesteps_p1 = 120
timesteps_p2 = 180
### trial part 1
# create a list that can have results added to it for averaging at end
trial_results = []
for values in range(num_timesteps):
trial_results.append(0)
# and a list for the resistancies to plot fredonol-resistant virus population
resistancies = []
for values in range(num_timesteps):
resistancies.append(0)
# instantiate patients through list and run them through timesteps
for case in range(num_trials):
virus_init_list = []
for num in range(num_viruses):
virus_init_list.append(ResistantVirus(max_birth_prob, clear_prob, resistances, mut_prob))
instance_patient = TreatedPatient(virus_init_list, max_pop)
for update_instance in range(timesteps_p1):
trial_results[update_instance] += instance_patient.update()
resistancies[update_instance] += instance_patient.get_resist_pop(['fredonol'])
instance_patient.add_prescription("fredonol")
for update_instance2 in range(timesteps_p2):
trial_results[update_instance2 + timesteps_p1] += instance_patient.update()
resistancies[update_instance2 + timesteps_p1] += instance_patient.get_resist_pop(['fredonol'])
# get average for total population
for step in range(len(trial_results)):
trial_results[step] = trial_results[step]/float(num_trials)
# get average for resistant populations
for step in range(len(resistancies)):
resistancies[step] = resistancies[step]/float(num_trials)
pylab.plot(range(num_timesteps), trial_results)
pylab.plot(range(num_timesteps), resistancies)
pylab.title("Average size of the virus population as a function of time")
pylab.legend(('Average size of virus population', 'Average size of fredonol resistant population'))
pylab.xlabel("Time (Hours)")
pylab.ylabel("Average population")
pylab.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment