Skip to content

Sync pyproject with mesa #268

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

Merged
merged 9 commits into from
May 21, 2025
27 changes: 11 additions & 16 deletions examples/aco_tsp/aco_tsp/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,10 @@ def from_tsp_file(cls, file_path: str) -> "TSPGraph":


class AntTSP(CellAgent):
"""
An agent
"""
"""An agent"""

def __init__(self, model, alpha: float = 1.0, beta: float = 5.0):
"""
Customize the agent
"""
"""Customize the agent"""
super().__init__(model)
self.alpha = alpha
self.beta = beta
Expand Down Expand Up @@ -141,11 +137,9 @@ def decide_next_city(self):
return new_city

def step(self):
"""
Modify this method to change what an individual agent will do during each step.
"""Modify this method to change what an individual agent will do during each step.
Can include logic based on neighbors states.
"""

for _ in range(self.model.num_cities - 1):
# Pick a random city that isn't in the list of cities visited
new_city = self.decide_next_city()
Expand All @@ -158,8 +152,7 @@ def step(self):


class AcoTspModel(mesa.Model):
"""
The model class holds the model-level attributes, manages the agents, and generally handles
"""The model class holds the model-level attributes, manages the agents, and generally handles
the global level of our model.

There is only one model-level parameter: how many agents the model contains. When a new model
Expand All @@ -168,12 +161,16 @@ class AcoTspModel(mesa.Model):

def __init__(
self,
tsp_graph: TSPGraph | None,
num_agents: int = 20,
tsp_graph: TSPGraph = TSPGraph.from_random(20),
max_steps: int = int(1e6),
ant_alpha: float = 1.0,
ant_beta: float = 5.0,
):
# Don't create the TSPGraph.from_random as argument default: https://docs.astral.sh/ruff/rules/function-call-in-default-argument/
if tsp_graph is None:
tsp_graph = TSPGraph.from_random(20)

super().__init__()
self.num_agents = num_agents
self.tsp_graph = tsp_graph
Expand Down Expand Up @@ -224,15 +221,13 @@ def update_pheromone(self, q: float = 100, ro: float = 0.5):
# Evaporate
tau_ij = (1 - ro) * self.grid.G[i][j]["pheromone"]
# Add ant's contribution
for k, delta_tau_ij_k in delta_tau_ij.items():
for _, delta_tau_ij_k in delta_tau_ij.items():
tau_ij += delta_tau_ij_k.get((i, j), 0.0)

self.grid.G[i][j]["pheromone"] = tau_ij

def step(self):
"""
A model step. Used for activating the agents and collecting data.
"""
"""A model step. Used for activating the agents and collecting data."""
self.agents.shuffle_do("step")
self.update_pheromone()

Expand Down
4 changes: 1 addition & 3 deletions examples/aco_tsp/app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Configure visualization elements and instantiate a server
"""
"""Configure visualization elements and instantiate a server"""

import networkx as nx
import solara
Expand Down
16 changes: 9 additions & 7 deletions examples/bank_reserves/bank_reserves/agents.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
The following code was adapted from the Bank Reserves model included in Netlogo
"""The following code was adapted from the Bank Reserves model included in Netlogo
Model information can be found at:
http://ccl.northwestern.edu/netlogo/models/BankReserves
Accessed on: November 2, 2017
Expand All @@ -18,7 +17,8 @@ class Bank:
class. This is because there is only one bank in this model, and it does not
use any Mesa-specific features like the scheduler or the grid, and doesn't
have a step method. It is just used to keep track of the bank's reserves and
the amount it can loan out, for Person agents to interact with."""
the amount it can loan out, for Person agents to interact with.
"""

def __init__(self, model, reserve_percent=50):
self.model = model
Expand Down Expand Up @@ -63,8 +63,9 @@ def __init__(self, model, moore, bank, rich_threshold):
self.bank = bank

def do_business(self):
"""check if person has any savings, any money in wallet, or if the
bank can loan them any money"""
"""Check if person has any savings, any money in wallet, or if the
bank can loan them any money
"""
if (self.savings > 0 or self.wallet > 0 or self.bank.bank_to_loan > 0) and len(
self.cell.agents
) > 1:
Expand Down Expand Up @@ -164,8 +165,9 @@ def repay_a_loan(self, amount):

# part of balance_books()
def take_out_loan(self, amount):
"""borrow from the bank to put money in my wallet, and increase my
outstanding loans"""
"""Borrow from the bank to put money in my wallet, and increase my
outstanding loans
"""
self.loans += amount
self.wallet += amount
# decresae the amount the bank can loan right now
Expand Down
23 changes: 8 additions & 15 deletions examples/bank_reserves/bank_reserves/model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
The following code was adapted from the Bank Reserves model included in Netlogo
"""The following code was adapted from the Bank Reserves model included in Netlogo
Model information can be found at:
http://ccl.northwestern.edu/netlogo/models/BankReserves
Accessed on: November 2, 2017
Expand All @@ -25,39 +24,34 @@


def get_num_rich_agents(model):
"""return number of rich agents"""

"""Return number of rich agents"""
rich_agents = [a for a in model.agents if a.savings > model.rich_threshold]
return len(rich_agents)


def get_num_poor_agents(model):
"""return number of poor agents"""

"""Return number of poor agents"""
poor_agents = [a for a in model.agents if a.loans > 10]
return len(poor_agents)


def get_num_mid_agents(model):
"""return number of middle class agents"""

"""Return number of middle class agents"""
mid_agents = [
a for a in model.agents if a.loans < 10 and a.savings < model.rich_threshold
]
return len(mid_agents)


