Datasets:
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
< 1K
Tags:
Large Language Models
LLM Evaluation
Sequential Reasoning
Scaling Laws
Synthetic Benchmarks
Commonsense Reasoning
License:
Upload 3 files
Browse files- scripts /maze_visualizer_utility.py +222 -0
- scripts /plot.py +782 -0
- scripts /spatial.py +192 -0
scripts /maze_visualizer_utility.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
Maze Visualization Utility
|
4 |
+
|
5 |
+
This script provides easy-to-use functions for visualizing mazes with optimal paths
|
6 |
+
and model solutions. Supports multiple visualization modes:
|
7 |
+
- Empty maze (just structure)
|
8 |
+
- Optimal path only
|
9 |
+
- Model path only
|
10 |
+
- Side-by-side comparison
|
11 |
+
|
12 |
+
Usage Examples:
|
13 |
+
# Side-by-side comparison (default)
|
14 |
+
python maze_visualizer_utility.py --maze_id 91 --result_file results/.../91_run3.json
|
15 |
+
|
16 |
+
# Individual plots
|
17 |
+
python maze_visualizer_utility.py --maze_id 91 --mode empty
|
18 |
+
python maze_visualizer_utility.py --maze_id 91 --mode optimal
|
19 |
+
python maze_visualizer_utility.py --maze_id 91 --result_file results/.../91_run3.json --mode model
|
20 |
+
"""
|
21 |
+
|
22 |
+
import sys
|
23 |
+
import os
|
24 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
25 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'core'))
|
26 |
+
|
27 |
+
import json
|
28 |
+
import ast
|
29 |
+
import argparse
|
30 |
+
from pathlib import Path
|
31 |
+
|
32 |
+
from core.maze_loader import MazeLoader
|
33 |
+
from plot import pretty_plot_maze
|
34 |
+
|
35 |
+
|
36 |
+
def load_maze_data(maze_id, data_dir="data/emnlp/maze_40_40_2_True"):
|
37 |
+
"""Load maze data from pickle file."""
|
38 |
+
maze_file = os.path.join(data_dir, f"{maze_id}.pkl")
|
39 |
+
if not os.path.exists(maze_file):
|
40 |
+
raise FileNotFoundError(f"Maze file not found: {maze_file}")
|
41 |
+
|
42 |
+
loader = MazeLoader(maze_file, removed_key_count=0)
|
43 |
+
return loader, maze_file
|
44 |
+
|
45 |
+
|
46 |
+
def get_optimal_solution_room_names(loader):
|
47 |
+
"""Get optimal solution in room name format (the correct format for plot.py)."""
|
48 |
+
return loader.solution_with_room_names
|
49 |
+
|
50 |
+
|
51 |
+
def load_model_solution_from_json(json_file):
|
52 |
+
"""Load model solution from JSON result file (already in room name format)."""
|
53 |
+
with open(json_file, 'r') as f:
|
54 |
+
result_data = json.load(f)
|
55 |
+
|
56 |
+
solution_str = result_data['response']
|
57 |
+
solution_list = ast.literal_eval(solution_str)
|
58 |
+
|
59 |
+
return solution_list, result_data
|
60 |
+
|
61 |
+
|
62 |
+
def visualize_maze(maze_id, result_file=None, output_path=None, mode="comparison", data_dir="data/emnlp/maze_40_40_2_True"):
|
63 |
+
"""
|
64 |
+
Main visualization function with support for different modes.
|
65 |
+
|
66 |
+
Args:
|
67 |
+
maze_id: ID of the maze (e.g., '91')
|
68 |
+
result_file: Path to JSON result file with model solution
|
69 |
+
output_path: Where to save the visualization (auto-generated if None)
|
70 |
+
mode: Visualization mode ("comparison", "empty", "optimal", "model")
|
71 |
+
data_dir: Directory containing maze .pkl files
|
72 |
+
"""
|
73 |
+
print(f"Loading maze {maze_id}...")
|
74 |
+
loader, maze_file = load_maze_data(maze_id, data_dir)
|
75 |
+
|
76 |
+
print(f"Getting optimal solution...")
|
77 |
+
optimal_solution = get_optimal_solution_room_names(loader)
|
78 |
+
|
79 |
+
model_solution = None
|
80 |
+
model_info = "optimal_only"
|
81 |
+
|
82 |
+
if result_file and mode in ["comparison", "model"]:
|
83 |
+
print(f"Loading model solution from {result_file}...")
|
84 |
+
model_solution, result_data = load_model_solution_from_json(result_file)
|
85 |
+
|
86 |
+
provider = result_data.get('provider', 'unknown')
|
87 |
+
model_name = result_data.get('model_name', 'unknown')
|
88 |
+
model_info = f"{provider}_{model_name}"
|
89 |
+
|
90 |
+
# Generate output path if not provided
|
91 |
+
if output_path is None:
|
92 |
+
if mode == "empty":
|
93 |
+
output_path = f"maze_{maze_id}_empty.png"
|
94 |
+
elif mode == "optimal":
|
95 |
+
output_path = f"maze_{maze_id}_optimal.png"
|
96 |
+
elif mode == "model":
|
97 |
+
output_path = f"maze_{maze_id}_model_{model_info}.png"
|
98 |
+
else: # comparison
|
99 |
+
output_path = f"maze_{maze_id}_comparison_{model_info}.png"
|
100 |
+
|
101 |
+
print(f"Creating {mode} visualization...")
|
102 |
+
print(f" • Maze: {maze_id}")
|
103 |
+
print(f" • Mode: {mode}")
|
104 |
+
print(f" • Start: {loader.data['start_room']} ({loader.room_name[loader.data['start_room']]})")
|
105 |
+
print(f" • End: {loader.data['end_room']} ({loader.room_name[loader.data['end_room']]})")
|
106 |
+
|
107 |
+
if mode in ["comparison", "optimal"]:
|
108 |
+
print(f" • Optimal steps: {len(optimal_solution)}")
|
109 |
+
if mode in ["comparison", "model"] and model_solution:
|
110 |
+
print(f" • Model steps: {len(model_solution)}")
|
111 |
+
|
112 |
+
pretty_plot_maze(
|
113 |
+
loader,
|
114 |
+
save_path=output_path,
|
115 |
+
model_solution=model_solution,
|
116 |
+
ground_truth_solution=optimal_solution,
|
117 |
+
mode=mode
|
118 |
+
)
|
119 |
+
|
120 |
+
print(f"Visualization saved: {output_path}")
|
121 |
+
return output_path
|
122 |
+
|
123 |
+
|
124 |
+
# Convenience functions for each mode
|
125 |
+
def plot_empty_maze(maze_id, output_path=None, data_dir="data/emnlp/maze_40_40_2_True"):
|
126 |
+
"""Plot just the maze structure without any paths."""
|
127 |
+
return visualize_maze(maze_id, mode="empty", output_path=output_path, data_dir=data_dir)
|
128 |
+
|
129 |
+
|
130 |
+
def plot_optimal_path(maze_id, output_path=None, data_dir="data/emnlp/maze_40_40_2_True"):
|
131 |
+
"""Plot maze with optimal path only."""
|
132 |
+
return visualize_maze(maze_id, mode="optimal", output_path=output_path, data_dir=data_dir)
|
133 |
+
|
134 |
+
|
135 |
+
def plot_model_path(maze_id, result_file, output_path=None, data_dir="data/emnlp/maze_40_40_2_True"):
|
136 |
+
"""Plot maze with model path only."""
|
137 |
+
return visualize_maze(maze_id, result_file=result_file, mode="model", output_path=output_path, data_dir=data_dir)
|
138 |
+
|
139 |
+
|
140 |
+
def plot_comparison(maze_id, result_file, output_path=None, data_dir="data/emnlp/maze_40_40_2_True"):
|
141 |
+
"""Plot side-by-side comparison of optimal vs model paths."""
|
142 |
+
return visualize_maze(maze_id, result_file=result_file, mode="comparison", output_path=output_path, data_dir=data_dir)
|
143 |
+
|
144 |
+
|
145 |
+
def main():
|
146 |
+
parser = argparse.ArgumentParser(description="Visualize maze solutions with different modes")
|
147 |
+
parser.add_argument("--maze_id", required=True, help="Maze ID (e.g., '91')")
|
148 |
+
parser.add_argument("--result_file", help="Path to JSON result file")
|
149 |
+
parser.add_argument("--output_path", help="Output path for visualization")
|
150 |
+
parser.add_argument("--mode", default="comparison",
|
151 |
+
choices=["comparison", "empty", "optimal", "model"],
|
152 |
+
help="Visualization mode")
|
153 |
+
parser.add_argument("--data_dir", default="data/emnlp/maze_40_40_2_True",
|
154 |
+
help="Directory containing maze files")
|
155 |
+
|
156 |
+
args = parser.parse_args()
|
157 |
+
|
158 |
+
# Validate mode requirements
|
159 |
+
if args.mode == "model" and not args.result_file:
|
160 |
+
print("Error: --result_file is required for 'model' mode")
|
161 |
+
return
|
162 |
+
|
163 |
+
if args.mode == "comparison" and not args.result_file:
|
164 |
+
print("Error: --result_file is required for 'comparison' mode")
|
165 |
+
return
|
166 |
+
|
167 |
+
visualize_maze(
|
168 |
+
maze_id=args.maze_id,
|
169 |
+
result_file=args.result_file,
|
170 |
+
output_path=args.output_path,
|
171 |
+
mode=args.mode,
|
172 |
+
data_dir=args.data_dir
|
173 |
+
)
|
174 |
+
|
175 |
+
|
176 |
+
if __name__ == "__main__":
|
177 |
+
main()
|
178 |
+
|
179 |
+
|
180 |
+
# Convenience functions for interactive use
|
181 |
+
def quick_visualize(maze_id, result_file=None, mode="comparison"):
|
182 |
+
"""Quick visualization function for interactive use."""
|
183 |
+
return visualize_maze(maze_id, result_file, mode=mode)
|
184 |
+
|
185 |
+
|
186 |
+
def show_available_mazes(data_dir="data/emnlp/maze_40_40_2_True"):
|
187 |
+
"""List available maze IDs."""
|
188 |
+
maze_files = list(Path(data_dir).glob("*.pkl"))
|
189 |
+
maze_ids = [f.stem for f in maze_files]
|
190 |
+
return sorted(maze_ids, key=int)
|
191 |
+
|
192 |
+
|
193 |
+
def demo_all_modes():
|
194 |
+
"""Demonstrate all visualization modes."""
|
195 |
+
print("MAZE VISUALIZATION MODES DEMO")
|
196 |
+
print("=" * 50)
|
197 |
+
|
198 |
+
maze_id = "91"
|
199 |
+
result_file = "results/openai_gpt5_3shot_guided_cot_effectiveB2_origB2/maze_40_40_2_True/openai/gpt-5/91_removed_keys0_locked_doors2_shuffle0.0_noise0.0_run3.json"
|
200 |
+
|
201 |
+
modes = ["empty", "optimal", "model", "comparison"]
|
202 |
+
|
203 |
+
for mode in modes:
|
204 |
+
print(f"\nCreating {mode} visualization...")
|
205 |
+
try:
|
206 |
+
if mode in ["model", "comparison"] and not os.path.exists(result_file):
|
207 |
+
print(f" Skipping {mode} - result file not found")
|
208 |
+
continue
|
209 |
+
|
210 |
+
output_path = visualize_maze(maze_id, result_file if mode in ["model", "comparison"] else None, mode=mode)
|
211 |
+
print(f" Created: {output_path}")
|
212 |
+
except Exception as e:
|
213 |
+
print(f" Error: {e}")
|
214 |
+
|
215 |
+
print(f"\nDemo completed!")
|
216 |
+
|
217 |
+
if __name__ == "__main__":
|
218 |
+
if len(sys.argv) == 1:
|
219 |
+
print("\n" + "=" * 50)
|
220 |
+
demo_all_modes()
|
221 |
+
else:
|
222 |
+
main()
|
scripts /plot.py
ADDED
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import matplotlib
|
2 |
+
|
3 |
+
matplotlib.use("Agg")
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
import matplotlib.patches as patches
|
6 |
+
from matplotlib.patches import FancyArrowPatch, Rectangle
|
7 |
+
import numpy as np
|
8 |
+
from scipy.interpolate import splprep, splev
|
9 |
+
import math
|
10 |
+
|
11 |
+
|
12 |
+
def pretty_plot_maze(
|
13 |
+
maze_loader,
|
14 |
+
W=4,
|
15 |
+
H=4,
|
16 |
+
save_path=None,
|
17 |
+
model_solution=None,
|
18 |
+
ground_truth_solution=None,
|
19 |
+
mode="comparison",
|
20 |
+
):
|
21 |
+
"""
|
22 |
+
Display the maze using Matplotlib and optionally save to a file.
|
23 |
+
|
24 |
+
Args:
|
25 |
+
mode: Visualization mode
|
26 |
+
- "comparison": Side-by-side optimal vs model (default)
|
27 |
+
- "empty": Just maze structure
|
28 |
+
- "optimal": Maze + optimal path only
|
29 |
+
- "model": Maze + model path only
|
30 |
+
"""
|
31 |
+
|
32 |
+
plt.rcParams["font.size"] = 10
|
33 |
+
plt.rcParams["font.family"] = "sans-serif"
|
34 |
+
plt.rcParams["figure.dpi"] = 100
|
35 |
+
|
36 |
+
# Configure subplot layout based on mode
|
37 |
+
if mode == "comparison":
|
38 |
+
fig, (ax2, ax3) = plt.subplots(1, 2, figsize=(15, 8.5))
|
39 |
+
axes = [ax2, ax3]
|
40 |
+
elif mode == "empty":
|
41 |
+
# Special layout for empty maze with legend space
|
42 |
+
fig, ax = plt.subplots(1, 1, figsize=(14, 8.5))
|
43 |
+
axes = [ax]
|
44 |
+
else:
|
45 |
+
fig, ax = plt.subplots(1, 1, figsize=(10, 8.5))
|
46 |
+
axes = [ax]
|
47 |
+
|
48 |
+
# Draw the base maze on all plots
|
49 |
+
for ax in axes:
|
50 |
+
covered_cells = set()
|
51 |
+
for cell in maze_loader.connected_cells.keys():
|
52 |
+
for neighbor in maze_loader.connected_cells[cell]:
|
53 |
+
if (cell, neighbor) in covered_cells or (
|
54 |
+
neighbor,
|
55 |
+
cell,
|
56 |
+
) in covered_cells:
|
57 |
+
continue
|
58 |
+
covered_cells.add((cell, neighbor))
|
59 |
+
add_path_segment(
|
60 |
+
(cell[0] * W, cell[1] * H),
|
61 |
+
(neighbor[0] * W, neighbor[1] * H),
|
62 |
+
ax,
|
63 |
+
door=(cell, neighbor) in maze_loader.doors.keys(),
|
64 |
+
status=None
|
65 |
+
if (cell, neighbor) not in maze_loader.doors.keys()
|
66 |
+
else maze_loader.doors[(cell, neighbor)][0].split(" ")[0],
|
67 |
+
lock_status=(
|
68 |
+
None
|
69 |
+
if (cell, neighbor) not in maze_loader.doors.keys()
|
70 |
+
or maze_loader.doors[(cell, neighbor)][0] == "open"
|
71 |
+
else maze_loader.doors[(cell, neighbor)][0].split(" ")[-1]
|
72 |
+
),
|
73 |
+
)
|
74 |
+
|
75 |
+
# Add keys
|
76 |
+
for key_id, key_location in maze_loader.keys_locations.items():
|
77 |
+
door_locations = {
|
78 |
+
maze_loader.doors[(rA, rB)][1]: (
|
79 |
+
(rA[0] + rB[0]) * W / 2,
|
80 |
+
(rA[1] + rB[1]) * H / 2,
|
81 |
+
)
|
82 |
+
for (rA, rB) in maze_loader.doors.keys()
|
83 |
+
}
|
84 |
+
add_key(
|
85 |
+
key_location[0] * W,
|
86 |
+
key_location[1] * H,
|
87 |
+
ax,
|
88 |
+
door_location=door_locations.get(key_id, (0, 0)),
|
89 |
+
)
|
90 |
+
|
91 |
+
# Add start and end rooms
|
92 |
+
start = (
|
93 |
+
maze_loader.data["start_room"][0] * W,
|
94 |
+
maze_loader.data["start_room"][1] * H,
|
95 |
+
)
|
96 |
+
end = (maze_loader.data["end_room"][0] * W, maze_loader.data["end_room"][1] * H)
|
97 |
+
enhanced_mode = True # Use enhanced mode for all visualizations
|
98 |
+
add_start_and_end_room(start, end, ax, enhanced_mode=enhanced_mode)
|
99 |
+
|
100 |
+
# Create a mapping from room names to coordinates
|
101 |
+
room_name_to_coord = {}
|
102 |
+
for cell in maze_loader.connected_cells.keys():
|
103 |
+
room_name_to_coord[maze_loader.room_name[cell]] = cell
|
104 |
+
|
105 |
+
# Define colors for different action types
|
106 |
+
move_color_gt = "gold" # Yellow for regular movement (ground truth)
|
107 |
+
move_color_model = "mediumpurple" # Purple for regular movement (model)
|
108 |
+
start_color = "#FF7F0E" # Orange for start action
|
109 |
+
pickup_key_color = "#1E88E5" # Blue for key pickup
|
110 |
+
use_key_color = "#43A047" # Green for using a key
|
111 |
+
unlock_color = "#9C27B0" # Purple for unlocking door
|
112 |
+
rescue_color = "#D81B60" # Pink for rescue
|
113 |
+
|
114 |
+
# Draw a path with numbered steps
|
115 |
+
def process_solution(solution, ax, base_color="gold"):
|
116 |
+
if not solution:
|
117 |
+
return
|
118 |
+
|
119 |
+
all_actions = []
|
120 |
+
current_room = None
|
121 |
+
last_position = None
|
122 |
+
|
123 |
+
# Parse solution into actions
|
124 |
+
for i, action in enumerate(solution):
|
125 |
+
if len(action) < 2:
|
126 |
+
continue
|
127 |
+
|
128 |
+
action_type, param = action[0], action[1]
|
129 |
+
step_number = i + 1 # Start numbering from 1
|
130 |
+
|
131 |
+
# Track the current room for each action
|
132 |
+
if action_type == "start":
|
133 |
+
current_room = param
|
134 |
+
# Mark start position specially
|
135 |
+
all_actions.append((current_room, step_number, action_type, None))
|
136 |
+
elif action_type == "move_to" and param in room_name_to_coord:
|
137 |
+
prev_room = current_room
|
138 |
+
current_room = param
|
139 |
+
# Store movement with both source and destination
|
140 |
+
all_actions.append((current_room, step_number, action_type, prev_room))
|
141 |
+
elif action_type in [
|
142 |
+
"pick_up_key",
|
143 |
+
"use_key",
|
144 |
+
"unlock_and_open_door_to",
|
145 |
+
"rescue",
|
146 |
+
]:
|
147 |
+
if current_room:
|
148 |
+
# Store special action with current room
|
149 |
+
all_actions.append((current_room, step_number, action_type, None))
|
150 |
+
|
151 |
+
used_positions = set()
|
152 |
+
|
153 |
+
# First draw all movement paths
|
154 |
+
for room, step_number, action_type, prev_room in all_actions:
|
155 |
+
if (
|
156 |
+
action_type == "move_to"
|
157 |
+
and prev_room
|
158 |
+
and room in room_name_to_coord
|
159 |
+
and prev_room in room_name_to_coord
|
160 |
+
):
|
161 |
+
start_cell = room_name_to_coord[prev_room]
|
162 |
+
end_cell = room_name_to_coord[room]
|
163 |
+
|
164 |
+
# Get coordinates
|
165 |
+
x1, y1 = start_cell[0] * W, start_cell[1] * H
|
166 |
+
x2, y2 = end_cell[0] * W, end_cell[1] * H
|
167 |
+
|
168 |
+
# Draw the path for movement
|
169 |
+
ax.plot(
|
170 |
+
[x1, x2], [y1, y2], "-", color=base_color, linewidth=2, zorder=10, alpha=0.5
|
171 |
+
)
|
172 |
+
|
173 |
+
# Add arrow near destination
|
174 |
+
arrow_pos = 0.9
|
175 |
+
arrow_x = x1 + (x2 - x1) * arrow_pos
|
176 |
+
arrow_y = y1 + (y2 - y1) * arrow_pos
|
177 |
+
|
178 |
+
dx = x2 - x1
|
179 |
+
dy = y2 - y1
|
180 |
+
length = math.sqrt(dx * dx + dy * dy)
|
181 |
+
|
182 |
+
if length > 0:
|
183 |
+
dx /= length
|
184 |
+
dy /= length
|
185 |
+
arrow = FancyArrowPatch(
|
186 |
+
(arrow_x - dx * 0.3, arrow_y - dy * 0.3),
|
187 |
+
(arrow_x + dx * 0.3, arrow_y + dy * 0.3),
|
188 |
+
arrowstyle="-|>",
|
189 |
+
mutation_scale=12,
|
190 |
+
color=base_color,
|
191 |
+
linewidth=2,
|
192 |
+
zorder=10,
|
193 |
+
alpha=0.4,
|
194 |
+
)
|
195 |
+
ax.add_patch(arrow)
|
196 |
+
|
197 |
+
# Then add step markers for each action
|
198 |
+
for action_idx, (room, step_number, action_type, prev_room) in enumerate(
|
199 |
+
all_actions
|
200 |
+
):
|
201 |
+
if room in room_name_to_coord:
|
202 |
+
room_cell = room_name_to_coord[room]
|
203 |
+
|
204 |
+
# Determine position and color based on action type
|
205 |
+
if (
|
206 |
+
action_type == "move_to"
|
207 |
+
and prev_room
|
208 |
+
and prev_room in room_name_to_coord
|
209 |
+
):
|
210 |
+
# For movement, place marker along the path
|
211 |
+
start_cell = room_name_to_coord[prev_room]
|
212 |
+
end_cell = room_name_to_coord[room]
|
213 |
+
|
214 |
+
x1, y1 = start_cell[0] * W, start_cell[1] * H
|
215 |
+
x2, y2 = end_cell[0] * W, end_cell[1] * H
|
216 |
+
|
217 |
+
pos_x = x1 + (x2 - x1) * 0.6
|
218 |
+
pos_y = y1 + (y2 - y1) * 0.6
|
219 |
+
|
220 |
+
# Add perpendicular offset to avoid placing directly on line
|
221 |
+
dx = x2 - x1
|
222 |
+
dy = y2 - y1
|
223 |
+
length = math.sqrt(dx * dx + dy * dy)
|
224 |
+
|
225 |
+
if length > 0:
|
226 |
+
perp_x = -dy / length * 0.7
|
227 |
+
perp_y = dx / length * 0.7
|
228 |
+
|
229 |
+
# Alternate sides for consecutive steps
|
230 |
+
if step_number % 2 == 0:
|
231 |
+
perp_x = -perp_x
|
232 |
+
perp_y = -perp_y
|
233 |
+
|
234 |
+
pos_x += perp_x
|
235 |
+
pos_y += perp_y
|
236 |
+
|
237 |
+
color = base_color
|
238 |
+
else:
|
239 |
+
# For non-movement actions, place at the room with offset
|
240 |
+
pos_x = room_cell[0] * W
|
241 |
+
pos_y = room_cell[1] * H
|
242 |
+
|
243 |
+
# Special case for door-related actions - place them near but not at the door
|
244 |
+
if action_type in ["use_key", "unlock_and_open_door_to"]:
|
245 |
+
door_cell1 = room_cell
|
246 |
+
door_cell2 = None
|
247 |
+
|
248 |
+
if action_type == "unlock_and_open_door_to":
|
249 |
+
# Find the destination room for the door
|
250 |
+
dest_room = param
|
251 |
+
if dest_room in room_name_to_coord:
|
252 |
+
door_cell2 = room_name_to_coord[dest_room]
|
253 |
+
elif prev_room in room_name_to_coord:
|
254 |
+
# For use_key, consider the previous room as second door cell
|
255 |
+
door_cell2 = room_name_to_coord[prev_room]
|
256 |
+
|
257 |
+
if door_cell2:
|
258 |
+
# Calculate door position (midpoint between rooms)
|
259 |
+
door_x = (door_cell1[0] + door_cell2[0]) * W / 2
|
260 |
+
door_y = (door_cell1[1] + door_cell2[1]) * H / 2
|
261 |
+
|
262 |
+
# Calculate vector from door to room (normalized)
|
263 |
+
dx = pos_x - door_x
|
264 |
+
dy = pos_y - door_y
|
265 |
+
dist = math.sqrt(dx * dx + dy * dy)
|
266 |
+
|
267 |
+
if dist > 0:
|
268 |
+
# Normalize vector
|
269 |
+
dx /= dist
|
270 |
+
dy /= dist
|
271 |
+
|
272 |
+
# Position marker at 2/3 distance from door to room
|
273 |
+
pos_x = (
|
274 |
+
door_x + dx * 1.5
|
275 |
+
) # Place partway from door toward room
|
276 |
+
pos_y = door_y + dy * 1.5
|
277 |
+
|
278 |
+
# Add small perpendicular offset to avoid direct overlap with path
|
279 |
+
perp_x = -dy * 0.5
|
280 |
+
perp_y = dx * 0.5
|
281 |
+
|
282 |
+
# Alternate sides for consecutive markers
|
283 |
+
if step_number % 2 == 0:
|
284 |
+
perp_x = -perp_x
|
285 |
+
perp_y = -perp_y
|
286 |
+
|
287 |
+
pos_x += perp_x
|
288 |
+
pos_y += perp_y
|
289 |
+
else:
|
290 |
+
# Fallback if rooms are at same location
|
291 |
+
offset_x = 0.7 * (1 if step_number % 2 == 0 else -1)
|
292 |
+
offset_y = 0.7 * (1 if step_number % 4 >= 2 else -1)
|
293 |
+
pos_x += offset_x
|
294 |
+
pos_y += offset_y
|
295 |
+
else:
|
296 |
+
# If second door cell not found, use standard offset from room
|
297 |
+
offset_x = 0.7 * (1 if step_number % 2 == 0 else -1)
|
298 |
+
offset_y = 0.7 * (1 if step_number % 4 >= 2 else -1)
|
299 |
+
pos_x += offset_x
|
300 |
+
pos_y += offset_y
|
301 |
+
else:
|
302 |
+
# Regular offset for other action types
|
303 |
+
if action_type == "start":
|
304 |
+
# Start marker at top-left of room
|
305 |
+
offset_x, offset_y = -0.7, -0.7
|
306 |
+
else:
|
307 |
+
# Other actions - different offsets for different action types
|
308 |
+
offset_multiplers = {
|
309 |
+
"pick_up_key": (0.7, 0.7),
|
310 |
+
"rescue": (-0.7, -0.7),
|
311 |
+
}
|
312 |
+
multiplier = offset_multiplers.get(action_type, (0, 0))
|
313 |
+
offset_x, offset_y = multiplier
|
314 |
+
|
315 |
+
# Further vary offsets for multiple actions in same room
|
316 |
+
same_room_actions = sum(
|
317 |
+
1
|
318 |
+
for r, _, a_type, _ in all_actions[:action_idx]
|
319 |
+
if r == room and a_type != "move_to"
|
320 |
+
)
|
321 |
+
if same_room_actions > 0:
|
322 |
+
offset_x *= 1 + 0.3 * same_room_actions
|
323 |
+
offset_y *= 1 + 0.3 * same_room_actions
|
324 |
+
|
325 |
+
pos_x += offset_x
|
326 |
+
pos_y += offset_y
|
327 |
+
|
328 |
+
# Determine color for special actions - now with distinct colors for all types
|
329 |
+
if action_type == "start":
|
330 |
+
color = start_color
|
331 |
+
elif action_type == "pick_up_key":
|
332 |
+
color = pickup_key_color
|
333 |
+
elif action_type == "use_key":
|
334 |
+
color = use_key_color
|
335 |
+
elif action_type == "unlock_and_open_door_to":
|
336 |
+
color = unlock_color
|
337 |
+
elif action_type == "rescue":
|
338 |
+
color = rescue_color
|
339 |
+
else:
|
340 |
+
color = base_color
|
341 |
+
|
342 |
+
# Avoid overlap with existing markers
|
343 |
+
while any(
|
344 |
+
(abs(pos_x - px) < 0.8 and abs(pos_y - py) < 0.8)
|
345 |
+
for px, py in used_positions
|
346 |
+
):
|
347 |
+
# Slightly adjust position
|
348 |
+
pos_x += 0.3 * (1 if step_number % 2 == 0 else -1)
|
349 |
+
pos_y += 0.3 * (1 if step_number % 4 >= 2 else -1)
|
350 |
+
|
351 |
+
# Add marker
|
352 |
+
# ax.text(
|
353 |
+
# pos_x,
|
354 |
+
# pos_y,
|
355 |
+
# f"{step_number}",
|
356 |
+
# color="white",
|
357 |
+
# fontsize=3,
|
358 |
+
# ha="center",
|
359 |
+
# va="center",
|
360 |
+
# bbox=dict(
|
361 |
+
# boxstyle="circle,pad=0.3",
|
362 |
+
# fc=color,
|
363 |
+
# ec="black",
|
364 |
+
# alpha=0.9,
|
365 |
+
# linewidth=1,
|
366 |
+
# ),
|
367 |
+
# zorder=20,
|
368 |
+
# )
|
369 |
+
|
370 |
+
# Remember this position
|
371 |
+
used_positions.add((pos_x, pos_y))
|
372 |
+
|
373 |
+
title_props = dict(fontsize=12, fontweight="bold")
|
374 |
+
|
375 |
+
# Set titles and process solutions based on mode
|
376 |
+
if mode == "comparison":
|
377 |
+
axes[0].set_title("Optimal Path", **title_props)
|
378 |
+
axes[1].set_title("Model Path", **title_props)
|
379 |
+
|
380 |
+
if ground_truth_solution:
|
381 |
+
process_solution(ground_truth_solution, axes[0], base_color=move_color_gt)
|
382 |
+
if model_solution:
|
383 |
+
process_solution(model_solution, axes[1], base_color=move_color_model)
|
384 |
+
|
385 |
+
elif mode == "empty":
|
386 |
+
axes[0].set_title("Maze Layout", **title_props)
|
387 |
+
# No paths to process for empty maze
|
388 |
+
|
389 |
+
elif mode == "optimal":
|
390 |
+
axes[0].set_title("Optimal Path", **title_props)
|
391 |
+
if ground_truth_solution:
|
392 |
+
process_solution(ground_truth_solution, axes[0], base_color=move_color_gt)
|
393 |
+
|
394 |
+
elif mode == "model":
|
395 |
+
axes[0].set_title("Model Path", **title_props)
|
396 |
+
if model_solution:
|
397 |
+
process_solution(model_solution, axes[0], base_color=move_color_model)
|
398 |
+
|
399 |
+
for ax in axes:
|
400 |
+
ax.set_xticks([])
|
401 |
+
ax.set_yticks([])
|
402 |
+
ax.axis("off")
|
403 |
+
|
404 |
+
current_xlim = ax.get_xlim()
|
405 |
+
current_ylim = ax.get_ylim()
|
406 |
+
ax.set_xlim(current_xlim[0] - 1, current_xlim[1] + 1)
|
407 |
+
ax.set_ylim(current_ylim[0] - 3, current_ylim[1] + 1)
|
408 |
+
|
409 |
+
# Add legend for empty maze mode (enhanced for LLM interpretability)
|
410 |
+
if mode == "empty":
|
411 |
+
# Clean, simple title
|
412 |
+
axes[0].set_title("Maze Navigation: Find path from START (green) to GOAL (red)",
|
413 |
+
fontsize=12, fontweight='bold', pad=20)
|
414 |
+
|
415 |
+
legend_elements = [
|
416 |
+
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='limegreen',
|
417 |
+
markersize=12, markeredgecolor='darkgreen', markeredgewidth=2, label='START'),
|
418 |
+
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='red',
|
419 |
+
markersize=12, markeredgecolor='darkred', markeredgewidth=2, label='GOAL'),
|
420 |
+
plt.Rectangle((0, 0), 1, 1, facecolor='red', alpha=0.8, label='locked door'),
|
421 |
+
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='yellow',
|
422 |
+
markersize=10, markeredgecolor='orange', markeredgewidth=2, label='key'),
|
423 |
+
]
|
424 |
+
|
425 |
+
axes[0].legend(handles=legend_elements, loc='center left', bbox_to_anchor=(0.95, 0.5),
|
426 |
+
frameon=True, fancybox=True, shadow=False, fontsize=9)
|
427 |
+
|
428 |
+
# Only add path legend for non-empty modes
|
429 |
+
if mode != "empty":
|
430 |
+
legend_items = [
|
431 |
+
("Start", start_color),
|
432 |
+
("Move", move_color_gt if ground_truth_solution else move_color_model),
|
433 |
+
("Key pickup", pickup_key_color),
|
434 |
+
("Use key", use_key_color),
|
435 |
+
("Unlock door", unlock_color),
|
436 |
+
("Rescue", rescue_color),
|
437 |
+
]
|
438 |
+
|
439 |
+
legend_patches = [
|
440 |
+
plt.Rectangle((0, 0), 1, 1, fc=color, ec="black", alpha=0.9)
|
441 |
+
for _, color in legend_items
|
442 |
+
]
|
443 |
+
|
444 |
+
# fig.legend(
|
445 |
+
# legend_patches,
|
446 |
+
# [text for text, _ in legend_items],
|
447 |
+
# loc="lower center",
|
448 |
+
# bbox_to_anchor=(0.5, 0.02),
|
449 |
+
# ncol=len(legend_items),
|
450 |
+
# frameon=True,
|
451 |
+
# fancybox=True,
|
452 |
+
# shadow=True,
|
453 |
+
# fontsize=10,
|
454 |
+
# )
|
455 |
+
|
456 |
+
# Handle layout based on mode
|
457 |
+
if mode == "empty":
|
458 |
+
plt.tight_layout()
|
459 |
+
# Adjust layout to accommodate legend with less gap
|
460 |
+
plt.subplots_adjust(right=0.90)
|
461 |
+
else:
|
462 |
+
plt.tight_layout()
|
463 |
+
|
464 |
+
if save_path is not None:
|
465 |
+
try:
|
466 |
+
plt.savefig(save_path, dpi=400, bbox_inches="tight", format="png")
|
467 |
+
except Exception as e:
|
468 |
+
print(f"Error saving plot: {e}")
|
469 |
+
|
470 |
+
plt.close(fig)
|
471 |
+
|
472 |
+
|
473 |
+
def draw_path_with_arrow(
|
474 |
+
point1,
|
475 |
+
point2,
|
476 |
+
ax,
|
477 |
+
color="red",
|
478 |
+
linewidth=1.5,
|
479 |
+
alpha=0.8,
|
480 |
+
arrow_size=5,
|
481 |
+
arrow_color=None,
|
482 |
+
):
|
483 |
+
"""Draw a path between two points with a smaller, more subtle directional arrow."""
|
484 |
+
if arrow_color is None:
|
485 |
+
arrow_color = color
|
486 |
+
|
487 |
+
# Calculate the midpoint for the arrow position - shift slightly toward destination
|
488 |
+
# to avoid overlap with nodes
|
489 |
+
midpoint_x = point1[0] + (point2[0] - point1[0]) * 0.6
|
490 |
+
midpoint_y = point1[1] + (point2[1] - point1[1]) * 0.6
|
491 |
+
|
492 |
+
# Draw the line
|
493 |
+
line = ax.plot(
|
494 |
+
[point1[0], point2[0]],
|
495 |
+
[point1[1], point2[1]],
|
496 |
+
color=color,
|
497 |
+
linewidth=linewidth,
|
498 |
+
alpha=alpha,
|
499 |
+
)[0]
|
500 |
+
|
501 |
+
# Calculate the direction vector
|
502 |
+
dx = point2[0] - point1[0]
|
503 |
+
dy = point2[1] - point1[1]
|
504 |
+
|
505 |
+
# Normalize the direction vector
|
506 |
+
length = np.sqrt(dx**2 + dy**2)
|
507 |
+
if length > 0:
|
508 |
+
dx /= length
|
509 |
+
dy /= length
|
510 |
+
|
511 |
+
# Add a small arrow
|
512 |
+
ax.arrow(
|
513 |
+
midpoint_x,
|
514 |
+
midpoint_y,
|
515 |
+
dx * arrow_size / 3,
|
516 |
+
dy * arrow_size / 3,
|
517 |
+
head_width=arrow_size * 0.8,
|
518 |
+
head_length=arrow_size * 0.8,
|
519 |
+
fc=arrow_color,
|
520 |
+
ec=arrow_color,
|
521 |
+
alpha=alpha,
|
522 |
+
length_includes_head=True,
|
523 |
+
)
|
524 |
+
|
525 |
+
return line
|
526 |
+
|
527 |
+
|
528 |
+
def add_arc_between_points(point1, point2, ax, alpha=0.2):
|
529 |
+
|
530 |
+
# Use spline of degree 2 (since m = 3)
|
531 |
+
tck, _ = splprep(
|
532 |
+
[
|
533 |
+
[point1[0], (point1[0] + point2[0]) / 2.0 - alpha, point2[0]],
|
534 |
+
[point1[1], (point1[1] + point2[1]) / 2.0 + alpha, point2[1]],
|
535 |
+
],
|
536 |
+
s=0,
|
537 |
+
k=2,
|
538 |
+
)
|
539 |
+
t = np.linspace(0, 1, 100)
|
540 |
+
x_spline, y_spline = splev(t, tck)
|
541 |
+
# Plot
|
542 |
+
ax.plot(x_spline, y_spline, label="Spline curve", linestyle="--")
|
543 |
+
|
544 |
+
|
545 |
+
def add_door(
|
546 |
+
x_center, y_center, ax, status="closed", door_color="black", door_location=(0, 0)
|
547 |
+
):
|
548 |
+
# make a hallow rectangle
|
549 |
+
x1 = x_center - 0.2
|
550 |
+
x2 = x_center + 0.2
|
551 |
+
y1 = y_center - 0.4
|
552 |
+
y2 = y_center + 0.4
|
553 |
+
if status == "open":
|
554 |
+
# make the fill color transparent
|
555 |
+
rect = patches.Polygon(
|
556 |
+
[[x1, y1], [x2, y1], [x2, y2], [x1, y2]],
|
557 |
+
closed=True,
|
558 |
+
edgecolor="black",
|
559 |
+
facecolor="none",
|
560 |
+
)
|
561 |
+
else:
|
562 |
+
rect = patches.Polygon(
|
563 |
+
[[x1, y1], [x2, y1], [x2, y2], [x1, y2]], closed=True, facecolor=door_color
|
564 |
+
)
|
565 |
+
ax.add_patch(rect)
|
566 |
+
|
567 |
+
|
568 |
+
def h_link(
|
569 |
+
x1,
|
570 |
+
x2,
|
571 |
+
y,
|
572 |
+
ax,
|
573 |
+
door=False,
|
574 |
+
status="closed",
|
575 |
+
lock_status="unlocked",
|
576 |
+
line_color="#76b5c5",
|
577 |
+
):
|
578 |
+
# make sure it is brought to the front of all other patches z_order = 100
|
579 |
+
ax.add_patch(patches.Circle((x1, y), 0.3, facecolor="black", zorder=100000))
|
580 |
+
ax.add_patch(patches.Circle((x2, y), 0.3, facecolor="black", zorder=100000))
|
581 |
+
|
582 |
+
x1 = x1 - 0.05
|
583 |
+
x2 = x2 + 0.05
|
584 |
+
y = y - 0.05
|
585 |
+
rect = patches.Polygon(
|
586 |
+
[[x1, y], [x2, y], [x2, y + 0.1], [x1, y + 0.1]],
|
587 |
+
closed=True,
|
588 |
+
facecolor=line_color,
|
589 |
+
)
|
590 |
+
ax.add_patch(rect)
|
591 |
+
x_center = (x1 + x2) / 2.0 + 0.05
|
592 |
+
if door:
|
593 |
+
if status == "open":
|
594 |
+
add_door(x_center, y + 0.05, ax, status="open")
|
595 |
+
else:
|
596 |
+
if lock_status == "locked":
|
597 |
+
door_color = "red"
|
598 |
+
else:
|
599 |
+
door_color = "green"
|
600 |
+
add_door(x_center, y + 0.05, ax, status="closed", door_color=door_color)
|
601 |
+
# add circles at both ends of the line
|
602 |
+
|
603 |
+
|
604 |
+
def v_link(
|
605 |
+
x,
|
606 |
+
y1,
|
607 |
+
y2,
|
608 |
+
ax,
|
609 |
+
door=False,
|
610 |
+
status="closed",
|
611 |
+
lock_status="locked",
|
612 |
+
line_color="#76b5c5",
|
613 |
+
):
|
614 |
+
# make sure it is brought to the front of all other patches z_order = 100
|
615 |
+
ax.add_patch(patches.Circle((x, y1), 0.3, facecolor="black", zorder=100000))
|
616 |
+
ax.add_patch(patches.Circle((x, y2), 0.3, facecolor="black", zorder=100000))
|
617 |
+
y1 = y1 - 0.05
|
618 |
+
y2 = y2 + 0.05
|
619 |
+
x = x - 0.05
|
620 |
+
triangle = patches.Polygon(
|
621 |
+
[[x, y1], [x, y2], [x + 0.1, y2], [x + 0.1, y1]],
|
622 |
+
closed=True,
|
623 |
+
facecolor=line_color,
|
624 |
+
)
|
625 |
+
ax.add_patch(triangle)
|
626 |
+
y_center = (y1 + y2) / 2.0
|
627 |
+
if door:
|
628 |
+
if status == "open":
|
629 |
+
add_door(x + 0.05, y_center, ax, status="open")
|
630 |
+
else:
|
631 |
+
if lock_status == "locked":
|
632 |
+
door_color = "red"
|
633 |
+
else:
|
634 |
+
door_color = "green"
|
635 |
+
add_door(x + 0.05, y_center, ax, status="closed", door_color=door_color)
|
636 |
+
# add circles at both ends of the line
|
637 |
+
|
638 |
+
|
639 |
+
def add_start_and_end_room(start_room, end_room, ax, size=0.6, enhanced_mode=False):
|
640 |
+
if enhanced_mode:
|
641 |
+
# Enhanced mode for LLM interpretability - clean colored circles only
|
642 |
+
x, y = start_room
|
643 |
+
# Start room: Large green circle (no text)
|
644 |
+
ax.add_patch(patches.Circle((x, y), size*1.5, facecolor="limegreen", edgecolor="darkgreen", linewidth=3, zorder=100000))
|
645 |
+
|
646 |
+
x, y = end_room
|
647 |
+
# End room: Large red circle (no text)
|
648 |
+
ax.add_patch(patches.Circle((x, y), size*1.5, facecolor="red", edgecolor="darkred", linewidth=3, zorder=100000))
|
649 |
+
else:
|
650 |
+
# Original mode: black triangles
|
651 |
+
x, y = start_room
|
652 |
+
ax.add_patch(
|
653 |
+
patches.Polygon(
|
654 |
+
[[x - size, y - size], [x + size, y - size], [x, y + size]],
|
655 |
+
closed=True,
|
656 |
+
facecolor="black",
|
657 |
+
edgecolor="black",
|
658 |
+
zorder=100000,
|
659 |
+
)
|
660 |
+
)
|
661 |
+
x, y = end_room
|
662 |
+
ax.add_patch(
|
663 |
+
patches.Polygon(
|
664 |
+
[[x - size, y + size], [x + size, y + size], [x, y - size]],
|
665 |
+
closed=True,
|
666 |
+
facecolor="black",
|
667 |
+
edgecolor="black",
|
668 |
+
zorder=100000,
|
669 |
+
)
|
670 |
+
)
|
671 |
+
|
672 |
+
|
673 |
+
def add_path_segment(
|
674 |
+
point1, point2, ax, door=False, status="closed", lock_status="locked"
|
675 |
+
):
|
676 |
+
if point1[0] == point2[0]:
|
677 |
+
v_link(point1[0], point1[1], point2[1], ax, door, status, lock_status)
|
678 |
+
else:
|
679 |
+
h_link(point1[0], point2[0], point1[1], ax, door, status, lock_status)
|
680 |
+
|
681 |
+
|
682 |
+
def add_key(x, y, ax, door_location=(0, 0)):
|
683 |
+
# Enhanced key visualization - yellow circle
|
684 |
+
ax.add_patch(
|
685 |
+
patches.Circle((x, y), 0.4, facecolor="yellow", edgecolor="orange", linewidth=2, zorder=100000)
|
686 |
+
)
|
687 |
+
add_arc_between_points((x, y), door_location, ax)
|
688 |
+
|
689 |
+
|
690 |
+
if __name__ == "__main__":
|
691 |
+
# Create a plot
|
692 |
+
fig, ax = plt.subplots()
|
693 |
+
|
694 |
+
add_path_segment((1, 1), (1, 4), ax, door=True, status="open")
|
695 |
+
add_key(1, 4, ax, door_location=(2.5, 4))
|
696 |
+
add_path_segment(
|
697 |
+
(1, 4), (4, 4), ax, door=True, status="closed", lock_status="locked"
|
698 |
+
)
|
699 |
+
add_path_segment((4, 4), (4, 7), ax, door=False)
|
700 |
+
add_path_segment(
|
701 |
+
(4, 7), (1, 7), ax, door=True, status="closed", lock_status="unlocked"
|
702 |
+
)
|
703 |
+
|
704 |
+
ax.set_aspect("equal")
|
705 |
+
ax.axis("off")
|
706 |
+
ax.set_xlim(0, 10)
|
707 |
+
ax.set_ylim(0, 10)
|
708 |
+
plt.show()
|
709 |
+
|
710 |
+
|
711 |
+
|
712 |
+
def pretty_plot_maze_vs_noise(
|
713 |
+
maze_loader,
|
714 |
+
W=4,
|
715 |
+
H=4,
|
716 |
+
save_path=None,
|
717 |
+
ground_truth_solution=None,
|
718 |
+
problem_description=None
|
719 |
+
):
|
720 |
+
"""
|
721 |
+
Display the maze using Matplotlib and optionally save to a file.
|
722 |
+
Shows three plots: Maze Layout, Ground Truth Path, and Model Path.
|
723 |
+
"""
|
724 |
+
|
725 |
+
plt.rcParams["font.size"] = 10
|
726 |
+
plt.rcParams["font.family"] = "sans-serif"
|
727 |
+
plt.rcParams["figure.dpi"] = 100
|
728 |
+
|
729 |
+
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 8.5))
|
730 |
+
|
731 |
+
# Draw the base maze on all three plots
|
732 |
+
for ax in [ax1, ax2, ax3]:
|
733 |
+
covered_cells = set()
|
734 |
+
for cell in maze_loader.connected_cells.keys():
|
735 |
+
for neighbor in maze_loader.connected_cells[cell]:
|
736 |
+
if (cell, neighbor) in covered_cells or (
|
737 |
+
neighbor,
|
738 |
+
cell,
|
739 |
+
) in covered_cells:
|
740 |
+
continue
|
741 |
+
covered_cells.add((cell, neighbor))
|
742 |
+
add_path_segment(
|
743 |
+
(cell[0] * W, cell[1] * H),
|
744 |
+
(neighbor[0] * W, neighbor[1] * H),
|
745 |
+
ax,
|
746 |
+
door=(cell, neighbor) in maze_loader.doors.keys(),
|
747 |
+
status=None
|
748 |
+
if (cell, neighbor) not in maze_loader.doors.keys()
|
749 |
+
else maze_loader.doors[(cell, neighbor)][0].split(" ")[0],
|
750 |
+
lock_status=(
|
751 |
+
None
|
752 |
+
if (cell, neighbor) not in maze_loader.doors.keys()
|
753 |
+
or maze_loader.doors[(cell, neighbor)][0] == "open"
|
754 |
+
else maze_loader.doors[(cell, neighbor)][0].split(" ")[-1]
|
755 |
+
),
|
756 |
+
)
|
757 |
+
|
758 |
+
# Add keys
|
759 |
+
for key_id, key_location in maze_loader.keys_locations.items():
|
760 |
+
door_locations = {
|
761 |
+
maze_loader.doors[(rA, rB)][1]: (
|
762 |
+
(rA[0] + rB[0]) * W / 2,
|
763 |
+
(rA[1] + rB[1]) * H / 2,
|
764 |
+
)
|
765 |
+
for (rA, rB) in maze_loader.doors.keys()
|
766 |
+
}
|
767 |
+
add_key(
|
768 |
+
key_location[0] * W,
|
769 |
+
key_location[1] * H,
|
770 |
+
ax,
|
771 |
+
door_location=door_locations.get(key_id, (0, 0)),
|
772 |
+
)
|
773 |
+
|
774 |
+
# Add start and end rooms
|
775 |
+
start = (
|
776 |
+
maze_loader.data["start_room"][0] * W,
|
777 |
+
maze_loader.data["start_room"][1] * H,
|
778 |
+
)
|
779 |
+
end = (maze_loader.data["end_room"][0] * W, maze_loader.data["end_room"][1] * H)
|
780 |
+
add_start_and_end_room(start, end, ax)
|
781 |
+
|
782 |
+
|
scripts /spatial.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
from typing import Any, List, Tuple
|
3 |
+
import random
|
4 |
+
|
5 |
+
|
6 |
+
@dataclass
|
7 |
+
class CompositeTool:
|
8 |
+
name: str # name of the composite tool
|
9 |
+
tools: List[Tool] # tools that make up the composite tool
|
10 |
+
compatible_keys: List[str] # keys that the composite tool can fix
|
11 |
+
who_can_build: List[
|
12 |
+
Tuple[str, int]
|
13 |
+
] # expertise and count of people in each expertise needed to build the composite tool
|
14 |
+
|
15 |
+
def __str__(self):
|
16 |
+
return f"CompositeTool {self.name}"
|
17 |
+
|
18 |
+
def get_description(self):
|
19 |
+
return f"CompositeTool {self.name} can fix keys: {self.compatible_keys} but consists of tools: {self.tools}"
|
20 |
+
|
21 |
+
|
22 |
+
@dataclass
|
23 |
+
class Tool:
|
24 |
+
name: str # name of the tool
|
25 |
+
compatible_keys: List[str] # keys that the tool can fix
|
26 |
+
who_can_use: List[str] # expertise needed to use the tool
|
27 |
+
|
28 |
+
def __str__(self):
|
29 |
+
return f"Tool {self.name}"
|
30 |
+
|
31 |
+
def get_description(self):
|
32 |
+
return f"Tool {self.name} can fix keys: {self.compatible_keys}"
|
33 |
+
|
34 |
+
|
35 |
+
@dataclass
|
36 |
+
class Key:
|
37 |
+
name: str # name of the key
|
38 |
+
color: str # color of the key
|
39 |
+
broken: bool # whether the key is broken
|
40 |
+
fixable: bool # whether the key is fixable
|
41 |
+
tools: List[str] # tools or composite tools that are needed to fix the key
|
42 |
+
who_can_fix: List[
|
43 |
+
Tuple[str, int]
|
44 |
+
] # expertise and count of people in each expertise needed to fix the key
|
45 |
+
|
46 |
+
def __str__(self):
|
47 |
+
return f"Key {self.name}"
|
48 |
+
|
49 |
+
def description(self):
|
50 |
+
return f"""Key {self.name} is {self.color}
|
51 |
+
{'but it is broken and cannot be used' if self.broken else ' and it works'}"""
|
52 |
+
|
53 |
+
|
54 |
+
@dataclass
|
55 |
+
class Object:
|
56 |
+
name: str # name of the object
|
57 |
+
description: str # description of the object
|
58 |
+
|
59 |
+
def __str__(self):
|
60 |
+
return f"item {self.name} ({self.description})"
|
61 |
+
|
62 |
+
def get_description(self):
|
63 |
+
return f"item {self.name} is described as {self.description}"
|
64 |
+
|
65 |
+
|
66 |
+
@dataclass
|
67 |
+
class Box:
|
68 |
+
name: str # name of the box
|
69 |
+
contents: List[
|
70 |
+
str
|
71 |
+
] # contents of the box - list of box names or key names or tool names
|
72 |
+
locked: bool # whether the box is locked
|
73 |
+
|
74 |
+
def __str__(self):
|
75 |
+
return f"Box {self.name}"
|
76 |
+
|
77 |
+
def get_description(self):
|
78 |
+
return f"Box {self.name} contains: {self.contents}"
|
79 |
+
|
80 |
+
|
81 |
+
@dataclass
|
82 |
+
class Person:
|
83 |
+
name: str # name of the person
|
84 |
+
room: None | Any # room that the person is in
|
85 |
+
boxes: List[Box] # boxes that the person has
|
86 |
+
keys: List[Key] # keys that the person has
|
87 |
+
cooperates_with: List[str] # names of people
|
88 |
+
can_build: List[str] # names of composite tools that the person can build
|
89 |
+
can_fix: List[str] # names of keys that the person can fix
|
90 |
+
can_use: List[str] # names of keys that the person can use
|
91 |
+
|
92 |
+
def __str__(self):
|
93 |
+
return f"Person {self.name}"
|
94 |
+
|
95 |
+
def get_description(self):
|
96 |
+
return f"Person {self.name} is in room {self.room.name}"
|
97 |
+
|
98 |
+
|
99 |
+
@dataclass
|
100 |
+
class Door:
|
101 |
+
name: str # name of the door
|
102 |
+
locked: bool # whether the door is locked
|
103 |
+
key: None | Key # key that can unlock the door
|
104 |
+
two_way: bool # whether the door is two way
|
105 |
+
key_hole_outward_facing: bool # whether the key hole is outward facing
|
106 |
+
|
107 |
+
def __str__(self):
|
108 |
+
return f"Door {self.name}"
|
109 |
+
|
110 |
+
def get_description(self):
|
111 |
+
return f"Door {self.name} is {'locked' if self.locked else 'unlocked'}"
|
112 |
+
|
113 |
+
|
114 |
+
@dataclass
|
115 |
+
class Room:
|
116 |
+
name: str # name of the room
|
117 |
+
west: None | Door # door to the west
|
118 |
+
east: None | Door # door to the east
|
119 |
+
north: None | Door # door to the north
|
120 |
+
south: None | Door # door to the south
|
121 |
+
occupants: list[str] # names of people in the room
|
122 |
+
west_neighbor: None | Any # room to the west
|
123 |
+
east_neighbor: None | Any # room to the east
|
124 |
+
north_neighbor: None | Any # room to the north
|
125 |
+
south_neighbor: None | Any # room to the south
|
126 |
+
|
127 |
+
def __str__(self):
|
128 |
+
return f"""Room {self.name}"""
|
129 |
+
|
130 |
+
def get_description(self):
|
131 |
+
return f"""Room {self.name} is adjacent to {self.west_neighbor.name
|
132 |
+
if self.west_neighbor else 'none'} on the west side,
|
133 |
+
{self.east_neighbor.name if self.east_neighbor else 'none'} on the east side,
|
134 |
+
{self.north_neighbor.name if self.north_neighbor else 'none'} on the north side,
|
135 |
+
{self.south_neighbor.name if self.south_neighbor else 'none'} on the south side
|
136 |
+
{self.occupants} are in the room and there are doors on these sides
|
137 |
+
{self.west.name if self.west else 'none'} on the west side,
|
138 |
+
{self.east.name if self.east else 'none'} on the east side,
|
139 |
+
{self.north.name if self.north else 'none'} on the north side,
|
140 |
+
{self.south.name if self.south else 'none'} on the south side"""
|
141 |
+
|
142 |
+
|
143 |
+
@dataclass
|
144 |
+
class World:
|
145 |
+
rooms: List[Room] # rooms in the world
|
146 |
+
people: List[Person] # people in the world
|
147 |
+
boxes: List[Box] # boxes in the world
|
148 |
+
keys: List[Key] # keys in the world
|
149 |
+
tools: List[Tool] # tools in the world
|
150 |
+
|
151 |
+
def __str__(self):
|
152 |
+
return f"World"
|
153 |
+
|
154 |
+
def get_description(self):
|
155 |
+
return f"This is the world: {self.rooms} {self.people} {self.boxes} {self.keys} {self.tools}"
|
156 |
+
|
157 |
+
|
158 |
+
def generate_configuration(N_x: int, N_y: int, n_people: int):
|
159 |
+
|
160 |
+
# generate a random configuration of people in rooms
|
161 |
+
# sample larger than population with replacement
|
162 |
+
walls = [True] + random.choices([True, False], k=3)
|
163 |
+
random.shuffle(walls)
|
164 |
+
rooms = [
|
165 |
+
Room(
|
166 |
+
name=f"Room {i}",
|
167 |
+
west=walls[0],
|
168 |
+
east=walls[1],
|
169 |
+
north=walls[2],
|
170 |
+
south=walls[3],
|
171 |
+
occupants=[],
|
172 |
+
lattice_position=(i, j),
|
173 |
+
)
|
174 |
+
for i in range(N_y)
|
175 |
+
for j in range(N_x)
|
176 |
+
]
|
177 |
+
|
178 |
+
# generate a random configuration of people in rooms
|
179 |
+
people = [Person(name=f"Person {i}") for i in range(n_people)]
|
180 |
+
for person in people:
|
181 |
+
room = random.choice(rooms)
|
182 |
+
room.occupants.append(person)
|
183 |
+
return rooms
|
184 |
+
|
185 |
+
|
186 |
+
def print_walls():
|
187 |
+
for i in range(10):
|
188 |
+
print(generate_configuration(10, 10))
|
189 |
+
|
190 |
+
|
191 |
+
if __name__ == "__main__":
|
192 |
+
print_walls()
|