def getNewWorldByInsert(self, newVehicle, newVehicleIndex, vehicle, vehicleIndex, travelToInsert, indexToInsert, travelToRemoveIndex): newVehicleCopy = deepcopy(newVehicle) vehicleCopy = deepcopy(vehicle) newVehicleCopy.tour.insert(indexToInsert, travelToInsert) del vehicleCopy.tour[travelToRemoveIndex] newWorld = World.fromWorld(self.world) newWorld.vehicles[vehicleIndex] = vehicleCopy newWorld.vehicles[newVehicleIndex] = newVehicleCopy return newWorld
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 __init__(self): self.screen_size = (500, 300) self.FPS = 60 self.fps_clock = pygame.time.Clock() self.world = World(self.screen_size) # generate the world self.world.generate() # populate the world self.collider = Collider(self.world.objects, self.world.walls, self.screen_size) # print(self.world.objects) self.win_surf = pygame.display.set_mode(self.screen_size, 0, 32) pygame.display.set_caption('Ant-1!') self.renderer = Renderer(self.win_surf, self.world, self.fps_clock) self.brain = Brain() self.reward_total = 0 self.reward_previous = 0
def run_simulation(socket: SocketIO): random.seed(time()) monsters = generate_world_elements( lambda position_energy: NormalMonster(*position_energy, 1, "SlowMonster"), randint(5, 15), ) fast_monsters = generate_world_elements( lambda position_energy: NormalMonster(*position_energy, 2, "FastMonster"), randint(5, 15), ) for monster in fast_monsters: monsters.add(monster) foods = generate_world_elements( lambda position_energy: Food(*position_energy), randint(90, 100)) world = World(monsters, foods, world_map_constructor(socket)) for turn in range(500): if turn % 50 == 0: foods = generate_world_elements( lambda position_energy: Food(*position_energy), randint(20, 30)) for food in foods: world.foods.add(food) world.play_one_day() world.display() sleep(0.5)
def solve(self, world: World, display=False) -> bool: """ Solve the world provided, using a Depth-First Search algorithm. From the initial configuration of the world, this methods search for a winning configuration by exploring all the configuration possibles. :param world: the world to solve. :param display: if set to True, the method will draw each step of its computation. Set it to False if you need to quickly compute the result. :return True if there is a solution for this world, False otherwise. """ res = self.__solve__(world, world.to_configuration(), display) self.solution = self.solution[::-1] return res
def process(self, world_object: World) -> None: """Worms receive a bonus for killed worms in the same cell as they are.""" for worm in world_object.worms: if not worm.dead: continue eaters = world_object.worms_at(worm.coordinates) for eater in eaters: if eater.dead: continue eater.health += worm.get_level() + worm.get_damage( ) + worm.get_initiative() eater.energy += (worm.get_level() + worm.get_damage() + worm.get_initiative()) * 10
def play_game(self, world: World) -> None: """ This method should be called after self.solve() has been called. Emulate the game by making Ariane play all the moves found in the self.solution list. :param world: the world in which the solver should play the game :return: None """ for direction in self.solution: input_dir = get_dir_from_string(direction) world.move_ariane(input_dir) world.move_thesee() view.display(world) if world.game_lost() or world.game_won(): return world.move_minos(view) time.sleep(0.3)
class Simulation: graphic: Graphic world: World statistic: Statistic def __init__(self): self.world = World(*SimulationConfig.word_size) self.graphic = Graphic(self.world, *SimulationConfig.pane_size) if SimulationConfig.fixed_sick_cases: for i in range(SimulationConfig.population_size): if i < SimulationConfig.fixed_cases_count: self.world.add_agent_on_free(Agent(self.world, True)) else: self.world.add_agent_on_free(Agent(self.world, False)) else: for i in range(SimulationConfig.population_size): self.world.add_agent_on_free( Agent( self.world, get_it_with_probability( SimulationConfig.create_sick_agent_probability, True, False))) self.statistic = Statistic(self.world) def run(self): while True: self.step() self.graphic.render() self.statistic.collect_statistics() def step(self): random.shuffle(self.world.agents) self.world.clear_death_agents() for agent in self.world.agents: agent.step() self.world.process_step_effects()
def distance_to_boundary_data_for(state, writer, k): probabilities = probabilities = linear_probabilities_for(k) random.setstate(state) region_provider = GreedyRegionProvider.privacy_enhanced_generator(None, probabilities, 0.5) world = World(None, region_provider) for _ in range(0, USER_COUNT): add_random_user(world) results = {"k-anon": 0, "dist_to_boundary": {}, "expected_distance_frequency":{}, "corners":0, "expected_corners":0} start = int(round(time.time() * 1000)) middler_users = [u for u in world.users if coords_in_bounds(u)] print(len(middler_users)) for user in middler_users: print(int(round(time.time() * 1000)) - start) start = int(round(time.time() * 1000)) user.update_region() region:EuclidRegion region = user.current_region() results["k-anon"] += region.privacy if region.user_dist_to_boundary in results["dist_to_boundary"]: results["dist_to_boundary"][region.user_dist_to_boundary] += 1 else: results["dist_to_boundary"][region.user_dist_to_boundary] = 1 for dist in region.user_location_likelihoods: if dist in results["expected_distance_frequency"]: results["expected_distance_frequency"][dist] += region.user_location_likelihoods[dist] else: results["expected_distance_frequency"][dist] = region.user_location_likelihoods[dist] results["corners"] += 1 if region.is_corner else 0 results["expected_corners"] += 4 / region.area() for dist in results["expected_distance_frequency"]: data = [ k, results["k-anon"] / len(middler_users), dist, 0 if dist not in results["dist_to_boundary"] else results["dist_to_boundary"][dist], results["expected_distance_frequency"][dist], results["corners"], results["expected_corners"], ] writer.writerow(data)
def process(self, world_object: World) -> None: """Creates a worm with a parental genotype or with a genotype mixed from the genotypes of non-relatives worms in the cell.""" for parent in world_object.worms: if parent.get_divisions_limit() == 0: continue child = Worm(parent.coordinates) child.genetics.genotype = world_object.genetic_variability( parent.coordinates) world_object.cells[parent.coordinates].worms.append(child) world_object.worms.append(child) child.genetics.family_affinity = parent.genetics.family_affinity + 0.00000000000001 child.newborn_genetics_boost(child.genetics.genotype) parent.divisions_limit -= 1 child.generation = parent.get_generation() + 1
def process(self, world_object: World) -> None: """Every worm strikes another not a relatives worm at the same cell.""" for worm in world_object.worms_by_initiative: targets = world_object.worms_at(worm.coordinates) if len(targets) == 0: continue target = random.choice(targets) if target is worm: continue if worm.is_relative_to(target): continue worm.strike(target) target.strike(worm)
def main(): earth = World() turn_number = 0 while True: turn_number += 1 simulate_turn( earth, Virus( 10, 50, 70, industry=INDUSTRIES.index('Chemical Manufacturing'), start_region=earth.regions['West Europe']) ) input(f'Earth population is now {earth.population}. Press any key + enter to continue') if earth.population == 0: print('Congrats! You killed off earth.') print(f'It took {turn_number} days to do it.') break
def create_world_from_file(path: str) -> World: """ Parse the file provided and generate a world that represents the content of this file. :param path: path of the file to parse. :return: a world representing the content of the file (walls, characters). """ file = open(path, "r") size = int(file.readline()) grid = [[0 for _ in range(2 * size + 1)] for _ in range(2 * size + 1)] i = 0 j = 0 ariane = (-1, -1) thesee = (-1, -1) door = (-1, -1) mino_h = [] mino_v = [] for line in file: for char in line: if char == "\n": j = 0 continue elif char == "-": grid[i][j] = H_WALL elif char == "|": grid[i][j] = V_WALL elif char == "+": grid[i][j] = C_WALL elif char == 'A': ariane = (i, j) elif char == 'T': thesee = (i, j) elif char == 'H': mino_h.append((i, j)) grid[i][j] = MINO elif char == 'V': mino_v.append((i, j)) grid[i][j] = MINO elif char == 'P': door = (i, j) j += 1 i += 1 map_name = path.split("/")[1] return World(grid, ariane, thesee, mino_h, mino_v, door, map_name)
def __init__(self, max_nights=1000, strategy="random"): Wuzzlopolis = World(strategy=strategy) self.world_objects = Wuzzlopolis.objects_report() self.nightly_stats = [] self.nightly_stats.append(Wuzzlopolis.population_status()) for i in range(max_nights): Wuzzlopolis.night() w_snapshot = Wuzzlopolis.population_status() self.nightly_stats.append(w_snapshot) if Wuzzlopolis.wuzzle_population == 0: break self.simulation_length = len(self.nightly_stats) - 1
def generate_events(self, world: World): assert self.compliance <= 1 all_people = [p for p in world.all_people() if p.get_age() > self.min_age] cnt_to_Immune = int(self.compliance * len(all_people)) people_to_immune = random.sample(all_people,cnt_to_Immune) ret = [] group_index = 0 while cnt_to_Immune > 0: for i in range(min(self.people_per_day,cnt_to_Immune)): person_index = group_index * self.people_per_day + i p = people_to_immune[person_index] ok , events_to_add = p.immune_and_get_events(start_date = self.start_date, delta_time = timedelta(group_index)) # print("id:{} cnt:{}".format(p.get_id(),len(events_to_add))) ret += events_to_add cnt_to_Immune = cnt_to_Immune - 1 group_index = group_index + 1 if self.duration.days < group_index: break return ret
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 water_data_for(state, writer, map, region_provider, description, test_water): random.setstate(state) world = World(map, region_provider) for _ in range(0, USER_COUNT): add_random_user(world) metrics = { "water-k-anon": 0, "water-area": 0, "euclid-k-anon": 0, "euclid-area": 0, "time": 0 } middler_users = [u for u in world.users if coords_in_bounds(u)] print(len(middler_users)) for user in middler_users: start = int(round(time.time() * 1000)) user.update_region(test_water=test_water) duration = int(round(time.time() * 1000)) - start print(duration) region: EuclidRegion region = user.current_region() metrics["euclid-k-anon"] += region.privacy metrics["euclid-area"] += region.area() metrics["water-k-anon"] += region.water_anonymity metrics["water-area"] += region.non_water_area metrics["time"] += duration total = len(middler_users) writer.writerow([ description, metrics["euclid-k-anon"] / total, metrics["euclid-area"] / total, metrics["water-k-anon"] / total, metrics["water-area"] / total, metrics["time"] / total ])
def generate_events(self, world: World): """ generated events that add the relevent routine change to the people that are relevant for this intervention, and events that remove it after that given duration. :param world: World object :return: list of Event objects """ new_events = [] for person in world.all_people(): if self._condition(person): if random.random() < self.compliance: curr_events = make_routine_change_events( person, self.start_date, self.end_date, self._key, self._routine_generator, self._args ) for event in curr_events: new_events.append(event) return new_events
def __solve__(self, world: World, conf: tuple, display=False) -> bool: if world.game_won(): return True if world.game_lost(): return False self.visited.add(conf) for direction in Direction: world.load_configuration(conf) if not world.valid_direction(world.ariane, direction): continue else: world.move_all(direction) if display: view.display(world) time.sleep(0.05) updated_conf = world.to_configuration() if updated_conf in self.visited: continue if self.__solve__(world, updated_conf, display): self.solution.append(dir_to_string(direction)) return True else: continue return False
def __init__(self): self.controls = { "up": False, "down": False, "left": False, "right": False } Game.game = self pygame.init() pygame.mixer.music.load("assets/music/420.wav") pygame.mixer.music.play(loops=-1, start=0.0) self.clock = pygame.time.Clock() self.display = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self.font = pygame.font.Font("assets/fonts/unifont-10.0.06.ttf", TEXT_HEIGHT) self.world = World() self.player = Player() self.generate_asteroids() self.connect_to_server()
def main(): parser = argparse.ArgumentParser() #parser.add_argument('-attempts', default=100, type=int, # help='The number of attempts') parser.add_argument( '-cfree', action='store_true', help='When enabled, disables collision checking (for debugging).') parser.add_argument('-max_time', default=10 * 60, type=float, help='The maximum runtime') parser.add_argument('-num_samples', default=1000, type=int, help='The number of samples') parser.add_argument('-seed', default=None, help='The random seed to use.') parser.add_argument('-teleport', action='store_true', help='Uses unit costs') parser.add_argument( '-visualize', action='store_true', help= 'When enabled, visualizes planning rather than the world (for debugging).' ) args = parser.parse_args() # TODO: could record the full trajectories here world = World(use_gui=args.visualize) world.open_gripper() #joint_names = DRAWER_JOINTS + CABINET_JOINTS joint_names = ZED_LEFT_JOINTS print('Joints:', joint_names) print('Knobs:', KNOBS) wait_for_user('Start?') for joint_name in joint_names: collect_pull(world, joint_name, args) for knob_name in KNOBS: collect_pull(world, knob_name, args) world.destroy()
def generate_events(self, world: World): """ generate events that are applied on the person when his state changes to symptomatic, and add the isolation routine to the whole house. After the given duration and params, an event will remove the change. :param world: World object :return: list of new Events to register on the simulation """ ret = [] for person in world.all_people(): if random.random() < self.compliance: household_environment = person.get_environment('household') add_effect = AddRoutineChangeEnvironmentEffect( environment=household_environment, routine_change_key='household_isolation', routine_change_generator=household_isolation_routine ) states = ( DiseaseState.INCUBATINGPOSTLATENT, DiseaseState.SYMPTOMATICINFECTIOUS ) person._init_event(*states) entry_moment = Event() add_trigger = AndTrigger( AfterTrigger(entry_moment), TimeRangeTrigger(self.start_date, self.end_date) ) add_event = Event( add_trigger, add_effect ) entry_moment.hook(add_event) day_event = DayEvent(self.start_date) # Wasteful in memory! day_event.hook(add_event) ret.append(day_event) if self.delay_on_enter: delay_time = self.delay_on_enter person.hook_on_change( states, Event( EmptyTrigger(), DelayedEffect(entry_moment, delay_time) ) ) else: person.hook_on_change(states, entry_moment) remove_effect = RemoveRoutineChangeEnvironmentEffect( environment=household_environment, routine_change_key='household_isolation' ) if self.is_exit_after_recovery: state_changes = list(itertools.product( [DiseaseState.SYMPTOMATICINFECTIOUS, DiseaseState.CRITICAL], [DiseaseState.IMMUNE, DiseaseState.DECEASED] )) for states in state_changes: person._init_event(*states) remove_trigger = AndTrigger( OrTrigger([ AfterTrigger(person.state_to_events[states]) for states in state_changes ]), AfterTrigger(add_event) ) remove_event = Event( remove_trigger, DelayedEffect(Event(effect=remove_effect), self.delay_on_exit) ) for states in state_changes: person.hook_on_change(states, remove_event) else: remove_trigger = AfterTrigger(add_event) remove_event = Event( remove_trigger, DelayedEffect(Event(effect=remove_effect), self.delay_on_exit) ) add_event.hook(remove_event) return ret
def assign_world(context, var): context.variables[var] = World()
def RandomWorld(): return World()
from src.cooperative_astar import CooperativeAStar from src.world import World if __name__ == "__main__": # all coordinates are given in format [y,x] # import doctest # doctest.testmod() w = World(15, 15, 0.1) # Initialize cas = CooperativeAStar(w) start, goal = w.get_start_goal(0.6) cas.register_agent("A", start, goal) start, goal = w.get_start_goal(0.6) cas.register_agent("B", start, goal) start, goal = w.get_start_goal(0.3) cas.register_agent("C", start, goal) cas.run_simulation() cas.visualize("test")
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()
def _test_world(): assert World().world() == 'world'
def solve(self, world: World, display=False) -> bool: """ Solve the world provided, using a Breadth-First Search algorithm. From the initial configuration of the world, this methods search for a winning configuration with a minimal number of moves for Ariane. :param world: the world to solve. :param display: if set to True, the method will draw each step of its computation. Set it to False if you need to quickly compute the result. :return: True if there is a solution for this world, False otherwise. """ conf = world.to_configuration() to_treat = [(conf, [])] self.visited.add(conf) while len(to_treat) > 0: current, dir_list = to_treat.pop(0) world.load_configuration(current) if world.game_won(): self.solution = dir_list return True if world.game_lost(): continue for direction in Direction: if not world.valid_direction(world.ariane, direction): continue world.move_all(direction) if display: view.display(world) time.sleep(0.05) updated = world.to_configuration() if updated not in self.visited: self.visited.add(updated) # Constructing a new list containing all the directions that lead to the previous configuration, # and add the direction that leads to the new configuration updated_dir_list = dir_list + [dir_to_string(direction)] to_treat.append((updated, updated_dir_list)) world.load_configuration(current) return False
def combine(self) -> str: world = World() return f'{hello.hello()} {world.world()}'
def tests_simple(): #Creates an empty world earth = World(3, 3) #Inserts robot earth.insertRobot("r2d2", 1, 1) #Inserts walls earth.insertWalls(0, 1) #Inserts goal earth.insertGoal(2, 2) #testing where robot is test(earth.where_is_robot() == [1, 1]) #testing feasible locations test(earth.is_feasible(1, 2) == True) test(earth.is_feasible(1, 0) == True) test(earth.is_feasible(2, 1) == True) test(earth.is_feasible(0, 0) == True) test(earth.is_feasible(0, 1) == False) #testing movement earth.move_robot(1, 2) earth.move_robot(1, 1) earth.move_robot(1, 0) #testing where robot is test(earth.where_is_robot() == [1, 0]) #testing movement earth.move_robot(1, 1) earth.move_robot(1, 2) earth.move_robot(2, 2) #testing where robot is test(earth.where_is_robot() == [2, 2]) #testing movement earth.move_robot(2, 1) earth.move_robot(2, 0) #testing where robot is test(earth.where_is_robot() == [2, 0]) #testing movement earth.move_robot(2, 1) #testing where robot is test(earth.where_is_robot() == [2, 1]) #moving towards goal earth.move_robot(2, 2) #goal reached test(earth.goal_reached() == True)