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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
#!/usr/bin/env python3
"""lit_selfloop.py — the two empty-runs.

brain: the LIT machine is the world.  State = V + wiring, action = DO
(LOAD/WIRE), transition = lit_machine_step (one tick = F^64).  The
operator expands DOs, the tick creates new states, the convergence is
the halt judge, and the tree grows without any external data.

body: the EarthRover Mini Plus is the world.  State = 22 telemetry
floats + two camera hashes, action = (linear_velocity, angular_velocity)
in [-1, 1], transition = the real robot via the Frodobots SDK.  The
body cannot rewind, so it is sequential experience; each edge is
ingested into the same flat tree with lit_search_ingest.

Both use the 16-hex lit_codec: u64 state key, u64 action code.
"""
import argparse
import ctypes as C
import hashlib
import math
import struct
import sys
import time

import numpy as np

from lit_codec import FeatureCodec, hex16
from lit_libero import (
    ACTIONS_FN,
    EVENT_FN,
    EXPAND_FN,
    LIB,
    LIT_SEARCH_BUDGET,
    LIT_SEARCH_EMPTY,
    LIT_SEARCH_FOUND,
    LitAction,
    LitHost,
    LitKey,
    LitPath,
    LitSearchOpts,
    ROOT_FN,
)

MASK = (1 << 64) - 1

# ---------------------------------------------------------------- core ABI
class LitMachine(C.Structure):
    _fields_ = [
        ("n", C.c_uint32), ("k", C.c_uint32),
        ("a", C.POINTER(C.c_uint64)), ("b", C.POINTER(C.c_uint64)),
        ("V", C.POINTER(C.c_uint64)), ("prev", C.POINTER(C.c_uint64)),
        ("src", C.POINTER(C.c_uint32)), ("gain", C.POINTER(C.c_uint64)),
        ("weight", C.POINTER(C.c_uint64)), ("dist", C.POINTER(C.c_uint64)),
        ("diff", C.POINTER(C.c_uint64)),
        ("flat_src", C.POINTER(C.c_uint32)),
        ("flat_gain", C.POINTER(C.c_uint64)),
        ("flat_as", C.POINTER(C.c_uint32)),
        ("flat_bs", C.POINTER(C.c_uint32)),
        ("flat_ag", C.POINTER(C.c_uint64)),
        ("flat_bg", C.POINTER(C.c_uint64)),
        ("flat_dirty", C.c_int), ("pending", C.c_int),
        ("owns_state", C.c_int), ("bits", C.c_uint32),
        ("mask", C.c_uint64), ("levels", C.c_uint32),
        ("halt", C.c_uint32),
    ]


class LitDo(C.Structure):
    _fields_ = [
        ("kind", C.c_int), ("slot", C.c_uint32), ("src", C.c_uint32),
        ("gain", C.c_uint64), ("weight", C.c_uint64),
        ("value", C.c_uint64),
    ]


LIB.lit_machine_init.argtypes = [
    C.POINTER(LitMachine), C.POINTER(C.c_uint64), C.c_uint32, C.c_uint32,
    C.c_uint32]
LIB.lit_machine_init.restype = C.c_int
LIB.lit_machine_free.argtypes = [C.POINTER(LitMachine)]
LIB.lit_machine_load.argtypes = [C.POINTER(LitMachine),
                                 C.POINTER(C.c_uint64)]
LIB.lit_machine_graph.argtypes = [
    C.POINTER(LitMachine), C.POINTER(C.c_uint32),
    C.POINTER(C.c_uint64), C.POINTER(C.c_uint64), C.c_int]
LIB.lit_machine_graph.restype = C.c_int
LIB.lit_machine_step.argtypes = [C.POINTER(LitMachine)]
LIB.lit_machine_copy_v.argtypes = [C.POINTER(LitMachine),
                                   C.POINTER(C.c_uint64)]
LIB.lit_do_apply.argtypes = [C.POINTER(LitMachine), C.POINTER(LitDo)]
LIB.lit_do_apply.restype = C.c_int
LIB.lit_search_ingest.argtypes = [
    C.c_void_p, C.c_uint32, C.POINTER(LitAction), LitKey, C.c_uint64,
    C.c_int, C.c_int]
LIB.lit_search_ingest.restype = C.c_uint32


