-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Inconsistent state in FixedAgent after removal #3099
Description
Describe the bug
When a FixedAgent is removed from the model using the remove() method, it is left in an inconsistent state. The agent is correctly removed from its cell's list of agents, but the agent itself retains a reference to the cell it was just removed from (i.e., agent.cell is not set to None).
Expected behavior
After an agent is removed, its cell attribute should be set to None to reflect that it is no longer in any cell. This is the behavior for the standard CellAgent.
To Reproduce
The following code demonstrates the issue. A FixedAgent is created, placed in a cell, and then removed. An assertion checking if agent.cell is None after removal will fail.
import random
from mesa import Model
from mesa.discrete_space import Cell, FixedAgent
class MyModel(Model):
pass
model = MyModel()
cell = Cell(coordinate=(0, 0), capacity=None, random=model.random)
agent = FixedAgent(model)
agent.cell = cell
print(f"Agent's cell before removal: {agent.cell.coordinate}")
print(f"Is agent in cell's agent list? {'agent' in str(cell.agents)}")
agent.remove()
print(f"Agent's cell after removal: {agent.cell.coordinate if agent.cell else 'None'}")
print(f"Is agent in cell's agent list after removal? {'agent' in str(cell.agents)}")
try:
assert agent.cell is None
print("\nAssertion passed: agent.cell is None.")
except AssertionError:
print(f"\nAssertion failed: agent.cell is not None, it is {agent.cell}")Results:
Agent's cell before removal: (0, 0)
Is agent in cell's agent list? True
Agent's cell after removal: (0, 0)
Is agent in cell's agent list after removal? False
Assertion failed: agent.cell is not None, it is Cell((0, 0), [])
Additional context
The issue appears to stem from the remove() method in the FixedAgent class in mesa/discrete_space/cell_agent.py, which does not set self.cell=None.