Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff basic examples #2370

Merged
merged 3 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmarks/BoltzmannWealth/boltzmann_wealth.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def run_model(self, n):
n: the number of steps for which to run the model

"""
for _i in range(n):
for _ in range(n):
self.step()


Expand Down
14 changes: 5 additions & 9 deletions examples/basic/boid_flockers/agents.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from mesa import Agent
import numpy as np

from mesa import Agent


class Boid(Agent):
"""
A Boid-style flocker agent.
"""A Boid-style flocker agent.

The agent follows three behaviors to flock:
- Cohesion: steering towards neighboring agents.
Expand All @@ -28,8 +28,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.
Expand All @@ -51,10 +50,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))
Expand Down
6 changes: 4 additions & 2 deletions examples/basic/boid_flockers/app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from model import BoidFlockers
from mesa.visualization import SolaraViz, make_space_matplotlib
from mesa.visualization import Slider

from mesa.visualization import Slider, SolaraViz, make_space_matplotlib


def boid_draw(agent):
if not agent.neighbors: # Only for the first Frame
Expand All @@ -13,6 +14,7 @@ def boid_draw(agent):
elif neighbors >= 2:
return {"color": "green", "size": 20}


model_params = {
"population": Slider(
label="Number of boids",
Expand Down
17 changes: 6 additions & 11 deletions examples/basic/boid_flockers/model.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
"""
Flockers
"""Flockers.
=============================================================
A Mesa implementation of Craig Reynolds's Boids flocker model.
Uses numpy arrays to represent vectors.
"""

import mesa
import numpy as np
from agents import Boid

import mesa


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,
Expand All @@ -28,8 +26,7 @@ def __init__(
separate=0.015,
match=0.05,
):
"""
Create a new Flockers model.
"""Create a new Flockers model.

Args:
population: Number of Boids
Expand All @@ -52,9 +49,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
Expand Down
5 changes: 3 additions & 2 deletions examples/basic/boltzmann_wealth_model/app.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -16,7 +17,7 @@ def agent_portrayal(agent):


model_params = {
"N": {
"n": {
"type": "SliderInt",
"value": 50,
"label": "Number of agents:",
Expand Down
16 changes: 9 additions & 7 deletions examples/basic/boltzmann_wealth_model/model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import mesa
from agents import MoneyAgent

import mesa


class BoltzmannWealthModel(mesa.Model):
"""A simple model of an economy where agents exchange currency at random.

Expand All @@ -9,14 +11,14 @@ class BoltzmannWealthModel(mesa.Model):
highly skewed distribution of wealth.
"""

def __init__(self, N=100, width=10, height=10):
def __init__(self, n=100, width=10, height=10):
super().__init__()
self.num_agents = N
self.num_agents = n
self.grid = mesa.space.MultiGrid(width, height, True)

self.datacollector = mesa.DataCollector(
model_reporters={"Gini": self.compute_gini},
agent_reporters={"Wealth": "wealth"}
agent_reporters={"Wealth": "wealth"},
)
# Create agents
for _ in range(self.num_agents):
Expand All @@ -37,6 +39,6 @@ def step(self):
def compute_gini(self):
agent_wealths = [agent.wealth for agent in self.agents]
x = sorted(agent_wealths)
N = self.num_agents
B = sum(xi * (N - i) for i, xi in enumerate(x)) / (N * sum(x))
return 1 + (1 / N) - 2 * B
n = self.num_agents
b = sum(xi * (n - i) for i, xi in enumerate(x)) / (n * sum(x))
return 1 + (1 / n) - 2 * b
12 changes: 3 additions & 9 deletions examples/basic/conways_game_of_life/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ class Cell(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
Expand All @@ -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)
Expand All @@ -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
20 changes: 7 additions & 13 deletions examples/basic/conways_game_of_life/model.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
from agents import Cell

from mesa import Model
from mesa.space import SingleGrid

from agents import Cell


class ConwaysGameOfLife(Model):
"""
Represents the 2-dimensional array of cells in Conway's
Game of Life.
"""
"""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 = SingleGrid(width, height, 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():
for _contents, (x, y) in self.grid.coord_iter():
cell = Cell((x, y), self)
if self.random.random() < 0.1:
cell.state = cell.ALIVE
Expand All @@ -29,10 +24,9 @@ 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
- Then, all cells change state to their next state.
"""
self.agents.do("determine_state")
self.agents.do("assume_state")
3 changes: 1 addition & 2 deletions examples/basic/conways_game_of_life/portrayal.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
4 changes: 2 additions & 2 deletions examples/basic/conways_game_of_life/server.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import mesa

from model import ConwaysGameOfLife
from portrayal import portrayCell

import mesa

# Make a world that is 50x50, on a 250x250 display.
canvas_element = mesa.visualization.CanvasGrid(portrayCell, 50, 50, 250, 250)

Expand Down
7 changes: 2 additions & 5 deletions examples/basic/schelling/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@


class SchellingAgent(Agent):
"""
Schelling segregation agent
"""
"""Schelling segregation agent."""

def __init__(self, model: 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)
Expand Down
7 changes: 3 additions & 4 deletions examples/basic/schelling/app.py
Original file line number Diff line number Diff line change
@@ -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}**")


Expand Down
16 changes: 5 additions & 11 deletions examples/basic/schelling/model.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from agents import SchellingAgent

import mesa
from mesa import Model

from agents import SchellingAgent


class Schelling(Model):
"""
Model class for the Schelling segregation model.
"""
"""Model class for the Schelling segregation model."""

def __init__(
self,
Expand All @@ -19,8 +17,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.
Expand All @@ -30,7 +27,6 @@ def __init__(
radius: Search radius for checking similarity
seed: Seed for Reproducibility
"""

super().__init__(seed=seed)
self.homophily = homophily
self.radius = radius
Expand All @@ -55,9 +51,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")

Expand Down
7 changes: 3 additions & 4 deletions examples/basic/virus_on_network/agents.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from mesa import Agent
from enum import Enum

from mesa import Agent


class State(Enum):
SUSCEPTIBLE = 0
Expand All @@ -9,9 +10,7 @@ class State(Enum):


class VirusAgent(Agent):
"""
Individual Agent definition and its properties/interaction methods
"""
"""Individual Agent definition and its properties/interaction methods."""

def __init__(
self,
Expand Down
3 changes: 2 additions & 1 deletion examples/basic/virus_on_network/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import solara
from matplotlib.figure import Figure
from matplotlib.ticker import MaxNLocator
from mesa.visualization import SolaraViz, Slider, make_space_matplotlib
from model import State, VirusOnNetwork, number_infected

from mesa.visualization import Slider, SolaraViz, make_space_matplotlib


def agent_portrayal(graph):
def get_agent(node):
Expand Down
Loading
Loading