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

examples: Clean-up Epstein Civil Violence and PD grid #2373

Closed
wants to merge 13 commits into from
Closed
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
186 changes: 145 additions & 41 deletions examples/advanced/epstein_civil_violence/Epstein Civil Violence.ipynb

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions examples/advanced/epstein_civil_violence/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ Then open your browser to [http://127.0.0.1:8521/](http://127.0.0.1:8521/) and p

## Files

* ``EpsteinCivilViolence.py``: Core model and agent code.
* ``EpsteinCivilViolenceServer.py``: Sets up the interactive visualization.
* ``model.py``: Core model code.
* ``agent.py``: Agent classes.
* ``app.py``: Sets up the interactive visualization.
* ``Epstein Civil Violence.ipynb``: Jupyter notebook conducting some preliminary analysis of the model.

## Further Reading
Expand Down
70 changes: 70 additions & 0 deletions examples/advanced/epstein_civil_violence/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from mesa.visualization import SolaraViz, Slider, make_space_matplotlib, make_plot_measure

from agents import Citizen, Cop
from model import EpsteinCivilViolence

COP_COLOR = "#000000"
AGENT_QUIET_COLOR = "#648FFF"
AGENT_REBEL_COLOR = "#FE6100"
JAIL_COLOR = "#808080"
JAIL_SHAPE = "rect"


def citizen_cop_portrayal(agent):
if agent is None:
return

portrayal = {
"shape": "circle",
"x": agent.pos[0],
"y": agent.pos[1],
"filled": True,
}

if isinstance(agent, Citizen):
color = AGENT_QUIET_COLOR if agent.condition == "Quiescent" else AGENT_REBEL_COLOR
color = JAIL_COLOR if agent.jail_sentence else color
shape = JAIL_SHAPE if agent.jail_sentence else "circle"
portrayal["color"] = color
portrayal["shape"] = shape
if shape == "rect":
portrayal["w"] = 0.9
portrayal["h"] = 0.9
else:
portrayal["r"] = 0.5
portrayal["filled"] = False
portrayal["layer"] = 0

elif isinstance(agent, Cop):
portrayal["color"] = COP_COLOR
portrayal["r"] = 0.9
portrayal["layer"] = 1

return portrayal


model_params = {
"height": 40,
"width": 40,
"citizen_density": Slider("Initial Agent Density", 0.7, 0.0, 0.9, 0.1),
"cop_density": Slider("Initial Cop Density", 0.04, 0.0, 0.1, 0.01),
"citizen_vision": Slider("Citizen Vision", 7, 1, 10, 1),
"cop_vision": Slider("Cop Vision", 7, 1, 10, 1),
"legitimacy": Slider("Government Legitimacy", 0.82, 0.0, 1, 0.01),
"max_jail_term": Slider("Max Jail Term", 30, 0, 50, 1),
}

# space_component = make_space_matplotlib(citizen_cop_portrayal)
chart_component = make_plot_measure(["Quiescent", "Active", "Jailed"])

epstein_model = EpsteinCivilViolence()

page = SolaraViz(
epstein_model,
components=[
# space_component,
chart_component],
model_params=model_params,
name="Epstein Civil Violence",
)
page # noqa
Empty file.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import mesa

from .agent import Citizen, Cop
from agents import Citizen, Cop


class EpsteinCivilViolence(mesa.Model):
Expand Down Expand Up @@ -43,8 +43,9 @@ def __init__(
arrest_prob_constant=2.3,
movement=True,
max_iters=1000,
seed=None
):
super().__init__()
super().__init__(seed=seed)
self.width = width
self.height = height
self.citizen_density = citizen_density
Expand All @@ -59,9 +60,7 @@ def __init__(
self.max_iters = max_iters
self.iteration = 0

self.grid = mesa.experimental.cell_space.OrthogonalMooreGrid(
(width, height), capacity=1, torus=True
)
self.grid = mesa.experimental.cell_space.OrthogonalMooreGrid((width, height), capacity=1, torus=True, random=self.random)

model_reporters = {
"Quiescent": lambda m: self.count_type_citizens(m, "Quiescent"),
Expand Down Expand Up @@ -144,3 +143,17 @@ def count_cops(model):
Helper method to count jailed agents.
"""
return len(model.agents_by_type[Cop])


if __name__ == "__main__":

import mesa.experimental as experimental

import sys

print(sys.getrecursionlimit())

model = EpsteinCivilViolence()
import copy
# copy.deepcopy(model)
copy.deepcopy(experimental.cell_space.OrthogonalMooreGrid((100,100), torus=True, random=model.random))
3 changes: 0 additions & 3 deletions examples/advanced/epstein_civil_violence/requirements.txt

This file was deleted.

3 changes: 0 additions & 3 deletions examples/advanced/epstein_civil_violence/run.py

This file was deleted.

86 changes: 23 additions & 63 deletions examples/advanced/pd_grid/analysis.ipynb

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions examples/advanced/pd_grid/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import mesa
from mesa.visualization import SolaraViz
from mesa.visualization.UserParam import Slider
# Import make_space_altair
from mesa.visualization import make_space_altair, make_plot_measure

from model import PdGrid

def portray_pd_agent(agent):
"""This function is called to portray each agent in the visualization."""
if agent is None:
return {}
return {
"shape": "rect",
"w": 1,
"h": 1,
"color": "blue" if agent.isCooroperating else "red",
}

# Define model parameters
model_params = {
"height": Slider("Grid Height", 50, 10, 100, 1),
"width": Slider("Grid Width", 50, 10, 100, 1),
# TODO: Implement Choice in UserParam. See https://github.com/projectmesa/mesa/issues/2376
# "activation_order": Choice(
# "Activation regime",
# value="Random",
# choices=PdGrid.activation_regimes,
# ),
}

# Create the model instance
pd_model = PdGrid()

coop_plot = make_plot_measure("cooperating_agents")

# Create the SolaraViz instance
page = SolaraViz(
pd_model,
# TODO: Support the Cell Space in SolaraViz.
components=[coop_plot], # [make_space_altair(portray_pd_agent)],
model_params=model_params,
name="Prisoner's Dilemma"
)
page # noqa
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mesa
from mesa.experimental.cell_space import OrthogonalMooreGrid

from .agent import PDAgent
from agents import PDAgent


class PdGrid(mesa.Model):
Expand Down Expand Up @@ -41,7 +41,7 @@ def __init__(

self.datacollector = mesa.DataCollector(
{
"Cooperating_Agents": lambda m: len(
"cooperating_agents": lambda m: len(
[a for a in m.agents if a.move == "C"]
)
}
Expand Down
Empty file.
19 changes: 0 additions & 19 deletions examples/advanced/pd_grid/pd_grid/portrayal.py

This file was deleted.

21 changes: 0 additions & 21 deletions examples/advanced/pd_grid/pd_grid/server.py

This file was deleted.

7 changes: 4 additions & 3 deletions examples/advanced/pd_grid/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ Launch the ``Demographic Prisoner's Dilemma Activation Schedule.ipynb`` notebook

## Files

* ``run.py`` is the entry point for the font-end simulations.
* ``pd_grid/``: contains the model and agent classes; the model takes a ``activation_order`` string as an argument, which determines in which order agents are activated: Sequential, Random or Simultaneous.
* ``Demographic Prisoner's Dilemma Activation Schedule.ipynb``: Jupyter Notebook for running the scheduling experiment. This runs the model three times, one for each activation type, and demonstrates how the activation regime drives the model to different outcomes.
* ``model.py``: contains the model, which takes a ``activation_order`` string as an argument, which determines in which order agents are activated: Sequential, Random or Simultaneous.
* ``agents.py``: contains the agent class, which has a strategy and a score.
* ``app.py``: contains the interactive visualization of the model.
* ``analysis.ipynb``: Jupyter Notebook for running the scheduling experiment. This runs the model three times, one for each activation type, and demonstrates how the activation regime drives the model to different outcomes.

## Further Reading

Expand Down
3 changes: 0 additions & 3 deletions examples/advanced/pd_grid/requirements.txt

This file was deleted.

3 changes: 0 additions & 3 deletions examples/advanced/pd_grid/run.py

This file was deleted.

9 changes: 0 additions & 9 deletions mesa/experimental/cell_space/cell.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,6 @@ class Cell:
"__dict__",
]

# def __new__(cls,
# coordinate: tuple[int, ...],
# capacity: float | None = None,
# random: Random | None = None,):
# if capacity != 1:
# return object.__new__(cls)
# else:
# return object.__new__(SingleAgentCell)

def __init__(
self,
coordinate: Coordinate,
Expand Down
Loading