class ForestFire(Model): ''' Simple Forest Fire model. ''' def __init__(self, height, width, density): ''' 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. ''' # Initialize model parameters self.height = height self.width = width self.density = density # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.datacollector = DataCollector( {"Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out")}) # Place a tree in each cell with Prob = density for (contents, x, y) in self.grid.coord_iter(): if random.random() < self.density: # Create a tree new_tree = TreeCell((x, y)) # 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) self.running = True def step(self): ''' Advance the model by one step. ''' self.schedule.step() self.datacollector.collect(self) # Halt if no more fire if self.count_type(self, "On Fire") == 0: self.running = False @staticmethod def count_type(model, tree_condition): ''' Helper method to count trees in a given condition in a given model. ''' count = 0 for tree in model.schedule.agents: if tree.condition == tree_condition: count += 1 return count
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 InspectionModel(Model): ''' Simple Restaurant Inspection model. ''' def __init__(self, height, width, density): ''' Create a new restaurant inspection model. Args: height, width: The size of the grid to model density: What fraction of grid cells have a restaurant in them. ''' # Initialize model parameters self.height = height self.width = width self.density = density # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.datacollector = DataCollector( {"Good": lambda m: self.count_type(m, "Good"), "Bad": lambda m: self.count_type(m, "Bad")}) # Place a restaurant in each cell with Prob = density for (contents, x, y) in self.grid.coord_iter(): if random.random() < self.density: # Create a restaurant new_restaurant = RestaurantCell((x, y)) self.grid._place_agent((x, y), new_restaurant) self.schedule.add(new_restaurant) self.running = True def step(self): ''' Advance the model by one step. ''' self.schedule.step() self.datacollector.collect(self) @staticmethod def count_type(model, restaurant_hygiene): ''' Helper method to count restaurants in a given condition in a given model. ''' count = 0 for restaurant in model.schedule.agents: if restaurant.hygiene == restaurant_hygiene and restaurant.rating != 'Closed': count += 1 return count
class ForestFire(Model): def __init__(self, height=100, width=100, density=0.65): self.height = height self.width = width self.density = density self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.datacollector = DataCollector({ "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out"), }) for (contents, x, y) in self.grid.coord_iter(): if self.random.random() < self.density: 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) self.running = True self.datacollector.collect(self) def step(self): self.schedule.step() self.datacollector.collect(self) # Halt if no more fire if self.count_type(self, "On Fire") == 0: self.running = False @staticmethod def count_type(model, tree_condition): count = 0 for tree in model.schedule.agents: if tree.condition == tree_condition: count += 1 return count
class ForestFire(Model): """ Simple Forest Fire model. """ def __init__(self, width=100, height=100, density=0.65, wind=0.0): """ Create a new forest fire model. Args: width, height: The size of the grid to model density: What fraction of grid cells have a tree in them. """ # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(width, height, torus=False) self.width = width self.height = height self.count_step = 1 # Variáveis de controle self.density = density self.wind = wind self.datacollector_cluster_fine = DataCollector({ "Number of clusters (Fine)": lambda m: self.count_clusters(m, self.width, self.height, "Fine"), }) self.datacollector_cluster_fireputout = DataCollector({ "Number of clusters (Fire Put Out)": lambda m: self.count_clusters(m, self.width, self.height, "Fire Put Out"), }) self.datacollector = DataCollector({ "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out"), "Fire Put Out": lambda m: self.count_type(m, "Fire Put Out"), }) # 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, wind) # 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) self.running = True self.datacollector_cluster_fine.collect(self) self.datacollector_cluster_fireputout.collect(self) self.datacollector.collect(self) def step(self): """ Advance the model by one step. """ self.schedule.step() # collect data self.datacollector.collect(self) self.datacollector_cluster_fine.collect(self) self.datacollector_cluster_fireputout.collect(self) self.count_step = self.count_step + 1 # Halt if no more fire if self.count_type(self, "On Fire") == 0: self.running = False # Conta a quantidade de árvores em determinada condição, é uma variável dependente @staticmethod def count_type(model, tree_condition): """ Helper method to count trees in a given condition in a given model. """ count = 0 for tree in model.schedule.agents: if tree.condition == tree_condition: count += 1 return count # Conta a quantidade de clusters de determinada condição de árvore, é uma variável dependente @staticmethod def count_clusters(model, width, height, condition): grid_zeros = np.zeros(shape=(width, height), dtype=int) for x in range(width): for y in range(height): if model.grid[x, y] and model.grid[x, y].condition == condition: grid_zeros[x, y] = 1 vizinhos = np.ones(shape=(3, 3), dtype=int) _, num = measurements.label(input=grid_zeros, structure=vizinhos) return num @staticmethod def total_steps(model): return model.count_step def batch_run(self): fix_params = {"width": 100, "height": 100} variable_params = { # Variáveis de controle "density": [0.65, 0.5], "wind": [43.0, 48.0], } experiments_per_parameter_configuration = 150 max_steps_per_simulation = 100 batch_run = BatchRunner( ForestFire, variable_params, fix_params, iterations=experiments_per_parameter_configuration, max_steps=max_steps_per_simulation, model_reporters={ # Variáveis dependentes "Number of clusters (Fine)": lambda m: self.count_clusters(m, self.width, self.height, "Fine"), "Number of clusters (Fire Put Out)": lambda m: self.count_clusters(m, self.width, self.height, "Fire Put Out"), "Total steps of the fire forest": lambda m: self.total_steps(m), "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out"), "Fire Put Out": lambda m: self.count_type(m, "Fire Put Out"), }, agent_reporters={ #"Condition of tree": lambda x: x.condition }) batch_run.run_all() run_model_data = batch_run.get_model_vars_dataframe() #run_agent_data = batch_run.get_agent_vars_dataframe() now = str(datetime.now()).replace(':', '-') file_name_sufix = ("_iter_" + str(experiments_per_parameter_configuration) + "_steps_" + str(max_steps_per_simulation) + "_" + now) run_model_data.to_csv("model_data" + file_name_sufix + ".csv")
class ForestFire(Model): """ Simple Forest Fire model. """ def __init__(self, height=100, width=100, density=0.65, server=True, num_steps=1000): """ 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. """ # Initialize model parameters self.height = height self.width = width self.density = density self.server = server # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.num_steps = num_steps self.datacollector = DataCollector({ "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out") }) # Place a tree in each cell with Prob = density for (contents, x, y) in self.grid.coord_iter(): if self.random.random() < self.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) self.running = True self.datacollector.collect(self) def step(self): """ Advance the model by one step. """ self.schedule.step() # collect data self.datacollector.collect(self) # Halt if no more fire if self.count_type(self, "On Fire") == 0: self.running = False @staticmethod def count_type(model, tree_condition): """ Helper method to count trees in a given condition in a given model. """ count = 0 for tree in model.schedule.agents: if tree.condition == tree_condition: count += 1 return count def run_model(self, n=None, export_agent_data=False, export_model_data=False): if self.server == False: if not n: for _ in range(self.num_steps): self.step() if export_agent_data: return self.datacollector.get_agent_vars_dataframe() elif export_model_data: return self.datacollector.get_model_vars_dataframe() elif export_model_data and export_agent_data: return self.datacollector.get_model_vars_dataframe, self.datacollector.get_agent_vars_dataframe else: self.num_steps = n for _ in range(self.num_steps): self.step() # if export_agent_data: # return self.datacollector.get_agent_vars_dataframe() # elif export_model_data: # return self.datacollector.get_model_vars_dataframe() # elif export_model_data == True and export_agent_data == True: # return self.datacollector.get_model_vars_dataframe, self.datacollector.get_agent_vars_dataframe return self else: from .server import server server.launch()
class ForestFire(Model): """ Simple Forest Fire model. """ def __init__(self, height, width, density): """ 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. """ # Initialize model parameters self.height = height self.width = width self.density = density # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=True) self.datacollector = DataCollector({ "Unelectrified": lambda m: self.count_type(m, "Unelectrified"), "Transition": lambda m: self.count_type(m, "Transition"), "Electrified": lambda m: self.count_type(m, "Electrified") }) # Place a tree in each cell with Prob = density for (contents, x, y) in self.grid.coord_iter(): if random.random() < self.density: # Create a tree x = random.randrange(self.width) y = random.randrange(self.height) new_tree = TreeCell((x, y), self) # Set all trees in the first column on fire. # if x == 4: # new_tree.condition = "Transition" # self.grid._place_agent((x, y), new_tree) # self.schedule.add(new_tree) if (x < 40 & y < 40): new_tree.condition = "Transition" self.grid._place_agent((x, y), new_tree) self.schedule.add(new_tree) self.running = True def step(self): """ Advance the model by one step. """ self.schedule.step() self.datacollector.collect(self) # Halt if no more fire if self.count_type(self, "Transition") == 0: self.running = False @staticmethod def count_type(model, tree_condition): """ Helper method to count trees in a given condition in a given model. """ count = 0 for tree in model.schedule.agents: if tree.condition == tree_condition: count += 1 return count
class ForestFire(Model): ''' Simple Forest Fire Model. ''' def __init__(self, height=100, width=100, density=0.65): ''' Create a new forest fire model. Args: - height: the grid's height - width: the grid's width - density: what fraction of grid cells have a tree in them (initially) ''' ''' Set up model ojects RandomActivation is a schedular which actives each agent once per step, in random order, with the order reshuffled every step. This is equivalent to the NetLogo 'ask agent…' and is generally the default behavior for an ABM ''' self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.datacollector = DataCollector({ # lambda function, it is like: lambda x, y: x ** y 'Fine': lambda m: self.count_type(m, 'Fine'), 'On Fire': lambda m: self.count_type(m, 'On Fire'), 'Burned Out': lambda m: self.count_type(m, 'Burned Out'), }) # Place a tree in each cell with Prob = density (here is 0.65) # coord_iter: returns coordinates as well as cell contents. 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' # place_agent: positions an agent on the grid, and set its pos variable. self.grid._place_agent((x, y), new_tree) # Add an agent object to the schedule. self.schedule.add(new_tree) self.running = True self.datacollector.collect(self) def step(self): ''' Advance the model by one step. ''' self.schedule.step() # Collect data self.datacollector.collect(self) # Halt if no more fire if self.count_type(self, 'On Fire') == 0: self.running = False @staticmethod # I don’t know this method def count_type(model, tree_condition): ''' Helper method to count trees in a given condition in a given model. ''' # Bear in mind this kind method # initial score is 0, which is very helpful. count = 0 ''' The default DataCollector has sevaral assumptions: - The model has a schedule object called 'schedule' - The schedule has an agent list called 'agents' - For collecting agent-level variables, agents must have a unique_id ''' for tree in model.schedule.agents: if tree.condition == tree_condition: count += 1 return count
class ForestFire(Model): def __init__(self, height, width, density, esquinas): super().__init__() # Parámetros para inicializar modelo self.height = height self.width = width self.density = density self.esquinas = esquinas self.initialTrees = 0 self.burnedTrees = 0 self.percen = 0 # Creación del planificador y del grid self.schedule = RandomActivation(self) self.grid = Grid(width, height, torus=False) # Recolector de datos para gráfica self.datacollector = DataCollector({ "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out") }) # Creación de los agentes del modelo y configuración de parámetros self.setup() # Ejecución en navegador despues de crear self.running = True def setup(self): pos = list( filter(lambda t: random.random() < self.density, self.grid.coord_iter())) list(map(lambda t: self.add_tree(t[1], t[2]), pos)) self.initialTrees = len(pos) def add_tree(self, x, y): 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): self.schedule.step() self.datacollector.collect(self) self.burnedTrees = self.count_type(self, "Burned Out") self.percen = self.burnedTrees / self.initialTrees * 100 if self.count_type(self, "On Fire") == 0: self.running = False @staticmethod def count_type(model, tree_condition): return len( list( filter(lambda t: t.condition == tree_condition, model.schedule.agents)))