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
def test_createInfectedPersonsBestEffort2(): """ Test that when the population size is less then the amount of people that had been chosen to be infected, the simulation doesn't crash """ config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) ageList = [random.randint(19,40) for i in range(10)] PersonList = list(map(Person, ageList)) env_arr = [] my_world = World( all_people = PersonList, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.infect_random_set(num_infected = 0, infection_doc = "", per_to_immune = 2,city_name = None,min_age=18,people_per_day =0) my_simulation.simulate_day() cnt_immune = 0 cnt_sick = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune += 1 else: cnt_sick += 1 assert cnt_immune == 10 assert cnt_sick == 0
def test_createInfectedPersons(helpers): """ #create population with 5 people ages [9,19,29,39,49] #test that each day one of them is getting immuned """ helpers.clean_outputs() #Editig confige file saving is nessery config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") ConfigData = None #reading the confige file with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) persons_arr = list(map(Person, [9,19,29,39,49,59])) assert len(persons_arr) == 6 env_arr = [] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.run_simulation(7,"test_simulation",datas_to_plot = None,extensionsList = ["ImmuneByAgeExtension","EmptyExtension"] ) cnt = sum([1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE]) assert cnt == 4
def test_createInfectedPersons3(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) kids = [random.randint(0,17) for i in range(5)] adults = [random.randint(19,40) for i in range(5)] ageList = kids + adults PersonList = list(map(Person, ageList)) env_arr = [] my_world = World( all_people = PersonList, all_environments=env_arr, generating_city_name = "test", generating_scale = 1) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.infect_random_set(num_infected = 0, infection_doc = "", per_to_immune = 0.5,Immune_compliance = 0,city_name = None,min_age=18,people_per_day =5) my_simulation.simulate_day() #assert events dictionary is not empty cnt_immune = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune = cnt_immune + 1 assert cnt_immune == 0
def test_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_immune_and_get_events2(): config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) p = Person(30) ok,events = p.immune_and_get_events(INITIAL_DATE , timedelta(days = 20), \ ((DiseaseState.SUSCEPTIBLE,timedelta(10)),(DiseaseState.LATENT,timedelta(5)), \ (DiseaseState.SUSCEPTIBLE,None))) assert len(events) == 3 assert ok persons_arr = [p] env_arr = [] small_world = world.World(all_people=persons_arr, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=small_world, initial_date=INITIAL_DATE, interventions=[]) for i in range(10): my_simulation.simulate_day() events[0].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.LATENT for i in range(5): my_simulation.simulate_day() events[1].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.IMMUNE
def create_and_run_simulation(self, outdir, stop_early, with_population_caching=True, verbosity=False): """ The main function that handles the run of the simulation by the task. It updated the params changes, loads or creates the population, initializes the simulation and runs it. :param outdir: the output directory for the task :param stop_early: only relevant to R computation, see Simulation doc :param with_population_caching: bool, if False generates the population, else - tries to use the cache and save time. :param verbosity: bool, if it's True then additional output logs will be printed to the screen """ seed.set_random_seed() config_path = os.path.join(os.path.dirname(__file__), "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) citiesDataPath = ConfigData['CitiesFilePath'] paramsDataPath = ConfigData['ParamsFilePath'] Extensionslst = ConfigData['ExtensionsNamelst'] Params.load_from(os.path.join(os.path.dirname(__file__), paramsDataPath), override=True) for param, val in self.params_to_change.items(): Params.loader()[param] = val DiseaseState.init_infectiousness_list() citiesDataPath = citiesDataPath population_loader = PopulationLoader( citiesDataPath, added_description=Params.loader().description(), with_caching=with_population_caching, verbosity=verbosity) world = population_loader.get_world(city_name=self.city_name, scale=self.scale, is_smart=True) ExtensionType = None sim = Simulation(world, self.initial_date, self.interventions, verbosity=verbosity, outdir=outdir, stop_early=stop_early) self.infection_params.infect_simulation(sim, outdir) if len(Extensionslst) > 0: sim.run_simulation(self.days, self.scenario_name, datas_to_plot=self.datas_to_plot, extensionsList=Extensionslst) else: sim.run_simulation(self.days, self.scenario_name, datas_to_plot=self.datas_to_plot, extensionsList=None)
def 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]
def test_createInfectedPersonsByHouseHoldBestEffort2(): """ Test that when the population size is less then the amount of people that had been chosen to be infected by households, the simulation doesn't crash """ config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) #create diff enviroments KidsHouse = Household(city = None,contact_prob_between_each_two_people=1) AdultsHouse = Household(city = None,contact_prob_between_each_two_people=1) MixedHouse = Household(city = None,contact_prob_between_each_two_people=1) kidsAges = [random.randint(0,17) for i in range(4)] adultsAges = [random.randint(19,40) for i in range(3)] KidsLst = list(map(Person, kidsAges)) adultsLst = list(map(Person, adultsAges)) persons_arr = KidsLst + adultsLst #register people to diff env KidsHouse.sign_up_for_today(KidsLst[0],1) KidsHouse.sign_up_for_today(KidsLst[1],1) AdultsHouse.sign_up_for_today(adultsLst[0],1) AdultsHouse.sign_up_for_today(adultsLst[1],1) MixedHouse.sign_up_for_today(adultsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[3],1) assert len(KidsHouse.get_people()) == 2 assert len(AdultsHouse.get_people()) == 2 assert len(MixedHouse.get_people()) == 3 env_arr = [KidsHouse,AdultsHouse,MixedHouse] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1,) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.immune_households_infect_others(num_infected = 0, infection_doc = "", per_to_immune = 2 ,city_name = None,min_age=18,people_per_day =5) my_simulation.simulate_day() cnt_immune = 0 cnt_sick = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune += 1 elif person.get_disease_state() != DiseaseState.SUSCEPTIBLE: cnt_sick += 1 assert cnt_immune == 3 assert cnt_sick == 0
def test_ImmuneGeneralPopulationIntervention(): #pretesting config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) my_intervention = ImmuneGeneralPopulationIntervention( compliance=1, start_date=INITIAL_DATE, duration=daysdelta(40), people_per_day=1, min_age=15) assert my_intervention is not None persons_arr = list(map(Person, [10, 20, 30])) assert len(persons_arr) == 3 env_arr = [] small_world = World(all_people=persons_arr, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=small_world, initial_date=INITIAL_DATE, interventions=[my_intervention]) #test lst = my_intervention.generate_events(small_world) #Assert results assert lst is not None assert len(lst) == 2 for i in range(1): assert isinstance(lst[i], DayEvent) my_simulation.simulate_day() cnt_immune = sum([ 1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE ]) assert cnt_immune == 1 my_simulation.simulate_day() cnt_immune = sum([ 1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE ]) assert cnt_immune == 2 my_simulation.simulate_day() cnt_immune = sum([ 1 for p in persons_arr if p.get_disease_state() == DiseaseState.IMMUNE ]) assert cnt_immune == 2
def 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")
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()
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.]))
def test_createImmunehouseholds4(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) #create diff enviroments KidsHouse = Household(city = None,contact_prob_between_each_two_people=1) AdultsHouse = Household(city = None,contact_prob_between_each_two_people=1) MixedHouse = Household(city = None,contact_prob_between_each_two_people=1) kidsAges = [random.randint(0,17) for i in range(4)] adultsAges = [random.randint(19,40) for i in range(3)] KidsLst = list(map(Person, kidsAges)) adultsLst = list(map(Person, adultsAges)) persons_arr = KidsLst + adultsLst #register people to diff env KidsHouse.sign_up_for_today(KidsLst[0],1) KidsHouse.sign_up_for_today(KidsLst[1],1) AdultsHouse.sign_up_for_today(adultsLst[0],1) AdultsHouse.sign_up_for_today(adultsLst[1],1) MixedHouse.sign_up_for_today(adultsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[2],1) MixedHouse.sign_up_for_today(KidsLst[3],1) assert len(KidsHouse.get_people()) == 2 assert len(AdultsHouse.get_people()) == 2 assert len(MixedHouse.get_people()) == 3 env_arr = [KidsHouse,AdultsHouse,MixedHouse] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1,) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.immune_households_infect_others(num_infected = 0, infection_doc = "", per_to_immune = 1,Immune_compliance= 0 ,city_name = None,min_age=18,people_per_day= 3 ) my_simulation.simulate_day() #assert events dictionary is not empty cnt_immune = 0 for person in my_world.all_people(): if person.get_disease_state() == DiseaseState.IMMUNE: cnt_immune = cnt_immune + 1 assert cnt_immune == 0
def test_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
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
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()
def test_immune_and_get_events5(): """ Test that a person that is not Susptible nor latent when he should get immuned continues his usual path to his death """ config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") Expected = -1 with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) p = Person(30) ok, events = p.immune_and_get_events(INITIAL_DATE , timedelta(days = 20), \ ((DiseaseState.SUSCEPTIBLE,timedelta(10)),(DiseaseState.LATENT,timedelta(5)),\ (DiseaseState.ASYMPTOMATICINFECTIOUS,timedelta(5)),(DiseaseState.DECEASED,timedelta(5)),(DiseaseState.DECEASED,None))) assert len(events) == 4 assert ok == False persons_arr = [p] env_arr = [] small_world = world.World(all_people=persons_arr, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=small_world, initial_date=INITIAL_DATE, interventions=[]) for i in range(10): my_simulation.simulate_day() events[0].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.LATENT for i in range(5): my_simulation.simulate_day() events[1].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.ASYMPTOMATICINFECTIOUS #Because this person was not susptible nor latent he cannot be immuned for i in range(5): my_simulation.simulate_day() events[2].apply(simulation=my_simulation) assert p.get_disease_state() == DiseaseState.DECEASED
def test_CreateDeltaFile(helpers): helpers.clean_outputs() config_path = os.path.join(os.path.dirname(__file__), "..", "src", "config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__), "..", "src", paramsDataPath), override=True) ageList = [random.randint(0, 40) for i in range(10)] PersonList = list(map(Person, ageList)) events_acc = [] for person in PersonList: states_table = ((DiseaseState.LATENT, daysdelta(3)), (DiseaseState.ASYMPTOMATICINFECTIOUS, daysdelta(3)), (DiseaseState.IMMUNE, daysdelta(3)), (DiseaseState.IMMUNE, None)) events = person.gen_and_register_events_from_seir_times( date=INITIAL_DATE, states_and_times=states_table) events_acc += events # person.set_disease_state(DiseaseState.LATENT) env_arr = [] my_world = World(all_people=PersonList, all_environments=env_arr, generating_city_name="test", generating_scale=1) my_simulation = Simulation(world=my_world, initial_date=INITIAL_DATE) my_simulation.register_events(events_acc) my_simulation.run_simulation(num_days=10, name="test") #assert events dictionary is not empty txt = my_simulation.stats.get_state_stratified_summary_table( table_format=TableFormat.CSV) test_data = StringIO(txt) tbl = pd.read_csv(test_data) assert len(tbl) == 7 print(tbl) assert tbl.iloc[0, DiseaseState.SUSCEPTIBLE.value] == 10 assert tbl.iloc[3, DiseaseState.ASYMPTOMATICINFECTIOUS.value] == 10 assert tbl.iloc[6, DiseaseState.IMMUNE.value] == 10
def test_createImmunehouseholds2(): config_path = os.path.join(os.path.dirname(__file__),"..","src","config.json") with open(config_path) as json_data_file: ConfigData = json.load(json_data_file) paramsDataPath = ConfigData['ParamsFilePath'] Params.load_from(os.path.join(os.path.dirname(__file__),"..","src", paramsDataPath), override=True) #create diff enviroments house1 = Household(city = None,contact_prob_between_each_two_people=1) house2 = Household(city = None,contact_prob_between_each_two_people=1) house1Ages = [98,93,5] house2Ages = [94,6] house1Lst = list(map(Person, house1Ages)) house2Lst = list(map(Person, house2Ages)) persons_arr = house1Lst + house2Lst #register people to diff env house1.sign_up_for_today(house1Lst[0],1) house1.sign_up_for_today(house1Lst[1],1) house1.sign_up_for_today(house1Lst[2],1) house2.sign_up_for_today(house2Lst[0],1) house2.sign_up_for_today(house2Lst[1],1) assert len(house1.get_people()) == 3 assert len(house2.get_people()) == 2 env_arr = [house1,house2] my_world = World( all_people = persons_arr, all_environments=env_arr, generating_city_name = "test", generating_scale = 1,) my_simulation = Simulation(world = my_world, initial_date= INITIAL_DATE) my_simulation.immune_households_infect_others(num_infected = 0, infection_doc = "", per_to_immune = 0.6,Sort_order=ORDER.DESCENDING ,city_name = None,min_age=18,people_per_day= 3 ) my_simulation.simulate_day() #assert events dictionary is not empty cnt_immune = 0 for person in my_world.all_people(): if (person.get_age() in [94,93,98]) and (person.get_disease_state() == DiseaseState.IMMUNE): cnt_immune = cnt_immune + 1 assert cnt_immune == 3
def 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)
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)
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_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()
config = Config.load() evolution = Evolution(config) if chromosome: state_machine = AntStateMachine.from_chromosome_string( chromosome, evolution.genotype) score = evolution.evaluate(state_machine.to_chromosome()) else: evolution = Evolution(config) best_individual = evolution.start() state_machine = AntStateMachine.from_chromosome( best_individual.chromosome) score = best_individual.fitness print('Best found state machine:') print(state_machine.to_chromosome()) simulation = Simulation(state_machine, grid=config.grid()) if gui: gui_application = ArtificialAntApplication(simulation) gui_application.run(sys.argv) else: # Run in command line print(str(score)) # 000101101000000110001100111001010011010101011010000101011100111011000011100101111100001111 # 41 out of 88 baits eaten 46% in 500 steps # 000110011000000110001101100001001010010100000010010010011101001011000010100101111100001111 # 87 out of 88 baits eaten 98% in 500 steps
def ablation_simulation(): # the main function for ablation 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 # 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 = 0 # 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 # the simulation objects simulation_constC_constR = Simulation(total_balance, block_reward, mining_expense, bid_winner, transaction_fees, trace_tag, update_mining_cost_tag, update_block_reward_tag, perturbation_type) update_mining_cost_tag = True update_block_reward_tag = False simulation_propC_constR = Simulation(total_balance, block_reward, mining_expense, bid_winner, transaction_fees, trace_tag, update_mining_cost_tag, update_block_reward_tag, perturbation_type) update_mining_cost_tag = False update_block_reward_tag = True simulation_constC_propR = Simulation(total_balance, block_reward, mining_expense, bid_winner, transaction_fees, trace_tag, update_mining_cost_tag, update_block_reward_tag, perturbation_type) update_mining_cost_tag = True update_block_reward_tag = True simulation_propC_propR = 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 = 100000 for i in range(total_round): simulation_constC_constR.single_round() simulation_constC_propR.single_round() simulation_propC_constR.single_round() simulation_propC_propR.single_round() # legend labels labels = [ "R-const, C-const", "R-const, C-prop", "R-prop, C-const", "R-prop, C-prop" ] # colors and line styles for drawing colors = ["firebrick", "goldenrod", "dodgerblue", "forestgreen"] line_styles = ["-", "-", "-", "-"] draw_multiple(simulation_propC_propR.result[:, 0], [ simulation_constC_constR.result[:, 1], simulation_propC_constR.result[:, 1], simulation_constC_propR.result[:, 1], simulation_propC_propR.result[:, 1] ], labels, colors, line_styles, "Round Number", "Total Supply")
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()
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)
def sensitivity_simulation_for_update_rate(): # the main function for sensitivity simulation for gamma # 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 # 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 = 0 # 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 # the gamma gamma = 0.5 # the update rates for exchange coefficient update_rates = [1 / 100, 1 / 1000, 1 / 5000, 1 / 15000, 1 / 50000] # construct simulation objects with different transaction fees simulations = [] for i in range(len(update_rates)): simulations.append( Simulation(total_balance, block_reward, mining_expense, bid_winner, transaction_fees, trace_tag, update_mining_cost_tag, update_block_reward_tag, perturbation_type, gamma, update_rates[i])) # total round number round_number = 150000 # simulation process for j in range(round_number): for i in range(len(update_rates)): simulations[i].single_round() # legend labels labels = [ r"$ur = 1/100$", r"$ur = 1/1000$", r"$ur = 1/5000$", r"$ur = 1/15000$", r"$ur = 1/50000$" ] # colors and line styles for drawing colors = ['#FFB5C5', "#FF3030", "#EE2C2C", "#CD2626", "#8B1A1A"] line_styles = ["-", "-", "-", "-", "-"] simulation_results = [ simulations[i].result[:, 1] for i in range(len(update_rates)) ] draw_multiple(simulations[0].result[:, 0], simulation_results, labels, colors, line_styles, "Round Number", "Total Supply")