Fix caching_and_replay example for Mesa 3.x compatibility#327
Open
Jayantparashar10 wants to merge 5 commits intomesa:mainfrom
Open
Fix caching_and_replay example for Mesa 3.x compatibility#327Jayantparashar10 wants to merge 5 commits intomesa:mainfrom
Jayantparashar10 wants to merge 5 commits intomesa:mainfrom
Conversation
Fixes mesa#289 - Implement custom serialization/deserialization for CacheableModel to handle Mesa 3.x CellAgent positioning - Fix agent restoration by properly clearing all agent tracking dictionaries - Use cell.coordinate instead of pos for CellAgent position serialization - Update visualization to use Mesa 3.x patterns (make_space_component, make_plot_component) - Add cache status display to UI - Handle IndexError when no empty cells available for agent movement - Ensure deterministic replay of model states
- Simplify docstrings and comments to be more natural and concise - Follow Mesa documentation standards - Make error messages more user-friendly - Streamline README with clearer, less verbose instructions - Remove overly technical explanations
for more information, see https://pre-commit.ci
There was a problem hiding this comment.
Pull request overview
Updates the caching_and_replay example to work on Mesa 3.x by replacing deprecated visualization APIs and adding custom cache (de)serialization compatible with CellAgents and Mesa’s new internal agent tracking.
Changes:
- Migrates the example UI from
ModularServerto Solara (SolaraViz,make_space_component,make_plot_component) and adds cache/replay status UI. - Reworks caching logic with custom
_serialize_state/_deserialize_stateto store CellAgent positions viacell.coordinateand avoid Mesa 3.x serialization pitfalls. - Adds small robustness improvements (e.g., handling “full grid” moves) and updates README instructions.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 12 comments.
Show a summary per file
| File | Description |
|---|---|
| examples/caching_and_replay/cacheablemodel.py | Implements custom serialization/deserialization and record/replay orchestration for Mesa 3.x. |
| examples/caching_and_replay/run.py | New SolaraViz-based app for the cacheable model + cache status UI. |
| examples/caching_and_replay/server.py | Migrates the non-cacheable visualization components to Solara. |
| examples/caching_and_replay/model.py | Adjusts agent movement to handle “no empty cell” cases. |
| examples/caching_and_replay/README.md | Updates run instructions and usage notes for the Solara-based app. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- Combine nested if statements for better readability - Add noqa comment for pickle usage in cache serialization - Use contextlib.suppress for cleaner exception handling - Remove unnecessary imports and optimize code organization
for more information, see https://pre-commit.ci
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The caching_and_replay example was completely broken when run with Mesa 3.x, throwing multiple TypeErrors and AttributeErrors that prevented both recording and replay functionality. This PR fixes all Mesa 3.x compatibility issues, implementing custom serialization/deserialization logic to properly handle the new CellAgent architecture and internal agent management structures.
Bug / Issue
Fixes #289
The example was broken with Mesa 3.x due to fundamental changes in how Mesa handles agents, grids, and positioning:
What was expected: The example should record simulation states to a cache file and replay them deterministically.
What actually happened:
TypeError: 'AgentSet' object does not support item assignmentAttributeError: 'OrthogonalMooreGrid' object has no attribute 'get_cell'TypeError: AgentSet.__init__() missing required positional argument: 'agents'pos = None(CellAgents don't use pos, they usecell.coordinate)IndexErrordue to missing position dataRoot causes:
cell.coordinatefor positioning, notpos(which is always None)_agents,_agents_by_type,_all_agents) that weren't being cleared during deserializationget_cell()to direct_cellsdictionary accessmesa.visualization.ModularServerwhich was removed in Mesa 3.x in favor of Solara-based visualizationImplementation
Core Changes:
Custom Serialization (
_serialize_state)agent.cell.coordinateinstead ofagent.posCustom Deserialization (
_deserialize_state)agent.cell = cell_cellsdictionaryVisualization Migration
mesa.visualization.ModularServerwith manual component setup:SolaraVizwith modern component factory pattern:AgentPortrayalStylefor consistent agent renderingIndexErrorwhen grid is full (agent can't move)verboseparameter)Files Modified:
cacheablemodel.py- Complete rewrite with Mesa 3.x-compatible serializationrun.py- Updated visualization with replay controls and cache statusserver.py- Mesa 3.x visualization componentsmodel.py- Added error handling for full gridREADME.md- Updated documentation with clearer instructionsTesting
Comprehensive testing performed:
Cache Recording
Replay Determinism
Mesa 3.x Compliance
cell.coordinate)_cellsdictionary accessVisualization
Edge Cases
Test Results:
No Regressions:
Additional Notes
Technical Decisions:
Why custom serialization? Mesa 3.x's internal structures (WeakKeyDictionary for
_agents, CellAgent architecture) don't serialize well with default dill serialization. Custom implementation ensures reliability.Agent dict clearing: Mesa 3.x maintains multiple agent tracking dictionaries. All must be cleared before deserialization to prevent agent duplication.
CellAgent positioning: Mesa 3.x CellAgents have
pos = Noneby design. They usecell.coordinateinstead, which is what we serialize.Incremental cache writing: Cache is written after each step in RECORD mode for persistence, though full write happens on simulation completion.
Compatibility:
Future Improvements:
cache_step_rateparameter to UI for large simulationsDocumentation: