def test_scenario(self): scenario = Scenario(open(os.path.join(base_dir, os.path.join("input", "scenario70k60c.xml"))).read()) # Reading attributes self.assertEqual(scenario.name, "Olyset Duo") self.assertEqual(scenario.schemaVersion, 32) self.assertRaises(AttributeError, getattr, scenario, "wuID") self.assertRaises(AttributeError, lambda: scenario.analysisNo) # Changing attributes scenario.name = "Test name" self.assertEqual(scenario.name, "Test name") self.assertRaises(AssertionError, setattr, scenario, "name", 1) self.assertRaises(AttributeError, setattr, scenario, "schemaVersion", 31) # Check if xml code is correct self.assertEqual(len(scenario.xml), 20613) # Changing attributes scenario.wuID = 1 self.assertEqual(scenario.wuID, 1) self.assertRaises(AssertionError, setattr, scenario, "wuID", "string") scenario.analysisNo = 1024 self.assertEqual(scenario.analysisNo, 1024) self.assertRaises(AssertionError, setattr, scenario, "analysisNo", "string") # Checking sections self.assertEqual(hasattr(scenario, "monitoring"), True) self.assertIsInstance(scenario.monitoring, Monitoring)
def test_post_demography_view(self): scenario = Scenario(self.model_scenario.xml) self.assertEqual(scenario.demography.name, "Ifakara") self.assertEqual(scenario.demography.maximumAgeYrs, 90) self.assertEqual(scenario.demography.popSize, 1000) demographics_snippet = DemographicsSnippet.objects.get(name="Rachuonyo") self.assertIsNotNone(demographics_snippet) new_age_dist_xml = demographics_snippet.xml post_data = { "age_dist": "Rachuonyo", "age_dist_name": "Rachuonyo", "age_dist_xml": new_age_dist_xml, "maximum_age_yrs": "90", "human_pop_size": "100" } response = self.client.post(reverse("ts_om.demography", kwargs={"scenario_id": self.model_scenario.id}), post_data) self.assertEqual(response.status_code, 302) model_scenario = ScenarioModel.objects.get(id=self.model_scenario.id) scenario = Scenario(model_scenario.xml) self.assertEqual(scenario.demography.name, "Rachuonyo") self.assertEqual(scenario.demography.maximumAgeYrs, 90) self.assertEqual(scenario.demography.popSize, 100) self.assertEqual(scenario.demography.ageGroup.lowerbound, 0) self.assertEqual(float(scenario.demography.ageGroup.group[1]["upperbound"]), 5.0) self.assertEqual(float(scenario.demography.ageGroup.group[1]["poppercent"]), 13.1)
def test_post_healthsystem_view(self): scenario = Scenario(self.model_scenario.xml) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.name, "Kenya ACT") self.assertEqual(scenario.healthSystem.ImmediateOutcomes.firstLine, "ACT") self.assertEqual(scenario.healthSystem.ImmediateOutcomes.secondLine, "QN") self.assertEqual( scenario.healthSystem.ImmediateOutcomes.pSeekOfficialCareSevere, 0.48) self.assertEqual( scenario.healthSystem.ImmediateOutcomes. pSeekOfficialCareUncomplicated1, 0.04) self.assertEqual( scenario.healthSystem.ImmediateOutcomes. pSeekOfficialCareUncomplicated2, 0.04) self.assertEqual( scenario.healthSystem.ImmediateOutcomes.pSelfTreatUncomplicated, 0.0212) perc_total = 20 perc_formal = 40 expected_prob_total = get_prob_from_percentage(perc_total) expected_prob_formal = get_prob_from_percentage(100 - perc_formal) post_data = { "perc_total_treated": str(perc_total), "perc_formal_care": str(perc_formal), "first_line_drug": "SP", } response = self.client.post(self.url, post_data) self.assertEqual(response.status_code, 302) model_scenario = ScenarioModel.objects.get(id=self.model_scenario.id) scenario = Scenario(model_scenario.xml) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.name, "Kenya ACT") self.assertEqual(scenario.healthSystem.ImmediateOutcomes.firstLine, "SP") self.assertEqual(scenario.healthSystem.ImmediateOutcomes.secondLine, "QN") self.assertEqual( scenario.healthSystem.ImmediateOutcomes.pSeekOfficialCareSevere, 0.48) self.assertEqual( scenario.healthSystem.ImmediateOutcomes. pSeekOfficialCareUncomplicated1, expected_prob_total) self.assertEqual( scenario.healthSystem.ImmediateOutcomes. pSeekOfficialCareUncomplicated2, expected_prob_total) self.assertEqual( scenario.healthSystem.ImmediateOutcomes.pSelfTreatUncomplicated, expected_prob_formal)
def test_post_entomology_view(self): scenario = Scenario(self.model_scenario.xml) self.assertEqual(scenario.entomology.name, "one species") self.assertEqual(scenario.entomology.scaledAnnualEIR, 16) self.assertEqual(len(scenario.entomology.vectors), 1) vector = scenario.entomology.vectors["gambiae"] self.assertEqual(vector.mosquito, "gambiae") self.assertEqual(vector.propInfected, 0.078) self.assertEqual(vector.propInfectious, 0.015) self.assertEqual(vector.seasonality.annualEIR, 1) annual_eir = 25 perc_average_eir = 6 expected_average_eir = perc_average_eir / 100.0 perc_human_blood_index = 50 expected_human_blood_index = perc_human_blood_index / 100.0 monthly_values = [ 0.121950947577, 0.150033433731, 0.135783169538, 0.142507307385, 0.12160516792, 0.132069391, 0.14132650592, 0.12974214888, 0.10223384536, 0.08159456812, 0.0673589848, 0.08462085352 ] post_data = { "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_FORMS": 0, "form-MAX_FORMS": 1000, "annual_eir": annual_eir, "form-0-average_eir": perc_average_eir, "form-0-human_blood_index": perc_human_blood_index, "form-0-monthly_values": json.dumps(monthly_values), "form-0-name": "arabiensis", } response = self.client.post(self.url, post_data) self.assertEqual(response.status_code, 302) model_scenario = ScenarioModel.objects.get(id=self.model_scenario.id) scenario = Scenario(model_scenario.xml) self.assertEqual(scenario.entomology.scaledAnnualEIR, annual_eir) self.assertEqual(len(scenario.entomology.vectors), 1) self.assertRaises(KeyError, lambda: scenario.entomology.vectors["gambiae"]) vector = scenario.entomology.vectors["arabiensis"] self.assertEqual(vector.mosquito, "arabiensis") self.assertEqual(vector.propInfected, 0.078) self.assertEqual(vector.propInfectious, 0.015) self.assertEqual(vector.seasonality.annualEIR, expected_average_eir) self.assertEqual(vector.mosq.mosqHumanBloodIndex, expected_human_blood_index) self.assertEqual(vector.seasonality.monthlyValues, monthly_values)
def test_entomology(self): scenario = Scenario(open(os.path.join(base_dir, os.path.join("input", "scenario70k60c.xml"))).read()) # Reading attributes self.assertEqual(scenario.entomology.name, "Kenya Lowlands from EMOD") self.assertEqual(scenario.entomology.scaledAnnualEIR, 25.0) self.assertEqual(len(scenario.entomology.vectors), 1) for vector in scenario.entomology.vectors: self.assertIsInstance(vector, Vector) self.assertEqual(vector.mosquito, "gambiae") self.assertEqual(vector.propInfected, 0.078) gambiae = scenario.entomology.vectors["gambiae"] self.assertIsInstance(gambiae, Vector) self.assertEqual(gambiae.mosquito, "gambiae") self.assertEqual(gambiae.seasonality.annualEIR, 1.0) self.assertEqual(gambiae.seasonality.input, "EIR") self.assertEqual(gambiae.seasonality.smoothing, "fourier") self.assertEqual(gambiae.seasonality.monthlyValues, [0.0468, 0.0447, 0.0374, 0.0417, 0.0629, 0.0658, 0.0423, 0.0239, 0.0203, 0.0253, 0.0331, 0.0728]) self.assertEqual(gambiae.mosq.minInfectedThreshold, 0.001) self.assertEqual(gambiae.mosq.mosqRestDuration, 2) self.assertEqual(gambiae.mosq.mosqHumanBloodIndex, 0.85) # Writing attributes gambiae.seasonality.monthlyValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] self.assertRaises(AssertionError, setattr, gambiae, "propInfected", "string") gambiae.propInfected = 0.1 scenario.entomology.scaledAnnualEIR = 10.0 gambiae.seasonality.annualEIR = 6.1 gambiae.mosq.mosqHumanBloodIndex = 0.7 scenario2 = Scenario(scenario.xml) self.assertEqual(scenario2.entomology.vectors["gambiae"].seasonality.monthlyValues, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) self.assertEqual(scenario2.entomology.vectors["gambiae"].propInfected, 0.1) self.assertEqual(scenario2.entomology.vectors["gambiae"].seasonality.annualEIR, 6.1) self.assertEqual(scenario2.entomology.scaledAnnualEIR, 10.0) self.assertEqual(scenario2.entomology.vectors["gambiae"].mosq.mosqHumanBloodIndex, 0.70) # Deleting a mosquito scenario2.entomology.vectors["gambiae"].mosquito = "farauti" for vector in scenario2.entomology.vectors: self.assertEqual(vector.mosquito, "farauti") del scenario.entomology.vectors["gambiae"] scenario3 = Scenario(scenario.xml) self.assertEqual(len(scenario3.entomology.vectors), 0) self.assertRaises(AttributeError, scenario3.entomology.vectors.add, "<anopheles/>") for vector in scenario3.entomology.vectors: print vector
def update_deployments_form(request, scenario_id): if not request.user.is_authenticated( ) or not scenario_id or scenario_id < 0: return xml_file = request.POST['xml'] json_str = rest_validate(xml_file) validation_result = json.loads(json_str) valid = True if (validation_result['result'] == 0) else False if not valid: return HttpResponse(json_str, content_type="application/json") model_scenario = ScenarioModel.objects.get(id=scenario_id) if model_scenario is None: return HttpResponse(json.dumps({'valid': False}), content_type="application/json") if request.user != model_scenario.user: raise PermissionDenied try: temp_scenario = Scenario(xml_file) except ParseError: return HttpResponse(json.dumps({'valid': False}), content_type="application/json") extra_data = load_deployments_data(temp_scenario) html = render_to_string("ts_om_edit/deployments_list.html", extra_data) return HttpResponse(html)
def update_interventions_form(request, scenario_id): if not request.user.is_authenticated(): raise PermissionDenied xml_file = request.POST['xml'] json_str = rest_validate(xml_file) validation_result = json.loads(json_str) valid = True if (validation_result['result'] == 0) else False if not valid: return HttpResponse(json_str, content_type="application/json") model_scenario = get_object_or_404(ScenarioModel, id=scenario_id) if request.user != model_scenario.user: raise PermissionDenied temp_scenario = Scenario(xml_file) extra_data = load_interventions_data(temp_scenario) html = render_to_string("ts_om_edit/interventions/interventions_list.html", extra_data) return HttpResponse(html)
def test_monitoring(self): scenario = Scenario(open(os.path.join(base_dir, os.path.join("input", "scenario70k60c.xml"))).read()) self.assertEqual(scenario.monitoring.name, "Monthly Surveys") self.assertEqual(scenario.monitoring.detectionLimit, 100.0) self.assertEqual(scenario.monitoring.surveys, [730, 736, 742, 748]) self.assertEqual(len(scenario.monitoring.surveys), 4) self.assertEqual(scenario.monitoring.continuous, ['simulated EIR', 'GVI coverage']) measures = scenario.monitoring.continuous measures.append("Input EIR") scenario.monitoring.continuous = measures self.assertEqual(scenario.monitoring.continuous, ['simulated EIR', 'GVI coverage', 'Input EIR']) self.assertEqual(scenario.monitoring.SurveyOptions, ['nHost', 'nPatent', 'nUncomp', 'simulatedEIR', 'nMassGVI'])
def test_vectorpop_intervention(self): # No vectorPop section scenario = Scenario( open(os.path.join(base_dir, os.path.join("input", "scenario70k60c_no_interventions.xml"))).read()) self.assertEqual(scenario.interventions.vectorPop.interventions, {}) self.assertEqual(len(scenario.interventions.vectorPop), 0) i = None for i in scenario.interventions.vectorPop: print i.name self.assertIsNone(i) # make sure iterator returns an empty set # Empty vectorPop section scenario = Scenario( open(os.path.join(base_dir, os.path.join("files", "test_scenario", "empty_vectorpop_section.xml"))).read()) self.assertEqual(scenario.interventions.vectorPop.interventions, {}) self.assertEqual(len(scenario.interventions.vectorPop), 0) i = None for i in scenario.interventions.vectorPop: print i.name self.assertIsNone(i) # make sure iterator returns an empty set # Test vectorPop section with exactly one intervention scenario = Scenario( open(os.path.join(base_dir, os.path.join("files", "test_scenario", "larvacing.xml"))).read()) self.assertEqual(len(scenario.interventions.vectorPop), 1) for i in scenario.interventions.vectorPop: self.assertEqual(i.name, "simple larviciding translated from schema 30") # Test vectorPop section with multiple interventions scenario = Scenario( open(os.path.join(base_dir, os.path.join("files", "test_scenario", "triple_larvacing.xml"))).read()) self.assertEqual(len(scenario.interventions.vectorPop), 3) self.assertEqual(scenario.interventions.vectorPop["int1"].name, "int1") self.assertEqual(scenario.interventions.vectorPop["int2"].name, "int2") self.assertEqual(scenario.interventions.vectorPop["int3"].name, "int3") self.assertRaises(KeyError, lambda: scenario.interventions.vectorPop["int4"]) # test name setter scenario.interventions.vectorPop["int1"].name = "new name" self.assertEqual(scenario.interventions.vectorPop["new name"].name, "new name")
def test_post_scenario_monitoring_view(self): scenario = Scenario(self.model_scenario.xml) self.assertListEqual(scenario.monitoring.SurveyOptions, ["nUncomp"]) post_data = { "sim_start_date": 2015, "monitor_yrs": 10, "monitor_mos": 0, "monitor_start_date": 2025, "measure_outputs": "yearly", "parasite_detection_diagnostic_type": 100, "nr_per_age_group": "true", "patent_infections": "true" } response = self.client.post(self.url, post_data) self.assertEqual(response.status_code, 302) model_scenario = ScenarioModel.objects.get(id=self.model_scenario.id) scenario = Scenario(model_scenario.xml) self.assertListEqual(scenario.monitoring.SurveyOptions, ["nHost", "nPatent"])
def get_context_data(self, **kwargs): context = super(ScenarioSummaryView, self).get_context_data(**kwargs) try: self.scenario = Scenario(self.model_scenario.xml) except ParseError: set_notification(self.request, "Invalid XML Document", DANGER) self.scenario = None context["scenario"] = self.model_scenario context["xml"] = self.model_scenario.xml context["desc"] = self.model_scenario.description if self.model_scenario.description else "" if self.scenario: vectors = list(self.scenario.entomology.vectors) context["scenario_id"] = self.model_scenario.id context["name"] = self.model_scenario.name context["deleted"] = self.model_scenario.deleted context["version"] = self.scenario.schemaVersion if self.model_scenario.new_simulation: context['sim_id'] = self.model_scenario.new_simulation.id monitor_info = get_survey_times(self.scenario.monitoring, self.model_scenario.start_date) context["monitor_type"] = monitor_info["type"] context["monitor_yrs"] = monitor_info["yrs"] context["monitor_mos"] = monitor_info["mos"] context["timesteps"] = monitor_info["timesteps"] context["demography"] = self.scenario.demography.name context["pop_size"] = self.scenario.demography.popSize context["first_line_drug"] = self.scenario.healthSystem.ImmediateOutcomes.firstLine context["vectors"] = vectors if hasattr(self.scenario.entomology, 'scaledAnnualEIR'): context["annual_eir"] = self.scenario.entomology.scaledAnnualEIR else: context["annual_eir"] = None interventions = [] for component in self.scenario.interventions.human: interventions.append(component.id) for vectorPop in self.scenario.interventions.vectorPop: interventions.append(vectorPop.name) context["interventions"] = interventions return context
def get_form(self, form_class=None): if "scenario_id" in self.kwargs: scenario_id = self.kwargs["scenario_id"] self.model_scenario = ScenarioModel.objects.get(id=scenario_id) if self.request.user != self.model_scenario.user: raise PermissionDenied if "xml" in self.request.POST: xml = self.request.POST["xml"] else: xml = self.model_scenario.xml try: self.scenario = Scenario(xml) except ParseError: self.scenario = None return super(ScenarioBaseFormView, self).get_form(form_class)
def test_healthsystem(self): scenario = Scenario(open(os.path.join(base_dir, os.path.join("input", "scenario70k60c.xml"))).read()) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.name, "Kenya ACT") self.assertEqual(scenario.healthSystem.ImmediateOutcomes.pSeekOfficialCareUncomplicated1, 0.04) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.pSeekOfficialCareUncomplicated2, 0.04) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.pSelfTreatUncomplicated, 0.0212) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.pSeekOfficialCareSevere, 0.48) self.assertEqual(scenario.healthSystem.ImmediateOutcomes.firstLine, "ACT") scenario.healthSystem.ImmediateOutcomes.firstLine = "QN" self.assertEqual(scenario.healthSystem.ImmediateOutcomes.firstLine, "QN") self.assertEqual(len(scenario.healthSystem.ImmediateOutcomes.drugs), 3) for drug in scenario.healthSystem.ImmediateOutcomes.drugs: if drug.name == "ACT": self.assertEqual(drug.initialACR, 0.96) self.assertEqual(drug.compliance, 0.892) self.assertEqual(drug.nonCompliersEffective, 0.8544) self.assertEqual(drug.treatmentAction.name, 'clear blood-stage infections') self.assertEqual(drug.treatmentAction.timesteps, 1) self.assertEqual(drug.treatmentAction.stage, 'blood') scenario.healthSystem.ImmediateOutcomes.drugs.add("CQ", 0.5, ["initialACR", "compliance"]) self.assertEqual(len(scenario.healthSystem.ImmediateOutcomes.drugs), 4) drug = scenario.healthSystem.ImmediateOutcomes.drugs["CQ"] self.assertEqual(drug.initialACR, 0.5) self.assertEqual(drug.compliance, 0.5) self.assertEqual(drug.treatmentAction, None) drug.treatmentAction = 'test' drug.treatmentAction.timesteps = 1 drug.treatmentAction.stage = 'blood' self.assertEqual(drug.treatmentAction.name, 'test') self.assertEqual(drug.treatmentAction.timesteps, 1) self.assertEqual(drug.treatmentAction.stage, 'blood')
def test_vaccine_interventions(self): scenario = Scenario(open(os.path.join(base_dir, os.path.join("files", "test_scenario", "vaccine_interventions.xml"))).read()) self.assertEqual(len(scenario.interventions.human), 2) for i in scenario.interventions.human: if i.vaccine_type == "TBV": tbv = i else: pev = i self.assertEqual(tbv.id, "my_TBV_effect") self.assertEqual(pev.id, "some_PEV") self.assertEqual(tbv.efficacyB, 10) self.assertEqual(pev.efficacyB, 10) self.assertEqual(tbv.initialEfficacy, [0.512, 0.64, 0.8]) self.assertEqual(pev.initialEfficacy, [0.512, 0.64, 0.8]) tbv.decay.L = 2.0 tbv.efficacyB = float("8.2") tbv.initialEfficacy = [0.5, 0.6, 0.9, 0.2] self.assertEqual(tbv.decay.L, 2.0) self.assertEqual(tbv.efficacyB, 8.2) self.assertEqual(tbv.initialEfficacy[3], 0.2) self.assertEqual(len(scenario.interventions.human.deployments), 1) continuous = None timed = None for d in scenario.interventions.human.deployments: continuous = d.continuous timed = d.timesteps self.assertEqual(len(continuous), 3) self.assertEqual(len(timed), 6) self.assertEqual(continuous[0]["targetAgeYrs"], 0.0833) self.assertEqual(timed[0]["time"], 1) self.assertEqual(timed[0]["coverage"], 0.95)
def test_post_interventions_view(self): scenario = Scenario(self.model_scenario.xml) self.assertEqual(len(scenario.interventions.human), 3) intervention = scenario.interventions.human["ActellicBased"] self.assertEqual(intervention.id, "ActellicBased") self.assertEqual(intervention.name, "IRS") self.assertEqual(len(intervention.anophelesParams), 1) anopheles_params = intervention.anophelesParams[0] self.assertEqual(anopheles_params.mosquito, "gambiae") self.assertEqual(anopheles_params.propActive, 0.45) self.assertEqual(anopheles_params.deterrency, -0.23) self.assertEqual(anopheles_params.preprandialKillingEffect, 0.1) self.assertEqual(anopheles_params.postprandialKillingEffect, 0.5) self.assertEqual(len(scenario.interventions.human.deployments), 3) scenario.interventions.human.deployments = [] self.assertEqual(len(scenario.interventions.human.deployments), 0) post_data = { "gvi-TOTAL_FORMS": 1, "gvi-INITIAL_FORMS": 0, "gvi-MIN_FORMS": 0, "gvi-MAX_FORMS": 1000, "llin-TOTAL_FORMS": 0, "llin-INITIAL_FORMS": 0, "llin-MIN_FORMS": 0, "llin-MAX_FORMS": 1000, "irs-TOTAL_FORMS": 0, "irs-INITIAL_FORMS": 0, "irs-MIN_FORMS": 0, "irs-MAX_FORMS": 1000, "pyrethroids-TOTAL_FORMS": 0, "pyrethroids-INITIAL_FORMS": 0, "pyrethroids-MIN_FORMS": 0, "pyrethroids-MAX_FORMS": 1000, "ddt-TOTAL_FORMS": 0, "ddt-INITIAL_FORMS": 0, "ddt-MIN_FORMS": 0, "ddt-MAX_FORMS": 1000, "larviciding-TOTAL_FORMS": 0, "larviciding-INITIAL_FORMS": 0, "larviciding-MIN_FORMS": 0, "larviciding-MAX_FORMS": 1000, "mda-TOTAL_FORMS": 0, "mda-INITIAL_FORMS": 0, "mda-MIN_FORMS": 0, "mda-MAX_FORMS": 1000, "vaccine-bsv-TOTAL_FORMS": 0, "vaccine-bsv-INITIAL_FORMS": 0, "vaccine-bsv-MIN_FORMS": 0, "vaccine-bsv-MAX_FORMS": 1000, "vaccine-pev-TOTAL_FORMS": 0, "vaccine-pev-INITIAL_FORMS": 0, "vaccine-pev-MIN_FORMS": 0, "vaccine-pev-MAX_FORMS": 1000, "vaccine-tbv-TOTAL_FORMS": 0, "vaccine-tbv-INITIAL_FORMS": 0, "vaccine-tbv-MIN_FORMS": 0, "vaccine-tbv-MAX_FORMS": 1000, "gvi-0-id": "test", "gvi-0-name": "GVI", "gvi-0-attrition": 50, "gvi-0-vector_0_mosquito": "gambiae", "gvi-0-vector_0_propActive": 0.1, "gvi-0-vector_0_deterrency": 0.25, "gvi-0-vector_0_preprandialKillingEffect ": 0.2, "gvi-0-vector_0_postprandialKillingEffect ": 0.44, } response = self.client.post( reverse("ts_om.interventions", kwargs={"scenario_id": self.model_scenario.id}), post_data) self.assertEqual(response.status_code, 302) model_scenario = ScenarioModel.objects.get(id=self.model_scenario.id) scenario = Scenario(model_scenario.xml) self.assertEqual(len(scenario.interventions.human), 1) self.assertRaises( KeyError, lambda: scenario.interventions.human["ActellicBased"]) intervention = scenario.interventions.human["test"] self.assertEqual(intervention.id, "test") self.assertEqual(intervention.name, "GVI") self.assertEqual(len(intervention.anophelesParams), 1) anopheles_params = intervention.anophelesParams[0] self.assertEqual(anopheles_params.mosquito, "gambiae") self.assertEqual(anopheles_params.propActive, 0.1) self.assertEqual(anopheles_params.deterrency, 0.25) self.assertEqual(anopheles_params.preprandialKillingEffect, 0.2) self.assertEqual(anopheles_params.postprandialKillingEffect, 0.44)
def test_interventions(self): scenario = Scenario(open(os.path.join(base_dir, os.path.join("input", "scenario70k60c.xml"))).read()) self.assertEqual(scenario.interventions.changeHS, []) self.assertIs(scenario.interventions.changeEIR, None) for intervention in scenario.interventions.human: self.assertEqual(intervention.name, "Nets") self.assertEqual(intervention.decay.function, "step") self.assertEqual(len(intervention.anophelesParams), 1) self.assertEqual(intervention.anophelesParams[0].mosquito, "gambiae") self.assertEqual(intervention.anophelesParams[0].propActive, 0.7) self.assertEqual(intervention.anophelesParams[0].deterrency, 0.23076923077) self.assertEqual(intervention.anophelesParams[0].preprandialKillingEffect, 0.7) self.assertEqual(intervention.anophelesParams[0].postprandialKillingEffect, 0) intervention.anophelesParams[0].postprandialKillingEffect = 0.2 self.assertEqual(intervention.anophelesParams[0].postprandialKillingEffect, 0.2) new_anopheles_params = { "mosquito": "gambiae", "propActive": 0.8, "deterrency": 0.2222, "preprandialKillingEffect": 0.9, "postprandialKillingEffect": 0.1 } intervention.add_or_update_anophelesParams(new_anopheles_params) self.assertEqual(intervention.anophelesParams[0].mosquito, "gambiae") self.assertEqual(intervention.anophelesParams[0].propActive, 0.8) self.assertEqual(intervention.anophelesParams[0].deterrency, 0.2222) self.assertEqual(intervention.anophelesParams[0].preprandialKillingEffect, 0.9) self.assertEqual(intervention.anophelesParams[0].postprandialKillingEffect, 0.1) # Overwrite anophelesParams. anopheles_xml = """<anophelesParams mosquito="funestus" propActive="0.0"> <deterrency value="0.0" /> <preprandialKillingEffect value="0.0" /> <postprandialKillingEffect value="0.0" /> </anophelesParams>""" intervention.anophelesParams = [anopheles_xml] self.assertEqual(len(intervention.anophelesParams), 1) self.assertEqual(intervention.anophelesParams[0].mosquito, "funestus") self.assertEqual(intervention.anophelesParams[0].propActive, 0.0) self.assertEqual(intervention.anophelesParams[0].deterrency, 0.0) self.assertEqual(intervention.anophelesParams[0].preprandialKillingEffect, 0.0) self.assertEqual(intervention.anophelesParams[0].postprandialKillingEffect, 0) component_xml = """<component id="DDT" name="DDT"> <GVI> <decay L="0.5" function="exponential"/> </GVI> </component>""" self.assertEqual(len(scenario.interventions.human), 1) scenario.interventions.human.add(component_xml) self.assertEqual(len(scenario.interventions.human), 2) scenario.interventions.human.add(component_xml, "testing") self.assertEqual(len(scenario.interventions.human), 3) self.assertTrue(scenario.interventions.human["testing"] is not None) self.assertEqual(scenario.interventions.human["testing"].id, "testing") ddt = scenario.interventions.human["DDT"] self.assertEqual(ddt.id, "DDT") self.assertEqual(ddt.name, "DDT") self.assertEqual(ddt.decay.L, 0.5) self.assertEqual(ddt.decay.function, "exponential") mda_xml = """ <component id="Coartem" name="Coartem"> <MDA> <effects> <option name="0.5" pSelection="0.5"> <clearInfections stage="liver" timesteps="1"/> <clearInfections stage="blood" timesteps="3"/> </option> <option name="0.2" pSelection="0.2"> <clearInfections stage="liver" timesteps="1"/> <clearInfections stage="blood" timesteps="4"/> </option> <option name="0.3" pSelection="0.3"> <clearInfections stage="liver" timesteps="1"/> <clearInfections stage="blood" timesteps="5"/> </option> </effects> </MDA> </component> """ scenario.interventions.human.add(mda_xml) self.assertEqual(len(scenario.interventions.human), 4) mda = scenario.interventions.human["Coartem"] self.assertEqual(mda.id, "Coartem") self.assertEqual(mda.name, "Coartem") self.assertEqual(len(mda.treatment_options), 3) self.assertEqual(mda.treatment_options[0]["name"], "0.5") mda_params = { "name": "0.5", "pSelection": "0.5", "deploys": [{ "maxAge": "10", "minAge": "0", "p": "1", "components": ["Coartem"] }], "clearInfections": [{ "timesteps": "2", "stage": "liver" }, { "timesteps": "3", "stage": "blood" }] } mda.add_or_update_treatment_option(mda_params) self.assertEqual(len(mda.treatment_options), 3) self.assertEqual(mda.treatment_options[0]["name"], "0.5") self.assertEqual(mda.treatment_options[0]["deploys"][0].p, 1) # Test removal of a human intervention. del scenario.interventions.human["testing"] self.assertEqual(len(scenario.interventions.human), 3) # Test deployment section self.assertEqual(len(scenario.interventions.human.deployments), 1) for deployment in scenario.interventions.human.deployments: self.assertEqual(deployment.name, "Nets") self.assertEqual(deployment.components[0], "GVI") self.assertEqual(len(deployment.timesteps), 185) self.assertEqual(deployment.timesteps[0]["coverage"], 0.6) self.assertEqual(deployment.timesteps[0]["time"], 730) deployment.timesteps = [{"time": 73, "coverage": 0.7}, {"time": 730, "coverage": 0.7}] deployment.continuous = [{"targetAgeYrs": 5}, {"targetAgeYrs": 10}] self.assertEqual(len(deployment.timesteps), 2) self.assertEqual(len(deployment.continuous), 2) self.assertEqual(deployment.timesteps[0]["coverage"], 0.7) self.assertEqual(deployment.timesteps[0]["time"], 73) self.assertEqual(deployment.continuous[1]["targetAgeYrs"], 10) deployment.components = ["GVI"] self.assertEqual(deployment.components[0], "GVI") scenario.interventions.human.deployments = [{'name': 'Test', 'components': ['Coartem', 'Invalid'], 'timesteps': [{'time': 730, 'coverage': 0.8}]}] deployment_to_delete = None for deployment in scenario.interventions.human.deployments: self.assertEqual(deployment.name, "Test") self.assertEqual(len(deployment.components), 1) self.assertEqual(deployment.components[0], "Coartem") self.assertEqual(deployment.timesteps[0]["time"], 730) self.assertEqual(deployment.timesteps[0]["coverage"], 0.8) if deployment.delete_component("Coartem") == 0: deployment_to_delete = deployment.et if deployment_to_delete is not None: scenario.interventions.human.et.remove(deployment_to_delete) self.assertEqual(len(scenario.interventions.human.deployments), 0) # Add a nameless deployment. scenario.interventions.human.deployments = [{'components': ['Coartem'], 'timesteps': [{'time': 730, 'coverage': 0.8}]}] self.assertEqual(len(scenario.interventions.human.deployments), 1) for deployment in scenario.interventions.human.deployments: self.assertRaises(AttributeError, lambda: deployment.name) vector_pop_xml = """<intervention name="Larviciding"> <description> <anopheles mosquito="gambiae"> <emergenceReduction initial="0.8"> <decay L="0.2465753424657534" function="step" /> </emergenceReduction> </anopheles> </description> </intervention>""" if len(scenario.interventions.vectorPop) == 0: scenario.interventions.add_section("vectorPop") scenario.interventions.vectorPop.add(vector_pop_xml) self.assertEqual(len(scenario.interventions.vectorPop), 1) for intervention in scenario.interventions.vectorPop: self.assertEqual(intervention.name, "Larviciding") self.assertEqual(len(intervention.anopheles), 1) for anopheles in intervention.anopheles: self.assertEqual(anopheles.mosquito, "gambiae") self.assertEqual(anopheles.emergenceReduction, 0.8) decay = anopheles.decays["emergenceReduction"] self.assertEqual(decay.L, 0.2465753424657534) self.assertEqual(decay.function, "step") anopheles.mosquito = "test" self.assertEqual(anopheles.mosquito, "test") anopheles.emergenceReduction = 0.3 self.assertEqual(anopheles.emergenceReduction, 0.3) new_anopheles = { "mosquito": "test", "emergenceReduction": 0.9 } intervention.add_or_update_anopheles(new_anopheles) self.assertEqual(intervention.anopheles[0].mosquito, "test") self.assertEqual(intervention.anopheles[0].emergenceReduction, 0.9) scenario.interventions.vectorPop.add(vector_pop_xml, "test") self.assertEqual(len(scenario.interventions.vectorPop), 2) self.assertTrue(scenario.interventions.vectorPop["test"] is not None) self.assertEqual(scenario.interventions.vectorPop["test"].name, "test") # Test removal of a vectorPop intervention. del scenario.interventions.vectorPop["test"] self.assertEqual(len(scenario.interventions.vectorPop), 1) del scenario.interventions.vectorPop["Larviciding"] if len(scenario.interventions.vectorPop) == 0: scenario.interventions.remove_section("vectorPop") self.assertEqual(scenario.interventions.vectorPop.et, None) # Imported Infection. imported_infections = scenario.interventions.importedInfections first_rate = imported_infections.rates[0] self.assertEqual(first_rate["time"], 0) self.assertEqual(first_rate["value"], 24) imported_infections.period = 1 self.assertEqual(imported_infections.period, 1) # Scenario without interventions scenario1 = Scenario( open(os.path.join(base_dir, os.path.join("input", "scenario70k60c_no_interventions.xml"))).read()) self.assertEqual(len(scenario1.interventions.human.deployments), 0) i = 0 for deployment in scenario1.interventions.human.deployments: i += 1 self.assertEqual(i, 0) self.assertRaises(KeyError, lambda x: scenario1.interventions.human["123"], 1) i = 0 self.assertEqual(len(scenario1.interventions.human), 0) for intervention in scenario1.interventions.human: i += 1 self.assertEqual(i, 0) # Scenario without deployments in intervention section scenario1 = Scenario( open(os.path.join(base_dir, os.path.join("input", "scenario70k60c_no_deployments.xml"))).read()) self.assertEqual(len(scenario1.interventions.human.deployments), 0) i = 0 for deployment in scenario1.interventions.human.deployments: i += 1 self.assertEqual(i, 0)