Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 8,656 Bytes
3421ea2
161a2d3
 
 
 
3421ea2
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The move budget (huggingface/legion#115, section 6): `python budget.py [--draws 200]`
(Python 3.10+, no dependencies).

Simulates searches on the 32 trees in tasks/ with the maze service's own engine
(template/environment/maze/engine.py: every move goes through engine.Walk, which refuses what
the service refuses), without Legion or containers, and prints the success rate of each strategy
by team size N and per-agent move budget, as the Markdown table in README.md:

- (a) one agent, depth-first: it takes the first door it hasn't been through, in the order the
  room lists them, and goes back when it has none left;
- (b) best-of-N: N agents search independently, each depth-first as in (a), but taking the
  first listed unexplored door only half the time and a random one otherwise (each agent its
  own habit); the team succeeds if any one gets out. Agents that always follow the shared door
  order all walk (a)'s path, so then best-of-N is (a) at every N (`--habit 1`); `--habit 0` is
  N searches in independent random orders;
- (c) a perfect split: the 27 dead ends, in (a)'s order, are cut into N runs as equal as
  possible, and each agent searches only the branches that lead to its own run (it knows the
  tree's shape, which no real agent does), depth-first as in (a).

A success needs the exit reached within the budget by at least one agent. (b) is averaged
over `--draws` draws of the agents' habits per tree.
"""

import argparse
import json
import random
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.dont_write_bytecode = True  # nothing new in template/
sys.path.insert(0, str(HERE / "template" / "environment" / "maze"))
from engine import Maze, Walk  # noqa: E402

SIZES = (1, 2, 4, 8)
BUDGETS = (30, 60, 90, 120, 150, 180, 210, 240, 300, 360, 450, 600, 750)
NEVER = 10 ** 9


def load_trees() -> list[dict]:
    paths = sorted(HERE.glob("tasks/maze-t*/environment/maze/tree.json"))
    if not paths:
        raise SystemExit("no tasks/: run generate.py first")
    return [json.loads(p.read_text()) for p in paths]


def search(maze: Maze, choose, allowed: set[str] | None = None) -> int:
    """Moves until the exit, depth-first through `engine.Walk`: `choose(room, unexplored)` picks
    the next door among those not yet visited (in listed order, and in `allowed` if given);
    with none left, go back the way it came."""
    walk = Walk(maze)
    seen, path = {walk.room}, [walk.room]
    while not walk.reached:
        here = walk.look()
        unexplored = [d for d in here["doors"]
                      if d not in seen and (allowed is None or d in allowed)]
        if unexplored:
            target = choose(walk.room, unexplored)
            path.append(target)
        elif len(path) > 1:
            path.pop()
            target = path[-1]
        else:
            return NEVER  # searched everything it may enter
        _, why = walk.move(target)
        if why is not None:
            raise RuntimeError(f"the engine refused a search move: {why}")
        seen.add(target)
    return walk.moves


def first(room, unexplored):
    return unexplored[0]


def habit(rng: random.Random, q: float):
    def choose(room, unexplored):
        return unexplored[0] if rng.random() < q else rng.choice(unexplored)
    return choose


def dead_ends_in_order(maze: Maze) -> list[str]:
    """The dead ends in the order (a) reaches them."""
    order, seen = [], {maze.start}

    def visit(room):
        if len(maze.doors[room]) == 1 and room != maze.start:
            order.append(room)
        for door in maze.doors[room]:
            if door not in seen:
                seen.add(door)
                visit(door)

    visit(maze.start)
    return order


def toward(maze: Maze, targets: set[str]) -> set[str]:
    """The rooms on a path from the start to any of `targets`."""
    parent, queue = {maze.start: None}, [maze.start]
    for room in queue:
        for door in maze.doors[room]:
            if door not in parent:
                parent[door] = room
                queue.append(door)
    keep = set()
    for room in targets:
        while room is not None and room not in keep:
            keep.add(room)
            room = parent[room]
    return keep


def split_search(maze: Maze, n: int) -> int:
    """(c): moves until the exit for the agent whose run of dead ends holds it, searching
    depth-first only the rooms on its way to its own dead ends."""
    ends = dead_ends_in_order(maze)
    size, extra = divmod(len(ends), n)
    start = 0
    for k in range(n):
        share = ends[start:start + size + (k < extra)]
        start += len(share)
        if maze.exit in share:
            allowed = toward(maze, set(share))
            return search(maze, first, allowed)
    raise RuntimeError("the exit is in no agent's share")


def rates(trees: list[dict], draws: int, q: float, seed: int) -> dict:
    """Success rates by strategy, N and budget."""
    rng = random.Random(seed)
    a, b, c = [], {n: [] for n in SIZES}, {n: [] for n in SIZES}
    for tree in trees:
        maze = Maze({**tree, "budget": NEVER})
        a.append(search(maze, first))
        singles = [search(maze, habit(rng, q)) for _ in range(draws * max(SIZES))]
        for n in SIZES:
            b[n].append([min(singles[i * n:(i + 1) * n]) for i in range(draws)])
            c[n].append(split_search(maze, n))
    out = {"a": {}, "b": {n: {} for n in SIZES}, "c": {n: {} for n in SIZES},
           "a_moves": sorted(a)}
    for budget in BUDGETS:
        out["a"][budget] = sum(m <= budget for m in a) / len(trees)
        for n in SIZES:
            out["b"][n][budget] = sum(sum(m <= budget for m in draw) / draws
                                      for draw in b[n]) / len(trees)
            out["c"][n][budget] = sum(m <= budget for m in c[n]) / len(trees)
    return out


def exact(tree: dict) -> dict:
    """(a) and (c) for an exit chosen uniformly: every tree has the same shape (only the labels,
    the door order and the exit differ), so the exit on each of one tree's 27 dead ends in turn
    gives the exact rates."""
    ends = dead_ends_in_order(Maze(tree))
    moves = {"a": [], **{n: [] for n in SIZES}}
    for end in ends:
        maze = Maze({**tree, "exit": end, "budget": NEVER})
        moves["a"].append(search(maze, first))
        for n in SIZES:
            moves[n].append(split_search(maze, n))
    return {"a": {budget: sum(m <= budget for m in moves["a"]) / len(ends) for budget in BUDGETS},
            "c": {n: {budget: sum(m <= budget for m in moves[n]) / len(ends)
                      for budget in BUDGETS} for n in SIZES}}


def table(r: dict, b: bool = True) -> str:
    sizes = [n for n in SIZES if n > 1]
    head = (["budget", "(a) N=1"] + [f"(b) N={n}" for n in sizes] * b
            + [f"(c) N={n}" for n in sizes])
    lines = ["| " + " | ".join(head) + " |", "|" + "---:|" * len(head)]
    for budget in BUDGETS:
        cells = [str(budget), f"{r['a'][budget]:.0%}"]
        if b:
            cells += [f"{r['b'][n][budget]:.0%}" for n in sizes]
        cells += [f"{r['c'][n][budget]:.0%}" for n in sizes]
        lines.append("| " + " | ".join(cells) + " |")
    return "\n".join(lines)


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--draws", type=int, default=200, help="(b)'s draws per tree")
    parser.add_argument("--habit", type=float, default=0.5,
                        help="(b): how often an agent takes the first listed unexplored door")
    parser.add_argument("--seed", type=int, default=0, help="(b)'s draws")
    parser.add_argument("--json", action="store_true", help="the rates as JSON instead")
    parser.add_argument("--exact", action="store_true",
                        help="(a) and (c) for a uniformly chosen exit instead of the 32 trees'")
    args = parser.parse_args(argv)
    trees = load_trees()
    if args.exact:
        r = exact(trees[0])
        title = "(a) and (c) for an exit chosen uniformly among the 27 dead ends"
        print(json.dumps(r) if args.json else title + "\n" + table(r, b=False))
        return 0
    r = rates(trees, args.draws, args.habit, args.seed)
    if r["c"][1] != r["a"]:  # one agent's split is the whole tree
        raise SystemExit("(c) at N = 1 is not (a)")
    if args.json:
        print(json.dumps(r))
    else:
        print(f"{len(trees)} trees, (b) with habit {args.habit} over {args.draws} draws per tree")
        print(table(r))
        print("(a)'s moves to the exit, by tree:", r["a_moves"])
    return 0


if __name__ == "__main__":
    sys.exit(main())