-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathps8b.py
executable file
·636 lines (532 loc) · 23.2 KB
/
ps8b.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# Problem Set 8: Simulating the Spread of Disease and Virus Population Dynamics
import numpy
import random
import pylab
'''
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 can 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, 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
# TODO
def getMaxBirthProb(self):
"""
Returns the max birth probability.
"""
return self.maxBirthProb
# TODO
def getClearProb(self):
"""
Returns the clear probability.
"""
return self.clearProb
# TODO
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
else:
return False
# TODO
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)):
return SimpleVirus(self.getMaxBirthProb(), self.getClearProb())
else:
raise NoChildException
# TODO
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
# TODO
def getViruses(self):
"""
Returns the viruses in this Patient.
"""
# TODO
return self.viruses
def getMaxPop(self):
"""
Returns the max population.
"""
# TODO
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.viruses)
# TODO
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)
"""
# TODO
#1
survivors = []
for virus in self.getViruses():
if not virus.doesClear():
survivors.append(virus)
self.viruses = survivors
#2
popDensity = float(len(self.getViruses()))/self.getMaxPop()
#3
for virus in survivors:
try:
self.viruses.append(virus.reproduce(popDensity))
except NoChildException:
continue
return self.getTotalPop()
'''
virus = SimpleVirus(1.0, 1.0)
patient = Patient([virus], 100)
virus.getClearProb()
virus.getMaxBirthProb()
#virus.reproduce(.5)
patient.getViruses()
patient.getMaxPop()
patient.getTotalPop()
for i in xrange(100):
patient.update()
print patient.getViruses()
'''
#
# PROBLEM 3
#
def simulationWithoutDrug(numViruses=100, maxPop=1000, maxBirthProb=0.1, clearProb=0.05,
numTrials=30):
"""
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)
"""
for trial in range(numTrials):
virusLevelResults = runTrial(300, numViruses, maxPop, maxBirthProb, clearProb)
print trial
if trial == 0: # First trial
# Save results of the first trial
accumulatedVirusLevels = virusLevelResults
else:
# Accumulate second and subsequent results to same list
for i in range(len(virusLevelResults)):
accumulatedVirusLevels[i] += virusLevelResults[i]
# At end of the trials, average the accumulated results over
# the number of trials carried out (see HINT in problem spec.)
for i in range(len(accumulatedVirusLevels)):
accumulatedVirusLevels[i] /= float(numTrials)
# PLOT THE RESULTS OF THE SIMULATION
# Let X-axis scale default to length of Y-values list (301)
pylab.plot(accumulatedVirusLevels, label = 'SampleVirus')
pylab.title('Population of SimpleVirus with '+str(numTrials)+' trials')
pylab.ylabel('Average number of viruses in patient')
pylab.xlabel('Time steps (arbitrary units)')
pylab.legend(loc = 'best')
pylab.show()
# TODO
def runTrial(numTimeSteps, numViruses, maxPop, maxBirthProb, clearProb):
# Create numViruses virus instances with:
# maxBirthProb
# clearProb
# attribute values
viruses = []
for i in xrange(numViruses):
viruses.append(SimpleVirus(maxBirthProb, clearProb))
# Instantiate a patient with the list of numVirus virus instances
# and a Maximum Sustainable Virus Population of maxPop
# one line of code
patient = Patient(viruses, maxPop)
# The following pseudocode simulates, records and returns changes
# to the virus population over elapsedTimeSteps steps.
# Note that the patient has numViruses viruses at start.
virusLevelsThisTrial = []
# NOTE: You SHOULD NOT record the starting level of viruses in the
# patient as the virus population at t=0.
#
# The Problem Statement/Specification for Problem 3 is quite clear.
# It says: "The population at time=0 is the population after the
# first call to update". So the next line of pseudocode should
# not be imnplemented! If you are having problems with the grader
# AND you had implemented the next line, take it out. Your code
# should pass the grader.
#REMOVE THIS LINE# virusLevelsThisTrial.append(...) # numViruses
# Record virus population changes over numTimeSteps number
# of updates. Do the update first then record the virus
# level/population that results.
for i in xrange(numTimeSteps):
patient.update()#... call update() method
virusLevelsThisTrial.append(patient.getTotalPop())#... append to allVirusLevelsThisTrial # use the getter method
# Note: in the above we can roll those two steps into one by
# appending directly the value returned by update().
# But see the "Discussion Section" later on for the
# reason I adopt the former approach.
return virusLevelsThisTrial # a list with numTimeStep values (300)
#
# PROBLEM 4
#
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.
"""
self.resistances = resistances
self.mutProb = mutProb
SimpleVirus.__init__(self, maxBirthProb, clearProb)
# TODO
def getResistances(self):
"""
Returns the resistances for this virus.
"""
# TODO
return self.resistances
def getMutProb(self):
"""
Returns the mutation probability for this virus.
"""
# TODO
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.
"""
try:
return self.getResistances()[drug]
except KeyError:
return False
# TODO
def reproduce(self, popDensity, activeDrugs):
"""
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 activeDrugs list. For example, if there are 2 drugs in the
activeDrugs 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 activeDrugs, then the virus reproduces with probability:
self.getMaxBirthProb * (1 - popDensity).
If this virus particle reproduces, then reproduce() creates and returns
the instance of the offspring ResistantVirus (which has the same
maxBirthProb and clearProb values as its parent). The offspring virus
will have the same maxBirthProb, clearProb, and mutProb as the parent.
For each drug resistance trait of the virus (i.e. each key of
self.resistances), the offspring has probability 1-mutProb of
inheriting that resistance trait from the parent, and probability
mutProb of switching that resistance trait in the offspring.
For example, if a virus particle is resistant to guttagonol but not
srinol, and self.mutProb is 0.1, then there is a 10% chance that
that the offspring will lose resistance to guttagonol and a 90%
chance that the offspring will be resistant to guttagonol.
There is also a 10% chance that the offspring will gain resistance to
srinol and a 90% chance that the offspring will not be resistant to
srinol.
popDensity: the population density (a float), defined as the current
virus population divided by the maximum population
activeDrugs: 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
maxBirthProb and clearProb values as this virus. Raises a
NoChildException if this virus particle does not reproduce.
"""
isResistantToActiveDrugs = True
for drug in activeDrugs:
if not self.isResistantTo(drug):
isResistantToActiveDrugs = False
break
else:
continue
if isResistantToActiveDrugs and (random.random() <= (self.getMaxBirthProb() * (1 - popDensity))) :
offspringResistances = {}
for drug in self.getResistances().keys():
resistanceDict = self.getResistances()
if resistanceDict[drug]:
if random.random()<(1-self.getMutProb()):
offspringResistances[drug] = True
else:
offspringResistances[drug] = False
else:
if random.random()<self.getMutProb():
offspringResistances[drug] = True
else:
offspringResistances[drug] = False
return ResistantVirus(self.getMaxBirthProb(), self.getClearProb(), offspringResistances, self.getMutProb())
else:
raise NoChildException
# TODO
'''
a = ResistantVirus(.99,.01,{'srinol':True}, .2)
j=0
for i in xrange(100):
try:
a.reproduce(.1, [])
print j
j+=1
except NoChildException:
continue
'''
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)
"""
self.prescriptions = []
Patient.__init__(self, viruses, maxPop)
# TODO
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 not in self.getPrescriptions():
self.prescriptions.append(newDrug)
# TODO
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.prescriptions
# TODO
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.getViruses():
for drug in drugResist:
if virus.isResistantTo(drug):
count += 1
return count
# TODO
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)
"""
#1
survivors = []
for virus in self.getViruses():
if not virus.doesClear():
survivors.append(virus)
self.viruses = survivors
#2
popDensity = float(len(self.getViruses()))/self.getMaxPop()
#3
for virus in survivors:
try:
self.viruses.append(virus.reproduce(popDensity, self.getPrescriptions()))
except NoChildException:
continue
return self.getTotalPop()
# TODO
#
# PROBLEM 5
#
def simulationWithDrug(numViruses = 10, maxPop = 1000, maxBirthProb = .9, clearProb = .2, resistances = {'guttagonol':True, 'srinol':True},
mutProb = .9, numTrials = 10):
"""
Runs simulations and plots graphs for problem 5.
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)
"""
# TODO
for trial in range(numTrials):
(totalVirusResult, resistantVirusResult) = runTrial2(150, 150,
numViruses, maxPop,
maxBirthProb, clearProb,
resistances, mutProb)
if trial == 0: # First trial
# Save results of the first trial...
totalVirusPop = totalVirusResult
resistantVirusPop = resistantVirusResult
else:
# ...then accumulate second and subsequent sets
for i in range(len(totalVirusResult)):
totalVirusPop[i] += totalVirusResult[i]
resistantVirusPop[i] += resistantVirusResult[i]
# End of the numTrial trials. Average the results accumulated during
# the trials over the number of trials. (See HINT in problem spec.)
for i in range(len(totalVirusPop)):
totalVirusPop[i] /= float(numTrials)
resistantVirusPop[i] /= float(numTrials)
# PLOT THE RESULTS OF THE SIMULATION AS TWO PLOTS
# Let X-axis scale default to length of Y-values lists (300)
# Here is how we deal with plotting two sets of y-values
pylab.plot(totalVirusPop, label = 'TotalVirusPop')
pylab.plot(resistantVirusPop, label = 'ResistantVirusPop')
pylab.title('Population of SimpleVirus with '+str(numTrials)+' trials')
pylab.ylabel('Average number of viruses in patient')
pylab.xlabel('Time steps (arbitrary units)')
pylab.legend(loc = 'best')
pylab.show()
def runTrial2(numTimeSteps1, numTimeSteps2,
numViruses, maxPop,
maxBirthProb, clearProb,
resistances, mutProb):
# Create numViruses virus instances with specified:
# maxBirthProb
# clearProb
# resistances
# mutProb
# attribute values
viruses = []
for i in xrange(numViruses):
viruses.append(ResistantVirus(maxBirthProb, clearProb, resistances, mutProb))
# Instantiate a patient with the list of numVirus virus instances
# and a Maximum Sustainable Virus Population of maxPop
patient = TreatedPatient(viruses, maxPop) # one line of code
# Simulate changes to the virus population over elapsedTimeSteps
# steps.
# The patient has numViruses virus level at start.
allVirusLevelsThisTrial = []
resistantVirusLevelsThisTrial = []
# Record starting level of viruses in patient...
# NO! See the BEWARE! comments above..
#REMOVE LINE# allVirusLevelsThisTrial.append(...) # total virus...
#REMOVE LINE# resistantVirusLevelsThisTrial.append(...) # resistant virus...
# Record virus population changes over numTimeSteps1
# number of updates. Do the update first then record the
# two virus populations of interest that results.
for i in xrange(numTimeSteps1):
patient.update()#... call update() method
allVirusLevelsThisTrial.append(patient.getTotalPop())#... append to allVirusLevelsThisTrial # use the getter method
# Note below, looking at virus population resistant to 'guttagonol'
resistantVirusLevelsThisTrial.append(patient.getResistPop(['guttagonol'])) # use the getter method
# Add the drug 'guttagonol' to the patient and run a further
# numTimeSteps2 number of updates
patient.addPrescription('guttagonol')
for i in xrange(numTimeSteps2):
patient.update()#... call update() method
allVirusLevelsThisTrial.append(patient.getTotalPop())#... append to allVirusLevelsThisTrial # use the getter method
# Note below, looking at virus population resistant to 'guttagonol'
resistantVirusLevelsThisTrial.append(patient.getResistPop(['guttagonol'])) # use the getter method
return (allVirusLevelsThisTrial, resistantVirusLevelsThisTrial)