예제 #1
0
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)
예제 #2
0
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)
예제 #3
0
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
예제 #4
0
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)
예제 #5
0
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
예제 #6
0
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_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
예제 #8
0
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
예제 #9
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
    
예제 #10
0
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
예제 #11
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)
예제 #12
0
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
예제 #13
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
예제 #14
0
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
예제 #15
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)
예제 #16
0
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()
예제 #17
0
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)
예제 #18
0
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
예제 #19
0
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
예제 #20
0
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
예제 #21
0
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
예제 #22
0
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 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())
예제 #24
0
def test_SymptomaticIsolationIntervention_Genarete_events(helpers):
    #pretesting
    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)

    my_intervention = SymptomaticIsolationIntervention(compliance=1,
                                                       start_date=INITIAL_DATE,
                                                       duration=daysdelta(40))
    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) == 3
    for i in range(1):
        assert isinstance(lst[i], DayEvent)
    for person in persons_arr:
        assert len(list(person.state_to_events.keys())) == (1 + 4)

    my_simulation.run_simulation(name="test", num_days=60)
예제 #25
0
def test_CityGeneration():
    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)
    tmp_city = pop.get_city_by_name('Haifa')
    city = generate_city(tmp_city,
                         True,
                         internal_workplaces=True,
                         scaling=1.0,
                         verbosity=False,
                         to_world=True)

    humans = city.all_people()
    assert abs(283637 - len(humans)) < 5
    assert len(city.get_all_city_communities()) == 1
    assert city.get_person_from_id(humans[0]._id) is not None
예제 #26
0
def test_sortHouseholdsAscendingandAndDescending():
    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,95,5]    
    house2Ages  = [94,6]    
    
    house1Lst = list(map(Person, house1Ages))
    house2Lst = list(map(Person, house2Ages))
    
    #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
 
    houses = []
    houses.append(house1)
    houses.append(house2)
    
    houses = sorted(houses,key = cmp_to_key(Household.house_comperator_ASCENDING))
    assert 5 in [p.get_age() for p in houses[0].get_people()]

    houses = sorted(houses,key = cmp_to_key(Household.house_comperator_DESCENDING))
    assert 98 in [p.get_age() for p in houses[0].get_people()]
예제 #27
0
def test_CreateDeltaFileAtlit(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)
        citiesDataPath = ConfigData['CitiesFilePath']
        paramsDataPath = ConfigData['ParamsFilePath']
    Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src",
                                  paramsDataPath),
                     override=True)
    Params.loader()["person"]["state_macine_type"] = "SIR"

    DiseaseState.init_infectiousness_list()
    pop = population_loader.PopulationLoader(citiesDataPath)
    my_world = pop.get_world(city_name='Atlit', scale=1, is_smart=False)

    sim = Simulation(world=my_world, initial_date=INITIAL_DATE)
    sim.infect_random_set(num_infected=500, infection_doc="")
    sim.run_simulation(num_days=180, name="test")
    #assert events dictionary is not empty
    txt = sim.stats.get_state_stratified_summary_table(
        table_format=TableFormat.CSV)
    test_data = StringIO(txt)

    tbl = pd.read_csv(test_data)
    cnt_start = tbl.iloc[0, DiseaseState.SUSCEPTIBLE.value] + tbl.iloc[
        0, DiseaseState.LATENT.value]
    cnt_end = 0
    for i in range(len(tbl)):
        cnt_end = cnt_end + tbl.iloc[i, DiseaseState.IMMUNE.value] + tbl.iloc[
            i, DiseaseState.DECEASED.value]
    plug_number = len([
        p for p in sim._world.all_people()
        if p.get_disease_state() == DiseaseState.SUSCEPTIBLE
    ])
    assert cnt_start >= cnt_end + plug_number
def test_single_person_infected_contact1(params_path):
    """
    Tests that if we have only one person that is sick but he is in confinement,
    he won't infect a single person with contact_prob = 1
    """
    Params.load_from(params_path)
    DiseaseState.init_infectiousness_list()
    contact_prob = 1
    num_of_people = 400
    weight_list = [
        max(0.3,
            random.random() - 0.1) for _ in range(num_of_people)
    ]
    env = HomogeneousEnvironment(contact_prob, "test")
    infections = []

    env._person_dict = {
        Person(random.randint(20, 60)): weight_list[i]
        for i in range(num_of_people)
    }
    last_person = None
    for p, w in env._person_dict.items():
        p._disease_state = DiseaseState.SUSCEPTIBLE
        p._change()
        env.sign_up_for_today(p, w)
        last_person = p
    last_person._disease_state = DiseaseState.ASYMPTOMATICINFECTIOUS
    last_person._infectiousness_prob = 0
    last_person._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)

    assert num_of_infections == 0
예제 #29
0
def main():
    """
    This is the main function that runs the simulation.
    here we are able to add different intervention, params, and more configurations to the run.
    This is an example for using the code in the project, and running different simulations of the disease.
    """
    # sets the logging output to be at debug level, meaning more output than a regular run
    logging.basicConfig(format='%(levelname)s:%(message)s',
                        level=logging.DEBUG)

    scenarios = {
        # "scenario_1": scenario_1_interventions,
        # "scenario_21": scenario_21_interventions,
        # "scenario_22": scenario_22_interventions,
        # "scenario_23": scenario_23_interventions,
        # "scenario_24": scenario_24_interventions,
        # "scenario_25": scenario_25_interventions,
        # "scenario_26": scenario_26_interventions,
        # "scenario_232": scenario_232_interventions,
        # "scenario_262": scenario_262_interventions,
        # "scenario_272": scenario_272_interventions,
        # "scenario_282": scenario_282_interventions,
        # "scenario_36": scenario_36_interventions,
        # "scenario_39": scenario_39_interventions,
        # "scenario_365": scenario_365_interventions,
        # "scenario_395": scenario_395_interventions
        #"reality1" : scenario_reality1
        #"check" : scenario_check
        #"reality2" : scenario_reality2
        #"reality3": scenario_reality3
        #"reality4": scenario_reality4
        #"no_interventions": no_interventions
        #"not_relaxing_interventions": not_relaxing_interventions
        #"grant_time1" : grant_time1,
        #"grant_time2" : grant_time2
        "paper_1": paper_1
        #"paper_2" : paper_2
        #"paper_3" : paper_3
        #"paper_4" : paper_4
        #"paper_5": paper_5
        #"paper_6": paper_6
        #"paper_7": paper_7
        #"paper_8": paper_8
        #"paper_2_comp_9": paper_2_comp_9
    }

    datas_to_plot = get_datas_to_plot()

    # choosing the city and the scale of the run:
    # the city name and scale determine the city and the size proportion to take (use 'all' for entire country)
    # city_name, scale = 'holon', 1
    # city_name, scale = 'all', 0.01 # This means loading 1% of the entire country
    # city_name, scale = 'all', 0.1 # This means loading the entire country
    print("Running all simulations...")
    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)
        paramsDataPath = ConfigData['ParamsFilePath']

    Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath),
                     override=True)

    # we build a list of the jobs to run:
    # each job can be run as a different process, and the population generation will be done once
    # if caching option is on

    jobs = []
    for initial_percentage_immune in [0.0, 0.5]:
        for initial_num_infected in [25, 100, 250, 500]:
            for city_name, scale in [("Holon", 1), ("Bene Beraq", 1)]:
                for compliance in [0.8]:
                    for ci_delay in [4]:
                        for hi_delay in [4]:
                            for symptomatic_probs_scale in [1]:
                                for scenario_name, intervention_scheme in scenarios.items(
                                ):
                                    params_to_change = {
                                        ('disease_parameters', 'symptomatic_given_infected_per_age'):
                                        get_rescaled_symptomatic_probs(
                                            symptomatic_probs_scale)
                                    }
                                    full_scenario_name = generate_scenario_name(
                                        city_name, scenario_name,
                                        initial_num_infected,
                                        initial_percentage_immune, compliance,
                                        ci_delay, hi_delay,
                                        symptomatic_probs_scale)
                                    #                                    full_scenario_name = "res"
                                    jobs.append(
                                        RepeatJob(
                                            SimpleJob(
                                                full_scenario_name,
                                                days=180,
                                                city_name=city_name,
                                                scale=scale,
                                                infection_params=
                                                NaiveInitialInfectionParams(
                                                    initial_num_infected,
                                                    per_to_Immune=
                                                    initial_percentage_immune),
                                                #infection_params=SmartInitialInfectionParams(initial_num_infected, round(initial_num_infected/10)),
                                                params_to_change=
                                                params_to_change,
                                                interventions=
                                                intervention_scheme(
                                                    compliance, ci_delay,
                                                    hi_delay),
                                                datas_to_plot=datas_to_plot),
                                            num_repetitions=50))

    # add job to make r to base infectiousness graph:
    # jobs += [make_base_infectiousness_to_r_job('r_graph_default', city_name, scale,
    #                                            [0.03, 0.06, 0.1, 0.13, 0.16, 0.2],
    #                                            interventions=ci_sde,num_repetitions=3)]

    # this start the run of the jobs
    run(jobs,
        multi_processed=True,
        with_population_caching=False,
        verbosity=False)
예제 #30
0
def test_ImmuneByHouseholdIntervention():
    #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 = ImmuneByHouseholdIntervention(compliance=1,
                                                    start_date=INITIAL_DATE,
                                                    duration=daysdelta(40),
                                                    houses_per_day=1,
                                                    min_age=18)
    assert my_intervention is not None

    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,
                               interventions=[my_intervention])

    #test
    lst = my_intervention.generate_events(my_world)
    #Assert results
    assert lst is not None
    assert len(lst) == 5
    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 <= 3
    my_simulation.simulate_day()
    cnt_immune = sum([
        1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE
    ])
    assert cnt_immune == 5
    my_simulation.simulate_day()