# ---------------------------------------------------------------- brain
class BrainHost:
    """The LIT machine as a self-generated world.

    Root state V and wiring are fixed.  The action set is open: every
    expansion samples new WIRE DOs the closed world never had, so the
    tick explores new V/wiring and the tree grows beyond the root set.
    The convergence (dist == 0) is the halt judge.
    """

    def __init__(self, max_depth=6, seed=0, new_actions=1):
        self.n = 64
        self.max_depth = max_depth
        self.new_actions = int(new_actions)
        self.rng = np.random.default_rng(seed)
        self.m = LitMachine()
        root_v = [((i * 0x9E3779B97F4A7C15) + 0x123456789ABCDEF0) & MASK
                  for i in range(self.n)]
        self.root_v = (C.c_uint64 * self.n)(*root_v)
        if LIB.lit_machine_init(C.byref(self.m), self.root_v, self.n, 1,
                                64) != 0:
            raise RuntimeError("lit_machine_init failed")
        self.root_src = (C.c_uint32 * self.n)(
            *[(i * 7 + 3) % self.n for i in range(self.n)])
        self.root_gain = (C.c_uint64 * self.n)(
            *[(((i * 2 + 1) << 33) | 1) & MASK for i in range(self.n)])
        self.root_weight = (C.c_uint64 * self.n)(*([1] * self.n))
        LIB.lit_machine_graph(C.byref(self.m), self.root_src,
                              self.root_gain, self.root_weight, -1)

        self.dos = [
            LitDo(0, i, (i + 1) % self.n,
                  (0x9E3779B97F4A7C15 ^ (i << 40)) & MASK, 1, 0)
            for i in range(8)
        ]
        self.acts_buf = (LitAction * len(self.dos))()
        for i in range(len(self.dos)):
            self.acts_buf[i].kind = i
            self.acts_buf[i].cost = 1

        self._root_cb = ROOT_FN(self._root)
        self._actions_cb = ACTIONS_FN(self._actions)
        self._expand_cb = EXPAND_FN(self._expand)
        self._event_cb = EVENT_FN(self._event)
        self.host = LitHost()
        self.host.root = self._root_cb
        self.host.actions = self._actions_cb
        self.host.expand = self._expand_cb
        self.host.event = self._event_cb

    def _grow(self):
        """Open the action set: new WIRE DOs the closed world never had."""
        for _ in range(self.new_actions):
            self.dos.append(LitDo(
                0,
                int(self.rng.integers(self.n)),
                int(self.rng.integers(self.n)),
                (int(self.rng.integers(0, 1 << 63)) << 1) | 1,
                int(self.rng.integers(1, 4)),
                0))
        self.acts_buf = (LitAction * len(self.dos))()
        for i in range(len(self.dos)):
            self.acts_buf[i].kind = i
            self.acts_buf[i].cost = 1

    def close(self):
        LIB.lit_machine_free(C.byref(self.m))

    # -- root / replay ------------------------------------------------
    def _restore_root(self):
        LIB.lit_machine_load(C.byref(self.m), self.root_v)
        LIB.lit_machine_graph(C.byref(self.m), self.root_src,
                              self.root_gain, self.root_weight, -1)

    def _apply(self, idx):
        d = self.dos[idx]
        LIB.lit_do_apply(C.byref(self.m), C.byref(d))
        LIB.lit_machine_step(C.byref(self.m))

    def _key(self):
        h = hashlib.blake2b(digest_size=16)
        h.update(b"litcore")
        for i in range(self.n):
            h.update(struct.pack("<Q", self.m.V[i]))
            h.update(struct.pack("<I", self.m.src[i]))
            h.update(struct.pack("<Q", self.m.gain[i]))
            h.update(struct.pack("<Q", self.m.weight[i]))
        d = h.digest()
        return (int.from_bytes(d[:8], "little"),
                int.from_bytes(d[8:], "little"))

    def _snapshot(self):
        v = (C.c_uint64 * self.n)()
        LIB.lit_machine_copy_v(C.byref(self.m), v)
        return (v,
                [self.m.src[i] for i in range(self.n)],
                [self.m.gain[i] for i in range(self.n)],
                [self.m.weight[i] for i in range(self.n)])

    def _restore(self, snap):
        v, src, gain, weight = snap
        LIB.lit_machine_load(C.byref(self.m), v)
        s = (C.c_uint32 * self.n)(*src)
        g = (C.c_uint64 * self.n)(*gain)
        w = (C.c_uint64 * self.n)(*weight)
        LIB.lit_machine_graph(C.byref(self.m), s, g, w, -1)

    # -- callbacks ----------------------------------------------------
    def _root(self, ctx, key, goal, dead):
        _ = ctx
        self._restore_root()
        key[0].hi, key[0].lo = self._key()
        goal[0] = 0
        dead[0] = 0
        return 0

    def _actions(self, ctx, path, path_len, acts_out, n_out):
        _ = ctx, path
        if path_len >= self.max_depth:
            n_out[0] = 0
            return 0
        self._grow()
        acts_out[0] = C.cast(self.acts_buf, C.POINTER(LitAction))
        n_out[0] = len(self.dos)
        return 0

    def _expand(self, ctx, path, path_len, acts, child_g, nacts,
                keys, goals, deads):
        _ = ctx, child_g
        self._restore_root()
        for j in range(path_len):
            self._apply(path[j].kind)
        snap = self._snapshot()
        for i in range(nacts):
            self._restore(snap)
            self._apply(acts[i].kind)
            keys[i].hi, keys[i].lo = self._key()
            goals[i] = 1 if self.m.dist[0] == 0 else 0
            deads[i] = 0
        self._restore(snap)
        return 0

    def _event(self, ctx, path, path_len, pops, nodes, open_n, g, score,
               goal):
        _ = ctx, path, open_n, g, score
        if goal or pops % 25 == 0:
            print("brain: pops=%d nodes=%d depth=%d goal=%d"
                  % (pops, nodes, path_len, goal))


