Skip to content

Commit 1bd9537

Browse files
puer-robustusrht
authored andcommitted
warn if placing already placed agent
While it might be desired in a specific model to have the same agent be placed in multiple spots simultaneously, the typical use case is that one agent has one position at every given moment. This commit decorates the place_agent() method in a way that it emits a warning when called with an agent which already has a location. Fixes: #1522
1 parent 57d9cb5 commit 1bd9537

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

mesa/space.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,21 @@ def is_integer(x: Real) -> bool:
7171
return isinstance(x, _types_integer)
7272

7373

74+
def warn_if_agent_has_position_already(placement_func):
75+
def wrapper(self, agent, *args, **kwargs):
76+
if agent.pos is not None:
77+
warnings.warn(
78+
f"""Agent {agent.unique_id} is being placed with
79+
place_agent() despite already having the position {agent.pos}. In most
80+
cases, you'd want to clear the current position with remove_agent()
81+
before placing the agent again.""",
82+
stacklevel=2,
83+
)
84+
placement_func(self, agent, *args, **kwargs)
85+
86+
return wrapper
87+
88+
7489
class _Grid:
7590
"""Base class for a rectangular grid.
7691
@@ -976,6 +991,7 @@ class SingleGrid(_PropertyGrid):
976991
the grid for empty spaces.
977992
"""
978993

994+
@warn_if_agent_has_position_already
979995
def place_agent(self, agent: Agent, pos: Coordinate) -> None:
980996
"""Place the agent at the specified location, and set its pos variable."""
981997
if self.is_cell_empty(pos):
@@ -1024,6 +1040,7 @@ def default_val() -> MultiGridContent:
10241040
"""Default value for new cell elements."""
10251041
return []
10261042

1043+
@warn_if_agent_has_position_already
10271044
def place_agent(self, agent: Agent, pos: Coordinate) -> None:
10281045
"""Place the agent at the specified location, and set its pos variable."""
10291046
x, y = pos
@@ -1355,6 +1372,7 @@ def _invalidate_agent_cache(self):
13551372
self._agent_points = None
13561373
self._index_to_agent = {}
13571374

1375+
@warn_if_agent_has_position_already
13581376
def place_agent(self, agent: Agent, pos: FloatCoordinate) -> None:
13591377
"""Place a new agent in the space.
13601378
@@ -1515,6 +1533,7 @@ def default_val() -> list:
15151533
"""Default value for a new node."""
15161534
return []
15171535

1536+
@warn_if_agent_has_position_already
15181537
def place_agent(self, agent: Agent, node_id: int) -> None:
15191538
"""Place an agent in a node."""
15201539
self.G.nodes[node_id]["agent"].append(agent)

0 commit comments

Comments
 (0)