Fix: Cell.get_neighborhood() RecursionError for large radius (#3105)#3106
Merged
Fix: Cell.get_neighborhood() RecursionError for large radius (#3105)#3106
Conversation
|
Performance benchmarks:
|
ab6feb1 to
3c210d4
Compare
quaquel
approved these changes
Jan 12, 2026
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.
Fixes #3105
This PR improves
Cell.get_neighborhood()by replacing the recursive implementation with an iterative Breadth-First Search (BFS). This change provides two key benefits:RecursionErrorwhen radius exceeds Python's recursion limit (~1000)Problem
The previous implementation used recursion to traverse cell neighborhoods:
This had two issues:
radius > sys.getrecursionlimit()(~1000), it causedRecursionError: maximum recursion depth exceededSolution
Replaced with iterative BFS using explicit layer-by-layer traversal:
Benefits
~2x faster neighborhood lookups (confirmed by maintainer benchmarks)
No recursion limit: Can handle any radius value (memory-limited, not stack-limited)
Same behavior: All 37 existing discrete_space tests pass
Same time complexity: O(number of cells in radius)
Changes
mesa/discrete_space/cell.py: Replaced recursive_neighborhood()with iterative BFStests/discrete_space/test_discrete_space.py: Added 3 regression tests:test_large_radius_neighborhood: Tests radius=1500 on a 2000-cell chaintest_large_radius_with_include_center: Testsinclude_centerparameter with large radiustest_radius_exceeds_reachable_cells: Tests radius > available cellsTesting
$ python -m pytest tests/discrete_space/test_discrete_space.py -v ============================= 37 passed in 13.67s =============================All existing tests pass + 3 new regression tests added.