# ---------------------------------------------------------------- body
# EarthRover Mini Plus telemetry (22 numeric dims; the two camera hashes
# take slots 22 and 23 of the 64-slot state).
BODY_STATE = [
    ("speed", -100.0, 100.0),
    ("battery_level", 0.0, 100.0),
    ("orientation", -360.0, 360.0),
    ("gps_latitude", -90.0, 90.0),
    ("gps_longitude", -180.0, 180.0),
    ("gps_signal", 0.0, 100.0),
    ("signal_level", 0.0, 5.0),
    ("vibration", 0.0, 10000.0),
    ("lamp", 0.0, 1.0),
    ("accelerometer_x", -100.0, 100.0),
    ("accelerometer_y", -100.0, 100.0),
    ("accelerometer_z", -100.0, 100.0),
    ("gyroscope_x", -100.0, 100.0),
    ("gyroscope_y", -100.0, 100.0),
    ("gyroscope_z", -100.0, 100.0),
    ("magnetometer_filtered_x", -1000.0, 1000.0),
    ("magnetometer_filtered_y", -1000.0, 1000.0),
    ("magnetometer_filtered_z", -1000.0, 1000.0),
    ("wheel_rpm_0", -1000.0, 1000.0),
    ("wheel_rpm_1", -1000.0, 1000.0),
    ("wheel_rpm_2", -1000.0, 1000.0),
    ("wheel_rpm_3", -1000.0, 1000.0),
]

BODY_GRID = [(lin, ang)
             for lin in (-1.0, 0.0, 1.0)
             for ang in (-1.0, 0.0, 1.0)]


class BodyHost:
    """The EarthRover Mini Plus as a sequential world.

    The robot cannot rewind, so this host only supplies the root key and
    the dummy search callbacks; every real action is ingested into the
    same flat tree with lit_search_ingest.
    """

    def __init__(self, robot):
        self.robot = robot
        stats = {n: {"min": [lo], "max": [hi]}
                 for n, lo, hi in BODY_STATE}
        self.codec = FeatureCodec.from_robot(
            "earthrover_mini_plus", robot.observation_features,
            robot.action_features, stats)
        self._root_cb = ROOT_FN(self._root)
        self._actions_cb = ACTIONS_FN(self._actions)
        self._expand_cb = EXPAND_FN(self._expand)
        self.host = LitHost()
        self.host.root = self._root_cb
        self.host.actions = self._actions_cb
        self.host.expand = self._expand_cb

    def key(self, obs):
        return (self.codec.state_key(self.codec.state_words(obs)), 0)

    def action_code(self, lin, ang):
        return self.codec.action_code([lin, ang])

    def _root(self, ctx, key, goal, dead):
        _ = ctx
        k = self.key(self.robot.get_observation())
        key[0].hi, key[0].lo = k
        goal[0] = 0
        dead[0] = 0
        return 0

    def _actions(self, ctx, path, path_len, acts_out, n_out):
        _ = ctx, path, path_len, acts_out
        n_out[0] = 0
        return 0

    def _expand(self, ctx, path, path_len, acts, child_g, nacts,
                keys, goals, deads):
        _ = ctx, path, path_len, acts, child_g, nacts, keys, goals, deads
        return 0


