File size: 11,358 Bytes
232313d
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
fda80b2
 
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af7da50
fda80b2
 
af7da50
fda80b2
232313d
fda80b2
 
 
 
 
 
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fda80b2
 
232313d
 
 
 
 
 
 
 
af7da50
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Closed-loop game simulations driven by any `decide(state, questions) -> answers` callable (the System One call).

The method of a Snake race: the game code works out what each move would do and words it; the model
answers one yes/no question per move; the move with the highest P(yes) is played. Two framings, as in JevSpatial:
  q  the consequence is written INSIDE each question ("Moving up: the snake moves closer to the food. Should the snake
     move up?"), minimal status state;
  s  the consequences are in the STATE ({"if the snake moves up": ...}), plain questions ("Is moving up a good move?").
Games (toy physics, fixed seeds, endless: a crash restarts the game): Snake 12x12, Dino, Breakout, Whac-A-Mole.
Reported per game and framing, over N decisions: apples (Snake), obstacles cleared (Dino), bricks (Breakout), moles
(Whac-A-Mole), the failures, and the median decision latency in ms. Wording and consequences come from
spatial_bench.py.

  # any Python decider: module.path:factory, factory() returns an object with .decide(state, questions) or a function:
  python play_bench.py --decider python --decider-target my_module:make_decider --decisions 300
  # a /v1/systemone server (any server speaking the same protocol):
  python play_bench.py --decider http --url http://127.0.0.1:8017 --decisions 300
  # references: --decider oracle (always the best move), --decider random
"""

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

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))

import spatial_bench as S  # noqa: E402

GAMES = ("Snake", "Dino", "Breakout", "Whac-A-Mole")


# ------------------------------------------------------------------ environments
class Snake:
    name, n = "Snake", 12

    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.m = {"apples": 0, "deaths": 0}
        self.reset()

    def reset(self):
        c = (self.n // 2, self.n // 2)
        self.walk = [(c[0], c[1] - 2), (c[0], c[1] - 1), c]
        self.age = 0
        self.spawn()

    def spawn(self):
        free = [(r, c) for r in range(self.n) for c in range(self.n) if (r, c) not in self.walk]
        self.food = self.rng.choice(free)

    def sit(self):
        moves = S.snake_moves(self.walk, self.food, self.n)
        status = {"game": "Snake", "board": f"{self.n}x{self.n}", "length": len(self.walk),
                  "apples eaten": len(self.walk) - 3, "turn": self.age}
        return {"game": "Snake", "unit": "the snake", "status": status, "moves": moves}

    def act(self, mid):
        self.age += 1
        dr, dc = S.DIRS[mid]
        h = self.walk[-1]
        new = (h[0] + dr, h[1] + dc)
        if not (0 <= new[0] < self.n and 0 <= new[1] < self.n) or new in self.walk[1:] or self.age > 600:
            self.m["deaths"] += 1
            return self.reset()
        self.walk.append(new)
        if new == self.food:
            self.m["apples"] += 1
            self.spawn()
        else:
            self.walk.pop(0)


class Dino:
    name, v, lo = "Dino", 8, 34

    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.m = {"obstacles_cleared": 0, "crashes": 0}
        self.obs = []  # [distance of the front edge, kind]
        self.busy = 0
        self.score = 0
        self.fill()

    def fill(self):
        last = self.obs[-1][0] if self.obs else 150
        while len(self.obs) < 3:
            last += self.rng.randint(150, 260)
            self.obs.append([last, self.rng.choice(list(S.DINO_OBS))])

    def phase(self):
        if not self.obs or self.obs[0][0] >= 160:
            return "clear", "clear"
        d, kind = self.obs[0]
        return ("now" if d < self.lo + self.v else "far"), kind

    def advance(self):
        for o in self.obs:
            o[0] -= self.v
        self.score += 1

    def settle(self):
        """Obstacles that reached the dinosaur without an action hit it."""
        while self.obs and self.obs[0][0] < self.lo:
            self.m["crashes"] += 1
            self.obs.pop(0)
        self.fill()

    def sit(self):
        ph, kind = self.phase()
        moves = S.dino_moves(kind, ph)
        status = {"game": "Dino", "score": self.score, "speed": "medium"}
        return {"game": "Dino", "unit": "the dinosaur", "status": status, "moves": moves}

    def act(self, mid):
        ph, kind = self.phase()
        need = "run" if ph != "now" else ("duck" if S.DINO_OBS[kind] == "high" else "jump")
        if ph == "now":
            self.obs.pop(0)
            self.m["obstacles_cleared" if mid == need else "crashes"] += 1
            self.fill()
        elif mid != need:  # acted too early: busy for a few ticks, obstacles keep coming
            for _ in range(6):
                self.advance()
                self.settle()
            return
        self.advance()
        self.settle()


class Breakout:
    name, W, w, step = "Breakout", 200, 40, 20

    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.m = {"bricks": 0, "balls_lost": 0}
        self.p = 100
        self.launch()

    def launch(self):
        self.t = self.rng.randint(5, 9)
        reach = (self.t - 1) * self.step
        self.x = min(self.W - 10, max(10, self.p + self.rng.randint(-reach, reach)))

    def sit(self):
        moves = S.breakout_moves(self.p, self.x, self.w, self.step, self.W)
        status = {"game": "Breakout", "lives": 3, "bricks left": 40 - self.m["bricks"] % 40}
        return {"game": "Breakout", "unit": "the paddle", "status": status, "moves": moves}

    def act(self, mid):
        d = {"left": -1, "stay": 0, "right": 1}[mid]
        self.p = min(self.W - self.w // 2, max(self.w // 2, self.p + d * self.step))
        self.t -= 1
        if self.t == 0:
            self.m["bricks" if abs(self.p - self.x) <= self.w // 2 else "balls_lost"] += 1
            self.launch()


class Mole:
    name = "Whac-A-Mole"

    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.m = {"moles": 0, "bombs_hit": 0, "empty_swings": 0}
        self.kinds = {}

    def sit(self):
        while True:
            s = S.mole_sit(self.rng)
            if s:
                break
        self.kinds = {m["id"]: ("mole" if m["good"] else "bomb" if m["rank"] == 0 else "empty") for m in s["moves"]}
        return s

    def act(self, mid):
        k = self.kinds[mid]
        self.m["moles" if k == "mole" else "bombs_hit" if k == "bomb" else "empty_swings"] += 1


ENVS = {"Snake": Snake, "Dino": Dino, "Breakout": Breakout, "Whac-A-Mole": Mole}


# ------------------------------------------------------------------ deciders
def p_yes(a) -> float:
    """P(yes) from a System One noul answer ({"noul": p}, or a probabilities / probability variant)."""
    if isinstance(a, (int, float)):
        return float(a)
    if isinstance(a, dict):
        for k in ("noul", "probability", "p_yes", "yes"):
            if k in a:
                return float(a[k])
        pr = a.get("probabilities")
        if isinstance(pr, dict):
            for k in ("true", "yes", "True"):
                if k in pr:
                    return float(pr[k])
    raise ValueError(f"no P(yes) in {a!r}")


def make_python(target):
    """`module.path:factory`: import the module, call factory(); use the result's .decide(state, questions), or the
    result itself when it is a function."""
    import importlib
    import os

    sys.path.insert(0, os.getcwd())
    mod, _, name = target.partition(":")
    if not name:
        raise SystemExit("--decider-target must look like module.path:factory")
    obj = getattr(importlib.import_module(mod), name)()
    return obj.decide if hasattr(obj, "decide") else obj


def make_http(url="http://127.0.0.1:8017", key=None, model="jev-latest", timeout=30):
    import urllib.request

    def decide(state, questions):
        req = urllib.request.Request(url.rstrip("/") + "/v1/systemone", method="POST",
                                     data=json.dumps({"model": model, "state": state, "questions": questions}).encode(),
                                     headers={"Content-Type": "application/json",
                                              **({"Authorization": f"Bearer {key}"} if key else {})})
        out = json.load(urllib.request.urlopen(req, timeout=timeout))
        for wrap in ("answers", "results", "output"):  # tolerate an envelope around the {question id: answer} map
            if isinstance(out, dict) and wrap in out and isinstance(out[wrap], dict) and set(questions) <= set(out[wrap]):
                return out[wrap]
        return out

    return decide


def make_random(seed=0):
    rng = random.Random(seed)
    return lambda state, questions: {k: {"type": "noul", "noul": rng.random()} for k in questions}


# ------------------------------------------------------------------ the loop
def play(game: str, framing: str, decide, decisions: int, seed: int = 0, oracle: bool = False) -> dict:
    env = ENVS[game](seed)
    rng = random.Random(f"{seed}:frame")
    lat = []
    t_all = time.perf_counter()
    for i in range(decisions):
        sit = env.sit()
        item = (S.render_q if framing == "q" else S.render_s)(sit, rng, i)
        keys = [m["id"] for m in sit["moves"]]
        if oracle:
            mid = max(sit["moves"], key=lambda m: m["rank"])["id"]
        else:
            t = time.perf_counter()
            ans = decide(item["state"], {k: q for k, q in item["questions"].items() if k in keys})
            lat.append((time.perf_counter() - t) * 1000)
            mid = max(keys, key=lambda k: p_yes(ans[k]))
        env.act(mid)
    out = {"game": game, "framing": framing, "decisions": decisions, **env.m,
           "median_decision_ms": round(statistics.median(lat), 2) if lat else None,
           "wall_s": round(time.perf_counter() - t_all, 2)}
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--decider", choices=["python", "http", "oracle", "random"], default="python")
    ap.add_argument("--decider-target", default=None, help="module.path:factory for --decider python")
    ap.add_argument("--url", default="http://127.0.0.1:8017")
    ap.add_argument("--key", default=None)
    ap.add_argument("--decisions", type=int, default=300, help="decisions per game and framing")
    ap.add_argument("--games", default=",".join(GAMES))
    ap.add_argument("--framings", default="q,s")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=None)
    a = ap.parse_args()
    decide = {"python": lambda: make_python(a.decider_target), "http": lambda: make_http(a.url, a.key),
              "random": make_random, "oracle": lambda: None}[a.decider]()
    if decide is not None and a.decider != "random":  # warm-up: compile / load outside the timed loop
        play("Snake", "q", decide, 3, seed=999)
    rows = []
    for g in a.games.split(","):
        for f in a.framings.split(","):
            r = play(g, f, decide, a.decisions, a.seed, oracle=a.decider == "oracle")
            rows.append(r)
            print(json.dumps(r), flush=True)
    if a.out:
        json.dump(rows, open(a.out, "w"), indent=1)


if __name__ == "__main__":
    main()