#!/usr/bin/env python3 """Extract RING labels for every scan tick per enemy. The ring (tools/ring_spike/spike.py) fires N rays simultaneously from the shooter's BELIEF centre at bullet speed and takes the first contact with the enemy circle. The label is the 2-D offset between that contact's enemy position and the belief centre, dead-reckoned to the CONTACT tick: Pstar = enemy TRUE position at tick fire+k (observer truth) C = belief centre dead-reckoned to fire+k (what we believed then) R = Pstar - C (px, the ring label) decomposed in the shooter's frame at fire time: radial = R . u (u = unit bearing C-S) range error lateral = R . n (n = left of u) aim error label = atan2(lateral, beliefDist) radians -- SAME UNITS AND SIGN as the incumbent 1-D aim-error label, so the two are comparable row-for-row. Belief reconstruction and ring geometry are imported from spike.py (one definition, no drift). Default is same-tick semantics (fire_tick = scan tick, last scan with turn <= fire_tick), matching extract_realistic.py's default; --prev is the strictly-prior variant (fire_tick = scan tick + 1, last scan with turn < fire_tick), matching extract_realistic.py --prev. usage: extract_ring.py [OUT.ndjson] [ROOT] [--prev] [--base FILE] --base FILE merge into an existing samples_*.ndjson instead of emitting a bare side table: every base row keeps its own features and gains ringK/ringLat/ringRad/ringLatAng, `label` becomes the ring label and `label1d` keeps the incumbent aim error. """ import glob, gzip, json, math, os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(REPO0 := os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")), "tools", "ring_spike")) from spike import collect, ring_contact, BOT_RADIUS REPO = REPO0 def wrap(a): while a > math.pi: a -= TAU while a < -math.pi: a += TAU return a TAU = 2 * math.pi def belief_centre(hist, ft, prev): """Same belief as extract_realistic.py: last two usable scans, then dead-reckon with the two-point velocity to `ft`. Returns (cx, cy, age).""" use = [h for h in hist if (h[0] < ft if prev else h[0] <= ft)] if len(use) < 2: return None (t1, x1, y1), (t0, x0, y0) = use[-1], use[-2] gap = t1 - t0 if gap <= 0: return None age = ft - t1 if age < 0: return None return (x1 + (x1 - x0) / gap * age, y1 + (y1 - y0) / gap * age, age) def extract(path, tag, prev, spd, rays, rng, out, kint=False): scans, true, names = collect(path) n = 0 for rnd in sorted({k[0] for k in scans}): bots = sorted({k[1] for k in scans if k[0] == rnd} | {k[2] for k in scans if k[0] == rnd}) for s in bots: for t in bots: if s == t: continue h = scans.get((rnd, s, t), []) if len(h) < 2: continue track = {turn: xy for (rr, bid, turn), xy in true.items() if rr == rnd and bid == t} for (st, _, _) in h: ft = st + 1 if prev else st bc = belief_centre(h, ft, prev) if bc is None: continue Sp = true.get((rnd, s, ft)) if Sp is None: continue res = ring_contact((bc[0], bc[1]), track, ft, spd, rays, rng) if res is None: continue _, k = res Pstar = track.get(ft + k) if Pstar is None: continue los = math.atan2(bc[1] - Sp[1], bc[0] - Sp[0]) de = math.hypot(bc[0] - Sp[0], bc[1] - Sp[1]) if kint: # INTENDED ring tick: the bullet flight time, i.e. the tick # at which a shot aimed at the belief would land. Fully # observable (round(believed range / bullet speed)); used # because the literal contact search degenerates to k=1 # (see README: the belief is already within BotRadius of # the enemy, so ray step 1 always "hits"). k = max(1, int(round(de / spd))) Pstar = track.get(ft + k) if Pstar is None: continue ux, uy = math.cos(los), math.sin(los) nx, ny = -uy, ux rx, ry = Pstar[0] - bc[0], Pstar[1] - bc[1] lat = rx * nx + ry * ny rad = rx * ux + ry * uy out.write(json.dumps({ "group": f"{tag}:{rnd}", "round": rnd, "tick": ft, "shooter": names.get(s, str(s)), "target": names.get(t, str(t)), "ringK": k, "ringLat": lat, "ringRad": rad, "ringMag": math.hypot(rx, ry), "ringLatAng": math.atan2(lat, max(de, 1.0)), "ringRadAng": math.atan2(rad, max(de, 1.0)), "ringDist": de, "ringAge": bc[2], }) + "\n") n += 1 return n def main(): here = os.path.dirname(os.path.abspath(__file__)) args = [a for a in sys.argv[1:] if not a.startswith("--")] prev = "--prev" in sys.argv kint = "--kintercept" in sys.argv base = None if "--base" in sys.argv: base = sys.argv[sys.argv.index("--base") + 1] args = [a for a in args if a != base] dest = os.path.join(here, args[0] if args else "ring.ndjson") root = os.path.abspath(args[1]) if len(args) > 1 else os.path.join(REPO, "data", "drussgt_raw") spd = 10.0 # bullet power 1.0 -> 10 px/tick; spike: <=1.5 reaches 100% rays = 360 rng = 800.0 files = sorted(glob.glob(os.path.join(root, "**", "*.battle.gz"), recursive=True)) total = 0 with open(dest, "w") as out: for f in files: tag = os.path.relpath(os.path.dirname(f), root).replace(os.sep, ":") k = extract(f, tag, prev, spd, rays, rng, out, kint) total += k print(f"{tag}/{os.path.basename(f)}: {k} ring contacts") print("TOTAL", total, "->", dest) if base: bp = os.path.join(here, base) side = {} for line in open(dest): j = json.loads(line) side[(j["group"], j["round"], j["tick"], j["shooter"], j["target"])] = j merged = os.path.join(here, dest + ".merged") hit = 0 n = 0 with open(bp) as src, open(merged, "w") as out: for line in src: if not line.strip(): continue j = json.loads(line) key = (j["group"], j["round"], j["tick"], j["shooter"], j["target"]) r = side.get(key) if r is None: continue hit += 1 n += 1 j["label1d"] = j["label"] j["label"] = r["ringLatAng"] for f in ("ringK", "ringLat", "ringRad", "ringMag", "ringLatAng", "ringRadAng", "ringDist"): j[f] = r[f] out.write(json.dumps(j) + "\n") print(f"MERGED {n} of {sum(1 for _ in open(bp))} base rows -> {merged}") if __name__ == "__main__": main()