# ---------------------------------------------------------------- runs
def run_brain(args):
    h = BrainHost(max_depth=args.max_depth,
                  seed=args.seed)
    s = LIB.lit_search_new(C.byref(h.host))
    if not s:
        raise SystemExit("lit_search_new failed")
    try:
        for level in range(args.levels):
            opts = LitSearchOpts(max_steps=0, max_nodes=args.nodes)
            path = LitPath()
            rc = LIB.lit_search_continue(s, C.byref(opts), C.byref(path))
            print("brain level %d: rc=%d pops=%d nodes=%d path=%d actions=%d"
                  % (level, rc, path.pops, path.nodes, path.n, len(h.dos)))
            if rc == LIT_SEARCH_FOUND and path.n:
                acts = [path.acts[i].kind for i in range(path.n)]
                print("brain win path:", acts)
            LIB.lit_path_free(C.byref(path))
            if rc not in (LIT_SEARCH_FOUND, LIT_SEARCH_EMPTY,
                          LIT_SEARCH_BUDGET):
                break
    finally:
        LIB.lit_search_free(s)
        h.close()
    return 0


def haversine(lat1, lon1, lat2, lon2):
    r = 6371000.0
    p1, p2 = math.radians(lat1), math.radians(lat2)
    dp = math.radians(lat2 - lat1)
    dl = math.radians(lon2 - lon1)
    a = (math.sin(dp / 2) ** 2 +
         math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2)
    return 2 * r * math.asin(math.sqrt(a))


def run_body(args):
    try:
        from lerobot.robots.earthrover_mini_plus import (
            EarthRoverMiniPlus, EarthRoverMiniPlusConfig)
    except Exception as e:
        print("LeRobot EarthRover Mini Plus import failed:", e)
        return 1

    robot = EarthRoverMiniPlus(EarthRoverMiniPlusConfig())
    try:
        robot.connect()
    except Exception as e:
        print("Frodobots SDK is not running:", e)
        print("Start it first:")
        print("  git clone https://github.com/frodobots-org/earth-rovers-sdk.git")
        print("  cd earth-rovers-sdk && pip install -r requirements.txt")
        print("  # .env: SDK_API_TOKEN, BOT_SLUG, CHROME_EXECUTABLE_PATH, MISSION_SLUG")
        print("  hypercorn main:app --reload")
        print("  open http://localhost:8000 and click Join")
        return 1

    if args.target_lat is not None and args.target_lon is not None:
        def judge(obs):
            return 1 if haversine(obs["gps_latitude"], obs["gps_longitude"],
                                  args.target_lat, args.target_lon) <= args.radius else 0
    else:
        def judge(obs):
            _ = obs
            return 0

    host = BodyHost(robot)
    s = LIB.lit_search_new(C.byref(host.host))
    if not s:
        robot.disconnect()
        raise SystemExit("lit_search_new failed")

    rng = np.random.default_rng(args.seed)
    parent = 0
    try:
        for step in range(args.steps):
            if args.policy == "random":
                lin, ang = BODY_GRID[int(rng.integers(len(BODY_GRID)))]
            else:
                lin, ang = BODY_GRID[step % len(BODY_GRID)]
            code = host.action_code(lin, ang)
            act = LitAction(0, code & 0xFFFFFFFF, (code >> 32) & 0xFFFFFFFF,
                            0, 1)
            robot.send_action({"linear_velocity": lin,
                               "angular_velocity": ang})
            time.sleep(1.0 / args.fps)
            obs = robot.get_observation()
            k = host.key(obs)
            goal = judge(obs)
            parent = LIB.lit_search_ingest(
                s, parent, C.byref(act), LitKey(k[0], k[1]),
                step + 1, goal, 0)
            print("body: step=%d a=(%.1f,%.1f) code=%s key=%s goal=%d"
                  % (step, lin, ang, hex16(code), hex16(k[0]), goal))
            if parent == 0xFFFFFFFF:
                print("ingest failed")
                break
            if goal:
                print("body: judge win at step", step)
                break
    finally:
        LIB.lit_search_free(s)
        robot.disconnect()
    return 0


def main(argv):
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--mode", choices=["brain", "body"], default="brain")
    p.add_argument("--nodes", type=int, default=100)
    p.add_argument("--levels", type=int, default=3)
    p.add_argument("--max-depth", type=int, default=6)
    p.add_argument("--steps", type=int, default=100)
    p.add_argument("--fps", type=float, default=10.0)
    p.add_argument("--policy", choices=["cycle", "random"], default="cycle")
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--target-lat", type=float, default=None)
    p.add_argument("--target-lon", type=float, default=None)
    p.add_argument("--radius", type=float, default=3.0)
    args = p.parse_args(argv[1:])
    if args.mode == "brain":
        return run_brain(args)
    return run_body(args)


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))