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 test__school_contact_matrices():
    interaction_instance = Interaction.from_file()
    xi = 0.3
    age_min = 3
    age_max = 7
    school_years = tuple(range(age_min, age_max + 1))
    contact_matrix = interaction_instance.contact_matrices["school"]
    n_contacts_same_year = interaction._get_contacts_in_school(
        contact_matrix, school_years, 4, 4)
    assert n_contacts_same_year == 2.875 * 3

    n_contacts_year_above = interaction._get_contacts_in_school(
        contact_matrix, school_years, 4, 5)
    assert n_contacts_year_above == xi * 2.875 * 3

    n_contacts_teacher_teacher = interaction._get_contacts_in_school(
        contact_matrix, school_years, 0, 0)
    assert n_contacts_teacher_teacher == 5.25 * 3

    n_contacts_teacher_student = interaction._get_contacts_in_school(
        contact_matrix, school_years, 0, 4)
    np.isclose(n_contacts_teacher_student, (16.2 * 3 / len(school_years)),
               rtol=1e-6)

    n_contacts_student_teacher = interaction._get_contacts_in_school(
        contact_matrix, school_years, 4, 0)
    assert n_contacts_student_teacher == 0.81 * 3
Example #3
0
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__contact_matrices_from_default():
    interaction = Interaction.from_file(config_filename=test_config)
    np.testing.assert_allclose(
        interaction.contact_matrices["pub"],
        np.array([[3 * (1 + 0.12) * 24 / 3]]),
        rtol=0.05,
    )
    xi = 0.3
    contacts_school = interaction.contact_matrices["school"]
    for i in range(len(contacts_school)):
        for j in range(len(contacts_school)):
            if i == j:
                if i == 0:
                    assert contacts_school[i][j] == 5.25 * 3  # 24 / 8
                else:
                    assert contacts_school[i][j] == 2.875 * 3
            else:
                if i == 0:
                    assert np.isclose(contacts_school[i][j],
                                      16.2 * 3,
                                      rtol=1e-6)
                elif j == 0:
                    assert np.isclose(contacts_school[i][j],
                                      0.81 * 3,
                                      atol=0,
                                      rtol=1e-6)
                else:
                    assert np.isclose(
                        contacts_school[i][j],
                        xi**abs(i - j) * 2.875 * 3,
                        atol=0,
                        rtol=1e-6,
                    )
Example #5
0
 def apply(self, date: datetime, interaction: Interaction):
     active_policies = self.get_active(date)
     beta_reductions = defaultdict(lambda: 1.0)
     for policy in active_policies:
         beta_reductions_dict = policy.apply()
         for group in beta_reductions_dict:
             beta_reductions[group] *= beta_reductions_dict[group]
     interaction.beta_reductions = beta_reductions
Example #6
0
def create_interaction():
    interaction = Interaction.from_file()
    interaction.beta['school'] = 0.8
    interaction.beta['cinema'] = 0.0
    interaction.beta['pub'] = 0.0
    interaction.beta['household'] = 10.0
    interaction.alpha_physical = 2.7
    return interaction
    def apply(self, date: datetime, interaction: Interaction):
        """
        Implement social distancing policy
        
        -----------
        Parameters:
        betas: e.g. (dict) from DefaultInteraction, e.g. DefaultInteraction.from_file(selector=selector).beta

        Assumptions:
        - Currently we assume that social distancing is implemented first and this affects all
          interactions and intensities globally
        - Currently we assume that the changes are not group dependent
        TODO:
        - Implement structure for people to adhere to social distancing with a certain compliance
        - Check per group in config file
        """
        if self.end_time == date:  # deactivate policy, restore betas.
            for key, value in self.original_betas.items():
                interaction.beta[key] = value

        if self.start_time == date:  # activate policy, save current betas.
            for key, value in self.beta_factors.items():
                self.original_betas[key] = interaction.beta[key]
                interaction.beta[key] = interaction.beta[key] * value
def test__checkpoints_are_saved(selector):
    june.simulator.logger.disabled = True
    sim = run_simulator(selector)
    fresh_world = generate_world_from_hdf5("./checkpoint_world.hdf5")
    interaction = Interaction.from_file()
    policies = Policies([])
    sim_recovered = Simulator.from_checkpoint(
        world=fresh_world,
        checkpoint_path="tests/checkpoint_2020-03-25.pkl",
        interaction=interaction,
        infection_selector=selector,
        config_filename=test_config,
        leisure=None,
        policies=policies,
        save_path="tests",
    )
    # check timer is correct
    assert sim_recovered.timer.initial_date == sim.timer.initial_date
    assert sim_recovered.timer.final_date == sim.timer.final_date
    assert sim_recovered.timer.now == sim.timer.now
    assert sim_recovered.timer.date.date() == datetime.datetime(2020, 3, 26).date()
    assert sim_recovered.timer.shift == sim.timer.shift
    assert sim_recovered.timer.delta_time == sim.timer.delta_time
    for person1, person2 in zip(sim.world.people, sim_recovered.world.people):
        assert person1.id == person2.id
        if person1.health_information is not None:
            assert person2.health_information is not None
            h1 = person1.health_information
            h2 = person2.health_information
            for slot in h1.__slots__:
                if slot == "infection":
                    inf1 = h1.infection
                    inf2 = h2.infection
                    assert inf1.start_time == inf1.start_time
                    assert inf1.last_time_updated == inf1.last_time_updated
                    assert inf1.infection_probability == inf2.infection_probability
                    assert inf1.transmission.probability == inf2.transmission.probability
                    assert inf1.symptoms.tag == inf2.symptoms.tag
                    assert inf1.symptoms.max_severity == inf2.symptoms.max_severity
                    continue
                p1_attr = getattr(person1.health_information, slot)
                p2_attr = getattr(person2.health_information, slot)
                assert p1_attr == p2_attr
        assert person1.susceptible == person2.susceptible
        assert person1.infected == person2.infected
        assert person1.recovered == person2.recovered
        assert person1.susceptibility == person2.susceptibility
        assert person1.dead == person2.dead
