guns/elm.nim online sequential ELM (ridge/RLS), fixed random
hidden layer, one pass, no backprop
guns/waveelm.nim the WaveElm gun: a simulated omnidirectional expanding
ring of probes fired from the SHOOTER, where the ELM
learns a BIAS CORRECTION to the ring's reconstructed
position (predicting the position outright was measured
and refuted: it collapses on abrupt/burst movement)
guns/gun_knowledge.nim GUNK: a learned additive angular residual on top of
the self-consistent lead forecast. Only answers "which
absolute gun direction", nothing else
guns/docs/ the open-access OS-ELM / ELM reference set plus
fetch_papers.sh, which re-downloads it idempotently
Plus the matching test and measurement harnesses (test_waveelm*, test_elm,
test_gun_knowledge, test_knowledge_registration, gk_aim_probe,
measure_gk_{residual,virtual}.py) and the docs README with the citations.
1395 lines
66 KiB
Nim
1395 lines
66 KiB
Nim
## Unit tests for guns/gun_knowledge.nim — the 15-bit key over 3840 rows, the
|
|
## residual bins, the self-consistent forecast base, the closed-form CROSS-CHECK,
|
|
## the scan-track turn/trend derivation (with gkUnknown as a first-class value),
|
|
## the opponent -> global -> zero fallback chain, learning, and hard
|
|
## save/load (atomic write, strict header, truncation rejection, exact
|
|
## round-trip).
|
|
##
|
|
## No Java, no battle, no env vars. Run:
|
|
## nim c -r --path:common_libs common_libs/tests/test_gun_knowledge.nim
|
|
|
|
import std/[math, os, random, strutils, tables]
|
|
import guns/gun_knowledge
|
|
import gun_harness/gun_interface
|
|
import gun_harness/virtual_bullets # PowerBins, the slots pending[] is indexed by
|
|
import guns/lead_forecast # radialFrac / VelocityTracker (feature 6)
|
|
|
|
var checks = 0
|
|
var failures = 0
|
|
proc check(name: string, ok: bool) =
|
|
inc checks
|
|
if ok: echo "PASS: ", name
|
|
else:
|
|
echo "FAIL: ", name
|
|
inc failures
|
|
|
|
proc captureStderr(body: proc()): string =
|
|
## Run `body` with the process stderr pointed at a temp file and return what
|
|
## it wrote. Persistence failures are REPORTED, not raised, so the only way a
|
|
## test can see the diagnostic is to read it.
|
|
let cap = getTempDir() / "gk_stderr_capture.txt"
|
|
removeFile(cap)
|
|
let saved = stderr
|
|
var f = open(cap, fmWrite)
|
|
stderr = f
|
|
body()
|
|
stderr.flushFile()
|
|
close(stderr)
|
|
stderr = saved
|
|
result = readFile(cap)
|
|
removeFile(cap)
|
|
|
|
proc close(a, b: float, eps = 1e-6): bool = abs(a - b) < eps
|
|
|
|
proc mk(ex, ey, dir, spd, power: float): GkFeatures =
|
|
## Self at the origin, enemy at (ex, ey), world heading `dir`, and the three
|
|
## enum features at their NEUTRAL bins (straight / constant / free), which is
|
|
## what the caller means by "nothing observed yet".
|
|
GkFeatures(enemyX: ex, enemyY: ey, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: dir, enemySpeed: spd, power: power,
|
|
turning: gkStraight, speedTrend: gkConstant, space: gkFree,
|
|
hasTarget: true)
|
|
|
|
proc legalFresh(a: GkAim): bool =
|
|
## What EXPLORATION GUARANTEES on an under-sampled row: nothing is learned
|
|
## from an OPPONENT row yet, and the residual is EITHER the null (bin -1) OR
|
|
## exactly the centre of the bin `aim` reported. That is the whole contract
|
|
## between `aim` and `update`: whatever `residualBin` says is what gets
|
|
## filed, so the answer must be reproducible from the bin alone.
|
|
a.source != gkSourceOpponent and
|
|
(a.residualBin == -1 or
|
|
(a.residualBin in 0 ..< GK_NBINS and
|
|
close(a.residual, binCentre(a.residualBin), 1e-9)))
|
|
|
|
# ── 1. residual bins: round-trip and clamping ─────────────────────────────────
|
|
|
|
proc testResidualBins() =
|
|
check "the negative step is 60/32 = 1.875 deg", close(GK_RES_WIDTH, 1.875)
|
|
check "the positive step is 2.0 deg (32 bins, 16 below and 15 above the null)",
|
|
close(GK_RES_POS_WIDTH, 2.0)
|
|
check "bin 0 is the NULL residual and it is 0 deg",
|
|
GK_NULL_BIN == 0 and binCentre(GK_NULL_BIN) == 0.0
|
|
check "a 0 deg residual lands on the null bin", residualBin(0.0) == 0
|
|
check "a small negative lands on the null bin", residualBin(-0.5) == 0
|
|
check "a small positive lands on the null bin", residualBin(1.99) == 0
|
|
check "-1.875 deg is the bin just below the null", residualBin(-1.875) == 1
|
|
check "+2.0 deg is the bin just above the null", residualBin(2.0) == 17
|
|
check "-30.0 deg is the most negative centre", residualBin(-30.0) == 16
|
|
check "+30.0 deg is the most positive centre", residualBin(30.0) == 31
|
|
check "-30.1 deg clamps into the -30 bin", residualBin(-30.1) == 16
|
|
check "+30.1 deg clamps into the +30 bin", residualBin(30.1) == 31
|
|
check "lowest angle clamps to the -30 bin", residualBin(-1.0e6) == 16
|
|
check "highest angle clamps to the +30 bin", residualBin(1.0e6) == 31
|
|
check "binCentre(0) is 0, not a large correction", binCentre(0) == 0.0
|
|
check "binCentre(1) is just below the null", close(binCentre(1), -1.875)
|
|
check "binCentre(16) is the -30 extreme", close(binCentre(16), -30.0)
|
|
check "binCentre(17) is just above the null", close(binCentre(17), 2.0)
|
|
check "binCentre(31) is the +30 extreme", close(binCentre(31), 30.0)
|
|
check "binCentre clamps out-of-range indices",
|
|
binCentre(-5) == binCentre(0) and binCentre(99) == binCentre(31)
|
|
# exact inverses, BOTH directions, over all 32 bins
|
|
var fwdStable = true
|
|
var backStable = true
|
|
for b in 0 ..< GK_NBINS:
|
|
if residualBin(binCentre(b)) != b: fwdStable = false
|
|
if abs(binCentre(residualBin(binCentre(b))) - binCentre(b)) > 0.0:
|
|
backStable = false
|
|
check "angle -> bin -> centre -> bin is the identity for all 32 bins", fwdStable
|
|
check "bin -> centre -> bin -> centre is the identity for all 32 bins", backStable
|
|
# and the 32 centres really span exactly [-30, +30], with 0 in the middle
|
|
var lo = binCentre(0)
|
|
var hi = binCentre(0)
|
|
for b in 0 ..< GK_NBINS:
|
|
lo = min(lo, binCentre(b))
|
|
hi = max(hi, binCentre(b))
|
|
check "the 32 centres span exactly [-30,+30]",
|
|
close(lo, GK_RES_LO) and close(hi, GK_RES_HI) and
|
|
close(lo, -30.0) and close(hi, 30.0)
|
|
check "the null bin is in the middle: 16 bins below it, 15 above",
|
|
(block:
|
|
var below = 0
|
|
var above = 0
|
|
for b in 0 ..< GK_NBINS:
|
|
if binCentre(b) < 0.0: inc below
|
|
elif binCentre(b) > 0.0: inc above
|
|
below == 16 and above == 15)
|
|
check "each side is monotone in magnitude away from the null",
|
|
(block:
|
|
var neg = true
|
|
for b in 1 .. 16:
|
|
if abs(binCentre(b)) - abs(binCentre(b - 1)) <= 0.0: neg = false
|
|
var pos = abs(binCentre(17)) > abs(binCentre(GK_NULL_BIN))
|
|
for b in 18 ..< GK_NBINS:
|
|
if abs(binCentre(b)) - abs(binCentre(b - 1)) <= 0.0: pos = false
|
|
neg and pos)
|
|
|
|
# ── 2. the 13-bit key over 2160 rows ─────────────────────────────────────────
|
|
|
|
proc testKeyPacking() =
|
|
# ── individual feature binners ──
|
|
let d1 = mk(0.0, 0.0, 0.0, 1.0, 1.0) # dist 0 -> band 0
|
|
let d2 = mk(250.0, 0.0, 0.0, 1.0, 1.0) # dist 250 -> band 2
|
|
let d3 = mk(600.0, 0.0, 0.0, 1.0, 1.0) # dist 600 -> band 4
|
|
check "the distance band is lead_gain's lgBandOf (5 bands)",
|
|
lgBandOf(gkDist(d1)) == 0 and lgBandOf(gkDist(d2)) == 2 and
|
|
lgBandOf(gkDist(d3)) == 4
|
|
check "gun heat quarters [0,1]",
|
|
binHeat(0.0) == 0 and binHeat(0.24) == 0 and binHeat(0.25) == 1 and
|
|
binHeat(0.5) == 2 and binHeat(0.74) == 2 and binHeat(0.75) == 3 and
|
|
binHeat(1.0) == 3
|
|
check "radialFrac quarters [0,1] and clamps out-of-range input",
|
|
binRadial(0.0) == 0 and binRadial(0.49) == 1 and binRadial(0.5) == 2 and
|
|
binRadial(0.9) == 3 and binRadial(-3.0) == 0 and binRadial(9.0) == 3
|
|
|
|
# ── each feature moves the key, and the all-min tuple gives row 0 ──
|
|
# mixed-radix weights: band 3*4*4*4*4=768, space 4*4*4*4=256, turning 4*4*4=64,
|
|
# trend 4*4=16, heat 4, radial 1
|
|
var f0 = mk(0.0, 0.0, 0.0, 0.0, 1.0) # band 0, everything else its minimum
|
|
f0.space = gkNearWall # ord 0
|
|
f0.turning = gkStraight # ord 0
|
|
f0.speedTrend = gkAccelerating # ord 0
|
|
f0.gunHeat = 0.0
|
|
f0.radialFrac = 0.0
|
|
check "the all-min feature tuple gives key 0", keyOf(f0) == 0
|
|
|
|
var dOnly = mk(250.0, 0.0, 0.0, 0.0, 1.0) # band 2 (outermost digit)
|
|
dOnly.space = gkNearWall
|
|
dOnly.turning = gkStraight
|
|
dOnly.speedTrend = gkAccelerating
|
|
check "the distance band is the outermost digit (2*768 = 1536)",
|
|
keyOf(dOnly) == 2 * 768 and lgBandOf(gkDist(dOnly)) == 2
|
|
dOnly.space = gkCorner
|
|
check "one space bin up moves the key by 256", keyOf(dOnly) == 2 * 768 + 1 * 256
|
|
dOnly.turning = gkLeft
|
|
check "the turning digit is next (2*64 = 128)",
|
|
keyOf(dOnly) == 2 * 768 + 1 * 256 + 2 * 64
|
|
dOnly.speedTrend = gkDecelerating
|
|
check "the speed-trend digit is next (2*16 = 32)",
|
|
keyOf(dOnly) == 2 * 768 + 1 * 256 + 2 * 64 + 2 * 16
|
|
dOnly.gunHeat = 0.9
|
|
check "the heat digit is next (3*4 = 12)",
|
|
keyOf(dOnly) == 2 * 768 + 1 * 256 + 2 * 64 + 2 * 16 + 3 * 4
|
|
dOnly.radialFrac = 0.9
|
|
check "the radial digit is innermost (+3)",
|
|
keyOf(dOnly) == 2 * 768 + 1 * 256 + 2 * 64 + 2 * 16 + 3 * 4 + 3
|
|
|
|
# ── gkUnknown is a FIRST-CLASS value, not a silent degrade to straight ──
|
|
var uTurn = dOnly # currently gkLeft / gkDecelerating
|
|
uTurn.turning = gkStraight # ord 0
|
|
uTurn.speedTrend = gkDecelerating # ord 2
|
|
let straightKey = keyOf(uTurn)
|
|
uTurn.turning = gkUnknown # ord 3 -> +3 turn digits = +192
|
|
let unknownTurnKey = keyOf(uTurn)
|
|
check "gkUnknown gets its OWN turn row, distinct from gkStraight",
|
|
unknownTurnKey != straightKey and
|
|
unknownTurnKey == straightKey + 3 * 64 and
|
|
ord(GkTurn.gkUnknown) == 3
|
|
uTurn.turning = gkStraight
|
|
uTurn.speedTrend = gkConstant # ord 1
|
|
let constantKey = keyOf(uTurn)
|
|
uTurn.speedTrend = gkUnknown # ord 3 -> +2 trend digits = +32
|
|
check "gkUnknown gets its OWN trend row, distinct from gkConstant",
|
|
keyOf(uTurn) != constantKey and
|
|
keyOf(uTurn) == constantKey + 2 * 16 and
|
|
ord(GkTrend.gkUnknown) == 3
|
|
check "GkTurn and GkTrend each have 4 values (3 bits)",
|
|
ord(GkTurn.high) + 1 == 4 and ord(GkTrend.high) + 1 == 4
|
|
|
|
# ── the key is a dense index, never out of the table ──
|
|
var big = mk(900.0, 0.0, 0.0, 8.0, 1.0) # band 4 (last)
|
|
big.space = gkFree # ord 2
|
|
big.turning = gkUnknown # ord 3
|
|
big.speedTrend = gkUnknown # ord 3
|
|
big.gunHeat = 1.0
|
|
big.radialFrac = 1.0
|
|
check "an all-max key is the LAST row, GK_NKEYS - 1", keyOf(big) == GK_NKEYS - 1
|
|
check "an all-max key fits in GK_KEY_BITS = 15 bits", keyOf(big) < (1 shl GK_KEY_BITS)
|
|
check "GK_KEY_BITS is 15 and GK_NKEYS is the reachable 5*3*4*4*4*4 = 3840",
|
|
GK_KEY_BITS == 15 and GK_NKEYS == 3840
|
|
check "GK_NKEYS is smaller than 2^15 (the table is dense, not bit-shaped)",
|
|
GK_NKEYS == 5 * 3 * 4 * 4 * 4 * 4 and GK_NKEYS < (1 shl GK_KEY_BITS)
|
|
|
|
# ── no two distinct feature tuples collide: the FULL cartesian product ──
|
|
let dists = [10.0, 150.0, 250.0, 350.0, 600.0] # bands 0..4
|
|
let heats = [0.0, 0.3, 0.6, 0.9] # bins 0..3
|
|
let radials = [0.0, 0.3, 0.6, 0.9] # bins 0..3
|
|
var seen = initTable[int, string]()
|
|
var collisions = 0
|
|
for d in dists:
|
|
for sp in GkSpace:
|
|
for t in GkTurn:
|
|
for r in GkTrend:
|
|
for h in heats:
|
|
for rf in radials:
|
|
let f = GkFeatures(enemyX: d, enemyY: 0.0, selfX: 0.0, selfY: 0.0,
|
|
enemySpeed: 3.0, power: 2.0, turning: t,
|
|
speedTrend: r, space: sp, gunHeat: h,
|
|
radialFrac: rf, hasTarget: true)
|
|
let k = keyOf(f)
|
|
let sig = $d & "/" & $ord(sp) & "/" & $ord(t) & "/" & $ord(r) &
|
|
"/" & $h & "/" & $rf
|
|
if k in seen: inc collisions
|
|
else: seen[k] = sig
|
|
check "the full 3840-tuple cartesian product produces " & $seen.len &
|
|
" distinct keys and 0 collisions",
|
|
collisions == 0 and seen.len == GK_NKEYS
|
|
check "every row index 0..3839 is reached exactly once",
|
|
seen.len == GK_NKEYS and
|
|
(block:
|
|
var covered = true
|
|
for k in 0 ..< GK_NKEYS:
|
|
if k notin seen: covered = false
|
|
covered)
|
|
|
|
# ── 3. the closed form — CROSS-CHECK ONLY (not the production path) ──────────
|
|
|
|
proc testClosedFormCrossCheck() =
|
|
# This is NOT what `aim` uses. It is kept, and tested, because it is the
|
|
# single-step estimator the fixed point replaced; see the module header and
|
|
# guns/lead_forecast's header for the measured failure.
|
|
# v = 20 - 3*2 = 14 ; t = 100/14 = 7.142857 ;
|
|
# lato = 4*7.142857*sin(90) = 28.5714 ; lungo = 100 + 4*7.142857*cos(90) = 100
|
|
# atan2(28.5714, 100) = 15.9454 ; base = 30 + 15.9454 = 45.9454
|
|
let v = 20.0 - 3.0 * 2.0
|
|
let t = 100.0 / v
|
|
let expectLead = radToDeg(arctan2(4.0 * t, 100.0))
|
|
check "CROSS-CHECK bullet speed for power 2.0 is 14", close(v, 14.0)
|
|
check "CROSS-CHECK flight time is ~7.1429", close(t, 7.142857, 1e-5)
|
|
check "CROSS-CHECK expected lead angle is ~15.945 deg", close(expectLead, 15.9454, 1e-3)
|
|
let base = closedFormLead(100.0, 2.0, 4.0, 30.0, 90.0)
|
|
check "CROSS-CHECK closed form: dist=100 power=2 spd=4 gamma=90 bearing=30 -> ~46 deg",
|
|
close(base, 45.9454, 1e-3) and close(base, 46.0, 0.1)
|
|
# zero enemy speed -> aim is just the bearing, no lead
|
|
check "CROSS-CHECK stationary enemy gets no lead",
|
|
close(closedFormLead(300.0, 2.0, 0.0, 42.0, 0.0), 42.0)
|
|
# gamma = 0 (receding) -> lead is purely radial, still angular 0
|
|
check "CROSS-CHECK receding enemy (gamma=0) still has zero angular lead",
|
|
close(closedFormLead(300.0, 2.0, 5.0, 10.0, 0.0), 10.0)
|
|
# symmetric: gamma = -90 is a mirror of gamma = +90
|
|
check "CROSS-CHECK gamma is antisymmetric",
|
|
close(closedFormLead(100.0, 2.0, 4.0, 30.0, -90.0),
|
|
30.0 - (45.9454 - 30.0), 1e-3)
|
|
# clamping to [-180, 180]
|
|
check "CROSS-CHECK result is clamped into [-180,180]",
|
|
closedFormLead(500.0, 0.1, 8.0, 179.0, 90.0) <= 180.0 and
|
|
closedFormLead(500.0, 0.1, 8.0, -179.0, -90.0) >= -180.0
|
|
# power is clamped to the legal window, so no division by zero
|
|
check "CROSS-CHECK illegal power does not divide by zero",
|
|
closedFormLead(100.0, 0.0, 4.0, 10.0, 90.0) ==
|
|
closedFormLead(100.0, 0.1, 4.0, 10.0, 90.0)
|
|
# the projection helpers that feed it
|
|
check "gammaOf: enemy heading perpendicular to LOS = +90",
|
|
close(gammaOf(90.0, 0.0, 0.0, 100.0, 0.0), 90.0)
|
|
check "gammaOf: enemy heading along LOS = 0",
|
|
close(gammaOf(0.0, 0.0, 0.0, 100.0, 0.0), 0.0)
|
|
check "gkDist / gkBearing / gkGamma project the world snapshot",
|
|
close(gkDist(mk(100.0, 0.0, 0.0, 1.0, 1.0)), 100.0) and
|
|
close(gkBearing(mk(0.0, 100.0, 0.0, 1.0, 1.0)), 90.0) and
|
|
close(gkGamma(mk(100.0, 0.0, 90.0, 1.0, 1.0)), 90.0)
|
|
|
|
# ── 4. the forecast base (THE production path) ────────────────────────────────
|
|
|
|
proc testForecastBase() =
|
|
# Same situation as the closed-form cross-check above, in the WORLD frame:
|
|
# us at the origin, the gun pointing along +x (gunHeading = 0), the enemy
|
|
# 100 px east moving north at 4 px/tick, power 2 (bullet speed 14).
|
|
let f = mk(100.0, 0.0, 90.0, 4.0, 2.0)
|
|
check "gkBearing is the LOS, here 0 deg", close(gkBearing(f), 0.0)
|
|
# the self-consistent fixed point, iterated here to CONVERGENCE (not the 5
|
|
# times forecastLinear does) so the test is an independent statement of the
|
|
# invariant rather than a copy of the implementation
|
|
var tc = 100.0 / 14.0
|
|
for _ in 0 ..< 80: tc = hypot(100.0, 4.0 * tc) / 14.0
|
|
let fixedLead = radToDeg(arctan2(4.0 * tc, 100.0))
|
|
let base = forecastBase(f, 0.0)
|
|
check "the forecast base IS the flight-time fixed point (to 1e-3 deg)",
|
|
close(base, fixedLead, 1e-3)
|
|
check "the fixed point leads further than the single-step closed form",
|
|
base > closedFormLead(100.0, 2.0, 4.0, 0.0, 90.0)
|
|
check "forecastBase == radToDeg(forecastLinear().bearing), the ABSOLUTE form",
|
|
close(forecastBase(f, 0.0), base) and
|
|
close(forecastBase(f, 0.0),
|
|
radToDeg(forecastLinear(
|
|
WorldState(enemyX: 100.0, enemyY: 0.0, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: 90.0, enemySpeed: 4.0),
|
|
bulletSpeed(2.0)).bearing))
|
|
# the base is an ABSOLUTE world bearing: the bot's own heading is NOT part of
|
|
# it. It used to be (`gunHeading + lead`), which pointed the gun backwards
|
|
# whenever the bot faced away from the target. See testAimFrameInvariant.
|
|
check "the base does NOT move when the gun heading moves",
|
|
close(forecastBase(f, 37.0), base) and
|
|
close(forecastBase(f, -120.0), base) and
|
|
close(forecastBase(f, 179.0), base)
|
|
# a stationary enemy: no lead at all, the aim is the LOS
|
|
let still = mk(300.0, 0.0, 0.0, 0.0, 2.0)
|
|
check "a stationary enemy gets no lead from the forecast",
|
|
close(forecastBase(still, 12.0), 0.0) and close(forecastBase(still, 0.0), 0.0)
|
|
# a receding enemy is still angularly zero: the base is the LOS bearing
|
|
let away = mk(200.0, 0.0, 0.0, 5.0, 2.0)
|
|
check "a receding enemy still aims along the LOS",
|
|
close(forecastBase(away, 0.0), 0.0) and close(forecastBase(away, 90.0), 0.0)
|
|
# the answer is always inside [-180, 180]
|
|
check "the forecast base is wrapped into [-180,180]",
|
|
forecastBase(mk(-500.0, 0.0, 179.0, 8.0, 0.1), 179.0) <= 180.0 and
|
|
forecastBase(mk(500.0, 0.0, -179.0, 8.0, 0.1), -179.0) >= -180.0
|
|
# `aim` really uses it, not the closed form
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
let a = gk.aim(f, 0.0)
|
|
check "aim().base IS the forecast, not the closed form",
|
|
close(a.base, forecastBase(f, 0.0)) and
|
|
not close(a.base, closedFormLead(100.0, 2.0, 4.0, 0.0, 90.0))
|
|
|
|
# ── 4b. THE FRAME INVARIANT (the bug this suite exists for) ────────────────────
|
|
##
|
|
## `ModularBot.nim:1501-1503` does
|
|
## of KnowledgeId: bot.knowledge.predict(bot.lastState, bulletSpeed(power))
|
|
## let aimTarget = aimAngle(getX(), getY(), pred.x, pred.y)
|
|
## let gunDelta = (aimTarget - getGunDirection()) mod 360.0
|
|
## so the caller consumes an ABSOLUTE prediction point and does the
|
|
## turret-relative subtraction ITSELF. The module must therefore answer with an
|
|
## absolute world bearing. It used to answer `selfHeading + (fc.bearing - los)`,
|
|
## an absolute heading plus a relative lead, so the aim carried an error of
|
|
## `gunHeading - los` -- ~180 deg when the bot faced away. THE SAME PREDICTION
|
|
## MUST NOT DEPEND ON WHERE THE BOT IS FACING: that is the property below, and
|
|
## it is what no test before this one asserted.
|
|
proc mkState(selfHeading, ex, ey, ehead, espd: float): WorldState =
|
|
WorldState(enemyX: ex, enemyY: ey, enemyHeading: ehead, enemySpeed: espd,
|
|
selfX: 400.0, selfY: 300.0, selfHeading: selfHeading,
|
|
selfRadarHeading: selfHeading, selfEnergy: 100.0,
|
|
enemyEnergy: 100.0, arenaWidth: 800.0, arenaHeight: 600.0,
|
|
tick: 1000)
|
|
|
|
proc testAimFrameInvariant() =
|
|
# Us at (400,300), the enemy 120 px due east heading north at 5 px/tick, p2.
|
|
let ex = 520.0
|
|
let ey = 300.0
|
|
var byHeading = newSeq[float](4)
|
|
for k, hdg in [0.0, 90.0, 180.0, 270.0]:
|
|
var g = initKnowledgeGun("")
|
|
g.gunHeat = 0.0
|
|
g.targetId = 7
|
|
let p = g.predict(mkState(hdg, ex, ey, 90.0, 5.0), bulletSpeed(2.0))
|
|
byHeading[k] = radToDeg(arctan2(p.y - 300.0, p.x - 400.0))
|
|
check "heading 0/90/180/270 deg away from the target give ONE aim direction",
|
|
close(byHeading[0], byHeading[1], 1e-6) and
|
|
close(byHeading[0], byHeading[2], 1e-6) and
|
|
close(byHeading[0], byHeading[3], 1e-6)
|
|
check "that aim is the forecast bearing + the (null) residual",
|
|
(block:
|
|
let fc = forecastLinear(
|
|
WorldState(enemyX: ex, enemyY: ey, enemyHeading: 90.0,
|
|
enemySpeed: 5.0, selfX: 400.0, selfY: 300.0),
|
|
bulletSpeed(2.0))
|
|
close(byHeading[0], normalize180(radToDeg(fc.bearing)), 1e-3))
|
|
check "the aim is never the opposite direction (the live symptom)",
|
|
abs(byHeading[0]) < 90.0
|
|
# the caller's units/range: `aimAngle` returns DEGREES in (-180, 180], and
|
|
# `setGunTurnRate` takes the wrapped difference against getGunDirection().
|
|
var g2 = initKnowledgeGun("")
|
|
g2.gunHeat = 0.0
|
|
g2.targetId = 7
|
|
let p2 = g2.predict(mkState(180.0, 150.0, 300.0, 0.0, 8.0), bulletSpeed(3.0))
|
|
let ang = radToDeg(arctan2(p2.y - 300.0, p2.x - 400.0))
|
|
check "the prediction is a finite point away from us, not at the origin",
|
|
p2.x == p2.x and p2.y == p2.y and (p2.x != 400.0 or p2.y != 300.0)
|
|
check "an enemy due west of us is aimed at to the west, in degrees [-180,180]",
|
|
abs(ang) > 90.0 and ang >= -180.0 and ang <= 180.0
|
|
|
|
# ── 5. the scan track: turn direction and speed trend ────────────────────────
|
|
|
|
proc testScanTrack() =
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
# straight ahead, constant speed, one scan per turn
|
|
gk.observe(1, 100.0, 100.0, 10.0, 4.0, 100)
|
|
gk.observe(1, 100.0, 100.0, 20.0, 4.0, 101)
|
|
let t1 = gk.trackFor(1)
|
|
check "a track needs two scans", t1.trackKnown and
|
|
gk.tracks.len == 1
|
|
check "CCW-positive heading change reads as turning LEFT", t1.turnOf == gkLeft
|
|
check "a constant speed reads as gkConstant", t1.trendOf == gkConstant
|
|
|
|
var gk2 = initGunKnowledge(800.0, 600.0)
|
|
gk2.observe(2, 100.0, 100.0, 20.0, 4.0, 100)
|
|
gk2.observe(2, 100.0, 100.0, 10.0, 4.0, 101)
|
|
check "a CW heading change reads as turning RIGHT", gk2.trackFor(2).turnOf == gkRight
|
|
|
|
# inside the dead band -> straight, and the sign does not matter
|
|
var gk3 = initGunKnowledge(800.0, 600.0)
|
|
gk3.observe(3, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gk3.observe(3, 0.0, 0.0, 1.0, 4.0, 101) # +1 deg/turn < GK_TURN_DEAD (2)
|
|
check "a 1 deg/turn drift inside the dead band is 'straight'",
|
|
gk3.trackFor(3).turnOf == gkStraight
|
|
|
|
# speed trend
|
|
var gk4 = initGunKnowledge(800.0, 600.0)
|
|
gk4.observe(4, 0.0, 0.0, 0.0, 2.0, 100)
|
|
gk4.observe(4, 0.0, 0.0, 0.0, 5.0, 101)
|
|
check "speeding up reads as accelerating", gk4.trackFor(4).trendOf == gkAccelerating
|
|
var gk5 = initGunKnowledge(800.0, 600.0)
|
|
gk5.observe(5, 0.0, 0.0, 0.0, 5.0, 100)
|
|
gk5.observe(5, 0.0, 0.0, 0.0, 1.0, 101)
|
|
check "slowing down reads as decelerating", gk5.trackFor(5).trendOf == gkDecelerating
|
|
var gk6 = initGunKnowledge(800.0, 600.0)
|
|
gk6.observe(6, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gk6.observe(6, 0.0, 0.0, 0.0, 4.02, 101) # 0.02 < GK_TREND_DEAD (0.05)
|
|
check "a 0.02 px/turn change inside the dead band is 'constant'",
|
|
gk6.trackFor(6).trendOf == gkConstant
|
|
|
|
# ── the gap rule ──
|
|
var gk7 = initGunKnowledge(800.0, 600.0)
|
|
gk7.observe(7, 0.0, 0.0, 0.0, 4.0, 100)
|
|
check "a single scan is not enough", not gk7.trackFor(7).trackKnown
|
|
check "a single scan has no gap to average over", gk7.trackFor(7).trackGap == -1
|
|
# a gap of exactly GK_GAP_MAX is the last trusted one, and the rate is
|
|
# divided by the REAL gap: 20 deg over 6 turns = 3.33 deg/turn -> still a
|
|
# clear left turn.
|
|
gk7.observe(7, 0.0, 0.0, 20.0, 4.0, 100 + GK_GAP_MAX)
|
|
let t7 = gk7.trackFor(7)
|
|
check "a gap of exactly GK_GAP_MAX is the last trusted one", t7.trackKnown and
|
|
t7.trackGap == GK_GAP_MAX
|
|
check "the turn rate is divided by the real gap (20 deg / 6 turns > GK_TURN_DEAD)",
|
|
t7.turnOf == gkLeft
|
|
# 4 deg over a 6-turn gap = 0.67 deg/turn -> inside the dead band. Without the
|
|
# division this would read as a confident 4 deg/turn turn.
|
|
var gk8 = initGunKnowledge(800.0, 600.0)
|
|
gk8.observe(8, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gk8.observe(8, 0.0, 0.0, 4.0, 4.0, 100 + GK_GAP_MAX)
|
|
check "the same 4 deg over a 6-turn gap is inside the dead band",
|
|
gk8.trackFor(8).turnOf == gkStraight
|
|
# a gap of GK_GAP_MAX + 1 is UNKNOWN, not a confident answer
|
|
var gk9 = initGunKnowledge(800.0, 600.0)
|
|
gk9.observe(9, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gk9.observe(9, 0.0, 0.0, 90.0, 4.0, 100 + GK_GAP_MAX + 1)
|
|
let t9 = gk9.trackFor(9)
|
|
check "a gap over GK_GAP_MAX turns is UNKNOWN, not confident",
|
|
not t9.trackKnown
|
|
check "an over-gap turn is gkUnknown, NOT degraded to gkStraight",
|
|
t9.turnOf == gkUnknown
|
|
var gk10 = initGunKnowledge(800.0, 600.0)
|
|
gk10.observe(10, 0.0, 0.0, 0.0, 1.0, 100)
|
|
gk10.observe(10, 0.0, 0.0, 0.0, 8.0, 100 + GK_GAP_MAX + 1)
|
|
check "an over-gap speed trend is gkUnknown, NOT degraded to gkConstant",
|
|
not gk10.trackFor(10).trackKnown and
|
|
gk10.trackFor(10).trendOf == gkUnknown
|
|
check "a single scan is gkUnknown on both features, not straight/constant",
|
|
(block:
|
|
var g = initGunKnowledge(800.0, 600.0)
|
|
g.observe(77, 0.0, 0.0, 0.0, 4.0, 10)
|
|
g.trackFor(77).turnOf == gkUnknown and
|
|
g.trackFor(77).trendOf == gkUnknown)
|
|
|
|
# ── the MEASURED gap limit: GK_GAP_MAX = 6 ──
|
|
# 184 recorded round-battles, 118,253 alive ticks / 24,883 scans = a mean
|
|
# inter-scan gap of 4.75. The old limit of 2 threw at least 57.9% of every
|
|
# observation into gkUnknown. 6 covers the measured mean.
|
|
check "GK_GAP_MAX is 6 (the measured mean gap is 4.75, the old limit was 2)",
|
|
GK_GAP_MAX == 6
|
|
# a 5-tick gap: over the old limit of 2, under the new one -> a REAL value
|
|
var gkGap5 = initGunKnowledge(800.0, 600.0)
|
|
gkGap5.observe(20, 0.0, 0.0, 0.0, 2.0, 100)
|
|
gkGap5.observe(20, 0.0, 0.0, 25.0, 8.0, 105) # gap 5: 5 deg/tick, +1.2 px/tick
|
|
let tGap5 = gkGap5.trackFor(20)
|
|
check "a 5-tick gap is KNOWN, not gkUnknown (it was unknown at the old limit)",
|
|
tGap5.trackKnown and tGap5.turnOf == gkLeft and
|
|
tGap5.trendOf == gkAccelerating
|
|
check "a 5-tick gap is a GAP-AVERAGE, divided by 5 (25 deg / 5 = 5 deg/tick)",
|
|
tGap5.trackGap == 5 and tGap5.turnOf == gkLeft
|
|
# a 7-tick gap is still over the limit
|
|
var gkGap7 = initGunKnowledge(800.0, 600.0)
|
|
gkGap7.observe(21, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gkGap7.observe(21, 0.0, 0.0, 90.0, 4.0, 107)
|
|
check "a 7-tick gap is still over the limit and yields gkUnknown",
|
|
gkGap7.trackFor(21).trackGap == 7 and
|
|
not gkGap7.trackFor(21).trackKnown and
|
|
gkGap7.trackFor(21).turnOf == gkUnknown and
|
|
gkGap7.trackFor(21).trendOf == gkUnknown
|
|
# ── the long-gap counter: the averaging is MEASURABLE, not claimed ──
|
|
let wsGap = WorldState(enemyX: 400.0, enemyY: 300.0, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: 0.0, enemySpeed: 4.0)
|
|
var gkGapCount = initGunKnowledge(800.0, 600.0)
|
|
check "longGapRate is 0.0 before anything is derived", gkGapCount.longGapRate() == 0.0
|
|
gkGapCount.observe(30, 400.0, 300.0, 0.0, 4.0, 100)
|
|
gkGapCount.observe(30, 400.0, 300.0, 30.0, 8.0, 101) # gap 1 -> no averaging
|
|
discard gkGapCount.featuresFor(wsGap, 30, 2.0, 0.0, 0.0)
|
|
check "a 1-tick gap is NOT a long gap: the rate is instantaneous",
|
|
gkGapCount.longGapCount == 0 and gkGapCount.longGapRate() == 0.0
|
|
gkGapCount.observe(30, 400.0, 300.0, 60.0, 12.0, 105) # gap 5 -> averaged
|
|
discard gkGapCount.featuresFor(wsGap, 30, 2.0, 0.0, 0.0)
|
|
check "the long-gap counter increments when a gap over 1 tick is used",
|
|
gkGapCount.longGapCount == 1 and
|
|
close(gkGapCount.longGapRate(), 0.5) and
|
|
gkGapCount.featureCount == 2
|
|
check "a gap-averaged derivation is a REAL turn, not gkUnknown",
|
|
gkGapCount.trackFor(30).turnOf == gkLeft and
|
|
gkGapCount.trackFor(30).trendOf == gkAccelerating and
|
|
gkGapCount.unknownCount == 0
|
|
|
|
# repeated scans of the SAME turn are ignored (no invented motion)
|
|
var gk11 = initGunKnowledge(800.0, 600.0)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 100)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 100)
|
|
check "a duplicate scan of the same turn is ignored",
|
|
gk11.trackFor(11).n == 1 and not gk11.trackFor(11).trackKnown
|
|
# the ring never grows past GK_TRACK_N
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 101)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 102)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 103)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 104)
|
|
gk11.observe(11, 0.0, 0.0, 0.0, 4.0, 105)
|
|
check "the scan ring is capped at GK_TRACK_N samples",
|
|
gk11.trackFor(11).n == GK_TRACK_N
|
|
|
|
# ── featuresFor wires the track into the key ──
|
|
var gk12 = initGunKnowledge(800.0, 600.0)
|
|
gk12.observe(12, 400.0, 300.0, 0.0, 4.0, 200)
|
|
gk12.observe(12, 400.0, 300.0, 20.0, 4.0, 201)
|
|
let ws = WorldState(enemyX: 400.0, enemyY: 300.0, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: 20.0, enemySpeed: 4.0, selfHeading: 0.0)
|
|
let ff = gk12.featuresFor(ws, 12, 2.0, 0.0, 0.0)
|
|
check "featuresFor derives turning/trend from the bot's own track",
|
|
ff.turning == gkLeft and ff.speedTrend == gkConstant
|
|
check "featuresFor keeps the world geometry and derives the space feature",
|
|
ff.enemyX == 400.0 and ff.gkDist == 500.0 and ff.space == gkFree
|
|
# the same snapshot, but the caller asks for a different bot's (empty) track
|
|
let f0 = gk12.featuresFor(ws, 99, 2.0, 0.0, 0.0)
|
|
check "an unknown botId yields gkUnknown, not the straight/constant row",
|
|
f0.turning == gkUnknown and f0.speedTrend == gkUnknown
|
|
var fStraight = f0
|
|
fStraight.turning = gkStraight
|
|
fStraight.speedTrend = gkConstant
|
|
check "the gkUnknown row is NOT the straight/constant row",
|
|
keyOf(f0) != keyOf(ff) and keyOf(f0) != keyOf(fStraight)
|
|
|
|
# the featuresFor snapshot keys exactly like a hand-built one
|
|
var hand = ff
|
|
hand.gunHeat = 0.0
|
|
hand.radialFrac = 0.0
|
|
hand.space = gkFree
|
|
check "featuresFor produces the key the same features would by hand",
|
|
keyOf(ff) == keyOf(hand)
|
|
|
|
# ── feature 6 really is lead_forecast.radialFrac ──
|
|
var vt = VelocityTracker()
|
|
var rx = 500.0
|
|
for t in 0 ..< 20: # closing fast: purely radial motion
|
|
let px = rx
|
|
rx -= 8.0
|
|
vt.observe(WorldState(enemyX: px, enemyY: 0.0, selfX: 0.0, selfY: 0.0, tick: t))
|
|
let radial = vt.radialFrac(RadialWindow)
|
|
check "a purely radial target gives radialFrac ~ 1",
|
|
radial > 0.95 and binRadial(radial) == 3
|
|
var vt2 = VelocityTracker()
|
|
var px2 = 500.0
|
|
for t in 0 ..< 20: # pure orbit: the range is held
|
|
let px = px2
|
|
px2 += 0.0
|
|
vt2.observe(WorldState(enemyX: px, enemyY: px2, selfX: 0.0, selfY: 0.0, tick: t))
|
|
check "a purely tangential target gives radialFrac ~ 0",
|
|
vt2.radialFrac(RadialWindow) < 0.05 and
|
|
binRadial(vt2.radialFrac(RadialWindow)) == 0
|
|
|
|
# ── 6. the fallback chain ─────────────────────────────────────────────────────
|
|
|
|
proc testFallbackChain() =
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
let f = mk(150.0, 20.0, 60.0, 3.0, 2.0)
|
|
|
|
# fresh: no target sentinel
|
|
var none = mk(0, 0, 0, 0, 1.0)
|
|
none.hasTarget = false
|
|
let a0 = gk.aim(none, 0.0)
|
|
check "no target -> hasTarget=false, source=none, aim=0",
|
|
not a0.hasTarget and a0.source == gkSourceNone and a0.aim == 0.0
|
|
|
|
# fresh situation: no source claimed, the global row starts counting. The
|
|
# answer is the null EXCEPT on the GK_EPSILON of the shots that explore (see
|
|
# testExploration), so what is asserted here is the contract, not a draw.
|
|
let a1 = gk.aim(f, 0.0)
|
|
check "fresh situation -> no source claimed, global row attempt 1",
|
|
a1.legalFresh and gk.rowAttempts(f) == 1
|
|
check "a1.base is the forecast and a1.aim == base + whatever was applied",
|
|
close(a1.aim, clamp(a1.base + a1.residual, -180.0, 180.0)) and
|
|
close(a1.base, forecastBase(f, 0.0))
|
|
|
|
# fill the global row to just under threshold: still no source claimed
|
|
while gk.rowAttempts(f) < GK_GLOBAL_MIN_ATTEMPTS - 1:
|
|
let a = gk.aim(f, 0.0)
|
|
check "still no source claimed while the global row is sub-threshold",
|
|
a.legalFresh
|
|
check "below global threshold -> still no source claimed",
|
|
gk.rowAttempts(f) == GK_GLOBAL_MIN_ATTEMPTS - 1 and
|
|
gk.aim(f, 0.0).source == gkSourceNone
|
|
|
|
# at threshold the row is allowed to speak — but only if a bin is past the
|
|
# per-bin minimum; a row with zero hits degrades to 0 residual, not garbage.
|
|
check "at global threshold with no hits -> source=global, residual 0",
|
|
(block:
|
|
let a = gk.aim(f, 0.0)
|
|
a.source == gkSourceGlobal and a.residual == 0.0 and
|
|
a.residualBin == -1)
|
|
|
|
# now teach it bin 10 and it must be used
|
|
let target = 10
|
|
for _ in 0 ..< 40: gk.update(f, target, true)
|
|
let a2 = gk.aim(f, 0.0)
|
|
check "global row past threshold with hits -> its residual is used",
|
|
a2.source == gkSourceGlobal and a2.residualBin == target and
|
|
close(a2.residual, binCentre(target)) and
|
|
close(a2.aim, clamp(a2.base + a2.residual, -180.0, 180.0))
|
|
|
|
# a single hit in a bin is NOT enough (GK_MIN_BIN_HITS)
|
|
var gk2 = initGunKnowledge(800.0, 600.0)
|
|
let g = mk(60.0, 30.0, 0.0, 0.0, 1.0)
|
|
for _ in 0 ..< 10: gk2.update(g, 5, false)
|
|
gk2.update(g, 5, true) # 1 hit, 11 attempts
|
|
check "a bin with 1 hit is below the per-bin minimum and is not chosen",
|
|
gk2.aim(g, 0.0).source == gkSourceGlobal and
|
|
gk2.aim(g, 0.0).residualBin == -1
|
|
|
|
# per-opponent override: 20 attempts required
|
|
var gk3 = initGunKnowledge(800.0, 600.0)
|
|
let h = mk(250.0, 0.0, 0.0, 1.0, 1.0)
|
|
let oid = gk3.opponentId("DrussGT")
|
|
check "interning is stable", gk3.opponentId("DrussGT") == oid and
|
|
gk3.opponentId("CoralBot") != oid and
|
|
gk3.opponentId("DrussGT") == oid
|
|
check "opponent name round-trips", gk3.opponentName(oid) == "DrussGT"
|
|
# a different opponent gets its OWN row: the global one stays empty
|
|
let oid2 = gk3.opponentId("CoralBot")
|
|
for _ in 0 ..< GK_OPP_MIN_ATTEMPTS - 1: gk3.update(h, 20, true, oid)
|
|
check "opponent row at 19 attempts is still ignored",
|
|
gk3.aim(h, 0.0, oid).source == gkSourceNone and
|
|
gk3.aim(h, 0.0, oid2).source == gkSourceNone
|
|
check "the other opponent did not inherit the row", gk3.oppRows.len == 1
|
|
gk3.update(h, 20, true, oid) # the 20th attempt
|
|
let a3 = gk3.aim(h, 0.0, oid)
|
|
check "opponent row at 20 attempts takes over",
|
|
a3.source == gkSourceOpponent and a3.residualBin == 20 and
|
|
a3.opponentId == oid
|
|
check "a query WITHOUT the opponent id still sees nothing",
|
|
gk3.aim(h, 0.0).source == gkSourceNone
|
|
|
|
# ── 7. learn-then-query ───────────────────────────────────────────────────────
|
|
|
|
proc testLearnThenQuery() =
|
|
var gk = initGunKnowledge(1000.0, 800.0)
|
|
let f = mk(300.0, 0.0, 90.0, 5.0, 3.0)
|
|
# Plant a strong preference for bin 4 (about -22 deg) and noise elsewhere.
|
|
let good = 4
|
|
let noise = [7, 12, 18, 25, 30]
|
|
for i in 0 ..< 400:
|
|
gk.update(f, if i mod 5 == 0: noise[i mod noise.len] else: good, i mod 5 != 0)
|
|
let a = gk.aim(f, 0.0)
|
|
check "learn-then-query returns the planted bin",
|
|
a.residualBin == good and close(a.residual, binCentre(good))
|
|
check "the aim is base + the learned residual",
|
|
close(a.aim, clamp(a.base + a.residual, -180.0, 180.0))
|
|
check "the forecast base is untouched by learning",
|
|
close(a.base, forecastBase(f, 0.0))
|
|
# a DIFFERENT situation must not inherit the correction
|
|
var other = f
|
|
other.turning = gkRight
|
|
check "a different 15-bit key is unaffected",
|
|
keyOf(other) != keyOf(f) and
|
|
gk.aim(other, 0.0).residual != binCentre(good) and
|
|
gk.rowAttempts(other) == 1
|
|
# a different opponent is unaffected too: it has no override row, so it falls
|
|
# back to the GLOBAL knowledge rather than to nothing.
|
|
let oid = gk.opponentId("Other")
|
|
let ao = gk.aim(f, 0.0, oid)
|
|
check "a NEW opponent falls back to the global row, not to the override",
|
|
ao.source == gkSourceGlobal and ao.residualBin == good and
|
|
ao.opponentId == oid
|
|
|
|
# an empty row degrades gracefully
|
|
var gk2 = initGunKnowledge()
|
|
let e = mk(50.0, 0.0, 0.0, 0.0, 1.0)
|
|
for _ in 0 ..< 20: gk2.update(e, 0, false) # attempts, zero hits
|
|
let ae = gk2.aim(e, 0.0)
|
|
check "an all-zero row returns 0 residual, bin -1, no crash",
|
|
ae.source == gkSourceGlobal and ae.residual == 0.0 and
|
|
ae.residualBin == -1
|
|
|
|
# ── 8. space derivation ──────────────────────────────────────────────────────
|
|
|
|
proc testSpace() =
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
# open field
|
|
check "middle of the arena is free",
|
|
gk.spaceFor(400.0, 300.0, 300.0, 200.0) == gkFree
|
|
# enemy in the bottom-right corner, we are up and to the left
|
|
check "enemy wedged in a corner we approach from = corner",
|
|
gk.spaceFor(780.0, 580.0, 200.0, 100.0) == gkCorner
|
|
# enemy near ONE wall, on the far side from us
|
|
check "enemy against the far right wall only = near one wall",
|
|
gk.spaceFor(775.0, 300.0, 200.0, 300.0) == gkNearWall
|
|
# enemy near a wall that is BEHIND US (we are closer to it) -> not counted
|
|
check "a wall behind us is not the enemy's wall",
|
|
gk.spaceFor(20.0, 300.0, 5.0, 300.0) == gkFree
|
|
# beyond the margin
|
|
check "just outside the 60 px margin = free",
|
|
gk.spaceFor(400.0, 300.0, 100.0, 300.0) == gkFree and
|
|
gk.spaceFor(400.0, 300.0, 300.0, 100.0) == gkFree
|
|
# unset arena degrades instead of dividing by zero
|
|
var gk0 = initGunKnowledge()
|
|
check "unset arena -> free", gk0.spaceFor(0, 0, 0, 0) == gkFree
|
|
# setArena changes the answer
|
|
var gk2 = initGunKnowledge()
|
|
gk2.setArena(800.0, 600.0)
|
|
check "setArena is picked up", gk2.spaceFor(400.0, 300.0, 300.0, 200.0) == gkFree
|
|
|
|
# ── 9. save / load round-trip ─────────────────────────────────────────────────
|
|
|
|
proc sameState(a, b: GunKnowledge): bool =
|
|
## EXACT equality of the whole persisted state: every global row's attempts
|
|
## and all 32 hit counters, every opponent row, the interner, and the
|
|
## unknown-rate counters. Not "approximately".
|
|
if a.unknownCount != b.unknownCount or a.featureCount != b.featureCount:
|
|
return false
|
|
for i in 0 ..< GK_NKEYS:
|
|
if a.globalRows[i].attempts != b.globalRows[i].attempts: return false
|
|
for k in 0 ..< GK_NBINS:
|
|
if a.globalRows[i].hits[k] != b.globalRows[i].hits[k]: return false
|
|
if a.oppRows.len != b.oppRows.len: return false
|
|
for ok in a.oppRows.keys:
|
|
if ok notin b.oppRows: return false
|
|
if a.oppRows[ok].attempts != b.oppRows[ok].attempts: return false
|
|
for k in 0 ..< GK_NBINS:
|
|
if a.oppRows[ok].hits[k] != b.oppRows[ok].hits[k]: return false
|
|
a.interner.names == b.interner.names and
|
|
a.interner.names.len == b.interner.ids.len and
|
|
b.interner.names.len == b.interner.ids.len
|
|
|
|
proc testPersistence() =
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
let f = mk(120.0, 0.0, 30.0, 2.0, 1.0)
|
|
for _ in 0 ..< 60: gk.update(f, 6, true)
|
|
for _ in 0 ..< 20: gk.update(f, 9, false)
|
|
let g2 = mk(450.0, 0.0, -30.0, 6.0, 3.0)
|
|
for _ in 0 ..< 30: gk.update(g2, 1, true)
|
|
let oid = gk.opponentId("DrussGT")
|
|
for _ in 0 ..< 25: gk.update(f, 31, true, oid)
|
|
discard gk.opponentId("CoralBot")
|
|
# bump the unknown-rate counters through the real derivation path: one bot
|
|
# seen every turn (known), one bot seen every 3 turns (unknown)
|
|
let ws = WorldState(enemyX: 400.0, enemyY: 300.0, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: 20.0, enemySpeed: 4.0)
|
|
for t in 0 ..< 4:
|
|
gk.observe(31, 400.0, 300.0, 0.0, 4.0, 300 + t) # consecutive -> known
|
|
for _ in 0 ..< 4:
|
|
discard gk.featuresFor(ws, 31, 2.0, 0.0, 0.0)
|
|
gk.observe(32, 400.0, 300.0, 0.0, 4.0, 400)
|
|
gk.observe(32, 400.0, 300.0, 0.0, 4.0, 400 + GK_GAP_MAX + 1) # over the limit
|
|
discard gk.featuresFor(ws, 32, 2.0, 0.0, 0.0)
|
|
check "the unknown counter sees exactly the 1 over-gap derivation",
|
|
gk.featureCount == 5 and gk.unknownCount == 1
|
|
|
|
let path = getTempDir() / "gk_test_table.bin"
|
|
let tmpPath = getTempDir() / "gk_test_table.bin.tmp"
|
|
removeFile(path)
|
|
removeFile(tmpPath)
|
|
check "save succeeds", gk.save(path)
|
|
check "the file exists and is non-trivial", fileExists(path) and
|
|
getFileSize(path) > 100
|
|
check "save is atomic: it leaves no temp file behind", not fileExists(tmpPath)
|
|
check "the saved file is exactly the encoding", getFileSize(path) == gk.encode().len
|
|
|
|
var gk2 = initGunKnowledge(1.0, 1.0)
|
|
gk2.setArena(800.0, 600.0)
|
|
check "load succeeds", gk2.load(path)
|
|
check "the ENTIRE state round-trips exactly (attempts, all 32 hits, interner, counters)",
|
|
sameState(gk, gk2) and gk2.unknownCount == 1 and gk2.featureCount == 5
|
|
check "global row attempts round-trip",
|
|
gk2.rowAttempts(f) == gk.rowAttempts(f) and
|
|
gk2.rowAttempts(f) == 80
|
|
check "global hits round-trip",
|
|
gk2.rowHitCount(f, 6) == 60 and gk2.rowHitCount(f, 9) == 0
|
|
check "the second situation round-trips too",
|
|
gk2.rowAttempts(g2) == 30 and gk2.rowHitCount(g2, 1) == 30
|
|
check "opponent rows round-trip",
|
|
gk2.rowAttempts(f, oid) == 25 and gk2.rowHitCount(f, 31, oid) == 25
|
|
check "the opponent name table round-trips",
|
|
gk2.opponentId("DrussGT") == oid and gk2.opponentName(oid) == "DrussGT" and
|
|
gk2.opponentId("CoralBot") != oid
|
|
let before = gk.aim(f, 0.0, oid)
|
|
let after = gk2.aim(f, 0.0, oid)
|
|
check "the AIM is identical after a round-trip",
|
|
before.residualBin == after.residualBin and
|
|
close(before.aim, after.aim) and close(before.residual, after.residual)
|
|
check "arena constants are not persisted (they are per-episode)",
|
|
gk2.arenaW == 800.0
|
|
|
|
# ── strict rejection: a partially-loaded table is never returned ──
|
|
let good = gk.encode()
|
|
var gk3 = initGunKnowledge()
|
|
check "the encoding starts with the magic and is at least a header long",
|
|
good.len > GK_HEADER_LEN and good[0 ..< GK_MAGIC.len] == GK_MAGIC and
|
|
GK_HEADER_LEN == GK_MAGIC.len + 6 * 4
|
|
|
|
# zero length
|
|
writeFile(path, "")
|
|
check "a zero-length file is rejected (empty table, false)",
|
|
gk3.load(path) == false and gk3.usedGlobalRows() == 0 and
|
|
gk3.oppRows.len == 0 and gk3.globalRows.len == GK_NKEYS
|
|
|
|
# corrupted magic
|
|
var bad = good
|
|
bad[0] = 'X'
|
|
writeFile(path, bad)
|
|
check "a corrupted magic is rejected", gk3.load(path) == false and
|
|
gk3.usedGlobalRows() == 0
|
|
|
|
# bumped version
|
|
bad = good
|
|
bad[GK_MAGIC.len] = '\x63'
|
|
writeFile(path, bad)
|
|
check "a bumped version field is rejected", gk3.load(path) == false and
|
|
gk3.usedGlobalRows() == 0
|
|
|
|
# truncated to half
|
|
bad = good[0 ..< good.len div 2]
|
|
writeFile(path, bad)
|
|
check "a file truncated to half its length is rejected",
|
|
gk3.load(path) == false and gk3.usedGlobalRows() == 0 and
|
|
gk3.oppRows.len == 0
|
|
|
|
# truncated by a single byte (payload one byte short)
|
|
bad = good[0 ..< good.len - 1]
|
|
writeFile(path, bad)
|
|
check "a file one byte short is rejected", gk3.load(path) == false and
|
|
gk3.usedGlobalRows() == 0
|
|
|
|
# 10 trailing bytes
|
|
writeFile(path, good & "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09")
|
|
check "a file with 10 extra trailing bytes is rejected", gk3.load(path) == false and
|
|
gk3.usedGlobalRows() == 0
|
|
|
|
# a header declaring more rows than the payload holds
|
|
bad = good
|
|
bad[12] = '\xFF' # nGlobal low byte -> absurd
|
|
writeFile(path, bad)
|
|
check "a header declaring an impossible row count is rejected",
|
|
gk3.load(path) == false and gk3.usedGlobalRows() == 0
|
|
|
|
# a missing file is not an error
|
|
removeFile(path)
|
|
check "a missing file returns false and stays empty",
|
|
gk3.load(path) == false and gk3.usedGlobalRows() == 0
|
|
|
|
# ── a NESTED, NON-EXISTENT directory works on the first save ──
|
|
# `TR_KNOWLEDGE_MEM` is a path, not a mode: a path whose directory does not
|
|
# exist yet must be CREATED, not rejected. It used to return false with the
|
|
# reason discarded at the call site, so a perfectly good path silently never
|
|
# persisted anything.
|
|
let nestedRoot = getTempDir() / "gk_nested_9f3a"
|
|
if dirExists(nestedRoot): removeDir(nestedRoot)
|
|
let nestedDir = nestedRoot / "deeper"
|
|
let nestedPath = nestedDir / "table.bin"
|
|
let nestedTmp = nestedDir / "table.bin.tmp"
|
|
check "neither level of the nested directory exists before the first save",
|
|
not dirExists(nestedRoot) and not dirExists(nestedDir)
|
|
var nestedThrew = false
|
|
var nestedOk = false
|
|
try:
|
|
nestedOk = gk.save(nestedPath)
|
|
except CatchableError:
|
|
nestedThrew = true
|
|
check "save creates the missing nested directory and succeeds",
|
|
not nestedThrew and nestedOk and dirExists(nestedDir)
|
|
check "the first save through a created directory leaves no temp file",
|
|
not fileExists(nestedTmp)
|
|
var gkNested = initGunKnowledge(1.0, 1.0)
|
|
gkNested.setArena(800.0, 600.0)
|
|
check "the table written through a just-created directory loads back",
|
|
gkNested.load(nestedPath)
|
|
check "the round trip through a just-created directory is BYTE-EXACT " &
|
|
"(attempts, all 32 hits, interner, unknown counter)",
|
|
sameState(gk, gkNested) and
|
|
gkNested.unknownCount == gk.unknownCount and
|
|
gkNested.featureCount == gk.featureCount and
|
|
gkNested.rowAttempts(f) == 80 and gkNested.rowHitCount(f, 6) == 60 and
|
|
gkNested.opponentId("DrussGT") == oid
|
|
check "a second save over the now-existing path still succeeds and is atomic",
|
|
gk.save(nestedPath) and not fileExists(nestedTmp) and
|
|
getFileSize(nestedPath) == gk.encode().len
|
|
|
|
# ── (1) the directory cannot be created: REPORTED, no temp, load unaffected ──
|
|
# The parent is a REGULAR FILE, so createDir fails with ENOTDIR for ANY uid
|
|
# (a 0555 parent would NOT fail when the tests are run as root).
|
|
let blocker = getTempDir() / "gk_blocker_9f3a"
|
|
removeFile(blocker)
|
|
writeFile(blocker, "not a directory")
|
|
let undirrable = blocker / "sub" / "table.bin"
|
|
var mkdirThrew = false
|
|
var mkdirOk = true
|
|
let mkdirMsg = captureStderr(proc() =
|
|
try:
|
|
mkdirOk = gk.save(undirrable)
|
|
except CatchableError:
|
|
mkdirThrew = true)
|
|
check "an uncreatable parent directory returns false and does not throw",
|
|
not mkdirThrew and mkdirOk == false
|
|
check "the uncreatable-directory failure is REPORTED, naming path and reason",
|
|
mkdirMsg.contains("cannot create directory") and
|
|
mkdirMsg.contains(undirrable) and
|
|
mkdirMsg.len > "cannot create directory".len + undirrable.len and
|
|
not mkdirMsg.contains("cannot write the knowledge table to")
|
|
check "an uncreatable-directory failure leaves no temp file and no directory",
|
|
not fileExists(undirrable.parentDir / "table.bin.tmp") and
|
|
not dirExists(blocker / "sub")
|
|
var gkAfterFail = initGunKnowledge(1.0, 1.0)
|
|
gkAfterFail.setArena(800.0, 600.0)
|
|
check "load is unaffected by a failed save (the good file still loads)",
|
|
gkAfterFail.load(nestedPath) and gkAfterFail.rowAttempts(f) == 80
|
|
removeFile(blocker)
|
|
|
|
# ── the path IS a directory: REPORTED distinctly, no crash, no temp ──
|
|
let dirTarget = getTempDir() / "gk_dir_target_9f3a"
|
|
if dirExists(dirTarget): removeDir(dirTarget)
|
|
createDir(dirTarget)
|
|
let dirTmp = getTempDir() / "gk_dir_target_9f3a.tmp"
|
|
var dirThrew = false
|
|
var dirOk = true
|
|
let dirMsg = captureStderr(proc() =
|
|
try:
|
|
dirOk = gk.save(dirTarget)
|
|
except CatchableError:
|
|
dirThrew = true)
|
|
check "a path that IS a directory returns false and does not throw",
|
|
not dirThrew and dirOk == false
|
|
check "the directory-path failure is REPORTED distinctly, naming the path",
|
|
dirMsg.contains("cannot write the knowledge table to") and
|
|
dirMsg.contains(dirTarget) and dirMsg.contains("is a directory") and
|
|
not dirMsg.contains("cannot create directory")
|
|
check "a directory-path failure leaves no temp and does not remove the dir",
|
|
not fileExists(dirTmp) and dirExists(dirTarget)
|
|
check "load on a directory path is a plain false, never a crash",
|
|
(block:
|
|
var gkD = initGunKnowledge()
|
|
gkD.load(dirTarget) == false and gkD.usedGlobalRows() == 0)
|
|
removeDir(dirTarget)
|
|
removeFile(nestedPath)
|
|
removeDir(nestedDir)
|
|
removeDir(nestedRoot)
|
|
removeFile(path)
|
|
|
|
# ── 9b. unknown is a first-class, measurable state ───────────────────────────
|
|
|
|
proc testUnknown() =
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
let ws = WorldState(enemyX: 400.0, enemyY: 300.0, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: 20.0, enemySpeed: 4.0)
|
|
check "unknownRate is 0.0 before anything is derived",
|
|
gk.unknownRate() == 0.0 and gk.featureCount == 0
|
|
|
|
# a gap of exactly GK_GAP_MAX is still evidence -> no unknown
|
|
gk.observe(1, 400.0, 300.0, 0.0, 4.0, 100)
|
|
gk.observe(1, 400.0, 300.0, 30.0, 4.0, 100 + GK_GAP_MAX) # 5 deg/tick avg
|
|
let fOk = gk.featuresFor(ws, 1, 2.0, 0.0, 0.0)
|
|
check "a gap within GK_GAP_MAX produces no unknown",
|
|
fOk.turning == gkLeft and fOk.speedTrend == gkConstant and
|
|
gk.unknownCount == 0 and gk.featureCount == 1 and gk.unknownRate() == 0.0
|
|
|
|
# a gap of GK_GAP_MAX + 1 is no evidence -> unknown, counted
|
|
gk.observe(2, 400.0, 300.0, 0.0, 4.0, 200)
|
|
gk.observe(2, 400.0, 300.0, 12.0, 4.0, 200 + GK_GAP_MAX + 1)
|
|
let fBad = gk.featuresFor(ws, 2, 2.0, 0.0, 0.0)
|
|
check "a gap over GK_GAP_MAX produces gkUnknown on both features",
|
|
fBad.turning == gkUnknown and fBad.speedTrend == gkUnknown
|
|
check "the unknown counter and rate reflect exactly that one derivation",
|
|
gk.unknownCount == 1 and gk.featureCount == 2 and
|
|
close(gk.unknownRate(), 0.5)
|
|
check "the unknown situation keys to its own row, apart from the known one",
|
|
keyOf(fBad) != keyOf(fOk)
|
|
|
|
# the unknown row is a usable, separate row: learning in it never leaks into
|
|
# the confidently-straight one
|
|
var straight = fOk
|
|
straight.turning = gkStraight
|
|
straight.speedTrend = gkConstant
|
|
for _ in 0 ..< 40: gk.update(fBad, 3, true)
|
|
for _ in 0 ..< 40: gk.update(straight, 20, true)
|
|
check "the unknown row keeps its own learned residual",
|
|
gk.aim(fBad, 0.0).residualBin == 3 and
|
|
gk.aim(straight, 0.0).residualBin == 20
|
|
|
|
# ── 10. prune (maintenance) ───────────────────────────────────────────────────
|
|
|
|
proc testPrune() =
|
|
var gk = initGunKnowledge()
|
|
# four DIFFERENT keys, one per situation (space / distance separate them)
|
|
let dead = mk(150.0, 0.0, 0.0, 0.0, 1.0) # free, 3 attempts -> below 5
|
|
for _ in 0 ..< 3: gk.update(dead, 0, false)
|
|
var liveF = dead # near one wall, 8 attempts
|
|
liveF.space = gkNearWall
|
|
for _ in 0 ..< 8: gk.update(liveF, 2, true)
|
|
let oppLow = mk(250.0, 0.0, 0.0, 1.0, 1.0) # free, opponent row below 20
|
|
let oid = gk.opponentId("X")
|
|
for _ in 0 ..< 7: gk.update(oppLow, 3, true, oid)
|
|
var oppLive = oppLow # in a corner, opponent row 30
|
|
oppLive.space = gkCorner
|
|
for _ in 0 ..< 30: gk.update(oppLive, 4, true, oid)
|
|
|
|
check "the four situations really are four different keys",
|
|
keyOf(dead) != keyOf(liveF) and keyOf(oppLow) != keyOf(oppLive) and
|
|
keyOf(dead) != keyOf(oppLow)
|
|
|
|
let dropped = gk.prune()
|
|
check "prune drops the two sub-threshold rows", dropped == 2
|
|
check "prune KEEPS a global row at threshold",
|
|
gk.rowAttempts(liveF) == 8 and gk.rowHitCount(liveF, 2) == 8
|
|
check "prune KEEPS an opponent row past its threshold",
|
|
gk.rowAttempts(oppLive, oid) == 30
|
|
check "prune reset the sub-threshold rows to empty",
|
|
gk.rowAttempts(dead) == 0 and gk.rowAttempts(oppLow, oid) == 0
|
|
check "prune is idempotent", gk.prune() == 0
|
|
|
|
# ── 11. row layout, table size and memory ─────────────────────────────────────
|
|
|
|
proc testLayout() =
|
|
check "GkRow is 2 + 32*2 = 66 bytes (no bool: opponent rows live separately)",
|
|
sizeof(GkRow) == 2 + 32 * 2
|
|
check "the table is sized to the reachable row count, 3840",
|
|
GK_NKEYS == 3840
|
|
var gk = initGunKnowledge()
|
|
check "the global table really has 3840 rows allocated",
|
|
gk.globalRows.len == 3840
|
|
check "memoryBytes is exactly 3840 * 66 = 253440 B for an empty table",
|
|
gk.memoryBytes() == 3840 * 66 and gk.memoryBytes() == 253440
|
|
check "memoryBytes grows by one row per opponent row",
|
|
(block:
|
|
let f = mk(120.0, 0.0, 0.0, 2.0, 1.0)
|
|
let oid = gk.opponentId("X")
|
|
let before = gk.memoryBytes()
|
|
gk.update(f, 3, true, oid)
|
|
gk.memoryBytes() == before + sizeof(GkRow))
|
|
check "the table is a sane amount of RAM (< 1 MiB, was 35 MiB at 19 bits)",
|
|
GK_NKEYS * sizeof(GkRow) < 1024 * 1024 and
|
|
GK_NKEYS * sizeof(GkRow) == 253440
|
|
check "thresholds are 5 global / 20 opponent / 3 per bin",
|
|
GK_GLOBAL_MIN_ATTEMPTS == 5 and GK_OPP_MIN_ATTEMPTS == 20 and
|
|
GK_MIN_BIN_HITS == 3
|
|
check "the turn and trend features each spend 3 bits on their gkUnknown value",
|
|
GK_TURN_BITS == 3 and GK_TREND_BITS == 3
|
|
check "the six feature widths sum to the 15 bits of GK_KEY_BITS",
|
|
GK_DIST_BITS + GK_SPACE_BITS + GK_TURN_BITS + GK_TREND_BITS +
|
|
GK_HEAT_BITS + GK_RADIAL_BITS == GK_KEY_BITS
|
|
check "the header is magic + 6 u32 = 32 bytes",
|
|
GK_HEADER_LEN == 32 and GK_MAGIC.len == 8 and GK_VERSION == 1'u32
|
|
|
|
# ── 9c. the NULL residual: no correction, and no correction is what a row
|
|
# that learned nothing must say ────────────────────────────────────────
|
|
|
|
proc testNullResidual() =
|
|
let f = mk(320.0, 40.0, 55.0, 3.5, 2.0)
|
|
|
|
# a FRESH row explores (GK_EPSILON of its shots take a uniform bin out of all
|
|
# 32) but the null is still the DEFAULT: it is what an unmeasured row says,
|
|
# and it is the only answer that is right whenever the base was right.
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
let fresh = gk.aim(f, 0.0)
|
|
check "a fresh row claims no source and its answer is the null or its bin",
|
|
fresh.legalFresh
|
|
check "the fresh row's null is bin 0, the 0 deg bin",
|
|
residualBin(0.0) == GK_NULL_BIN and
|
|
binCentre(GK_NULL_BIN) == 0.0
|
|
|
|
# many null-residual observations: hits pile into bin 0, and the answer stays
|
|
# 0 deg forever
|
|
for _ in 0 ..< 500: gk.update(f, -1, true)
|
|
let after = gk.aim(f, 0.0)
|
|
check "500 null-residual hits still answer with the null residual",
|
|
after.residual == 0.0 and after.source == gkSourceGlobal and
|
|
after.residualBin == GK_NULL_BIN and close(after.aim, after.base)
|
|
check "those hits really landed in bin 0 and nowhere else",
|
|
gk.rowHitCount(f, 0) == 500 and
|
|
(block:
|
|
var elsewhere = false
|
|
for b in 1 ..< GK_NBINS:
|
|
if gk.rowHitCount(f, b) != 0: elsewhere = true
|
|
not elsewhere)
|
|
|
|
# 500 null-residual MISSES (attempts, no hits) must not produce a correction
|
|
var gkMiss = initGunKnowledge(800.0, 600.0)
|
|
for _ in 0 ..< 500: gkMiss.update(f, -1, false)
|
|
let am = gkMiss.aim(f, 0.0)
|
|
check "500 null-residual misses still answer with the null residual",
|
|
am.residual == 0.0 and am.source == gkSourceGlobal
|
|
|
|
# a shot filed with a below-threshold residual never buys a large correction
|
|
var gkThin = initGunKnowledge(800.0, 600.0)
|
|
for _ in 0 ..< 3: gkThin.update(f, -1, true) # 3 hits, the per-bin minimum
|
|
for _ in 0 ..< 9: gkThin.update(f, -1, false) # 12 attempts: row is at threshold
|
|
let at = gkThin.aim(f, 0.0)
|
|
check "a below-threshold shot filed 12x answers with 0 deg, never a correction",
|
|
at.source == gkSourceGlobal and at.residual == 0.0 and
|
|
abs(at.residual) < 1e-9 and at.residualBin == GK_NULL_BIN
|
|
|
|
# but real evidence on a non-central bin DOES move the answer
|
|
var gkLearn = initGunKnowledge(800.0, 600.0)
|
|
let far = 25 # +18.0 deg
|
|
for _ in 0 ..< 40: gkLearn.update(f, far, true)
|
|
for _ in 0 ..< 40: gkLearn.update(f, GK_NULL_BIN, false)
|
|
let al = gkLearn.aim(f, 0.0)
|
|
check "40 hits on bin 25 win the argmax over 40 misses on the null",
|
|
al.residualBin == far and close(al.residual, binCentre(far)) and
|
|
al.residual > 0.0
|
|
check "a negative bin is learned the same way",
|
|
(block:
|
|
var g = initGunKnowledge(800.0, 600.0)
|
|
for _ in 0 ..< 50: g.update(f, 8, true) # -15.0 deg
|
|
let a = g.aim(f, 0.0)
|
|
a.residualBin == 8 and close(a.residual, -15.0))
|
|
check "an all-miss non-central bin never wins: the null keeps the tie",
|
|
(block:
|
|
var g = initGunKnowledge(800.0, 600.0)
|
|
for _ in 0 ..< 20: g.update(f, 31, false) # -30 bin, all misses
|
|
for _ in 0 ..< 20: g.update(f, GK_NULL_BIN, true)
|
|
g.aim(f, 0.0).residualBin == GK_NULL_BIN)
|
|
|
|
# ── 9d. EXPLORATION: an under-sampled row must actually TRY the bins ─────────
|
|
##
|
|
## The failure this test exists for: if every shot is filed at the null (bin 0)
|
|
## then `bestResidual`'s argmax can never move off the null, no non-zero
|
|
## correction is ever discovered, and the table is a machine for recording that
|
|
## the base was right. The policy is one line: below GK_EXPLORE_MIN attempts a
|
|
## shot takes a UNIFORM bin out of all 32 with probability GK_EPSILON, at or
|
|
## above it the row speaks for itself.
|
|
|
|
proc testExploration() =
|
|
let f = mk(320.0, 40.0, 55.0, 3.5, 2.0)
|
|
|
|
# 1. a fresh row DOES explore, and the bin it tried is what gets filed.
|
|
# The window is the 19 shots a row has before GK_EXPLORE_MIN attempts.
|
|
var gk = initGunKnowledge(800.0, 600.0)
|
|
var tried: seq[int] = @[]
|
|
var nulls = 0
|
|
var allLegal = true
|
|
for i in 0 ..< GK_EXPLORE_MIN - 1:
|
|
let a = gk.aim(f, 0.0)
|
|
if not a.legalFresh: allLegal = false
|
|
if a.residualBin == -1: inc nulls
|
|
else: tried.add a.residualBin
|
|
# the caller files what `aim` REPORTED, and the hits land in that bin
|
|
gk.update(f, a.residualBin, a.residualBin in 0 ..< GK_NBINS and i mod 2 == 0)
|
|
check "every under-sampled answer is the null or the centre of its own bin",
|
|
allLegal
|
|
check "a fresh row explores: the under-sampled shots try non-null bins",
|
|
tried.len > 0
|
|
check "exploration covers more than one bin (a uniform draw, not a fixed one)",
|
|
(block:
|
|
var seen = initTable[int, bool]()
|
|
for b in tried: seen[b] = true
|
|
seen.len > 1)
|
|
check "the null is still the DEFAULT: it is the majority of the shots",
|
|
nulls > (GK_EXPLORE_MIN - 1) div 2
|
|
check "the FIRST shot on a row is never a probe",
|
|
(block:
|
|
var g0 = initGunKnowledge(800.0, 600.0)
|
|
let a0 = g0.aim(f, 0.0)
|
|
a0.residualBin == -1 and a0.residual == 0.0 and
|
|
g0.rowAttempts(f) == 1)
|
|
check "an explored shot's hits are filed in ITS bin, not in the null",
|
|
(block:
|
|
var credited = false
|
|
for b in tried:
|
|
if gk.rowHitCount(f, b) > 0: credited = true
|
|
credited)
|
|
|
|
# 2. the exploration rate over the window is near GK_EPSILON
|
|
var gkRate = initGunKnowledge(800.0, 600.0)
|
|
var tries = 0
|
|
for _ in 0 ..< GK_EXPLORE_MIN - 1: # a SECOND table, its own LCG state
|
|
if gkRate.aim(f, 0.0).residualBin != -1: inc tries
|
|
check "the exploration rate is near GK_EPSILON (got " & $tries & "/" &
|
|
$(GK_EXPLORE_MIN - 1) & ")", tries > 0 and
|
|
abs(tries.float / (GK_EXPLORE_MIN - 1).float - GK_EPSILON) < 0.15
|
|
|
|
# 3. at or above the threshold there is NO exploration: the row answers with
|
|
# bestResidual. Planted as attempts >= GK_EXPLORE_MIN with no bin past
|
|
# GK_MIN_BIN_HITS, so the ONLY thing that could answer is the null.
|
|
var gkQuiet = initGunKnowledge(800.0, 600.0)
|
|
for _ in 0 ..< GK_EXPLORE_MIN: gkQuiet.update(f, -1, false)
|
|
var stillNull = true
|
|
for _ in 0 ..< 200:
|
|
let a = gkQuiet.aim(f, 0.0)
|
|
if a.residualBin != -1 or a.residual != 0.0: stillNull = false
|
|
check "at/above GK_EXPLORE_MIN attempts the row answers with bestResidual only",
|
|
stillNull and gkQuiet.rowAttempts(f) >= GK_EXPLORE_MIN
|
|
|
|
# 4. once evidence exists the argmax wins over the exploration entirely
|
|
var gkConv = initGunKnowledge(800.0, 600.0)
|
|
let good = 20 # +8 deg
|
|
for _ in 0 ..< 40: gkConv.update(f, good, true)
|
|
for _ in 0 ..< 40: gkConv.update(f, GK_NULL_BIN, false)
|
|
var alwaysGood = true
|
|
for _ in 0 ..< 50:
|
|
let a = gkConv.aim(f, 0.0)
|
|
if a.residualBin != good: alwaysGood = false
|
|
check "a row that has learned a bin stops exploring and returns the argmax",
|
|
alwaysGood and close(gkConv.aim(f, 0.0).residual, binCentre(good))
|
|
|
|
# 5. the exploration RNG is the MODULE'S OWN: the global stream is untouched,
|
|
# and the module's stream is deterministic (same seed, same answers).
|
|
randomize(1234)
|
|
let before = rand(1_000_000)
|
|
randomize(1234)
|
|
var gkRng = initGunKnowledge(800.0, 600.0)
|
|
var gkRng2 = initGunKnowledge(800.0, 600.0)
|
|
var same = true
|
|
for _ in 0 ..< GK_EXPLORE_MIN - 1:
|
|
let a1 = gkRng.aim(f, 0.0)
|
|
let a2 = gkRng2.aim(f, 0.0)
|
|
if a1.residualBin != a2.residualBin: same = false
|
|
gkRng.update(f, a1.residualBin, true)
|
|
gkRng2.update(f, a2.residualBin, true)
|
|
let after = rand(1_000_000)
|
|
check "the whole aim+update path does not perturb the global RNG",
|
|
before == after
|
|
check "the exploration stream is deterministic (constant seed, two tables)",
|
|
same
|
|
|
|
# ── 9e. the returned point preserves the FORECAST distance ────────────────────
|
|
##
|
|
## `predict` places the aim point at `GkAim.dist`, the distance to the
|
|
## PREDICTED enemy position, and NOT the current LOS distance. The forecast is a
|
|
## self-consistent fixed point precisely so the radius the bullet is resolved at
|
|
## is the radius it actually flies; using the fire-time LOS distance is the
|
|
## failure `lead_forecast`'s header records for the closed form.
|
|
|
|
proc testForecastDistance() =
|
|
proc distTo(g: var KnowledgeGun, ex, ey, ehead, espd, spd, selfX, selfY: float
|
|
): tuple[d, los, fc: float] =
|
|
let ws = WorldState(enemyX: ex, enemyY: ey, enemyHeading: ehead,
|
|
enemySpeed: espd, selfX: selfX, selfY: selfY,
|
|
selfHeading: 0.0, arenaWidth: 800.0,
|
|
arenaHeight: 600.0, tick: 10)
|
|
let p = g.predict(ws, spd)
|
|
(hypot(p.x - selfX, p.y - selfY),
|
|
hypot(ex - selfX, ey - selfY),
|
|
forecastLinear(ws, spd).dist)
|
|
|
|
let sx = 400.0
|
|
let sy = 300.0
|
|
# receding: the forecast point is FARTHER than the enemy is now
|
|
var away = initKnowledgeGun("")
|
|
away.gunHeat = 0.0
|
|
away.targetId = 3
|
|
let a = away.distTo(520.0, 300.0, 0.0, 6.0, bulletSpeed(2.0), sx, sy)
|
|
check "a receding target: the point is at the FORECAST distance, not the LOS",
|
|
a.fc > a.los and close(a.d, a.fc, 1e-6)
|
|
# closing: the forecast point is NEARER
|
|
var near = initKnowledgeGun("")
|
|
near.gunHeat = 0.0
|
|
near.targetId = 3
|
|
let b = near.distTo(520.0, 300.0, 180.0, 6.0, bulletSpeed(2.0), sx, sy)
|
|
check "an approaching target: the point is at the FORECAST distance, not the LOS",
|
|
b.fc < b.los and close(b.d, b.fc, 1e-6)
|
|
# a stationary target has no forecast lead, so the two distances coincide --
|
|
# this is the ONE case where the two readings are indistinguishable
|
|
var still = initKnowledgeGun("")
|
|
still.gunHeat = 0.0
|
|
still.targetId = 3
|
|
let c = still.distTo(520.0, 300.0, 0.0, 0.0, bulletSpeed(2.0), sx, sy)
|
|
check "a stationary target: forecast distance == LOS distance == the point",
|
|
close(c.fc, c.los) and close(c.d, c.fc, 1e-6)
|
|
# the same numbers straight out of the learner
|
|
var gkL = initGunKnowledge(800.0, 600.0)
|
|
let fA = mk(520.0, 300.0, 0.0, 6.0, 2.0)
|
|
check "aim() reports the forecast distance in GkAim.dist",
|
|
close(gkL.aim(fA, 0.0).dist,
|
|
forecastLinear(
|
|
WorldState(enemyX: 520.0, enemyY: 300.0, selfX: 0.0, selfY: 0.0,
|
|
enemyHeading: 0.0, enemySpeed: 6.0),
|
|
bulletSpeed(2.0)).dist, 1e-9)
|
|
|
|
# ── 15. the pending slot is the VIRTUAL bin's, never the real shot's ─────────
|
|
##
|
|
## `pending[powerBinSlot(power)]` was written from BOTH `predict` call sites:
|
|
## the per-bin virtual loop (`ModularBot.nim:1380`, exact `PowerBins[i]`) and
|
|
## the real-shot predict (`ModularBot.nim:1484`, the policy-capped power,
|
|
## often 0.7). `powerBinSlot` FLOORS it onto the next bin down (0.7 -> 1.0,
|
|
## 1.7 -> 1.5), so the real shot OVERWROTE that bin's pending record with its
|
|
## own features and residual -- same fireTick, so the resolution guard
|
|
## (`fireTick` match) let it through and the bin's virtual bullet trained the
|
|
## wrong power's row, silently.
|
|
|
|
proc testPendingSlotOwnership() =
|
|
let ws = mkState(0.0, 520.0, 300.0, 90.0, 5.0)
|
|
# 1. a real-shot power that is NOT a bin must not touch the slot it floors
|
|
# into: 0.7 -> bin 1.0, 1.7 -> bin 1.5 (the slot the 1.5 virtual aim uses)
|
|
for nonBin in [0.7'f64, 1.7'f64]:
|
|
var g = initKnowledgeGun("")
|
|
g.gunHeat = 0.0
|
|
g.targetId = 7
|
|
discard g.predict(ws, bulletSpeed(nonBin))
|
|
let slot = powerBinSlot(nonBin)
|
|
check "a non-bin real-shot power is not an exact PowerBins value",
|
|
abs(PowerBins[slot] - nonBin) > 1e-9
|
|
check "a real shot at p=" & $nonBin & " writes no pending slot " &
|
|
"(it would have floored onto bin " & $PowerBins[slot] & ")",
|
|
not g.pending[slot].valid
|
|
# 2. the per-bin virtual loop (exact bin) still records its pending aim
|
|
var v = initKnowledgeGun("")
|
|
v.gunHeat = 0.0
|
|
v.targetId = 7
|
|
discard v.predict(ws, bulletSpeed(1.5))
|
|
check "an exact-bin virtual predict still writes its pending slot",
|
|
v.pending[powerBinSlot(1.5)].valid and
|
|
v.pending[powerBinSlot(1.5)].fireTick == ws.tick and
|
|
close(v.pending[powerBinSlot(1.5)].f.power, 1.5, 1e-6)
|
|
# 3. and the record survives a later non-bin real shot on the SAME tick
|
|
# (same fireTick => the resolution guard alone would not have caught it)
|
|
let before = v.pending[powerBinSlot(1.5)]
|
|
discard v.predict(ws, bulletSpeed(1.7)) # floors onto the SAME slot (1.5)
|
|
let after = v.pending[powerBinSlot(1.5)]
|
|
check "a non-bin real shot does not OVERWRITE the bin's pending record",
|
|
after.valid and after.usedBin == before.usedBin and
|
|
after.fireTick == before.fireTick and
|
|
close(after.f.power, before.f.power, 1e-9)
|
|
# 4. onResult for that power trains nothing (no pending record to resolve)
|
|
var g2 = initKnowledgeGun("")
|
|
g2.gunHeat = 0.0
|
|
g2.targetId = 7
|
|
discard g2.predict(ws, bulletSpeed(0.7))
|
|
let gkBefore = g2.gk
|
|
g2.onResult(FeedbackEvent(fireTick: ws.tick, powerBin: powerBinSlot(0.7),
|
|
hit: true))
|
|
check "onResult on a non-bin power trains NO row (the corruption itself)",
|
|
sameState(g2.gk, gkBefore)
|
|
# 5. the legit path still learns: the exact-bin record resolves and updates
|
|
var g3 = initKnowledgeGun("")
|
|
g3.gunHeat = 0.0
|
|
g3.targetId = 7
|
|
discard g3.predict(ws, bulletSpeed(1.5))
|
|
let gkBefore3 = g3.gk
|
|
g3.onResult(FeedbackEvent(fireTick: ws.tick, powerBin: powerBinSlot(1.5),
|
|
hit: true))
|
|
check "onResult on the exact-bin power still trains its own row",
|
|
not sameState(g3.gk, gkBefore3)
|
|
|
|
# ── driver ────────────────────────────────────────────────────────────────────
|
|
|
|
testResidualBins()
|
|
testKeyPacking()
|
|
testClosedFormCrossCheck()
|
|
testForecastBase()
|
|
testAimFrameInvariant()
|
|
testScanTrack()
|
|
testUnknown()
|
|
testFallbackChain()
|
|
testLearnThenQuery()
|
|
testSpace()
|
|
testPersistence()
|
|
testPrune()
|
|
testNullResidual()
|
|
testExploration()
|
|
testForecastDistance()
|
|
testPendingSlotOwnership()
|
|
testLayout()
|
|
|
|
echo ""
|
|
echo "checks: ", checks, " failures: ", failures
|
|
if failures > 0: quit(1)
|