Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Oct 15, 2024
1 parent 9d0d6c0 commit 9ba1be2
Show file tree
Hide file tree
Showing 26 changed files with 94 additions and 202 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@

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
self.empty_neighbors = [c for c in self.neighborhood if c.is_empty]


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:
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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)])
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand All @@ -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])
7 changes: 2 additions & 5 deletions examples/advanced/pd_grid/analysis.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
7 changes: 3 additions & 4 deletions examples/advanced/pd_grid/pd_grid/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions examples/advanced/pd_grid/pd_grid/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 1 addition & 2 deletions examples/advanced/pd_grid/pd_grid/portrayal.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
3 changes: 2 additions & 1 deletion examples/advanced/sugarscape_g1mt/app.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
3 changes: 2 additions & 1 deletion examples/advanced/sugarscape_g1mt/run.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
20 changes: 7 additions & 13 deletions examples/advanced/sugarscape_g1mt/sugarscape_g1mt/model.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
"""
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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])
Expand Down
Loading

0 comments on commit 9ba1be2

Please sign in to comment.