mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Grid2DMovingAgent.move / HexGridMovingAgent.move leave the agent partway when a multi-cell move fails

Open RITVIKKAMASETTY opened this issue 2 weeks ago • 11 comments

Describe the bug Grid2DMovingAgent.move(direction, distance) and HexGridMovingAgent.move(direction, distance) move one cell at a time by calling move_relative() in a loop, and each step moves the agent immediately. If a later step has no cell to move into (for example, the edge of a non-torus grid), the method raises, but the agent has already moved part of the way. The caller gets an error and an agent in a position it never asked for.

Expected behavior A move that fails should leave the agent where it was. The target cell should be found first, and the agent moved only once the whole move is known to be possible.

To Reproduce

from mesa import Model
from mesa.discrete_space import (
    CellAgent,
    Grid2DMovingAgent,
    HexGrid,
    HexGridMovingAgent,
    OrthogonalMooreGrid,
)

model = Model(rng=42)

# 1. Square grid: the move fails, but the agent has already moved
grid = OrthogonalMooreGrid((5, 5), torus=False, random=model.random)
agent = Grid2DMovingAgent(model)
agent.cell = grid[(2, 2)]
try:
    agent.move("east", distance=5)  # only 2 cells to the edge
except Exception as e:
    print(f"{type(e).__name__}: {e}")
print(agent.cell.coordinate)  # expected (2, 2)

# 2. Hex grid: same behavior
hex_grid = HexGrid((5, 5), torus=False, random=model.random)
hex_agent = HexGridMovingAgent(model)
hex_agent.cell = hex_grid[(2, 2)]
try:
    hex_agent.move("e", distance=5)
except Exception as e:
    print(f"{type(e).__name__}: {e}")
print(hex_agent.cell.coordinate)  # expected (2, 2)

# 3. A full cell on the way blocks the move, even though the destination is empty
grid1 = OrthogonalMooreGrid((5, 5), torus=False, random=model.random, capacity=1)
mover = Grid2DMovingAgent(model)
mover.cell = grid1[(2, 0)]
blocker = CellAgent(model)
blocker.cell = grid1[(2, 1)]
try:
    mover.move("east", distance=2)  # destination (2, 2) is empty
except Exception as e:
    print(f"{type(e).__name__}: {e}")
print(mover.cell.coordinate, grid1[(2, 2)].is_empty)

Output on current main:

ValueError: No cell in direction (0, 1)
(2, 4)
ValueError: No cell in direction (1, 0)
(4, 2)
CellFullException: Cell at coordinate (2, 1) is full.
(2, 0) True

In cases 1 and 2 the agent ends up 2 cells from where it started, even though the move raised.

Additional context This affects any model where agents move more than one cell per step (fast predators, vehicles, "flee N cells") on a non-torus grid. A model that catches the error and tries another direction or a shorter move does so from the wrong cell, which silently changes its results. No existing test covers distance > 1.

A possible fix: walk cell.connections from the current cell to find the target first, and only assign self.cell = target once every step exists. If a step is missing, raise before anything changes. #4001 (moving an agent that has no cell) touches the same move_relative() path, and the discussion there settled on SpaceException rather than ValueError for this kind of error, so the fix could raise that too.

Case 3 is a design question I'd like input on: should a multi-cell move be blocked by a full cell on the way, or should only the destination's capacity matter? Today the intermediate cell blocks it. With the "find target, then move once" fix, only the destination would matter, unless the path is also checked.

I'm happy to open a PR once the direction for case 3 is clear.

  • Mesa: 4.0.0a0 (current main, e1ca9eac)
  • Python: 3.13

RITVIKKAMASETTY avatar Nov 15 '26 06:11 RITVIKKAMASETTY

@EwoutH can you please guide me here

RITVIKKAMASETTY avatar Nov 15 '26 06:11 RITVIKKAMASETTY

Describe the bug Grid2DMovingAgent.move(direction, distance) and HexGridMovingAgent.move(direction, distance) move one cell at a time by calling move_relative() in a loop, and each step moves the agent immediately. If a later step has no cell to move into (for example, the edge of a non-torus grid), the method raises, but the agent has already moved part of the way. The caller gets an error and an agent in a position it never asked for.

Expected behavior A move that fails should leave the agent where it was. The target cell should be found first, and the agent moved only once the whole move is known to be possible.

I don't think if I agree that should be the expected behavior. The agent moved in the direction, as far as it could, untill it couldn't anymore. Sounds like the intended behavior of the function.

What we could do is add a switch, something like only_complete (default false), which if set true would only perform complete moves.

