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

Bug in Demographic Prisoner's Dilemma Activation Schedule #2552

Open
sjgenco opened this issue Dec 18, 2024 · 2 comments · May be fixed by #2553
Open

Bug in Demographic Prisoner's Dilemma Activation Schedule #2552

sjgenco opened this issue Dec 18, 2024 · 2 comments · May be fixed by #2553

Comments

@sjgenco
Copy link

sjgenco commented Dec 18, 2024

Describe the bug
I copied the code for pd_grid into JupyterLab on my computer. When I walked thru it, the code broke on all three activation examples. The error is this: AttributeError: 'OrthogonalMooreGrid' object has no property layer called 'coord_iter'.

Here's the full error message:

/Users/sjgenco/anaconda3/envs/spyder-env/lib/python3.12/site-packages/mesa/experimental/cell_space/property_layer.py:226: FutureWarning: The property layer functionality and associated classes are experimental. It may be changed or removed in any and all future releases, including patch releases.
We would love to hear what you think about this new feature. If you have any thoughts, share them with us here: https://github.com/projectmesa/mesa/discussions/1932
  layer = PropertyLayer(
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/anaconda3/envs/spyder-env/lib/python3.12/site-packages/mesa/experimental/cell_space/property_layer.py:405, in HasPropertyLayers.__getattr__(self, name)
    404 try:
--> 405     return self._mesa_property_layers[name]
    406 except KeyError as e:

KeyError: 'coord_iter'

The above exception was the direct cause of the following exception:

AttributeError                            Traceback (most recent call last)
Cell In[6], line 2
      1 m = PdGrid(50, 50, "Sequential", seed=seed)
----> 2 run_model(m)

Cell In[4], line 12, in run_model(model)
      9 ax3 = fig.add_subplot(233)
     10 ax4 = fig.add_subplot(212)
---> 12 draw_grid(model, ax1)
     13 model.run(10)
     14 draw_grid(model, ax2)

Cell In[3], line 12, in draw_grid(model, ax)
     10     fig, ax = plt.subplots(figsize=(6, 6))
     11 grid = np.zeros((model.grid.width, model.grid.height))
---> 12 for agent, (x, y) in model.grid.coord_iter():
     13     if agent.move == "D":
     14         grid[y][x] = 1

File ~/anaconda3/envs/spyder-env/lib/python3.12/site-packages/mesa/experimental/cell_space/property_layer.py:407, in HasPropertyLayers.__getattr__(self, name)
    405     return self._mesa_property_layers[name]
    406 except KeyError as e:
--> 407     raise AttributeError(
    408         f"'{type(self).__name__}' object has no property layer called '{name}'"
    409     ) from e

AttributeError: 'OrthogonalMooreGrid' object has no property layer called 'coord_iter'

Expected behavior
I was expecting the code to work, as it's a tutorial.

To Reproduce
I've included below the rest of my ipynb file. You can check if anything differs from the version on your github site (at https://github.com/projectmesa/mesa/blob/main/mesa/examples/advanced/pd_grid/), but it looks like the error is occurring inside the mesa code, the new coord_iter property doesn't seem to be available in the new OrthogonalMooreGrid class.

Additional context
here is the rest of my ipynb file:

import matplotlib.pyplot as plt
import numpy as np
from pd_grid.model import PdGrid

%matplotlib inline
bwr = plt.get_cmap("bwr")


def draw_grid(model, ax=None):
    """
    Draw the current state of the grid, with Defecting agents in red
    and Cooperating agents in blue.
    """
    if not ax:
        fig, ax = plt.subplots(figsize=(6, 6))
    grid = np.zeros((model.grid.width, model.grid.height))
    for agent, (x, y) in model.grid.coord_iter():
        if agent.move == "D":
            grid[y][x] = 1
        else:
            grid[y][x] = 0
    ax.pcolormesh(grid, cmap=bwr, vmin=0, vmax=1)
    ax.axis("off")
    ax.set_title(f"Steps: {model.steps}")
def run_model(model):
    """
    Run an experiment with a given model, and plot the results.
    """
    fig = plt.figure(figsize=(12, 8))

    ax1 = fig.add_subplot(231)
    ax2 = fig.add_subplot(232)
    ax3 = fig.add_subplot(233)
    ax4 = fig.add_subplot(212)

    draw_grid(model, ax1)
    model.run(10)
    draw_grid(model, ax2)
    model.run(10)
    draw_grid(model, ax3)
    model.datacollector.get_model_vars_dataframe().plot(ax=ax4)
# Set the random seed
seed = 21
m = PdGrid(50, 50, "Sequential", seed=seed)
run_model(m)
@quaquel
Copy link
Member

quaquel commented Dec 18, 2024

coord_iter is something that exists in "old style" spaces and not in the experimental cell space. You use a new style space in your model, but your draw_grid method uses old style space syntax. Your draw_grid method is therefore not correct. There are various ways to resolve this.

  1. You can use the plotting functionality in mesa.visualization.mpl_space_drawing
  2. You can rewrite the for loop by iterating over all agents in the model:
grid = np.zeros((model.grid.width, model.grid.height))
for agent in model.agents:
    x, y = agent.cell.coordinate
    grid[x,y] = 1 if agent.move == "D" else 0

3 You can rewrite the for loop by iterating over all cells in the model:

grid = np.zeros((model.grid.width, model.grid.height))
for cell in model.grid.all_cells:
    x, y = cell.coordinate
    agent = cell.agents[0]  # this assumes there is exactly 1 agent in each cell.
    grid[x,y] = 1 if agent.move == "D" else 0

@sjgenco
Copy link
Author

sjgenco commented Dec 18, 2024 via email

@quaquel quaquel linked a pull request Dec 19, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants