def test__seed_with_age_profile(selector, ): geography = Geography.from_file(filter_key={"super_area": ["E02004940"]}) demography = Demography.for_geography(geography) for area in geography.areas: area.populate(demography) seed = InfectionSeed(super_areas=geography.super_areas, selector=selector, age_profile={ '0-9': 0., '10-39': 1., '40-100': 0. }) seed.unleash_virus(100) should_not_infected = [ person for super_area in geography.super_areas for person in super_area.people if person.infected and (person.age < 10 or person.age >= 40) ] assert len(should_not_infected) == 0 should_infected = [ person for super_area in geography.super_areas for person in super_area.people if person.infected and (person.age >= 10 and person.age < 40) ] assert len(should_infected) == 100
def test__full_run(dummy_world, selector): world = dummy_world # restore health status of people for person in world.people: person.health_information = None person.susceptibility = 1.0 person.dead = False leisure_instance = leisure.generate_leisure_for_world( world=world, list_of_leisure_groups=[ "pubs", "cinemas", "groceries", "household_visits", "care_home_visits", ], ) leisure_instance.distribute_social_venues_to_households(world.households) interaction = Interaction.from_file() policies = Policies.from_file() sim = Simulator.from_file( world=world, interaction=interaction, infection_selector=selector, config_filename=test_config, leisure=leisure_instance, policies=policies, save_path=None, ) seed = InfectionSeed(sim.world.super_areas, selector) seed.unleash_virus(1) sim.run()
def test__simple_age_profile_test(selector, ): n_people = 10000 ages = np.random.randint(low=0, high=100, size=n_people) people = [Person.from_attributes(age=ages[n]) for n in range(n_people)] seed = InfectionSeed(super_areas=None, selector=selector, age_profile={ '0-9': 0.3, '10-39': 0.5, '40-100': 0.2 }) choice = seed.select_from_susceptible(people, 1000, age_profile=seed.age_profile) ages_infected = np.array([person.age for person in people])[choice] count = Counter(ages_infected) count_0_9 = sum([ count_value for count_key, count_value in count.items() if count_key < 10 ]) assert count_0_9 / len(ages_infected) == pytest.approx(0.3, 0.05) count_10_39 = sum([ count_value for count_key, count_value in count.items() if count_key >= 10 and count_key < 40 ]) assert count_10_39 / len(ages_infected) == pytest.approx(0.5, 0.05) count_40_100 = sum([ count_value for count_key, count_value in count.items() if count_key > 40 ]) assert count_40_100 / len(ages_infected) == pytest.approx(0.2, 0.05)
def test_box_full_run(simulator_box, selector): seed = InfectionSeed( simulator_box.world.boxes, selector, ) seed.unleash_virus(10, box_mode=True) simulator_box.run()
def test__infection_is_isolated(selector): geography = Geography.from_file({"area": ["E00002559"]}) world = generate_world_from_geography(geography, include_households=True) interaction = Interaction.from_file() infection_seed = InfectionSeed(world.super_areas, selector) n_cases = 5 infection_seed.unleash_virus( n_cases) # play around with the initial number of cases policies = Policies([]) simulator = Simulator.from_file( world=world, interaction=interaction, infection_selector=selector, config_filename=pathlib.Path(__file__).parent.absolute() / "interaction_test_config.yaml", leisure=None, policies=policies, save_path=None, ) infected_people = [person for person in world.people if person.infected] assert len(infected_people) == 5 infected_households = [] for household in world.households: infected = False for person in household.people: if person.infected: infected = True break if infected: infected_households.append(household) assert len(infected_households) <= 5 simulator.run() for person in world.people: if not (person.residence.group in infected_households): assert not person.infected and person.susceptible
def get_seed(geography, selector, demography): super_area_to_region = pd.DataFrame({ "super_area": SUPER_AREA_LIST, "region": REGION_LIST }) return InfectionSeed(geography.super_areas, selector, None, super_area_to_region)
def run_simulator(selector): world = create_world() world.to_hdf5("./checkpoint_world.hdf5") # restore health status of people for person in world.people: person.health_information = None person.susceptibility = 1.0 person.dead = False interaction = Interaction.from_file() policies = Policies([]) sim = Simulator.from_file( world=world, interaction=interaction, infection_selector=selector, config_filename=test_config, leisure=None, policies=policies, save_path="tests", ) seed = InfectionSeed(sim.world.super_areas, selector) seed.unleash_virus(20) sim.run() return sim
def create_sim(world, interaction, selector): leisure_instance = leisure.generate_leisure_for_config( world=world, config_filename=test_config) leisure_instance.distribute_social_venues_to_households(world.households) policies = Policies([ Quarantine(n_days=5), Quarantine(n_days=10), CloseLeisureVenue(start_time="2020-3-1", end_time="2020-3-30", venues_to_close=['pub', 'cinema']) ]) infection_seed = InfectionSeed(super_areas=world.super_areas, selector=selector) n_cases = 2 infection_seed.unleash_virus(n_cases) sim = Simulator.from_file(world=world, interaction=interaction, infection_selector=selector, config_filename=test_config, leisure=leisure_instance, policies=policies) return sim
def make_infection_seed(self, infection_selector, world): oc = Observed2Cases.from_file( health_index_generator=infection_selector.health_index_generator, smoothing=True, ) daily_cases_per_region = oc.get_regional_latent_cases() daily_cases_per_super_area = oc.convert_regional_cases_to_super_area( daily_cases_per_region, dates=[self.seeding_start, self.seeding_end] ) infection_seed = InfectionSeed( world=world, infection_selector=infection_selector, daily_super_area_cases=daily_cases_per_super_area, seed_strength=self.seed_strength, age_profile=self.age_profile, ) return infection_seed
def test__seed_strength(selector, ): geography = Geography.from_file( filter_key={"super_area": [ "E02004940", "E02004935", "E02004936", ]}) demography = Demography.for_geography(geography) for area in geography.areas: area.populate(demography) n_cases_region = pd.DataFrame({ 'East of England': np.array([100, 200, 300, 400]).astype(np.int), 'date': [ '2020-03-01', '2020-03-02', '2020-03-03', '2020-03-04', ] }) n_cases_region.set_index('date', inplace=True) n_cases_region.index = pd.to_datetime(n_cases_region.index) seed = InfectionSeed.from_file(super_areas=geography.super_areas, selector=selector, n_cases_region=n_cases_region, seed_strength=0.2) timer = Timer( initial_day='2020-02-29', total_days=7, ) while timer.date <= timer.final_date: time = timer.date if (time >= seed.min_date) and (time <= seed.max_date): seed.unleash_virus_per_region(time) next(timer) n_infected = 0 for super_area in geography.super_areas: for person in super_area.people: if person.infected: n_infected += 1 n_cases = (seed.n_cases_region["East of England"].sum()) np.testing.assert_allclose(0.2 * n_cases, n_infected, rtol=0.05)
def generate_simulator(): record = Record(record_path=save_path, record_static_data=True, mpi_rank=mpi_rank) if mpi_rank == 0: with h5py.File(world_file, "r") as f: super_area_names = f["geography"]["super_area_name"][:] super_area_ids = f["geography"]["super_area_id"][:] super_area_names = [name.decode() for name in super_area_names] super_area_name_to_id = { key: value for key, value in zip(super_area_names, super_area_ids) } # make dictionary super_area_id -> domain domain_splitter = DomainSplitter(number_of_domains=mpi_size, world_path=world_file) super_areas_per_domain = domain_splitter.generate_domain_split( niter=20) super_area_names_to_domain_dict = {} super_area_ids_to_domain_dict = {} for domain, super_areas in super_areas_per_domain.items(): for super_area in super_areas: super_area_names_to_domain_dict[super_area] = domain super_area_ids_to_domain_dict[int( super_area_name_to_id[super_area])] = domain with open("super_area_ids_to_domain.json", "w") as f: json.dump(super_area_ids_to_domain_dict, f) with open("super_area_names_to_domain.json", "w") as f: json.dump(super_area_names_to_domain_dict, f) mpi_comm.Barrier() if mpi_rank > 0: with open("super_area_ids_to_domain.json", "r") as f: super_area_ids_to_domain_dict = json.load(f, object_hook=keys_to_int) domain = Domain.from_hdf5( domain_id=mpi_rank, super_areas_to_domain_dict=super_area_ids_to_domain_dict, hdf5_file_path=world_file, ) record.static_data(world=domain) # regenerate lesiure leisure = generate_leisure_for_config(domain, config_path) # # health index and infection selecctor health_index_generator = HealthIndexGenerator.from_file() infection_selector = InfectionSelector( health_index_generator=health_index_generator) oc = Observed2Cases.from_file( health_index_generator=health_index_generator, smoothing=True) daily_cases_per_region = oc.get_regional_latent_cases() daily_cases_per_super_area = oc.convert_regional_cases_to_super_area( daily_cases_per_region, dates=["2020-02-28", "2020-03-02"]) infection_seed = InfectionSeed( world=domain, infection_selector=infection_selector, daily_super_area_cases=daily_cases_per_super_area, seed_strength=100, ) # interaction interaction = Interaction.from_file( config_filename="./config_interaction.yaml", population=domain.people) # policies policies = Policies.from_file() # events events = Events.from_file() # create simulator travel = Travel() simulator = Simulator.from_file( world=domain, policies=policies, events=events, interaction=interaction, leisure=leisure, travel=travel, infection_selector=infection_selector, infection_seed=infection_seed, config_filename=config_path, record=record, ) print("simulator ready to go") return simulator
world.cemeteries = Cemeteries() selector = InfectionSelector.from_file() interaction = Interaction.from_file() print(interaction.beta) # modify interactions (example x 2) interaction.beta['household'] *= 2 print(interaction.beta) interaction.alpha_physical interaction.alpha_physical /= 2 interaction.alpha_physical # # Seed the disease # There are two options implemented in the seed at the moment, either you specify the number of cases and these are then homogeneously distributed by population to the different areas, or you use UK data on cases per region. For now use the first case. seed = InfectionSeed( world.super_areas, selector, ) n_cases = 50 seed.unleash_virus(n_cases) # play around with the initial number of cases # # Set policies policies = Policies.from_file() # # Run the simulation # Since the timer configuration is a bit cumbersome, it is read from the config file at ``configs/config_example.yml CONFIG_PATH = "configs/config_example.yaml" leisure = generate_leisure_for_config(world=world, config_filename=CONFIG_PATH) simulator = Simulator.from_file(world, interaction, selector,
print("World loaded succesfully") # regenerate lesiure leisure = generate_leisure_for_config(world, config_path) # health index and infection selecctor health_index_generator = HealthIndexGenerator.from_file(asymptomatic_ratio=0.2) infection_selector = InfectionSelector.from_file( health_index_generator=health_index_generator) # interaction interaction = Interaction.from_file() # initial infection seeding infection_seed = InfectionSeed( world.super_areas, infection_selector, ) infection_seed.unleash_virus(50) # number of initial cases # policies policies = Policies.from_file() # create simulator simulator = Simulator.from_file( world=world, policies=policies, interaction=interaction, leisure=leisure, infection_selector=infection_selector,
cases_detected = { "CXB-202": 3, "CXB-204": 6, "CXB-208": 8, "CXB-203": 1, "CXB-207": 2, "CXB-213": 2, } # By the 24th May print("Detected cases = ", sum(cases_detected.values())) msoa_region_filename = camp_data_path / "input/geography/area_super_area_region.csv" msoa_region = pd.read_csv(msoa_region_filename)[["super_area", "region"]] infection_seed = InfectionSeed( super_areas=world.super_areas, selector=selector, msoa_region=msoa_region ) for key, n_cases in cases_detected.items(): infection_seed.unleash_virus_regional_cases(key, n_cases * 10) # Add some extra random cases infection_seed.unleash_virus(n_cases=100) print("Infected people in seed = ", len(world.people.infected)) CONFIG_PATH = camp_configs_path / "learning_center_config.yaml" # ==================================================================================# # =================================== leisure config ===============================# leisure_instance = generate_leisure_for_config(world=world, config_filename=CONFIG_PATH)
cases_detected = { "CXB-202": 3, "CXB-204": 6, "CXB-208": 8, "CXB-203": 1, "CXB-207": 2, "CXB-213": 2, } # By the 24th May print("Detected cases = ", sum(cases_detected.values())) super_region_filename = camp_data_path / "input/geography/area_super_area_region.csv" super_region_df = pd.read_csv(super_region_filename)[["super_area", "region"]] infection_seed = InfectionSeed( world=world, infection_selector=selector, ) for region in world.regions: if region.name in cases_detected.keys(): infection_seed.unleash_virus( n_cases=2 * cases_detected[region.name], population=Population(region.people), ) # Add some extra random cases infection_seed.unleash_virus(n_cases=44, population=world.people) print("Infected people in seed = ", len(world.people.infected)) # ==================================================================================# # =================================== leisure config ===============================#