But I don't think the current behavior is necessarily wrong or unintended.

@quaquel @codebreaker32 what do you think?

EwoutH avatar Nov 15 '26 08:11 EwoutH

@EwoutH Thanks. If "move as far as possible" is the intended behavior, I'm fine keeping it as the default.

The part that seems inconsistent to me is that it moves partway and raises. If the partial move is intended, the caller still gets an error saying the move failed, and has to check agent.cell to find out how far it actually got. A couple of options:

Add only_complete (default False) as you suggest. With True, it checks the whole path first and raises without moving if it can't complete. With False, it keeps today's behavior. Additionally, document the current behavior in the move docstrings (it stops at the last reachable cell and then raises), since that isn't stated anywhere right now and there are no tests for distance > 1. Happy to implement whichever you and @quaquel / @codebreaker32 prefer. I'd also add tests for distance > 1 either way.

RITVIKKAMASETTY avatar Nov 16 '26 14:11 RITVIKKAMASETTY

The part that seems inconsistent to me is that it moves partway and raises.

Fair.

I would say:

  • allow_partial_move=True moves as far as it can and doesn't raise, partial move is intended behavior (default)
  • allow_partial_move=False doesn't move and raises (and possibly catch the error)

EwoutH avatar Nov 16 '26 18:11 EwoutH

The part that seems inconsistent to me is that it moves partway and raises.

Fair.

I would say:

  • allow_partial_move=True moves as far as it can and doesn't raise, partial move is intended behavior (default)
  • allow_partial_move=False doesn't move and raises (and possibly catch the error)

Sounds good, thanks. Before I start, a few details to confirm:

With allow_partial_move=True as the default, move() would no longer raise when it runs out of cells, which changes current behavior for code that catches that error. Is that OK as is, or should it be noted in the changelog / migration guide? Should move() return the number of cells actually moved? Then with the default, a caller can still tell a partial or zero-length move apart without an exception. A full cell on the way (capacity): with True the agent stops before it; with False it raises without moving. Does that match what you had in mind? For False, which exception: keep ValueError, or SpaceException in line with the discussion in #4001? Happy to open a PR once these are settled, with tests for distance > 1 on both Grid2DMovingAgent and HexGridMovingAgent.

and I was looking for issues if you want me to look into anything please let me know

RITVIKKAMASETTY avatar Nov 18 '26 13:11 RITVIKKAMASETTY

Maybe False can also be the default (I might have swapped them in my head. @quaquel do you have an opinion?

EwoutH avatar Nov 18 '26 19:11 EwoutH

I would favor False. Basically, when in doubt, refuse the temptation to guess. So, you can't complete the full move, so you raise an exception and leave it to the user to handle it.

quaquel avatar Nov 18 '26 19:11 quaquel

@EwoutH is there any community group to join and I was looking for issues if you want me look into anything please let me know

RITVIKKAMASETTY avatar Nov 19 '26 14:11 RITVIKKAMASETTY

One detail that may help settle the capacity case: the current example starts the mover at (2, 0) and puts the blocker at (2, 1), so the move fails on its first step. It doesn't test a capacity failure after the agent has already moved.

If allow_partial_move=False is meant to be atomic for capacity failures too, a case with (2, 1) open and (2, 2) full would test that: should the mover remain at (2, 0)?

For allow_partial_move=True, should it stop at (2, 1) and return normally?

Jenil1905 avatar Nov 19 '26 17:11 Jenil1905

Hi @EwoutH @quaquel, I would like to work on this issue and implement the agreed design:

  • llow_partial_move=False (default): raises without moving the agent if the full path cannot be completed (whether due to grid bounds or cell capacity), keeping multi-cell movement atomic.
  • llow_partial_move=True: moves as far as possible along the path until blocked and returns without raising.
  • Add comprehensive regression tests covering distance > 1 on both Grid2DMovingAgent and HexGridMovingAgent.

Could you please assign this issue to me?

shubham-x06 avatar Nov 23 '26 08:11 shubham-x06

Hi @shubham-x06, just a heads-up: I opened #4149 for this same change (allow_partial_move with whole-path validation for #4099), and quaquel closed it because the new movement API needs to be settled first:

There is still an open discussion on this. I am closing this PR. We first need to resolve the new API before making other changes.

The discussion is here: https://github.com/mesa/mesa/discussions/2967#discussioncomment-19664291

Since this PR changes the same move() methods, the same probably applies here, so it may be worth checking that thread before putting more time into it.

RITVIKKAMASETTY avatar Nov 23 '26 13:11 RITVIKKAMASETTY