#!/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("= 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))