class MesaModel(Model): """A MESA Model""" def __init__(self): self.schedule = BaseScheduler(self) def add_agent(self, agent: MesaAgent): self.schedule.add(agent) return agent def get_agent(self, agentName: str) -> Optional[AgentMET4FOF]: agent = next( (x for x in self.schedule.agents if x.name == agentName), None) return agent def step(self): """Advance the model by one step.""" self.schedule.step() def agents(self): return [agent.name for agent in self.schedule.agents] def shutdown(self): """Shutdown entire MESA model with all agents and schedulers""" for agent in self.agents(): agent_obj = self.get_agent(agent) agent_obj.shutdown()
class MockModel(Model): """ Minimalistic model for testing purposes """ def __init__(self, variable_model_param, variable_agent_param, fixed_model_param=None, schedule=None, **kwargs): super().__init__() self.schedule = BaseScheduler(None) if schedule is None else schedule self.variable_model_param = variable_model_param self.variable_agent_param = variable_agent_param self.fixed_model_param = fixed_model_param self.n_agents = kwargs.get('n_agents', NUM_AGENTS) self.running = True self.init_agents() def init_agents(self): for i in range(self.n_agents): self.schedule.add(MockAgent(i, self, self.variable_agent_param)) def step(self): self.schedule.step()
class Modelo(Model): def __init__(self, N): self.num_ind = N self.schedule = BaseScheduler(self) self.crearciudad() def crearciudad(self): self.ciudad = Ciudad(self) for ind in self.ciudad.generarindividuos(): self.schedule.add(ind) #Se planta un infectado en la simulación self.schedule.agents[50].salud = INFECTADO #Se crean las casas distribuyendo los individuos self.ciudad.crear_hogares() #Se agrega una tienda a la ciudad y se conecta con todas las casas self.ciudad.add_node(2000, tipo='tienda', habitantes=None, ocupantes=[]) self.ciudad.conectaracasas(2000) def step(self): self.schedule.step() agente = self.schedule.agents[0] def conteo(self): #Una función para contar los casos actuales en la ciudad datos = [0, 0, 0, 0] for a in self.schedule.agents: datos[a.salud] += 1 return datos
class MockModel(Model): """ Minimalistic model for testing purposes. """ schedule = BaseScheduler(None) def __init__(self): self.schedule = BaseScheduler(self) self.model_val = 100 for i in range(10): a = MockAgent(i, self, val=i) self.schedule.add(a) self.datacollector = DataCollector( { "total_agents": lambda m: m.schedule.get_agent_count(), "model_value": "model_val", }, { "value": lambda a: a.val, "value2": "val2" }, {"Final_Values": ["agent_id", "final_value"]}, ) def step(self): self.schedule.step() self.datacollector.collect(self)
class CollisionModel(Model): def __init__(self, N, width, height, init_value): self.num_agents = N self.init_value = init_value self.grid = MultiGrid(width, height, True) self.schedule = BaseScheduler(self) # Create Agents for i in range(self.num_agents): a = CollisionAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = random.randrange(self.grid.width) y = random.randrange(self.grid.height) self.grid.place_agent(a, (x, y)) self.datacollector = DataCollector( #model_reporters={"AvgReward": compute_avgreward}, #model_reporters={"AvgCollision": compute_avgcollision}, model_reporters={"0": compute_avg_reward_angle_0, "90": compute_avg_reward_angle_1, "180": compute_avg_reward_angle_2, "270": compute_avg_reward_angle_3}, agent_reporters={"Reward": lambda a: a.reward}) def step(self): self.datacollector.collect(self) self.schedule.step()
class EnergyModel(Model): # model with some entities def __init__(self): # list of named activated agents by sheetname active_agents = [ "a" + str(int(i)) for i in wb.sheets['IO'].range("I3:I12").value if int(i) > 0 ] print("Active Agents: {}".format(active_agents)) self.num_agents = len(active_agents) self.schedule = BaseScheduler(self) # imports timesteps=[1:96] and datetimes(e.g. 00:00) self.time = wb.sheets['a1'].range("C3:D99").options(pd.Series).value # timesteps=[1:96] self.timeindex = self.time.index # Create Prosumer agents for i in active_agents: name = i a = Prosumer(i, self, name) self.schedule.add(a) def step(self): self.schedule.step()
class ScientistModel(Model): def __init__(self, scientists_per_cycle, ideas_per_cycle, cycles, granularity, max_idea_effort, \ true_means_mean, true_means_std_dev, true_std_devs_mean, true_std_devs_std_dev, \ starting_effort_mean, starting_effort_std_dev, k_mean, k_std_dev): self.schedule = BaseScheduler(self) # has a .time() function # Constant variables self.scientists_per_cycle = scientists_per_cycle self.ideas_per_cycle = ideas_per_cycle self.total_scientists = scientists_per_cycle * cycles self.total_ideas = ideas_per_cycle * cycles self.granularity = granularity self.current_idea_effort = np.zeros(self.total_ideas) self.max_idea_effort = max_idea_effort # Varied variables self.true_means_mean = true_means_mean self.true_means_std_dev = true_means_std_dev self.true_std_devs_mean = true_std_devs_mean self.true_std_devs_std_dev = true_std_devs_std_dev self.starting_effort_mean = starting_effort_mean self.starting_effort_std_dev = starting_effort_std_dev self.k_mean = k_mean self.k_std_dev = k_std_dev def step(self): for i in range(self.scientists_per_cycle): a = Scientist(self.schedule.time, self.scientists_per_cycle, self.ideas_per_cycle, self.total_scientists, \ self.total_ideas, self.granularity, self.current_idea_effort, self.max_idea_effort, \ self.true_means_mean, self.true_means_std_dev, self.true_std_devs_mean, self.true_std_devs_std_dev, \ self.starting_effort_mean, self.starting_effort_std_dev, self.k_mean, self.k_std_dev, self) self.schedule.add(a) self.schedule.step()
class ForestFire(Model): """ Simple Forest Fire model. """ def __init__(self, height=100, width=100, density=0.7): """ Create a new forest fire model. Args: height, width: The size of the grid to model density: What fraction of grid cells have a tree in them. """ # Set up model objects self.schedule = BaseScheduler(self) self.grid = Grid(height, width, torus=False) # Place a tree in each cell with Prob = density for (contents, x, y) in self.grid.coord_iter(): if self.random.random() < density: # Create a tree new_tree = TreeCell((x, y), self) # Set all trees in the first column on fire. if x == 0: new_tree.condition = "On Fire" self.grid._place_agent((x, y), new_tree) self.schedule.add(new_tree) def step(self): """ Advance the model by one step. """ self.schedule.step()
class MockMixedModel(Model): def __init__(self, **other_params): super().__init__() self.variable_name = other_params.get("variable_name", 42) self.fixed_name = other_params.get("fixed_name") self.running = True self.schedule = BaseScheduler(None) self.schedule.add(MockAgent(1, self, 0)) def step(self): self.schedule.step()
class MockMixedModel(Model): def __init__(self, **other_params): super().__init__() self.variable_name = other_params.get('variable_name', 42) self.fixed_name = other_params.get('fixed_name') self.running = True self.schedule = BaseScheduler(None) self.schedule.add(MockAgent(1, self, 0)) def step(self): self.schedule.step()
class Bloodstream(Model): # initialise source organ def __init__(self, N, width, height): self.num_agents = N self.grid = MultiGrid(height, width, True) self.schedule = BaseScheduler(self) self.source = Pituitary("Pituitary") self.target = Thyroid("Thyroid") self.schedule.add(self.source) # advance a step def step(self): self.schedule.step()
class RandomDilemma(Model): """ A model with two agents, prisoners in a game where their actions are distributed according to each agent's attribute probability of cooperation. """ def __init__(self, pdt_a, pdt_b, pdt_c, pdt_d, alpha_actions, beta_actions, dummy): super().__init__() self.num_agents = 2 self.a, self.b, self.c, self.d = pdt_a, pdt_b, pdt_c, pdt_d self.running = True # create agents. They will be activated one at a time in the order of add self.schedule = BaseScheduler(self) alpha = Prisoner("alpha", self, prob_coop=alpha_actions) beta = Prisoner("beta", self, prob_coop=beta_actions) self.schedule.add(alpha) self.schedule.add(beta) # collect wealth of agents self.data_collector = DataCollector( model_reporters=dict(pref_GI=pref_GI), agent_reporters=dict(Wealth="wealth", Action="action")) self.data_collector.collect(self) def step(self): """ Advance the model by one step. - all agents take their actions. - increment agent's wealth according to their actions. - collect the data on individual wealth. """ self.schedule.step() if self.schedule.agents[0].action == 'C' and self.schedule.agents[ 1].action == 'C': self.schedule.agents[0].wealth += self.a self.schedule.agents[1].wealth += self.a elif self.schedule.agents[0].action == 'C' and self.schedule.agents[ 1].action == 'D': self.schedule.agents[0].wealth += self.b self.schedule.agents[1].wealth += self.c elif self.schedule.agents[0].action == 'D' and self.schedule.agents[ 1].action == 'C': self.schedule.agents[0].wealth += self.c self.schedule.agents[1].wealth += self.b elif self.schedule.agents[0].action == 'D' and self.schedule.agents[ 1].action == 'D': self.schedule.agents[0].wealth += self.d self.schedule.agents[1].wealth += self.d self.data_collector.collect(self)
class MultiAgentModel(Model): def __init__(self, N): self.n_agents = N self.schedule = BaseScheduler(self) # Creating the environment and adding it to the scheduler, so I can access it on every agent step environment = Environment.Environment(N, self) self.schedule.add(environment) # Creating agents for i in range(self.n_agents): agent = Consumer.Consumer(i, self) self.schedule.add(agent) def step(self): self.schedule.step()
class WasteModel(Model): def __init__(self, num_generators, num_receivers): super().__init__() self.num_generators = num_generators self.num_receivers = num_receivers self.schedule = BaseScheduler(self) for i in range(num_generators): generator = WasteGenerator(self.next_id(), 1, self) self.schedule.add(generator) for i in range(num_receivers): receiver = WasteReceiver(self.next_id(), self) self.schedule.add(receiver) def step(self) -> None: self.schedule.step()
class SMA_collab(Model): """A model for infection spread.""" def __init__(self, nb_pop, nb_generations, n_truck, truck_capacity, list_clients, time_matrix, n_pool, radius_pool): self.nb_pop = nb_pop self.nb_generations = nb_generations self.n_truck = n_truck self.truck_capacity = truck_capacity self.list_clients = list_clients self.time_matrix = time_matrix self.n_pool = n_pool #self.grid = MultiGrid(width, height, True) self.datacollector = DataCollector(agent_reporters={"State": "state"}) #l'ordonnanceur du modele (instance de RandomActivation) #tester SimultaneousActivation (qui permet d'activer tous les agents en mêê temps) self.schedule = BaseScheduler(self) a = gen_agent(1, self, nb_pop, nb_generations, n_trucks, truck_capacity, list_clients) self.schedule.add(a) # b = tab_agent(2,self) # self.schedule.add(b) # c = rs_agent(3, self, n_trucks, truck_capacity) # self.schedule.add(c) # Gestion du pool d = pool_agent(4, self, n_pool, radius_pool) self.schedule.add(d) # Gestion des courbes e1 = graphic_agent(5, self, a.solution, self.list_clients) # e2 = graphic_agent(6,self,b.solution, self.list_clients) # e3 = graphic_agent(7,self,c.solution, self.list_clients) #e = graphic_agent() self.schedule.add(e1) # self.schedule.add(e2) # self.schedule.add(e3) def step(self): #passage de l'instant t à l'instant (t+1) self.schedule.step()
class Modelo (Model): def __init__ (self): self.schedule = BaseScheduler(self) self.schedule.add( DBAgent(0, self) ) self.schedule.add( ChatAgent(1, self) ) self.intent = None self.entity = None self.pendingQuery = False self.answer = None self.pendingAnswer = False def step(self): self.schedule.step()
class ExposureDecay(Model): """A model with some number of agents.""" def __init__(self, N): self.num_agents = N self.schedule = BaseScheduler(self) # Create agents for i in range(self.num_agents): a = Consumer(i, self) self.schedule.add(a) self.datacollector = DataCollector( model_reporters={"Awareness": computeLiftandDecay}, agent_reporters={"Quintile": "quintile"}) def step(self): self.datacollector.collect(self) self.schedule.step()
class ConversationModel(Model): # Model with 'no_of_agents_local' initial agents def __init__(self, no_of_agents_local, no_of_population_nodes): self.num_agents = no_of_agents_local self.schedule = BaseScheduler(self) self.list_of_agent_objects = [] self.no_of_population_nodes = no_of_population_nodes for population_node in range(self.no_of_population_nodes): agents_in_node = [] for agent_index in range(self.num_agents): agent = ConversationAgent(agent_index, self) agents_in_node.append(agent) self.list_of_agent_objects.append(agents_in_node) def step(self): self.schedule.step()
class MockModel(Model): """ Minimalistic model for testing purposes """ def __init__(self, variable_model_param=None, variable_agent_param=None, fixed_model_param=None, schedule=None, enable_agent_reporters=True, **kwargs): super().__init__() self.schedule = BaseScheduler(self) if schedule is None else schedule self.variable_model_param = variable_model_param self.variable_agent_param = variable_agent_param self.fixed_model_param = fixed_model_param self.n_agents = 3 if enable_agent_reporters: agent_reporters = {"agent_id": "unique_id", "agent_local": "local"} else: agent_reporters = None self.datacollector = DataCollector( model_reporters={ "reported_model_param": self.get_local_model_param }, agent_reporters=agent_reporters, ) self.running = True self.init_agents() def init_agents(self): if self.variable_agent_param is None: agent_val = 1 else: agent_val = self.variable_agent_param for i in range(self.n_agents): self.schedule.add(MockAgent(i, self, agent_val)) def get_local_model_param(self): return 42 def step(self): self.datacollector.collect(self) self.schedule.step()
class MockModel(Model): def __init__(self, shuffle=False, activation=STAGED): ''' Creates a Model instance with a schedule Args: shuffle (Bool): whether or not to instantiate a scheduler with shuffling. This option is only used for StagedActivation schedulers. activation (str): which kind of scheduler to use. 'random' creates a RandomActivation scheduler. 'staged' creates a StagedActivation scheduler. The default scheduler is a BaseScheduler. ''' super().__init__() self.random_state = MockRandomState() self.log = [] # Make scheduler if activation == STAGED: model_stages = ["stage_one", "stage_two"] self.schedule = StagedActivation(self, stage_list=model_stages, shuffle=shuffle, random_state=self.random_state) elif activation == RANDOM: self.schedule = RandomActivation(self, random_state=self.random_state) elif activation == SIMULTANEOUS: self.schedule = SimultaneousActivation(self, random_state=self.random_state) else: self.schedule = BaseScheduler(self, random_state=self.random_state) # Make agents for name in ["A", "B"]: agent = MockAgent(name, self) self.schedule.add(agent) def step(self): self.schedule.step()
class MockModel(Model): """ Minimalistic model for testing purposes """ def __init__(self, model_param, agent_param): """ Args: model_param (any): parameter specific to the model agent_param (int): parameter specific to the agent """ self.schedule = BaseScheduler(None) self.model_param = model_param self.running = True for i in range(NUM_AGENTS): a = MockAgent(i, agent_param) self.schedule.add(a) def step(self): self.schedule.step()
class PetriDish(Model): """ Main model instance. It assignes one cell in each grid location, selecting its type randomly at the time of assignment; it assigns a single activated Producer cell in the middle of the grid. """ def __init__(self, width=50, height=50, proportion_producers=0.3, proportion_consumers=0.3): self.running = True self.schedule = BaseScheduler(self) self.grid = SingleGrid(width, height, torus=False) initial_activator = Producer("Initial activator", self, activated=True) center_coords = (math.floor(width / 2), math.floor(height / 2)) ## Rolled into the placement of other cells # self.schedule.add(initial_activator) # self.grid.place_agent(initial_activator, center_coords) # roll a die and place Producer, Consumer or undifferentiated cell for x in range(width): for y in range(height): roll = r.random() coords = (x, y) if coords == center_coords: agent = initial_activator elif roll <= proportion_producers: agent = Producer(coords, self) elif roll <= proportion_producers + proportion_consumers: agent = Consumer(coords, self) else: agent = Cell(coords, self) self.schedule.add(agent) self.grid.place_agent(agent, coords) def step(self): self.schedule.step() # goes through agents in the order of addition
class MockModel(Model): ''' Minimalistic model for testing purposes. ''' schedule = BaseScheduler(None) def __init__(self): self.schedule = BaseScheduler(self) for i in range(10): a = MockAgent(i, i) self.schedule.add(a) self.datacollector = DataCollector( {"total_agents": lambda m: m.schedule.get_agent_count()}, {"value": lambda a: a.val}, {"Final_Values": ["agent_id", "final_value"]}) def step(self): self.schedule.step() self.datacollector.collect(self)
class FireSupportModel(Model): 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])) # print(self.schedule.agents[1]) def step(self): self.schedule.step()
class TicTacToe(Model): def __init__(self): super().__init__() self.running = True self.endgame = None self.grid = SingleGrid(3, 3, False) self.schedule = BaseScheduler(self) playerX = Player(1, self) playerO = Player(-1, self) self.schedule.add(playerX) self.schedule.add(playerO) def step(self): if not self.endgame: self.schedule.step() else: self.running = False
class MockModel(Model): """ Minimalistic model for testing purposes. """ schedule = BaseScheduler(None) def __init__(self): self.schedule = BaseScheduler(self) self.model_val = 100 for i in range(10): a = MockAgent(i, self, val=i) self.schedule.add(a) self.datacollector = DataCollector( { "total_agents": lambda m: m.schedule.get_agent_count(), "model_value": "model_val", "model_calc": self.schedule.get_agent_count, "model_calc_comp": [self.test_model_calc_comp, [3, 4]], "model_calc_fail": [self.test_model_calc_comp, [12, 0]] }, { "value": lambda a: a.val, "value2": "val2" }, {"Final_Values": ["agent_id", "final_value"]}, ) def test_model_calc_comp(self, input1, input2): if input2 > 0: return (self.model_val * input1) / input2 else: assert ValueError return None def step(self): self.schedule.step() self.datacollector.collect(self)
class MockModel(Model): def __init__(self, shuffle=False, activation=STAGED): """ Creates a Model instance with a schedule Args: shuffle (Bool): whether or not to instantiate a scheduler with shuffling. This option is only used for StagedActivation schedulers. activation (str): which kind of scheduler to use. 'random' will create a RandomActivation scheduler. 'staged' will create a StagedActivation scheduler. The default scheduler is a BaseScheduler. """ self.log = [] # Make scheduler if activation == STAGED: model_stages = ["stage_one", "stage_two"] self.schedule = StagedActivation(self, model_stages, shuffle=shuffle) elif activation == RANDOM: self.schedule = RandomActivation(self) elif activation == SIMULTANEOUS: self.schedule = SimultaneousActivation(self) else: self.schedule = BaseScheduler(self) # Make agents for name in ["A", "B"]: agent = MockAgent(name) self.schedule.add(agent) def step(self): self.schedule.step()
class ScientistModel(Model): def __init__(self, N, ideas_per_time, time_periods): self.num_scientists = N self.total_ideas = ideas_per_time*time_periods # Store the max investment allowed in any idea self.max_investment = poisson(lam=50, size=self.total_ideas) # Store parameters for true idea return distribution self.true_sds = poisson(4, size=self.total_ideas) self.true_means = poisson(50, size=self.total_ideas) # Create array to keep track of total effort allocated to each idea self.total_effort = np.zeros(self.total_ideas) self.schedule = BaseScheduler(self) for i in range(self.num_scientists): a = Scientist(i, self) self.schedule.add(a) def step(self): self.schedule.step()
class MockModel(Model): """ Minimalistic model for testing purposes """ def __init__(self, variable_model_param, variable_agent_param, fixed_model_param=None, schedule=None, **kwargs): super().__init__() self.schedule = BaseScheduler(None) if schedule is None else schedule self.variable_model_param = variable_model_param self.variable_agent_param = variable_agent_param self.fixed_model_param = fixed_model_param self.n_agents = kwargs.get("n_agents", NUM_AGENTS) self.datacollector = DataCollector(model_reporters={ "reported_model_param": self.get_local_model_param }, agent_reporters={ "agent_id": "unique_id", "agent_local": "local" }) self.running = True self.init_agents() def get_local_model_param(self): return 42 def init_agents(self): for i in range(self.n_agents): self.schedule.add(MockAgent(i, self, self.variable_agent_param)) def step(self): self.datacollector.collect(self) self.schedule.step()
class Antcluster(Model): """A model with some number of agents.""" def __init__(self, N): self.num_agents = N self.i = 1 self.grid = SingleGrid(120, 120, True) self.grid1 = SingleGrid(120, 120, True) self.schedule = RandomActivation(self) self.schedule_dados = BaseScheduler(self) # Create agents for i in range(self.num_agents): a = Ant(i, self) self.schedule.add(a) x = self.random.randrange(self.grid.width) y = self.random.randrange(self.grid.height) #z = np.asarray([x,y]) #print(z) plt.axis([-10, 125, -10, 125]) #plt.scatter(x,y) self.grid.place_agent(a, (x, y)) #create data for i in range(150): b = dado(i, self) self.schedule_dados.add(b) x = self.random.randrange(self.grid1.width) y = self.random.randrange(self.grid1.height) #print(x,y) z = np.asarray([x, y]) plt.axis([-10, 125, -10, 125]) plt.scatter(x, y) self.grid1.place_agent(b, (x, y)) def step(self): '''Advance the model by one step.''' self.schedule_dados.step() self.schedule.step()
class CarModel(Model): ''' Model class for the Nagel-Schreckenberg Car model. ''' def __init__(self, height, width, dawdle_prob, car_amount): ''' ''' super().__init__() self.height = height self.width = width self.dawdle_prob = dawdle_prob self.car_amount = car_amount self.schedule = BaseScheduler(self) self.grid = SingleGrid(height, width, torus=True) self.place_agents() self.running = True def place_agents(self): for i in range(self.car_amount): while True: try: r = random() agent = CarAgent((int(r*100), 5), self, 10) self.grid.position_agent(agent, int(r*100), 5) self.schedule.add(agent) break except Exception: continue def step(self): self.schedule.step()
class ContactModel(Model): def __init__(self, N, height, width, exponent, steps, seed): self.number_of_agents = N self.height = height self.width = width self.exponent = exponent self.x_locs = np.zeros((N, steps + 1)) self.y_locs = np.zeros((N, steps + 1)) self.current_step = 0 #NEW self.current_step_contacts = [] self.adjacency_matrix = np.zeros((N, N)) self.grid = MultiGrid(self.width, self.height, torus=False) self.schedule = BaseScheduler(self) #RandomActivation(self) # Add N pedestrians to model (schedule, grid) taken_pos = [] for i in range(self.number_of_agents): x = self.random.randrange(1, self.grid.width - 1) y = self.random.randrange(1, self.grid.height - 1) pos = (x, y) new_human = Pedestrian(i, self, pos, self.exponent, seed=i) self.schedule.add(new_human) self.grid.place_agent(new_human, pos) self.x_locs[i][0] = x self.y_locs[i][0] = y taken_pos.append(pos) self.data_collector = DataCollector() self.running = True self.data_collector.collect(self) def contact_update(self, contact_ids): contact_ids = sorted(contact_ids) if contact_ids not in self.current_step_contacts: self.current_step_contacts.append(contact_ids) def update_adjecency_matrix(self): ''' #TODO: order agent steps, order updates, double or not for id_tuple in self.current_step_contacts: self.adjacency_matrix[id_tuple[0], id_tuple[1]]+=1 ''' agents = self.schedule.agents for i, agent in enumerate(agents): neighbors = self.grid.get_neighbors(agent.pos, moore=True, radius=5) for neighbor in neighbors: if neighbor.unique_id > agent.unique_id: self.adjacency_matrix[agent.unique_id, neighbor.unique_id] += 1 def step(self): self.schedule.step() self.update_adjecency_matrix() #self.current_step_contacts=[] #self.data_collector.collect(self) def run(self, N): for i in range(N): self.step() self.current_step += 1 #NEW for agent in self.schedule.agents: self.x_locs[agent.unique_id][i + 1] = agent.pos[0] self.y_locs[agent.unique_id][i + 1] = agent.pos[1] if i % 100 == 0: print(i)
class Travel_Model(Model): def __init__(self, networks=None, season_length=91, n_agents=100, max_steps=1000): self.n_steps = 0 self.max_steps = max_steps self.season_length = season_length self.schedule = BaseScheduler(self) if networks is None: networks = self._demo_networks() self.n_seasons = len(networks) # space nodes = networks[0].nodes() edges = [] for network in networks: edges.append(network.edges(data=True)) self.network = MultilayerNetworkSpace(nodes,edges) # agents for n in range(n_agents): start, dest = sample(nodes,2) start_time = randrange(self.n_seasons * self.season_length ) agent = Travel_Agent(start,dest,start_time,n) self.schedule.add(agent) # data collection self.dc = DataCollector( { "enroute": lambda m: self.count_en_route(m) }, { "position": lambda a: a.pos, "travel_time": lambda a: a.travel_time } ) self.dc.collect(self) self.running = True def step(self): self.schedule.step() self.dc.collect(self) self.n_steps +=1 if self.count_en_route(self) == 0 or self.n_steps >= self.max_steps: self.running = False def get_season(self, time): return (time // self.season_length) % self.n_seasons def _demo_networks(self): networks = [] for i in range(3): g = nx.random_graphs.watts_strogatz_graph(100, 2, 0.05) dists = np.random.randint(1,30, g.number_of_edges()) dists = dict(zip(g.edges(),dists)) nx.set_edge_attributes(g, 'distance', dists) networks.append(g) return networks @staticmethod def count_en_route(model): count = len(model.schedule.agents) for agent in model.schedule.agents: if agent.pos == agent.dest: count -=1 return count
class Board(Model): def __init__(self, width, height): self.running = True self.grid = MultiGrid(width, height, False) #true for toroidal grid self.schedule = BaseScheduler(self) self.adversary_pieces = [] self.agent_pieces = [] self.initialize_grid() def initialize_grid(self): ''' Here we initialize the d by d board with pits and pieces ''' #initialize the pits num_pits = (d // 3) - 1 for j in range(1, d - 1): for i in random.sample(list(range(0, d)), d)[0:num_pits]: pit = Pit('pit', self) self.grid.place_agent(pit, (i, j)) #init all pieces num_pieces = d // 3 for j in range(d): j_off = j + 1 if j_off % 3 == 1: piece_adv = Piece('wumpus', self, 'adversary') piece_agent = Piece('wumpus', self, 'agent') elif j_off % 3 == 2: piece_adv = Piece('hero', self, 'adversary') piece_agent = Piece('hero', self, 'agent') else: piece_adv = Piece('mage', self, 'adversary') piece_agent = Piece('mage', self, 'agent') self.grid.place_agent(piece_adv, (j, 0)) self.grid.place_agent(piece_agent, (j, d - 1)) self.adversary_pieces.append(piece_adv) self.agent_pieces.append(piece_agent) def get_adversary_piece(self): ''' Here is where player enters coordinates of piece they want to move. Checks for invalid inputs and protects against them ''' pos = '' agents = [] while not is_valid_position(pos) or agents == [] or agents[ 0].name == 'pit' or agents[0].player == 'agent': print("Enter position of piece you want to move (sep by spaces): ", end='') pos = input() if not is_valid_position(pos): print('invalid argument') continue x, y = int(pos.split()[0]) - 1, int(pos.split()[1]) - 1 agents = list(self.grid[x][y]) if agents != []: if agents[0].name == 'pit': print('cannot select a pit') continue if agents[0].player == 'adversary': piece = agents[0] return piece else: print('You cannot move agent\'s pieces') continue else: print('cannot select empty square') def get_agent_piece_and_move(self): ''' here we will call minimax from minimax.py. This will return the agent piece that will move along with the coordinate it will move to ''' start = time.time() _, _, piece, pos = minimax(self, depth, float('-inf'), float('inf'), True) print('time passed:', time.time() - start) return piece, pos def winner(self): ''' here we will implement the winning condition we will return the value True and the player who won. we want the game to stop when win() == True.. and we will implement this in the step function ''' return self.adversary_pieces == [] or self.agent_pieces == [] def collision_check(self, piece): x, y = piece.pos agents = list(self.grid[x][y]) #pop piece from agents agents.remove(piece) for agent in agents: if agent.name == 'pit': self.grid.remove_agent(piece) self._remove_piece_from_list(piece) elif agent.player != piece.player: if agent.name == piece.name: self.grid.remove_agent(piece) self.grid.remove_agent(agent) self._remove_piece_from_list(piece) self._remove_piece_from_list(agent) elif agent.name in ['hero', 'wumpus' ] and piece.name in ['hero', 'wumpus']: agent_to_remove = agent if agent.name == 'wumpus' else piece self.grid.remove_agent(agent_to_remove) self._remove_piece_from_list(agent_to_remove) elif piece.name in ['mage', 'hero' ] and agent.name in ['mage', 'hero']: agent_to_remove = agent if agent.name == 'hero' else piece self.grid.remove_agent(agent_to_remove) self._remove_piece_from_list(agent_to_remove) elif piece.name in ['mage', 'wumpus' ] and agent.name in ['mage', 'wumpus']: agent_to_remove = agent if agent.name == 'mage' else piece self.grid.remove_agent(agent_to_remove) self._remove_piece_from_list(agent_to_remove) def _remove_piece_from_list(self, piece): if piece.player == 'agent': self.agent_pieces.remove(piece) else: self.adversary_pieces.remove(piece) def distance_to_board(self): #calculates manhattan distance from each piece to all of other pieces then adds all those up #also weights attacking pieces and vulnerable pieces so that agent runs towards #pieces it can capture and runs away from pieces that can capture it opposing_offense = {'wumpus': 'mage', 'mage': 'hero', 'hero': 'wumpus'} opposing_defense = {j: i for i, j in opposing_offense.items()} total = 0 for ag_piece in self.agent_pieces: for adv_piece in self.adversary_pieces: weight = 1 x1, y1 = ag_piece.pos x2, y2 = adv_piece.pos if opposing_offense[ag_piece.name] == adv_piece.name: weight = 2 elif opposing_defense[ag_piece.name] == adv_piece.name: weight = -2 total += weight * (abs(x1 - x2) + abs(y1 - y2)) return total / len(self.agent_pieces) def evaluate(self): #returns the score for the whole board (made for agent's favor) try: return len(self.agent_pieces) - len(self.adversary_pieces) + ( eval_weight / self.distance_to_board()) except: return len(self.agent_pieces) - len(self.adversary_pieces) def step(self): ''' Each time step is called, player enters move and their piece moves. Agent also moves its piece that was returned from get_agent_piece_and_move(). This is essentially two turns of the game: player's turn and agent's turn. ''' if not self.winner(): adversary_piece = self.get_adversary_piece() self.schedule.add(adversary_piece) self.schedule.step() self.collision_check(adversary_piece) self.schedule.remove(adversary_piece) agent_piece, agent_pos = self.get_agent_piece_and_move() if agent_piece != None: agent_piece.move(pos=agent_pos) self.collision_check(agent_piece) else: print('Game Over')