Add extract_predict.py, which builds the movement-prediction corpus: for each sampled tick with the shooter fixed to DevControlBot (power 2), the label is wrap(trueImpactBearing - geometricInterceptBearing), solved against the observer's true trajectory. Unlike the old opponent-aim-error label this is centred near zero (mean -0.33 deg, sd 18.3 deg). Add train_predict.nim: round-group 5-fold evaluation, baselines (plain intercept / constant), small H x lambda sweep, prediction-mean centring check, and a |correction|>tau gate calibrated on held-out folds, then export. Delete the old train_elm_gun.nim (it wrote the live weights from the old label) and mark extract_realistic.py deprecated.
197 lines
7.1 KiB
Python
197 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Movement-prediction corpus: LABEL = correction from the geometric intercept to
|
|
the enemy's TRUE impact point.
|
|
|
|
This replaces the old opponent-bias label. The old label measured how far the
|
|
SHOOTER's shot landed from a correct intercept (the opponent's own aim error);
|
|
using that as our own correction is why the ELM added a constant +1.6..+11 deg
|
|
bias. The new label measures the TARGET's real motion deviation:
|
|
|
|
base = plain geometric intercept bearing, solved from the target's CURRENT
|
|
scan-based position/velocity (the same `heuristicAim` the gun runs);
|
|
true = bearing to the target's ACTUAL position at the tick the bullet of
|
|
speed v reaches it, taken from the observer's true trajectory;
|
|
label = wrap(true - base).
|
|
|
|
A target that holds a straight line gives label 0; a target that turns/accelerates
|
|
gives the correction a real movement-prediction gun must apply. Samples are built
|
|
with the shooter FIXED to DevControlBot (power 2, v = 14) so the shooter's own
|
|
state and the bullet speed match the live gun; the TARGET is the opponent whose
|
|
movement we want to learn.
|
|
|
|
Output: samples_predict.ndjson, one row per sampled tick.
|
|
|
|
python3 extract_predict.py [OUT.ndjson] [ROOT] [--stride N] [--shooter NAME]
|
|
"""
|
|
import glob, gzip, json, math, os, sys
|
|
|
|
TAU = 2 * math.pi
|
|
W = 8 # motion-window length (scans), newest first
|
|
POWER = 2.0
|
|
VB = 20.0 - 3.0 * POWER # physical bullet speed, = 14
|
|
|
|
|
|
def wrap(a):
|
|
while a > math.pi:
|
|
a -= TAU
|
|
while a < -math.pi:
|
|
a += TAU
|
|
return a
|
|
|
|
|
|
def sample_std(v):
|
|
if len(v) < 2:
|
|
return 0.0
|
|
m = sum(v) / len(v)
|
|
return math.sqrt(sum((x - m) ** 2 for x in v) / len(v))
|
|
|
|
|
|
def extract(path, tag, out, shooter_name, stride):
|
|
ticks = []
|
|
with gzip.open(path, "rt") as fh:
|
|
for line in fh:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
m = json.loads(line)
|
|
if m.get("type") == "TickEventForObserver":
|
|
ticks.append(m)
|
|
|
|
# true trajectory: (round, botId) -> {turn: (x, y)}
|
|
track = {}
|
|
names = {}
|
|
for m in ticks:
|
|
rnd, turn = m["roundNumber"], m["turnNumber"]
|
|
for b in m["botStates"]:
|
|
names[b["id"]] = b["name"]
|
|
track.setdefault((rnd, b["id"]), {})[turn] = (b["x"], b["y"])
|
|
|
|
def true_pos(rnd, bid, t):
|
|
tr = track[(rnd, bid)]
|
|
lo = math.floor(t)
|
|
if lo not in tr:
|
|
return None
|
|
if lo + 1 in tr:
|
|
f = t - lo
|
|
x0, y0 = tr[lo]
|
|
x1, y1 = tr[lo + 1]
|
|
return (x0 + (x1 - x0) * f, y0 + (y1 - y0) * f)
|
|
return tr[lo]
|
|
|
|
n = 0
|
|
for m in ticks:
|
|
rnd, turn = m["roundNumber"], m["turnNumber"]
|
|
if turn % stride != 0:
|
|
continue
|
|
bs = {b["id"]: b for b in m["botStates"]}
|
|
sids = [i for i, b in bs.items() if b["name"] == shooter_name and b["energy"] > 0]
|
|
if len(sids) != 1:
|
|
continue
|
|
sid = sids[0]
|
|
tid = [i for i in bs if i != sid and bs[i]["energy"] > 0]
|
|
if len(tid) != 1:
|
|
continue
|
|
tid = tid[0]
|
|
S = (bs[sid]["x"], bs[sid]["y"])
|
|
tr = track.get((rnd, tid), {})
|
|
# need a full window of true positions behind the fire tick
|
|
if len(tr) < W or any((turn - k) not in tr for k in range(1, W)):
|
|
continue
|
|
|
|
win = [tr[turn - k] for k in range(W)] # newest first
|
|
winTick = [turn - k for k in range(W)]
|
|
ex, ey = win[0]
|
|
vx = (win[0][0] - win[1][0]) / float(winTick[0] - winTick[1])
|
|
vy = (win[0][1] - win[1][1]) / float(winTick[0] - winTick[1])
|
|
|
|
# ---- base: geometric intercept from the scan belief (heuristicAim) ----
|
|
d = math.hypot(ex - S[0], ey - S[1])
|
|
tof = d / VB
|
|
bx, by = ex + vx * tof, ey + vy * tof
|
|
base = math.atan2(by - S[1], bx - S[0])
|
|
|
|
# ---- true impact: target's TRUE position when the bullet arrives -----
|
|
t = d / VB
|
|
p = true_pos(rnd, tid, turn + t)
|
|
for _ in range(8):
|
|
if p is None:
|
|
break
|
|
t = math.hypot(p[0] - S[0], p[1] - S[1]) / VB
|
|
p = true_pos(rnd, tid, turn + t)
|
|
if p is None:
|
|
continue
|
|
true_ang = math.atan2(p[1] - S[1], p[0] - S[0])
|
|
label = wrap(true_ang - base)
|
|
|
|
# ---- features (target-motion-centric) --------------------------------
|
|
ang = math.atan2(ey - S[1], ex - S[0]) # line-of-sight bearing
|
|
rel = wrap(ang - math.radians(bs[sid]["direction"]))
|
|
sp = math.hypot(vx, vy)
|
|
lat = -vx * math.sin(ang) + vy * math.cos(ang)
|
|
rad = vx * math.cos(ang) + vy * math.sin(ang)
|
|
losrate = lat / max(d, 1.0)
|
|
pred_err = wrap(base - ang)
|
|
disp = []
|
|
speeds = []
|
|
for k in range(W - 1):
|
|
gap = float(winTick[k] - winTick[k + 1])
|
|
dx = (win[k][0] - win[k + 1][0]) / gap
|
|
dy = (win[k][1] - win[k + 1][1]) / gap
|
|
disp.append((dx, dy))
|
|
speeds.append(math.hypot(dx, dy))
|
|
# heading / turn of the newest two displacements
|
|
hx, hy = disp[0]
|
|
head = math.atan2(hy, hx)
|
|
phead = math.atan2(disp[1][1], disp[1][0])
|
|
dtheta = wrap(head - phead)
|
|
curve = abs(dtheta) / max(sp, 1e-6)
|
|
|
|
rec = {
|
|
"group": f"{names[tid]}:{tag}:{rnd}",
|
|
"target": names[tid],
|
|
"round": rnd, "tick": turn, "shooter": shooter_name,
|
|
"label": label,
|
|
"ownX": S[0], "ownY": S[1],
|
|
"ownHeading": math.radians(bs[sid]["direction"]),
|
|
"ownSpeed": abs(bs[sid]["speed"]),
|
|
"gunHeat": bs[sid].get("gunHeat", 0.0),
|
|
"power": POWER, "bulletSpeed": VB,
|
|
"ex": ex, "ey": ey, "vx": vx, "vy": vy,
|
|
"scanAge": 0.0, "scanGap": 1.0,
|
|
"winX": [p[0] for p in win], "winY": [p[1] for p in win],
|
|
"winTick": winTick,
|
|
# diagnostics
|
|
"dbg_speed": sp, "dbg_curve": curve,
|
|
}
|
|
out.write(json.dumps(rec) + "\n")
|
|
n += 1
|
|
return n
|
|
|
|
|
|
def main():
|
|
here = os.path.dirname(os.path.abspath(__file__))
|
|
repo = os.path.abspath(os.path.join(here, "..", ".."))
|
|
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
|
stride = 5
|
|
shooter = "DevControlBot"
|
|
for a in sys.argv[1:]:
|
|
if a.startswith("--stride"):
|
|
stride = int(a.split("=")[1]) if "=" in a else stride
|
|
if a.startswith("--shooter"):
|
|
shooter = a.split("=")[1] if "=" in a else shooter
|
|
dest = os.path.join(here, args[0] if args else "samples_predict.ndjson")
|
|
root = os.path.abspath(args[1]) if len(args) > 1 else os.path.join(repo, "data")
|
|
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, out, shooter, stride)
|
|
print(f"{tag}/{os.path.basename(f)}: {k} samples")
|
|
total += k
|
|
print("TOTAL", total, "->", dest)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|