def test_basic_contact_trace(): tweaking = { 'n_days': 60, 'pop_size': 2000, 'pop_type': 'hybrid' } start_days = [] interventions = [] test_prob_start_day = 35 prob_test_perfect_symptomatic = test_prob(symp_prob=1.0, symp_quar_prob=1.0, asymp_quar_prob=1.0, test_sensitivity=1.0, test_delay=1, start_day=test_prob_start_day) start_days.append(test_prob_start_day) interventions.append(prob_test_perfect_symptomatic) contact_trace_start_day = 35 all_contacts = { 'h': 1.0, 'w': 1.0, 's': 1.0, 'c': 1.0 } single_day_delays = { 'h': 1, 'w': 1, 's': 1, 'c': 1 } brutal_contact_trace = contact_tracing(trace_probs=all_contacts, trace_time=single_day_delays, start_day=contact_trace_start_day) start_days.append(contact_trace_start_day) interventions.append(brutal_contact_trace) tweaking['interventions'] = interventions test_stuff_simulation = Sim(pars=tweaking) test_stuff_simulation.run() test_stuff_results = test_stuff_simulation.to_json(tostring=False) with open("DEBUG_test_intervention_list_simulation.json","w") as outfile: json.dump(test_stuff_results, outfile, indent=4, sort_keys=True) pass assert test_stuff_results["results"]["n_symptomatic"][test_prob_start_day] > 0 # If there are symptomatics assert sum(test_stuff_results["results"]["new_tests"][test_prob_start_day:test_prob_start_day + 5]) > 0 # then there should be tests assert sum(test_stuff_results["results"]["new_diagnoses"][test_prob_start_day + 1:test_prob_start_day + 6]) > 0 # and some diagnoses assert sum(test_stuff_results["results"]["new_diagnoses"][test_prob_start_day + 2:test_prob_start_day + 7]) > 0 # and therefore some quarantined pass
class MiscellaneousFeatureTests(CovaSimTest): def setUp(self): super().setUp() self.sim = Sim() self.pars = parameters.make_pars() self.is_debugging = False def test_xslx_generation(self): super().tearDown() self.sim.run() self.sim.to_xlsx() pass def test_set_pars_invalid_key(self): with self.assertRaises(KeyError) as context: self.sim['n_infectey'] = 10 pass error_message = str(context.exception) self.assertIn('n_infectey', error_message) self.assertIn('n_infected', error_message) print("OH YEAH") pass def test_update_pars_invalid_key(self): invalid_key = {'dooty_doo': 5} with self.assertRaises(KeyError) as context: self.sim.update_pars(invalid_key) pass error_message = str(context.exception) self.assertIn('dooty_doo', error_message) pass def test_update_pars_invalid_type(self): invalid_key = ('dooty_doo', 5) with self.assertRaises(TypeError) as context: self.sim.update_pars(invalid_key) pass error_message = str(context.exception) self.assertIn('dict', error_message) pass
class CovaSimTest(unittest.TestCase): def setUp(self): self.is_debugging = False self.simulation_parameters = None self.sim = None self.simulation_result = None self.expected_result_filename = f"DEBUG_{self.id()}.json" if os.path.isfile(self.expected_result_filename): os.unlink(self.expected_result_filename) pass def tearDown(self): if not self.is_debugging: if os.path.isfile(self.expected_result_filename): os.unlink(self.expected_result_filename) pass # region configuration methods def set_simulation_parameters(self, params_dict=None): """ Overrides all of the default sim parameters with the ones in the dictionary Args: params_dict: keys are param names, values are expected values to use Returns: None, sets self.simulation_params """ if not self.simulation_parameters: self.simulation_parameters = parameters.make_pars( set_prognoses=True, prog_by_age=True, use_layers=True) if params_dict: self.simulation_parameters.update(params_dict) pass def set_simulation_prognosis_probability(self, params_dict): """ Allows for testing prognoses probability as absolute rather than relative. NOTE: You can only call this once per test or you will overwrite your stuff. """ ProbKeys = TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys supported_probabilities = [ ProbKeys.inf_to_symptomatic_probability, ProbKeys.sym_to_severe_probability, ProbKeys.sev_to_critical_probability, ProbKeys.crt_to_death_probability ] for k in params_dict: if k not in supported_probabilities: raise KeyError( f"Key {k} not found in {supported_probabilities}.") if not self.simulation_parameters: self.set_simulation_parameters() pass for k in params_dict: expected_prob = params_dict[k] old_probs = self.simulation_parameters['prognoses'][k] self.simulation_parameters['prognoses'][k] = np.array( [expected_prob] * len(old_probs)) pass pass def set_duration_distribution_parameters(self, duration_in_question, par1, par2): if not self.simulation_parameters: self.set_simulation_parameters() pass duration_node = self.simulation_parameters["dur"] duration_node[duration_in_question] = { "dist": "normal", "par1": par1, "par2": par2 } params_dict = {"dur": duration_node} self.set_simulation_parameters(params_dict=params_dict) def run_sim(self, params_dict=None, write_results_json=False): if not self.simulation_parameters or params_dict: # If we need one, or have one here self.set_simulation_parameters(params_dict=params_dict) pass self.sim = Sim(pars=self.simulation_parameters, datafile=None) self.sim.run(verbose=0) self.simulation_result = self.sim.to_json(tostring=False) if write_results_json: with open(self.expected_result_filename, 'w') as outfile: json.dump(self.simulation_result, outfile, indent=4, sort_keys=True) pass # endregion # region simulation results support def get_full_result_channel(self, channel): result_data = self.simulation_result["results"][channel] return result_data def get_day_zero_channel_value( self, channel=TestProperties.ResultsDataKeys.susceptible_at_timestep): """ Args: channel: timeseries channel to report ('n_susceptible') Returns: day zero value for channel """ result_data = self.get_full_result_channel(channel=channel) return result_data[0] def get_day_final_channel_value(self, channel): channel = self.get_full_result_channel(channel=channel) return channel[-1] # endregion # region specialized simulation methods def set_microsim(self): Simkeys = TestProperties.ParameterKeys.SimulationKeys Micro = TestProperties.SpecializedSimulations.Microsim microsim_parameters = { Simkeys.number_agents: Micro.n, Simkeys.initial_infected_count: Micro.pop_infected, Simkeys.number_simulated_days: Micro.n_days } self.set_simulation_parameters(microsim_parameters) pass def set_everyone_infected(self, agent_count=1000): Simkeys = TestProperties.ParameterKeys.SimulationKeys everyone_infected = { Simkeys.number_agents: agent_count, Simkeys.initial_infected_count: agent_count } self.set_simulation_parameters(params_dict=everyone_infected) pass DurationKeys = TestProperties.ParameterKeys.ProgressionKeys.DurationKeys def set_everyone_infectious_same_day(self, num_agents, days_to_infectious=1, num_days=60): """ Args: num_agents: number of agents to create and infect days_to_infectious: days until all agents are infectious (1) num_days: days to simulate (60) """ self.set_everyone_infected(agent_count=num_agents) prob_dict = { TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.inf_to_symptomatic_probability: 0 } self.set_simulation_prognosis_probability(prob_dict) test_config = { TestProperties.ParameterKeys.SimulationKeys.number_simulated_days: num_days } self.set_duration_distribution_parameters( duration_in_question=DurationKeys.exposed_to_infectious, par1=days_to_infectious, par2=0) self.set_simulation_parameters(params_dict=test_config) pass def set_everyone_symptomatic(self, num_agents, constant_delay: int = None): """ Cause all agents in the simulation to begin infected And proceed to symptomatic (but not severe or death) Args: num_agents: Number of agents to begin with """ self.set_everyone_infectious_same_day(num_agents=num_agents, days_to_infectious=0) prob_dict = { TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.inf_to_symptomatic_probability: 1.0, TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.sym_to_severe_probability: 0 } self.set_simulation_prognosis_probability(prob_dict) if constant_delay is not None: self.set_duration_distribution_parameters( duration_in_question=DurationKeys.infectious_to_symptomatic, par1=constant_delay, par2=0) pass def set_everyone_is_going_to_die(self, num_agents): """ Cause all agents in the simulation to begin infected and die. Args: num_agents: Number of agents to simulate """ ProbKeys = TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys self.set_everyone_infectious_same_day(num_agents=num_agents) prob_dict = { ProbKeys.inf_to_symptomatic_probability: 1, ProbKeys.sym_to_severe_probability: 1, ProbKeys.sev_to_critical_probability: 1, ProbKeys.crt_to_death_probability: 1 } self.set_simulation_prognosis_probability(prob_dict) pass def set_everyone_severe(self, num_agents, constant_delay: int = None): self.set_everyone_symptomatic(num_agents=num_agents, constant_delay=constant_delay) prob_dict = { TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.sym_to_severe_probability: 1.0, TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.sev_to_critical_probability: 0.0 } self.set_simulation_prognosis_probability(prob_dict) if constant_delay is not None: self.set_duration_distribution_parameters( duration_in_question=DurationKeys.symptomatic_to_severe, par1=constant_delay, par2=0) pass def set_everyone_critical(self, num_agents, constant_delay: int = None): """ Causes all agents to become critically ill day 1 """ self.set_everyone_severe(num_agents=num_agents, constant_delay=constant_delay) prob_dict = { TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.sev_to_critical_probability: 1.0, TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys.crt_to_death_probability: 0.0 } self.set_simulation_prognosis_probability(prob_dict) if constant_delay is not None: self.set_duration_distribution_parameters( duration_in_question=DurationKeys.severe_to_critical, par1=constant_delay, par2=0) pass def set_smallpop_hightransmission(self): """ Creates a small population with lots of transmission """ Simkeys = TestProperties.ParameterKeys.SimulationKeys Transkeys = TestProperties.ParameterKeys.TransmissionKeys Progkeys = TestProperties.ParameterKeys.ProgressionKeys Hightrans = TestProperties.SpecializedSimulations.Hightransmission hightrans_parameters = { Simkeys.number_agents: Hightrans.n, Simkeys.initial_infected_count: Hightrans.pop_infected, Simkeys.number_simulated_days: Hightrans.n_days, Transkeys.beta: Hightrans.beta } self.set_simulation_parameters(hightrans_parameters) pass # endregion pass
class CovaSimTest(unittest.TestCase): def setUp(self): self.is_debugging = False self.simulation_parameters = None self.sim = None self.simulation_result = None self.expected_result_filename = f"DEBUG_{self.id()}.json" if os.path.isfile(self.expected_result_filename): os.unlink(self.expected_result_filename) pass def tearDown(self): if not self.is_debugging: if os.path.isfile(self.expected_result_filename): os.unlink(self.expected_result_filename) pass # region configuration methods def set_simulation_parameters(self, params_dict=None): """ Overrides all of the default sim parameters with the ones in the dictionary Args: params_dict: keys are param names, values are expected values to use Returns: None, sets self.simulation_params """ if not self.simulation_parameters: self.simulation_parameters = parameters.make_pars() if params_dict: self.simulation_parameters.update(params_dict) pass def run_sim(self, params_dict=None, write_results_json=True): if not self.simulation_parameters or params_dict: # If we need one, or have one here self.set_simulation_parameters(params_dict=params_dict) pass self.sim = Sim(pars=self.simulation_parameters, datafile=None) self.sim.run(verbose=0) self.simulation_result = self.sim.to_json(tostring=False) if write_results_json: with open(self.expected_result_filename, 'w') as outfile: json.dump(self.simulation_result, outfile, indent=4, sort_keys=True) pass # endregion # region simulation results support def get_full_result_channel(self, channel): result_data = self.simulation_result["results"][channel] return result_data def get_day_zero_channel_value( self, channel=TestProperties.ResultsDataKeys.susceptible_at_timestep): """ Args: channel: timeseries channel to report ('n_susceptible') Returns: day zero value for channel """ result_data = self.get_full_result_channel(channel=channel) return result_data[0] def get_day_final_channel_value(self, channel): channel = self.get_full_result_channel(channel=channel) return channel[-1] # endregion # region specialized simulation methods def set_microsim(self): Simkeys = TestProperties.ParameterKeys.SimulationKeys Transkeys = TestProperties.ParameterKeys.TransmissionKeys Micro = TestProperties.SpecializedSimulations.Microsim microsim_parameters = { Simkeys.number_agents: Micro.n, Simkeys.initial_infected_count: Micro.n_infected, Simkeys.number_simulated_days: Micro.n_days, Transkeys.contacts_per_agent: Micro.contacts } self.set_simulation_parameters(microsim_parameters) pass def set_smallpop_hightransmission(self): """ Creates a small population with lots of transmission """ Simkeys = TestProperties.ParameterKeys.SimulationKeys Transkeys = TestProperties.ParameterKeys.TransmissionKeys Progkeys = TestProperties.ParameterKeys.ProgressionKeys Hightrans = TestProperties.SpecializedSimulations.Hightransmission hightrans_parameters = { Simkeys.number_agents: Hightrans.n, Simkeys.initial_infected_count: Hightrans.n_infected, Simkeys.number_simulated_days: Hightrans.n_days, Transkeys.contacts_per_agent: Hightrans.contacts, Transkeys.beta: Hightrans.beta, Progkeys.exposed_to_infectious: Hightrans.serial, Progkeys.exposed_to_infectious_std: Hightrans.serial_std, Progkeys.infectiousness_duration: Hightrans.dur } self.set_simulation_parameters(hightrans_parameters) pass def set_superhigh_mortality(self): """ builds on high transmission with high mortality """ Simkeys = TestProperties.ParameterKeys.SimulationKeys MortKeys = TestProperties.ParameterKeys.MortalityKeys MortalityTestKeys = TestProperties.SpecializedSimulations.HighMortality self.set_smallpop_hightransmission() more_people_high_mortality = { Simkeys.number_agents: MortalityTestKeys.n, MortKeys.use_cfr_by_age: MortalityTestKeys.cfr_by_age, MortKeys.default_cfr: MortalityTestKeys.default_cfr, MortKeys.time_to_death: MortalityTestKeys.timetodie, MortKeys.time_to_death_std: MortalityTestKeys.timetodie_std } self.set_simulation_parameters(params_dict=more_people_high_mortality) pass # endregion pass
class CovaSimTest(unittest.TestCase): def setUp(self): self.is_debugging = False self.simulation_parameters = None self.sim = None self.simulation_result = None self.expected_result_filename = f"DEBUG_{self.id()}.json" if os.path.isfile(self.expected_result_filename): os.unlink(self.expected_result_filename) pass def tearDown(self): if not self.is_debugging: if os.path.isfile(self.expected_result_filename): os.unlink(self.expected_result_filename) pass # region configuration methods def set_simulation_parameters(self, params_dict=None): """ Overrides all of the default sim parameters with the ones in the dictionary Args: params_dict: keys are param names, values are expected values to use Returns: None, sets self.simulation_params """ if not self.simulation_parameters: self.simulation_parameters = parameters.make_pars() if params_dict: self.simulation_parameters.update(params_dict) pass def run_sim(self, params_dict=None, write_results_json=True): if not self.simulation_parameters or params_dict: # If we need one, or have one here self.set_simulation_parameters(params_dict=params_dict) pass self.sim = Sim(pars=self.simulation_parameters, datafile=None) self.sim.run(verbose=0) self.simulation_result = self.sim.to_json(tostring=False) if write_results_json: with open(self.expected_result_filename, 'w') as outfile: json.dump(self.simulation_result, outfile, indent=4, sort_keys=True) pass # endregion # region simulation results support def get_full_result_channel(self, channel): result_data = self.simulation_result["results"][channel] return result_data def get_day_zero_channel_value(self, channel=TestProperties.ResultsDataKeys.susceptible_at_timestep): """ Args: channel: timeseries channel to report ('n_susceptible') Returns: day zero value for channel """ result_data = self.get_full_result_channel(channel=channel) return result_data[0] def get_day_final_channel_value(self, channel): channel = self.get_full_result_channel(channel=channel) return channel[-1] # endregion # region specialized simulation methods def set_microsim(self): Simkeys = TestProperties.ParameterKeys.SimulationKeys Transkeys = TestProperties.ParameterKeys.TransmissionKeys Micro = TestProperties.SpecializedSimulations.Microsim microsim_parameters = { Simkeys.number_agents : Micro.n, Simkeys.initial_infected_count: Micro.n_infected, Simkeys.number_simulated_days: Micro.n_days, Transkeys.contacts_per_agent: Micro.contacts } self.set_simulation_parameters(microsim_parameters) pass def set_everyone_infected(self, agent_count=1000): Simkeys = TestProperties.ParameterKeys.SimulationKeys everyone_infected = { Simkeys.number_agents: agent_count, Simkeys.initial_infected_count: agent_count } self.set_simulation_parameters(params_dict=everyone_infected) pass def set_everyone_infectious_same_day(self, num_agents, days_to_infectious=1, num_days=60): """ Args: num_agents: number of agents to create and infect days_to_infectious: days until all agents are infectious (1) num_days: days to simulate (60) """ self.set_everyone_infected(agent_count=num_agents) test_config = { TestProperties.ParameterKeys.SimulationKeys.number_simulated_days: num_days, TestProperties.ParameterKeys.ProgressionKeys.exposed_to_infectious: days_to_infectious, TestProperties.ParameterKeys.ProgressionKeys.exposed_to_infectious_std: 0, TestProperties.ParameterKeys.MortalityKeys.use_cfr_by_age: False, TestProperties.ParameterKeys.MortalityKeys.prob_infected_symptomatic: 0 } self.set_simulation_parameters(params_dict=test_config) pass def set_everyone_symptomatic(self, num_agents): """ Cause all agents in the simulation to begin infected And proceed to symptomatic (but not severe or death) Args: num_agents: Number of agents to begin with """ self.set_everyone_infectious_same_day(num_agents=num_agents, days_to_infectious=0) everyone_symptomatic_config = { TestProperties.ParameterKeys.MortalityKeys.prob_infected_symptomatic: 1.0, TestProperties.ParameterKeys.MortalityKeys.prob_symptomatic_severe: 0 } self.set_simulation_parameters(params_dict=everyone_symptomatic_config) pass def set_everyone_is_going_to_die(self, num_agents): """ Cause all agents in the simulation to begin infected and die. Args: num_agents: Number of agents to simulate """ self.set_everyone_infectious_same_day(num_agents=num_agents) everyone_dying_config = { TestProperties.ParameterKeys.MortalityKeys.use_cfr_by_age: False, TestProperties.ParameterKeys.MortalityKeys.prob_infected_symptomatic: 1, # Uh oh TestProperties.ParameterKeys.MortalityKeys.prob_symptomatic_severe: 1, # Oh no TestProperties.ParameterKeys.MortalityKeys.prob_severe_death: 1, # No recoveries } self.set_simulation_parameters(params_dict=everyone_dying_config) pass def set_smallpop_hightransmission(self): """ Creates a small population with lots of transmission """ Simkeys = TestProperties.ParameterKeys.SimulationKeys Transkeys = TestProperties.ParameterKeys.TransmissionKeys Progkeys = TestProperties.ParameterKeys.ProgressionKeys Hightrans = TestProperties.SpecializedSimulations.Hightransmission hightrans_parameters = { Simkeys.number_agents : Hightrans.n, Simkeys.initial_infected_count: Hightrans.n_infected, Simkeys.number_simulated_days: Hightrans.n_days, Transkeys.contacts_per_agent: Hightrans.contacts, Transkeys.beta : Hightrans.beta, Progkeys.exposed_to_infectious: Hightrans.serial, Progkeys.exposed_to_infectious_std: Hightrans.serial_std, Progkeys.infectiousness_duration: Hightrans.dur } self.set_simulation_parameters(hightrans_parameters) pass # endregion pass