Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix draw_network: Handle multiple agents per node correctly (#2691) #2693

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions mesa/visualization/mpl_space_drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,17 +483,45 @@ def draw_network(
x_padding = width / 20
y_padding = height / 20

node_to_agents = {}
for agent in space.agents: # ✅ Directly access the agent list
if hasattr(agent, "pos"): # Ensure agent has a position
if agent.pos not in node_to_agents:
node_to_agents[agent.pos] = []
node_to_agents[agent.pos].append(agent)

# Adjust positions for multiple agents per node
adjusted_positions = []
for agent in space.agents: # ✅ Correct way to iterate through agents
if (
hasattr(agent, "pos") and agent.pos in pos
): # Ensure the agent has a valid position
base_x, base_y = pos[agent.pos] # ✅ Get node position correctly
agents_at_node = node_to_agents.get(agent.pos, [])
num_agents = len(agents_at_node)

# Spread agents to avoid overlap
i = node_to_agents[agent.pos].index(agent) # Find agent index at node
angle = (2 * np.pi * i) / max(1, num_agents)
offset_x = 0.05 * np.cos(angle)
offset_y = 0.05 * np.sin(angle)
adjusted_positions.append((agent, (base_x + offset_x, base_y + offset_y)))

# gather agent data
s_default = (180 / max(width, height)) ** 2
arguments = collect_agent_data(space, agent_portrayal, size=s_default)

# this assumes that nodes are identified by an integer
# which is true for default nx graphs but might user changeable
pos = np.asarray(list(pos.values()))
arguments["loc"] = pos[arguments["loc"]]
# Update agent locations
if len(adjusted_positions) > 0:
arguments["loc"] = np.array(
[pos for _, pos in adjusted_positions], dtype=np.float64
).reshape(-1, 2)
else:
arguments["loc"] = np.zeros((0, 2)) # ✅ Ensure correct shape even when empty

# plot the agents
_scatter(ax, arguments, **kwargs)
if arguments["loc"].shape[0] > 0:
_scatter(ax, arguments, **kwargs)

# further styling
ax.set_axis_off()
Expand Down
Loading