Nabidnur's picture
sync src: Track D, Panda env, RACE-Net, text mazes
e3ca3be verified
Raw History Blame Contribute Delete
3.51 kB
"""Text-maze navigation for LLM agents (procedural, exact validator).
A maze from `trackD.make_maze` is shown as ASCII ('#' wall, '.' free, 'S' start, 'G' goal). The agent
answers with a move string over U/D/L/R. The validator simulates it and reports the first illegal move
or where the walk ended: the feedback signal for an LLM-Modulo repair loop (same protocol as PlanBench).
"""
from __future__ import annotations
import re
import numpy as np
from robotics.bench.trackD import bfs, make_maze
MOVES = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)}
PROMPT = """You are navigating a grid maze. '#' is a wall, '.' is free, 'S' is your start, 'G' is the goal.
Rows are numbered from the top (row 0), columns from the left (column 0).
Moves: U = up (row - 1), D = down (row + 1), L = left (column - 1), R = right (column + 1).
You cannot move into a wall.
{grid}
Start S is at (row {sr}, column {sc}). Goal G is at (row {gr}, column {gc}).
Give a sequence of moves that takes you from S to G.
Finish with one line of the form: PATH: <moves> for example PATH: RRDDLU"""
def make_instance(seed: int, cells: int):
G = make_maze(cells, cells, loops=0.05, seed=seed)
rng = np.random.default_rng(seed + 7)
free = np.argwhere(G == 0)
while True:
s, g = (tuple(int(v) for v in free[k]) for k in rng.choice(len(free), 2, replace=False))
opt = int(bfs(G == 0, g)[s])
if opt >= 2 * cells: # non-trivial: optimal path at least 2 x maze width
break
rows = []
for r in range(G.shape[0]):
rows.append("".join("S" if (r, c) == s else "G" if (r, c) == g else "#" if G[r, c] else "." for c in range(G.shape[1])))
return {"id": f"maze{cells}x{cells}_{seed}", "cells": cells, "grid": rows, "start": s, "goal": g, "optimal": opt}
def prompt(inst):
return PROMPT.format(grid="\n".join(inst["grid"]), sr=inst["start"][0], sc=inst["start"][1],
gr=inst["goal"][0], gc=inst["goal"][1])
def parse(text: str) -> str | None:
text = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S)
m = re.findall(r"PATH\s*[::]\s*([UDLR\s,\->]+)", text.upper())
return re.sub(r"[^UDLR]", "", m[-1]) if m else None
def validate(inst, path: str | None):
"""-> dict(solved, error, end, n_moves)."""
if not path:
return {"solved": False, "error": "no 'PATH: ...' line with moves found", "end": inst["start"], "n_moves": 0}
r, c = inst["start"]
grid = inst["grid"]
for k, mv in enumerate(path, 1):
dr, dc = MOVES[mv]
rr, cc = r + dr, c + dc
if not (0 <= rr < len(grid) and 0 <= cc < len(grid[0])) or grid[rr][cc] == "#":
return {"solved": False, "end": (r, c), "n_moves": len(path),
"error": f"move {k} ({mv}) from (row {r}, column {c}) hits a wall at (row {rr}, column {cc}); "
f"the first {k - 1} moves were legal"}
r, c = rr, cc
if (r, c) == tuple(inst["goal"]):
return {"solved": True, "error": None, "end": (r, c), "n_moves": k}
return {"solved": False, "end": (r, c), "n_moves": len(path),
"error": f"all {len(path)} moves are legal but the walk ends at (row {r}, column {c}), not at the goal "
f"(row {inst['goal'][0]}, column {inst['goal'][1]})"}
def suite(n_per_size=20, sizes=(4, 6), seed0=500):
return [make_instance(seed0 + 100 * cells + i, cells) for cells in sizes for i in range(n_per_size)]