class TestBaseGrid(unittest.TestCase): ''' Testing a non-toroidal grid. ''' torus = False def setUp(self): ''' Create a test non-toroidal grid and populate it with Mock Agents ''' self.grid = Grid(3, 5, self.torus) self.agents = [] counter = 0 for y in range(3): for x in range(5): if TEST_GRID[y][x] == 0: continue counter += 1 # Create and place the mock agent a = MockAgent(counter, None) self.agents.append(a) self.grid.place_agent(a, (x, y)) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for agent in self.agents: x, y = agent.pos assert self.grid[y][x] == agent def test_neighbors(self): ''' Test the base neighborhood methods on the non-toroid. ''' neighborhood = self.grid.get_neighborhood(1, 1, moore=True) assert len(neighborhood) == 8 neighborhood = self.grid.get_neighborhood(4, 1, moore=True) assert len(neighborhood) == 5 neighborhood = self.grid.get_neighborhood(0, 0, moore=False) assert len(neighborhood) == 2 neighbors = self.grid.get_neighbors(4, 1, moore=False) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors(4, 1, moore=True) assert len(neighbors) == 2 neighbors = self.grid.get_neighbors(1, 1, moore=False, include_center=True) assert len(neighbors) == 3 neighbors = self.grid.get_neighbors(3, 1, moore=False, radius=2) assert len(neighbors) == 4
class ConwaysGameOfLife(Model): ''' Represents the 2-dimensional array of cells in Conway's Game of Life. ''' def __init__(self, height=50, width=50, server=True): ''' Create a new playing area of (height, width) cells. ''' # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.schedule = SimultaneousActivation(self) self.server = server # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) #Datacollector -- default for this model is no data collection, but one can use OABM to assign one. #so this is an empty DataCollector instance from MESA self.datacollector = DataCollector() # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self) if self.random.random() < 0.1: cell.state = cell.ALIVE self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.running = True def step(self): ''' Have the scheduler advance each cell by one step ''' self.schedule.step() def run_model(self, n=None): if n: self.num_steps = n if self.server == False: for _ in range(self.num_steps): self.step() return self else: from .server import server server.launch()
class ColorPatchModel(Model): ''' represents a 2D lattice where agents live ''' def __init__(self, width, height): ''' Create a 2D lattice with strict borders where agents live The agents next state is first determined before updating the grid ''' self._grid = Grid(width, height, torus=False) self._schedule = SimultaneousActivation(self) # self._grid.coord_iter() # --> should really not return content + col + row # -->but only col & row # for (contents, col, row) in self._grid.coord_iter(): # replaced content with _ to appease linter for (_, row, col) in self._grid.coord_iter(): cell = ColorCell((row, col), self, ColorCell.OPINIONS[random.randrange(0, 16)]) self._grid.place_agent(cell, (row, col)) self._schedule.add(cell) self.running = True def step(self): ''' Advance the model one step. ''' self._schedule.step() # the following is a temporary fix for the framework classes accessing # model attributes directly # I don't think it should # --> it imposes upon the model builder to use the attributes names that # the framework expects. # # Traceback included in docstrings @property def grid(self): return self._grid @property def schedule(self): return self._schedule
class MockModel(Model): """Test model for testing""" def __init__(self, width, height, key1=103, key2=104): self.width = width self.height = height self.key1 = (key1, ) self.key2 = key2 self.schedule = SimultaneousActivation(self) self.grid = Grid(width, height, torus=True) for (c, x, y) in self.grid.coord_iter(): a = MockAgent(x + y * 100, self, x * y * 3) self.grid.place_agent(a, (x, y)) self.schedule.add(a) def step(self): self.schedule.step()
class MockModel(Model): """ Test model for testing """ def __init__(self, width, height, key1=103, key2=104): self.width = width self.height = height self.key1 = key1, self.key2 = key2 self.schedule = SimultaneousActivation(self) self.grid = Grid(width, height, torus=True) for (c, x, y) in self.grid.coord_iter(): a = MockAgent(x + y * 100, self, x * y * 3) self.grid.place_agent(a, (x, y)) self.schedule.add(a) def step(self): self.schedule.step()
class ConwaysGameOfLife(Model): """ Represents the 2-dimensional array of cells in Conway's Game of Life. """ def __init__(self, size, **kwargs): """ Create a new playing area of (height, width) cells. """ # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(size, size, torus=True) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (_contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self) if self.random.random() < 0.1: cell.state = cell.ALIVE self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.running = True def step(self): """ Have the scheduler advance each cell by one step """ self.schedule.step() def on_click(self, x, y, **kwargs): print(x, y) cell = self.grid[x][y] cell.state = cell.ALIVE
class CGoLModel(Model): ''' Represents the 2-dimensional array of cells in Conway's Game of Life. ''' def __init__(self, height, width): ''' Create a new playing area of (height, width) cells. ''' # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): pos = (x, y) init_state = CGoLCell.DEAD # Initially, make 10% of the cells ALIVE. if random.random() < 0.1: init_state = CGoLCell.ALIVE cell = CGoLCell(pos, self, init_state) # Put this cell in the grid at position (x, y) self.grid.place_agent(cell, pos) # Add this cell to the scheduler. self.schedule.add(cell) self.running = True def step(self): ''' Advance the model by one step. ''' self.schedule.step()
class CGoLModel(Model): ''' Represents the 2-dimensional array of cells in Conway's Game of Life. ''' def __init__(self, height, width): ''' Create a new playing area of (height, width) cells. ''' # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): pos = (x, y) init_state = CGoLCell.DEAD # Initially, make 10% of the cells ALIVE. if random.random() < 0.1: init_state = CGoLCell.ALIVE cell = CGoLCell(pos, self, init_state) # Put this cell in the grid at position (x, y) self.grid.place_agent(cell, pos) # Add this cell to the scheduler. self.schedule.add(cell) self.running = True def step(self): ''' Advance the model by one step. ''' self.schedule.step()
class ConwaysGameOfLife(Model): ''' Respresents the 2-dimentional array of cells in Conway's Game of Life. ''' def __init__(self, height=50, width=50): ''' Create a new playing area of (height, width) cells. ''' # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # Computing their next state simultaneously. # This needs to be done because each cell's next state depends on # the current state of all its neighbors -- before they've changed self.schedule = SimultaneousActivation(self) # Use a single grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self) if self.random.random() < 0.1: cell.state = cell.ALIVE # place_agent: Position an agent on the Grid, and set its pos variable self.grid.place_agent(cell, (x, y)) # add(): Add an agent object to the schedule self.schedule.add(cell) self.running = True def step(self): ''' Have the schedular advance each cell by one step ''' # step(): Execute the step of all the agents, one at a time. self.schedule.step()
class ConwaysGameOfLife(Model): ''' Represents the 2-dimensional array of cells in Conway's Game of Life. ''' def __init__(self, height=50, width=50): ''' Create a new playing area of (height, width) cells. ''' # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self) if self.random.random() < 0.1: cell.state = cell.ALIVE self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.running = True def step(self): ''' Have the scheduler advance each cell by one step ''' self.schedule.step()
class ForestFireModel(Model): def __init__(self, L, p): super().__init__() self.grid = Grid(L, L, False) self.schedule = SimultaneousActivation(self) self.running = True self.p = p for i in range(L): for j in range(L): if self.random.random() <= self.p: if i == L - 1: tree = TreeAgent((i, j), self, "burning") else: tree = TreeAgent((i, j), self, "occupied") self.schedule.add(tree) self.grid.place_agent(tree, (i, j)) self.datacollector = DataCollector(model_reporters={ "p*": compute_p, "Cluster": compute_cluster }) def step(self): self.schedule.step() if not self.exists_status("burning"): self.datacollector.collect(self) self.running = False def exists_status( self, status ): # function to check is exist any tree which has some status for tree in self.schedule.agents: if tree.status == status: return True
class ColorPatchModel(Model): ''' represents a 2D lattice where agents live ''' def __init__(self, width, height): ''' Create a 2D lattice with strict borders where agents live The agents next state is first determined before updating the grid ''' self._grid = Grid(width, height, torus=False) self._schedule = SimultaneousActivation(self) # self._grid.coord_iter() # --> should really not return content + col + row # -->but only col & row # for (contents, col, row) in self._grid.coord_iter(): # replaced content with _ to appease linter for (_, row, col) in self._grid.coord_iter(): cell = ColorCell((row, col), self, ColorCell.OPINIONS[random.randrange(0, 16)]) self._grid.place_agent(cell, (row, col)) self._schedule.add(cell) self.running = True def step(self): ''' Advance the model one step. ''' self._schedule.step() # the following is a temporary fix for the framework classes accessing # model attributes directly # I don't think it should # --> it imposes upon the model builder to use the attributes names that # the framework expects. # # Traceback included in docstrings @property def grid(self): """ /mesa/visualization/modules/CanvasGridVisualization.py is directly accessing Model.grid 76 def render(self, model): 77 grid_state = defaultdict(list) ---> 78 for y in range(model.grid.height): 79 for x in range(model.grid.width): 80 cell_objects = model.grid.get_cell_list_contents([(x, y)]) AttributeError: 'ColorPatchModel' object has no attribute 'grid' """ return self._grid @property def schedule(self): """ mesa_ABM/examples_ABM/color_patches/mesa/visualization/ModularVisualization.py", line 278, in run_model while self.model.schedule.steps < self.max_steps and self.model.running: AttributeError: 'NoneType' object has no attribute 'steps' """ return self._schedule
class infection_model(Model): def __init__(self, height=100, width=100, dummy="", density=0.5, p_inf=0.1, p_rec=0.3, p_reinf=0.05, p_test=0.1, p_death=0.2, test_n=0, hood="Moore", datacollector={}): ''' Create a new playing area of (height, width) cells. ''' # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.height = height self.width = width self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Use the DataCollector method to store the relevant information of our # model. This helps with plotting in the web socke, but also with running #more models at the same time using BatchRunner (in batch.py) self.datacollector = DataCollector( model_reporters=self.compute_reporters()) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self, p_inf, p_rec, p_reinf, p_test, p_death, test_n, hood) if self.random.random() < density: cell.state = cell.INFECTED self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.measure_CA = [] self.running = True self.datacollector.collect(self) def step(self): ''' Have the scheduler advance each cell by one step ''' self.measure_CA = [a for a in self.schedule.agents] self.schedule.step() # collect data self.datacollector.collect(self) def compute_reporters(self): ''' Returns A dictionary of the fractions of the population that are Infected, Quarantined, Recovered or Dead ''' mod_rep = { "Fraction Infected": lambda m: self.count_infected(m, self.height * self.width), "Fraction Quarantined": lambda m: self.count_quarantined(m, self.height * self.width), "Fraction Recovered": lambda m: self.count_recovered(m, self.height * self.width), "Fraction Dead": lambda m: self.count_dead(m, self.height * self.width), } return mod_rep @staticmethod def count_infected(model, grid_size): """ Helper method to count INFECTED cells in the model. """ list_state = [ a for a in model.schedule.agents if (a.state == a.INFECTED or a.state == a.QUARANTINED) ] return len(list_state) / grid_size @staticmethod def count_recovered(model, grid_size): """ Helper method to count RECOVERED cells in the model. """ list_state = [ a for a in model.schedule.agents if (a.state == a.RECOVERED or a.state == a.DEAD) ] return len(list_state) / grid_size @staticmethod def count_quarantined(model, grid_size): """ Helper method to count QUARANTINED cells in the model. """ list_state = [ a for a in model.schedule.agents if a.state == a.QUARANTINED ] return len(list_state) / grid_size @staticmethod def count_dead(model, grid_size): ''' Helper method to count DEAD cells in the model. ''' list_state = [a for a in model.schedule.agents if a.state == a.DEAD] return len(list_state) / grid_size
class EpiDyn(Model): ''' Represents the 2-dimensional model for epidemic dynamics ''' schedule_types = { "Random": RandomActivation, "Simultaneous": SimultaneousActivation } def __init__(self, height=100, width=100, dummy="", schedule_type="Simultaneous", startblock=1, density=0.1, p_infect=0.25, p_death=0.0, spatial=1, groupsize=4, quarantine_delay=7, neighbourdic={}, groupswitch=True, switchperx=2): ''' Create the CA field with (height, width) cells. ''' #setting an explicit seed allows you to reproduce interesting runs #self.random.seed(30) # Set up the grid and schedule. self.schedule_type = schedule_type self.schedule = self.schedule_types[self.schedule_type](self) self.neighbourdic = neighbourdic self.quarantine_delay = quarantine_delay self.groupswitch = groupswitch self.switchperx = switchperx self.counter = 0 # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) self.datacollector = DataCollector({ "Infectious": lambda m: self.count_infectious(m, width * height), "Removed": lambda m: self.count_removed(m, width * height), "Exposed": lambda m: self.count_removed(m, width * height) }) # Place a cell at each location, with default SENSTIVE, # and some (a 2x2 block) initialized to INFECTIOUS for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self, spatial, unique_id=int(0.5 * (x + y) * (x + y + 1) + y)) cell.state = cell.SENSITIVE cell.p_infect = p_infect cell.p_death = p_death cell.groupsize = groupsize if startblock: if ((x == height / 2 or x == height / 2 + 1) and (y == height / 2 or y == height / 2 + 1)): cell.state = cell.INFECTIOUS elif self.random.random() < density: cell.state = cell.INFECTIOUS self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.measure_CA = [] self.running = True self.datacollector.collect(self) def step(self): ''' Have the scheduler advance each cell by one step ''' #Need this seperately so the Reset button works fo no group switches if self.counter == 0: self.neighbourdic.clear() if (self.counter - self.quarantine_delay) % self.switchperx == 0: if self.groupswitch == 1: self.neighbourdic.clear() self.measure_CA = [a for a in self.schedule.agents] self.schedule.step() # collect data self.datacollector.collect(self) self.counter = self.counter + 1 @staticmethod def count_infectious(model, grid_size): """ Helper method to count cells in a given state in a given model. """ list_state = [ a for a in model.schedule.agents if a.state == a.INFECTIOUS ] return len(list_state) / grid_size @staticmethod def count_removed(model, grid_size): """ Helper method to count cells in a given state in a given model. """ list_state = [a for a in model.schedule.agents if a.state == a.REMOVED] return len(list_state) / grid_size @staticmethod def count_exposed(model, grid_size): """ Helper method to count cells in a given state in a given model. """ list_state = [ a for a in model.schedule.agents if a.state == a.NEIGHBOUR ] return len(list_state) / grid_size
class OilSpread(Model): def __init__(self, height=20, width=20, initial_macchie=1, qnt=10, qnt_prop=50, initial_barche=1, power_boat=3, initial_land=20): self.height = height self.width = width self.initial_macchie = initial_macchie self.qnt = qnt self.qnt_prop = qnt_prop self.initial_barche = initial_barche self.power_boat = power_boat self.initial_land = initial_land self.schedule = RandomActivation(self) self.grid = Grid(width, height, torus=True) self.datacollector = DataCollector({ "Oil": lambda m: m.schedule.get_agent_count() - self.initial_barche - self .initial_land - self.height #"Cane": lambda m: self.count_type(self, 0) }) # Create terra for i in range(self.initial_land): x = 0 y = i terra = Land((x, y), self, 0) self.grid.place_agent(terra, (x, y)) self.schedule.add(terra) # Create terra for i in range(20): x = self.width - 1 y = i limite = Bound((x, y), self) self.grid.place_agent(limite, (x, y)) self.schedule.add(limite) # Create macchie di petrolio for i in range(self.initial_macchie): x = self.random.randrange(self.width) y = self.random.randrange(self.height) if (x == 0): x += 1 if (y == self.width): y -= 2 macchia = Oil((x, y), self, qnt, qnt_prop) self.grid.place_agent(macchia, (x, y)) self.schedule.add(macchia) # Create barchette pulisci mondo for i in range(self.initial_barche): x = self.random.randrange(self.width) y = self.random.randrange(self.height) if (x == 0): x += 1 if (y == self.width): y -= 2 barca = Boat((x, y), self, power_boat) self.grid.place_agent(barca, (x, y)) self.schedule.add(barca) self.running = True self.datacollector.collect(self) def step(self): self.schedule.step() # collect data self.datacollector.collect(self) print("il numero di macchie di petrolio sono in gioco sono " + str(self.schedule.get_agent_count() - self.initial_barche - self.initial_land - self.height)) if self.schedule.get_agent_count( ) == self.initial_barche + self.initial_land + self.height: self.running = False
class TestBaseGrid(unittest.TestCase): """ Testing a non-toroidal grid. """ torus = False def setUp(self): """ Create a test non-toroidal grid and populate it with Mock Agents """ width = 3 # width of grid height = 5 # height of grid self.grid = Grid(width, height, self.torus) self.agents = [] counter = 0 for x in range(width): for y in range(height): if TEST_GRID[x][y] == 0: continue counter += 1 # Create and place the mock agent a = MockAgent(counter, None) self.agents.append(a) self.grid.place_agent(a, (x, y)) def test_agent_positions(self): """ Ensure that the agents are all placed properly. """ for agent in self.agents: x, y = agent.pos assert self.grid[x][y] == agent def test_cell_agent_reporting(self): """ Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact. """ for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents([(x, y)]) def test_listfree_cell_agent_reporting(self): """ Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. """ for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents((x, y)) def test_iter_cell_agent_reporting(self): """ Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact. """ for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents([(x, y)]) def test_listfree_iter_cell_agent_reporting(self): """ Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. """ for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents((x, y)) def test_neighbors(self): """ Test the base neighborhood methods on the non-toroid. """ neighborhood = self.grid.get_neighborhood((1, 1), moore=True) assert len(neighborhood) == 8 neighborhood = self.grid.get_neighborhood((1, 4), moore=False) assert len(neighborhood) == 3 neighborhood = self.grid.get_neighborhood((1, 4), moore=True) assert len(neighborhood) == 5 neighborhood = self.grid.get_neighborhood((0, 0), moore=False) assert len(neighborhood) == 2 neighbors = self.grid.get_neighbors((4, 1), moore=False) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((4, 1), moore=True) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((1, 1), moore=False, include_center=True) assert len(neighbors) == 3 neighbors = self.grid.get_neighbors((1, 3), moore=False, radius=2) assert len(neighbors) == 2 def test_coord_iter(self): ci = self.grid.coord_iter() # no agent in first space first = next(ci) assert first[0] is None assert first[1] == 0 assert first[2] == 0 # first agent in the second space second = next(ci) assert second[0].unique_id == 1 assert second[0].pos == (0, 1) assert second[1] == 0 assert second[2] == 1 def test_agent_move(self): # get the agent at [0, 1] agent = self.agents[0] self.grid.move_agent(agent, (1, 1)) assert agent.pos == (1, 1) # move it off the torus and check for the exception if not self.torus: with self.assertRaises(Exception): self.grid.move_agent(agent, [-1, 1]) with self.assertRaises(Exception): self.grid.move_agent(agent, [1, self.grid.height + 1]) else: self.grid.move_agent(agent, [-1, 1]) assert agent.pos == (self.grid.width - 1, 1) self.grid.move_agent(agent, [1, self.grid.height + 1]) assert agent.pos == (1, 1) def test_agent_remove(self): agent = self.agents[0] x, y = agent.pos self.grid.remove_agent(agent) assert agent.pos is None assert self.grid.grid[x][y] is None
class SMfgModel(Model): def __init__(self, height=model_height, width=model_width, no_nodes=no_nodes): # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the nodes # computing their next state and actions simultaneously. # This needs to be done because each node's next state # depends on the current state of all its neighbors # -- before they've changed. self.clock = 0 self.last_step = LAST_STEP self.schedule = SimultaneousActivation(self) self.order_schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Create an order manager order_manager = OrderManager(1,self) self.order_schedule.add(order_manager) for _ in range(no_nodes): pos = self.grid.find_empty() node = Node(pos,self) self.grid.place_agent(node,pos) self.schedule.add(node) self.platform_overall_capacity = a.platform_capacity(self) self.datacollector = DataCollector( model_reporters={ "Platform Overall Capacity": a.getPlatformOverallCapacity, "Platform Current Capacity": a.platform_capacity, "Utilization Rate": a.getPlatformUtilizationRate, "Service Orders": a.getCurrentServiceOrder, "Service Capacity Request": a.getCurrentServiceRequests, "Service Queued": a.getCurrentServiceQueued, "Capacity Queued": a.getCurrentCapacityQueued, "Running Services": a.getCurrentServiceRunning, "Running Capacity": a.getCurrentRunningCapacity, "Completed Services": a.getCurrentCompletedServices, "Completed Capacity": a.getCurrentCompletedCapacity, "Rejected Services": a.getCurrentRejectedServices, "Rejected Capacity": a.getCurrentRejectedCapacity }, agent_reporters={ 'ID': 'id', 'Location': 'pos', 'Full Capacity': 'initial_capacity', 'Current Capacity': 'capacity', 'Balance': a.getNodeCurrentBalance, 'Revenue': a.getNodeCurrentRevenue, 'Fixed Costs': a.getNodeCurrentFixedCosts, 'Variable Costs': a.getNodeCurrentVariableCosts, 'Capital Investment': a.getNodeCapitalInvestment, 'Processed Quantities': a.getNodeCapitalProcessedQuantitites, 'Current Service Requests': a.getNodeCurrentServiceRequests, 'Current Service Waiting': a.getNodeCurrentServiceWaiting, 'Tasks queue': a.getNodeTasksQueue, 'Running Tasks': a.getNodeRunningTasks, 'Completed Tasks': a.getNodeCompletedTasks, }) print("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::") print(f"Created a platform with capacity: {self.platform_overall_capacity}") self.running = True def step(self): ''' Have the scheduler advance each node by one step ''' self.order_schedule.step() self.schedule.step() self.datacollector.collect(self) utilization_rate,overall_capacity = a.platform_utilization_rate(self) analytics = a.service_request_analysis(self) print(f"[{self.clock}]: Platform Current Capacity: {a.platform_capacity(self)}|{overall_capacity} - ({utilization_rate}) % utilization rate") print(f"[{self.clock}]: Current Service Order: {analytics['service_requests_len']} | Current Service Capacity Request: {analytics['services_capacity_request']}") print(f"[{self.clock}]: Current Service Queue: {analytics['service_queued_requests_len']} | Current Service Queued Capacity Request: {analytics['services_queued_request']}") print(f"[{self.clock}]: Running Services: {analytics['services_running_len']} | Running Capacity: {analytics['services_running_capacity']}") print(f"[{self.clock}]: Completed Services: {analytics['services_completed_len']} | Completed Capacity: {analytics['services_capacity_completed']}") print(f"[{self.clock}]: Rejected Services: {analytics['services_rejected_len']} | Rejected Capacity: {analytics['services_capacity_rejected']}") print("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::") self.clock += 1 '''
class ConwaysGameOfLife(Model): """ Represents the 2-dimensional array of cells in Conway's Game of Life. """ def __init__(self, data, height=10, width=10, part="Part 1"): """ Create a new playing area of (height, width) cells. """ # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbors -- before they've changed. self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=False) self.dc = DataCollector({ "Empty": lambda m: self.count_type(m, Cell.DEAD), "Occupied": lambda m: self.count_type(m, Cell.ALIVE), }) self.numalive = 0 # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): if data[(len(data) - 1) - y][x] == ".": state = Cell.FLOOR else: state = Cell.DEAD cell = Cell((x, y), self, state, part) self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.running = True self.dc.collect(self) def step(self): """ Have the scheduler advance each cell by one step """ print(self.numalive) prev = self.numalive self.schedule.step() self.schedule.step() self.dc.collect(self) self.numalive = self.count_type(self, Cell.ALIVE) if prev == self.numalive: self.running = False @staticmethod def count_type(model, condition): """ Helper method to count trees in a given condition in a given model. """ count = 0 for spot in model.schedule.agents: if spot.state == condition: count += 1 return count
class BZReactionModel(Model): def __init__(self, width=50, height=50, k_full=3, k_active=3, full_value=200, g=28): # scheduler self.schedule = RandomActivation(self) # grid: instance of Grid with specified width, height and torus=False self.grid = Grid(width=width, height=height, torus=False) ### TO BE DONE # Model parameters # Full value: maximum value can be reached by a cell self.full_value = None # k_full: how many neighbors with full state is needed for changing state of an inactive cell self.k_full = None # k_active: how many neighbors with active state is needed for changing state of an inactive cell self.k_active = None # g: accelerates activation of a cell, added to the change of state for an active cell self.g = None ### TO BE DONE # running: needed for interactive visualization self.running = True # Create molecules and place them in a grid cell # Looping through all rows of the grid for x in range(height): # Looping through all columns of the grid for y in range(width): ### TO BE DONE # Instantiate molecule molecule = MoleculeCell(pos=None, model=None) # Add molecule to the scheduler pass # Place molecule in the grid self.grid.place_agent(pos=None, agent=molecule) ### TO BE DONE # data collector for plotting self.data_collection = DataCollector( # collect number of inactive and full molecules at each step model_reporters={ "Inactives": count_inactive, "Fulls": count_full }, agent_reporters={"State": "state"}) def step(self): # Collect data self.data_collection.collect(self) # Execute step of each molecules self.schedule.step() # Update state of molecules by the calculated new states # Looping through all molecules ### TO BE DONE molecules = None for molecule in molecules: # Set new state to state pass
class ColorPatches(Model): ''' represents a 2D lattice where agents live ''' def __init__(self, width=20, height=20): ''' Create a 2D lattice with strict borders where agents live The agents next state is first determined before updating the grid ''' self._grid = Grid(width, height, torus=False) self._schedule = SimultaneousActivation(self) # self._grid.coord_iter() # --> should really not return content + col + row # -->but only col & row # for (contents, col, row) in self._grid.coord_iter(): # replaced content with _ to appease linter for (_, row, col) in self._grid.coord_iter(): cell = ColorCell((row, col), self, ColorCell.OPINIONS[random.randrange(0, 16)]) self._grid.place_agent(cell, (row, col)) self._schedule.add(cell) self.running = True def step(self): ''' Advance the model one step. ''' self._schedule.step() # the following is a temporary fix for the framework classes accessing # model attributes directly # I don't think it should # --> it imposes upon the model builder to use the attributes names that # the framework expects. # # Traceback included in docstrings @property def grid(self): """ /mesa/visualization/modules/CanvasGridVisualization.py is directly accessing Model.grid 76 def render(self, model): 77 grid_state = defaultdict(list) ---> 78 for y in range(model.grid.height): 79 for x in range(model.grid.width): 80 cell_objects = model.grid.get_cell_list_contents([(x, y)]) AttributeError: 'ColorPatches' object has no attribute 'grid' """ return self._grid @property def schedule(self): """ mesa_ABM/examples_ABM/color_patches/mesa/visualization/ModularVisualization.py", line 278, in run_model while self.model.schedule.steps < self.max_steps and self.model.running: AttributeError: 'NoneType' object has no attribute 'steps' """ return self._schedule
class Epidemic(Model): ''' Represents the 2-dimensional array of cells in Conway's Game of Life. ''' def __init__(self, height, width, map): ''' Create a new playing area of (height, width) cells and map. ''' # global time self.globaltime = 0 # Greyscale image self.map = map # Set up the grid and schedule. # Use SimultaneousActivation which simulates all the cells # computing their next state simultaneously. This needs to # be done because each cell's next state depends on the current # state of all its neighbours -- before they've changed. self.schedule = SimultaneousActivation(self) # Use a simple grid, where edges wrap around. self.grid = Grid(height, width, torus=True) # Place a cell at each location, with some initialized to # ALIVE and some to DEAD. for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self) # Creating a sea in the middle of the grid if self.map[x, y] == 1.0: if y > 37.5 and y < 55 and x > 37.5 and x < 62.5: cell.state = cell.ALIVE cell.starttime = 0 cell.endtime = 5000 cell.mobility = cell.IMMOBILE cell.infection = random() cell.infectious = True cell.mutability = cell.IMMUTABLE # Ardipithecus K if x > 77 and x < 81 and y > 60 and y < 64: cell.state = cell.DEAD cell.mobility = cell.MOBILE cell.infection = 0. cell.starttime = 0 cell.endtime = 60 cell.infectious = True if x > 50 and x < 54 and y > 67 and y < 71: # if y > 60 and y < 65 and x > 65 and x < 70: cell.state = cell.DEAD cell.mobility = cell.MOBILE cell.infection = 0. cell.starttime = 1950 cell.endtime = 2050 cell.infectious = True if x > 71 and x < 75 and y > 52 and y < 56: # if y > 60 and y < 65 and x > 65 and x < 70: cell.state = cell.DEAD cell.starttime = 2050 cell.endtime = 2150 cell.mobility = cell.MOBILE cell.infection = 0. cell.infectious = True else: cell.mobility = cell.IMMOBILE cell.activity = cell.INACTIVE self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.running = True self.datacollector = DataCollector( model_reporters={"Infection": compute_infection}) def step(self): ''' Have the scheduler advance each cell by one step ''' # global time self.globaltime += 1 if self.globaltime == 88: for (contents, x, y) in self.grid.coord_iter(): cell = Cell((x, y), self) # Ardipithecus R if x > 77 and x < 81 and y > 60 and y < 64: cell.state = cell.DEAD cell.mobility = cell.MOBILE cell.infection = 0. cell.starttime = 90 #1150 cell.endtime = 150 #1250 cell.infectious = True cell.globaltime = self.globaltime self.grid.place_agent(cell, (x, y)) self.schedule.add(cell) self.datacollector.collect(self) self.schedule.step()
class TestBaseGrid(unittest.TestCase): ''' Testing a non-toroidal grid. ''' torus = False def setUp(self): ''' Create a test non-toroidal grid and populate it with Mock Agents ''' width = 3 # width of grid height = 5 # height of grid self.grid = Grid(width, height, self.torus) self.agents = [] counter = 0 for x in range(width): for y in range(height): if TEST_GRID[x][y] == 0: continue counter += 1 # Create and place the mock agent a = MockAgent(counter, None) self.agents.append(a) self.grid.place_agent(a, (x, y)) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for agent in self.agents: x, y = agent.pos assert self.grid[x][y] == agent def test_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents([(x, y)]) def test_listfree_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents((x, y)) def test_iter_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents([(x, y)]) def test_listfree_iter_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents((x, y)) def test_neighbors(self): ''' Test the base neighborhood methods on the non-toroid. ''' neighborhood = self.grid.get_neighborhood((1, 1), moore=True) assert len(neighborhood) == 8 neighborhood = self.grid.get_neighborhood((1, 4), moore=False) assert len(neighborhood) == 3 neighborhood = self.grid.get_neighborhood((1, 4), moore=True) assert len(neighborhood) == 5 neighborhood = self.grid.get_neighborhood((0, 0), moore=False) assert len(neighborhood) == 2 neighbors = self.grid.get_neighbors((4, 1), moore=False) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((4, 1), moore=True) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((1, 1), moore=False, include_center=True) assert len(neighbors) == 3 neighbors = self.grid.get_neighbors((1, 3), moore=False, radius=2) assert len(neighbors) == 2 def test_coord_iter(self): ci = self.grid.coord_iter() # no agent in first space first = next(ci) assert first[0] is None assert first[1] == 0 assert first[2] == 0 # first agent in the second space second = next(ci) assert second[0].unique_id == 1 assert second[0].pos == (0, 1) assert second[1] == 0 assert second[2] == 1 def test_agent_move(self): # get the agent at [0, 1] agent = self.agents[0] self.grid.move_agent(agent, (1, 1)) assert agent.pos == (1, 1) # move it off the torus and check for the exception if not self.torus: with self.assertRaises(Exception): self.grid.move_agent(agent, [-1, 1]) with self.assertRaises(Exception): self.grid.move_agent(agent, [1, self.grid.height + 1]) else: self.grid.move_agent(agent, [-1, 1]) assert agent.pos == (self.grid.width - 1, 1) self.grid.move_agent(agent, [1, self.grid.height + 1]) assert agent.pos == (1, 1) def test_agent_remove(self): agent = self.agents[0] x, y = agent.pos self.grid.remove_agent(agent) assert agent.pos is None assert self.grid.grid[x][y] is None
class TestBaseGrid(unittest.TestCase): ''' Testing a non-toroidal grid. ''' torus = False def setUp(self): ''' Create a test non-toroidal grid and populate it with Mock Agents ''' self.grid = Grid(3, 5, self.torus) self.agents = [] counter = 0 for y in range(3): for x in range(5): if TEST_GRID[y][x] == 0: continue counter += 1 # Create and place the mock agent a = MockAgent(counter, None) self.agents.append(a) self.grid.place_agent(a, (x, y)) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for agent in self.agents: x, y = agent.pos assert self.grid[y][x] == agent def test_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents([(x, y)]) def test_listfree_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents((x, y)) def test_iter_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents([(x, y)]) def test_listfree_iter_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents((x, y)) def test_neighbors(self): ''' Test the base neighborhood methods on the non-toroid. ''' neighborhood = self.grid.get_neighborhood((1, 1), moore=True) assert len(neighborhood) == 8 neighborhood = self.grid.get_neighborhood((4, 1), moore=True) assert len(neighborhood) == 5 neighborhood = self.grid.get_neighborhood((0, 0), moore=False) assert len(neighborhood) == 2 neighbors = self.grid.get_neighbors((4, 1), moore=False) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((4, 1), moore=True) assert len(neighbors) == 2 neighbors = self.grid.get_neighbors((1, 1), moore=False, include_center=True) assert len(neighbors) == 3 neighbors = self.grid.get_neighbors((3, 1), moore=False, radius=2) assert len(neighbors) == 4 def test_coord_iter(self): ci = self.grid.coord_iter() # no agent in first space first = next(ci) assert first[0] is None assert first[1] == 0 assert first[2] == 0 # first agent in the second space second = next(ci) assert second[0].unique_id == 1 assert second[0].pos == (1, 0) assert second[1] == 1 assert second[2] == 0
class ForestFireModel(Model): def __init__(self, L, p, direction, strength): """ :param L: size of model's grid :param p: probability of tree's occurrence in a cell :param direction: tuple (x,y) - direction of the wind: (0,0) - no wind, (0,1) - North, (0,-1) - South, (1,0) - East, (-1,0) - West, (1,1) - North-East, (-1,1) - North-West, (1,-1) - South-East, (-1,-1) - South-West. :param strength: int [0,1] - let's assume 0 - 0 km/h, 1 - 100km/h At the beginning we assume that every tree has probability of becoming a burning cell equal to 0.5 (if has burning neighbour). If considered non-burning tree has a burning neighbour tree and wind is blowing from the same direction as the burning neighbour, then probability of setting considered tree to fire is raising by half of the wind strength (not speed). On the other side, if source of fire is on the opposite site of source of wind then probability of setting considered tree to fire is lowered by half of wind strength. Otherwise, probability of setting tree to fire is not changed (trees occurring diagonal and perpendicular to wind direction are not affected by wind). """ super().__init__() self.grid = Grid(L, L, False) self.schedule = SimultaneousActivation(self) self.running = True self.p = p self.direction = direction self.strength = strength for i in range(L): for j in range(L): if self.random.random() <= self.p: if i == L - 1: tree = TreeAgent((i, j), self, "burning") else: tree = TreeAgent((i, j), self, "occupied") self.schedule.add(tree) self.grid.place_agent(tree, (i, j)) self.datacollector = DataCollector(model_reporters={ "p*": compute_p, "Cluster": compute_cluster }) def step(self): self.schedule.step() if not self.exists_status("burning"): self.datacollector.collect(self) self.running = False def exists_status( self, status ): # function checking if there is any tree which has given status for tree in self.schedule.agents: if tree.status == status: return True
class TestBaseGrid(unittest.TestCase): ''' Testing a non-toroidal grid. ''' torus = False def setUp(self): ''' Create a test non-toroidal grid and populate it with Mock Agents ''' width = 3 # width of grid height = 5 # height of grid self.grid = Grid(width, height, self.torus) self.agents = [] counter = 0 for x in range(width): for y in range(height): if TEST_GRID[x][y] == 0: continue counter += 1 # Create and place the mock agent a = MockAgent(counter, None) self.agents.append(a) self.grid.place_agent(a, (x, y)) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for agent in self.agents: x, y = agent.pos assert self.grid[x][y] == agent def test_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents([(x, y)]) def test_listfree_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, get_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.get_cell_list_contents((x, y)) def test_iter_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents([(x, y)]) def test_listfree_iter_cell_agent_reporting(self): ''' Ensure that if an agent is in a cell, iter_cell_list_contents accurately reports that fact, even when single position is not wrapped in a list. ''' for agent in self.agents: x, y = agent.pos assert agent in self.grid.iter_cell_list_contents((x, y)) def test_neighbors(self): ''' Test the base neighborhood methods on the non-toroid. ''' neighborhood = self.grid.get_neighborhood((1, 1), moore=True) assert len(neighborhood) == 8 neighborhood = self.grid.get_neighborhood((1, 4), moore=False) assert len(neighborhood) == 3 neighborhood = self.grid.get_neighborhood((1, 4), moore=True) assert len(neighborhood) == 5 neighborhood = self.grid.get_neighborhood((0, 0), moore=False) assert len(neighborhood) == 2 neighbors = self.grid.get_neighbors((4, 1), moore=False) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((4, 1), moore=True) assert len(neighbors) == 0 neighbors = self.grid.get_neighbors((1, 1), moore=False, include_center=True) assert len(neighbors) == 3 neighbors = self.grid.get_neighbors((1, 3), moore=False, radius=2) assert len(neighbors) == 2 def test_coord_iter(self): ci = self.grid.coord_iter() # no agent in first space first = next(ci) assert first[0] is None assert first[1] == 0 assert first[2] == 0 # first agent in the second space second = next(ci) assert second[0].unique_id == 1 assert second[0].pos == (0, 1) assert second[1] == 0 assert second[2] == 1
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.range = 5 self.neighborhood_deltas = self.initialize_neighborhood_deltas() 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 = Grid(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): while True: x = self.random.randrange(1, self.grid.width - 1) y = self.random.randrange(1, self.grid.height - 1) pos = (x, y) if not pos in taken_pos: break new_human = Pedestrian(i, self, pos, self.exponent, seed=i) self.schedule.add(new_human) self.grid.place_agent(new_human, pos) taken_pos.append(pos) self.data_collector = DataCollector() self.running = True self.data_collector.collect(self) def initialize_neighborhood_deltas(self): neighborhood_deltas = [] for x in range(-self.range, self.range + 1): for y in range(-self.range, self.range + 1): if x**2 + y**2 <= self.range**2: neighborhood_deltas.append((x, y)) return neighborhood_deltas 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 get_neighbor_ids(self, position, id): x = position[0] y = position[1] neighbors = [] for deltas in self.neighborhood_deltas: dx = deltas[0] dy = deltas[1] nx, ny = x + dx, y + dy if (not (0 <= nx < self.width) or not (0 <= ny < self.height)): continue content = self.grid[nx][ny] if isinstance(content, Pedestrian) and content.unique_id != id: #neighbors += [content.unique_id] neighbors += [content.unique_id] return neighbors 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 ''' #print('ADJACENCY UPDATE') agents = self.schedule.agents for i, agent in enumerate(agents): neighbor_ids = self.get_neighbor_ids(agent.pos, agent.unique_id) for neighbor_id in neighbor_ids: if neighbor_id > agent.unique_id: self.adjacency_matrix[agent.unique_id, neighbor_id] += 1 def step(self): self.schedule.step() self.update_adjecency_matrix() #self.current_step_contacts=[] #self.data_collector.collect(self) def run(self, steps): for i in range(steps): 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)