From 9ba1be2bec4a4d34331f9dda9a4024e192bb5208 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 15 Oct 2024 08:56:13 +0000 Subject: [PATCH] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../epstein_civil_violence/agent.py | 28 ++++----- .../epstein_civil_violence/model.py | 19 ++---- examples/advanced/pd_grid/analysis.ipynb | 7 +-- examples/advanced/pd_grid/pd_grid/agent.py | 7 +-- examples/advanced/pd_grid/pd_grid/model.py | 3 +- .../advanced/pd_grid/pd_grid/portrayal.py | 3 +- examples/advanced/sugarscape_g1mt/app.py | 3 +- examples/advanced/sugarscape_g1mt/run.py | 3 +- .../sugarscape_g1mt/sugarscape_g1mt/model.py | 20 +++---- .../sugarscape_g1mt/resource_agents.py | 6 +- .../sugarscape_g1mt/trader_agents.py | 60 +++++-------------- .../advanced/wolf_sheep/wolf_sheep/agents.py | 7 +-- .../advanced/wolf_sheep/wolf_sheep/model.py | 10 +--- examples/basic/boid_flockers/app.py | 1 + .../boid_flockers/SimpleContinuousModule.py | 4 +- .../boid_flockers/boid_flockers/model.py | 28 +++------ examples/basic/boltzmann_wealth_model/app.py | 3 +- .../conways_game_of_life/cell.py | 12 +--- .../conways_game_of_life/model.py | 10 +--- .../conways_game_of_life/portrayal.py | 3 +- examples/basic/schelling/analysis.ipynb | 4 +- examples/basic/schelling/app.py | 7 +-- examples/basic/schelling/model.py | 19 ++---- examples/basic/schelling/run_ascii.py | 15 ++--- examples/basic/virus_on_network/app.py | 3 +- .../virus_on_network/model.py | 11 ++-- 26 files changed, 94 insertions(+), 202 deletions(-) diff --git a/examples/advanced/epstein_civil_violence/epstein_civil_violence/agent.py b/examples/advanced/epstein_civil_violence/epstein_civil_violence/agent.py index edd1d1ebabf..6e0ab6a4e80 100644 --- a/examples/advanced/epstein_civil_violence/epstein_civil_violence/agent.py +++ b/examples/advanced/epstein_civil_violence/epstein_civil_violence/agent.py @@ -5,9 +5,7 @@ class EpsteinAgent(mesa.experimental.cell_space.CellAgent): def update_neighbors(self): - """ - Look around and see who my neighbors are - """ + """Look around and see who my neighbors are""" self.neighborhood = self.cell.get_neighborhood(radius=self.vision) self.neighbors = self.neighborhood.agents @@ -15,8 +13,7 @@ def update_neighbors(self): class Citizen(EpsteinAgent): - """ - A member of the general population, may or may not be in active rebellion. + """A member of the general population, may or may not be in active rebellion. Summary of rule: If grievance - risk > threshold, rebel. Attributes: @@ -46,8 +43,8 @@ def __init__( threshold, vision, ): - """ - Create a new Citizen. + """Create a new Citizen. + Args: model: the model to which the agent belongs hardship: Agent's 'perceived hardship (i.e., physical or economic @@ -73,9 +70,7 @@ def __init__( self.arrest_probability = None def step(self): - """ - Decide whether to activate, then move if applicable. - """ + """Decide whether to activate, then move if applicable.""" if self.jail_sentence: self.jail_sentence -= 1 return # no other changes or movements if agent is in jail. @@ -92,8 +87,7 @@ def step(self): self.move_to(new_cell) def update_estimated_arrest_probability(self): - """ - Based on the ratio of cops to actives in my neighborhood, estimate the + """Based on the ratio of cops to actives in my neighborhood, estimate the p(Arrest | I go active). """ cops_in_vision = len([c for c in self.neighbors if isinstance(c, Cop)]) @@ -111,8 +105,7 @@ def update_estimated_arrest_probability(self): class Cop(EpsteinAgent): - """ - A cop for life. No defection. + """A cop for life. No defection. Summary of rule: Inspect local vision and arrest a random active agent. Attributes: @@ -123,8 +116,8 @@ class Cop(EpsteinAgent): """ def __init__(self, model, vision): - """ - Create a new Cop. + """Create a new Cop. + Args: x, y: Grid coordinates vision: number of cells in each direction (N, S, E and W) that @@ -135,8 +128,7 @@ def __init__(self, model, vision): self.vision = vision def step(self): - """ - Inspect local vision and arrest a random active agent. Move if + """Inspect local vision and arrest a random active agent. Move if applicable. """ self.update_neighbors() diff --git a/examples/advanced/epstein_civil_violence/epstein_civil_violence/model.py b/examples/advanced/epstein_civil_violence/epstein_civil_violence/model.py index 8bf06bf1540..d217b734119 100644 --- a/examples/advanced/epstein_civil_violence/epstein_civil_violence/model.py +++ b/examples/advanced/epstein_civil_violence/epstein_civil_violence/model.py @@ -4,8 +4,7 @@ class EpsteinCivilViolence(mesa.Model): - """ - Model 1 from "Modeling civil violence: An agent-based computational + """Model 1 from "Modeling civil violence: An agent-based computational approach," by Joshua Epstein. http://www.pnas.org/content/99/suppl_3/7243.full Attributes: @@ -103,9 +102,7 @@ def __init__( self.datacollector.collect(self) def step(self): - """ - Advance the model by one step and collect data. - """ + """Advance the model by one step and collect data.""" self.agents.shuffle_do("step") # collect data self.datacollector.collect(self) @@ -115,9 +112,7 @@ def step(self): @staticmethod def count_type_citizens(model, condition, exclude_jailed=True): - """ - Helper method to count agents by Quiescent/Active. - """ + """Helper method to count agents by Quiescent/Active.""" citizens = model.agents_by_type[Citizen] if exclude_jailed: @@ -133,14 +128,10 @@ def count_type_citizens(model, condition, exclude_jailed=True): @staticmethod def count_jailed(model): - """ - Helper method to count jailed agents. - """ + """Helper method to count jailed agents.""" return len([a for a in model.agents_by_type[Citizen] if a.jail_sentence > 0]) @staticmethod def count_cops(model): - """ - Helper method to count jailed agents. - """ + """Helper method to count jailed agents.""" return len(model.agents_by_type[Cop]) diff --git a/examples/advanced/pd_grid/analysis.ipynb b/examples/advanced/pd_grid/analysis.ipynb index e3f52170a1c..9810b47fc90 100644 --- a/examples/advanced/pd_grid/analysis.ipynb +++ b/examples/advanced/pd_grid/analysis.ipynb @@ -58,8 +58,7 @@ "\n", "\n", "def draw_grid(model, ax=None):\n", - " \"\"\"\n", - " Draw the current state of the grid, with Defecting agents in red\n", + " \"\"\"Draw the current state of the grid, with Defecting agents in red\n", " and Cooperating agents in blue.\n", " \"\"\"\n", " if not ax:\n", @@ -82,9 +81,7 @@ "outputs": [], "source": [ "def run_model(model):\n", - " \"\"\"\n", - " Run an experiment with a given model, and plot the results.\n", - " \"\"\"\n", + " \"\"\"Run an experiment with a given model, and plot the results.\"\"\"\n", " fig = plt.figure(figsize=(12, 8))\n", "\n", " ax1 = fig.add_subplot(231)\n", diff --git a/examples/advanced/pd_grid/pd_grid/agent.py b/examples/advanced/pd_grid/pd_grid/agent.py index 4890b74905b..b7c11b282a1 100644 --- a/examples/advanced/pd_grid/pd_grid/agent.py +++ b/examples/advanced/pd_grid/pd_grid/agent.py @@ -5,8 +5,7 @@ class PDAgent(CellAgent): """Agent member of the iterated, spatial prisoner's dilemma model.""" def __init__(self, model, starting_move=None): - """ - Create a new Prisoner's Dilemma agent. + """Create a new Prisoner's Dilemma agent. Args: model: model instance @@ -27,8 +26,8 @@ def is_cooroperating(self): def step(self): """Get the best neighbor's move, and change own move accordingly - if better than own score.""" - + if better than own score. + """ # neighbors = self.model.grid.get_neighbors(self.pos, True, include_center=True) neighbors = [*list(self.cell.neighborhood.agents), self] best_neighbor = max(neighbors, key=lambda a: a.score) diff --git a/examples/advanced/pd_grid/pd_grid/model.py b/examples/advanced/pd_grid/pd_grid/model.py index 38ef5f5b945..f29ca01e388 100644 --- a/examples/advanced/pd_grid/pd_grid/model.py +++ b/examples/advanced/pd_grid/pd_grid/model.py @@ -17,8 +17,7 @@ class PdGrid(mesa.Model): def __init__( self, width=50, height=50, activation_order="Random", payoffs=None, seed=None ): - """ - Create a new Spatial Prisoners' Dilemma Model. + """Create a new Spatial Prisoners' Dilemma Model. Args: width, height: Grid size. There will be one agent per grid cell. diff --git a/examples/advanced/pd_grid/pd_grid/portrayal.py b/examples/advanced/pd_grid/pd_grid/portrayal.py index a7df44a439f..ae5bcc9e962 100644 --- a/examples/advanced/pd_grid/pd_grid/portrayal.py +++ b/examples/advanced/pd_grid/pd_grid/portrayal.py @@ -1,6 +1,5 @@ def portrayPDAgent(agent): - """ - This function is registered with the visualization server to be called + """This function is registered with the visualization server to be called each tick to indicate how to draw the agent in its current state. :param agent: the agent in the simulation :return: the portrayal dictionary diff --git a/examples/advanced/sugarscape_g1mt/app.py b/examples/advanced/sugarscape_g1mt/app.py index 146d3d5c51f..ae09dd04a62 100644 --- a/examples/advanced/sugarscape_g1mt/app.py +++ b/examples/advanced/sugarscape_g1mt/app.py @@ -1,10 +1,11 @@ import numpy as np import solara from matplotlib.figure import Figure -from mesa.visualization import SolaraViz, make_plot_measure from sugarscape_g1mt.model import SugarscapeG1mt from sugarscape_g1mt.trader_agents import Trader +from mesa.visualization import SolaraViz, make_plot_measure + def SpaceDrawer(model): def portray(g): diff --git a/examples/advanced/sugarscape_g1mt/run.py b/examples/advanced/sugarscape_g1mt/run.py index f1056fa4b8f..1be9dffc174 100644 --- a/examples/advanced/sugarscape_g1mt/run.py +++ b/examples/advanced/sugarscape_g1mt/run.py @@ -1,12 +1,13 @@ import sys import matplotlib.pyplot as plt -import mesa import networkx as nx import pandas as pd from sugarscape_g1mt.model import SugarscapeG1mt from sugarscape_g1mt.server import server +import mesa + # Analysis def assess_results(results, single_agent): diff --git a/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/model.py b/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/model.py index d51b8bc0746..8251ba662c4 100644 --- a/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/model.py +++ b/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/model.py @@ -1,7 +1,8 @@ from pathlib import Path -import mesa import numpy as np + +import mesa from mesa.experimental.cell_space import OrthogonalVonNeumannGrid from .resource_agents import Resource @@ -10,23 +11,19 @@ # Helper Functions def flatten(list_of_lists): - """ - helper function for model datacollector for trade price + """Helper function for model datacollector for trade price collapses agent price list into one list """ return [item for sublist in list_of_lists for item in sublist] def geometric_mean(list_of_prices): - """ - find the geometric mean of a list of prices - """ + """Find the geometric mean of a list of prices""" return np.exp(np.log(list_of_prices).mean()) def get_trade(agent): - """ - For agent reporters in data collector + """For agent reporters in data collector return list of trade partners and None for other agents """ @@ -37,9 +34,7 @@ def get_trade(agent): class SugarscapeG1mt(mesa.Model): - """ - Manager class to run Sugarscape with Traders - """ + """Manager class to run Sugarscape with Traders""" def __init__( self, @@ -125,8 +120,7 @@ def __init__( ) def step(self): - """ - Unique step function that does staged activation of sugar and spice + """Unique step function that does staged activation of sugar and spice and then randomly activates traders """ # step Resource agents diff --git a/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/resource_agents.py b/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/resource_agents.py index d9f276948c1..1722a8292af 100644 --- a/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/resource_agents.py +++ b/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/resource_agents.py @@ -2,8 +2,7 @@ class Resource(FixedAgent): - """ - Resource: + """Resource: - contains an amount of sugar and spice - grows 1 amount of sugar at each turn - grows 1 amount of spice at each turn @@ -18,8 +17,7 @@ def __init__(self, model, max_sugar, max_spice, cell): self.cell = cell def step(self): - """ - Growth function, adds one unit of sugar and spice each step up to + """Growth function, adds one unit of sugar and spice each step up to max amount """ self.sugar_amount = min([self.max_sugar, self.sugar_amount + 1]) diff --git a/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/trader_agents.py b/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/trader_agents.py index 579f3470978..a228f3882b0 100644 --- a/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/trader_agents.py +++ b/examples/advanced/sugarscape_g1mt/sugarscape_g1mt/trader_agents.py @@ -7,12 +7,10 @@ # Helper function def get_distance(cell_1, cell_2): - """ - Calculate the Euclidean distance between two positions + """Calculate the Euclidean distance between two positions used in trade.move() """ - x1, y1 = cell_1.coordinate x2, y2 = cell_2.coordinate dx = x1 - x2 @@ -21,8 +19,7 @@ def get_distance(cell_1, cell_2): class Trader(CellAgent): - """ - Trader: + """Trader: - has a metabolism of sugar and spice - harvest and trade sugar and spice to survive """ @@ -54,19 +51,13 @@ def get_resource(self, cell): raise Exception(f"Resource agent not found in the position {cell.coordinate}") def get_trader(self, cell): - """ - helper function used in self.trade_with_neighbors() - """ - + """Helper function used in self.trade_with_neighbors()""" for agent in cell.agents: if isinstance(agent, Trader): return agent def is_occupied_by_other(self, cell): - """ - helper function part 1 of self.move() - """ - + """Helper function part 1 of self.move()""" if cell is self.cell: # agent's position is considered unoccupied as agent can stay there return False @@ -74,13 +65,11 @@ def is_occupied_by_other(self, cell): return any(isinstance(a, Trader) for a in cell.agents) def calculate_welfare(self, sugar, spice): - """ - helper function + """Helper function part 2 self.move() self.trade() """ - # calculate total resources m_total = self.metabolism_sugar + self.metabolism_spice # Cobb-Douglas functional form; starting on p. 97 @@ -90,29 +79,22 @@ def calculate_welfare(self, sugar, spice): ) def is_starved(self): - """ - Helper function for self.maybe_die() - """ - + """Helper function for self.maybe_die()""" return (self.sugar <= 0) or (self.spice <= 0) def calculate_MRS(self, sugar, spice): - """ - Helper function for + """Helper function for - self.trade() - self.maybe_self_spice() Determines what trader agent needs and can give up """ - return (spice / self.metabolism_spice) / (sugar / self.metabolism_sugar) def calculate_sell_spice_amount(self, price): - """ - helper function for self.maybe_sell_spice() which is called from + """Helper function for self.maybe_sell_spice() which is called from self.trade() """ - if price >= 1: sugar = 1 spice = int(price) @@ -122,22 +104,17 @@ def calculate_sell_spice_amount(self, price): return sugar, spice def sell_spice(self, other, sugar, spice): - """ - used in self.maybe_sell_spice() + """Used in self.maybe_sell_spice() exchanges sugar and spice between traders """ - self.sugar += sugar other.sugar -= sugar self.spice -= spice other.spice += spice def maybe_sell_spice(self, other, price, welfare_self, welfare_other): - """ - helper function for self.trade() - """ - + """Helper function for self.trade()""" sugar_exchanged, spice_exchanged = self.calculate_sell_spice_amount(price) # Assess new sugar and spice amount - what if change did occur @@ -175,12 +152,10 @@ def maybe_sell_spice(self, other, price, welfare_self, welfare_other): return True def trade(self, other): - """ - helper function used in trade_with_neighbors() + """Helper function used in trade_with_neighbors() other is a trader agent object """ - # sanity check to verify code is working as expected assert self.sugar > 0 assert self.spice > 0 @@ -228,14 +203,12 @@ def trade(self, other): ###################################################################### def move(self): - """ - Function for trader agent to identify optimal move for each step in 4 parts + """Function for trader agent to identify optimal move for each step in 4 parts 1 - identify all possible moves 2 - determine which move maximizes welfare 3 - find closest best option 4 - move """ - # 1. identify all possible moves neighboring_cells = [ @@ -289,22 +262,17 @@ def eat(self): self.spice -= self.metabolism_spice def maybe_die(self): - """ - Function to remove Traders who have consumed all their sugar or spice - """ - + """Function to remove Traders who have consumed all their sugar or spice""" if self.is_starved(): self.remove() def trade_with_neighbors(self): - """ - Function for trader agents to decide who to trade with in three parts + """Function for trader agents to decide who to trade with in three parts 1- identify neighbors who can trade 2- trade (2 sessions) 3- collect data """ - neighbor_agents = [ self.get_trader(cell) for cell in self.cell.get_neighborhood(radius=self.vision) diff --git a/examples/advanced/wolf_sheep/wolf_sheep/agents.py b/examples/advanced/wolf_sheep/wolf_sheep/agents.py index 8e71988bc9a..c617a550eb0 100644 --- a/examples/advanced/wolf_sheep/wolf_sheep/agents.py +++ b/examples/advanced/wolf_sheep/wolf_sheep/agents.py @@ -76,13 +76,10 @@ def feed(self): class GrassPatch(FixedAgent): - """ - A patch of grass that grows at a fixed rate and it is eaten by sheep - """ + """A patch of grass that grows at a fixed rate and it is eaten by sheep""" def __init__(self, model, fully_grown, countdown): - """ - Creates a new patch of grass + """Creates a new patch of grass Args: grown: (boolean) Whether the patch of grass is fully grown or not diff --git a/examples/advanced/wolf_sheep/wolf_sheep/model.py b/examples/advanced/wolf_sheep/wolf_sheep/model.py index 5b43b7912e1..794dff940b2 100644 --- a/examples/advanced/wolf_sheep/wolf_sheep/model.py +++ b/examples/advanced/wolf_sheep/wolf_sheep/model.py @@ -1,5 +1,4 @@ -""" -Wolf-Sheep Predation Model +"""Wolf-Sheep Predation Model ================================ Replication of the model found in NetLogo: @@ -16,9 +15,7 @@ class WolfSheep(mesa.Model): - """ - Wolf-Sheep Predation Model - """ + """Wolf-Sheep Predation Model""" height = 20 width = 20 @@ -53,8 +50,7 @@ def __init__( sheep_gain_from_food=4, seed=None, ): - """ - Create a new Wolf-Sheep model with the given parameters. + """Create a new Wolf-Sheep model with the given parameters. Args: initial_sheep: Number of sheep to start with diff --git a/examples/basic/boid_flockers/app.py b/examples/basic/boid_flockers/app.py index 205cb21858c..ade2deb2616 100644 --- a/examples/basic/boid_flockers/app.py +++ b/examples/basic/boid_flockers/app.py @@ -1,4 +1,5 @@ from boid_flockers.model import BoidFlockers + from mesa.visualization import SolaraViz, make_space_matplotlib diff --git a/examples/basic/boid_flockers/boid_flockers/SimpleContinuousModule.py b/examples/basic/boid_flockers/boid_flockers/SimpleContinuousModule.py index ec670d7af1c..ef26ddf7b80 100644 --- a/examples/basic/boid_flockers/boid_flockers/SimpleContinuousModule.py +++ b/examples/basic/boid_flockers/boid_flockers/SimpleContinuousModule.py @@ -5,9 +5,7 @@ class SimpleCanvas(mesa.visualization.VisualizationElement): local_includes = ["boid_flockers/simple_continuous_canvas.js"] def __init__(self, portrayal_method=None, canvas_height=500, canvas_width=500): - """ - Instantiate a new SimpleCanvas - """ + """Instantiate a new SimpleCanvas""" self.portrayal_method = portrayal_method self.canvas_height = canvas_height self.canvas_width = canvas_width diff --git a/examples/basic/boid_flockers/boid_flockers/model.py b/examples/basic/boid_flockers/boid_flockers/model.py index ae3099f3549..d293a6bdc5f 100644 --- a/examples/basic/boid_flockers/boid_flockers/model.py +++ b/examples/basic/boid_flockers/boid_flockers/model.py @@ -1,17 +1,16 @@ -""" -Flockers +"""Flockers ============================================================= A Mesa implementation of Craig Reynolds's Boids flocker model. Uses numpy arrays to represent vectors. """ -import mesa import numpy as np +import mesa + class Boid(mesa.Agent): - """ - A Boid-style flocker agent. + """A Boid-style flocker agent. The agent follows three behaviors to flock: - Cohesion: steering towards neighboring agents. @@ -35,8 +34,7 @@ def __init__( separate=0.015, match=0.05, ): - """ - Create a new Boid flocker agent. + """Create a new Boid flocker agent. Args: speed: Distance to move per step. @@ -58,10 +56,7 @@ def __init__( self.neighbors = None def step(self): - """ - Get the Boid's neighbors, compute the new vector, and move accordingly. - """ - + """Get the Boid's neighbors, compute the new vector, and move accordingly.""" self.neighbors = self.model.space.get_neighbors(self.pos, self.vision, False) n = 0 match_vector, separation_vector, cohere = np.zeros((3, 2)) @@ -83,9 +78,7 @@ def step(self): class BoidFlockers(mesa.Model): - """ - Flocker model class. Handles agent creation, placement and scheduling. - """ + """Flocker model class. Handles agent creation, placement and scheduling.""" def __init__( self, @@ -100,8 +93,7 @@ def __init__( separate=0.015, match=0.05, ): - """ - Create a new Flockers model. + """Create a new Flockers model. Args: population: Number of Boids @@ -124,9 +116,7 @@ def __init__( self.make_agents() def make_agents(self): - """ - Create self.population agents, with random positions and starting headings. - """ + """Create self.population agents, with random positions and starting headings.""" for _ in range(self.population): x = self.random.random() * self.space.x_max y = self.random.random() * self.space.y_max diff --git a/examples/basic/boltzmann_wealth_model/app.py b/examples/basic/boltzmann_wealth_model/app.py index 199b3a1a50e..0c38c742500 100644 --- a/examples/basic/boltzmann_wealth_model/app.py +++ b/examples/basic/boltzmann_wealth_model/app.py @@ -1,9 +1,10 @@ +from model import BoltzmannWealthModel + from mesa.visualization import ( SolaraViz, make_plot_measure, make_space_matplotlib, ) -from model import BoltzmannWealthModel def agent_portrayal(agent): diff --git a/examples/basic/conways_game_of_life/conways_game_of_life/cell.py b/examples/basic/conways_game_of_life/conways_game_of_life/cell.py index 35c8d3f2791..9d286d925cd 100644 --- a/examples/basic/conways_game_of_life/conways_game_of_life/cell.py +++ b/examples/basic/conways_game_of_life/conways_game_of_life/cell.py @@ -8,9 +8,7 @@ class Cell(mesa.Agent): ALIVE = 1 def __init__(self, pos, model, init_state=DEAD): - """ - Create a cell, in the given state, at the given x, y position. - """ + """Create a cell, in the given state, at the given x, y position.""" super().__init__(model) self.x, self.y = pos self.state = init_state @@ -25,14 +23,12 @@ def neighbors(self): return self.model.grid.iter_neighbors((self.x, self.y), True) def determine_state(self): - """ - Compute if the cell will be dead or alive at the next tick. This is + """Compute if the cell will be dead or alive at the next tick. This is based on the number of alive or dead neighbors. The state is not changed here, but is just computed and stored in self._nextState, because our current state may still be necessary for our neighbors to calculate their next state. """ - # Get the neighbors and apply the rules on whether to be alive or dead # at the next tick. live_neighbors = sum(neighbor.isAlive for neighbor in self.neighbors) @@ -47,7 +43,5 @@ def determine_state(self): self._nextState = self.ALIVE def assume_state(self): - """ - Set the state to the new computed state -- computed in step(). - """ + """Set the state to the new computed state -- computed in step().""" self.state = self._nextState diff --git a/examples/basic/conways_game_of_life/conways_game_of_life/model.py b/examples/basic/conways_game_of_life/conways_game_of_life/model.py index 76d9ca9fef4..d00261c90c7 100644 --- a/examples/basic/conways_game_of_life/conways_game_of_life/model.py +++ b/examples/basic/conways_game_of_life/conways_game_of_life/model.py @@ -4,15 +4,12 @@ class ConwaysGameOfLife(mesa.Model): - """ - Represents the 2-dimensional array of cells in Conway's + """Represents the 2-dimensional array of cells in Conway's Game of Life. """ def __init__(self, width=50, height=50): - """ - Create a new playing area of (width, height) cells. - """ + """Create a new playing area of (width, height) cells.""" super().__init__() # Use a simple grid, where edges wrap around. self.grid = mesa.space.SingleGrid(width, height, torus=True) @@ -28,8 +25,7 @@ def __init__(self, width=50, height=50): self.running = True def step(self): - """ - Perform the model step in two stages: + """Perform the model step in two stages: - First, all cells assume their next state (whether they will be dead or alive) - Then, all cells change state to their next state """ diff --git a/examples/basic/conways_game_of_life/conways_game_of_life/portrayal.py b/examples/basic/conways_game_of_life/conways_game_of_life/portrayal.py index 4f68468d857..1c8d6d0fadd 100644 --- a/examples/basic/conways_game_of_life/conways_game_of_life/portrayal.py +++ b/examples/basic/conways_game_of_life/conways_game_of_life/portrayal.py @@ -1,6 +1,5 @@ def portrayCell(cell): - """ - This function is registered with the visualization server to be called + """This function is registered with the visualization server to be called each tick to indicate how to draw the cell in its current state. :param cell: the cell in the simulation :return: the portrayal dictionary. diff --git a/examples/basic/schelling/analysis.ipynb b/examples/basic/schelling/analysis.ipynb index 71d925c1802..4feabbb4ba4 100644 --- a/examples/basic/schelling/analysis.ipynb +++ b/examples/basic/schelling/analysis.ipynb @@ -324,9 +324,7 @@ "outputs": [], "source": [ "def get_segregation(model):\n", - " \"\"\"\n", - " Find the % of agents that only have neighbors of their same type.\n", - " \"\"\"\n", + " \"\"\"Find the % of agents that only have neighbors of their same type.\"\"\"\n", " segregated_agents = 0\n", " for agent in model.agents:\n", " segregated = True\n", diff --git a/examples/basic/schelling/app.py b/examples/basic/schelling/app.py index fb837351d16..da4d6765f69 100644 --- a/examples/basic/schelling/app.py +++ b/examples/basic/schelling/app.py @@ -1,17 +1,16 @@ import solara +from model import Schelling + from mesa.visualization import ( Slider, SolaraViz, make_plot_measure, make_space_matplotlib, ) -from model import Schelling def get_happy_agents(model): - """ - Display a text count of how many happy agents there are. - """ + """Display a text count of how many happy agents there are.""" return solara.Markdown(f"**Happy agents: {model.happy}**") diff --git a/examples/basic/schelling/model.py b/examples/basic/schelling/model.py index b7523ef2b6d..3e6b141c518 100644 --- a/examples/basic/schelling/model.py +++ b/examples/basic/schelling/model.py @@ -2,13 +2,10 @@ class SchellingAgent(mesa.Agent): - """ - Schelling segregation agent - """ + """Schelling segregation agent""" def __init__(self, model: mesa.Model, agent_type: int) -> None: - """ - Create a new Schelling agent. + """Create a new Schelling agent. Args: agent_type: Indicator for the agent's type (minority=1, majority=0) @@ -30,9 +27,7 @@ def step(self) -> None: class Schelling(mesa.Model): - """ - Model class for the Schelling segregation model. - """ + """Model class for the Schelling segregation model.""" def __init__( self, @@ -44,8 +39,7 @@ def __init__( minority_pc=0.2, seed=None, ): - """ - Create a new Schelling model. + """Create a new Schelling model. Args: width, height: Size of the space. @@ -55,7 +49,6 @@ def __init__( radius: Search radius for checking similarity seed: Seed for Reproducibility """ - super().__init__(seed=seed) self.homophily = homophily self.radius = radius @@ -80,9 +73,7 @@ def __init__( self.datacollector.collect(self) def step(self): - """ - Run one step of the model. - """ + """Run one step of the model.""" self.happy = 0 # Reset counter of happy agents self.agents.shuffle_do("step") diff --git a/examples/basic/schelling/run_ascii.py b/examples/basic/schelling/run_ascii.py index 460fabbb746..da78828acd0 100644 --- a/examples/basic/schelling/run_ascii.py +++ b/examples/basic/schelling/run_ascii.py @@ -1,16 +1,13 @@ -import mesa from model import Schelling +import mesa + class SchellingTextVisualization(mesa.visualization.TextVisualization): - """ - ASCII visualization for schelling model - """ + """ASCII visualization for schelling model""" def __init__(self, model): - """ - Create new Schelling ASCII visualization. - """ + """Create new Schelling ASCII visualization.""" self.model = model grid_viz = mesa.visualization.TextGrid(self.model.grid, self.print_ascii_agent) @@ -19,9 +16,7 @@ def __init__(self, model): @staticmethod def print_ascii_agent(a): - """ - Minority agents are X, Majority are O. - """ + """Minority agents are X, Majority are O.""" if a.type == 0: return "O" if a.type == 1: diff --git a/examples/basic/virus_on_network/app.py b/examples/basic/virus_on_network/app.py index caa1360f880..ea9fa3b0d6b 100644 --- a/examples/basic/virus_on_network/app.py +++ b/examples/basic/virus_on_network/app.py @@ -3,9 +3,10 @@ import solara from matplotlib.figure import Figure from matplotlib.ticker import MaxNLocator -from mesa.visualization import SolaraViz, make_space_matplotlib from virus_on_network.model import State, VirusOnNetwork, number_infected +from mesa.visualization import SolaraViz, make_space_matplotlib + def agent_portrayal(graph): def get_agent(node): diff --git a/examples/basic/virus_on_network/virus_on_network/model.py b/examples/basic/virus_on_network/virus_on_network/model.py index d892a0c4c06..527b98a51a8 100644 --- a/examples/basic/virus_on_network/virus_on_network/model.py +++ b/examples/basic/virus_on_network/virus_on_network/model.py @@ -1,9 +1,10 @@ import math from enum import Enum -import mesa import networkx as nx +import mesa + class State(Enum): SUSCEPTIBLE = 0 @@ -28,9 +29,7 @@ def number_resistant(model): class VirusOnNetwork(mesa.Model): - """ - A virus model with some number of agents - """ + """A virus model with some number of agents""" def __init__( self, @@ -105,9 +104,7 @@ def run_model(self, n): class VirusAgent(mesa.Agent): - """ - Individual Agent definition and its properties/interaction methods - """ + """Individual Agent definition and its properties/interaction methods""" def __init__( self,