def test_createInfectedPersons3(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) kids = [random.randint(0,17) for i in range(5)] adults = [random.randint(19,40) for i in range(5)] ageList = kids + adults PersonList = list(map(Person, ageList)) env_arr = [] my_world = World( all_people = PersonList, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.infect_random_set(num_infected = 0, infection_doc = "", per_to_immune = 0.5,Immune_compliance = 0,city_name = None,min_age=18,people_per_day =5) my_simulation.simulate_day() #assert events dictionary is not empty cnt_immune = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune = cnt_immune + 1 assert cnt_immune == 0
def test_createInfectedPersons(helpers): """ #create population with 5 people ages [9,19,29,39,49] #test that each day one of them is getting immuned """ helpers.clean_outputs() #Editig confige file saving is nessery config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") ConfigData = None #reading the confige file with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) persons_arr = list(map(Person, [9,19,29,39,49,59])) assert len(persons_arr) == 6 env_arr = [] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.run_simulation(7,"test_simulation",datas_to_plot = None,extensionsList = ["ImmuneByAgeExtension","EmptyExtension"] ) cnt = sum([1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE]) assert cnt == 4
def create_city_and_serialize(city_name, scale, params_to_change): """ Generate population of a given city. Done once for each triplet (city, scale, params_to_change). :param city_name: str city name, "all" for entire country :param scale: float between 0-1, that states the size proportion of the city. 1 if for actual size :param params_to_change: dict of params to change, in Params object :return: World object """ config_path = os.path.dirname(__file__) + "/config.json" with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) citiesDataPath = ConfigData['CitiesFilePath'] paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath), override=True) #Check if dictionary is empty if not params_to_change: for param, val in params_to_change.items(): Params.loader()[param] = val population_loader = PopulationLoader( citiesDataPath, added_description=Params.loader().description(), with_caching=False) else: population_loader = PopulationLoader(citiesDataPath, added_description="", with_caching=False) population_loader.get_world(city_name=city_name, scale=scale)
def test_createInfectedPersonsOredredASCENDING(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) kids = [0,4,8,12,16] adults = [25,29,33] ageList = kids + adults youngest = Person(21) Oldest = Person(37) PersonList = list(map(Person, ageList)) PersonList = PersonList + [youngest , Oldest] env_arr = [] my_world = World( all_people = PersonList, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.infect_random_set(num_infected = 0, infection_doc = "", per_to_immune = 0.5,order= ORDER.ASCENDING,city_name = None,min_age=18,people_per_day =1) my_simulation.simulate_day() assert youngest.get_disease_state() == DiseaseState.IMMUNE #Can't check day by day lots of noise with seir times for _ in range(4): my_simulation.simulate_day() cnt_immune =0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune = cnt_immune + 1 assert cnt_immune <= 5
def test_SIRS_second_infection(): """ Test that in SIRS model in case that a person get sick twice, (and get recovered between them). He will experience two different time schedule of the illness """ #Pretest Params.clean() SIRS.clean() config_path = os.path.join( os.path.dirname(__file__), "tests_config_files", "test_latent_incubating_critical_immune_config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "tests_params_files", paramsDataPath), override=True) Params.loader()["person"]["state_macine_type"] = "SIRS" p = Person(30) event_lst = p.infect_and_get_events(INITIAL_DATE, InitialGroup.initial_group()) p.set_disease_state(DiseaseState.SUSCEPTIBLE) event_lst2 = p.infect_and_get_events(INITIAL_DATE, InitialGroup.initial_group()) assert not (event_lst == event_lst2)
def test_latent_incubating_critical_deceased(): #Pretest Params.clean() SIRS.clean() config_path = os.path.join( os.path.dirname(__file__), "tests_config_files", "test_latent_incubating_critical_deceased_config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "tests_params_files", paramsDataPath), override=True) p = Person(30) for _ in range(100): for cur_type in machine_type: tbl = sample_seir_times(cur_type, p) assert tbl[0][0] == DiseaseState.LATENT, "{}".format(cur_type.name) assert tbl[1][0] == DiseaseState.INCUBATINGPOSTLATENT, "{}".format( cur_type.name) assert tbl[2][ 0] == DiseaseState.SYMPTOMATICINFECTIOUS, "{}".format( cur_type.name) assert tbl[3][0] == DiseaseState.CRITICAL, "{}".format( cur_type.name) assert tbl[4][0] == DiseaseState.DECEASED, "{}".format( cur_type.name)
def test_sample_SIRS_seirs_times(): #Pretest Params.clean() SIRS.clean() config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) curr_machine_type = machine_type["SIRS"] p = Person(94) final_states = [] for i in range(1000): table = sample_seir_times(curr_machine_type, p) assert table[0][0] == DiseaseState.LATENT final_states.append(table[-1][0]) cnt_table = Counter(final_states) assert DiseaseState.DECEASED in cnt_table.keys() assert DiseaseState.SUSCEPTIBLE in cnt_table.keys() assert len(cnt_table.keys()) == 2
def test_propagate_infection(params_path): """ tests the consistency of the propagate_infection function in HomogenousEnvironment """ Params.load_from(params_path) DiseaseState.init_infectiousness_list() percent_infected = 0.1 contact_prob = 0.25 num_of_people = 400 weight_list = [ max(0.3, random.random() - 0.1) for _ in range(num_of_people) ] env = HomogeneousEnvironment(contact_prob, "test") total = 0 infections = [] loops = 100 for _ in range(loops): env._person_dict = { Person(random.randint(20, 60)): weight_list[i] for i in range(num_of_people) } for p, w in env._person_dict.items(): if percent_infected < random.random(): p._disease_state = DiseaseState.ASYMPTOMATICINFECTIOUS else: p._disease_state = DiseaseState.SUSCEPTIBLE p._change() env.sign_up_for_today(p, w) num_of_infections = len( env.propagate_infection(date(year=2020, month=12, day=1))) infections.append(num_of_infections) total += num_of_infections avg = total / loops assert abs(avg - median(infections)) < 10
def test_immune_and_get_events2(): config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) p = Person(30) ok,events = p.immune_and_get_events(INITIAL_DATE , timedelta(days = 20), \ ((DiseaseState.SUSCEPTIBLE,timedelta(10)),(DiseaseState.LATENT,timedelta(5)), \ (DiseaseState.SUSCEPTIBLE,None))) assert len(events) == 3 assert ok persons_arr = [p] env_arr = [] small_world = world.World(all_people=persons_arr, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=small_world, initial_date=INITIAL_DATE, interventions=[]) for i in range(10): my_simulation.simulate_day() events[0].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.LATENT for i in range(5): my_simulation.simulate_day() events[1].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.IMMUNE
def test_createInfectedPersonsBestEffort2(): """ Test that when the population size is less then the amount of people that had been chosen to be infected, the simulation doesn't crash """ config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) ageList = [random.randint(19,40) for i in range(10)] PersonList = list(map(Person, ageList)) env_arr = [] my_world = World( all_people = PersonList, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.infect_random_set(num_infected = 0, infection_doc = "", per_to_immune = 2,city_name = None,min_age=18,people_per_day =0) my_simulation.simulate_day() cnt_immune = 0 cnt_sick = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune += 1 else: cnt_sick += 1 assert cnt_immune == 10 assert cnt_sick == 0
def create_and_run_simulation(self, outdir, stop_early, with_population_caching=True, verbosity=False): """ The main function that handles the run of the simulation by the task. It updated the params changes, loads or creates the population, initializes the simulation and runs it. :param outdir: the output directory for the task :param stop_early: only relevant to R computation, see Simulation doc :param with_population_caching: bool, if False generates the population, else - tries to use the cache and save time. :param verbosity: bool, if it's True then additional output logs will be printed to the screen """ seed.set_random_seed() config_path = os.path.join(os.path.dirname(__file__), "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) citiesDataPath = ConfigData['CitiesFilePath'] paramsDataPath = ConfigData['ParamsFilePath'] Extensionslst = ConfigData['ExtensionsNamelst'] Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath), override=True) for param, val in self.params_to_change.items(): Params.loader()[param] = val DiseaseState.init_infectiousness_list() citiesDataPath = citiesDataPath population_loader = PopulationLoader( citiesDataPath, added_description=Params.loader().description(), with_caching=with_population_caching, verbosity=verbosity) world = population_loader.get_world(city_name=self.city_name, scale=self.scale, is_smart=True) ExtensionType = None sim = Simulation(world, self.initial_date, self.interventions, verbosity=verbosity, outdir=outdir, stop_early=stop_early) self.infection_params.infect_simulation(sim, outdir) if len(Extensionslst) > 0: sim.run_simulation(self.days, self.scenario_name, datas_to_plot=self.datas_to_plot, extensionsList=Extensionslst) else: sim.run_simulation(self.days, self.scenario_name, datas_to_plot=self.datas_to_plot, extensionsList=None)
def __init__(self, age, environments=None): params = Params.loader()['population'] R0 = params["R0_percent"] StartAsRecovered = False #if random.random() < R0: # StartAsRecovered = True self._changed = True if not environments: environments = [] self._age = age assert len(set([ env.name for env in environments ])) == len(environments), "Got duplicate environment names" self._environments = {env.name: env for env in environments} self._current_routine = { env_name: 1 for env_name in self._environments } params = Params.loader()['person'] self._infectiousness_prob = \ min(params['base_infectiousness'] * \ _np.random.gamma( params['individual_infectiousness_gamma_shape'], params['individual_infectiousness_gamma_scale'] ), 1) #if StartAsRecovered: # self._disease_state = DiseaseState.IMMUNE # self.is_susceptible = False # self.is_infected = True #else: self._disease_state = DiseaseState.SUSCEPTIBLE self.is_susceptible = True self.is_dead = False self.is_infectious = False self.is_infected = False str_type = params['state_macine_type'] assert str_type in ['SIRS', 'SIR'] self.state_machine_type = machine_type[str_type] self._id = Person.num_people_so_far # hold all the events that are triggered by some disease state(s) change(s), like isolation when symptomatic self.state_to_events = {} # The following counts the number of different interventions that force each routine change on this person. # For instance, I might be in quarantine because I'm old and because I'm symptomatic. # Without this counter, people could go into quarantine because they're old, get symptoms during quarantine, # then go out of quarantine when the symptoms pass. self.routine_change_multiplicities = {} self.routine_changes = {} self._infection_data = None # Table that currespond to seir times and events so it will be easier to mange self._seir_times = None self._my_neighborhood = None self._num_infections = 0 #if StartAsRecovered: # self.last_state =RedactedPerson(self.get_age(), self.get_disease_state()) #else: self.last_state = None Person.num_people_so_far += 1
def test_createInfectedPersonsByHouseHoldBestEffort2(): """ Test that when the population size is less then the amount of people that had been chosen to be infected by households, the simulation doesn't crash """ config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) #create diff enviroments KidsHouse = Household(city = None,contact_prob_between_each_two_people=1) AdultsHouse = Household(city = None,contact_prob_between_each_two_people=1) MixedHouse = Household(city = None,contact_prob_between_each_two_people=1) kidsAges = [random.randint(0,17) for i in range(4)] adultsAges = [random.randint(19,40) for i in range(3)] KidsLst = list(map(Person, kidsAges)) adultsLst = list(map(Person, adultsAges)) persons_arr = KidsLst + adultsLst #register people to diff env KidsHouse.sign_up_for_today(KidsLst[0],1) KidsHouse.sign_up_for_today(KidsLst[1],1) AdultsHouse.sign_up_for_today(adultsLst[0],1) AdultsHouse.sign_up_for_today(adultsLst[1],1) MixedHouse.sign_up_for_today(adultsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[3],1) assert len(KidsHouse.get_people()) == 2 assert len(AdultsHouse.get_people()) == 2 assert len(MixedHouse.get_people()) == 3 env_arr = [KidsHouse,AdultsHouse,MixedHouse] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1,) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.immune_households_infect_others(num_infected = 0, infection_doc = "", per_to_immune = 2 ,city_name = None,min_age=18,people_per_day =5) my_simulation.simulate_day() cnt_immune = 0 cnt_sick = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune += 1 elif person.get_disease_state() != DiseaseState.SUSCEPTIBLE: cnt_sick += 1 assert cnt_immune == 3 assert cnt_sick == 0
def test_ImmuneGeneralPopulationIntervention(): #pretesting config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) my_intervention = ImmuneGeneralPopulationIntervention( compliance=1, start_date=INITIAL_DATE, duration=daysdelta(40), people_per_day=1, min_age=15) assert my_intervention is not None persons_arr = list(map(Person, [10, 20, 30])) assert len(persons_arr) == 3 env_arr = [] small_world = World(all_people=persons_arr, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=small_world, initial_date=INITIAL_DATE, interventions=[my_intervention]) #test lst = my_intervention.generate_events(small_world) #Assert results assert lst is not None assert len(lst) == 2 for i in range(1): assert isinstance(lst[i], DayEvent) my_simulation.simulate_day() cnt_immune = sum([ 1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE ]) assert cnt_immune == 1 my_simulation.simulate_day() cnt_immune = sum([ 1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE ]) assert cnt_immune == 2 my_simulation.simulate_day() cnt_immune = sum([ 1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE ]) assert cnt_immune == 2
def test_createImmunehouseholds4(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) #create diff enviroments KidsHouse = Household(city = None,contact_prob_between_each_two_people=1) AdultsHouse = Household(city = None,contact_prob_between_each_two_people=1) MixedHouse = Household(city = None,contact_prob_between_each_two_people=1) kidsAges = [random.randint(0,17) for i in range(4)] adultsAges = [random.randint(19,40) for i in range(3)] KidsLst = list(map(Person, kidsAges)) adultsLst = list(map(Person, adultsAges)) persons_arr = KidsLst + adultsLst #register people to diff env KidsHouse.sign_up_for_today(KidsLst[0],1) KidsHouse.sign_up_for_today(KidsLst[1],1) AdultsHouse.sign_up_for_today(adultsLst[0],1) AdultsHouse.sign_up_for_today(adultsLst[1],1) MixedHouse.sign_up_for_today(adultsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[3],1) assert len(KidsHouse.get_people()) == 2 assert len(AdultsHouse.get_people()) == 2 assert len(MixedHouse.get_people()) == 3 env_arr = [KidsHouse,AdultsHouse,MixedHouse] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1,) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.immune_households_infect_others(num_infected = 0, infection_doc = "", per_to_immune = 1,Immune_compliance= 0 ,city_name = None,min_age=18,people_per_day= 3 ) my_simulation.simulate_day() #assert events dictionary is not empty cnt_immune = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune = cnt_immune + 1 assert cnt_immune == 0
def test_create_SIRS_machine(): #Pretest Params.clean() SIRS.clean() config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) b = SIRS.make() assert isinstance(b, SIRS)
def city_curfew_routine(person: Person, city_name): """ Create a routine change that represents a city curfew effect on a person routine. Here we try to represent the changing (decreasing/ increasing of weights) of the weight in all the environment, due to the closure of the city. :param person: Person :return: routine change dict, keys are environment names, values are weight multipliers. """ params = Params.loader()["interventions_routines"]["city_curfew"] routine = {} has_free_time = False for env_name, env in person._environments.items(): if env._city is None: continue if not ((env._city.get_name() == city_name) ^ (person.get_city_name() == city_name)): continue else: routine[env_name] = params["out_of_city"] has_free_time = True if has_free_time: routine['household'] = params["in_city"]["household"] routine['city_community'] = params["in_city"]["city_community"] routine['neighborhood_community'] = params["in_city"]["neighborhood_community"] return routine
def __init__(self): params = Params.loader()['disease_parameters'] self.symptomatic_given_infected_per_age = params[ "symptomatic_given_infected_per_age"] self.hospitalization_given_symptomatic_per_age = params[ "hospitalization_given_symptomatic_per_age"] self.critical_given_hospitalized_per_age = params[ "critical_given_hospitalized_per_age"] self.deceased_given_critical_per_age = params[ "deceased_given_critical_per_age"] self._latent_period_distribution = self.generate_gamma_distribution( params["latent_period_gamma_params"]) self._infectious_before_symptomatic_distribution = self.generate_gamma_distribution( params["infectious_before_symptomatic_gamma_params"]) self._infectious_before_immune_distribution = self.generate_gamma_distribution( params["infectious_before_immune_gamma_params"]) self._symptomatic_before_critical_distribution = self.generate_gamma_distribution( params["symptomatic_before_critical_gamma_params"]) self._symptomatic_before_immune_distribution = self.generate_gamma_distribution( params["symptomatic_before_immune_gamma_params"]) self._critical_before_deceased_distribution = self.generate_gamma_distribution( params["critical_before_deceased_gamma_params"]) self._critical_before_immune_distribution = self.generate_gamma_distribution( params["critical_before_immune_gamma_params"])
def test_sortPersonsDescending(): config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) persons_arr = [Person(random.randint(0, 99)) for _ in range(20)] persons_arr = sorted(persons_arr, key=cmp_to_key(Person.person_comperator_DESCENDING)) for i in range(1, 20): assert persons_arr[i - 1].get_age() >= persons_arr[i].get_age()
def test_create_SIR_machine(): #Pretest Params.clean() RealDataSeirTimesGeneration.clean() config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) #Assert able to create statte machines properly a = RealDataSeirTimesGeneration.make() assert isinstance(a, RealDataSeirTimesGeneration)
def write_params(self): """ Write a params.json file corresponding to the parameters used to the output directory (for documentation purposes) """ params_path = os.path.join(self._output_path, 'params.json') params = Params.loader() assert params == self._params_at_init, "Params changed mid-simulation!" params.dump(params_path)
def test_Init_haifa(): citiesDataPath = "" config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) citiesDataPath = ConfigData['CitiesFilePath'] paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath), override=True) pop = population_loader.PopulationLoader(citiesDataPath, added_description="", with_caching=False, verbosity=False) world = pop.get_world(city_name='Haifa', scale=1, is_smart=False) assert world is not None
def quarantine_routine(person: Person): """ Create a routine change that represents a person being in quarantine. Here we try to represent the changing (decreasing of weights) of the weight in all the environment, due to the quarantine. :param person: Person :return: routine change dict, keys are environment names, values are weight multipliers. """ params = Params.loader()["interventions_routines"]["quarantine"] return {env_name: params["all"] for env_name in person.get_routine()}
def test_CreateDeltaFile(helpers): helpers.clean_outputs() config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) ageList = [random.randint(0, 40) for i in range(10)] PersonList = list(map(Person, ageList)) events_acc = [] for person in PersonList: states_table = ((DiseaseState.LATENT, daysdelta(3)), (DiseaseState.ASYMPTOMATICINFECTIOUS, daysdelta(3)), (DiseaseState.IMMUNE, daysdelta(3)), (DiseaseState.IMMUNE, None)) events = person.gen_and_register_events_from_seir_times( date=INITIAL_DATE, states_and_times=states_table) events_acc += events # person.set_disease_state(DiseaseState.LATENT) env_arr = [] my_world = World(all_people=PersonList, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=my_world, initial_date=INITIAL_DATE) my_simulation.register_events(events_acc) my_simulation.run_simulation(num_days=10, name="test") #assert events dictionary is not empty txt = my_simulation.stats.get_state_stratified_summary_table( table_format=TableFormat.CSV) test_data = StringIO(txt) tbl = pd.read_csv(test_data) assert len(tbl) == 7 print(tbl) assert tbl.iloc[0, DiseaseState.SUSCEPTIBLE.value] == 10 assert tbl.iloc[3, DiseaseState.ASYMPTOMATICINFECTIOUS.value] == 10 assert tbl.iloc[6, DiseaseState.IMMUNE.value] == 10
def test_createImmunehouseholds2(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) #create diff enviroments house1 = Household(city = None,contact_prob_between_each_two_people=1) house2 = Household(city = None,contact_prob_between_each_two_people=1) house1Ages = [98,93,5] house2Ages = [94,6] house1Lst = list(map(Person, house1Ages)) house2Lst = list(map(Person, house2Ages)) persons_arr = house1Lst + house2Lst #register people to diff env house1.sign_up_for_today(house1Lst[0],1) house1.sign_up_for_today(house1Lst[1],1) house1.sign_up_for_today(house1Lst[2],1) house2.sign_up_for_today(house2Lst[0],1) house2.sign_up_for_today(house2Lst[1],1) assert len(house1.get_people()) == 3 assert len(house2.get_people()) == 2 env_arr = [house1,house2] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1,) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.immune_households_infect_others(num_infected = 0, infection_doc = "", per_to_immune = 0.6,Sort_order=ORDER.DESCENDING ,city_name = None,min_age=18,people_per_day= 3 ) my_simulation.simulate_day() #assert events dictionary is not empty cnt_immune = 0 for person in my_world.all_people(): if (person.get_age() in [94,93,98]) and (person.get_disease_state() == DiseaseState.IMMUNE): cnt_immune = cnt_immune + 1 assert cnt_immune == 3
def test_immune_and_get_events5(): """ Test that a person that is not Susptible nor latent when he should get immuned continues his usual path to his death """ config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) p = Person(30) ok, events = p.immune_and_get_events(INITIAL_DATE , timedelta(days = 20), \ ((DiseaseState.SUSCEPTIBLE,timedelta(10)),(DiseaseState.LATENT,timedelta(5)),\ (DiseaseState.ASYMPTOMATICINFECTIOUS,timedelta(5)),(DiseaseState.DECEASED,timedelta(5)),(DiseaseState.DECEASED,None))) assert len(events) == 4 assert ok == False persons_arr = [p] env_arr = [] small_world = world.World(all_people=persons_arr, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=small_world, initial_date=INITIAL_DATE, interventions=[]) for i in range(10): my_simulation.simulate_day() events[0].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.LATENT for i in range(5): my_simulation.simulate_day() events[1].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.ASYMPTOMATICINFECTIOUS #Because this person was not susptible nor latent he cannot be immuned for i in range(5): my_simulation.simulate_day() events[2].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.DECEASED
def _save_on_me(self, world, is_smart): """ Saves a generated World to a local dict on this object :param world: The World we wish to save :param is_smart: Was the world generated using smart world generation :return: None """ tup = (world._generating_city_name, is_smart, world._generating_scale) assert tup not in self.city_smart_scale_to_world, "Dumping an existent city" self.city_smart_scale_to_world[tup] = (world, Params.loader())
def test_Init_haifaParms(): citiesDataPath = "" config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) citiesDataPath = ConfigData['CitiesFilePath'] paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath), override=True) pop = population_loader.PopulationLoader(citiesDataPath, added_description="", with_caching=False, verbosity=False) City1 = pop.get_city_by_name('Haifa') assert City1.region == 3 assert City1.nafa == 31
def assert_params_are_valid(params): """ Makes sure the params that appear in a serialized file are the same as the current ones we are using (otherwise there will be compatibility errors) :param params: The params that should be checked against the curret ones :return: None (throws an exception of it does not hold) """ assert params == Params.loader(), \ "Trying to load a file corresponding to different params!"
def test_neiborhoods_diff_IDs(): ''' Test different neiborhood get different ids ''' file_path = os.path.dirname(__file__) + "/../src/config.json" with open(file_path) as json_data_file: ConfigData = json.load(json_data_file) citiesDataPath = ConfigData['CitiesFilePath'] paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath), override=True) pop = population_loader.PopulationLoader(citiesDataPath) my_world = pop.get_world(city_name='Atlit', scale=1, is_smart=True) sample = [] for env in my_world.all_environments: if env.name == "neighborhood_community": sample.append(env) assert not (sample[0].get_neighborhood_id() == sample[1].get_neighborhood_id())