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.
326 lines
15 KiB
Nim
326 lines
15 KiB
Nim
## Registration guard for the KNOWLEDGE gun (rack id 17), the learned additive
|
|
## angular residual on top of the self-consistent lead forecast
|
|
## (`common_libs/guns/gun_knowledge.nim`).
|
|
##
|
|
## Mirrors `test_lead_gain_registration.nim`: no Java, no battle, no network
|
|
## build. Covers:
|
|
## * KNOWLEDGE is APPENDED at id 17 and every pre-existing id is byte-identical
|
|
## (a rack gun that renumbered would silently re-address every
|
|
## `tools/ab/arms_*.txt` config and every `gun_stats.jsonl` column);
|
|
## * it defaults to `off`, so the shipped rack still admits exactly Pattern;
|
|
## * `TR_RACK_KNOWLEDGE=...` is what admits it, in 1v1 and in melee, and the
|
|
## live `vBulletAdmitted` spawn gate honours the membership;
|
|
## * `initKnowledgeGun()` is LAZY (0 bytes before first use) and the whole
|
|
# aim+update path, EXPLORATION included, does NOT touch the global RNG, so
|
|
## a rack that admits it cannot perturb the selector's `rand` stream;
|
|
## * the gun implements the rack `Gun` concept, learns from its own feedback
|
|
## into the exact row that produced the angle, keeps its counts across a
|
|
## round boundary and persists them atomically.
|
|
##
|
|
## Run: nim c -r --path:common_libs common_libs/tests/test_knowledge_registration.nim
|
|
|
|
import std/[math, os, random, strutils, tables]
|
|
import gun_harness/virtual_bullets
|
|
import gun_harness/selector
|
|
import gun_harness/gun_interface
|
|
import guns/gun_knowledge
|
|
|
|
const
|
|
KnowledgeId = 17
|
|
PatternId = 5
|
|
LeadGainId = 16
|
|
## The rack as it was BEFORE this gun was appended. Pinned literal-by-literal:
|
|
## if a future edit shifts an id, this fails here instead of in a live battle.
|
|
PreRack = ["HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN",
|
|
"WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF",
|
|
"KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"]
|
|
|
|
var failures = 0
|
|
proc check(name: string, ok: bool) =
|
|
if ok: echo "PASS: ", name
|
|
else: echo "FAIL: ", name; inc failures
|
|
|
|
proc clearRackEnv() =
|
|
for name in RackGunNames: delEnv("TR_RACK_" & name)
|
|
|
|
proc wsFor(tick: int, ex, ey, es, eh: float): WorldState =
|
|
WorldState(enemyX: ex, enemyY: ey, enemySpeed: es, enemyHeading: eh,
|
|
selfX: 0.0, selfY: 0.0, selfHeading: 0.0,
|
|
arenaWidth: 800.0, arenaHeight: 600.0, tick: tick)
|
|
|
|
# ── the rack table ───────────────────────────────────────────────────────────
|
|
|
|
proc testTable() =
|
|
check "rack: KNOWLEDGE is registered at id 17", RackGunNames[KnowledgeId] == "KNOWLEDGE"
|
|
check "rack: NumRackGuns grew to 18", NumRackGuns >= 18 and
|
|
RackGunNames.len == NumRackGuns
|
|
check "rack: KNOWLEDGE defaults to `off`", DefaultRackMembership[KnowledgeId] == rmOff
|
|
check "rack: the membership table has one entry per gun",
|
|
DefaultRackMembership.len == NumRackGuns
|
|
|
|
# No existing id moved, and no existing name changed. (`>` not `==`: guns
|
|
# appended AFTER KNOWLEDGE, e.g. WAVEELM at 18, do not move anything.)
|
|
var untouched = RackGunNames.len > PreRack.len
|
|
for i in 0 ..< PreRack.len:
|
|
if RackGunNames[i] != PreRack[i]: untouched = false
|
|
check "rack: every pre-existing id kept its name (KNOWLEDGE appended at the end)", untouched
|
|
|
|
var seen = initTable[string, bool]()
|
|
var allDistinct = true
|
|
for n in RackGunNames:
|
|
if n in seen: allDistinct = false
|
|
seen[n] = true
|
|
check "rack: all rack gun names are distinct", allDistinct
|
|
|
|
# Id 17 was free: no shipped gun occupied it. (It is the id the RETIRED ADE+SBC
|
|
# BITBRAIN gun briefly had; nothing addresses it any more — `TR_RACK_BITBRAIN`
|
|
# is LEADGAIN's legacy alias, pinned by test_lead_gain_legacy.nim.)
|
|
check "rack: KNOWLEDGE's id is in range for every per-gun table",
|
|
KnowledgeId < NumRackGuns
|
|
|
|
var onlyPattern = true
|
|
for i in 0..<RackGunNames.len:
|
|
let want = if i == PatternId: rmBoth else: rmOff
|
|
if DefaultRackMembership[i] != want: onlyPattern = false
|
|
check "rack: the shipped default is still the onlyPattern rack", onlyPattern
|
|
check "rack: the default rack admits only Pattern (1v1)",
|
|
admittedGuns(NumRackGuns, rm1v1, DefaultRackMembership) == @[PatternId]
|
|
check "rack: the default rack admits only Pattern (melee)",
|
|
admittedGuns(NumRackGuns, rmMelee, DefaultRackMembership) == @[PatternId]
|
|
check "gate: KNOWLEDGE is NOT spawned under the default rack",
|
|
not vBulletAdmitted(KnowledgeId, rm1v1, DefaultRackMembership, true)
|
|
check "gate: LEADGAIN is still NOT spawned under the default rack (no regression)",
|
|
not vBulletAdmitted(LeadGainId, rm1v1, DefaultRackMembership, true)
|
|
|
|
# ── the env override, per membership semantics ───────────────────────────────
|
|
|
|
proc testEnvOverride() =
|
|
clearRackEnv()
|
|
putEnv("TR_RACK_KNOWLEDGE", "both")
|
|
let m = loadRackMembership()
|
|
check "env: TR_RACK_KNOWLEDGE=both admits KNOWLEDGE",
|
|
m[KnowledgeId] == rmBoth and
|
|
vBulletAdmitted(KnowledgeId, rm1v1, m, true) and
|
|
vBulletAdmitted(KnowledgeId, rmMelee, m, true)
|
|
check "env: admitting KNOWLEDGE leaves Pattern as the only other member",
|
|
admittedGuns(NumRackGuns, rm1v1, m) == @[PatternId, KnowledgeId]
|
|
check "env: the legacy alias still selects LEADGAIN, not KNOWLEDGE",
|
|
m[LeadGainId] == rmOff
|
|
clearRackEnv()
|
|
|
|
putEnv("TR_RACK_KNOWLEDGE", "1v1")
|
|
let m1 = loadRackMembership()
|
|
check "env: =1v1 admits it in 1v1 only",
|
|
vBulletAdmitted(KnowledgeId, rm1v1, m1, true) and
|
|
not vBulletAdmitted(KnowledgeId, rmMelee, m1, true)
|
|
check "env: =1v1 leaves the melee rack as Pattern alone",
|
|
admittedGuns(NumRackGuns, rmMelee, m1) == @[PatternId]
|
|
clearRackEnv()
|
|
|
|
putEnv("TR_RACK_KNOWLEDGE", "melee")
|
|
let mM = loadRackMembership()
|
|
check "env: =melee admits it in melee only",
|
|
vBulletAdmitted(KnowledgeId, rmMelee, mM, true) and
|
|
not vBulletAdmitted(KnowledgeId, rm1v1, mM, true)
|
|
clearRackEnv()
|
|
|
|
putEnv("TR_RACK_KNOWLEDGE", "off")
|
|
let mOff = loadRackMembership()
|
|
check "env: =off is still the shipped behaviour",
|
|
mOff[KnowledgeId] == rmOff and
|
|
not vBulletAdmitted(KnowledgeId, rm1v1, mOff, true)
|
|
clearRackEnv()
|
|
|
|
# The gate's `admitOnly=false` escape hatch keeps every gun spawning.
|
|
check "gate: TR_VBULLET_ADMIT_ONLY=0 spawns KNOWLEDGE even when off",
|
|
vBulletAdmitted(KnowledgeId, rm1v1, DefaultRackMembership, false)
|
|
|
|
# ── lazy init and the global-RNG contract ────────────────────────────────────
|
|
|
|
proc testLazyAndRngClean() =
|
|
delEnv(GK_MEM_ENV)
|
|
var g = initKnowledgeGun()
|
|
check "lazy: constructing the gun does NOT build the 3840-row table (0 bytes)",
|
|
g.networkBytes == 0
|
|
check "lazy: unset TR_KNOWLEDGE_MEM is memory-only (no disk path)",
|
|
g.memPath.len == 0
|
|
check "lazy: the gun is a `Gun` (predict + onResult, the rack concept)",
|
|
isGun(KnowledgeGun)
|
|
|
|
var warm = initKnowledgeGun()
|
|
let ws = WorldState(enemyX: 300.0, enemyY: 200.0, enemySpeed: 3.0,
|
|
enemyHeading: 180.0, selfX: 0.0, selfY: 0.0,
|
|
selfHeading: 0.0, arenaWidth: 800.0, arenaHeight: 600.0,
|
|
tick: 1)
|
|
discard warm.predict(ws, bulletSpeed(1.0))
|
|
check "lazy: the table exists after the first predict",
|
|
warm.networkBytes == GK_NKEYS * sizeof(GkRow)
|
|
|
|
# Global RNG parity: constructing the gun must not consume global randomness.
|
|
# The 3840-row table is a plain `newSeq`/`initTable`; nothing in the module's
|
|
# init path draws, so the selector's `rand` stream is untouched.
|
|
randomize(1234)
|
|
let a = rand(1_000_000)
|
|
randomize(1234)
|
|
var g2 = initKnowledgeGun()
|
|
discard g2.networkBytes
|
|
let b = rand(1_000_000)
|
|
check "parity: initKnowledgeGun() does not perturb the global RNG", a == b
|
|
|
|
# ...and neither does the first USE of the table (the allocation + the first
|
|
# forecast), which is the moment a random draw would be most tempting.
|
|
randomize(1234)
|
|
let c = rand(1_000_000)
|
|
randomize(1234)
|
|
var g3 = initKnowledgeGun()
|
|
for t in 0 .. 5:
|
|
discard g3.predict(wsFor(t, 300.0 - 5.0 * t.float, 200.0, 3.0,
|
|
180.0 + 4.0 * t.float), bulletSpeed(1.0))
|
|
let d = rand(1_000_000)
|
|
check "parity: using the table does not perturb the global RNG either", c == d
|
|
|
|
# ...and EXPLORATION draws, but from the module's OWN LCG state
|
|
# (`GunKnowledge.rng`), never from the global one. The learner probes a
|
|
# uniform residual bin on an under-sampled row, so this is the check that
|
|
# actually covers the draw, over a whole learn/resolve loop.
|
|
randomize(1234)
|
|
let e = rand(1_000_000)
|
|
randomize(1234)
|
|
var g4 = initKnowledgeGun()
|
|
g4.targetId = 3
|
|
var explored = false
|
|
for t in 0 ..< 40:
|
|
let fired = g4.predict(wsFor(t, 300.0 - 4.0 * t.float, 200.0, 3.0,
|
|
180.0 + 3.0 * t.float),
|
|
bulletSpeed(PowerBins[0]))
|
|
g4.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0],
|
|
fireTick: t, powerBin: 0, missDistance: 4.0,
|
|
hit: t mod 3 == 0, confidence: fired.confidence))
|
|
if g4.pending[0].usedBin != -1: explored = true
|
|
let h = rand(1_000_000)
|
|
check "parity: exploration (40 predict+onResult) does not touch global rand",
|
|
e == h
|
|
check "parity: that loop really did explore a non-null residual bin",
|
|
explored
|
|
|
|
# ── the gun learns, and the learning lands on the row that produced the angle ──
|
|
|
|
proc testLearning() =
|
|
delEnv(GK_MEM_ENV)
|
|
var g = initKnowledgeGun()
|
|
g.targetId = 3 # the caller names the opponent
|
|
check "learn: an unarmed gun still returns an aim point",
|
|
g.predict(wsFor(0, 300.0, 200.0, 3.0, 0.0), bulletSpeed(1.0)).x != 0.0
|
|
check "learn: the confidence carries the gkUnknown rate (0.0 = no data yet)",
|
|
g.unknownRate == 0.0
|
|
|
|
# Two ticks, so the track has a pair and the turn/trend features are known.
|
|
discard g.predict(wsFor(1, 297.0, 200.0, 3.0, 0.0), bulletSpeed(1.0))
|
|
check "learn: the gkUnknown rate is exposed for a live battle",
|
|
g.unknownRate >= 0.0 and g.unknownRate <= 1.0
|
|
|
|
# Fire the virtual bullet the way the harness does, and resolve it as a HIT.
|
|
# The row that produced the angle must be the row that learns.
|
|
let fired = g.predict(wsFor(2, 294.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0]))
|
|
g.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0],
|
|
fireTick: 2, powerBin: 0, missDistance: 4.0,
|
|
hit: true, confidence: fired.confidence))
|
|
check "learn: onResult wrote an attempt into the table",
|
|
g.gk.featureCount > 0 and g.gk.unknownCount <= g.gk.featureCount
|
|
|
|
# A MISS resolving the same tick/bucket adds a second attempt and no hit.
|
|
let fired2 = g.predict(wsFor(3, 291.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0]))
|
|
g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0],
|
|
fireTick: 3, powerBin: 0, missDistance: 40.0,
|
|
hit: false, confidence: fired2.confidence))
|
|
check "learn: a miss resolves into the same per-power-bucket record",
|
|
g.gk.usedGlobalRows >= 1
|
|
|
|
# A feedback for a tick the gun never predicted (a stale / other-round bullet)
|
|
# must NOT create evidence: the row is only updated for the shot taken.
|
|
let before = g.gk.usedGlobalRows
|
|
g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0],
|
|
fireTick: 999, powerBin: 0, missDistance: 4.0,
|
|
hit: true, confidence: fired2.confidence))
|
|
check "learn: feedback for an unknown fire tick is dropped, not learned",
|
|
g.gk.usedGlobalRows == before
|
|
|
|
# The fallback chain has to REACH a threshold before it answers with a
|
|
# residual, so a cold gun must return the plain forecast (residual 0) and
|
|
# start COUNTING the situation so it can get there.
|
|
var fresh = initGunKnowledge(800.0, 600.0)
|
|
let fCold = fresh.featuresFor(wsFor(0, 300.0, 200.0, 3.0, 0.0), 3, 1.0, 0.0, 0.0)
|
|
let aCold = fresh.aim(fCold, 0.0)
|
|
check "learn: a cold table answers with no residual (the forecast alone)",
|
|
aCold.hasTarget and aCold.residual == 0.0 and
|
|
aCold.residualBin == -1 and aCold.source == gkSourceNone
|
|
check "learn: the cold answer still counts the situation for later",
|
|
fresh.usedGlobalRows == 1 and fresh.rowAttempts(fCold) == 1
|
|
|
|
# Round boundary: the counts SURVIVE (this gun's own capability), the
|
|
# per-round scan track does not.
|
|
let usedRows = g.gk.usedGlobalRows
|
|
g.onRoundBoundary()
|
|
check "persist: the learned rows survive a round boundary",
|
|
g.gk.usedGlobalRows == usedRows
|
|
check "persist: the per-round scan track is dropped at the boundary",
|
|
g.gk.tracks.len == 0
|
|
|
|
# ── on-disk persistence, at a round boundary ─────────────────────────────────
|
|
|
|
proc testPersistence() =
|
|
let path = getTempDir() / "gk_registration_table.bin"
|
|
if fileExists(path): removeFile(path)
|
|
defer:
|
|
if fileExists(path): removeFile(path)
|
|
|
|
var g = initKnowledgeGun(path)
|
|
check "persist: an explicit path is the memory path", g.memPath == path
|
|
g.targetId = 7
|
|
# 30 ticks of ONE steady situation (tangential move, constant heading and
|
|
# speed), so the SAME key accumulates 30 attempts: past the global threshold
|
|
# (5) and past the opponent one (20). Fewer ticks would leave every row below
|
|
# threshold and `prune` — correctly — would drop all of them at the save.
|
|
for t in 0 ..< 30:
|
|
discard g.predict(wsFor(t, 300.0, 200.0 + 0.5 * t.float, 3.0, 90.0),
|
|
bulletSpeed(PowerBins[0]))
|
|
let rows = g.gk.usedGlobalRows + g.gk.oppRows.len
|
|
g.onRoundBoundary() # first boundary: load (nothing) + prune + save
|
|
let saved = g.gk.usedGlobalRows + g.gk.oppRows.len
|
|
check "persist: the round boundary wrote the table", fileExists(path)
|
|
check "persist: the table holds learned rows after the prune", saved > 0
|
|
check "persist: prune drops the rows that never reached threshold", saved <= rows
|
|
|
|
# A fresh gun in a fresh process-equivalent state picks the table back up.
|
|
var g2 = initKnowledgeGun(path)
|
|
g2.ensureInit()
|
|
check "persist: a cold gun has no rows before the load",
|
|
g2.gk.usedGlobalRows == 0 and g2.gk.oppRows.len == 0
|
|
g2.onRoundBoundary() # loads, then round-trips
|
|
check "persist: the table came back off disk",
|
|
g2.gk.usedGlobalRows + g2.gk.oppRows.len == saved
|
|
|
|
# A truncated file is REJECTED (strict parser), never half-loaded.
|
|
let full = readFile(path)
|
|
writeFile(path, full[0 ..< full.len div 2])
|
|
var g3 = initKnowledgeGun(path)
|
|
g3.ensureInit()
|
|
check "persist: a truncated file is rejected and the table stays empty",
|
|
not g3.gk.load(path) and g3.gk.usedGlobalRows == 0
|
|
writeFile(path, full)
|
|
var g4 = initKnowledgeGun(path)
|
|
g4.ensureInit()
|
|
check "persist: the intact file is accepted again",
|
|
g4.gk.load(path) and g4.gk.usedGlobalRows + g4.gk.oppRows.len == saved
|
|
|
|
testTable()
|
|
testEnvOverride()
|
|
testLazyAndRngClean()
|
|
testLearning()
|
|
testPersistence()
|
|
|
|
if failures > 0:
|
|
echo "\n", failures, " check(s) FAILED"
|
|
quit(1)
|
|
echo "\nAll KNOWLEDGE registration checks passed."
|