Skip to content

Commit

Permalink
Simplify code in ContinuousSpace (projectmesa#1536)
Browse files Browse the repository at this point in the history
* Simplify code in ContinuousSpace

* Update space.py
  • Loading branch information
Tortar authored Nov 24, 2022
1 parent 63be75f commit c9f10a6
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions mesa/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,13 +849,11 @@ def __init__(
def _build_agent_cache(self):
"""Cache agents positions to speed up neighbors calculations."""
self._index_to_agent = {}
agents = self._agent_to_index.keys()
for idx, agent in enumerate(agents):
for idx, agent in enumerate(self._agent_to_index):
self._agent_to_index[agent] = idx
self._index_to_agent[idx] = agent
self._agent_points = np.array(
[self._index_to_agent[idx].pos for idx in range(len(agents))]
)
# Since dicts are ordered by insertion, we can iterate through agents keys
self._agent_points = np.array([agent.pos for agent in self._agent_to_index])

def _invalidate_agent_cache(self):
"""Clear cached data of agents and positions in the space."""
Expand Down Expand Up @@ -888,8 +886,7 @@ def move_agent(self, agent: Agent, pos: FloatCoordinate) -> None:
# instead of invalidating the full cache,
# apply the move to the cached values
idx = self._agent_to_index[agent]
self._agent_points[idx, 0] = pos[0]
self._agent_points[idx, 1] = pos[1]
self._agent_points[idx] = pos

def remove_agent(self, agent: Agent) -> None:
"""Remove an agent from the space.
Expand All @@ -899,7 +896,7 @@ def remove_agent(self, agent: Agent) -> None:
"""
if agent not in self._agent_to_index:
raise Exception("Agent does not exist in the space")
self._agent_to_index.pop(agent)
del self._agent_to_index[agent]

self._invalidate_agent_cache()
agent.pos = None
Expand Down

0 comments on commit c9f10a6

Please sign in to comment.