class PopulationModel(Model): """ a model with population in a district """ num_S = 0 num_I = 0 num_R = 0 num_agents = 0 def __init__(self, N, r, p, width, height): self.num_agents = N self.num_S = N self.required_social_dist = r self.infect_overallprob = p """ scheduler controls the order at which agents are activated """ """ RandomActivation activates all the agents once per step """ self.schedule = RandomActivation(self) """ create a continuous space """ self.district = ContinuousSpace(width, height, True) # create agents for i in range(self.num_agents): a = PersonAgent(i, self.required_social_dist, self.infect_overallprob, self) # i is the id number self.schedule.add(a) """ add an agent to the schedule using add method """ # place the agent in the continuous space x = self.random.randrange(self.district.width) y = self.random.randrange(self.district.height) self.district.place_agent(a, (x, y)) print("id " + str(i) + " is at " + str(x) + "," + str(y)) def step(self): """ advance the model by one step """ self.schedule.step()
def __init__(self, floorplan, human_count): super().__init__() self.n_agents = human_count self.floorplan = [] self.humans = [] self.obstacles = [] self.exits = [] self.spawns = [] self.scheduler = DistanceScheduler(self) # Loads floorplan textfile with open('C:/Users/jozse/github/ABMasters/floorplans/' + floorplan) as f: [ self.floorplan.append(line.strip().split()) for line in f.readlines() ] # Creates continuous Mesa space & discrete grid for pathfinding size = len(self.floorplan[0]), len(self.floorplan) self.space = ContinuousSpace(size[0], size[1], torus=False) self.grid = [] for y in range(6 * size[1]): row = [] for x in range(6 * size[0]): row.append(ca.Node((x, y))) self.grid.append(row) # Places all elements in Mesa space and grid for x in range(size[0]): for y in range(size[1]): value = str(self.floorplan[y][x]) if value == 'W': self.new_agent(ca.Wall, (x, y)) for i in range(6 * x, 6 * (x + 1)): for j in range(6 * y, 6 * (y + 1)): self.grid[j][i].done = True elif value == 'F': self.new_agent(ca.Furniture, (x, y)) for i in range(6 * x, 6 * (x + 1)): for j in range(6 * y, 6 * (y + 1)): self.grid[j][i].done = True elif value == 'S': self.spawns.append((x, y)) elif value == 'E': self.new_agent(ca.Exit, (x, y)) i = 6 * x + 1 j = 6 * y + 1 self.grid[j][i].exit = True # Spawn specified number of Humans in spawn points humans = rnd.sample(self.spawns, self.n_agents) for pos in humans: self.new_agent(ca.Human, pos) print("Classroom initialised.")
def __init__(self, ax, ax2): self.schedule = RandomActivation(self) self.grid = ContinuousSpace(400, 400, True) self.ax = ax self.ax2 = ax2 # Creating all agents enemy_inf1 = EnInfantry(1, self, 10, enemy1_locx, enemy1_locy, self.ax) self.schedule.add(enemy_inf1) self.grid.place_agent(enemy_inf1, (enemy1_locx, enemy1_locy)) enemy_arty1 = EnArty(10, self, 30, enemy2_locx, enemy2_locy, self.ax) self.schedule.add(enemy_arty1) self.grid.place_agent(enemy_arty1, (enemy2_locx, enemy2_locy)) enemy_tank1 = EnArmour(20, self, 20, enemy3_locx, enemy3_locy, self.ax) self.schedule.add(enemy_tank1) self.grid.place_agent(enemy_tank1, (enemy3_locx, enemy3_locy)) friendly_unit1 = FrUnit(30, self, friendly_unit_health, frUnit_init_locx, frUnit_init_locy, self.ax, self.ax2) self.schedule.add(friendly_unit1) self.grid.place_agent(friendly_unit1, (frUnit_init_locx, frUnit_init_locy)) friendly_arty = FrArty(40, self, 10, fs_init_locx, fs_init_locy, self.ax) self.schedule.add(friendly_arty) self.grid.place_agent(friendly_arty, (fs_init_locx, fs_init_locy))
def __init__(self, red_col, red_row, red_squad, blue_col, blue_row, blue_squad, blue_agents_elite_squad, red_movement, blue_movement, width, height): self.running = True self.space = ContinuousSpace(width, height, False) self.schedule = RandomActivation(self) self.next_agent_id = 1 self.RED_MOVEMENT_SPEED = red_movement self.BLUE_MOVEMENT_SPEED = blue_movement separation_y = 1.5 # Find center red_first_y = ((height / 2 - (red_squad * red_row / 2 * separation_y)) + separation_y / 2) - ((red_squad - 1) * separation_y * 2) blue_first_y = ( (height / 2 - (blue_squad * blue_row / 2 * separation_y)) + separation_y / 2) - ((blue_squad - 1) * separation_y * 2) # Create agents self.spawner(15.0, red_first_y, 1.5, separation_y, red_col, red_row, red_squad, 0, 'red') self.spawner(width - 15.0, blue_first_y, -1.5, separation_y, blue_col, blue_row, blue_squad, blue_agents_elite_squad, 'blue')
def __init__(self, Prey_count, Tiger_count, width, height, CANVAS): self.count = 0 # Number of agents self.schedule = mesa.time.RandomActivation(self) self.space = ContinuousSpace(width + 1, height + 1, torus=False) self.step_num = 0 self.last_uid = 0 self.canvas = CANVAS self.grass_ticks = dict() self.Prey_count = 0 self.Tiger_count = 0 # Create patches for x, y in itertools.product(range(width), range(height)): a = Patch(self.new_uid(), self) # self.schedule.add(a) self.space.place_agent(a, (x, y)) a.canvas = CANVAS a.draw() # Create Animals: for i in range(Prey_count): x = random.randrange(self.space.width) y = random.randrange(self.space.width) self.create_baby(x, y, age=random.randint(1, 5)) for i in range(Tiger_count): x = random.randrange(self.space.width) y = random.randrange(self.space.width) self.create_baby(x, y, age=random.randint(1, 5), type='Tiger')
class ShoalModel(Model): """ Shoal model class. Handles agent creation, placement and scheduling. """ # Todo: removed vision. Do neighbours need to be included here too? def __init__(self, population=100, width=100, height=100, speed=1, separation=2, cohere=0.025, separate=0.25, match=0.04): """ Create a new Boids model. Args: N: Number of Boids width, height: Size of the space. speed: how fast the boids should move. separation: what's the minimum distance each Boid will attempt to keep from any other cohere, separate, match: factors for the relative importance of the three drives. """ self.population = population self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True, grid_width=10, grid_height=10) self.factors = dict(cohere=cohere, separate=separate, match=match) self.make_agents() self.running = True def make_agents(self): """ Create N agents, with random positions and starting velocities. """ # Todo: fix issue with "1 missing required positional argument: 'separation' for i in range(self.population): x = random.random() * self.space.x_max y = random.random() * self.space.y_max pos = np.array((x, y)) velocity = np.random.random(2) * 2 - 1 fish = Fish(i, self, pos, self.speed, velocity, self.separation, **self.factors) self.space.place_agent(fish, pos) self.schedule.add(fish) self.datacollector = DataCollector(model_reporters={ "Polarization": polar, "Nearest Neighbour Distance": nnd }) def step(self): self.datacollector.collect(self) self.schedule.step()
def __init__(self, N=200, width=20, height=20): self.num_agents = int(N / 2) self.grid = ContinuousSpace(height, width, True) self.redAgentList = [] self.blueAgentList = [] self.turn = 1 #redLethality = input("Enter Red team lethality coefficient") #blueLethality = input("Enter Blue team lethality coefficient") # Create Red and Blue agents for i in range(self.num_agents): a = RedSoldier(i, self) self.redAgentList.append(a) # add red soldier to random location on grid rx = self.random.randrange(self.grid.width) ry = self.random.randrange(self.grid.height) self.grid.place_agent(a, (rx, ry)) b = BlueSoldier(i, self) self.blueAgentList.append(b) # add blue soldier to random location on grid bx = self.random.randrange(self.grid.width) by = self.random.randrange(self.grid.height) self.grid.place_agent(b, (bx, by)) self.running = True
def __init__(self, formation, population, width, height, vision, min_dist, flock_vel, accel_time, equi_dist, repulse_max, repulse_spring, align_frict, align_slope, align_min, wall_decay, wall_frict, form_shape, form_track, form_decay, wp_tolerance): ''' Create a new Flockers model. Args: population: Number of agents. width, height: Size of the space. vision: How far around should each agents look for its neighbors. min_dist: Minimum allowed distance between agents before a collision occurs. This is only used for statistics. ''' # set parameters self.population = population self.space = ContinuousSpace(width, height, torus=False) self.vision = vision self.min_dist = min_dist self.params = dict(formation=formation, population=population, flock_vel=flock_vel, accel_time=accel_time, equi_dist=equi_dist, repulse_max=repulse_max, repulse_spring=repulse_spring, align_frict=align_frict, align_slope=align_slope, align_min=align_min, wall_decay=wall_decay, wall_frict=wall_frict, form_shape=form_shape, form_track=form_track, form_decay=form_decay, wp_tolerance=wp_tolerance) # data collection for plots self.datacollector = DataCollector( model_reporters={ "Minimum Distance": minimum_distance, "Maximum Distance": maximum_distance, "Average Distance": average_distance, "Collisions": collisions, "Messags Distributed": messages_distributed, "Messags Centralized": messages_centralized }) # execute agents sequentially in a random order self.schedule = RandomActivation(self) # place agents self.make_agents() # pairwise distances self.agent_distances() # run model self.running = True # collect initial data sample self.datacollector.collect(self)
def __init__(self, population=100, width=100, height=100, speed=1, vision=10, separation=2, cohere=0.025, separate=0.25, match=0.04): # Todo: add parameter for blind spot """ Create a new Boids model. Args: N: Number of Boids width, height: Size of the space. speed: how fast the boids should move. vision: how far around should each Boid look for its neighbors separation: what's the minimum distance each Boid will attempt to keep from any other cohere, separate, match: factors for the relative importance of the three drives. """ self.population = population self.vision = vision self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, torus=True, grid_width=10, grid_height=10) self.factors = dict(cohere=cohere, separate=separate, match=match) self.make_agents() self.running = True
def __init__(self, ax, ax2): self.schedule = BaseScheduler(self) self.grid = ContinuousSpace(400, 400, True) self.ax = ax self.ax2 = ax2 # Creating all agents # All agents are activated in the order they are added to the scheduler. friendly_arty = FrArty(10, self, 10, fsUnit_loc[0], fsUnit_loc[1], self.ax, enemy1_loc, fsUnit_loc, ammunition_heavy_round, ammunition_light_round) self.schedule.add(friendly_arty) self.grid.place_agent(friendly_arty, (fsUnit_loc[0], fsUnit_loc[1])) friendly_unit1 = FrUnit(11, self, friendly_unit_health, frUnit_init_loc[0], frUnit_init_loc[1], self.ax, self.ax2, fsUnit_loc) self.schedule.add(friendly_unit1) self.grid.place_agent(friendly_unit1, (frUnit_init_loc[0], frUnit_init_loc[1])) enemy_inf1 = EnInfantry(1, self, 20, enemy1_loc[0], enemy1_loc[1], self.ax, fsUnit_loc, enemy1_loc) self.schedule.add(enemy_inf1) self.grid.place_agent(enemy_inf1, (enemy1_loc[0], enemy1_loc[1])) enemy_arty1 = EnArty(2, self, 20, enemy2_loc[0], enemy2_loc[1], self.ax, fsUnit_loc, enemy2_loc) self.schedule.add(enemy_arty1) self.grid.place_agent(enemy_arty1, (enemy2_loc[0], enemy2_loc[1])) enemy_tank1 = EnArmour(3, self, 20, enemy3_loc[0], enemy3_loc[1], self.ax, fsUnit_loc, enemy3_loc) self.schedule.add(enemy_tank1) self.grid.place_agent(enemy_tank1, (enemy3_loc[0], enemy3_loc[1]))
def __init__(self, agent_type, width=500, height=500, num_adversaries=8, road_width=60, frozen=True, epsilon=0, episode_duration=100, Q=None, N=None): self.num_adversaries = num_adversaries self.road_width = road_width self.episode_duration = episode_duration self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True) self.cars = [] self.make_agents(AgentType(agent_type), frozen, epsilon, Q, N) self.running = True self.step_count = 0 self.count = 0 self.curr_reward = 0 self.reset() self.datacollector = DataCollector( model_reporters={"Agent rewards sum": get_rewards_sum_log})
def __init__(self, population=100, width=100, height=100, speed=1, vision=10, separation=2, cohere=0.025, separate=0.25, match=0.04): ''' Create a new Flockers model. Args: population: Number of Boids width, height: Size of the space. speed: How fast should the Boids move. vision: How far around should each Boid look for its neighbors separation: What's the minimum distance each Boid will attempt to keep from any other cohere, separate, match: factors for the relative importance of the three drives. ''' self.population = population self.vision = vision self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True) self.factors = dict(cohere=cohere, separate=separate, match=match) self.make_agents() self.running = True
class SimulationModel(Model): def __init__(self, x_max, y_max, species, iterations): super(SimulationModel, self).__init__() self.starved = 0 self.space = ContinuousSpace(x_max, y_max, grid_width=20, grid_height=20, torus=True) self.schedule = SimultaneousActivation(self) self.iterations = iterations self.species = [] self.create_population(species) def create_population(self, species): for specie, lamarck, params in species: individuals = [] for param in params: individuals.append( self.create_individual(specie, lamarck, param)) self.schedule.add(individuals[-1]) self.species.append(individuals) def create_individual(self, specie, lamarck, param): x = random.random() * self.space.x_max y = random.random() * self.space.y_max ind = specie(self.space, x, y, lamarck, param) self.space.place_agent(ind, ind.pos) return ind def step(self): self.schedule.step() self.cleanup_corpses() self.update_iterations() def update_iterations(self): self.iterations -= 1 if not self.iterations: self.running = False def cleanup_corpses(self): for agent in filter(t_matcher(AutonomicAgent), self.schedule.agents): if agent.energy <= 0: self.schedule.remove(agent) # noinspection PyProtectedMember self.space._remove_agent(agent.pos, agent) self.starved += 1 def results(self): def get_energy(individual): return individual.eaten, individual.energy def get_energies(specie): return map(get_energy, specie) return map(get_energies, self.species)
class ShoalModel(Model): """ Shoal model class. Handles agent creation, placement and scheduling. """ def __init__(self, population=100, width=100, height=100, speed=1, vision=10, separation=2, cohere=0.025, separate=0.25, match=0.04): # Todo: add parameter for blind spot """ Create a new Boids model. Args: N: Number of Boids width, height: Size of the space. speed: how fast the boids should move. vision: how far around should each Boid look for its neighbors separation: what's the minimum distance each Boid will attempt to keep from any other cohere, separate, match: factors for the relative importance of the three drives. """ self.population = population self.vision = vision self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, torus=True, grid_width=10, grid_height=10) self.factors = dict(cohere=cohere, separate=separate, match=match) self.make_agents() self.running = True def make_agents(self): """ Create N agents, with random positions and starting velocities. """ for i in range(self.population): x = random.random() * self.space.x_max y = random.random() * self.space.y_max pos = np.array((x, y)) velocity = np.random.random(2) * 2 - 1 fish = Fish(i, self, pos, self.speed, velocity, self.vision, self.separation, **self.factors) self.space.place_agent(fish, pos) self.schedule.add(fish) self.datacollector = DataCollector( model_reporters={"Polarization": polar, "Nearest Neighbour Distance": nnd, "Shoal Area": area, "Mean Distance from Centroid": centroid_dist}) def step(self): self.datacollector.collect(self) self.schedule.step()
class BattleFieldModel(Model): """A model of an agent-based battle simulation using Lanchester’s Law. First assume it is analogous to the continuous model whereby all troops are homogenous and jumbled together. At combat start, each troop is put in a random position. A shooting occurs on each side at each time step, if any enemies are left to kill. The soldier shooting shall be chosen randomly from among the remaining troops. Thus each is equally likely to be the random shooter on his/her side. The probability of killing an opposing troop is expressed in the lethality coefficients. """ def __init__(self, N=200, width=20, height=20): self.num_agents = int(N / 2) self.grid = ContinuousSpace(height, width, True) self.redAgentList = [] self.blueAgentList = [] self.turn = 1 #redLethality = input("Enter Red team lethality coefficient") #blueLethality = input("Enter Blue team lethality coefficient") # Create Red and Blue agents for i in range(self.num_agents): a = RedSoldier(i, self) self.redAgentList.append(a) # add red soldier to random location on grid rx = self.random.randrange(self.grid.width) ry = self.random.randrange(self.grid.height) self.grid.place_agent(a, (rx, ry)) b = BlueSoldier(i, self) self.blueAgentList.append(b) # add blue soldier to random location on grid bx = self.random.randrange(self.grid.width) by = self.random.randrange(self.grid.height) self.grid.place_agent(b, (bx, by)) self.running = True def step(self): numRed = len(self.redAgentList) numBlue = len(self.blueAgentList) if ((numRed > 0) and (numBlue > 0)): if (self.turn == 1): print("Red Turn") self.redAgentList[random.randint(0, numRed - 1)].step() self.turn = 0 else: print("Blue Turn") self.blueAgentList[random.randint(0, numBlue - 1)].step() self.turn = 1 else: if (numRed == 0): print("Battle Over! Blue Team Wins.") else: print("Battle Over! Red Team Wins.") self.running = False
def __init__(self, N=1, O=1, sensorRange=5, target_speed=1.0, active_prediction=False, a=1, width=150, height=150): super().__init__() #self.running = True self.num_agents = N self.num_observer_agents = O self.target_speed = target_speed self.multiplication_factor = 1.0 / target_speed self.sensor_range = sensorRange # * self.multiplication_factor self.targets_observed = set() self.grid = ContinuousSpace(int(width), int(height), False) self.schedule = RandomActivation(self) self.observers_indications = [] self.a = a self.active_prediction = active_prediction self.verbose = False # Print-monitoring # self.datacollector = DataCollector( # {"Wolves": lambda m: m.schedule.get_breed_count(Wolf), # "Sheep": lambda m: m.schedule.get_breed_count(Sheep)}) # Create targets for i in range(self.num_agents): # Add the agent to a random grid cell x = self.random.randrange(self.grid.width) y = self.random.randrange(self.grid.height) a = TargetAgent("t_" + str(i), (x, y), self, self.target_speed) self.schedule.add(a) self.grid.place_agent(a, (x, y)) # Create observers for i in range(self.num_observer_agents): #b = ObserverAgent("o_"+str(i), self.sensor_range, self.multiplication_factor, self) # Add the agent to a kmens indication self.observers_indications = self.kmeans_indications() point = self.observers_indications[i] x = math.floor(point[0]) y = math.floor(point[1]) b = ObserverAgent("o_" + str(i), (x, y), self, self.sensor_range, self.multiplication_factor) self.schedule.add(b) self.grid.place_agent(b, (x, y)) self.datacollector = DataCollector( model_reporters={"Observation": "mean_observation"})
def __init__(self, height=100, width=100, init_prey=100, prey_reproduction=0.03, init_predator=10, predator_vision=1, predator_reproduction=0.5, predator_death=0.02, local_offspring=False, max_iters=500, seed=None): super().__init__() self.height = height self.width = width self.init_prey = init_prey self.prey_reproduction = prey_reproduction self.init_predator = init_predator self.predator_vision = predator_vision self.predator_reproduction = predator_reproduction self.predator_death = predator_death self.local_offspring = local_offspring self.iteration = 0 self.max_iters = max_iters self.schedule = RandomActivation(self) self.space = ContinuousSpace(height, width, torus=True) model_reporters = { 'Prey': lambda model: self.count('Prey'), 'Predator': lambda model: self.count('Predator'), } self.datacollector = DataCollector(model_reporters=model_reporters) # Place prey for i in range(self.init_prey): x = self.random.uniform(0, self.width) y = self.random.uniform(0, self.height) # next_id() starts at 1 prey = Prey(self.next_id(), self, (x, y), self.prey_reproduction) self.space.place_agent(prey, (x, y)) self.schedule.add(prey) # Place predators for i in range(self.init_predator): x = self.random.uniform(0, self.width) y = self.random.uniform(0, self.height) predator = Predator(self.next_id(), self, (x, y), self.predator_reproduction, self.predator_death, self.predator_vision) self.space.place_agent(predator, (x, y)) self.schedule.add(predator) self.running = True self.datacollector.collect(self)
class BoidModel(Model): ''' Flocker model class. Handles agent creation, placement and scheduling. ''' def __init__(self, population=100, width=100, height=100, speed=1, vision=10, separation=2, cohere=0.025, separate=0.25, match=0.04): ''' Create a new Flockers model. Args: population: Number of Boids width, height: Size of the space. speed: How fast should the Boids move. vision: How far around should each Boid look for its neighbors separation: What's the minimum distance each Boid will attempt to keep from any other cohere, separate, match: factors for the relative importance of the three drives. ''' self.population = population self.vision = vision self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True, grid_width=10, grid_height=10) self.factors = dict(cohere=cohere, separate=separate, match=match) self.make_agents() self.running = True def make_agents(self): ''' Create self.population agents, with random positions and starting headings. ''' for i in range(self.population): x = random.random() * self.space.x_max y = random.random() * self.space.y_max pos = np.array((x, y)) velocity = np.random.random(2) * 2 - 1 boid = Boid(i, self, pos, self.speed, velocity, self.vision, self.separation, **self.factors) self.space.place_agent(boid, pos) self.schedule.add(boid) def step(self): self.schedule.step()
def setUp(self): """ Create a test space and populate with Mock Agents. """ self.space = ContinuousSpace(70, 50, False, -30, -30) self.agents = [] for i, pos in enumerate(REMOVAL_TEST_AGENTS): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos)
def setUp(self): ''' Create a test space and populate with Mock Agents. ''' self.space = ContinuousSpace(70, 20, False, -30, -30, 100, 100) self.agents = [] for i, pos in enumerate(TEST_AGENTS): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos)
def __init__(self): super().__init__() self.schedule = SimultaneousActivation(self) self.grid = ContinuousSpace(75, 40, False) ## Creation des agents de base for _ in range(1): a = Walker(self.next_id(), self) self.schedule.add(a) self.grid.place_agent(a, (0, 0))
def __init__(self, seed=None, population=100, width=500, height=500, initial_proportion_sick=0.1, proportion_moving=0.5, speed=1.0, time_until_symptomatic=3, transmission_probability=0.2, transmission_distance=1.0, recovery_probability=0.6, death_probability=0.02, quarantine_probability=0.5): """ Create a new Transmission model. Potential things to add # age as an attribute. # differential mobility as a function of age. # differential recovery as a function of age. # time dependence of recovery (e.g., sick for longer = higher probability of death?) # non random walking # add another state that is self quarantied (based on time to symptoms), so movers and nonmovers can become # self quarantied after symptoms arise. Then they don't transmit. """ super(Transmission, self).__init__(seed=seed) self.population = population self.proportion_moving = proportion_moving self.initial_proportion_sick = initial_proportion_sick self.speed = speed self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True) self.factors = dict(transmission_probability=transmission_probability, recovery_probability=recovery_probability, death_probability=death_probability, transmission_distance=transmission_distance, time_until_symptomatic=time_until_symptomatic, quarantine_probability=quarantine_probability) self.make_agents() self.running = True self.datacollector = DataCollector( model_reporters={ "uninfected": analyze_uninfected, "sick": analyze_sick, "recovered": analyze_recovered, "dead": analyze_dead, "quarantined": analyze_quarantined, })
def __init__(self, N, width, height): self.num_agents = N self.grid = ContinuousSpace(width, height, False) self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): a = StudentAgent(i, self) self.schedule.add(a) x = random.randrange(self.grid.width) y = random.randrange(self.grid.height) self.grid.place_agent(a, (x, y))
class GangRivalry(Model): """ """ def __init__(self, grid_size=GRID_DIM, gang_info=GANGS, pars=PARS): super().__init__() self.width, self.height = grid_size self.area = ContinuousSpace(self.width, self.height, False) self.gang_info = gang_info self.parameters = pars self.total_gangs = len(self.gang_info) self.rivalry_matrix = np.zeros((self.total_gangs, self.total_gangs)) self.road_density = np.random.rand(self.width, self.height) self.schedule_GangMember = OneRandomActivation(self) self.init_population() self.datacollector = DataCollector({ "Interaction": lambda m: self.schedule_GangMember.get_agent_count() }) self.running = True self.datacollector.collect(self) def init_population(self): """ """ for gang in self.gang_info: size = gang["gang_size"] pos = gang["anchor"] name = gang["name"] for _ in range(size): self.new_agent(pos, name) def new_agent(self, pos, name): """ """ agent = GangMember(self.next_id(), self, pos, name) self.area.place_agent(agent, pos) self.schedule_GangMember.add(agent) def update_rivalry(self, agent1, agent2): """ """ self.rivalry_matrix[agent1.gang, agent2.gang] += 1 def step(self): self.schedule_GangMember.step() self.datacollector.collect(self) def run_model(self, step_count=200): for _ in range(step_count): self.step()
def __init__(self, floorplan, human_count): super().__init__() self.n_agents = human_count self.floorplan = [] self.humans = [] self.obstacles = [] self.exits = [] self.spawns = [] self.scheduler = DistanceScheduler(self) # Creates continuous Mesa space & discrete grid for pathfinding size = len(self.floorplan[0]), len(self.floorplan) self.space = ContinuousSpace(size[0], size[1], torus=False) self.grid = [] for y in range(6 * size[1]): row = [] for x in range(6 * size[0]): row.append(ca.Node((x, y))) self.grid.append(row) # Places all elements in Mesa space and grid for x in range(size[0]): for y in range(size[1]): value = str(self.floorplan[y][x]) if value == 'W': self.new_agent(ca.Wall, (x, y)) for i in range(6 * x, 6 * (x + 1)): for j in range(6 * y, 6 * (y + 1)): self.grid[j][i].done = True elif value == 'F': self.new_agent(ca.Furniture, (x, y)) for i in range(6 * x, 6 * (x + 1)): for j in range(6 * y, 6 * (y + 1)): self.grid[j][i].done = True elif value == 'S': self.spawns.append((x, y)) elif value == 'E': self.new_agent(ca.Exit, (x, y)) i = 6 * x + 1 j = 6 * y + 1 self.grid[j][i].exit = True # Spawn n_agents according to floorplan for pos in rnd.sample(self.spawns, self.n_agents): self.new_agent(ca.Human, pos)
def __init__(self, x_max, y_max, species, iterations): super(SimulationModel, self).__init__() self.starved = 0 self.space = ContinuousSpace(x_max, y_max, grid_width=20, grid_height=20, torus=True) self.schedule = SimultaneousActivation(self) self.iterations = iterations self.species = [] self.create_population(species)
def __init__(self): self.num_agents_sita = 30 self.num_agents_ue = 30 self.num_kabe = 1 self.schedule = RandomActivationByBreed(self) #self.schedule = RandomActivation(self) self.width = 10 self.height = 50 self.space = ContinuousSpace(self.width, self.height, True) self.syudan_hito_sita = np.zeros((self.num_agents_sita, 2)) self.syudan_hito_ue = np.zeros((self.num_agents_ue, 2)) self.syudan_kabe = np.zeros((self.num_kabe, 2)) self.time = 1000 # Create agents for j in range(self.num_agents_sita): a = Hokousya_sita(j, self) self.syudan_hito_sita[j, 0] = a.iti_x self.syudan_hito_sita[j, 1] = a.iti_y self.schedule.add(a) #self.syudan_hito_sita[i,0] = a.iti_x #self.syudan_hito_sita[i,1] = a.iti_y for i in range(self.num_agents_ue): b = Hokousya_ue(i, self) self.syudan_hito_ue[i, 0] = b.iti_x self.syudan_hito_ue[i, 1] = b.iti_y self.schedule.add(b)
def __init__(self, width=100, height=100, torus=True): self.running = True self.unique_id_counter = 0 # number from 1 to 4, indicating the stage of the day self.firm_count = 0 self.household_count = 0 self.households = [] self.firms = [] self.luxury_firms = [] self.daily_tick = 0 self.money_supply = 10e6 self.population = 10 self.luxury_price = 0 self.gdp = 0 self.space = ContinuousSpace(width, height, torus) self.schedule = BaseScheduler(self) self._populate() # Networking self.G = nx.Graph() self._make_network() # Data collection self.datacollector = DataCollector( model_reporters={'agg_wealth': compute_agg_wealth} #agent_reporters = {TODO if you need to} )
def __init__(self): self.num_agents_sita = 20 self.num_agents_ue = 20 self.num_kabe = 1 self.schedule = SimultaneousActivation(self) self.width = 10 self.height = 50 self.space = ContinuousSpace(self.width, self.height, True) self.syudan_hito_sita = np.zeros((self.num_agents_sita, 2)) self.syudan_hito_ue = np.zeros((self.num_agents_ue, 2)) self.syudan_kabe = np.zeros((self.num_kabe, 2)) self.time = 1000 # Create agents for i in range(self.num_agents_sita): a = Hokousya_sita(i, self) self.schedule.add(a) self.syudan_hito_sita[i,0] = a.iti_x self.syudan_hito_sita[i,1] = a.iti_y for i in range(self.num_agents_ue): b = Hokousya_ue(i, self) self.schedule.add(b) self.syudan_hito_ue[i,0] = b.iti_x self.syudan_hito_ue[i,1] = b.iti_y #壁を作る for i in range(self.num_kabe): c = Kabe(i, self) self.schedule.add(c) self.syudan_kabe[i, 0] = c.iti[0] self.syudan_kabe[i, 1] = c.iti[1]
class BoidModel(Model): ''' Flocker model class. Handles agent creation, placement and scheduling. ''' N = 100 width = 100 height = 100 def __init__(self, N, width, height, speed, vision, separation): ''' Create a new Flockers model. Args: N: Number of Boids width, height: Size of the space. speed: How fast should the Boids move. vision: How far around should each Boid look for its neighbors separtion: What's the minimum distance each Boid will attempt to keep from any other ''' self.N = N self.vision = vision self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True, grid_width=10, grid_height=10) self.make_agents() self.running = True def make_agents(self): ''' Create N agents, with random positions and starting headings. ''' for i in range(self.N): x = random.random() * self.space.x_max y = random.random() * self.space.y_max pos = (x, y) heading = np.random.random(2) * 2 - np.array((1, 1)) heading /= np.linalg.norm(heading) boid = Boid(i, pos, self.speed, heading, self.vision, self.separation) self.space.place_agent(boid, pos) self.schedule.add(boid) def step(self): self.schedule.step()
class TestSpaceToroidal(unittest.TestCase): ''' Testing a toroidal continuous space. ''' def setUp(self): ''' Create a test space and populate with Mock Agents. ''' self.space = ContinuousSpace(70, 20, True, -30, -30, 100, 100) self.agents = [] for i, pos in enumerate(TEST_AGENTS): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for i, pos in enumerate(TEST_AGENTS): a = self.agents[i] assert a.pos == pos def test_distance_calculations(self): ''' Test toroidal distance calculations. ''' pos_1 = (-30, -30) pos_2 = (70, 20) assert self.space.get_distance(pos_1, pos_2) == 0 pos_3 = (-30, -20) assert self.space.get_distance(pos_1, pos_3) == 10 def test_neighborhood_retrieval(self): ''' Test neighborhood retrieval ''' neighbors_1 = self.space.get_neighbors((-20, -20), 1) assert len(neighbors_1) == 2 neighbors_2 = self.space.get_neighbors((40, -10), 10) assert len(neighbors_2) == 0 neighbors_3 = self.space.get_neighbors((-30, -30), 10) assert len(neighbors_3) == 1
def __init__(self, N, width, height, speed, vision, separation): ''' Create a new Flockers model. Args: N: Number of Boids width, height: Size of the space. speed: How fast should the Boids move. vision: How far around should each Boid look for its neighbors separtion: What's the minimum distance each Boid will attempt to keep from any other ''' self.N = N self.vision = vision self.speed = speed self.separation = separation self.schedule = RandomActivation(self) self.space = ContinuousSpace(width, height, True, grid_width=10, grid_height=10) self.make_agents() self.running = True
class TestSpaceToroidal(unittest.TestCase): ''' Testing a toroidal continuous space. ''' def setUp(self): ''' Create a test space and populate with Mock Agents. ''' self.space = ContinuousSpace(70, 20, True, -30, -30, 100, 100) self.agents = [] for i, pos in enumerate(TEST_AGENTS): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for i, pos in enumerate(TEST_AGENTS): a = self.agents[i] assert a.pos == pos def test_distance_calculations(self): ''' Test toroidal distance calculations. ''' pos_1 = (-30, -30) pos_2 = (70, 20) assert self.space.get_distance(pos_1, pos_2) == 0 pos_3 = (-30, -20) assert self.space.get_distance(pos_1, pos_3) == 10 def test_heading(self): pos_1 = (-30, -30) pos_2 = (70, 20) self.assertEqual((0, 0), self.space.get_heading(pos_1, pos_2)) pos_1 = (65, -25) pos_2 = (-25, -25) self.assertEqual((10, 0), self.space.get_heading(pos_1, pos_2)) def test_neighborhood_retrieval(self): ''' Test neighborhood retrieval ''' neighbors_1 = self.space.get_neighbors((-20, -20), 1) assert len(neighbors_1) == 2 neighbors_2 = self.space.get_neighbors((40, -10), 10) assert len(neighbors_2) == 0 neighbors_3 = self.space.get_neighbors((-30, -30), 10) assert len(neighbors_3) == 1 def test_bounds(self): ''' Test positions outside of boundary ''' boundary_agents = [] for i, pos in enumerate(OUTSIDE_POSITIONS): a = MockAgent(len(self.agents) + i, None) boundary_agents.append(a) self.space.place_agent(a, pos) for a, pos in zip(boundary_agents, OUTSIDE_POSITIONS): adj_pos = self.space.torus_adj(pos) assert a.pos == adj_pos a = self.agents[0] for pos in OUTSIDE_POSITIONS: assert self.space.out_of_bounds(pos) self.space.move_agent(a, pos)
class TestSpaceAgentMapping(unittest.TestCase): ''' Testing a continuous space for agent mapping during removal. ''' def setUp(self): ''' Create a test space and populate with Mock Agents. ''' self.space = ContinuousSpace(70, 50, False, -30, -30) self.agents = [] for i, pos in enumerate(REMOVAL_TEST_AGENTS): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos) def test_remove_first(self): ''' Test removing the first entry ''' agent_to_remove = self.agents[0] self.space.remove_agent(agent_to_remove) for i, agent in self.space._index_to_agent.items(): assert agent.pos == tuple(self.space._agent_points[i, :]) assert i == self.space._agent_to_index[agent] assert agent_to_remove not in self.space._agent_to_index assert agent_to_remove.pos is None with self.assertRaises(Exception): self.space.remove_agent(agent_to_remove) def test_remove_last(self): ''' Test removing the last entry ''' agent_to_remove = self.agents[-1] self.space.remove_agent(agent_to_remove) for i, agent in self.space._index_to_agent.items(): assert agent.pos == tuple(self.space._agent_points[i, :]) assert i == self.space._agent_to_index[agent] assert agent_to_remove not in self.space._agent_to_index assert agent_to_remove.pos is None with self.assertRaises(Exception): self.space.remove_agent(agent_to_remove) def test_remove_middle(self): ''' Test removing a middle entry ''' agent_to_remove = self.agents[3] self.space.remove_agent(agent_to_remove) for i, agent in self.space._index_to_agent.items(): assert agent.pos == tuple(self.space._agent_points[i, :]) assert i == self.space._agent_to_index[agent] assert agent_to_remove not in self.space._agent_to_index assert agent_to_remove.pos is None with self.assertRaises(Exception): self.space.remove_agent(agent_to_remove)
class TestSpaceNonToroidal(unittest.TestCase): ''' Testing a toroidal continuous space. ''' def setUp(self): ''' Create a test space and populate with Mock Agents. ''' self.space = ContinuousSpace(70, 20, False, -30, -30) self.agents = [] for i, pos in enumerate(TEST_AGENTS): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for i, pos in enumerate(TEST_AGENTS): a = self.agents[i] assert a.pos == pos def test_agent_matching(self): ''' Ensure that the agents are all placed and indexed properly. ''' for i, agent in self.space._index_to_agent.items(): assert agent.pos == tuple(self.space._agent_points[i, :]) assert i == self.space._agent_to_index[agent] def test_distance_calculations(self): ''' Test toroidal distance calculations. ''' pos_2 = (70, 20) pos_3 = (-30, -20) assert self.space.get_distance(pos_2, pos_3) == 107.70329614269008 def test_heading(self): pos_1 = (-30, -30) pos_2 = (70, 20) self.assertEqual((100, 50), self.space.get_heading(pos_1, pos_2)) pos_1 = (65, -25) pos_2 = (-25, -25) self.assertEqual((-90, 0), self.space.get_heading(pos_1, pos_2)) def test_neighborhood_retrieval(self): ''' Test neighborhood retrieval ''' neighbors_1 = self.space.get_neighbors((-20, -20), 1) assert len(neighbors_1) == 2 neighbors_2 = self.space.get_neighbors((40, -10), 10) assert len(neighbors_2) == 0 neighbors_3 = self.space.get_neighbors((-30, -30), 10) assert len(neighbors_3) == 0 def test_bounds(self): ''' Test positions outside of boundary ''' for i, pos in enumerate(OUTSIDE_POSITIONS): a = MockAgent(len(self.agents) + i, None) with self.assertRaises(Exception): self.space.place_agent(a, pos) a = self.agents[0] for pos in OUTSIDE_POSITIONS: assert self.space.out_of_bounds(pos) with self.assertRaises(Exception): self.space.move_agent(a, pos)