def clinicinfo(): publications = root.child('publications').get() list = [] # create a list to store all the publication objects for pubid in publications: eachpublication = publications[pubid] if eachpublication['type'] == 'scli': print(eachpublication) clinic = Clinic(eachpublication['title'], eachpublication['type'], eachpublication['address'], eachpublication['phone'], eachpublication['openingHour'], eachpublication['busNo'], eachpublication['mrtStation'], eachpublication['hospital'], eachpublication['created_by'], eachpublication['areaName'], eachpublication['region']) print(eachpublication) clinic.set_pubid(pubid) print(clinic.get_pubid()) list.append(clinic) else: print(eachpublication) disease = Disease(eachpublication['title'], eachpublication['type'], eachpublication['cause'], eachpublication['symptom'], eachpublication['treatment'], eachpublication['complication'], eachpublication['specialist'], eachpublication['created_by']) print(eachpublication['cause']) disease.set_pubid(pubid) list.append(disease) return render_template('clinicinfo.html', publications=list)
def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 100 self.logInteractions = True self.popSize = 100 #Size of the population self.minFam = 2 self.maxFam = 6 self.igConnectLow = 2 self.igConnectHigh = 5 self.xConnects = round(.2 * self.popSize) self.intsPerTime = .2 # interactions as a proportion of the population per time period self.meanPosVal = 5 #Mean value of an interaction self.meanAvoidVal = 0 #Mean value of avoiding an interaction self.disRisk = .05 #Probability of being a disease carrier at the start of the simulation) self.immuneProb = .05 #Probability of being immune to disease at the start of the simulation self.newDisease = Disease() self.newPop = Population(self.popSize, self.disRisk, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectLow, self.igConnectHigh) self.intLog = [] self.totalInts = 0 self.timeLog = [] self.startTime = None self.endTime = None self.timePerInt = None self.runTime = None self.runVals = None
def initialize_map_objects(self): # grab the population and the diseases from the data # note: format is (person id | current location | (disease name | disease state)) import re # first just the disease names, since it'll be repeated for everyone i = 3 # i should be on the name of the first disease (4th cell) while not re.match( r'[0-9]+', self.data[0] [i]): # while the current cell isn't a number (i.e. a person's id) # make a dummy disease to sit here with the right name (need this for typing to work right) from Disease import Disease Disease.DISEASE_ID_COUNTER = 0 dis = Disease(self.data[0][i]) self.diseases.update({self.data[0][i]: dis}) i += 2 # now go ahead and add the right amount of people # total number of cells = (num of people) * ((num of diseases) * 2 + 2) + 1 # so num of people = (number of cells - 1) / (2 * (num of diseases)) num_people = int( (len(self.data[0]) - 1) / ((2 * len(self.diseases)) + 2)) from PersonState import Person houses = None for _ in range(num_people): house, houses = self.M.get_random_house(houses) p = Person(house, self.M) # doesn't really matter what their home is self.population.append(p)
def initialize_simulation(): covid19 = Disease() cities = [] city1 = City(disease=covid19) city2 = City(disease=covid19, population=100000, area=5, hospital_beds=200, num_infected=2) city3 = City(disease=covid19, population=50000, area=10, hospital_beds=100, num_infected=20) city4 = City(disease=covid19, population=200000, area=8, hospital_beds=400, num_infected=3) city5 = City(disease=covid19, population=20000, area=3, hospital_beds=40, num_infected=10) city6 = City(disease=covid19, population=30000, area=6, hospital_beds=60, num_infected=15) city7 = City(disease=covid19, population=125000, area=5, hospital_beds=250, num_infected=1) # city1 = City(disease = covid19, population = 200, area= .005, # hospital_beds = 5, num_infected = 3) # city2 = City(disease = covid19, population = 100, area = .001, # hospital_beds = 2, num_infected = 2) # city3 = City(disease = covid19, population = 500, area = .01, # hospital_beds = 2, num_infected = 2) # city4 = City(disease = covid19, population = 75, area = .001, # hospital_beds = 2, num_infected = 2) # city5 = City(disease = covid19, population = 50, area = .001, # hospital_beds = 2, num_infected = 2) cities.append(city1) cities.append(city2) cities.append(city3) # cities.append(city4) # cities.append(city5) # cities.append(city6) # cities.append(city7) region = Region(cities) return region
class TestLocation(TestCase): from Map import MapReader v = False # use the map reader since making one of these by hand is going to be a pain mr = MapReader(PUBLIC_BLOCK_SIZE=(2, 2), CAPACITY_PER_PIXEL=2, TIME_STEP_PER_PIXEL=2) M = mr.create_map_from_file('../test_map_small.png') tl_tl_home = M.loc_list[0] # top left home tl_home = M.loc_list[ 42] # this is the home which is down-right of the top-left home (9th cell if counting left-right, top-bottom) br_shop = M.loc_list[175] # this is the shop in the bottom right corner L_office = M.loc_list[119] # this is the L-shaped office from Disease import Disease t_disease = Disease('test disease pls ignore') t_disease.infectivity = { 'idle': 1, 'sleep': 1, 'traveling': 1, 'talking': 1, 'intimate': 1 } t_disease.hand_wash_coef = 0.5 t_disease.symptom_show_rate = 1 t_disease.symptom_infectivity_modifier = 0 t_disease.recovery_rate = 0 t_disease.die_probability = 1 t_disease.vaccination_effectiveness = 0 t_disease.vaccination_rate = 0 def test_infection_round(self): from PersonState import Person p0 = Person(self.tl_home, self.M) p1 = Person(self.tl_home, self.M) p2 = Person(self.tl_home, self.M) p3 = Person(self.tl_home, self.M) p4 = Person(self.tl_home, self.M) p0.disease_state[self.t_disease] = 'II' p1.disease_state[self.t_disease] = 'VS' p2.disease_state[self.t_disease] = 'S' p3.disease_state[self.t_disease] = 'VU' p4.disease_state[self.t_disease] = 'R' self.tl_home.infection_round() assert (p0.disease_state[self.t_disease] == 'II') assert (p1.disease_state[self.t_disease] == 'VII') assert (p2.disease_state[self.t_disease] == 'II') assert (p3.disease_state[self.t_disease] == 'VU') assert (p4.disease_state[self.t_disease] == 'R')
def getAllSymptomps(): objects = Disease.objects() result="" for object in objects: for symptom in object.symptoms: if symptom not in result: result = result + "\n" + symptom return result
def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 50 # number of time periods that a simulation should run self.logInteractions = True # boolean indicating whether to log each interaction during the simulation (set to 'false' for large populations) self.popSize = 1000 #Size of the population self.minFam = 2 # minimum number of agents in each family self.maxFam = 6 # maximum number of agents in each family self.igConnectMin = 2 # minimum number of ingroup (non-family) connections for each agent self.igConnectMax = 5 # maximum number of ingroup (non-family) connections for each agent self.xConnects = round(.1 * self.popSize) # set the number of outgroup connections as a proportion of the total population size self.meanPosVal = 1 # set the average health value change resulting from an interaction self.meanAvoidVal = -1 # set the average health value change resulting from avoiding an interaction self.immuneProb = 0 # set the probability that an agent has natural immunity from disease self.newDisease = Disease() # initialize a disease that can be spread in the poppulation self.newPop = Population(self.popSize, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectMin, self.igConnectMax) # initialize a new population graph using the parameters set above self.intLog = [] # initialize a new interaction log as a list self.totalInts = 0 # initialize the total number of interactions to zero self.timeLog = [] # initialize a new log for summary statistics at each time period self.startTime = None # initialize the variable to hold the system time associated with the start of the simulation self.endTime = None # initialize the variable to hold the system time associated with the end of the simulation self.timePerInt = None # initialize the variable to hold the average time per interaction during the simulation self.runTime = None # initialize the variable to hold the total run time of the simultion self.runVals = None # initialize the variable to hold the log of parameters governing the simulation run
def mutate(individual, mutation_chance, num_gene, gene_length): for x in range(0, 40): for y in range(0, num_gene): for z in range(0, gene_length): if x < 39: if random.randint(0, 10000) < mutation_chance / 100: individual.chromosomes[x].genes[y][1][ z] = individual.chromosomes[x].gene_name_generator( ) if random.randint(0, 10000) > 9999: new_tuple = (Disease(), individual.chromosomes[x].genes[y][1]) individual.chromosomes[x].genes[y] = new_tuple print("Disease by Mutation")
def __init__(self, num_genes, entered_gene_size): self.name = "N/A" self.is_y = False self.genes = [(None, [])] * num_genes gene_size = entered_gene_size self.traits = { 0: "Hair: None", 1: "Hair: Brown", 2: "Hair: White", 3: "Hair: Black", 4: "Hair: Blond", 5: "Eye: Blue", 6: "Eye: Red", 7: "Eye: Green", 8: "Eye: Hazel", 9: "Eye: Yellow", 10: "Skin: White", 11: "Skin: Black" } #instantiates the nucleobases of a gene and determines link with disease, if applicable. for y in range(0, len(self.genes)): acid_list = [] for x in range(0, gene_size): acid_list.append(self.gene_name_generator()) if random.randint( 0, 100000) > 99998: #chance of gene linked disease set to 1% disease = Disease() disease.name = "Syndrome" disease.gene_linked = True self.genes[y] = (disease, acid_list) else: self.genes[y] = (self.pheno_data(random.randint(0, 11)), acid_list)
def getDiseases(symptoms): objects = Disease.objects() result = [] for disease in objects: for symptom in symptoms: if(symptom in disease.symptoms): if(disease not in result): result.append(disease) else: pass return result
class ActorTest(unittest.TestCase): ## # Generate World and disease for testing purposes def setUp(self): self.world_one = World(10, 15) self.disease_one = Disease() self.world_one.addObject(self.disease_one, 5, 10) def test_constructor(self): self.assertEqual(self.disease_one.getGrowthCondition(), (0, 0, 0)) def test_getStrenght(self): self.assertEqual(self.disease_one.getStrength(), 1) def test_getQuadrant(self): self.assertEqual(self.disease_one.getQuadrant(), 3) def test_setStrength(self): self.disease_one.setStrength(2) self.assertEqual(self.disease_one.getStrength(), 2)
def setUp(self): self.world_one = World(10, 15) self.disease_one = Disease() self.world_one.addObject(self.disease_one, 5, 10)
def new(): form = PublicationForm(request.form) if request.method == 'POST' and form.validate(): if form.pubtype.data == 'scli': title = form.title.data type = form.pubtype.data address = form.address.data phone = form.phone.data openingHour = form.openingHour.data busNo = form.busNo.data mrtStation = form.mrtStation.data hospital = form.hospital.data areaName = form.areaName.data region = form.region.data #status = form.status.data #frequency = form.frequency.data #publisher = form.publisher.data created_by = "U0001" # hardcoded value #mag = Magazine(title, publisher, status, created_by, category, type, frequency) cli = Clinic(title,type,address,phone,openingHour,busNo,mrtStation,hospital,created_by,areaName,region) cli_db = root.child('publications') cli_db.push({ 'title': cli.get_title(), 'type': cli.get_type(), 'address': cli.get_address(), 'phone': cli.get_phone(), 'openingHour': cli.get_openingHour(), 'busNo': cli.get_busNo(), 'mrtStation': cli.get_mrtStation(), 'hospital': cli.get_hospital(), 'areaName': cli.get_areaName(), 'region': cli.get_region(), 'created_by': cli.get_created_by(), 'create_date': cli.get_created_date() }) flash('Clinic Inserted Sucessfully.', 'success') elif form.pubtype.data == 'sdis': title = form.title.data type = form.pubtype.data cause = form.cause.data symptom = form.symptom.data treatment = form.treatment.data complication = form.complication.data specialist = form.specialist.data created_by = "U0001" # hardcoded value dis = Disease(title,type,cause,symptom,created_by,treatment,complication,specialist) dis_db = root.child('publications') dis_db.push({ 'title': dis.get_title(), 'type': dis.get_type(), 'cause': dis.get_cause(), 'symptom': dis.get_symptom(), 'treatment': dis.get_treatment(), 'complication': dis.get_complication(), 'specialist': dis.get_specialist(), 'created_by': dis.get_created_by(), 'create_date': dis.get_created_date() }) flash('Disease Inserted Sucessfully.', 'success') return redirect(url_for('viewpublications')) return render_template('create_publication.html', form=form)
class Simulation: def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 100 self.logInteractions = True self.popSize = 100 #Size of the population self.minFam = 2 self.maxFam = 6 self.igConnectLow = 2 self.igConnectHigh = 5 self.xConnects = round(.2 * self.popSize) self.intsPerTime = .2 # interactions as a proportion of the population per time period self.meanPosVal = 5 #Mean value of an interaction self.meanAvoidVal = 0 #Mean value of avoiding an interaction self.disRisk = .05 #Probability of being a disease carrier at the start of the simulation) self.immuneProb = .05 #Probability of being immune to disease at the start of the simulation self.newDisease = Disease() self.newPop = Population(self.popSize, self.disRisk, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectLow, self.igConnectHigh) self.intLog = [] self.totalInts = 0 self.timeLog = [] self.startTime = None self.endTime = None self.timePerInt = None self.runTime = None self.runVals = None # --- Accessor Functions def getSimNum(self): return self.simNum def getNumTimePeriods(self): return self.numTimePeriods def getLogInteractions(self): return self.logInteractions def getPopSize(self): return self.getPopSize def getMinFam(self): return self.minFam def getMaxFam(self): return self.maxFam def getIGConnectLow(self): return self.igConnectLow def getIGConnectHigh(self): return self.igConnectHigh def getIntsPerTime(self): return self.intsPerTime def getMeanPosVal(self): return self.meanPosVal def getMeanAvoidVal(self): return self.meanAvoidVal def getDisRisk(self): return self.disRisk def getImmuneProb(self): return self.immuneProb def getDisease(self): return self.newDisease def getPopulation(self): return self.newPop def getIntLog(self): return self.intLog def getTotalInts(self): return self.totalInts def getTimeLog(self): return self.timeLog def getStartTime(self): return self.startTime def getEndTime(self): return self.endTime def getTimePerInt(self): return self.timePerInt def getRunTime(self): return self.runTime def getRunVals(self): return self.runVals # --- Additional Functions def preSimSetup(self): self.newPop.setPop() self.newPop.logStart() self.newPop.createInitialGraph() self.runVals = [(self.popSize), (self.intsPerTime * self.popSize), self.meanPosVal, self.meanAvoidVal, self.newDisease.getSickValue(), self.newDisease.getSickTime(), self.disRisk, self.newDisease.getTransRate(), self.immuneProb] timeLogFirstRow = [ "Time", "PopSize", "NumSick", "NumImmune", "New Disease Transmissions", "Effective R0", "NumInteractions" ] self.timeLog.append(timeLogFirstRow) timeLogStartRow = [ 0, self.newPop.getSize(), self.newPop.getInitialSick(), self.newPop.getInitialImmune(), 0, 0, 0 ] self.timeLog.append(timeLogStartRow) self.startTime = time.time() self.writeInitialPop() def runSim(self): lowPopFlag = False for i in range(1, self.numTimePeriods + 1): if lowPopFlag: break newTrans = 0 numInts = int(round(self.intsPerTime * self.newPop.getSize())) for j in range(1, numInts + 1): deadCheck = True while deadCheck: edgeNum = random.randint(0, len(self.newPop.agents.es) - 1) randEdge = self.newPop.agents.es[edgeNum] vert1 = self.newPop.agents.vs[randEdge.source] vert2 = self.newPop.agents.vs[randEdge.target] agent1 = vert1["Agent"] agent2 = vert2["Agent"] newInt = Interaction(agent1, agent2) deadCheck = newInt.deadCheck() newInt.setStartVals() newRule = Rules([agent1, agent2]) newResult = newRule.gameResult(self.meanPosVal, self.meanAvoidVal) if newResult[0] == "Avoid": vert1["Agent"].updateValue(newResult[1]) vert2["Agent"].updateValue(newResult[2]) else: newTrans = newTrans + vert1["Agent"].updateDisease( vert2["Agent"], newResult[1]) newTrans = newTrans + vert2["Agent"].updateDisease( vert1["Agent"], newResult[2]) newInt.setEndVals() if self.logInteractions == True: interaction = [i, j, newInt, newRule, newResult] self.intLog.append(interaction) self.newPop.updateSickTime() self.newPop.updateDead() self.totalInts = self.totalInts + numInts self.newPop.logEnd() R0 = self.newPop.calcRo() newLogVals = [ i, self.newPop.getSize(), self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans, R0, numInts ] self.timeLog.append(newLogVals) print('Completed time ' + str(i)) if lowPopFlag: break newLogVals = [ i, numInts, self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans ] self.totalInts = self.totalInts + numInts self.timeLog.append(newLogVals) totalDied = self.newPop.calcNumDied() totalImmune = self.newPop.getFinalImmune() self.runVals.append(totalDied) self.runVals.append(totalImmune) self.endTime = time.time() self.runTime = round((self.endTime - self.startTime), 2) self.timePerInt = self.runTime / self.totalInts print('The simulation ran in ' + str(self.runTime) + ' seconds') print('Total number of interactions simulated: ' + str(self.totalInts)) print('Effective time per interaction: ' + str(self.timePerInt)) return self def writeInitialPop(self): os.chdir('C:/Users/russ.clay/Desktop/Simulations/Agent/Exports') filename = 'initialPopulationLogData_' + str(self.simNum) + '.csv' with open(filename, 'wb') as csvfile: datawriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) firstRow = [ "ID", "Openness", "Value", "SickVal", "DeadVal", "Disease", "DiseaseTime", "Immunity" ] datawriter.writerow(firstRow) for i in self.newPop.agents.vs: tempAgent = i["Agent"] ID = tempAgent.getID() opn = tempAgent.getOpenness() val = tempAgent.getValue() if tempAgent.getDisease(): sck = tempAgent.diseaseType.getSickValue() else: sck = None ded = tempAgent.getDeadValue() dis = tempAgent.getDisease() dtm = tempAgent.getDiseaseTime() imm = tempAgent.getImmunity() newRow = [ID, opn, val, sck, ded, dis, dtm, imm] datawriter.writerow(newRow)
def update_publication(id): form = PublicationForm(request.form) if request.method == 'POST' and form.validate(): if form.pubtype.data =='scli': title = form.title.data type = form.pubtype.data address = form.address.data phone = form.phone.data openingHour = form.openingHour.data busNo = form.busNo.data mrtStation = form.mrtStation.data hospital = form.hospital.data areaName = form.areaName.data region = form.region.data created_by = "U0001" # hardcoded value cli = Clinic(title,type,address,phone,openingHour,busNo,mrtStation,hospital,created_by,areaName,region) # create the clinic object cli_db = root.child('publications/'+ id ) cli_db.set({ 'title': cli.get_title(), 'type': cli.get_type(), 'address': cli.get_address(), 'phone': cli.get_phone(), 'openingHour': cli.get_openingHour(), 'busNo': cli.get_busNo(), 'mrtStation': cli.get_mrtStation(), 'hospital': cli.get_hospital(), 'areaName': cli.get_areaName(), 'region': cli.get_region(), 'created_by': cli.get_created_by(), 'create_date':cli.get_created_date() }) flash('Clinic Updated Sucessfully.', 'success') elif form.pubtype.data == 'sdis': title = form.title.data type = form.pubtype.data # this should be pubtype cause = form.cause.data symptom = form.symptom.data treatment = form.treatment.data complication = form.complication.data specialist = form.specialist.data created_by = "U0001" # hardcoded value dis = Disease(title,type,cause,symptom,treatment,complication,specialist,created_by) dis_db = root.child('publications/'+id) dis_db.set({ 'title': dis.get_title(), 'type': dis.get_type(), 'cause': dis.get_cause(), 'symptom': dis.get_symptom(), 'treatment': dis.get_treatment(), 'complication': dis.get_complication(), 'specialist': dis.get_specialist(), 'created_by': dis.get_created_by(), 'create_date': dis.get_created_date() }) flash('Disease Updated Sucessfully.', 'success') return redirect(url_for('viewpublications')) else: url = 'publications/' + id eachpub = root.child(url).get() if eachpub['type']== 'scli': clinic = Clinic(eachpub['title'], eachpub['type'] , eachpub['address'],eachpub['phone'], eachpub['openingHour'],eachpub['busNo'],eachpub['mrtStation'],eachpub['hospital'], eachpub['created_by'],eachpub['areaName'], eachpub['region']) clinic.set_pubid(id) form.title.data = clinic.get_title() form.pubtype.data = clinic.get_type() form.address.data = clinic.get_address() form.phone.data = clinic.get_phone() form.openingHour.data = clinic.get_openingHour() form.busNo.data = clinic.get_busNo() form.mrtStation.data = clinic.get_mrtStation() form.hospital.data = clinic.get_hospital() form.areaName.data = clinic.get_areaName() form.region.data = clinic.get_region() elif eachpub['type'] == 'sdis': disease = Disease(eachpub['title'], eachpub['type'], eachpub['cause'], eachpub['symptom'], eachpub['treatment'], eachpub['complication'], eachpub['specialist'], eachpub['created_by']) disease.set_pubid(id) form.title.data = disease.get_title() form.cause.data = disease.get_cause() form.symptom.data = disease.get_symptom() form.treatment.data = disease.get_treatment() form.complication.data = disease.get_complication() form.specialist.data = disease.get_specialist() return render_template('update_publication.html', form=form)
class Simulation: def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 100 self.logInteractions = True self.popSize = 100 #Size of the population self.minFam = 2 self.maxFam = 6 self.igConnectLow = 2 self.igConnectHigh = 5 self.xConnects = round(.2 * self.popSize) self.intsPerTime = .2 # interactions as a proportion of the population per time period self.meanPosVal = 5 #Mean value of an interaction self.meanAvoidVal = 0 #Mean value of avoiding an interaction self.disRisk = .05 #Probability of being a disease carrier at the start of the simulation) self.immuneProb = .05 #Probability of being immune to disease at the start of the simulation self.newDisease = Disease() self.newPop = Population(self.popSize, self.disRisk, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectLow, self.igConnectHigh) self.intLog = [] self.totalInts = 0 self.timeLog = [] self.startTime = None self.endTime = None self.timePerInt = None self.runTime = None self.runVals = None # --- Accessor Functions def getSimNum(self): return self.simNum def getNumTimePeriods(self): return self.numTimePeriods def getLogInteractions(self): return self.logInteractions def getPopSize(self): return self.getPopSize def getMinFam(self): return self.minFam def getMaxFam(self): return self.maxFam def getIGConnectLow(self): return self.igConnectLow def getIGConnectHigh(self): return self.igConnectHigh def getIntsPerTime(self): return self.intsPerTime def getMeanPosVal(self): return self.meanPosVal def getMeanAvoidVal(self): return self.meanAvoidVal def getDisRisk(self): return self.disRisk def getImmuneProb(self): return self.immuneProb def getDisease(self): return self.newDisease def getPopulation(self): return self.newPop def getIntLog(self): return self.intLog def getTotalInts(self): return self.totalInts def getTimeLog(self): return self.timeLog def getStartTime(self): return self.startTime def getEndTime(self): return self.endTime def getTimePerInt(self): return self.timePerInt def getRunTime(self): return self.runTime def getRunVals(self): return self.runVals # --- Additional Functions def preSimSetup(self): self.newPop.setPop() self.newPop.logStart() self.newPop.createInitialGraph() self.runVals = [(self.popSize), (self.intsPerTime * self.popSize), self.meanPosVal, self.meanAvoidVal, self.newDisease.getSickValue(), self.newDisease.getSickTime(), self.disRisk, self.newDisease.getTransRate(), self.immuneProb] timeLogFirstRow = ["Time", "PopSize", "NumSick", "NumImmune", "New Disease Transmissions", "Effective R0", "NumInteractions"] self.timeLog.append(timeLogFirstRow) timeLogStartRow = [0, self.newPop.getSize(), self.newPop.getInitialSick(), self.newPop.getInitialImmune(), 0, 0, 0] self.timeLog.append(timeLogStartRow) self.startTime = time.time() self.writeInitialPop() def runSim(self): lowPopFlag = False for i in range(1, self.numTimePeriods+1): if lowPopFlag: break newTrans = 0 numInts = int(round(self.intsPerTime * self.newPop.getSize())) for j in range(1,numInts+1): deadCheck = True while deadCheck: edgeNum = random.randint(0, len(self.newPop.agents.es)-1) randEdge = self.newPop.agents.es[edgeNum] vert1 = self.newPop.agents.vs[randEdge.source] vert2 = self.newPop.agents.vs[randEdge.target] agent1 = vert1["Agent"] agent2 = vert2["Agent"] newInt = Interaction(agent1, agent2) deadCheck = newInt.deadCheck() newInt.setStartVals() newRule = Rules([agent1, agent2]) newResult = newRule.gameResult(self.meanPosVal, self.meanAvoidVal) if newResult[0] == "Avoid": vert1["Agent"].updateValue(newResult[1]) vert2["Agent"].updateValue(newResult[2]) else: newTrans = newTrans + vert1["Agent"].updateDisease(vert2["Agent"], newResult[1]) newTrans = newTrans + vert2["Agent"].updateDisease(vert1["Agent"], newResult[2]) newInt.setEndVals() if self.logInteractions == True: interaction = [i, j, newInt, newRule, newResult] self.intLog.append(interaction) self.newPop.updateSickTime() self.newPop.updateDead() self.totalInts = self.totalInts + numInts self.newPop.logEnd() R0 = self.newPop.calcRo() newLogVals = [i, self.newPop.getSize(), self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans, R0, numInts] self.timeLog.append(newLogVals) print('Completed time ' + str(i)) if lowPopFlag: break newLogVals = [i, numInts, self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans] self.totalInts = self.totalInts + numInts self.timeLog.append(newLogVals) totalDied = self.newPop.calcNumDied() totalImmune = self.newPop.getFinalImmune() self.runVals.append(totalDied) self.runVals.append(totalImmune) self.endTime = time.time() self.runTime = round((self.endTime - self.startTime), 2) self.timePerInt = self.runTime / self.totalInts print('The simulation ran in ' + str(self.runTime) + ' seconds') print('Total number of interactions simulated: ' + str(self.totalInts)) print('Effective time per interaction: ' + str(self.timePerInt)) return self def writeInitialPop(self): os.chdir('C:/Users/russ.clay/Desktop/Simulations/Agent/Exports') filename = 'initialPopulationLogData_' + str(self.simNum) + '.csv' with open(filename, 'wb') as csvfile: datawriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) firstRow = ["ID", "Openness", "Value", "SickVal", "DeadVal", "Disease", "DiseaseTime", "Immunity"] datawriter.writerow(firstRow) for i in self.newPop.agents.vs: tempAgent = i["Agent"] ID = tempAgent.getID() opn = tempAgent.getOpenness() val = tempAgent.getValue() if tempAgent.getDisease(): sck = tempAgent.diseaseType.getSickValue() else: sck = None ded = tempAgent.getDeadValue() dis = tempAgent.getDisease() dtm = tempAgent.getDiseaseTime() imm = tempAgent.getImmunity() newRow = [ID, opn, val, sck, ded, dis, dtm, imm] datawriter.writerow(newRow)
def initDiseases(self, numDisStr: int) -> ArrayDisease: return [Disease() for _ in range(numDisStr)]
class Simulation: def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 50 # number of time periods that a simulation should run self.logInteractions = True # boolean indicating whether to log each interaction during the simulation (set to 'false' for large populations) self.popSize = 1000 #Size of the population self.minFam = 2 # minimum number of agents in each family self.maxFam = 6 # maximum number of agents in each family self.igConnectMin = 2 # minimum number of ingroup (non-family) connections for each agent self.igConnectMax = 5 # maximum number of ingroup (non-family) connections for each agent self.xConnects = round(.1 * self.popSize) # set the number of outgroup connections as a proportion of the total population size self.meanPosVal = 1 # set the average health value change resulting from an interaction self.meanAvoidVal = -1 # set the average health value change resulting from avoiding an interaction self.immuneProb = 0 # set the probability that an agent has natural immunity from disease self.newDisease = Disease() # initialize a disease that can be spread in the poppulation self.newPop = Population(self.popSize, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectMin, self.igConnectMax) # initialize a new population graph using the parameters set above self.intLog = [] # initialize a new interaction log as a list self.totalInts = 0 # initialize the total number of interactions to zero self.timeLog = [] # initialize a new log for summary statistics at each time period self.startTime = None # initialize the variable to hold the system time associated with the start of the simulation self.endTime = None # initialize the variable to hold the system time associated with the end of the simulation self.timePerInt = None # initialize the variable to hold the average time per interaction during the simulation self.runTime = None # initialize the variable to hold the total run time of the simultion self.runVals = None # initialize the variable to hold the log of parameters governing the simulation run # --- Accessor Functions def getSimNum(self): return self.simNum def getNumTimePeriods(self): return self.numTimePeriods def getLogInteractions(self): return self.logInteractions def getPopSize(self): return self.getPopSize def getMinFam(self): return self.minFam def getMaxFam(self): return self.maxFam def getIGConnectMin(self): return self.igConnectMin def getIGConnectMax(self): return self.igConnectMax def getIntsPerTime(self): return self.intsPerTime def getMeanPosVal(self): return self.meanPosVal def getMeanAvoidVal(self): return self.meanAvoidVal def getImmuneProb(self): return self.immuneProb def getDisease(self): return self.newDisease def getPopulation(self): return self.newPop def getIntLog(self): return self.intLog def getTotalInts(self): return self.totalInts def getTimeLog(self): return self.timeLog def getStartTime(self): return self.startTime def getEndTime(self): return self.endTime def getTimePerInt(self): return self.timePerInt def getRunTime(self): return self.runTime def getRunVals(self): return self.runVals #------------------------- # --- Class Functions #------------------------- def preSimSetup(self): # Create initial Population self.newPop.setPop() # Select 1 random member of the population to be infected with disease randInfect = random.randint(0, len(self.newPop.agents.vs)) self.newPop.agents.vs[randInfect]["Agent"].setDisease(self.newDisease) # Log the starting population values self.newPop.logStart() self.newPop.createGraph(0) self.runVals = [(self.popSize), len(self.newPop.agents.es), self.meanPosVal, self.meanAvoidVal, self.newDisease.getSickValue(), self.newDisease.getSickTime(), self.newDisease.getTransRate(), self.immuneProb] timeLogFirstRow = ["Time", "PopSize", "NumSick", "NumImmune", "New Disease Transmissions", "Effective R0", "NumInteractions"] self.timeLog.append(timeLogFirstRow) if self.logInteractions == True: self.writeFirstIntLogRow() timeLogStartRow = [0, self.newPop.getSize(), self.newPop.getInitialSick(), self.newPop.getInitialImmune(), 0, 0, 0] self.timeLog.append(timeLogStartRow) self.startTime = time.time() self.writeInitialPop() def runSim(self): # iterate through the following steps for the defined number of time periods for i in range(1, self.numTimePeriods+1): numInts = 0 # generate a new group of random outgroup connections each time period self.newPop.clearOutgroupConnects() self.newPop.addOutgroupConnects() self.newPop.clearTransmissions() newTransStack = [] # initialize stack of potential disease transmission interactions - necessary so that agents can only spread disease a maximum of one connection away during each time period # iterate through the following steps for each connection (graph edge) in the population for j in self.newPop.agents.es: # print('Edge #' + str(j.index)) # debugging # extract agents from the connection vert1 = self.newPop.agents.vs[j.source] vert2 = self.newPop.agents.vs[j.target] agent1 = vert1["Agent"] agent2 = vert2["Agent"] newInt = Interaction(agent1, agent2) intType = j["Relation"] # check to see if either of the agents are dead deadCheck = newInt.deadCheck() # execute the following if both agents are alive if not(deadCheck): # print "Dead Check Passed" # debugging newInt.setStartVals() # capture the starting health values for both agents # print "Interaction start values set" intPair = [vert1, vert2] # store the verticies to be passed to the gameResult() function newResult = self.gameResult(intPair, self.meanPosVal, self.meanAvoidVal) # determine whether the pair of agents interacted or avoided # print "Calculated interaction result" # debugging # update the health values of the agents based on the result of the interaction vert1["Agent"].updateValue(newResult[1]) vert2["Agent"].updateValue(newResult[2]) # if the agents interacted, determine whether disease transmission ocurred if newResult[0] == "Interact": newTransStack.append(vert1["Agent"].updateDisease(vert2["Agent"])) newTransStack.append(vert2["Agent"].updateDisease(vert1["Agent"])) numInts+=1 # increment the number of total interactions # print "Interaction...checked and logged disease spread" # debugging newInt.setEndVals() # log the updated health values of the agents # print "ending interaction values set" # debugging # if interaction logging is turned on, log the values captured during the interaction if self.logInteractions == True: interaction = [i, numInts, newInt, [vert1, vert2], newResult, intType] self.intLog.append(interaction) # print "appended interaction record to log" # debugging # after all interactions have ocurred for the time period, update disease spread (done separately so that disease does not spread throughout the population in a single time period) newTrans = self.updateDiseaseSpread(newTransStack) # print "determined disease spread" # debugging # increment the sick time for all agents who are infected with disease self.newPop.updateSickTime() # print "updated sick time" # debug self.newPop.updateDead() # iterate through the population to set the status of any agents with 0 or lower health value to 'Dead' # print "updated deceased population members" # debug self.totalInts = self.totalInts + numInts # update the total number of interactions # print "updated number of interactions" # debugging # Log ending summary population statistics for the time period self.newPop.logEnd() # print "logged ending values for time iteration" #debugging R0 = self.newPop.calcRo(self.timeLog[len(self.timeLog)-1][2]) # print "calculated R0 value" # debugging self.newPop.createGraph(i) newLogVals = [i, self.newPop.getSize(), self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans, R0, numInts] self.timeLog.append(newLogVals) self.writeInteractions(i) print('Completed time ' + str(i)) # debugging # Update summary statistics after final time period newLogVals = [i, numInts, self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans] self.totalInts = self.totalInts + numInts self.timeLog.append(newLogVals) totalDied = self.newPop.calcNumDied() totalImmune = self.newPop.getFinalImmune() self.runVals.append(totalDied) self.runVals.append(totalImmune) self.endTime = time.time() self.runTime = round((self.endTime - self.startTime), 2) self.timePerInt = self.runTime / self.totalInts # Write out completed simulation statistics to the console print('The simulation ran in ' + str(self.runTime) + ' seconds') print('Total number of interactions simulated: ' + str(self.totalInts)) print('Effective time per interaction: ' + str(self.timePerInt)) # return a copy off the simulation instance to main for logging return self # ------------------- # --- Class Functions #-------------------- def gameResult(self, intPair, posVal, avoidVal): if intPair[0]["Family"] == intPair[1]["Family"]: newResult = self.famInteract(intPair, posVal, avoidVal) else: if intPair[0]["Group"] == intPair[1]["Group"]: newResult = self.ingroupInteract(intPair, posVal, avoidVal) else: newResult = self.outgroupInteract(intPair, posVal, avoidVal) return newResult def famInteract(self, intPair, posVal, avoidVal): randSeed = random.uniform(0,1) p1Interact = .95 + (intPair[0]["Agent"].getOpenness() * .05) p2Interact = .95 + (intPair[1]["Agent"].getOpenness() * .05) if (p1Interact < randSeed): newResult=self.avoidResult(avoidVal) else: if(p2Interact < randSeed): newResult=self.avoidResult(avoidVal) else: newResult=self.interactResult(posVal) return newResult def ingroupInteract(self, intPair, posVal, avoidVal): randSeed = random.uniform(0,1) p1Interact = .75 + (intPair[0]["Agent"].getOpenness() * .25) p2Interact = .75 + (intPair[1]["Agent"].getOpenness() * .25) if (p1Interact < randSeed): newResult=self.avoidResult(avoidVal) else: if(p2Interact < randSeed): newResult=self.avoidResult(avoidVal) else: newResult=self.interactResult(posVal) return newResult def outgroupInteract(self, intPair, posVal, avoidVal): randSeed = random.uniform(0,1) p1Interact = intPair[0]["Agent"].getOpenness() p2Interact = intPair[1]["Agent"].getOpenness() if (p1Interact < randSeed): newResult=self.avoidResult(avoidVal) else: if(p2Interact < randSeed): newResult=self.avoidResult(avoidVal) else: newResult=self.interactResult(posVal) return newResult def avoidResult(self, avoidVal): avoid1=random.gauss(avoidVal, .1) avoid2=random.gauss(avoidVal, .1) return ["Avoid", avoid1, avoid2] def interactResult(self, posVal): interact1=random.gauss(posVal, .1) interact2=random.gauss(posVal, .1) return ["Interact", interact1, interact2] def updateDiseaseSpread(self, newTransStack): newTrans = 0 for i in newTransStack: if not(i == False): agentID = i[0] disease = i[1] for j in self.newPop.agents.vs: if j["Agent"].getID() == agentID: j["Agent"].setDisease(disease) newTrans+=1 return newTrans def writeInitialPop(self): os.chdir('C:/Users/russ.clay/Desktop/Simulations/Agent/Exports') filename = 'initialPopulationLogData_' + str(self.simNum) + '.csv' with open(filename, 'wb') as csvfile: datawriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) firstRow = ["ID", "Family", "Group", "Openness", "Value", "SickVal", "DeadVal", "Disease", "DiseaseTime", "Immunity"] datawriter.writerow(firstRow) for i in self.newPop.agents.vs: tempAgent = i["Agent"] family = i["Family"] group = i["Group"] ID = tempAgent.getID() opn = tempAgent.getOpenness() val = tempAgent.getValue() if tempAgent.getDisease(): sck = tempAgent.diseaseType.getSickValue() else: sck = None ded = tempAgent.getDeadValue() dis = tempAgent.getDisease() dtm = tempAgent.getDiseaseTime() imm = tempAgent.getImmunity() newRow = [ID, family, group, opn, val, sck, ded, dis, dtm, imm] datawriter.writerow(newRow) def writeFirstIntLogRow(self): os.chdir('C:/Users/russ.clay/Desktop/Simulations/Agent/Exports') with open('interactionData.csv', 'wb') as csvfile: datawriter = csv.writer(csvfile, delimiter=',', lineterminator = '\n', quotechar='|', quoting=csv.QUOTE_MINIMAL) firstRow = ["TimeNum", "IntNum", "Agent1", "Agent1-Openness", "Agent1-Family", "Agent1-Group", "Agent1-StartVal", "Agent1-Change", "Agent1-EndVal", "Agent2", "Agent2-Openness", "Agent2-Family", "Agent2-Group", "Agent2-StartVal", "Agent2-Change", "Agent2-EndVal", "IntResult", "IntType"] datawriter.writerow(firstRow) def writeInteractions(self, i): os.chdir('C:/Users/russ.clay/Desktop/Simulations/Agent/Exports') with open('interactionData.csv', 'a') as csvfile: datawriter = csv.writer(csvfile, delimiter=',', lineterminator = '\n', quotechar='|', quoting=csv.QUOTE_MINIMAL) for i in range(0, len(self.intLog)): timeNum = self.intLog[i][0] intNum = self.intLog[i][1] interaction = self.intLog[i][2] vertPair = self.intLog[i][3] result = self.intLog[i][4] intType = self.intLog[i][5] firstAgent = interaction.getAgent1() secondAgent = interaction.getAgent2() position1 = str(firstAgent.getID()) position2 = str(secondAgent.getID()) a1Openness = firstAgent.getOpenness() a2Openness = secondAgent.getOpenness() a1Family = vertPair[0]["Family"] a2Family = vertPair[1]["Family"] a1Group = vertPair[0]["Group"] a2Group = vertPair[1]["Group"] a1StartVal = interaction.getAgent1StartVal() a2StartVal = interaction.getAgent2StartVal() a1EndVal = interaction.getAgent1EndVal() a2EndVal = interaction.getAgent2EndVal() intResult = result[0] agent1Change = result[1] agent2Change = result[2] newRow = [timeNum, intNum, position1, a1Openness, a1Family, a1Group, a1StartVal, agent1Change, a1EndVal, position2, a2Openness, a2Family, a2Group, a2StartVal, agent2Change, a2EndVal, intResult, intType] datawriter.writerow(newRow) self.intLog = []
def initDiseases(self, numDisStr): array = [] for _ in range(int(numDisStr)): array.append(Disease()) self.__arrayDis.append(Disease()) return array
def mousePressed(self, e): x, y = self.wvmap.viewportToWindow(e.x, e.y) disease = Disease() disease.addedToWorld(self.world) disease.setLocation(x, y) quad = disease.getQuadrant() self.diseases.append(disease) if quad >= 0 or quad <= 3: disease.setGrowthCondition( self.world.getTemp(quad) - 1, self.world.getTemp(quad) + 1, 2.0) self.dict[(round(disease.getX()), round(disease.getY()))] = disease.getStrength()