seqBench / scripts /plot.py
emnlp-submission's picture
Upload 3 files
fb0015f verified
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import FancyArrowPatch, Rectangle
import numpy as np
from scipy.interpolate import splprep, splev
import math
def pretty_plot_maze(
maze_loader,
W=4,
H=4,
save_path=None,
model_solution=None,
ground_truth_solution=None,
mode="comparison",
):
"""
Display the maze using Matplotlib and optionally save to a file.
Args:
mode: Visualization mode
- "comparison": Side-by-side optimal vs model (default)
- "empty": Just maze structure
- "optimal": Maze + optimal path only
- "model": Maze + model path only
"""
plt.rcParams["font.size"] = 10
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["figure.dpi"] = 100
# Configure subplot layout based on mode
if mode == "comparison":
fig, (ax2, ax3) = plt.subplots(1, 2, figsize=(15, 8.5))
axes = [ax2, ax3]
elif mode == "empty":
# Special layout for empty maze with legend space
fig, ax = plt.subplots(1, 1, figsize=(14, 8.5))
axes = [ax]
else:
fig, ax = plt.subplots(1, 1, figsize=(10, 8.5))
axes = [ax]
# Draw the base maze on all plots
for ax in axes:
covered_cells = set()
for cell in maze_loader.connected_cells.keys():
for neighbor in maze_loader.connected_cells[cell]:
if (cell, neighbor) in covered_cells or (
neighbor,
cell,
) in covered_cells:
continue
covered_cells.add((cell, neighbor))
add_path_segment(
(cell[0] * W, cell[1] * H),
(neighbor[0] * W, neighbor[1] * H),
ax,
door=(cell, neighbor) in maze_loader.doors.keys(),
status=None
if (cell, neighbor) not in maze_loader.doors.keys()
else maze_loader.doors[(cell, neighbor)][0].split(" ")[0],
lock_status=(
None
if (cell, neighbor) not in maze_loader.doors.keys()
or maze_loader.doors[(cell, neighbor)][0] == "open"
else maze_loader.doors[(cell, neighbor)][0].split(" ")[-1]
),
)
# Add keys
for key_id, key_location in maze_loader.keys_locations.items():
door_locations = {
maze_loader.doors[(rA, rB)][1]: (
(rA[0] + rB[0]) * W / 2,
(rA[1] + rB[1]) * H / 2,
)
for (rA, rB) in maze_loader.doors.keys()
}
add_key(
key_location[0] * W,
key_location[1] * H,
ax,
door_location=door_locations.get(key_id, (0, 0)),
)
# Add start and end rooms
start = (
maze_loader.data["start_room"][0] * W,
maze_loader.data["start_room"][1] * H,
)
end = (maze_loader.data["end_room"][0] * W, maze_loader.data["end_room"][1] * H)
enhanced_mode = True # Use enhanced mode for all visualizations
add_start_and_end_room(start, end, ax, enhanced_mode=enhanced_mode)
# Create a mapping from room names to coordinates
room_name_to_coord = {}
for cell in maze_loader.connected_cells.keys():
room_name_to_coord[maze_loader.room_name[cell]] = cell
# Define colors for different action types
move_color_gt = "gold" # Yellow for regular movement (ground truth)
move_color_model = "mediumpurple" # Purple for regular movement (model)
start_color = "#FF7F0E" # Orange for start action
pickup_key_color = "#1E88E5" # Blue for key pickup
use_key_color = "#43A047" # Green for using a key
unlock_color = "#9C27B0" # Purple for unlocking door
rescue_color = "#D81B60" # Pink for rescue
# Draw a path with numbered steps
def process_solution(solution, ax, base_color="gold"):
if not solution:
return
all_actions = []
current_room = None
last_position = None
# Parse solution into actions
for i, action in enumerate(solution):
if len(action) < 2:
continue
action_type, param = action[0], action[1]
step_number = i + 1 # Start numbering from 1
# Track the current room for each action
if action_type == "start":
current_room = param
# Mark start position specially
all_actions.append((current_room, step_number, action_type, None))
elif action_type == "move_to" and param in room_name_to_coord:
prev_room = current_room
current_room = param
# Store movement with both source and destination
all_actions.append((current_room, step_number, action_type, prev_room))
elif action_type in [
"pick_up_key",
"use_key",
"unlock_and_open_door_to",
"rescue",
]:
if current_room:
# Store special action with current room
all_actions.append((current_room, step_number, action_type, None))
used_positions = set()
# First draw all movement paths
for room, step_number, action_type, prev_room in all_actions:
if (
action_type == "move_to"
and prev_room
and room in room_name_to_coord
and prev_room in room_name_to_coord
):
start_cell = room_name_to_coord[prev_room]
end_cell = room_name_to_coord[room]
# Get coordinates
x1, y1 = start_cell[0] * W, start_cell[1] * H
x2, y2 = end_cell[0] * W, end_cell[1] * H
# Draw the path for movement
ax.plot(
[x1, x2], [y1, y2], "-", color=base_color, linewidth=2, zorder=10, alpha=0.5
)
# Add arrow near destination
arrow_pos = 0.9
arrow_x = x1 + (x2 - x1) * arrow_pos
arrow_y = y1 + (y2 - y1) * arrow_pos
dx = x2 - x1
dy = y2 - y1
length = math.sqrt(dx * dx + dy * dy)
if length > 0:
dx /= length
dy /= length
arrow = FancyArrowPatch(
(arrow_x - dx * 0.3, arrow_y - dy * 0.3),
(arrow_x + dx * 0.3, arrow_y + dy * 0.3),
arrowstyle="-|>",
mutation_scale=12,
color=base_color,
linewidth=2,
zorder=10,
alpha=0.4,
)
ax.add_patch(arrow)
# Then add step markers for each action
for action_idx, (room, step_number, action_type, prev_room) in enumerate(
all_actions
):
if room in room_name_to_coord:
room_cell = room_name_to_coord[room]
# Determine position and color based on action type
if (
action_type == "move_to"
and prev_room
and prev_room in room_name_to_coord
):
# For movement, place marker along the path
start_cell = room_name_to_coord[prev_room]
end_cell = room_name_to_coord[room]
x1, y1 = start_cell[0] * W, start_cell[1] * H
x2, y2 = end_cell[0] * W, end_cell[1] * H
pos_x = x1 + (x2 - x1) * 0.6
pos_y = y1 + (y2 - y1) * 0.6
# Add perpendicular offset to avoid placing directly on line
dx = x2 - x1
dy = y2 - y1
length = math.sqrt(dx * dx + dy * dy)
if length > 0:
perp_x = -dy / length * 0.7
perp_y = dx / length * 0.7
# Alternate sides for consecutive steps
if step_number % 2 == 0:
perp_x = -perp_x
perp_y = -perp_y
pos_x += perp_x
pos_y += perp_y
color = base_color
else:
# For non-movement actions, place at the room with offset
pos_x = room_cell[0] * W
pos_y = room_cell[1] * H
# Special case for door-related actions - place them near but not at the door
if action_type in ["use_key", "unlock_and_open_door_to"]:
door_cell1 = room_cell
door_cell2 = None
if action_type == "unlock_and_open_door_to":
# Find the destination room for the door
dest_room = param
if dest_room in room_name_to_coord:
door_cell2 = room_name_to_coord[dest_room]
elif prev_room in room_name_to_coord:
# For use_key, consider the previous room as second door cell
door_cell2 = room_name_to_coord[prev_room]
if door_cell2:
# Calculate door position (midpoint between rooms)
door_x = (door_cell1[0] + door_cell2[0]) * W / 2
door_y = (door_cell1[1] + door_cell2[1]) * H / 2
# Calculate vector from door to room (normalized)
dx = pos_x - door_x
dy = pos_y - door_y
dist = math.sqrt(dx * dx + dy * dy)
if dist > 0:
# Normalize vector
dx /= dist
dy /= dist
# Position marker at 2/3 distance from door to room
pos_x = (
door_x + dx * 1.5
) # Place partway from door toward room
pos_y = door_y + dy * 1.5
# Add small perpendicular offset to avoid direct overlap with path
perp_x = -dy * 0.5
perp_y = dx * 0.5
# Alternate sides for consecutive markers
if step_number % 2 == 0:
perp_x = -perp_x
perp_y = -perp_y
pos_x += perp_x
pos_y += perp_y
else:
# Fallback if rooms are at same location
offset_x = 0.7 * (1 if step_number % 2 == 0 else -1)
offset_y = 0.7 * (1 if step_number % 4 >= 2 else -1)
pos_x += offset_x
pos_y += offset_y
else:
# If second door cell not found, use standard offset from room
offset_x = 0.7 * (1 if step_number % 2 == 0 else -1)
offset_y = 0.7 * (1 if step_number % 4 >= 2 else -1)
pos_x += offset_x
pos_y += offset_y
else:
# Regular offset for other action types
if action_type == "start":
# Start marker at top-left of room
offset_x, offset_y = -0.7, -0.7
else:
# Other actions - different offsets for different action types
offset_multiplers = {
"pick_up_key": (0.7, 0.7),
"rescue": (-0.7, -0.7),
}
multiplier = offset_multiplers.get(action_type, (0, 0))
offset_x, offset_y = multiplier
# Further vary offsets for multiple actions in same room
same_room_actions = sum(
1
for r, _, a_type, _ in all_actions[:action_idx]
if r == room and a_type != "move_to"
)
if same_room_actions > 0:
offset_x *= 1 + 0.3 * same_room_actions
offset_y *= 1 + 0.3 * same_room_actions
pos_x += offset_x
pos_y += offset_y
# Determine color for special actions - now with distinct colors for all types
if action_type == "start":
color = start_color
elif action_type == "pick_up_key":
color = pickup_key_color
elif action_type == "use_key":
color = use_key_color
elif action_type == "unlock_and_open_door_to":
color = unlock_color
elif action_type == "rescue":
color = rescue_color
else:
color = base_color
# Avoid overlap with existing markers
while any(
(abs(pos_x - px) < 0.8 and abs(pos_y - py) < 0.8)
for px, py in used_positions
):
# Slightly adjust position
pos_x += 0.3 * (1 if step_number % 2 == 0 else -1)
pos_y += 0.3 * (1 if step_number % 4 >= 2 else -1)
# Add marker
# ax.text(
# pos_x,
# pos_y,
# f"{step_number}",
# color="white",
# fontsize=3,
# ha="center",
# va="center",
# bbox=dict(
# boxstyle="circle,pad=0.3",
# fc=color,
# ec="black",
# alpha=0.9,
# linewidth=1,
# ),
# zorder=20,
# )
# Remember this position
used_positions.add((pos_x, pos_y))
title_props = dict(fontsize=12, fontweight="bold")
# Set titles and process solutions based on mode
if mode == "comparison":
axes[0].set_title("Optimal Path", **title_props)
axes[1].set_title("Model Path", **title_props)
if ground_truth_solution:
process_solution(ground_truth_solution, axes[0], base_color=move_color_gt)
if model_solution:
process_solution(model_solution, axes[1], base_color=move_color_model)
elif mode == "empty":
axes[0].set_title("Maze Layout", **title_props)
# No paths to process for empty maze
elif mode == "optimal":
axes[0].set_title("Optimal Path", **title_props)
if ground_truth_solution:
process_solution(ground_truth_solution, axes[0], base_color=move_color_gt)
elif mode == "model":
axes[0].set_title("Model Path", **title_props)
if model_solution:
process_solution(model_solution, axes[0], base_color=move_color_model)
for ax in axes:
ax.set_xticks([])
ax.set_yticks([])
ax.axis("off")
current_xlim = ax.get_xlim()
current_ylim = ax.get_ylim()
ax.set_xlim(current_xlim[0] - 1, current_xlim[1] + 1)
ax.set_ylim(current_ylim[0] - 3, current_ylim[1] + 1)
# Add legend for empty maze mode (enhanced for LLM interpretability)
if mode == "empty":
# Clean, simple title
axes[0].set_title("Maze Navigation: Find path from START (green) to GOAL (red)",
fontsize=12, fontweight='bold', pad=20)
legend_elements = [
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='limegreen',
markersize=12, markeredgecolor='darkgreen', markeredgewidth=2, label='START'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='red',
markersize=12, markeredgecolor='darkred', markeredgewidth=2, label='GOAL'),
plt.Rectangle((0, 0), 1, 1, facecolor='red', alpha=0.8, label='locked door'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='yellow',
markersize=10, markeredgecolor='orange', markeredgewidth=2, label='key'),
]
axes[0].legend(handles=legend_elements, loc='center left', bbox_to_anchor=(0.95, 0.5),
frameon=True, fancybox=True, shadow=False, fontsize=9)
# Only add path legend for non-empty modes
if mode != "empty":
legend_items = [
("Start", start_color),
("Move", move_color_gt if ground_truth_solution else move_color_model),
("Key pickup", pickup_key_color),
("Use key", use_key_color),
("Unlock door", unlock_color),
("Rescue", rescue_color),
]
legend_patches = [
plt.Rectangle((0, 0), 1, 1, fc=color, ec="black", alpha=0.9)
for _, color in legend_items
]
# fig.legend(
# legend_patches,
# [text for text, _ in legend_items],
# loc="lower center",
# bbox_to_anchor=(0.5, 0.02),
# ncol=len(legend_items),
# frameon=True,
# fancybox=True,
# shadow=True,
# fontsize=10,
# )
# Handle layout based on mode
if mode == "empty":
plt.tight_layout()
# Adjust layout to accommodate legend with less gap
plt.subplots_adjust(right=0.90)
else:
plt.tight_layout()
if save_path is not None:
try:
plt.savefig(save_path, dpi=400, bbox_inches="tight", format="png")
except Exception as e:
print(f"Error saving plot: {e}")
plt.close(fig)
def draw_path_with_arrow(
point1,
point2,
ax,
color="red",
linewidth=1.5,
alpha=0.8,
arrow_size=5,
arrow_color=None,
):
"""Draw a path between two points with a smaller, more subtle directional arrow."""
if arrow_color is None:
arrow_color = color
# Calculate the midpoint for the arrow position - shift slightly toward destination
# to avoid overlap with nodes
midpoint_x = point1[0] + (point2[0] - point1[0]) * 0.6
midpoint_y = point1[1] + (point2[1] - point1[1]) * 0.6
# Draw the line
line = ax.plot(
[point1[0], point2[0]],
[point1[1], point2[1]],
color=color,
linewidth=linewidth,
alpha=alpha,
)[0]
# Calculate the direction vector
dx = point2[0] - point1[0]
dy = point2[1] - point1[1]
# Normalize the direction vector
length = np.sqrt(dx**2 + dy**2)
if length > 0:
dx /= length
dy /= length
# Add a small arrow
ax.arrow(
midpoint_x,
midpoint_y,
dx * arrow_size / 3,
dy * arrow_size / 3,
head_width=arrow_size * 0.8,
head_length=arrow_size * 0.8,
fc=arrow_color,
ec=arrow_color,
alpha=alpha,
length_includes_head=True,
)
return line
def add_arc_between_points(point1, point2, ax, alpha=0.2):
# Use spline of degree 2 (since m = 3)
tck, _ = splprep(
[
[point1[0], (point1[0] + point2[0]) / 2.0 - alpha, point2[0]],
[point1[1], (point1[1] + point2[1]) / 2.0 + alpha, point2[1]],
],
s=0,
k=2,
)
t = np.linspace(0, 1, 100)
x_spline, y_spline = splev(t, tck)
# Plot
ax.plot(x_spline, y_spline, label="Spline curve", linestyle="--")
def add_door(
x_center, y_center, ax, status="closed", door_color="black", door_location=(0, 0)
):
# make a hallow rectangle
x1 = x_center - 0.2
x2 = x_center + 0.2
y1 = y_center - 0.4
y2 = y_center + 0.4
if status == "open":
# make the fill color transparent
rect = patches.Polygon(
[[x1, y1], [x2, y1], [x2, y2], [x1, y2]],
closed=True,
edgecolor="black",
facecolor="none",
)
else:
rect = patches.Polygon(
[[x1, y1], [x2, y1], [x2, y2], [x1, y2]], closed=True, facecolor=door_color
)
ax.add_patch(rect)
def h_link(
x1,
x2,
y,
ax,
door=False,
status="closed",
lock_status="unlocked",
line_color="#76b5c5",
):
# make sure it is brought to the front of all other patches z_order = 100
ax.add_patch(patches.Circle((x1, y), 0.3, facecolor="black", zorder=100000))
ax.add_patch(patches.Circle((x2, y), 0.3, facecolor="black", zorder=100000))
x1 = x1 - 0.05
x2 = x2 + 0.05
y = y - 0.05
rect = patches.Polygon(
[[x1, y], [x2, y], [x2, y + 0.1], [x1, y + 0.1]],
closed=True,
facecolor=line_color,
)
ax.add_patch(rect)
x_center = (x1 + x2) / 2.0 + 0.05
if door:
if status == "open":
add_door(x_center, y + 0.05, ax, status="open")
else:
if lock_status == "locked":
door_color = "red"
else:
door_color = "green"
add_door(x_center, y + 0.05, ax, status="closed", door_color=door_color)
# add circles at both ends of the line
def v_link(
x,
y1,
y2,
ax,
door=False,
status="closed",
lock_status="locked",
line_color="#76b5c5",
):
# make sure it is brought to the front of all other patches z_order = 100
ax.add_patch(patches.Circle((x, y1), 0.3, facecolor="black", zorder=100000))
ax.add_patch(patches.Circle((x, y2), 0.3, facecolor="black", zorder=100000))
y1 = y1 - 0.05
y2 = y2 + 0.05
x = x - 0.05
triangle = patches.Polygon(
[[x, y1], [x, y2], [x + 0.1, y2], [x + 0.1, y1]],
closed=True,
facecolor=line_color,
)
ax.add_patch(triangle)
y_center = (y1 + y2) / 2.0
if door:
if status == "open":
add_door(x + 0.05, y_center, ax, status="open")
else:
if lock_status == "locked":
door_color = "red"
else:
door_color = "green"
add_door(x + 0.05, y_center, ax, status="closed", door_color=door_color)
# add circles at both ends of the line
def add_start_and_end_room(start_room, end_room, ax, size=0.6, enhanced_mode=False):
if enhanced_mode:
# Enhanced mode for LLM interpretability - clean colored circles only
x, y = start_room
# Start room: Large green circle (no text)
ax.add_patch(patches.Circle((x, y), size*1.5, facecolor="limegreen", edgecolor="darkgreen", linewidth=3, zorder=100000))
x, y = end_room
# End room: Large red circle (no text)
ax.add_patch(patches.Circle((x, y), size*1.5, facecolor="red", edgecolor="darkred", linewidth=3, zorder=100000))
else:
# Original mode: black triangles
x, y = start_room
ax.add_patch(
patches.Polygon(
[[x - size, y - size], [x + size, y - size], [x, y + size]],
closed=True,
facecolor="black",
edgecolor="black",
zorder=100000,
)
)
x, y = end_room
ax.add_patch(
patches.Polygon(
[[x - size, y + size], [x + size, y + size], [x, y - size]],
closed=True,
facecolor="black",
edgecolor="black",
zorder=100000,
)
)
def add_path_segment(
point1, point2, ax, door=False, status="closed", lock_status="locked"
):
if point1[0] == point2[0]:
v_link(point1[0], point1[1], point2[1], ax, door, status, lock_status)
else:
h_link(point1[0], point2[0], point1[1], ax, door, status, lock_status)
def add_key(x, y, ax, door_location=(0, 0)):
# Enhanced key visualization - yellow circle
ax.add_patch(
patches.Circle((x, y), 0.4, facecolor="yellow", edgecolor="orange", linewidth=2, zorder=100000)
)
add_arc_between_points((x, y), door_location, ax)
if __name__ == "__main__":
# Create a plot
fig, ax = plt.subplots()
add_path_segment((1, 1), (1, 4), ax, door=True, status="open")
add_key(1, 4, ax, door_location=(2.5, 4))
add_path_segment(
(1, 4), (4, 4), ax, door=True, status="closed", lock_status="locked"
)
add_path_segment((4, 4), (4, 7), ax, door=False)
add_path_segment(
(4, 7), (1, 7), ax, door=True, status="closed", lock_status="unlocked"
)
ax.set_aspect("equal")
ax.axis("off")
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()
def pretty_plot_maze_vs_noise(
maze_loader,
W=4,
H=4,
save_path=None,
ground_truth_solution=None,
problem_description=None
):
"""
Display the maze using Matplotlib and optionally save to a file.
Shows three plots: Maze Layout, Ground Truth Path, and Model Path.
"""
plt.rcParams["font.size"] = 10
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["figure.dpi"] = 100
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 8.5))
# Draw the base maze on all three plots
for ax in [ax1, ax2, ax3]:
covered_cells = set()
for cell in maze_loader.connected_cells.keys():
for neighbor in maze_loader.connected_cells[cell]:
if (cell, neighbor) in covered_cells or (
neighbor,
cell,
) in covered_cells:
continue
covered_cells.add((cell, neighbor))
add_path_segment(
(cell[0] * W, cell[1] * H),
(neighbor[0] * W, neighbor[1] * H),
ax,
door=(cell, neighbor) in maze_loader.doors.keys(),
status=None
if (cell, neighbor) not in maze_loader.doors.keys()
else maze_loader.doors[(cell, neighbor)][0].split(" ")[0],
lock_status=(
None
if (cell, neighbor) not in maze_loader.doors.keys()
or maze_loader.doors[(cell, neighbor)][0] == "open"
else maze_loader.doors[(cell, neighbor)][0].split(" ")[-1]
),
)
# Add keys
for key_id, key_location in maze_loader.keys_locations.items():
door_locations = {
maze_loader.doors[(rA, rB)][1]: (
(rA[0] + rB[0]) * W / 2,
(rA[1] + rB[1]) * H / 2,
)
for (rA, rB) in maze_loader.doors.keys()
}
add_key(
key_location[0] * W,
key_location[1] * H,
ax,
door_location=door_locations.get(key_id, (0, 0)),
)
# Add start and end rooms
start = (
maze_loader.data["start_room"][0] * W,
maze_loader.data["start_room"][1] * H,
)
end = (maze_loader.data["end_room"][0] * W, maze_loader.data["end_room"][1] * H)
add_start_and_end_room(start, end, ax)