Skip to content

Optimize near-full Grid empty-cell selection - #3619

Closed
yassinekolsi wants to merge 3 commits into
mesa:mainfrom
yassinekolsi:optimize-grid-empty-selection-near-full
Closed

yassinekolsi wants to merge 3 commits into
mesa:mainfrom
yassinekolsi:optimize-grid-empty-selection-near-full

Conversation

@yassinekolsi

Copy link
Copy Markdown
Contributor

Summary

  • optimize Grid.select_random_empty_cell for near-full grids
  • keep random probing for sparse grids (fast path)
  • after a few misses, estimate empty-cell count once and skip excessive random retries when grid is near full
  • keep deterministic fallback using the empty property layer
  • add a test verifying near-full path avoids exhaustive random sampling and still returns the correct empty cell

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

  • Atomic change: only empty-cell selection heuristic in Grid
  • Files changed: 2

Validation

  • syntax-checked modified files with python3 -m py_compile
  • added focused test in tests/discrete_space/test_discrete_space.py

Overlap check

  • Checked open PRs/issues for select_random_empty_cell and random empty cell topics
  • No open PR found with this specific optimization

Copilot AI review requested due to automatic review settings March 23, 2026 10:42

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_cell to 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_index rather than np.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.

Comment thread mesa/discrete_space/grid.py Outdated
Comment on lines +294 to +307
# 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."
)

Copilot AI Mar 23, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment thread mesa/discrete_space/grid.py Outdated
Comment on lines +300 to +321
# 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)]
)

Copilot AI Mar 23, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.

assert selected_cell.coordinate == target_empty
# Old behavior always sampled 50 times before fallback; near-full now skips that.
assert sampled_from_cells < 50

Copilot AI Mar 23, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
assert sampled_from_cells < 50
assert sampled_from_cells <= 10

Copilot uses AI. Check for mistakes.
@yassinekolsi

Copy link
Copy Markdown
Contributor Author

Addressed Copilot feedback in the latest update:

  1. Deferred O(n) scan further to preserve cheap probing behavior.
  • Increased the pre-scan random probe window from 5 to 10.
  • Kept total random attempts at 50 for non-near-full grids.
  1. Removed duplicate full-mask scans.
  • The random branch now computes empty indices once with np.flatnonzero(empty_mask).
  • Uses .size for count, full-grid check, and deterministic fallback selection.
  1. Tightened and expanded regression tests.
  • Near-full test now asserts random probes are <= 10.
  • Added a non-near-full test that verifies the code continues random probing up to 50 attempts before fallback.

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.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.9% [-1.4%, -0.3%] 🔵 +1.7% [+1.4%, +1.9%]
BoltzmannWealth large 🔵 -1.3% [-2.1%, -0.4%] 🔵 -0.4% [-3.2%, +2.1%]
Schelling small 🔵 -2.9% [-3.6%, -2.1%] 🔵 -1.5% [-2.3%, -0.7%]
Schelling large 🔵 -2.2% [-3.0%, -1.3%] 🔴 +10.9% [+8.2%, +13.7%]
WolfSheep small 🟢 -4.9% [-5.6%, -4.2%] 🔵 +1.2% [-3.0%, +5.1%]
WolfSheep large 🟢 -6.7% [-8.2%, -5.1%] 🟢 -21.7% [-23.2%, -20.1%]
SugarscapeG1mt small 🟢 -6.4% [-7.1%, -5.9%] 🔵 -4.0% [-5.6%, -2.2%]
SugarscapeG1mt large 🟢 -10.4% [-12.0%, -8.8%] 🟢 -8.1% [-10.3%, -5.6%]
BoidFlockers small 🔵 -0.7% [-1.1%, -0.3%] 🔵 +0.6% [+0.1%, +1.2%]
BoidFlockers large 🔵 +1.3% [+0.9%, +1.7%] 🔵 +0.6% [+0.4%, +0.9%]

@quaquel

quaquel commented Mar 23, 2026

Copy link
Copy Markdown
Member

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.

@quaquel quaquel closed this Mar 23, 2026
@yassinekolsi

Copy link
Copy Markdown
Contributor Author

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.

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 this pull request may close these issues.

3 participants