Example #9
0
def setup_sim(dummy_world, selector):
    world = dummy_world
    leisure_instance = leisure.generate_leisure_for_world(
        world=world, list_of_leisure_groups=["pubs", "cinemas", "groceries"])
    leisure_instance.distribute_social_venues_to_households(world.households)
    interaction = Interaction.from_file()
    policies = Policies.from_file()
    sim = Simulator.from_file(
        world=world,
        infection_selector=selector,
        interaction=interaction,
        config_filename=test_config,
        leisure=leisure_instance,
        policies=policies,
    )
    sim.activity_manager.leisure.generate_leisure_probabilities_for_timestep(
        3, False)
    return sim
def test__average_time_to_infect(n_teachers, mode):
    selector_config = paths.configs_path / "defaults/transmission/TransmissionConstant.yaml"
    transmission_probability = 0.1
    selector = InfectionSelector.from_file(
        transmission_config_path=selector_config)
    n_students = 1
    contact_matrices = {
        "contacts": [[n_teachers - 1, 1], [1, 0]],
        "proportion_physical": [[
            0,
            0,
        ], [0, 0]],
        "xi": 1.0,
        "characteristic_time": 24,
    }
    interaction = Interaction(
        beta={
            "school": 1,
        },
        alpha_physical=1,
        contact_matrices={"school": contact_matrices},
    )
    n_days = []
    for _ in range(200):
        people, school = create_school(n_students, n_teachers)
        for student in people[:n_students]:
            selector.infect_person_at_time(student, time=0)
        for teacher in people[n_students:n_students + n_teachers - 1]:
            selector.infect_person_at_time(teacher, time=0)
        school.clear()
        teacher = people[-1]
        n_days.append(
            days_to_infection(interaction, teacher, school, people,
                              n_students))
    teacher_teacher = transmission_probability * (n_teachers - 1)
    student_teacher = transmission_probability / n_students
    np.testing.assert_allclose(
        np.mean(n_days),
        1.0 / (teacher_teacher + student_teacher),
        rtol=0.1,
    )
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 make_interaction(self):
     interaction = Interaction.from_file(
         config_filename=self.baseline_interaction_path, population=self.population
     )
     if self.alpha_physical is not None:
         interaction.alpha_physical = self.alpha_physical
     if self.betas is not None:
         allowed_betas = interaction.beta
         for key, value in self.betas.items():
             if key not in allowed_betas:
                 raise ValueError(
                     f"Trying to change a beta for a non-existing group."
                 )
             else:
                 interaction.beta[key] = value
     # susceptibility
     if self.susceptibilities_by_age is not None:
         interaction.susceptibilities_by_age = self.susceptibilities_by_age
         interaction.set_population_susceptibilities(
             population=self.population,
             susceptibilities_by_age=self.susceptibilities_by_age,
         )
     return interaction
Example #13
0
# =================================== policies ===============================#

policies = Policies.from_file(
    camp_configs_path / "defaults/policy/home_care_policy.yaml",
    base_policy_modules=("june.policy", "camps.policy"),
)

# ============================================================================#

# =================================== infection ===============================#


selector = InfectionSelector.from_file(health_index_generator=health_index_generator)

interaction = Interaction.from_file(
    config_filename=camp_configs_path
    / "defaults/interaction/ContactInteraction_med_low_low_low.yaml",
)


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"
Example #14
0
def create_interaction():
    interaction = Interaction.from_file()
    interaction.selector = infect.InfectionSelector.from_file(
        transmission_config_path=constant_config)
    return interaction
Example #15
0
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
Example #16
0
                                      include_commute=True)

print("World length", len(world.people))
world.to_hdf5("world.hdf5")

world = generate_world_from_hdf5("world.hdf5")

# leisure
geography = load_geography_from_hdf5("world.hdf5")
world.cinemas = Cinemas.for_geography(geography)
world.pubs = Pubs.for_geography(geography)
world.groceries = Groceries.for_super_areas(world.super_areas,
                                            venues_per_capita=1 / 500)
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,
)
Example #17
0
def create_interaction():
    interaction = Interaction.from_file()
    return interaction
        camp_configs_path / "defaults/policy/home_care_policy.yaml",
        base_policy_modules=("june.policy", "camps.policy"),
    )

# ============================================================================#

# =================================== infection ===============================#

selector = InfectionSelector(
    health_index_generator=health_index_generator,
    transmission_config_path=transmission_config_path,
)

interaction = Interaction.from_file(
    config_filename=camp_configs_path / "defaults/interaction/" /
    args.parameters,
    population=world.people,
)

if args.child_susceptibility:
    interaction = Interaction.from_file(
        config_filename=camp_configs_path /
        "defaults/interaction/ContactInteraction_med_low_low_low_child.yaml",
        population=world.people,
    )
else:
    interaction = Interaction.from_file(
        config_filename=camp_configs_path / "defaults/interaction/" /
        args.parameters,
        population=world.people,
    )