From 0f7866d5e30284df6c508ecbad1cc571e0c153fa Mon Sep 17 00:00:00 2001 From: Ewout ter Hoeven Date: Tue, 23 Apr 2024 20:56:50 +0200 Subject: [PATCH 1/2] Make agent move to actual random closest position This fixes a bug in which move_agent_to_one_of is deterministic when pos has multiple closest choices and selection="closest". --- mesa/space.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mesa/space.py b/mesa/space.py index b9044387234..6ce58e77dbe 100644 --- a/mesa/space.py +++ b/mesa/space.py @@ -461,7 +461,7 @@ def move_agent_to_one_of( # Find the closest position without sorting all positions closest_pos = None min_distance = float("inf") - for p in pos: + for p in agent.random.shuffle(pos): distance = self._distance_squared(p, current_pos) if distance < min_distance: min_distance = distance From 0521dd7f26f0fd156281d3970a17986f0cef4b40 Mon Sep 17 00:00:00 2001 From: Ewout ter Hoeven Date: Tue, 23 Apr 2024 21:06:07 +0200 Subject: [PATCH 2/2] Correctly shuffle pos list The function `random.shuffle` from Python's random module does not return any value; it modifies the list `pos` in-place. Therefore, `agent.random.shuffle(pos)` results in `None`, and trying to iterate over `None` leads to the error you're seeing. This commit fixes this error. --- mesa/space.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mesa/space.py b/mesa/space.py index 6ce58e77dbe..2be9503eef7 100644 --- a/mesa/space.py +++ b/mesa/space.py @@ -461,7 +461,8 @@ def move_agent_to_one_of( # Find the closest position without sorting all positions closest_pos = None min_distance = float("inf") - for p in agent.random.shuffle(pos): + agent.random.shuffle(pos) + for p in pos: distance = self._distance_squared(p, current_pos) if distance < min_distance: min_distance = distance