Repository navigation
Optimize near-full Grid empty-cell selection - #3619
yassinekolsi wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR refines Grid.select_random_empty_cell to reduce wasted random probing on near-full grids by switching earlier to a deterministic selection based on the empty property layer, and adds a regression test covering the near-full behavior.
Changes:
- Adjusted
select_random_empty_cellto do a small number of random probes, estimate emptiness for near-full detection, and then either continue probing or fall back to a vectorized selection. - Switched the deterministic fallback to use
np.flatnonzero+np.unravel_indexrather thannp.argwhere. - Added a test ensuring near-full grids avoid exhaustive random sampling and still return the correct empty cell.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
mesa/discrete_space/grid.py |
Updates the empty-cell selection heuristic to short-circuit random retries on near-full grids and uses a vectorized fallback path. |
tests/discrete_space/test_discrete_space.py |
Adds a regression test validating the near-full shortcut reduces random sampling and still selects the correct empty cell. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # First do a few cheap random probes. | ||
| for _ in range(5): | ||
| cell = random.choice(cells) | ||
| if cell.is_empty: | ||
| return cell | ||
|
|
||
| empty_coords = np.argwhere(self.property_layers["empty"]) | ||
| try: | ||
| random_coord = self.random.choice(empty_coords) | ||
| except IndexError as e: | ||
| # If random probing fails repeatedly, estimate emptiness ratio once. | ||
| # For near-full grids, skip most random retries and go straight to fallback. | ||
| empty_count = int(np.count_nonzero(empty_mask)) | ||
| if empty_count == 0: | ||
| raise ValueError( | ||
| "Grid is completely full. No empty cells available. " | ||
| "Cannot select a random empty cell." | ||
| ) |
There was a problem hiding this comment.
select_random_empty_cell now does an O(n) np.count_nonzero(empty_mask) scan after only 5 failed probes. For moderately-full large grids (e.g., ~20% empties), missing 5 times is still fairly likely, so this can introduce a performance regression vs the old behavior which kept random probing cheap for up to 50 attempts before any full scan. Consider increasing the “misses before scan” threshold (possibly scaling with grid size) or otherwise deferring the O(n) pass so sparse/moderately-full grids keep the fast path.
| # If random probing fails repeatedly, estimate emptiness ratio once. | ||
| # For near-full grids, skip most random retries and go straight to fallback. | ||
| empty_count = int(np.count_nonzero(empty_mask)) | ||
| if empty_count == 0: | ||
| raise ValueError( | ||
| "Grid is completely full. No empty cells available. " | ||
| "Cannot select a random empty cell." | ||
| ) | ||
|
|
||
| near_full_cutoff = max(1, len(cells) // 20) # 5% empties | ||
| if empty_count > near_full_cutoff: | ||
| for _ in range(45): | ||
| cell = random.choice(cells) | ||
| if cell.is_empty: | ||
| return cell | ||
|
|
||
| empty_flat_indices = np.flatnonzero(empty_mask) | ||
| if empty_flat_indices.size == 0: | ||
| raise ValueError( | ||
| "Grid is completely full. No empty cells available. " | ||
| "Cannot select a random empty cell." | ||
| ) from e | ||
| return self._cells[tuple(random_coord)] | ||
| ) |
There was a problem hiding this comment.
The fallback path scans the empty mask twice: first via np.count_nonzero(empty_mask) and then again via np.flatnonzero(empty_mask). On near-full grids (the case this change targets), that’s two full passes over the array after only a few probes. You can avoid the duplicate scan by computing empty_flat_indices once (using .size as the count) and reusing it both for the full-grid check and for selection.
|
|
||
| assert selected_cell.coordinate == target_empty | ||
| # Old behavior always sampled 50 times before fallback; near-full now skips that. | ||
| assert sampled_from_cells < 50 |
There was a problem hiding this comment.
The new test only asserts sampled_from_cells < 50, which would still pass if the implementation regresses to doing 40–49 random probes before falling back. Tightening this assertion to the expected upper bound for the near-full shortcut would make the test more robust at catching regressions in the optimization behavior it’s targeting.
| assert sampled_from_cells < 50 | |
| assert sampled_from_cells <= 10 |
|
Addressed Copilot feedback in the latest update:
Also, the Ubuntu 3.12 failure appears to be the existing flaky visualization test (test_virus_on_network_model), unrelated to this grid-only change. |
|
Performance benchmarks:
|
|
This is faster for one but not the other benchmark. Check #1565 for past work on this. I am closing this PR and first would like to see a good discussion building on the work on both mesa and agentjl. |
|
I agree with closing #3619. I'll open a benchmark-first discussion that builds directly on #1565 and the Agents.jl approach, define acceptance criteria up front, and add a reproducible benchmark script in-repo so cutoff choices are evidence-based and easy to recompute across Python versions. After agreement on methodology, I'll submit a focused implementation PR with model-level and microbenchmark results, with an explicit pass/fail criterion on Schelling large run time to guard against regressions. |
Summary
Why
The current implementation uses up to 50 random probes before fallback. On near-full grids this can spend many failed probes before doing deterministic selection. This PR reduces that waste while preserving existing behavior and errors.
Scope
Validation
Overlap check