Ejemplo n.º 1
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
    
Ejemplo n.º 2
0
    def __init__(self, network, T=5, dt=.001, **kwargs):
        """
        Pass in a wc unit, set up recordings, get ready to run.
        Args:
            sensory_units (SensoryWCUnit): it should already have everything you want connected to it
            T (float): T in seconds
            dt (float): integration timestep (seconds)
            **kwargs:
        Derived attributes:
            self.tax (numpy.array): time axis
            self.ttot (int): total number of time steps
            self.t_i (int): the current time step
            self.traces (dict): traces
        """
        Simulation.__init__(self, T=T, dt=dt, **kwargs)
        self.network = network
        self.traces = OrderedDict()

        # just slap a trace on there?
        for unit in self.network.units:
            # we'll just staple the traces to the unit, maybe this is wrong but it should make things easier
            unit.trace_dict = OrderedDict()

            trace_sources = OrderedDict(
                FR=unit.r)  # , stim=unit.stim, SFA=unit.a
            # )
            for k, v in trace_sources.items():
                self.add_new_trace(unit, source=v, trace_name=k)

            current_trace_sources = unit.currents
            for k, v in current_trace_sources.items():
                self.add_new_current_trace(unit, source=v, trace_name=k)
Ejemplo n.º 3
0
    def __init__(self, sensory_unit=None, T=5, dt=.001, **kwargs):
        """
        Pass in a wc unit, set up recordings, get ready to run.
        Args:
            sensory_unit (SensoryWCUnit): it should already have everything you want connected to it
            T (float): T in seconds
            dt (float): integration timestep (seconds)
            **kwargs:
        Derived attributes:
            self.tax (numpy.array): time axis
            self.ttot (int): total number of time steps
            self.t_i (int): the current time step
            self.traces (dict): traces
        """
        Simulation.__init__(self, T=T, dt=dt, **kwargs)
        self.unit = sensory_unit

        trace_sources = {
            "FR": sensory_unit.r,
            "stim": sensory_unit.stim,
            "SFA": sensory_unit.a,
            # "u1_S": wc_unit.S
        }
        for k, v in trace_sources.items():
            self.add_new_trace(source=v, trace_name=k)
Ejemplo n.º 4
0
def test_immune_and_get_events1():
    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 =  15), \
        ((DiseaseState.SUSCEPTIBLE,timedelta(10)),(DiseaseState.IMMUNE,timedelta(21))))

    assert len(events) == 2
    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.IMMUNE
    assert len(p._seir_times) == 3
Ejemplo n.º 5
0
    def __init__(self, network, T=5, dt=.001, **kwargs):
        """
        Pass in a wc unit, set up recordings, get ready to run.
        Args:
            sensory_units (SensoryWCUnit): it should already have everything you want connected to it
            T (float): T in seconds
            dt (float): integration timestep (seconds)
            **kwargs:
        Derived attributes:
            self.tax (numpy.array): time axis
            self.ttot (int): total number of time steps
            self.t_i (int): the current time step
            self.traces (dict): traces
        """
        Simulation.__init__(self, T=T, dt=dt, **kwargs)
        self.network = network
        self.traces = OrderedDict()

        for name, unit in self.network.units.items():
            trace_sources = OrderedDict(
                FR=unit.r, stim=unit.stim, SFA=unit.a
            )
            self.traces[unit.name] = OrderedDict()

            for k, v in trace_sources.items():
                self.add_new_trace(unit, source=v, trace_name=k)
Ejemplo n.º 6
0
def test_simulation_init():
    eps = .000001
    sim = Simulation()
    assert sim.ttot == 5 / .001
    sim2 = Simulation(dt=.05, T=5000)
    tax = sim2.tax
    assert tax[-1] - tax[-2] - .05 < eps
Ejemplo n.º 7
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
Ejemplo n.º 8
0
def test_nested_trace():
    # this seems very annoying... TODO: I HATE THIS
    sim = Simulation()
    sim.traces["foo"] = dict()
    src = [0]
    trc = Trace(sim, source=src, target=sim.traces["foo"], trace_name="bar")
    # print(trc.__dict__.get("source"))
    for ind in xrange(5):
        src[0] = ind
        trc.update_trace()
        trc.sim.step()
    print(sim.traces["foo"]["bar"].source)
    print(sim.traces["foo"]["bar"].trace)

    assert len(sim.traces["foo"]["bar"].trace) == sim.ttot
    assert sim.traces["foo"]["bar"].source[0] == 4
    assert sim.traces["foo"]["bar"].trace[4] == 4
Ejemplo n.º 9
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']

        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)
        sim = Simulation(world,
                         self.initial_date,
                         self.interventions,
                         verbosity=verbosity,
                         outdir=outdir,
                         stop_early=stop_early)
        self.infection_params.infect_simulation(sim, outdir)
        sim.run_simulation(self.days,
                           self.scenario_name,
                           datas_to_plot=self.datas_to_plot)
