-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation.py
1854 lines (1647 loc) · 73.5 KB
/
simulation.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# ReliefSim Prototype programmed by Eric Mattes
# October 2006
version = "1.1"
import string
import time
import os
import os.path
import copy
from random import Random
g = Random()
class UI:
"""the user interface to the game."""
def __init__(self, sim):
self.shortcut = {
"ap": AssessRefugeePopulation,
"aw": AssessCampWaterSupplyDemand,
"aq": AssessCampWaterQuality,
"af": AssessRefugeeFoodSupplyDemand,
"adm": AssessRefugeeMeasles,
"adf": AssessRefugeeMalnourished,
"adc": AssessRefugeeCholera,
"add": AssessRefugeeDiarrhea,
"ade": AssessRefugeeMeningitis,
"ada": AssessRefugeeMalaria,
"as": AssessCampLatrines,
"iw": AddCampWaterQuantity,
"iq": AddCampWaterQuality,
"id": AddCampLatrineDefTrench,
"ic": AddCampLatrineCommPit,
"itf": SetUpSuppFeedingCenter,
"if": AddCampFoodQuantity,
"ad": AssessRefugeeMedicalProfile,
"itm": TreatMeasles,
"itc": TreatCholeraAndDiarrhea,
"ite": TreatMeningitis,
"ita": TreatMalaria,
"ivm": VaccinateMeasles,
"ivc": VaccinateCholera,
"ive": VaccinateMeningitis
}
self.specialShortcut = {"endTurn": "endTurn", "unAssign": "unassign"}
self.population = ""
self.flag = "false"
self.gaintHighlightedItems = ""
self.systemTime = time.strftime("%m/%d")
self.sim = sim
self.messages = [] # a list of messages for the user to see
self.known = {} # dictionary for known info
self.bd = {} # dictionary for known info about population breakdown
# 'gauges' and 'bdGauges' are for formatting classifications
# and for putting '?' in for unknowns
self.gauges = [
"refugees.nutritionalDemand", "refugees.waterDemand",
"camp.waterQuality", "camp.waterQuantity",
"camp.solidWaste", "camp.latrinesDefTrench",
"camp.foodQuantity", "camp.suppFeedingCenters",
"camp.latrinesCommPit", "refugees.immMeasles",
"refugees.immCholera", "refugees.immMeningitis"
] # internal names for gauges/keys
self.bdGauges = [
"population", "cholera", "diarrhea", "measles", "malnourished",
"meningitis", "malaria", "dead"
] # population breakdown
self.assembleMenuString()
def assembleMenuString(self):
"""assembles the menu by filling in the gauges, team members,
and message information"""
self.newMenu = ""
self.newStatus = ""
self.newMessage = "Message: "
# format the data from infoStore and store it into a 'local' dictionary
for refcamp in ("refugees", "camp"):
for k in getattr(self.sim.action.infoStore, refcamp).keys():
temp = getattr(self.sim.action.infoStore, refcamp)[k]
if (refcamp + "." + k) in self.gauges:
# the normal gauges
if type(temp) == float:
if float(temp) % 1000.0 == 0.0 and temp != 0:
temp = ("%(temp).0f" % vars())[:-3] + "k"
else:
temp = ("%(temp).2f") % vars()
elif type(temp) == int:
if float(temp) % 1000.0 == 0.0 and temp != 0:
temp = str(temp)[:-3] + "k"
else:
temp = str(temp)
self.known[refcamp + "." + k] = string.rjust(temp, 7)
else:
# the population breakdown gauges
self.bd[k] = copy.deepcopy(temp)
for i in range(len(self.bd[k])):
self.bd[k][i] = string.rjust(str(self.bd[k][i]), 6)
for k in self.gauges:
# fill in unknown info with a '?'
if k not in self.known.keys():
self.known[k] = "?"
for k in self.bdGauges:
# fill in unknown info with a '?'
if k not in self.bd.keys():
self.bd[k] = ["?", "?", "?", "?"]
self.infoGauge = (
"foodQuantity:: " + self.known["camp.foodQuantity"]
+ "$$" + "waterQuantity:: "
+ self.known["camp.waterQuantity"]
+ "$$" + "nutritionalDemand:: "
+ self.known["refugees.nutritionalDemand"]
+ "$$" + "waterDemand:: "
+ self.known["refugees.waterDemand"]
+ "$$" + "solidWaste:: "
+ self.known["camp.solidWaste"]
+ "$$" + "waterQuality:: "
+ self.known["camp.waterQuality"]
+ "$$" + "latrinesCommPit:: "
+ self.known["camp.latrinesCommPit"]
+ "$$" + "suppFeedingCenters:: "
+ self.known["camp.suppFeedingCenters"]
+ "$$" + "latrinesDefTrench:: "
+ self.known["camp.latrinesDefTrench"])
for bdName in ["population", "dead", "malnourished",
"cholera", "diarrhea", "malaria",
"measles", "meningitis"]:
x = self.bd[bdName]
self.newMenu += (bdName + ":: " + x[0] + "@@" + x[1] + "@@"
+ x[2] + "@@" + x[3] + "$$")
if(self.flag == "true"):
self.population = (self.population + "$$"
+ self.bd["population"][0]
+ "@@" + self.bd["population"][1]
+ "@@" + self.bd["population"][2]
+ "@@" + self.bd["population"][3])
self.tempTime = time.strptime(time.strftime("%Y-%m-%d %H:%M:%S"),
"%Y-%m-%d %H:%M:%S")
self.tempSysTime = time.mktime(self.tempTime)
self.tempSysTime = (self.tempSysTime
+ (3 * 24 * 60 * 60)
* (self.sim.probability.turn - 1))
self.tempSysTime = time.strftime(
"%m/%d",
time.localtime(self.tempSysTime))
self.systemTime = self.systemTime + "$$" + self.tempSysTime
self.flag = "false"
i = 1
for x in self.sim.action.resource.personnel:
temp = x.name + ':'
self.newStatus += temp
if x.getDaysBusy() != 0:
self.newStatus += ("Busy " + x.task.statusText
+ " for " + str(x.getDaysBusy())
+ " more turn")
if x.getDaysBusy() > 1:
self.newStatus += "s"
self.newStatus += ": " + x.taskId
else:
self.newStatus += "available"
self.newStatus += "@@"
i += 1
self.isPersonnelFree = "true"
for x in self.sim.action.resource.personnel:
if x.getDaysBusy() != 0:
self.isPersonnelFree = "false"
else:
self.isPersonnelFree = "true"
break
if(self.isPersonnelFree == "false"):
self.sim.action.infoStore.messages.append(self.isPersonnelFree)
for x in self.sim.action.infoStore.messages:
self.messages.append(x)
for x in self.messages:
self.newMessage += x + "\n"
self.sim.action.infoStore.messages = [] # clear the infostore messages
self.messages = [] # clear the interface messages
self.newMenu += ("##" + self.newStatus + "##"
+ self.newMessage + "##"
+ self.infoGauge + "##"
+ str(self.sim.probability.turn)
+ "##" + self.population
+ "##" + self.systemTime
+ "##" + self.gaintHighlightedItems)
def process(self, input):
""" process the input by translating the keyboard
shortcut into the corresponding command"""
inputValue = (input).split("split")
inputCommond = inputValue[0]
userId = inputValue[1]
self.processRequest(inputCommond, userId)
def processRequest(self, inputCommond, userId):
if inputCommond in self.specialShortcut.keys():
if inputCommond.endswith("endTurn"):
# execute the input command
getattr(self.sim.action,
self.specialShortcut[inputCommond])()
self.gaintHighlightedItems = (self.gaintHighlightedItems
+ "$$" + userId)
self.sim.action.infoStore.messages.append(
"Your team members have performed their tasks and are "
"ready for new assignments. Be sure to check your "
"information gauges for new data, if necessary.")
self.flag = "true"
else:
self.sim.action.unassign(userId)
else:
# assign a task to somebody in your personnel
endAfterCommand = 0
if inputCommond.endswith("endTurn"):
endAfterCommand = 1
inputCommond = inputCommond[:-1] # cut off the '.'
if inputCommond not in self.shortcut.keys():
self.messages.append("Unrecognized command. Try again.")
else:
self.sim.action.assignTask(
self.shortcut[inputCommond], userId, inputCommond)
if endAfterCommand == 1:
self.sim.action.endTurn()
def exportHistory(self):
"""write the history data to a file"""
# format:
# [ [[titles],[breakdownTitles],[personnelNames]], \
# ([data],[[bd1,bd2],...],[tasks]), ... ]
t = time.localtime()
hist = self.sim.action.infoStore.history
fileName = "rs_hist%02u%02u%02u%02u%02u.txt" % (
t[0], t[1], t[2], t[3], t[4])
try:
if not os.path.exists('history/'):
os.mkdir('history')
f = open('history/' + fileName, 'w+')
# loop thru names of stat categories
f.write("\t")
(titles, bd, pn) = hist[0]
for t in titles:
f.write("%s\t" % (t))
for cat in bd:
f.write(
"Total %s\t%s Ages < 5\t%s Ages 5-14\t%s Ages 15+\t" % (
cat, cat, cat, cat))
for p in pn:
f.write("%s\t" % (p))
f.write("\n")
# write the data
for turn in range(1, len(hist)):
f.write("Turn %d\t" % (turn))
(data, bd, tasks) = hist[turn]
for stat in data:
if type(stat) == float:
f.write("%.2f\t" % (stat))
else:
f.write("%s\t" % (stat))
for stat in bd:
for i in range(len(stat)):
temp = stat[i]
if type(temp) == float:
f.write("%.2f" % (temp))
else:
f.write("%s\t" % (temp))
for task in tasks:
f.write("%s\t" % (task))
f.write("\n")
f.close()
except OSError:
print ("An error occurred. The history log "
"file could not be written.")
def doEndGame(self):
"""do whatever needs to be done after the game ends"""
self.exportHistory()
print self.style(9)
if self.sim.probability.gameOver == 1:
print "Sorry, all of your refugees have died! Game over!\n"
else:
print "Thanks for playing!\n"
print self.style(0) # reset colors
class WebUI(UI):
""" override some of the UI functionality for the web interface """
def style(self, arg):
return ""
def doEndGame(self):
data = self.exportHistory()
dead = self.sim.probability.gameOver == 1
return (dead, data)
def exportHistory(self):
# TODO: use actual csv module
# format: [ [[titles],[breakdownTitles],[personnelNames]],
# ([data],[[bd1, bd2],...],[tasks]), ... ]
t = time.localtime()
hist = self.sim.action.infoStore.history
from cStringIO import StringIO
f = StringIO()
# loop thru names of stat categories
f.write(", ")
(titles, bd, pn) = hist[0]
for t in titles:
f.write("%s," % (t))
for cat in bd:
f.write("Total %s,%s Ages < 5,%s Ages 5-14,%s Ages 15+, " % (
cat, cat, cat, cat))
for p in pn:
f.write("%s," % (p))
f.write("\n")
# write the data
for turn in range(1, len(hist)):
f.write("Turn %d," % (turn))
(data, bd, tasks) = hist[turn]
for stat in data:
if type(stat) == float:
f.write("%.2f," % (stat))
else:
f.write("%s," % (stat))
for stat in bd:
for i in range(len(stat)):
temp = stat[i]
if type(temp) == float:
f.write("%.2f" % (temp))
else:
f.write("%s," % (temp))
for task in tasks:
f.write("%s," % (task))
f.write("\n")
return f.getvalue()
######### END PRESENTATION/INTERFACE; BEGIN SIMULATION CODE ##########
class Simulation:
"""the mother-class for the simulation.
Seperate from the presentation/interface."""
def __init__(self):
self.refugees = Refugees(self)
self.camp = Camp(self)
self.probability = Probability(self)
self.action = Action(self)
self.scenario = Scenario(self.action)
class Action:
"""contains the 'API' for interacting with the simulation"""
def __init__(self, sim):
self.resource = Resource()
self.infoStore = InfoStore()
self.sim = sim
self.probability = self.sim.probability
self.camp = self.sim.camp
self.refugees = self.sim.refugees
# auto-updating data is stuff that the user is entitled
# to know every turn without assessing for it
self.autoUpdating = [
"camp.suppFeedingCenters",
"refugees.immMeasles",
"refugees.immCholera",
"refugees.immMeningitis"]
# hints are only given once, after which they turn into a 1
self.hints = {"cholera": 0}
def assignTask(self, task, userId, taskId):
"""try to assign a task to somebody on your personnel"""
personnelObj = self.sim.action.resource.personnel
userId = int(userId)
if personnelObj[userId].task is None:
# assign a new instance of the task
personnelObj[userId].assign(task(self.sim))
personnelObj[userId].taskId = taskId
else:
self.infoStore.messages.append(
"No personnel are available to perform that task")
def initHistory(self):
"""initialize the history data structure"""
personnel = []
for p in self.sim.action.resource.personnel:
personnel.append(p.name)
titles = [
"General Health (avg)",
"Nutritional Health (avg)",
"Disease Health (avg)",
"Symptomatic", "Sick",
"Food Supply", "Avg Food Demand", "Supp. Feeding Centers",
"Water Quality",
"Water Supply", "Avg Water Demand", "Refugees w/o Latrines",
"Defecation Trenches", "Community Pits"]
bdTitles = [
"Population", "Dead*", "Cholera", "Diarrhea", "Malaria",
"Measles", "Meningitis", "Malnourished",
"Died with Cholera*", "Died with Diarrhea*",
"Died with both Cholera and Diarrhea*"]
self.infoStore.history.append([titles, bdTitles, personnel])
def storeHistory(self, camp, refugees):
"""load the current gamestate into the history list"""
# THIS DOES NOT INCLUDE SPECIFIC ILLNESS DATA
# AND SHOULD NOT BE USED TO SAVE THE GAMESTATE
c = self.camp.data
r = self.refugees.data
data = []
bd = []
taskSelection = []
for p in self.sim.action.resource.personnel:
if p.task is None:
taskSelection.append("None")
else:
taskSelection.append(p.task.statusText)
for itemName in ("population", "dead", "cholera", "diarrhea",
"malaria", "measles", "meningitis",
"malnourished", "diedWithCholera",
"diedWithDiarrhea", "diedWithBothCDD"):
item = r[itemName]
bd.append([item[0], item[1], item[2], item[3]])
data.extend([r["generalHealth"], r["nutritionalHealth"],
r["diseaseHealth"]])
data.extend([r["symptomatic"], r["sick"]])
data.extend([c["foodQuantity"], r["nutritionalDemand"],
c["suppFeedingCenters"]])
data.extend([c["waterQuality"], c["waterQuantity"], r["waterDemand"]])
data.extend([c["solidWaste"], c["latrinesDefTrench"],
c["latrinesCommPit"]])
self.infoStore.history.append((data, bd, taskSelection))
def updateInfoStore(self):
"""auto-update the infoStore to contain data the
user is always supposed to know"""
for i in self.autoUpdating:
(c, a) = i.split(".")
if c == "refugees":
self.infoStore.refugees[a] = self.probability.getRefugees(a)
elif c == "camp":
self.infoStore.camp[a] = self.probability.getCamp(a)
############ BEGIN NON-TASK 'SPECIAL' COMMANDS ############
def endTurn(self):
"""ends the turn"""
self.probability.endTurn()
def unassign(self, userId):
"""frees up a worker and cancels the task s/he was working on"""
userId = int(userId)
personnelObject = self.sim.action.resource.personnel
# free up the person and 'cancel' the task
personnelObject[userId].task = None
############### BEGIN TASK-HELPER COMMANDS ###########
def choleraHint(self):
"""if there is cholera present, display a hint"""
if (self.sim.refugees.data["cholera"][3] > 0
and self.hints["cholera"] == 0):
self.sim.action.infoStore.messages.append(
"A 22-year-old man has died of dehydration")
self.hints["cholera"] = 1
def addDefTrenchExpiration(self, num):
"""set 'num' deftrenches to expire in the designated number of turns"""
num = int(num[0])
self.camp.defTrenchExpiration.append([self.camp.defTrenchLifespan,
num])
def revealLatrineInfo(self):
"""put latrine info in the infoStore. Happens when building latrines"""
dummyAssessment = AssessLatrinesOnly(self.sim) # create a fake task...
dummyAssessment.do() # and then execute it immediately
def treatSickHelper(self, diseaseTuple):
"""distributes treatment among symptomatic sick people"""
# this treats in the order they were infected... not entirely realistic
# the number of people who can be treated in one turn by one person
number = 2000
dName = diseaseTuple[0]
refugeesRef = self.refugees
index = 0
for r in refugeesRef.pop:
if number > 0:
if dName in r.symptoms and g.random() <= 0.70:
# 70% chance of successful removal
for d in r.diseases:
if d.name == dName:
refugeesRef.removeDisease(r, index, d)
number -= 1
else:
break # we have treated the maximum number
index += 1
def treatWater(self):
"""treat the water quality. Effect wears off after a few turns"""
self.sim.camp.treatments[0] += 1
def vaccinate(self, diseaseTuple):
"""vaccinates some refugees against a disease"""
dName = diseaseTuple[0]
delay = diseaseTuple[1] # immunity delay of this vaccine
howMany = 2500
remaining = howMany
if dName == "measles":
# measles vaccine treats as well as immunizes (permanent immunity)
# kidsFirst ensures that children under 15 get their
# measles vaccine before anyone else.
kidsFirst = 1
while (1):
index = -1
for r in self.refugees.pop:
index += 1
if ((r.age < 15 or kidsFirst == 0)
and "measles" not in r.immunized):
# give them permanent immunity:
r.immunized.append("measles")
remaining -= 1
#### TREATMENT ####
for d in r.diseases:
if d.name == "measles":
self.refugees.removeDisease(r, index, d)
if remaining <= 0:
break
# if, after checking each child, we still have vaccines,
# do this loop one more time and vaccinate adults
if remaining > 0 and kidsFirst == 1:
kidsFirst = 0
else:
break
else:
# not measles...
for r in self.refugees.pop:
if dName not in r.immunized:
# check for existing immunity
for x in r.immunityCountdown:
if x[1] == dName:
break # check for pending immunity
else:
# if they are not immune and not pending immunity,
# vaccinate
r.immunityCountdown.append([delay, dName])
remaining -= 1
if remaining <= 0:
break
if remaining < howMany:
# increment the vaccine counters
statKey = "imm" + string.upper(dName[0]) + dName[1:]
self.sim.refugees.data[statKey] += howMany - remaining
###### BEGIN SCRIPT-ONLY COMMANDS (take 1 string parameter) ######
def addFood(self, num):
"""increases the daily food supply by the specified amount"""
self.camp.data["foodQuantity"] += int(num)
def addPersonnel(self, num):
"""add Personnel to your staff"""
numExisting = len(self.resource.personnel)
max = self.resource.maxPersonnel
num = int(num)
if numExisting + num > max:
# are we going to go over the limit?
if max - numExisting > 0:
# if we can add some but not all of the requested staff...
num = max - numExisting
else:
return # can't add any more
if num == 1:
sentenceStarting = ""
sentenceEnding = " person has joined your staff!"
else:
sentenceStarting = "Use your "
sentenceEnding = (
" staff members to protect and stabilize "
"this camp population in as few turns as "
"possible. Each turn is 3 days.<span "
"class='welcomeMessage'>Select either an "
"assessment or an intervention by clicking on it. Then click "
"the \"ASSIGN\" button next to a member of your staff. "
"When you have finished assigning tasks, have your team "
"perform them by hitting the \"END TURN\" button.</span>")
self.infoStore.messages.append(
sentenceStarting + str(num) + sentenceEnding)
for x in range(num):
p = Personnel()
self.resource.personnel.append(p)
if self.probability.turn > 0:
# append their name to the history header list
self.infoStore.history[0][2].append(p.name)
def addRefugees(self, num):
"""add refugees to the camp"""
self.refugees.addRandomizedRefugees(num) # pass along the task
if num == 1:
self.infoStore.messages.append(
"New Refugees have joined your camp!")
def addWater(self, num):
"""increases the daily water supply by the specified amount"""
self.camp.data["waterQuantity"] += int(num)
def feedingCenterMeaslesOutbreak(self):
""" if this is our first feeding center, schedule a measles
outbreak in two turns"""
# +1 will make it happen at the END of the next turn.
turn = self.sim.probability.turn + 1
script = self.sim.scenario.script
self.sim.camp.measlesOutbreak = 1
if turn in script.keys():
script[turn].append("measlesOutbreak 10")
else:
script[turn] = ["measlesOutbreak 10"]
def measlesOutbreak(self, numCases):
"""cause an outbreak of measles in the lowest age bracket"""
numCases = int(numCases)
lenRef = len(self.refugees.pop)
vector = Measles()
# starting at the beginning, infect only those under 5,
# stopping after numCases.
for i in range(lenRef):
person = self.refugees.pop[i]
if person.age < 5:
self.refugees.infect(i, vector)
if numCases > 1:
numCases -= 1
else:
break
############# END NON-TASK COMMANDS #############
class Task:
"""Something that occupies a person's time"""
def __init__(self, sim, daysToComplete, statusText):
self.daysToComplete = daysToComplete
self.statusText = statusText
self.daysRemaining = self.daysToComplete
self.sim = sim
self.beforeFunc = [] # a list of function names to call first
self.afterFunc = [] # a list of function names to call last
def do(self):
pass # override this method when inheriting!
def timePass(self):
"""subtract a day from the days remaining counter"""
self.daysRemaining -= 1
class Assessment(Task):
"""an assessment of the conditions of the camp/refugees"""
def __init__(self, sim, daysToComplete, statusText, properties):
Task.__init__(self, sim, daysToComplete, statusText)
self.properties = properties
self.isa = "assessment"
def do(self):
for (func, arg) in self.beforeFunc:
# calls each designated function
getattr(self.sim.action, func)(arg)
for x in self.properties:
(c, a) = x.split(".")
if c == "refugees":
self.sim.action.infoStore.refugees[a] = copy.deepcopy(
self.sim.probability.getRefugees(a))
elif c == "camp":
self.sim.action.infoStore.camp[a] = copy.deepcopy(
self.sim.probability.getCamp(a))
for stuff in self.afterFunc:
if len(stuff) == 1:
# calls the designated function
getattr(self.sim.action, stuff[0])()
else:
# calls it with a tuple of arguments
getattr(self.sim.action, stuff[0])(stuff[1:])
class Intervention(Task):
"""an action meant to change a condition of the camp or the refugees"""
def __init__(self, sim, daysToComplete, statusText, propertyPairs):
Task.__init__(self, sim, daysToComplete, statusText)
# a list of doubles in the form ("area.property", amount)
self.propertyPairs = propertyPairs
self.isa = "intervention"
def do(self):
for stuff in self.beforeFunc:
if len(stuff) == 1:
# calls the designated function
getattr(self.sim.action, stuff[0])()
else:
# calls it with a tuple of arguments
getattr(self.sim.action, stuff[0])(stuff[1:])
for (x, y) in self.propertyPairs:
self.sim.probability.adjustProperty(x, y)
for stuff in self.afterFunc:
if len(stuff) == 1:
# calls the designated function
getattr(self.sim.action, stuff[0])()
else:
# calls it with a tuple of arguments
getattr(self.sim.action, stuff[0])(stuff[1:])
######### BEGIN SPECIFIC COMMMAND TYPES ####
class AssessRefugeeMedicalProfile(Assessment):
"""an assessment of the medical profile of the refugees"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 3, "assessing refugee medical profile",
["refugees.population", "refugees.dead", "refugees.cholera",
"refugees.diarrhea", "refugees.measles", "refugees.malaria",
"refugees.malnourished", "refugees.malaria",
"refugees.meningitis"])
class AssessRefugeePopulation(Assessment):
"""an assessment of the number of refugees in your camp"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing refugee population",
["refugees.population", "refugees.dead"])
class AssessRefugeeFoodSupplyDemand(Assessment):
"""an assessment of how many calories per day the average
refugee is not getting AND how many calories are being
delivered to the camp."""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing refugee food supply/demand",
["refugees.nutritionalDemand", "camp.foodQuantity"])
class AssessRefugeeCholera(Assessment):
"""an assessment of how many people are showing symptoms of cholera"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing for cholera symptoms",
["refugees.cholera", "refugees.population", "refugees.dead"])
class AssessRefugeeDiarrhea(Assessment):
"""an assessment of how many people are showing symptoms of diarrhea"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing for diarrhea symptoms",
["refugees.diarrhea", "refugees.population", "refugees.dead"])
class AssessRefugeeMeasles(Assessment):
"""an assessment of how many people are showing symptoms of measles"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing for measles symptoms",
["refugees.measles", "refugees.population", "refugees.dead"])
class AssessRefugeeMalaria(Assessment):
"""an assessment of how many people are showing symptoms of malaria"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing for malaria symptoms",
["refugees.malaria", "refugees.population", "refugees.dead"])
class AssessRefugeeMalnourished(Assessment):
"""an assessment of how many people are malnourished"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing for malnutrition",
["refugees.malnourished", "refugees.population", "refugees.dead"])
class AssessRefugeeMeningitis(Assessment):
"""an assessment of how many people are showing symptoms of Meningitis"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing for meningitis symptoms",
["refugees.meningitis", "refugees.population", "refugees.dead"])
class AssessLatrinesOnly(Assessment):
"""an assessment of the number of each type of latrine in your camp"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "you should not be reading this",
["camp.latrinesDefTrench", "camp.latrinesCommPit"])
class AssessCampLatrines(Assessment):
"""an assessment of the number of each type of latrine
in your camp and the number of unserviced refugees"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing sanitation facilities",
["camp.latrinesDefTrench", "camp.latrinesCommPit",
"camp.solidWaste"])
self.afterFunc = [("choleraHint",)]
class AssessCampWaterQuality(Assessment):
"""an assessment of the water quality in your camp"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing camp water quality",
["camp.waterQuality"])
class AssessCampWaterSupplyDemand(Assessment):
"""an assessment of how many liters of water is being
delivered daily to camp and how much the avg
refugee isn't getting"""
def __init__(self, sim):
Assessment.__init__(
self, sim, 1, "assessing camp water supply and demand",
["camp.waterQuantity", "refugees.waterDemand"])
###### END ASSESSMENTS / BEGIN INTERVENTIONS #######
class AddCampFoodQuantity(Intervention):
"""Increase the daily food supply at the camp"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "arranging for daily food supply increase",
[("camp.foodQuantity", 2000000)])
class AddCampLatrineDefTrench(Intervention):
"""Dig some defecation trenches at the camp"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "digging 100 new defecation trenches",
[("camp.latrinesDefTrench", 100)])
self.afterFunc = [("revealLatrineInfo",),
("addDefTrenchExpiration", "100")]
class AddCampLatrineCommPit(Intervention):
"""Build some community pits at the camp"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "building 60 new community pits",
[("camp.latrinesCommPit", 60)])
self.afterFunc = [("revealLatrineInfo",)]
class AddCampWaterQuality(Intervention):
"""Improve the quality of the water at the camp"""
def __init__(self, sim):
Intervention.__init__(self, sim, 1, "improving water quality", [])
self.afterFunc = [("treatWater",)]
class AddCampWaterQuantity(Intervention):
"""Increase the daily water delivery amount"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "arranging for more water",
[("camp.waterQuantity", 10000)])
class SetUpSuppFeedingCenter(Intervention):
"""Set up a supplimentary feeding center for malnourished
children age 5 and under"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 2, "setting up a supplimentary feeding center",
[("camp.suppFeedingCenters", 1)])
class TreatMeasles(Intervention):
"""Treat refugees who are showing symptoms of measles"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "treating refugees showing measles symptoms",
[])
self.beforeFunc = [("treatSickHelper", "measles")]
class TreatCholeraAndDiarrhea(Intervention):
"""Treat refugees who are showing symptoms of cholera or diarrhea"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1,
"treating refugees with cholera or diarrhea symptoms",
[])
self.beforeFunc = [("treatSickHelper", "cholera")]
self.afterFunc = [("treatSickHelper", "diarrhea")]
class TreatMeningitis(Intervention):
"""Treat refugees who are showing symptoms of meningitis"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "treating refugees showing meningitis symptoms", [])
self.beforeFunc = [("treatSickHelper", "meningitis")]
class TreatMalaria(Intervention):
"""Treat refugees who are showing symptoms of malaria"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "treating refugees showing malaria symptoms", [])
self.beforeFunc = [("treatSickHelper", "malaria")]
class VaccinateMeasles(Intervention):
"""Vaccinate some refugees against measles"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "vaccinating some refugees against measles", [])
self.beforeFunc = [("vaccinate", "measles", 2)]
class VaccinateCholera(Intervention):
"""Vaccinate some refugees against cholera"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "vaccinating some refugees against cholera", [])
self.beforeFunc = [("vaccinate", "cholera", 14)]
class VaccinateMeningitis(Intervention):
"""Vaccinate some refugees against meningitis"""
def __init__(self, sim):
Intervention.__init__(
self, sim, 1, "vaccinating some refugees against meningitis", [])
self.beforeFunc = [("vaccinate", "meningitis", 5)]
############ END COMMAND TYPES ###########
class Resource:
"""resources for the user to manage"""
def __init__(self):
self.personnel = []
self.maxPersonnel = 5
def findFreePersonnel(self):
"""return the first non-busy person on staff,
or 'None' if everyone is busy"""
for x in self.personnel:
if x.getDaysBusy() == 0:
return x
def nextDay(self):
"""decrement all personnel task daysRemaining counters."""
for x in self.personnel:
if x.task is not None:
x.task.timePass()
# pass either "assessment" or "intervention"
def doTasks(self, taskType):
"""do all tasks of the indicated type that are to be done today"""
for x in self.personnel:
if (x.task is not None
and x.task.isa == taskType
and x.task.daysRemaining == 0):
x.task.do()
x.task = None
class Personnel:
names = ["Juan", "Alexis", "Eric", "Marilyn", "Ryan"]
nameCount = 0
taskId = ""
def __init__(self):
self.name = Personnel.names[Personnel.nameCount]
Personnel.nameCount += 1
if Personnel.nameCount >= len(Personnel.names):
Personnel.nameCount = 0
self.task = None
def assign(self, task):
"""assign a task to this person"""
self.task = task
def getDaysBusy(self):
"""return the number of days this person will be busy
doing their current task"""
if self.task is not None:
return self.task.daysRemaining
else:
return 0
class InfoStore:
"""contains known data about the camp and the refugees"""
def __init__(self):