mesa icon indicating copy to clipboard operation
mesa copied to clipboard

wolf sheep example crashes when i try to run it with grass regrowth enabled=False

Open disgruntled-penguin opened this issue 8 months ago • 10 comments

Image

disgruntled-penguin avatar Mar 22 '26 13:03 disgruntled-penguin

Hey @disgruntled-penguin, thanks for the clear traceback!

It looks like the DataCollector stops tracking the 'Grass' metric when grass_regrowth is set to False, but the matplotlib_components.py visualizer is still blindly attempting to plot it, throwing the KeyError.

I'd love to take this one on. I can put together a PR that adds a safety check in the plotting component to verify the metric exists in the dataframe columns before attempting to plot it. Let me know if I'm good to open a PR for this!

laxmi2577 avatar Mar 22 '26 14:03 laxmi2577

I think I have seen this issue before at some point. Is this on main or on 3.5?

quaquel avatar Mar 22 '26 15:03 quaquel

I think I have seen this issue before at some point. Is this on main or on 3.5?

I checked it, prominent in both.

codebreaker32 avatar Mar 22 '26 19:03 codebreaker32

Thanks for checking. @laxmi2577 diagnosis makes sense to me. The main question then becomes what an elegant solution is for the problem.

quaquel avatar Mar 22 '26 19:03 quaquel

I went ahead and tried to fix this, there were two separate issues:

  1. The Frontend KeyError (@laxmi2577 is spot on): Added quick if check

https://github.com/mesa/mesa/blob/71cfd39e0fcf67f0eaa08d342846bfbccdbe7ff0/mesa/visualization/components/matplotlib_components.py#L157-L167

to

if isinstance(measure, str):
        if measure in df.columns:
            ax.plot(df.loc[:, measure])
            ax.set_ylabel(measure)
    elif isinstance(measure, dict):
        for m, color in measure.items():
            if m in df.columns:
                ax.plot(df.loc[:, m], label=m, color=color)
        ax.legend(loc="best")
    elif isinstance(measure, list | tuple):
        for m in measure:
            if m in df.columns:
                ax.plot(df.loc[:, m], label=m)
        ax.legend(loc="best")
  1. If you run the model headlessly (bypassing the UI crash), it dies with a StopIteration error because Sheep.feed() assumes a grass patch exists and calls next() on an empty generator without a default fallback.

I passed None as a default to next() in Sheep.feed(), and add a quick if grass_patch: check.

But then after reset, background disppeared

Image

codebreaker32 avatar Mar 22 '26 19:03 codebreaker32

This looks somewhat similar to what we encountered in Network(#3323 and #3345)

codebreaker32 avatar Mar 22 '26 19:03 codebreaker32

Reproduced both crashes locally and opened a fix PR. Bug 1 (StopIteration): Sheep.feed() calls next(generator) with no default. When grass=False no GrassPatch exists in any cell so the generator is always empty. Fix: next((gen), None) + if grass_patch is not None guard. Bug 2 (KeyError: 'Grass'): DataCollector only registers the "Grass" reporter when grass=True (model.py line 87). PlotMatplotlib was plotting all measure keys unconditionally. Fix: if m in df.columns guard — generalises to any model with conditionally-collected metrics. Both fixes are additive guards only, no change to the grass=True path. Two regression tests added.

Image

DipayanDasgupta avatar Mar 22 '26 20:03 DipayanDasgupta

Here's the fixed model running interactively with grass=False in the Solara visualizer — Wolves and Sheep population curves shown correctly, no crash, Grass metric absent from both the plot and the sidebar as expected.

Image

DipayanDasgupta avatar Mar 22 '26 20:03 DipayanDasgupta

@DipayanDasgupta i assumed setting regrowth to False means we start out with some initial grass and then it doesn’t grow back, is grass just absent from the get go in your solution?

disgruntled-penguin avatar Mar 22 '26 21:03 disgruntled-penguin

@disgruntled-penguin good point . You're right that semantically grass=False could mean "grass exists but doesn't regrow." In the current Mesa implementation though, grass=False means no GrassPatch agents are created at all (model.py line 122: if self.grass: # Create grass patches). So grass is absent from the start entirely. The parameter name grass controls whether the grass mechanic exists, not just whether it regrows — grass_regrowth_time controls the regrowth rate separately. The crash happens because Sheep.feed() assumed GrassPatch agents always exist in cells, which isn't true when grass=False.

DipayanDasgupta avatar Mar 23 '26 13:03 DipayanDasgupta