Ejemplo n.º 10
0
    def evaluate(self, individual: Individual) -> Fitness:
        """Evaluate an individual on the proving grounds. Return a fitness of this individual."""

        if individual not in self.__score_board:
            baits_eaten, steps_used = Simulation(AntStateMachine.from_chromosome(individual.chromosome), self.__grid).run()
            fitness = Fitness.from_result(self.__total_baits, baits_eaten, steps_used)
            self.__score_board[individual] = fitness

        return self.__score_board[individual]
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    def __init__(self,
                 syn_weights=weights,
                 selectivities=s_units,
                 stimulus=stim,
                 **kwargs):
        TonotopicNetwork.__init__(self, selectivities, stimulus, **kwargs)
        Simulation.__init__(self, **kwargs)  # is this black magic?
        """ this guy would take a bunch of selectivities and make some units """
        self.syn_weights = syn_weights

        # now we build us some arrays - we're going to vectorize
        self.R_var_array = np.zeros([len(self.units), self.ttot])
        self.A_var_array = np.zeros([len(self.units), self.ttot])
        self.S_var_array = np.zeros([len(self.units), self.ttot])

        # pull out the vars from the vars arrays
        self.vars = [
            x.split("_")[0] for x in self.__dict__ if x.endswith("_var_array")
        ]

        self.stim_currents = self.build_stimulus_currents()
        # list of units
        units_array = self.units
        self.gstims = np.array(
            [x.currents["stim"].weight for x in units_array])
        self.i_0s = np.array([x.i_0 for x in units_array])
        self.gees = np.array([x.gee for x in units_array])
        self.gSFAs = np.array([x.gSFA for x in units_array])
        self.Gs = np.array([x.G for x in units_array])
        self.taus = np.array([x.tau for x in units_array])
        self.tauAs = np.array([x.tauA for x in units_array])
        self.tauNMDAs = np.array([x.tauNMDA for x in units_array])

        # activation function parameters
        self.kes = np.array([x.ke for x in units_array])
        self.thes = np.array([x.the for x in units_array])
        self.f_e = self.f_activation_builder(self.kes, self.thes)
        self.kSs = np.array([x.kS for x in units_array])
        self.thSs = np.array([x.thS for x in units_array])
        self.f_S = self.f_activation_builder(self.kSs, self.thSs, self.b_00)
        # initialize
        self.point_wise_Isyn = np.outer(self.syn_weights, self.R_var_array)
Ejemplo n.º 13
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)
Ejemplo n.º 14
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
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def test_trace():
    sim = Simulation()
    src = [0]
    trc = Trace(sim, source=src, target=sim.traces, trace_name="foo")
    # print(trc.__dict__.get("source"))
    for ind in xrange(5):
        src[0] = ind
        trc.update_trace()
        trc.sim.step()
    #print(trc.__dict__)
    assert len(trc.trace) == trc.sim.ttot
    trc.trace[:5]
    assert all(trc.trace[:5] == np.array([0., 1., 2., 3., 4.]))
Ejemplo n.º 17
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
Ejemplo n.º 18
0
def test_current_trace():
    src = [0]
    curr = dCurrent(source=src, weight=0.5, target={}, name="foo")
    sim = Simulation()
    tar = {}
    trc = CurrentTrace(sim=sim, source=curr, target=tar, trace_name="foo")
    print(tar)
    assert isinstance(tar["foo"], CurrentTrace)
    for ind in xrange(5):
        src[0] = ind
        curr.update()
        trc.update_trace()
        trc.sim.step()
    trc.update_trace()
    # print trc.trace[:10]
    assert trc.trace[4] == src[0] * curr.weight
Ejemplo n.º 19
0
def main():
    simulation = Simulation()
    city = City.from_numbers(600, 100).assign_bikes_randomly()

    time = time_of_number_of_days(7)
    simulation.simulate(city, time)

    ResultWriter.write_to_excel(simulation.get_stations_data(),
                                "stations_states.xlsx")
    ResultWriter.write_to_excel(simulation.get_breaking_bikes_data(),
                                "bikes_breaking.xlsx")
Ejemplo n.º 20
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
Ejemplo n.º 21
0
    def test_working(self):
        city = City.from_numbers(100, 10).assign_bikes_randomly()
        time = time_of_number_of_days(3)
        simulaiton = Simulation()

        simulaiton.simulate(city, time)

        broken_bikes = simulaiton.get_breaking_bikes_data()
        trips_history = simulaiton.get_stations_data()

        res_stations_changes = station_changes.StationChanges(
            trips_history).find_stations_changes()
        scores = bikes_scoring.BikesScoring(res_stations_changes).score_bikes()
Ejemplo n.º 22
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
Ejemplo n.º 23
0
def perturbation_simulation():

    # the main function for perturbation simulation

    # initial parameters
    # initial total balance of the system
    total_balance = 1000000000000

    # the block reward for a single round
    block_reward = 0.000035 * total_balance

    # the expected mining expense for a single bidder
    mining_expense = 0.000006 * total_balance

    # the transaction fees of the first round
    transaction_fees = 0.00006 * total_balance

    # the number of bid winners
    bid_winner = 10

    # if simulation needs to be traced in console
    trace_tag = True
    # True if use C-prop, False to use C-const
    update_mining_cost_tag = False
    # True if use R-prop, False to use R-const
    update_block_reward_tag = False

    # perturbation type decides which kind of perturbation will be deployed
    # 1 indicates instant increase/decrease in total supply
    # 2 indicates instant increase/decrease in fisher coefficient
    # else for doing nothing
    perturbation_type = 1

    # the simulation object
    simulation = Simulation(total_balance, block_reward, mining_expense,
                            bid_winner, transaction_fees, trace_tag,
                            update_mining_cost_tag, update_block_reward_tag,
                            perturbation_type)

    # simulate round by round
    total_round = 500000
    for i in range(total_round):
        simulation.single_round()

    simulation.draw_time_series()
Ejemplo n.º 24
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
Ejemplo n.º 25
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
Ejemplo n.º 26
0
    def simulate(self, individual):
        self.robot.client.display_activation(False)
        simulation = Simulation(self.robot.client)
        simulation.start()
        self.robot.init_stream()
        time.sleep(0.1)
        start = self.robot.position

        for move in individual.moves:
            self.robot.pause(True)
            self.robot.wrist = math.radians(move.x())
            self.robot.elbow = math.radians(move.y())
            self.robot.shoulder = math.radians(move.z())
            self.robot.pause(False)
            self.robot.wait()

        end = self.robot.position
        simulation.stop()
        time.sleep(0.1)
        return euclidean_distance(start, end)
Ejemplo n.º 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
Ejemplo n.º 28
0
    print "Connection failed!"
    exit(1)

print client.id
robot = Robot(client)
if not robot.load():
    print "Robot initialization failed!"
    exit(1)

client.synchronous_mode()

random.seed()
for i in range(0, 3):
    # Wait until the robot is settled to the default position
    print "----- Simulation started -----"
    simulation = Simulation(client)
    simulation.start()
    # client.display_activation(False)
    robot.init_stream()
    start = robot.position
    # client.display_activation(False)

    # Make the robot move randomly five times
    for j in range(0, 20):
        # Generating random positions for the motors
        awrist = random.randint(0, 300)
        aelbow = random.randint(0, 300)
        ashoulder = random.randint(0, 300)

        robot.pause(True)
        robot.wrist = math.radians(awrist)
Ejemplo n.º 29
0
def test_count_infected_in_hood():
    '''
    Test that we gather the right data about the infected persons 
    in each neighborhood.
    '''
    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)
    Params.loader()["person"]["state_macine_type"] = "SIR"
    DiseaseState.init_infectiousness_list()

    #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
    
    n1 = NeighborhoodCommunity(city= None,contact_prob_between_each_two_people= 1)
    n2 = NeighborhoodCommunity(city= None,contact_prob_between_each_two_people= 1)

    states_table1 = ((DiseaseState.LATENT,daysdelta(3)),
                        (DiseaseState.ASYMPTOMATICINFECTIOUS,daysdelta(3)),
                        (DiseaseState.IMMUNE, daysdelta(3)),
                        (DiseaseState.IMMUNE, None))
    states_table2 = ((DiseaseState.IMMUNE, daysdelta(3)),
                    (DiseaseState.IMMUNE, None))

    events_acc = []
    for person in house1.get_people():
        person.add_environment(n1)
        events = person.gen_and_register_events_from_seir_times(date = INITIAL_DATE,states_and_times= states_table1)
        events_acc += events
    
    for person in house2.get_people():
        person.add_environment(n2)
        events = person.gen_and_register_events_from_seir_times(date = INITIAL_DATE,states_and_times= states_table2)
        events_acc += events

    env_arr = [house1,house2,n1,n2]
    persons_arr = []
    persons_arr += house1Lst
    persons_arr += house2Lst

    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.register_events(events_acc)

    for i in range(4):
        d1 = my_simulation.stats.get_neiborhood_data(INITIAL_DATE + daysdelta(i),n1.get_neighborhood_id())
        d2 = my_simulation.stats.get_neiborhood_data(INITIAL_DATE + daysdelta(i),n2.get_neighborhood_id())
        assert d1 == 0 ,  "Day:" + str(i)
        assert d2 == 0 ,  "Day:" + str(i)
        my_simulation.simulate_day()
    
    for i in range(3):
        d1 = my_simulation.stats.get_neiborhood_data(INITIAL_DATE + daysdelta(i+3),n1.get_neighborhood_id())
        d2 = my_simulation.stats.get_neiborhood_data(INITIAL_DATE + daysdelta(i+3),n2.get_neighborhood_id())
        assert d1 == 3 , "Day:" + str(3 + i)
        assert d2 == 0 , "Day:" + str(3 + i)
        my_simulation.simulate_day()

    for i in range(3):
        d1 = my_simulation.stats.get_neiborhood_data(INITIAL_DATE,n1.get_neighborhood_id())
        d2 = my_simulation.stats.get_neiborhood_data(INITIAL_DATE,n2.get_neighborhood_id())
        assert d1 == 0 , "Day:" + str(6 + i)
        assert d2 == 0 , "Day:" + str(6 + i)
        my_simulation.simulate_day()
Ejemplo n.º 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()