File size: 28,374 Bytes
fb0015f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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)