Skip to content

Commit

Permalink
Implement swap_pos
Browse files Browse the repository at this point in the history
  • Loading branch information
jnsp authored and rht committed Oct 27, 2022
1 parent 659b00a commit 373637e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
20 changes: 20 additions & 0 deletions mesa/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,26 @@ def position_agent(
coords = (x, y)
self.place_agent(agent, coords)

def swap_pos(self, agent_a: Agent, agent_b: Agent) -> None:
"""Swap agents positions"""
agents_no_pos = []
if (pos_a := agent_a.pos) is None:
agents_no_pos.append(agent_a)
if (pos_b := agent_b.pos) is None:
agents_no_pos.append(agent_b)
if agents_no_pos:
agents_no_pos = [f"<Agent id: {a.unique_id}>" for a in agents_no_pos]
raise Exception(f"{', '.join(agents_no_pos)} - not on the grid")

if pos_a == pos_b:
return

self.remove_agent(agent_a)
self.remove_agent(agent_b)

self.place_agent(agent_a, pos_b)
self.place_agent(agent_b, pos_a)

def place_agent(self, agent: Agent, pos: Coordinate) -> None:
if self.is_cell_empty(pos):
super().place_agent(agent, pos)
Expand Down
28 changes: 28 additions & 0 deletions tests/test_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,34 @@ def test_enforcement(self, mock_model):
with self.assertRaises(Exception):
self.move_to_empty(self.agents[0], num_agents=self.num_agents)

# Swap agents positions
agent_a, agent_b = random.sample(list(self.grid), k=2)
pos_a = agent_a.pos
pos_b = agent_b.pos

self.grid.swap_pos(agent_a, agent_b)

assert agent_a.pos == pos_b
assert agent_b.pos == pos_a
assert self.grid[pos_a] == agent_b
assert self.grid[pos_b] == agent_a

# Swap the same agents
self.grid.swap_pos(agent_a, agent_a)

assert agent_a.pos == pos_b
assert self.grid[pos_b] == agent_a

# Raise for agents not on the grid
self.grid.remove_agent(agent_a)
self.grid.remove_agent(agent_b)

id_a = agent_a.unique_id
id_b = agent_b.unique_id
e_message = f"<Agent id: {id_a}>, <Agent id: {id_b}> - not on the grid"
with self.assertRaisesRegex(Exception, e_message):
self.grid.swap_pos(agent_a, agent_b)


# Number of agents at each position for testing
# Initial agent positions for testing
Expand Down

0 comments on commit 373637e

Please sign in to comment.