def get_total_savings(model):
"""sum of all agents' savings"""

"""Sum of all agents' savings"""
agent_savings = [a.savings for a in model.agents]
# return the sum of agents' savings
return np.sum(agent_savings)


def get_total_wallets(model):
"""sum of amounts of all agents' wallets"""

"""Sum of amounts of all agents' wallets"""
agent_wallets = [a.wallet for a in model.agents]
# return the sum of all agents' wallets
return np.sum(agent_wallets)
Expand All @@ -80,8 +74,7 @@ def get_total_loans(model):


class BankReservesModel(mesa.Model):
"""
This model is a Mesa implementation of the Bank Reserves model from NetLogo.
"""This model is a Mesa implementation of the Bank Reserves model from NetLogo.
It is a highly abstracted, simplified model of an economy, with only one
type of agent and a single bank representing all banks in an economy. People
(represented by circles) move randomly within the grid. If two or more people
Expand Down Expand Up @@ -160,5 +153,5 @@ def step(self):
self.datacollector.collect(self)

def run_model(self):
for i in range(self.run_time):
for _ in range(self.run_time):
self.step()
3 changes: 1 addition & 2 deletions examples/bank_reserves/batch_run.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
The following code was adapted from the Bank Reserves model included in Netlogo
"""The following code was adapted from the Bank Reserves model included in Netlogo
Model information can be found at:
http://ccl.northwestern.edu/netlogo/models/BankReserves
Accessed on: November 2, 2017
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,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
num_agents = self.num_agents
B = sum(xi * (num_agents - i) for i, xi in enumerate(x)) / (num_agents * sum(x)) # noqa: N806
return 1 + (1 / num_agents) - 2 * B
3 changes: 1 addition & 2 deletions examples/caching_and_replay/cacheablemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@


class CacheableSchelling(CacheableModel):
"""
A wrapper around the original Schelling model to make the simulation cacheable
"""A wrapper around the original Schelling model to make the simulation cacheable
and replay-able. Uses CacheableModel from the Mesa-Replay library,
which is a wrapper that can be put around any regular mesa model to make it
"cacheable".
Expand Down
19 changes: 5 additions & 14 deletions examples/caching_and_replay/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,10 @@


class SchellingAgent(CellAgent):
"""
Schelling segregation agent
"""
"""Schelling segregation agent"""

def __init__(self, model, agent_type):
"""
Create a new Schelling agent.
"""Create a new Schelling agent.

Args:
x, y: Agent initial location.
Expand All @@ -34,9 +31,7 @@ def step(self):


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

def __init__(
self,
Expand All @@ -48,8 +43,7 @@ def __init__(
minority_pc=0.3,
seed=None,
):
"""
Create a new Schelling model.
"""Create a new Schelling model.

Args:
width, height: Size of the space.
Expand All @@ -59,7 +53,6 @@ def __init__(
radius: Search radius for checking similarity
seed: Seed for Reproducibility
"""

super().__init__(seed=seed)
self.height = height
self.width = width
Expand Down Expand Up @@ -88,9 +81,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
4 changes: 1 addition & 3 deletions examples/caching_and_replay/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@


def get_cache_file_status(_):
"""
Display an informational text about caching and the status of the cache file (existing versus not existing)
"""
"""Display an informational text about caching and the status of the cache file (existing versus not existing)"""
cache_file = Path(model_params["cache_file_path"])
return (
f"Only activate the 'Replay cached run?' switch when a cache file already exists, otherwise it will fail. "
Expand Down
8 changes: 2 additions & 6 deletions examples/caching_and_replay/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,12 @@


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 f"Happy agents: {model.happy}"


def schelling_draw(agent):
"""
Portrayal Method for canvas
"""
"""Portrayal Method for canvas"""
if agent is None:
return
portrayal = {"Shape": "circle", "r": 0.5, "Filled": "true", "Layer": 0}
Expand Down
16 changes: 9 additions & 7 deletions examples/charts/charts/agents.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
The following code was adapted from the Bank Reserves model included in Netlogo
"""The following code was adapted from the Bank Reserves model included in Netlogo
Model information can be found at:
http://ccl.northwestern.edu/netlogo/models/BankReserves
Accessed on: November 2, 2017
Expand All @@ -18,7 +17,8 @@ class Bank:
class. This is because there is only one bank in this model, and it does not
use any Mesa-specific features like the scheduler or the grid, and doesn't
have a step method. It is just used to keep track of the bank's reserves and
the amount it can loan out, for Person agents to interact with."""
the amount it can loan out, for Person agents to interact with.
"""

def __init__(self, model, reserve_percent=50):
self.model = model
Expand Down Expand Up @@ -63,8 +63,9 @@ def __init__(self, model, bank, rich_threshold):
self.bank = bank

def do_business(self):
"""check if person has any savings, any money in wallet, or if the
bank can loan them any money"""
"""Check if person has any savings, any money in wallet, or if the
bank can loan them any money
"""
if self.savings > 0 or self.wallet > 0 or self.bank.bank_to_loan > 0:
# create list of people at my location (includes self)
my_cell = [a for a in self.cell.agents if a != self]
Expand Down Expand Up @@ -167,8 +168,9 @@ def repay_a_loan(self, amount):

# part of balance_books()
def take_out_loan(self, amount):
"""borrow from the bank to put money in my wallet, and increase my
outstanding loans"""
"""Borrow from the bank to put money in my wallet, and increase my
outstanding loans
"""
self.loans += amount
self.wallet += amount
# decresae the amount the bank can loan right now
Expand Down
Loading
Loading