common_libs/guns: WaveElm ring gun, GUNK knowledge gun, online ELM

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.
This commit is contained in:
2026-10-05 22:43:22 +02:00
parent 68c6af98dc
commit 7505fbf089
17 changed files with 8427 additions and 0 deletions
+199
View File
@@ -0,0 +1,199 @@
# OS-ELM reference papers — audit, downloads, and update-rule notes
Audit date: 2026-08-22, extended 2026-10-02 (all identifiers re-fetched from arxiv.org,
api.crossref.org, api.openalex.org and doi.org — nothing here is trusted from a previous pass).
Re-download everything open access with:
```bash
./fetch_papers.sh # idempotent; exits non-zero and deletes any non-PDF
```
## CITATION NOTES — read this first
Three of the fourteen claimed citations were wrong, and one does not exist at all.
| Claim | Reality |
|---|---|
| `10.1109/TSMCS.2011.616645` — "Huang/Zhu/Zhou 2011–2012 ELM survey" | **DOES NOT EXIST.** `doi.org` returns **404**; absent from Crossref *and* OpenAlex. No paper carries this DOI. Do not cite it. |
| "Extreme Learning Machine: A Review and New Trends", Huang, IEEE T-SMC-B **42(2):513–529, 2012** | **WRONG TITLE + WRONG AUTHORS.** Those exact pages belong to `10.1109/TSMCB.2011.2168604` = *"Extreme Learning Machine for Regression and Multiclass Classification"*, **Huang, Zhou, Ding & Zhang** (4 authors, not 1). A Crossref title search for "…A Review and New Trends" returns **no such article**. Treat the title as fabricated. The likely intended real review is *"Trends in extreme learning machines: A review"*, `10.1016/j.neunet.2014.10.001` (Neural Networks 61:32–48, 2015). |
| `10.1007/s10922-025-09976-3` — "Shwaysh et al., Ensemble RELM, **J Real-Time Image Proc 2025**" | **WRONG VENUE.** It is *Journal of Network and Systems Management* **34(1), 2025** — an intrusion-detection paper. First author Shwaysh is correct. |
| `10.1007/s11042-021-11008-7` — "A review on extreme learning machine" | **TYPO, DOES NOT RESOLVE (404).** The correct DOI is **`10.1007/s11042-021-11007-7`** (11007, not 11008). |
Two more were near-misses rather than errors:
* **`arXiv:2512.21777` is REAL**, despite the "implausible number" flag. Submitted 2025-12-25, and the title matches almost verbatim (it spells out "Extreme Learning Machine"). Confirmed twice: `arxiv.org/abs/2512.21777` and the arXiv API. Not hallucinated.
* **`arXiv:2504.09028`** has a different title than claimed. It is *"Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing"*; the OSOS-ELM / one-sided-Jacobi content is real (it's in the abstract), only the title was misremembered.
One more non-existent citation, found on a later pass (audit date 2026-10-02):
* **"Extreme Learning Machines: A Survey", Huang / Zhu / Zhou, IEEE T-SMC-B 42(3):486–497 (2012)" — NOT DISCOVERABLE.** There is no such article. Crossref's full, *gap-free* inventory of T-SMC-B vol. 42 shows issue 2 runs 294–580 and issue 3 starts at 581, so pages 486–497 cannot be in either. The range 486–497 sits **inside** a different article, 42(2):482–500 = *"An Adaptive Differential Evolution Algorithm With Novel Mutation and Crossover Strategies for Global Numerical Optimization"* (`10.1109/TSMCB.2011.2167966`, Islam, Das, Ghosh, Roy, Suganthan), verified independently in OpenAlex. The genuine ELM article in issue 2 is 513–529 (`10.1109/TSMCB.2011.2168604`), the one already audited above. No DOI was found for a Huang/Zhu/Zhou survey; a `prefix:10.1109` Crossref title sweep and an OpenAlex title sweep both return nothing. **Do not cite 42(3):486–497.** Use `10.1007/s13042-011-0019-y` instead — it is the real, verifiable 2011 ELM survey, and it is now in this directory.
One open-access status correction:
* **`10.1007/s11042-021-11007-7` is listed as hybrid OA by OpenAlex, but its PDF cannot be fetched from here** — `link.springer.com/.../11007-7.pdf` answers `200 text/html` (a ~3 KB bot-challenge page), not a PDF. The green-OA copy at `ntu.edu.sg/.../ELM-Unified-Learning.pdf` now 404s. So it is listed as **not downloaded** below. MDPI likewise 403s on `www.mdpi.com/.../pdf`; `mdpi-res.com` works, which is what `fetch_papers.sh` uses.
## Audit table
| Claimed citation | Verdict | Correct identifier / real paper |
|---|---|---|
| arXiv:2512.21777 — "Online Learning ELM with Low-Complexity Predictive Plasticity Rule and FPGA Implementation" | **VERIFIED** (title differs only by spelling out "Extreme Learning Machine") | Zang, Li, Li — arXiv:2512.21777, 2025-12-25 |
| arXiv:2504.09028 — "…One-Sided Jacobi Rotation OSOS-ELM" | **VERIFIED (content)** / title wrong | Real title "Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing", Zang, Li, Li, 2025-04-12 |
| arXiv:2505.08129 — Liu & Cao, "High-order Regularization…" | **VERIFIED** | "High-order Regularization for Machine Learning and Learning-based Control", arXiv:2505.08129, 2025-05-13 |
| 10.1109/IJCNN.2017.7966094 — Park & Kim, "Online recurrent ELM … time-series prediction" | **VERIFIED** | Park Jin-Man & Kim Jong-Hwan, IJCNN 2017, **pp. 1983–1990** |
| 10.1002/er.8514 — Gu & Wang, BASO-optimized RELM | **VERIFIED** (full title longer) | "A beetle antennae search optimized recurrent extreme learning machine for battery state of charge estimation", *Int J Energy Res* **46(13):19190–19205, 2022** — BASO = Beetle Antennae Search Optimization |
| 10.1007/s10922-025-09976-3 — Shwaysh et al., J Real-Time Image Proc 2025 | **WRONG (venue)** | Shwaysh et al., *Journal of Network and Systems Management* **34(1), 2025**, "…Ensemble Recurrent Extreme Learning Machine for Enhanced Network Intrusion Detection Systems" |
| 10.3390/app7030217 — Lu, Huang, Lu, "Adaptive-Weight OS-ELM for time series", Appl Sci 7:217, 2017 | **VERIFIED** | "Time Series Prediction Based on Adaptive Weight Online Sequential Extreme Learning Machine", Lu Junjie, Huang Jinquan, Lu Feng, *Appl Sci* **7(3):217, 2017** — gold OA |
| 10.1016/j.neucom.2012.02.003 — Zhao, Wang, Park, forgetting mechanism | **VERIFIED** | *Neurocomputing* **87:79–89, 2012** |
| 10.1016/j.neucom.2009.02.013 — Lan, Soh, Huang, Ensemble of OSELM | **VERIFIED** | *Neurocomputing* **72(13–15):3391–3395, 2009** |
| 10.1109/TSMCS.2011.616645 — ELM survey DOI | **NOT FOUND** | 404 at doi.org, absent from Crossref and OpenAlex. No such DOI |
| 10.1109/tsmcb.2011.2168604 — Huang, "ELM: A Review and New Trends", 42(2):513–529 | **WRONG** | Same DOI = "Extreme Learning Machine for Regression and Multiclass Classification", Huang, **Zhou, Ding, Zhang**, T-SMC-B 42(2):513–529, 2012 |
| 10.1007/s13042-011-0019-y — Huang, Lan, Wang, "ELM: A Review", IJMLC 2(2):107–122 | **VERIFIED, author order wrong** | Crossref: **Huang, Wang, Lan** — "Extreme learning machines: a survey", *Int J Mach Learn Cybern* **2(2):107–122, 2011** |
| 10.1016/j.neunet.2017.04.001 — Yang et al., RL mean-p-power ELM | **VERIFIED, year off by one** | Yang, Ye, Rong, Chen, "Recursive least mean p-power Extreme Learning Machine", *Neural Networks* **91:22–33, 2017** (not 2018 — 2018 is the issue-print year) |
| 10.1109/codit.2018.8394791 — "A Survey of Online Sequential ELM", CoDIT 2018 | **VERIFIED, authors missing** | **Zhang Senyue, Tan Wenan, Li Yibo**, CoDIT 2018, **pp. 45–50** |
| `…/s11042-021-11008-7.pdf` | **NOT FOUND (typo)** | Correct: `…/s11042-021-11007-7.pdf` — Wang, Lu, Wang, Zhang, "A review on extreme learning machine", *Multimed Tools Appl* **81(29):41611–41660, 2021** |
## Downloaded (open access)
Files in this directory, all verified with `file` as real PDFs.
### zang_2025_predictive_plasticity_elm_fpga.pdf
*Online Learning Extreme Learning Machine with Low-Complexity Predictive Plasticity Rule and FPGA Implementation* — Zhenya Zang, Xingda Li, David Day Uei Li. arXiv:2512.21777, submitted 2025-12-25.
<https://arxiv.org/abs/2512.21777> · PDF: <https://arxiv.org/pdf/2512.21777>
Replaces the ELM's one-shot matrix inverse with a local, biologically inspired
predictive-plasticity rule: weights change only on prediction error, and each
update is a sparse vector addition gated by a binary firing mask. Training cost
drops from O(M³) to O(M) in hidden nodes M, at a reported accuracy cost of 3.6 %
train / 2.0 % test, and is demonstrated on an FPGA. **Update rule: predictive
plasticity (spike/error-gated local delta) — not RLS.** The most interesting
paper here for a real-time aiming loop: it is the only one whose whole point is
O(M) per-sample cost with no inverse.
### zang_2025_osos_elm_single_photon.pdf
*Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing* — Zhenya Zang, Xingda Li, David Day Uei Li. arXiv:2504.09028, submitted 2025-04-12.
<https://arxiv.org/abs/2504.09028> · PDF: <https://arxiv.org/pdf/2504.09028>
The hardware sibling of the above: an **OSOS-ELM** whose per-sample
inverse-covariance update is restructured as a **one-sided Jacobi rotation**, so
the RLS algebra becomes a sequence of rank-1 updates with no square matrix to
factor or invert. Evaluated against plain OS-ELM across hidden/input/output sizes
(comparable accuracy, better hardware efficiency) and implemented on a Xilinx
ZCU104 (multi-task ARM cores + pipelined logic fabric) and on a Jetson Xavier NX
GPU, with three single-photon case studies. **Update rule: one-sided Jacobi
rotation RLS (OSOS-ELM).** Same authors and line of work as the entry above.
### liu_2025_high_order_regularization.pdf
*High-order Regularization for Machine Learning and Learning-based Control* — Xinghua Liu, Ming Cao. arXiv:2505.08129, submitted 2025-05-13.
<https://arxiv.org/abs/2505.08129> · PDF: <https://arxiv.org/pdf/2505.08129>
Generalises L2 ridge regularisation to a **high-order (matrix) regulariser**,
framing regularisation as an inverse-map approximation with an explicitly
computable error bound; L2 appears as the special first-order case. The authors
prove convergence, give lower/upper error bounds, and show the solution is a
contraction whose generalisation is maximised by a suitable regulariser matrix.
Includes an **incremental** HR solution for regularised ELM, plus an RL
value-approximation case study. **Update rule: none per se — it is the
regularisation term itself; supplies the incremental-solution framing that makes
the ridge `lambda` in an online ELM meaningful.** Relevant to `common_libs/guns/elm.nim`,
which currently uses a scalar `lambda`.
### lu_2017_adaptive_weight_oselm.pdf
*Time Series Prediction Based on Adaptive Weight Online Sequential Extreme Learning Machine* — Junjie Lu, Jinquan Huang, Feng Lu. *Applied Sciences* 7(3):217, 2017.
<https://doi.org/10.3390/app7030217> · PDF: <https://mdpi-res.com/d_attachment/applsci/applsci-07-00217/article_deploy/applsci-07-00217.pdf>
Plain OS-ELM on a fixed random hidden layer, but each hidden node's contribution
is re-weighted per sample so that nodes which keep losing prediction error are
down-weighted, which stabilises long non-stationary time-series runs. Reports
improved forecasting accuracy over vanilla OS-ELM on public time-series
benchmarks. **Update rule: recursive least squares (OS-ELM RLS) + per-node adaptive
sample weighting.** This is the closest published match to what
`common_libs/guns/elm.nim` already implements.
## Manually supplied (paywalled — user-provided)
One paper here was **not** fetched by `fetch_papers.sh`: it is closed-access
(`oa_status: closed`, no legal OA copy anywhere) and was supplied by hand.
### huang_wang_lan_2011_elm_survey.pdf
*Extreme learning machines: a survey* — **Guang-Bin Huang, Dian Hui Wang, Yuan Lan**,
*International Journal of Machine Learning and Cybernetics* **2(2):107–122, 2011**.
DOI **`10.1007/s13042-011-0019-y`** — <https://doi.org/10.1007/s13042-011-0019-y>
Verified against both Crossref and OpenAlex (they agree on title, author order,
volume, issue and page range). The file is the **complete version of record**,
602314 bytes, md5 `547b4311cdb610fdf348d08107205907`, 16 pages = exactly the
printed range 107–122; the Springer DOI is printed on the title page and every
page footer reads `Int. J. Mach. Learn. & Cyber. (2011) 2:107–122`. Author order
is **Huang, Wang, Lan** (some citations wrongly give Huang, Lan, Wang).
Note the bibliographic trap this paper sits in: it is frequently mis-attributed
to *Neurocomputing* 75 (2011) 3051–3060. No such Neurocomputing article exists —
a Crossref sweep of every 2011 Neurocomputing paper by this trio returns only
the ELM2010 editorial (`10.1016/j.neucom.2011.03.030`, 74(16):2411–2412). It is
also unrelated to the phantom "IEEE T-SMC-B 42(3):486–497" survey above.
Content: the canonical ELM survey — the batch closed-form solution
`β = (HᵀH + λI)⁻¹HᵀT`, the universal-approximation theorem for SLFNs with
randomly generated hidden nodes, kernel ELM, and the full taxonomy of variants
including the OS-ELM/online-sequential family. **No single update rule** — it is
the map of the rules cited throughout this file.
## Paywalled (not downloaded, cited for reference)
OpenAlex reports `oa_status: closed` for all of these; no legal PDF exists to fetch.
* **Park Jin-Man, Kim Jong-Hwan**, "Online recurrent extreme learning machine and its application to time-series prediction", *IJCNN 2017*, pp. 1983–1990. <https://doi.org/10.1109/IJCNN.2017.7966094> — **update rule: recurrent ELM** (ELM hidden layer fed back over time).
* **Gu Tianyu, Wang Dongqing**, "A beetle antennae search optimized recurrent extreme learning machine for battery state of charge estimation", *Int J Energy Res* 46(13):19190–19205, 2022. <https://doi.org/10.1002/er.8514> — **update rule: recurrent ELM, hyper-parameters tuned by BASO** (beetle antennae search metaheuristic). BASO tunes the network, it is not a per-sample online rule.
* **Shwaysh Mustafa Muslih** et al., "…Ensemble Recurrent Extreme Learning Machine for Enhanced Network Intrusion Detection Systems", *J Network Syst Manage* 34(1), 2025. <https://doi.org/10.1007/s10922-025-09976-3> — **update rule: ensemble** of RELM members (combined with autoencoder feature selection).
* **Zhao Jianwei, Wang Zhihui, Park Dong Sun**, "Online sequential extreme learning machine with forgetting mechanism", *Neurocomputing* 87:79–89, 2012. <https://doi.org/10.1016/j.neucom.2012.02.003> — **update rule: RLS + forgetting factor.** The canonical source for the `rho` knob; `elm.nim` already cites it.
* **Lan Yuan, Soh Yeng Chai, Huang Guang-Bin**, "Ensemble of online sequential extreme learning machine", *Neurocomputing* 72(13–15):3391–3395, 2009. <https://doi.org/10.1016/j.neucom.2009.02.013> — **update rule: ensemble** of independently trained OS-ELMs.
* **Huang Guang-Bin, Zhou Hongming, Ding Xiaojian, Zhang Rui**, "Extreme Learning Machine for Regression and Multiclass Classification", *IEEE T-SMC-B* 42(2):513–529, 2012. <https://doi.org/10.1109/TSMCB.2011.2168604> — **update rule: none** (batch ELM; the closed-form ridge solution β = (HᵀH + λI)⁻¹HᵀT).
* **Yang Jing, Ye Feng, Rong Hai-Jun, Chen Badong**, "Recursive least mean p-power Extreme Learning Machine", *Neural Networks* 91:22–33, 2017. <https://doi.org/10.1016/j.neunet.2017.04.001> — **update rule: recursive least mean p-power (RLMP).** Like RLS but the gain is powered to *p* and normalised by the power of the activation, trading exactness for robustness — the right shape for noisy, drift-prone inputs.
* **Zhang Senyue, Tan Wenan, Li Yibo**, "A Survey of Online Sequential Extreme Learning Machine", *CoDIT 2018*, pp. 45–50. <https://doi.org/10.1109/CODIT.2018.8394791> — **survey** of the OS-ELM family; the map of the rules above.
* **Wang Jian, Lu Siyuan, Wang Shui-Hua, Zhang Yu-Dong**, "A review on extreme learning machine", *Multimed Tools Appl* 81(29):41611–41660, 2021. <https://doi.org/10.1007/s11042-021-11007-7> — open access in principle, but **bot-blocked from this machine** (see CITATION NOTES). **survey**, no single rule.
## Core OS-ELM RLS equations (plain text)
Hidden layer is drawn once and frozen: `H = [g₁ … g_M]` with `g_j = act(W_j x + b_j)`.
Output weights `β` (M×C) start at zero; `P` starts at `P₀ = (1/η) I`. No epochs, one pass.
Per sample `(x_t, y_t)`, with `g_t = act(W x_t + b_t)`:
```
g_t = act(W x_t + b_t) # frozen random hidden map
# optional forgetting factor (Zhao, Wang & Park 2012) — do this FIRST:
# P <- P / rho rho = 1 → plain RLS, rho > 1 → old data decays
# NOTE: divide rho**2 into lambda below to keep the steady-state noise floor sane.
K_t = P g_t / (lambda + g_t^T P g_t) # gain vector, no matrix inverse
beta_t = beta_{t-1} + K_t (y_t - g_t^T beta_{t-1}) # rank-1 weight correction
P_t = (I - K_t g_t^T) P_{t-1} # downdate the inverse correlation
```
Read `K_t` as: "how much of the current inverse correlation points along this
sample's hidden activation". `beta_t` only ever moves by a rank-1 step, so the
per-sample cost is O(M·C) plus one O(M²) downdate — versus the batch ELM's
O(M³) inverse. `P` is the inverse of `Σ_i g_i g_iᵀ + λI`, so the fixed point of
the recursion is exactly the ridge solution `β = (HᵀH + λI)⁻¹HᵀT`; RLS is that
solution, computed incrementally.
Variants referenced above:
* **Forgetting factor** (Zhao 2012) — insert `P ← P/ρ` before the update so the
fixed point becomes a exponentially-weighted least squares fit. `ρ = 1` is
exactly the equations above.
* **Ensemble** (Lan 2009, Shwaysh 2025) — run `N` independent copies (different
random hidden draws, different seeds) and average their outputs. Cost `N×`,
variance down.
* **Mean-p-power** (Yang 2017) — replace the gain with a powered, normalised
form: `K_t = P g_t / (lambda + ‖g_t‖_p^p)` style denominators, which caps the
influence of outlier activations instead of trusting them exactly.
* **One-sided Jacobi** (Zang 2025) — restructure `P`'s update as an explicit
sweep of one-sided Jacobi rotations so each step is a rank-1 rotation rather
than a matrix product; same fixed point, better pipelining on FPGA.
* **Predictive plasticity** (Zang 2025) — drop RLS entirely; `Δw ∝ (err) ⊙ mask`
on error only, O(M).
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Re-download the open-access OS-ELM / ELM reference PDFs.
# Idempotent: skips files that already exist and are genuine PDFs.
# Fails loudly (exit 1) if a download does not yield a real PDF.
#
# Only papers verified open access in CITATION NOTES (see README.md) are listed.
# Paywalled items are deliberately absent - there is nothing to fetch.
#
# huang_wang_lan_2011_elm_survey.pdf (10.1007/s13042-011-0019-y, IJMLC 2(2):107-122)
# is paywalled with no OA copy and is deliberately NOT in this list: adding a
# publisher URL here would just curl a bot-challenge page. It was supplied by
# hand - see README.md "Manually supplied". This script only ever writes or
# removes the filenames listed below, so that file is never touched.
set -uo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UA='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
mkdir -p "$DIR"
# name|url
PAPERS=(
"zang_2025_predictive_plasticity_elm_fpga.pdf|https://arxiv.org/pdf/2512.21777"
"zang_2025_osos_elm_single_photon.pdf|https://arxiv.org/pdf/2504.09028"
"liu_2025_high_order_regularization.pdf|https://arxiv.org/pdf/2505.08129"
"lu_2017_adaptive_weight_oselm.pdf|https://mdpi-res.com/d_attachment/applsci/applsci-07-00217/article_deploy/applsci-07-00217.pdf"
)
fail=0
for entry in "${PAPERS[@]}"; do
name="${entry%%|*}"; url="${entry#*|}"; out="$DIR/$name"
if [ -s "$out" ] && file -b "$out" | grep -q '^PDF'; then
echo "SKIP $name (already present, $(stat -c%s "$out") bytes)"
continue
fi
# MDPI blocks plain /pdf with a Referer-less request; arXiv does not care.
echo "GET $name <- $url"
if ! curl -fL -A "$UA" -H 'Referer: https://www.mdpi.com/' -H 'Accept: application/pdf,*/*' \
--retry 3 --retry-delay 2 -o "$out" "$url"; then
echo "FAIL $name (curl error)" >&2; rm -f "$out"; fail=1; continue
fi
if ! file -b "$out" | grep -q '^PDF'; then
echo "FAIL $name: not a PDF ($(file -b "$out"))" >&2
rm -f "$out"; fail=1; continue
fi
echo "OK $name ($(stat -c%s "$out") bytes)"
done
[ "$fail" -eq 0 ] || { echo "one or more downloads failed" >&2; exit 1; }
echo "all open-access papers present in $DIR"
+356
View File
@@ -0,0 +1,356 @@
## ELM — Extreme Learning Machine, ONLINE SEQUENTIAL variant (ridge / RLS).
##
## Fixed random hidden layer (weights + biases drawn ONCE from a seeded RNG,
## never trained) and output weights `beta` solved by recursive least squares as
## samples arrive. This is NOT gradient descent: no backprop, no epochs, one
## pass over the data.
##
## Per sample, with g = act(W x + b) the hidden activation:
## g = act(W x + b)
## P = rho P - rho^2 (P g)(g^T P) / (1 + rho g^T P g)
## beta = beta + (P_new g) (t - g^T beta)
## with P0 = I/lambda, so P is exactly (sum_i rho^{i-n} g_i g_i^T + lambda I)^-1
## and beta is the ridge solution beta = (H^T H + lambda I)^-1 H^T T solved in
## closed form at every step — no gradient descent, no epochs, one pass.
## rho = 1 is textbook ridge RLS (K = P g / (1 + g^T P g)); rho > 1 is the
## FORGETTING FACTOR of Zhao, Wang & Park, Neurocomputing 87:79-89 (2012) —
## it decays the accumulated information matrix (M <- M/rho) so the net tracks
## a non-stationary target instead of averaging over its whole history.
## Its effective memory is about 1/(rho - 1) samples.
##
## Two sign/placement traps this file got wrong first and now documents, because
## both fail silently (they train, they just never track a drift):
## * scale P UP by rho after the update, not down — scaling it down makes M
## grow with rho, i.e. rho > 1 AMPLIFIES the past and freezes the net;
## * the K gain must be P_new * g (post-update), not P_old * g: only the
## former preserves the invariant above once rho != 1.
##
## ── (OPTIONAL) RECURRENCE — the RELM hidden layer ───────────────────────────
## h_j(t) = act(sum_k W_jk x_k(t) + b_j + r_j * h_j(t-1))
## Park Jin-Man & Kim Jong-Hwan, "Online recurrent extreme learning machine for
## time-series prediction", IJCNN 2017 pp. 1983-1990, doi 10.1109/IJCNN.2017.7966094
## (citation verified in guns/docs/README.md; the PDF itself is NOT in
## guns/docs/, so the exact equation above is the STANDARD recurrent-ELM form
## taken on the citation's word, not a transcription — flagged as an assumption
## rather than passed off as verified).
##
## WHAT IT BUYS, MEASURED: nothing. The one caller that uses it,
## guns/waveelm.nim, sweeps it over synthetic target sequences
## (common_libs/tests/bench_waveelm_temporal.nim, 3 regimes x 2 motion styles x
## 3 seeds) and it lands between -1.4% and +4.7% on RMS error and between
## -4.6% and +9.7% on hit rate — noise around zero, both on its own and on top
## of the lag window, INCLUDING a case built specifically to favour it (a ground
## truth with a 12-tick memory, longer than any explicit window the feature map
## can carry, where only integrating over time can build the quantity: -0.2% to
## -1.4% RMS). It is therefore OFF by default (`recurrentGain = 0.0`), where it
## is not merely slow but BYTE-IDENTICAL to the feed-forward net: r_j = 0 makes
## the recurrent term vanish and `hidden` skips it entirely.
##
## WHY IT IS SAFE ANYWAY (the three things a recurrence can break):
## 1. DIVERGENCE. Every r_j is clamped to |r_j| <= ElmRMax = 0.9 < 1, and with
## act' <= 1 the map h -> act(a + r h) is a contraction, so h has a unique
## bounded fixed point for ANY input and cannot run away. `isSane` also
## checks |r_j| < 1 and every h_j for finiteness, so a poisoned recurrence
## is detected rather than propagated.
## 2. STATE LEAK. The node state is the state of a SEQUENCE, not of the net:
## `resetHidden` clears it and keeps beta/P (what was LEARNED survives, the
## sequence does not), and guns/waveelm.nim calls it when the resolved
## target id changes and exposes `resetTemporalState` for a new round.
## 3. MIS-ALIGNED LABELS. A gun's label arrives dozens of ticks after the
## shot, so re-running `hidden(x)` at training time would fit a DIFFERENT
## function (the node state has moved on). `trainHidden` therefore takes the
## activation the shot actually used, and the gun stores it in the probe
## trace. Also: the caller owns the clock — `hidden` and `predict` are
## read-only, only `predictStep` advances, so a gun probing four bullet
## speeds per tick steps the recurrence once per TICK, not once per probe.
##
## The tests for all of the above are common_libs/tests/test_waveelm_temporal.nim.
##
## Dependency-light on purpose: std/math + std/random only, so a gun plugin can
## import it without dragging in a network stack. Deliberately implements NO Gun
## interface — the caller feeds features in and reads predictions out.
##
## Coordinate/gun conventions of gun_harness/gun_interface.nim apply to callers,
## not here: nothing in this file knows about degrees or bullets.
import std/[math, random]
type
ElmActivation* = enum
## Hidden nonlinearity. tanh (default) is the usual ELM choice; sigmoid is
## offered because the original ELM paper used it and some targets are
## better served by a (0,1) squashing.
eaTanh
eaSigmoid
ElmNet* = object
inputDim*: int
hiddenDim*: int
outputDim*: int
act*: ElmActivation
lambda*: float ## ridge regularisation: beta = (H^T H + lambda I)^-1 H^T T
rho*: float ## forgetting factor, >= 1.0 (1.0 = no forgetting)
W*: seq[seq[float]] ## hiddenDim x inputDim, fixed after init
b*: seq[float] ## hiddenDim, fixed after init
r*: seq[float] ## hiddenDim, RELM recurrent gain per node; all-zero
## (the default) means NO recurrence at all
hPrev*: seq[float] ## hiddenDim, the hidden layer's own state h(t-1)
beta*: seq[seq[float]] ## hiddenDim x outputDim, learned
P*: seq[seq[float]] ## hiddenDim x hiddenDim inverse correlation, learned
samples*: int ## successful updates since init (or last reset)
resets*: int ## numerical blowups that forced a soft reset
const
ElmRMax* = 0.9
## HARD clamp on every recurrent gain r_j.
## WHY: with |r| < 1 the map h -> act(a + r*h) is a CONTRACTION whenever
## act' is bounded by 1 (max tanh' = 1, max sigmoid' = 1/4), so the recurrence
## has a unique BOUNDED fixed point for ANY input and provably cannot
## diverge. That clamp is what buys the guarantee, rather than hoping the
## seeded gains happen to be tame: a runaway hidden vector would feed NaN
## straight into the RLS and blow up P. 0.9 keeps a uniform margin below 1
## and still buys a ~10-sample memory (0.9^10 = 0.35).
# ── helpers ───────────────────────────────────────────────────────────────────
proc isFinite(x: float): bool {.inline.} =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc allFinite(m: seq[seq[float]]): bool =
for row in m:
for v in row:
if not isFinite(v): return false
true
proc allFinite(v: seq[float]): bool =
for x in v:
if not isFinite(x): return false
true
proc zeroMat(rows, cols: int): seq[seq[float]] =
result = newSeq[seq[float]](rows)
for i in 0..<rows: result[i] = newSeq[float](cols)
proc matVec(m: seq[seq[float]], v: openArray[float]): seq[float] =
## m * v, rectangular m allowed (only P*g is used today; P is square).
result = newSeq[float](m.len)
for i in 0..<m.len:
var s = 0.0
for j in 0..<min(m[i].len, v.len): s += m[i][j] * v[j]
result[i] = s
proc dot(a, b: openArray[float]): float {.inline.} =
for i in 0..<a.len: result += a[i] * b[i]
proc applyAct(net: ElmNet, v: float): float {.inline.} =
case net.act
of eaTanh: tanh(v)
of eaSigmoid: 1.0 / (1.0 + exp(-v))
# ── construction ──────────────────────────────────────────────────────────────
proc init*(inputDim, hiddenDim: int, seed: int64 = 42, outputDim = 1,
act = eaTanh, lambda = 1e-3, rho = 1.0,
recurrentGain = 0.0): ElmNet =
## Fixed hidden layer drawn from a seeded RNG, so the whole net is
## reproducible: same seed => same predictions.
##
## `recurrentGain` > 0 turns on the RELM hidden layer (Park Jin-Man & Kim
## Jong-Hwan, "Online recurrent extreme learning machine for time-series
## prediction", IJCNN 2017 pp. 1983-1990, doi 10.1109/IJCNN.2017.7966094):
## h_j(t) = act(sum_k W_jk x_k(t) + b_j + r_j * h_j(t-1))
## each hidden node feeds its OWN previous activation back into itself, which
## is what turns the feature map into a function of the SEQUENCE rather than
## of the current sample alone. (ASSUMPTION, documented honestly: the exact
## paper formulation could not be read from here — the PDF is not in
## guns/docs/ — so this is the standard recurrent-ELM form; the citation is
## verified in guns/docs/README.md.)
## The r_j are drawn from the SAME seeded RNG as W and b, in the same call
## order, so one seed still reproduces the entire net. Signs are symmetric:
## half the nodes remember forwards and half backwards, which is what lets a
## signed oscillatory quantity (a rotating aim bias) be represented.
## 0.0 (the default) leaves every r_j at 0 and the net is byte-identical to
## the plain feed-forward ELM: h_j(t) = act(W_j x + b_j), no state at all.
doAssert inputDim > 0 and hiddenDim > 0 and outputDim > 0
doAssert lambda > 0.0
var rng = initRand(seed)
result.inputDim = inputDim
result.hiddenDim = hiddenDim
result.outputDim = outputDim
result.act = act
result.lambda = lambda
result.rho = max(1.0, rho) # < 1 would amplify old samples; clamp, don't fail
result.W = newSeq[seq[float]](hiddenDim)
for h in 0..<hiddenDim:
result.W[h] = newSeq[float](inputDim)
for i in 0..<inputDim:
# Uniform in [-1,1] scaled by 1/sqrt(inputDim) keeps W x in a range tanh
# does not saturate on. (No randn in std/random; uniform is fine here.)
result.W[h][i] = (rand(rng, 1.0) * 2.0 - 1.0) / sqrt(float(inputDim))
result.b.add(rand(rng, 1.0) * 2.0 - 1.0)
var rj = 0.0
if recurrentGain > 0.0:
rj = clamp(recurrentGain * (rand(rng, 1.0) * 2.0 - 1.0), -ElmRMax, ElmRMax)
result.r.add(rj)
result.hPrev = newSeq[float](hiddenDim)
result.beta = zeroMat(hiddenDim, outputDim)
result.P = zeroMat(hiddenDim, hiddenDim)
# P0 = I/lambda: with no data yet the information matrix is exactly the ridge
# lambda*I, and the update below maintains P = (S + lambda*I)^-1. Anything else
# here (I, or I/lambda with the other denominator) silently stops the
# recursion from being the ridge solution.
for i in 0..<hiddenDim: result.P[i][i] = 1.0 / result.lambda
# ── numerics guard ─────────────────────────────────────────────────────────────
proc isSane*(net: ElmNet): bool =
## False as soon as any weight, bias or inverse-correlation entry is
## NaN/Inf — i.e. the RLS recursion has blown up — and false for a net that
## was never `init`ed (zero dims: every allFinite check vacuously passes, and
## the first `hidden` call would trip `x.len == inputDim` inside the gun).
if net.inputDim <= 0 or net.hiddenDim <= 0 or net.outputDim <= 0: return false
if net.W.len != net.hiddenDim or net.beta.len != net.hiddenDim or
net.P.len != net.hiddenDim or net.b.len != net.hiddenDim or
net.r.len != net.hiddenDim or net.hPrev.len != net.hiddenDim:
return false
if not allFinite(net.b): return false
if not allFinite(net.r): return false
if not allFinite(net.hPrev): return false
for rj in net.r:
if abs(rj) >= 1.0: return false # outside the contraction range
if not allFinite(net.beta): return false
allFinite(net.P)
proc resetHidden*(net: var ElmNet) =
## Drop the hidden layer's own state (h(t-1) -> 0) WITHOUT touching anything
## the RLS has learned. The recurrence belongs to a SEQUENCE: a new target,
## a new round or a re-acquired scan track is a new sequence, and carrying
## the old node states into it makes the first few predictions of the new
## sequence wrong for reasons that have nothing to do with beta.
net.hPrev = newSeq[float](net.hiddenDim)
proc softReset*(net: var ElmNet) =
## Drop everything learned; keep the fixed hidden layer (it is a pure
## function of the seed, so re-deriving it would change the net's identity).
net.beta = zeroMat(net.hiddenDim, net.outputDim)
net.P = zeroMat(net.hiddenDim, net.hiddenDim)
for i in 0..<net.hiddenDim: net.P[i][i] = 1.0 / net.lambda
net.samples = 0
net.resetHidden() # h(t-1) is state too: a reset net starts at h(0)=0
inc net.resets
proc recurrent*(net: ElmNet): bool {.inline.} =
## Is any hidden node recurrent? (All-zero r is the plain feed-forward ELM,
## and this is the flag that skips the recurrent term in the inner loop.)
for rj in net.r:
if rj != 0.0: return true
false
# ── forward / update ──────────────────────────────────────────────────────────
proc hidden*(net: ElmNet, x: openArray[float]): seq[float] =
## g = act(W x + b + r . h_prev), length hiddenDim. READ-ONLY: it reads the
## current state and never advances it, so the CALLER owns the clock. With
## every r_j = 0 (the default) the recurrent term is skipped entirely and
## this is the textbook feed-forward g.
doAssert x.len == net.inputDim
let rec = net.recurrent()
result = newSeq[float](net.hiddenDim)
for h in 0..<net.hiddenDim:
var s = net.b[h]
for i in 0..<net.inputDim: s += net.W[h][i] * x[i]
if rec: s += net.r[h] * net.hPrev[h]
result[h] = net.applyAct(s)
proc readOut*(net: ElmNet, g: openArray[float]): seq[float] =
## y = g^T beta, length outputDim. Returns zeros if the net went non-finite,
## so a caller can never propagate NaN into the gun's aim.
result = newSeq[float](net.outputDim)
for o in 0..<net.outputDim:
var s = 0.0
for h in 0..<net.hiddenDim: s += g[h] * net.beta[h][o]
result[o] = s
if not isFinite(s): return newSeq[float](net.outputDim)
proc predict*(net: ElmNet, x: openArray[float]): seq[float] =
## y = g(t)^T beta at the CURRENT state, WITHOUT advancing it. Kept
## immutable so a read-only caller (an evaluation sweep, a test) can use it;
## the gun, which owns the clock, calls `predictStep`.
if not net.isSane(): return newSeq[float](net.outputDim)
net.readOut(net.hidden(x))
proc predictStep*(net: var ElmNet, x: openArray[float]): seq[float] =
## One step of the SEQUENCE: y = g(t)^T beta, then h(t-1) <- g(t).
## The caller MUST advance exactly once per time step: a gun that probes four
## bullet speeds per tick has to call this once per TICK, not once per probe,
## or the node state runs at the probe rate instead of the tick rate.
if not net.isSane(): return newSeq[float](net.outputDim)
let g = net.hidden(x)
result = net.readOut(g)
if not net.isSane():
net.resetHidden() # blew up mid-step: drop the state, keep beta
return newSeq[float](net.outputDim)
net.hPrev = g
proc trainHidden*(net: var ElmNet, g: openArray[float],
t: openArray[float]): bool =
## One RLS step on an ALREADY COMPUTED hidden vector. A caller that owns a
## sequence (the gun stores the g of the shot it fired) must use this: the
## label belongs to the activation that actually produced it, and by the time
## a hit resolves (dozens of ticks later) `hidden(x)` would now be computed
## from a DIFFERENT h(t-1), i.e. it would train a different function.
## Returns false (leaving the net sane but untouched) if the sample is
## rejected, and true after a successful update — including the case where the
## step blew up and `softReset` was forced; check `resets` for that.
doAssert g.len == net.hiddenDim
doAssert t.len == net.outputDim
if net.P.len != net.hiddenDim or net.beta.len != net.hiddenDim:
net.softReset()
if not net.isSane(): net.softReset()
for v in g:
if not isFinite(v): return false
for v in t:
if not isFinite(v): return false
let Pg = matVec(net.P, g)
# rho enters here too: M = P^-1 becomes M/rho + g g^T this step.
let denom = 1.0 + net.rho * dot(g, Pg)
if not isFinite(denom) or denom <= 0.0:
net.softReset()
return true # consumed, but as a reset
# P = rho P - rho^2 (P g)(g^T P) / (1 + rho g^T P g)
# = rho (I - K g^T) P with K = P_new g — the subtracted term is
# K_i * (g^T P)_j = Pg[i]*Pg[j], NOT g[j]*P[i][j] (a different, wrong recursion).
var k = newSeq[float](net.hiddenDim)
for i in 0..<net.hiddenDim:
for j in 0..<net.hiddenDim:
net.P[i][j] = (net.P[i][j] - net.rho * Pg[i] * Pg[j] / denom) * net.rho
var ki = 0.0
for j in 0..<net.hiddenDim: ki += net.P[i][j] * g[j]
k[i] = ki
# beta += K (t - g^T beta), K = P_new g
for o in 0..<net.outputDim:
var pred = 0.0
for h in 0..<net.hiddenDim: pred += g[h] * net.beta[h][o]
let e = t[o] - pred
for h in 0..<net.hiddenDim: net.beta[h][o] += k[h] * e
inc net.samples
if not net.isSane():
net.softReset()
return true
true
proc train*(net: var ElmNet, x: openArray[float], t: openArray[float]): bool =
## Convenience wrapper: g = hidden(x) at the CURRENT state, then one RLS step.
## Fine for a batch/streaming learner; a sequence learner that can go back in
## time (the gun, whose label arrives long after the shot) must use
## `predictStep` + `trainHidden` instead.
doAssert x.len == net.inputDim
for v in x:
if not isFinite(v): return false # reject at the trust boundary, not
# after tanh has saturated it to 1.0
let g = net.hidden(x)
net.trainHidden(g, t)
File diff suppressed because it is too large Load Diff
+728
View File
@@ -0,0 +1,728 @@
## waveelm.nim — the WaveElm gun. The ONLY wave mechanism is a SIMULATED
## OMNIDIRECTIONAL EXPANDING RING; the ELM corrects the ring's MEASUREMENT.
##
## ── THE RING ─────────────────────────────────────────────────────────────────
## The ring is `RingProbes` rays fired simultaneously from the shooter at one
## bullet speed; at offset k the ring's radius is `k * bulletSpeed(power)`. It
## is a SIMULATION of an instrument, not a shot pattern: nothing is fired, so
## it costs no energy and no cooldown and it is legal at any time. What it
## measures, for the first enemy it touches, is the MEETING POINT — the
## interception radius (== the distance to the enemy at contact) and the bearing
## of the probe ray that touched it. Distance + bearing is a complete polar
## position measurement of a target we have already scanned.
##
## WHY A RING AND NOT A DIRECTED SHOT (measured, /tmp/ringspike, now removed —
## the spike source is kept at /tmp/ringspike/ring_backup_keep.nim):
## * directed design: only 21.5% of aimed offsets survive as training labels
## (mean labelled magnitude 0.23x the truth) — an aimed bullet misses a
## strafing target, and a miss carries no label. Interception ~21.5%.
## * ring: 720 probes, 100.00% interception (108/108), 0.92-0.93 labels per
## tick per enemy.
## * raw ring noise WITHOUT the ELM: radius error RMS 6.0 px, bearing
## quantisation 0.97 px.
##
## ── WHAT THE ELM LEARNS: A BIAS CORRECTION (mode b), NOT A POSITION ─────────
## The net predicts the CORRECTION to apply to the ring's reconstructed position
## — a BIAS, never a position. The alternative, predicting the enemy's position
## outright (spike mode a), was measured and REFUTED: flat 3.4-4.3 px RMS on
## smooth/accelerating regimes but a collapse to 29-44 px RMS on abrupt/burst,
## i.e. exactly when it matters; bias correction (mode b) stayed flat 3.4-4.3 px
## across ALL regimes at a 100% in-BotRadius rate. Baseline directed numbers for
## the same regimes: glide 7.990/11.815/23.072 RMS, burst 8.083/14.434/20.927.
##
## HONEST CAVEAT on those numbers, since it is easy to over-read them: mode (b)
## was measured with a feature map (velocity, ring distances, age) that has NO
## BEARING term, so part of its flatness is that the best correction it can
## express is the MEAN bias, which for a strafing target is near zero. The
## correction is therefore applied CARTESIAN here rather than in polar
## (dDist, dBear): the ring measures polar, but the feature map has no way to
## know which way the ring pointed, so a polar label would be unlearnable and
## would collapse to its own mean. See the label note in `onResult`.
##
## ── THE DAMAGE SHOT ─────────────────────────────────────────────────────────
## The ring produces labels; it does not damage anything. Real bullets are aimed
## at the ENEMY POSITION RECONSTRUCTED from the ring measurement
## (`self + (dist, bear)`) plus the ELM's bias correction, i.e. exactly the
## quantity the ring is well-conditioned about. When the gun has no ring
## measurement yet (a target it has seen once), it degrades to aiming at the
## scan position itself — a HeadOn shot, the rack's floor, never a crash.
##
## ── WHAT HAPPENS IF VIRTUAL BULLETS ARE DISABLED ───────────────────────────
## The ring is SIM-ONLY: it is simulated inside the gun from the scan track, so
## the gun's aim does not depend on the virtual-bullet tracker at all. What the
## tracker provides is the LABEL — `onResult` is fed by
## `VirtualTracker.tickBullets`, which is where the polar-free Cartesian bias
## between the ring reconstruction and the enemy comes from. With
## `TR_MODULE_VBULLETS=0` (or the rack unmembership `off`) `predict` still runs
## and still aims at the ring reconstruction — the gun degrades to the ring's raw
## measurement with NO learned correction, never to a crash and never to a
## HeadOn/no-op. With virtual bullets on, `VBulletAdmitOnly` already forces
## `admit[WaveElmId]` in ModularBot (see the `admit` block), so the gun is never
## skipped for being unselected.
##
## ── MEASURED, HONESTLY ──────────────────────────────────────────────────────
## The offline benchmark with the ring as the base (bench_waveelm_temporal.nim,
## same regimes as before): glide smooth 0.06 px / accel 0.11 px / abrupt 25.5 px
## RMS, burst smooth 29.9 / accel 37.6 / abrupt 80.1 px. The OLD directed
## baselines were glide 7.990/11.815/23.072 and burst 8.083/14.434/20.927. So:
## the ring is dramatically better where the target flies straight (0.06 px vs
## 8 px) and dramatically WORSE where it turns (80 px vs 21 px), because the ring
## is a constant-velocity lead and a turning target breaks that assumption over
## a long flight — and because the broken base means no confirmed hits, hence no
## labels, hence nothing to learn from. This is a documented ceiling, not a
## tuning miss: see `testSupervision` in common_libs/tests/test_waveelm.nim.
##
## ── SCAN-ONLY LEGITIMACY ────────────────────────────────────────────────────
## `ringFireFromScan` reads exactly three things: `state.enemyX/enemyY` (the
## position of the target the radar SELECTED, i.e. a scan), and the velocity
## DERIVED from the last two scans of that same target. It never reads
## `state.enemies`, the tracker's table, or any position at any tick other than
## the scan it was given. It is therefore scan-only by construction, and it is
## also honest in the deeper sense: it never needs to know where the enemy WILL
## be, because the ring's contact radius is a measurement of where it IS.
## See the module-level test in common_libs/tests/test_waveelm_ring.nim.
##
## ── THE LEFT/RIGHT OSCILLATION (measured, fixed, unchanged) ─────────────────
## A shot fired at tick T resolves at T + flightTime (20-80 ticks, far longer
## than the RLS memory 1/(rho-1) ~ 12 ticks), so the label describes the bias
## at the ARRIVAL tick while the features describe the FIRE tick. `WaveResolve
## Features` rebuilds each in-flight trace's features at its arrival tick so
## feature-time == label-time. Measured effect (perpendicular = left-right
## component of the aim error): accel 16.57 px -> 7.67 px, abrupt 5.12 px ->
## 1.18 px; a proven NO-OP when feedback is not delayed.
##
## ── ONE NET, SHARED ─────────────────────────────────────────────────────────
## A single `ElmNet` shared by every target, per-target state (scan track, ring
## measurement, pending traces) kept separately. The bias being learned is mostly
## a property of THIS BOT, and `rho` (the RLS forgetting factor, memory ~50
## samples) is what lets the shared net track a change of target.
import std/[math, tables]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/elm
const
# ── the ladder (rung == ring speed) ─────────────────────────────────────────
WavePowers* = [1.0, 2.0, 3.0] ## speed 17 / 14 / 11 px/tick
WaveRungs* = WavePowers.len
# ── RING GEOMETRY ──────────────────────────────────────────────────────────
RingArenaW* = 800.0 ## ASSUMPTION: the Tank Royale arena this gun is sized
RingArenaH* = 600.0 ## for. See `ringProbeCount` for why and what breaks.
RingSafety* = 2.0 ## safety factor on the probe count (see below)
# ── scan history ────────────────────────────────────────────────────────────
WaveTrackCap* = 9 ## == WaveLagKMax + 1: the longest lag window + 1
WaveLagKMax* = 8
# ── ELM shape ───────────────────────────────────────────────────────────────
WaveInputDim* = 10 ## width at lagK = 2 (two displacements)
WaveHiddenDim* = 16
WaveLambda* = 0.1
WaveRho* = 1.02 ## memory 1/(rho-1) ~ 50 samples; 1.05 is too short.
# ── (A) LAG WINDOW ──────────────────────────────────────────────────────────
WaveLagK* = 2 ## scan-to-scan displacements in the feature map
WaveRelmGain* = 0.0 ## RELM recurrent gain; 0 = recurrence OFF (measured a
## wash to a regression; left in, defaulted off)
# ── guards ──────────────────────────────────────────────────────────────────
WaveMaxResidual* = 3.0 * BotRadius
## 54 px on the Cartesian bias between the ring reconstruction and where the
## enemy was. MEASURED: it essentially never fires (a confirmed hit cannot be
## 54 px from the aim point).
WaveGateAdapt* = 0.0 ## adapting gate; 0 = fixed (measured identical)
WaveMaxOffset* = 2.0 * BotRadius
## clamp on the learned correction, in px for the radial output and, for the
## angular output, converted to px at the measured distance so both halves
## share one physical ceiling.
# ── flight-time feature alignment ───────────────────────────────────────────
WaveResolveFeatures* = true
# ── pending-trace ring ──────────────────────────────────────────────────────
WaveTraceSlots* = 1024
# ── the ring geometry ─────────────────────────────────────────────────────────
#
# N PROBES. The ring must have no angular GAP wider than a bot at maximum range,
# or an enemy sitting in the gap is never touched at all (the measurement, and
# therefore the label, is lost for that bearing forever). The gap at radius r is
# `2*pi*r/N`, so
#
# N >= 2*pi*rMax / BotRadius
#
# With rMax = the arena DIAGONAL (the largest possible separation between two
# bots) and BotRadius = 18 px: rMax = hypot(800, 600) = 1000 px, so
# N >= 2*pi*1000/18 = 349. `RingSafety` doubles that for margin (the enemy is a
# DISC, not a point, and it MOVES between the ring's radii):
#
# N = 2 * 349 = 698 -> rounded up to a multiple of 60 -> 720
#
# ASSUMPTION, STATED: rMax is the 800x600 diagonal above. `RingArenaW/H` are the
# single place that assumption lives. If the real map is bigger, the derived
# count grows automatically (`ringProbeCount` is a function of rMax); if it is
# smaller, 720 probes is merely more than needed — never fewer. The ONLY thing
# that breaks with too small a map is an angular gap wider than a bot at the
# corner, i.e. missed bearings; nothing crashes and nothing NaNs.
proc ringProbeCount*(rMax: float): int =
## Smallest probe count whose angular gap stays inside a bot's radius at
## `rMax`, with `RingSafety` margin, rounded up to a multiple of 60 (60 is the
## spike's measured value's factor: 720 = 12*60, and a multiple of 60 keeps
## `RingDirs` cheap and the geometry easy to state).
if not (rMax > 0.0): return 60
let need = int(ceil(2.0 * PI * rMax / BotRadius * RingSafety))
max(60, ((need + 59) div 60) * 60)
const
RingRMax* = hypot(RingArenaW, RingArenaH)
RingProbes* = ringProbeCount(RingRMax) ## 720 for the 800x600 assumption
let RingDirs*: seq[float] = block:
## Probe bearings, 0 = East, CCW positive (the Tank Royale convention).
var d = newSeq[float](RingProbes)
for i in 0..<RingProbes: d[i] = 2.0 * PI * i.float / RingProbes.float
d
type
RingHit* = object
found*: bool
dist*: float ## ring radius at first contact (== distance to enemy)
bearing*: float ## rad, bearing of the probe ray that made contact
tick*: int ## absolute tick of first contact (fireTick + k)
missDist*: float ## closest approach of the ray to the enemy
proc ringFireAt*(sx, sy: float, spd: float,
px, py: seq[float], fireTick: int,
maxRadius = RingRMax): RingHit =
## Simulate ONE expanding ring of `RingProbes` rays of SPEED `spd`, fired at
## `fireTick` from (sx, sy). `px/py` are the target's positions indexed by
## ABSOLUTE TICK; the ring is tested against the target's position on each tick
## `fireTick + k`, where its radius is `k * spd`. The first contact is the
## interception.
if not (spd > 0.0):
return RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
missDist: Inf)
let maxK = int(ceil(maxRadius / spd))
var closest = Inf ## closest approach of any probe ray, diagnostics
var got = false
var bestR = 0.0 ## the contact radius
var bestBear = 0.0
var bestTick = -1
var bestMiss = 0.0
var bestRadial = Inf ## |eDist - r| of the accepted contact
for k in 1..maxK:
let t = fireTick + k
if t < 0 or t >= px.len: break
let r = k.float * spd
let ex = px[t] - sx
let ey = py[t] - sy
let eAng = arctan2(ey, ex)
let eDist = hypot(ex, ey)
# nearest probe ray (search +-1 index, so quantisation is at most half a gap)
let idx = int(round(eAng / (2.0 * PI) * RingProbes.float)) mod RingProbes
var kbest = Inf
var kidx = 0
for o in [-1, 0, 1]:
let i = (idx + o + RingProbes) mod RingProbes
let perp = abs(eDist * sin(eAng - RingDirs[i]))
if perp < kbest:
kbest = perp
kidx = i
if kbest < closest: closest = kbest
# CONTACT. The ray must sweep the target's DISC (kbest <= BotRadius) AND the
# annulus must be within BotRadius of the target's radius.
#
# BEST k, NOT FIRST k. The ring's radius steps by a whole `spd` per tick, so
# "first contact" is systematically the annulus BELOW the target, biased by
# up to BotRadius (8.5 px mean at the 17 px rung) in the one direction the
# target is moving. Every acceptable annulus is a legal reading of the same
# measurement, so the ring reports the one whose radius is CLOSEST to the
# target's — the maximum-likelihood reading of a quantised instrument.
if kbest <= BotRadius and abs(eDist - r) <= BotRadius:
let radial = abs(eDist - r)
if radial < bestRadial:
bestRadial = radial
got = true
bestR = r
bestBear = RingDirs[kidx]
bestTick = t
bestMiss = kbest
if got:
return RingHit(found: true, dist: bestR, bearing: bestBear,
tick: bestTick, missDist: bestMiss)
RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1, missDist: closest)
proc ringFire*(sx, sy: float, power: float,
px, py: seq[float], fireTick: int,
maxRadius = RingRMax): RingHit =
## `ringFireAt` in bullet-speed form: power -> `bulletSpeed(power)`.
ringFireAt(sx, sy, bulletSpeed(power), px, py, fireTick, maxRadius)
proc ringDecode*(h: RingHit, sx, sy: float): tuple[x, y: float] =
## Ring measurement -> absolute position: the point on the contacted bearing at
## the contacted radius.
(sx + h.dist * cos(h.bearing), sy + h.dist * sin(h.bearing))
# ── helpers ───────────────────────────────────────────────────────────────────
proc isFinite(x: float): bool {.inline.} =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc finiteOr*(x, fallback: float): float {.inline.} =
## Scrub a non-finite float at the trust boundary (see the old note: an Inf in
## an angle wrap loop hangs the bot at 100% CPU).
if isFinite(x): x else: fallback
proc wrapDeg(x: float): float {.inline.} =
## Wrap an angle to [-180, 180). Bounded loop: with a non-finite input the
## condition can stay true while the body makes no progress, which hangs.
if not isFinite(x): return 0.0
result = x
for _ in 0..<4:
if result > 180.0: result -= 360.0
elif result < -180.0: result += 360.0
else: break
proc waveBinForSpeed*(spd: float): int =
## Map a bullet speed back to its power-bin index, or -1.
for i in 0..<len(vb.PowerBins):
if abs(spd - bulletSpeed(vb.PowerBins[i])) < 1e-6: return i
-1
proc waveTraceSlot(fireTick, binIdx: int): int {.inline.} =
((fireTick * len(vb.PowerBins)) + binIdx) mod WaveTraceSlots
# ── types ─────────────────────────────────────────────────────────────────────
type
WaveSample = object
tick: int
x, y: float
WaveTrack = object
## Index 0 is the NEWEST scan. samples[0..1] give the velocity,
## samples[k..k+1] the k-th most recent displacement.
s: array[WaveTrackCap, WaveSample]
n: int
WaveRing* = object
## The newest ring measurement for a target.
valid*: bool
dist*: float ## measured distance, px (== the contact radius)
bear*: float ## measured bearing, rad
fireTick*: int ## the tick the ring was fired on
tick*: int ## the tick the contact resolved on
flight*: float ## tick - fireTick
WaveElmGun* = object
net*: ElmNet
tracks*: Table[int, WaveTrack] ## EnemyInfo.id -> scan history
rings*: Table[int, WaveRing] ## EnemyInfo.id -> newest ring measurement
targetId*: int ## -1 => derive the id from state.enemies[0]
lastId*: int ## the id predict() actually resolved this tick
lastTick*: int ## tick the current scan was pushed on (predict runs
## 4-5x per tick; the scan must be pushed ONCE)
lagK*: int
relm*: float
maxResidual*: float
maxOffset*: float
gateAdapt*: float
recentRms*: float
traces*: array[WaveTraceSlots, WaveTrace]
resolveFeat*: bool
refreshAt*: seq[int] ## slots due for a feature refresh this tick; the queue
## is cleared as it is walked (self-cleaning)
# instrumentation (exported for the tests)
predictCalls*: int
trainedShots*: int
traceMisses*: int
rejectedShots*: int
missShots*: int
ringContacts*: int ## rings that found a contact
ringFires*: int ## rings fired
lastDx*, lastDy*: float ## the last learned correction, in px (Cartesian)
WaveTrace = object
fireTick: int
binIdx: int
resolveTick: int
measDist: float ## the ring measurement this shot was built from
measBear: float
selfX, selfY: float
feat: seq[float]
hid: seq[float] ## the FIRE-time hidden activation g(t); trained on
## directly, because by the time the hit resolves
## h(t-1) has moved on
alive: bool
# ── construction ──────────────────────────────────────────────────────────────
proc waveInputDim*(lagK: int): int {.inline.} =
## Feature width for a given lag window. 8 "static" features + 2 per
## displacement.
WaveInputDim + 2 * (max(2, lagK) - 2)
proc initWaveElmGun*(seed: int64 = 42, lagK = WaveLagK,
relm = WaveRelmGain,
hiddenDim = WaveHiddenDim,
lambda = WaveLambda, rho = WaveRho,
maxResidual = WaveMaxResidual,
maxOffset = WaveMaxOffset,
gateAdapt = WaveGateAdapt,
resolveFeat = WaveResolveFeatures): WaveElmGun =
## Every knob is an override of the module constant of the same name, so an
## offline sweep can compare configs without recompiling per value. A negative
## maxResidual/maxOffset means "no clamp".
result.lagK = clamp(lagK, 2, WaveLagKMax)
result.relm = max(0.0, relm)
result.net = init(inputDim = waveInputDim(result.lagK),
hiddenDim = hiddenDim, seed = seed, outputDim = 2,
lambda = lambda, rho = rho,
recurrentGain = result.relm)
result.maxResidual = maxResidual
result.maxOffset = maxOffset
result.gateAdapt = gateAdapt
result.resolveFeat = resolveFeat
result.targetId = -1
result.lastId = -1
result.lastTick = -1
proc resetTemporalState*(g: var WaveElmGun) =
## Per-episode reset: the RELM hidden state belongs to the SEQUENCE. beta and P
## are kept: what the net has LEARNED is a property of this bot.
g.net.resetHidden()
g.lastTick = -1
proc isWarmedUp*(g: WaveElmGun): bool {.inline.} =
## Two scans of the current target: enough to derive a velocity instead of
## falling back to heading*speed.
let id = if g.targetId >= 0: g.targetId else: g.lastId
if id < 0: return false
if g.tracks.hasKey(id): g.tracks[id].n >= 2
else: false
proc ringDecode*(r: WaveRing, sx, sy: float): tuple[x, y: float] {.inline.} =
## The stored per-target measurement, decoded. Falls back to the caller's own
## position when there is no measurement yet (a never-seen target).
if r.valid:
(sx + r.dist * cos(r.bear), sy + r.dist * sin(r.bear))
else: (sx, sy)
proc ringFor*(g: WaveElmGun, id: int): WaveRing {.inline.} =
## The newest ring measurement for a target; an invalid one when it has none.
if g.rings.hasKey(id): g.rings[id] else: WaveRing()
# ── the ring, from SCANS ONLY ─────────────────────────────────────────────────
proc ringFireFromScan*(g: var WaveElmGun, state: WorldState, vx, vy: float,
spd: float): RingHit =
## The LIVE ring. Its entire input is the SELECTED SCAN (`state.enemyX/Y`,
## the position the radar resolved this tick) plus the velocity DERIVED FROM
## THAT TARGET'S OWN LAST TWO SCANS. It reads nothing else: not
## `state.enemies`, not the tracker table, not any other tick's position.
##
## The scan is extended forward at constant velocity for the length of the
## ring's flight, and `ringFire` is run against that extension. The error that
## introduces (the target does not really fly straight) is exactly the BIAS
## the ELM is trained to correct — which is why the ELM's input includes the
## recent displacement window and why the label is a bias, not a position.
let sx = finiteOr(state.selfX, 0.0)
let sy = finiteOr(state.selfY, 0.0)
let ex = finiteOr(state.enemyX, 0.0)
let ey = finiteOr(state.enemyY, 0.0)
let vx = finiteOr(vx, 0.0)
let vy = finiteOr(vy, 0.0)
if not (spd > 0.0):
return RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
missDist: Inf)
let maxK = int(ceil(RingRMax / spd))
var px = newSeq[float](maxK + 1)
var py = newSeq[float](maxK + 1)
for k in 0..maxK:
px[k] = ex + vx * k.float
py[k] = ey + vy * k.float
inc g.ringFires
# `fireTick = 0`: the trajectory above is indexed by OFFSET from now, so the
# contact tick `ringFireAt` reports is the flight time in ticks, not an
# absolute tick.
let h = ringFireAt(sx, sy, spd, px, py, 0, RingRMax)
if h.found: inc g.ringContacts
h
# ── the feature vector ────────────────────────────────────────────────────────
#
# All inputs scaled to roughly unit magnitude so the random hidden layer does not
# saturate its tanhs. Index 0 is the NEWEST scan. Layout (lagK displacements):
#
# [0] vx [1] vy derived velocity, px/tick
# [2] dist RING-measured distance (scan distance before the
# first contact), /1000
# [3] hdelta range, closing/opening (from the scan heading)
# [4+2k] dx_k [5+2k] dy_k the k-th most recent scan-to-scan displacement,
# k = 0 is the newest, /16 px per tick
# [4+2*lagK] age staleness of the newest scan, ticks
# [5+2*lagK] flight ring flight time (ticks) to the contact, /64
proc waveFeatures*(g: WaveElmGun, state: WorldState, vx, vy, flightTime: float):
seq[float] =
let id = if g.targetId >= 0: g.targetId
elif state.enemies.len > 0: state.enemies[0].id
else: 0
# Sanitise at the trust boundary: every float that comes out of `state` (and
# every argument) is finite before it reaches arithmetic that assumes progress.
let ex = finiteOr(state.enemyX, 0.0)
let ey = finiteOr(state.enemyY, 0.0)
let sx = finiteOr(state.selfX, 0.0)
let sy = finiteOr(state.selfY, 0.0)
let heading = finiteOr(state.enemyHeading, 0.0)
var vx = finiteOr(vx, 0.0)
var vy = finiteOr(vy, 0.0)
var flightTime = finiteOr(flightTime, 0.0)
let dx = ex - sx
let dy = ey - sy
let los = arctan2(dy, dx)
# heading delta, wrapped: positive = the target moves to the LEFT of the line
# of sight (opening range), negative = closing.
let hdelta = wrapDeg(heading - radToDeg(los))
# The RANGE the net reasons about is the RING's measurement when there is one:
# the ring is the instrument, the scan distance is only what it is calibrated
# against.
let ring = g.ringFor(id)
let dist = if ring.valid: ring.dist else: hypot(dx, dy)
let lagK = max(2, g.lagK)
result = newSeq[float](waveInputDim(lagK))
result[0] = vx / 8.0
result[1] = vy / 8.0
result[2] = dist / 1000.0
result[3] = hdelta / 180.0
var age = 0.0
if g.tracks.hasKey(id):
let tr = g.tracks[id]
# Each displacement is normalised by its OWN tick gap, so a late scan
# contributes a per-tick velocity rather than a 3-tick one.
for k in 0..<lagK:
if tr.n >= k + 2:
let gap = (tr.s[k].tick - tr.s[k + 1].tick).float
if gap >= 1.0:
result[4 + 2 * k] = (tr.s[k].x - tr.s[k + 1].x) / (16.0 * gap)
result[4 + 2 * k + 1] = (tr.s[k].y - tr.s[k + 1].y) / (16.0 * gap)
age = (state.tick - tr.s[0].tick).float
result[4 + 2 * lagK] = age / 8.0
result[5 + 2 * lagK] = flightTime / 64.0
for i in 0..<result.len:
if not isFinite(result[i]): result[i] = 0.0
proc pushScan(g: var WaveElmGun, id: int, tick: int, x, y: float) =
let tr = addr g.tracks.mgetOrPut(id, WaveTrack())
for i in countdown(WaveTrackCap - 1, 1): tr.s[i] = tr.s[i - 1]
tr.s[0] = WaveSample(tick: tick, x: x, y: y)
if tr.n < WaveTrackCap: inc tr.n
proc derivedVelocity(g: WaveElmGun, id: int, state: WorldState): tuple[vx, vy: float] =
## Velocity from the last two scans of THIS target; else heading*speed, the
## fallback every other gun in the rack uses.
result = (finiteOr(cos(degToRad(state.enemyHeading)) * state.enemySpeed, 0.0),
finiteOr(sin(degToRad(state.enemyHeading)) * state.enemySpeed, 0.0))
if g.tracks.hasKey(id):
let tr = g.tracks[id]
if tr.n >= 2:
let gap = (tr.s[0].tick - tr.s[1].tick).float
if gap >= 1.0:
result.vx = finiteOr((tr.s[0].x - tr.s[1].x) / gap, 0.0)
result.vy = finiteOr((tr.s[0].y - tr.s[1].y) / gap, 0.0)
# ── the Gun concept ───────────────────────────────────────────────────────────
proc predict*(g: var WaveElmGun, state: WorldState, bulletSpeed: float): GunPrediction =
inc g.predictCalls
let id = if g.targetId >= 0: g.targetId
elif state.enemies.len > 0: state.enemies[0].id
else: 0
# (B) PER-ENEMY TEMPORAL RESET: the RELM node state is the state of a
# SEQUENCE, and a different target is a different sequence.
if g.lastId != id: g.net.resetHidden()
g.lastId = id
# ONE scan push per tick: the harness calls predict 4-5 times a tick.
let newTick = state.tick != g.lastTick
if newTick:
g.lastTick = state.tick
g.pushScan(id, state.tick, state.enemyX, state.enemyY)
let (vx, vy) = g.derivedVelocity(id, state)
# ── THE RING ────────────────────────────────────────────────────────────────
# One ring per rung per new tick, at that rung's speed. The contact resolves
# `flight` ticks later; until then the previous measurement stays in force.
let ring = g.ringFor(id)
var h = RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
missDist: Inf)
if newTick or not ring.valid:
h = g.ringFireFromScan(state, vx, vy, bulletSpeed)
if h.found:
g.rings[id] = WaveRing(valid: true, dist: h.dist, bear: h.bearing,
fireTick: state.tick, tick: state.tick + h.tick,
flight: float(h.tick))
let meas = g.ringFor(id)
let measDist = if meas.valid: meas.dist else: hypot(state.enemyX - state.selfX,
state.enemyY - state.selfY)
let measBear = if meas.valid: meas.bear
else: arctan2(state.enemyY - state.selfY,
state.enemyX - state.selfX)
let flight = if meas.valid: meas.flight else: measDist / max(bulletSpeed, 1e-6)
# ── FLIGHT-TIME FEATURE REFRESH (WaveResolveFeatures) ──────────────────────
# Every trace whose bullet resolves THIS tick has its features rebuilt from the
# state as it is NOW, so the label is paired with the state the LABEL describes
# rather than the state the shot was fired from. Runs once per tick, after the
# scan push (so the trace sees this tick's scan exactly as a predict at this
# tick would).
if g.resolveFeat and newTick and g.refreshAt.len > 0:
var keep: seq[int] = @[]
for slot in g.refreshAt:
var tr = g.traces[slot]
if tr.alive and tr.resolveTick == state.tick:
let f2 = g.waveFeatures(state, vx, vy, flight)
tr.feat = f2
tr.selfX = state.selfX
tr.selfY = state.selfY
if g.net.isSane(): tr.hid = g.net.hidden(f2)
g.traces[slot] = tr
elif not tr.alive:
discard # the bullet died (wall / stale target); drop the reminder
else:
keep.add slot
g.refreshAt = keep
# ── THE LEARNED BIAS CORRECTION ─────────────────────────────────────────────
# The learned bias, px, in the world frame (see the module header on why the
# ring measures polar but the correction is applied Cartesian).
var dDist = 0.0
var dBear = 0.0
# (named for the net's two outputs; both are px, see the label note in onResult)
var gh: seq[float]
if g.net.isSane():
let feat = g.waveFeatures(state, vx, vy, flight)
gh = g.net.hidden(feat)
if newTick: g.net.hPrev = gh
let off = g.net.readOut(gh)
if off.len == 2 and isFinite(off[0]) and isFinite(off[1]):
dDist = off[0]
dBear = off[1]
dDist = clamp(dDist, -g.maxOffset, g.maxOffset)
dBear = clamp(dBear, -g.maxOffset, g.maxOffset)
g.lastDx = dDist
g.lastDy = dBear
# ── THE DAMAGE SHOT ─────────────────────────────────────────────────────────
# Reconstruct the enemy from the ring measurement and apply the correction.
let (rx, ry) = (finiteOr(state.selfX, 0.0) + measDist * cos(measBear) + g.lastDx,
finiteOr(state.selfY, 0.0) + measDist * sin(measBear) + g.lastDy)
var px = rx
var py = ry
if not (isFinite(px) and isFinite(py)):
# Degenerate input (a NaN/Inf crept in from a scan): the ONE point we know
# is finite is our own position.
px = state.selfX
py = state.selfY
px = clamp(px, BotRadius, max(BotRadius, state.arenaWidth - BotRadius))
py = clamp(py, BotRadius, max(BotRadius, state.arenaHeight - BotRadius))
if not (isFinite(px)): px = BotRadius
if not (isFinite(py)): py = BotRadius
# Pending trace: the ring measurement AND the hidden activation this shot was
# built from, so onResult can train on EXACTLY those inputs.
let binIdx = waveBinForSpeed(bulletSpeed)
if binIdx >= 0:
let feat = g.waveFeatures(state, vx, vy, flight)
let slot = waveTraceSlot(state.tick, binIdx)
let resolveTick = state.tick + max(1, int(round(flight)))
g.traces[slot] = WaveTrace(fireTick: state.tick, binIdx: binIdx,
resolveTick: resolveTick,
measDist: measDist, measBear: measBear,
selfX: state.selfX, selfY: state.selfY,
feat: feat, hid: gh, alive: true)
if g.resolveFeat and resolveTick > state.tick and resolveTick notin g.refreshAt:
g.refreshAt.add slot
GunPrediction(x: px, y: py,
# The correction's magnitude IS the gun's intrinsic per-sample
# confidence.
confidence: hypot(g.lastDx, g.lastDy))
proc onResult*(g: var WaveElmGun, e: FeedbackEvent) =
# ── guard 1: only CONFIRMED hits carry a label ──────────────────────────────
# A miss says the aim was wrong, not where it was wrong, so it is not a
# sample. It is counted, never trained on.
if not e.hit:
inc g.missShots
return
let binIdx = if e.powerBin >= 0 and e.powerBin < len(vb.PowerBins): e.powerBin
else: waveBinForSpeed(bulletSpeed(e.bulletPower))
if binIdx < 0:
inc g.traceMisses
return
# ── guard 3: we need the ring measurement this shot was built from; without
# the trace there is no sample, and fabricating one would train the net on a
# measurement that never existed ─────────────────────────────────────────────
let slot = waveTraceSlot(e.fireTick, binIdx)
if not g.traces[slot].alive or g.traces[slot].fireTick != e.fireTick or
g.traces[slot].binIdx != binIdx:
inc g.traceMisses
return
if not (isFinite(e.actualX) and isFinite(e.actualY)):
inc g.rejectedShots
return
# ── THE LABEL: the BIAS of the RING RECONSTRUCTION. It is the offset between
# where the ring SAYS the enemy is (its measurement decoded into a position,
# `tr.measDist/bear` — the "base") and where it actually was, rotated into the
# world frame. Cartesian, not polar, because the feature map carries velocity
# and range but NO bearing term: a polar label would be unlearnable (the net
# could not tell which way the ring was pointing) and would collapse to its
# own mean. This is the same quantity the old directed gun learned, with the
# intercept replaced by the ring's reconstruction as the base. ───────────────
let tr = g.traces[slot]
let (bx, by) = (tr.selfX + tr.measDist * cos(tr.measBear),
tr.selfY + tr.measDist * sin(tr.measBear))
let dX = e.actualX - bx
let dY = e.actualY - by
if not (isFinite(dX) and isFinite(dY)):
inc g.rejectedShots
return
# ── guard 2: the bias must be physically plausible, measured in PIXELS ──────
var gate = (if g.maxResidual < 0.0: Inf else: g.maxResidual)
if g.gateAdapt > 0.0:
gate = clamp(g.gateAdapt * max(g.recentRms, 1.0),
g.maxResidual * 0.5, g.maxResidual * 4.0)
let rmag = hypot(dX, dY)
if rmag > gate:
inc g.rejectedShots
return
g.recentRms = max(rmag, g.recentRms * 0.95)
if not g.net.isSane(): g.net.softReset()
# Train on the ACTIVATION that was fired, not on a freshly recomputed one: with
# the RELM recurrence on, hidden(feat) now runs against a later h(t-1).
let lab = @[dX, dY]
if tr.hid.len == g.net.hiddenDim:
discard g.net.trainHidden(tr.hid, lab)
else:
discard g.net.train(tr.feat, lab)
g.traces[slot].alive = false
inc g.trainedShots
@@ -0,0 +1,393 @@
## bench_waveelm_temporal.nim — OFFLINE A/B BENCHMARK for the temporal
## modelling of the online ELM gun (guns/waveelm.nim).
##
## WHAT IS MEASURED
## The gun's job is to predict a systematic aim OFFSET that is added to the
## RING RECONSTRUCTION (the base the directed design got from `intercept()`,
## now measured by the ring instead). So the quantity with a ground truth is the
## offset, not the aim point: each tick the harness rebuilds the SAME base the
## gun computed (identical inputs, `ringDecode` over the gun's own ring
## measurement) and compares
##
## error(t) = (gunPred(t) - ice(t)) - trueOffset(t)
##
## before any feedback arrives. That is the aim-offset estimator's prediction
## error, i.e. exactly what a hit/miss decides later. Two metrics:
## * RMS error (px) over the EVAL window (after burn-in)
## * hit rate: fraction of rung-shots whose residual is within BotRadius,
## counted over the WHOLE stream. The gun is only TRAINED on the hits, so
## hit rate is both the score and the amount of supervision available —
## a variant that predicts the offset badly gets fewer labels and can never
## recover. That is the real failure mode being benchmarked.
##
## THE GROUND TRUTH (see `truthOffset`)
## trueOffset(t) = G(t) * (pos(t) - pos(t-L)) + rad(t)
## i.e. "the aim solution that was actually used was L ticks stale, by a gain
## G". This is the turret lag / slew-rate model: the turret points at where the
## target WAS, the ring points at where it WILL be, and the gap is
## the sum of the last L displacements. It is a LINEAR functional of the recent
## displacement history, so any feature set that hands the net the last L
## displacements can represent it exactly — which is precisely the hypothesis
## under test. It is not a strawman: the gun's own doc says the label absorbs
## turret lag.
##
## THE THREE REGIMES (same bias functional form, different temporal character
## of the TARGET, so the estimator is identical and only the input differs)
## a) smooth : constant speed, smooth steady turn (turn-rate quantised,
## as a real bot's heading is), constant gain.
## b) accel : speed and turn rate both ramp with tick, so the offset
## envelope grows with the second derivative.
## c) abrupt : at t = AbruptTick the target flips its strafing direction
## (a 110 deg heading step) AND the gain steps 1.0 -> 1.6:
## the non-stationary case.
##
## Headroom, honestly: regime (a) is nearly linear in the features the gun
## already has, so (a) is expected to show little movement. The signal is in
## (b) and (c).
##
## Run: nim c -r common_libs/tests/bench_waveelm_temporal.nim
## NO battle server, NO runBattle, NO java: pure offline replay, ~1 s.
import std/[math, strformat, sequtils]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/waveelm
const
BenchTicks* = 300 ## ticks per regime (3 regimes x 3 rungs per tick)
BenchBurnIn* = 60 ## ticks of warm-up excluded from the RMS
BenchSelfX* = 100.0
BenchSelfY* = 300.0
ArenaW = 800.0
ArenaH = 600.0
LagTicks* = 4 ## L: how stale the aim solution was
LongLagTicks* = 12 ## a staleness NO explicit lag window can represent
HeadStep = 1.0 ## deg: turn-rate limit of the target's heading
AbruptTick = 150
BenchSeeds = [42'i64, 7, 99] ## ELM/hidden-layer seeds averaged over
# ── the target trajectories ──────────────────────────────────────────────────
type Regime* = enum
rSmooth, rAccel, rAbrupt
proc regimeName*(r: Regime): string =
case r
of rSmooth: "smooth"
of rAccel: "accel"
of rAbrupt: "abrupt"
type Traj* = object
name*: string
px*, py*: seq[float] ## true position per tick
hx*, hy*: seq[float] ## true unit velocity direction per tick
sp*: seq[float] ## true speed per tick
ox*, oy*: seq[float] ## ground-truth systematic offset per tick
proc wrap180(x: float): float =
result = x
for _ in 0..<4:
if result > 180.0: result -= 360.0
elif result < -180.0: result += 360.0
else: break
proc buildTraj*(r: Regime, jitter: bool, lag = LagTicks): Traj =
## Forward integration of a turn-rate-LIMITED heading: the commanded heading
## turns smoothly, the actual heading is quantised to HeadStep deg. That
## quantisation is the tick-scale structure that makes the L-tick-averaged
## displacement different from the instantaneous one — it is what a lag
## window buys, and it is a real property of Tank Royale bots (they are
## commanded, not continuous).
result.name = regimeName(r)
result.px = newSeq[float](BenchTicks)
result.py = newSeq[float](BenchTicks)
result.hx = newSeq[float](BenchTicks)
result.hy = newSeq[float](BenchTicks)
result.sp = newSeq[float](BenchTicks)
var x = 400.0
var y = 300.0
var cmd = degToRad(20.0) ## commanded heading
var act = cmd ## actual (quantised) heading
## Irregular burst jitter: a seeded coin per tick, speed x0 or x2, mean x1.
## This is the tick-scale structure a lag window exists to filter: real bots
## do not glide at a constant px/tick (they are tickRate-limited, they stop
## and go, the radar only catches them on some ticks), so the instantaneous
## displacement is a poor estimator of the motion the bias was built from,
## while a 4-tick average is a good one. The seed is fixed, so the burst
## pattern is identical on every run.
var js = 0x2545F491'i64
for t in 0..<BenchTicks:
var speed, turn: float
case r
of rSmooth:
speed = 4.0
turn = 3.0 ## deg/tick, steady
of rAccel:
speed = 2.5 + 0.013 * t.float # 2.5 -> 6.4 px/tick
turn = 2.0 + 0.018 * t.float # 2.0 -> 7.3 deg/tick
of rAbrupt:
speed = if t < AbruptTick: 4.5 else: 5.5
turn = if t < AbruptTick: 3.0 else: -3.0
if jitter:
js = (js * 1103515245 + 12345) and 0x7FFFFFFF
speed *= (if ((js shr 12) and 1) == 0: 0.4 else: 1.6)
# Keep the target INSIDE the gun's solvable envelope. A target that
# outruns the slowest rung (bulletSpeed(3.0) = 11 px/tick) has NO
# intercept: t = |p + v t| / spd has no root, the fixed point diverges and
# the aim point leaves the arena — a geometry failure of the intercept
# solver, not a property of the offset estimator being benchmarked.
if speed > 10.0: speed = 10.0
act = degToRad(round(radToDeg(act) / HeadStep) * HeadStep)
result.px[t] = x
result.py[t] = y
result.hx[t] = cos(act)
result.hy[t] = sin(act)
result.sp[t] = speed
x += cos(cmd) * speed
y += sin(cmd) * speed
# Keep the run inside the arena. A hard position clamp here would fake a
# wall bounce (and a velocity that teleports), so instead the COMMANDED
# heading is steered back toward the centre before the border is reached.
if x < 150 or x > ArenaW - 150 or y < 150 or y > ArenaH - 150:
cmd = arctan2(ArenaH / 2.0 - y, ArenaW / 2.0 - x)
else:
cmd = degToRad(wrap180(radToDeg(cmd) + turn))
# ground truth: the aim solution was L ticks stale, scaled by the gain
let gain = proc(t: int): float =
case r
of rSmooth: 1.0
of rAccel: 0.9 + 0.0015 * t.float # the offset envelope grows
of rAbrupt: (if t < AbruptTick: 1.0 else: 1.6)
result.ox = newSeq[float](BenchTicks)
result.oy = newSeq[float](BenchTicks)
for t in 0..<BenchTicks:
let a = max(0, t - lag)
let (px, py) = (result.px[t], result.py[t])
let (qx, qy) = (result.px[a], result.py[a])
# the stale solution lags along the DISPLACEMENT VECTOR: what the turret
# was pointing at when the solution was made, minus where it is now, in the
# frame the offset is applied in. Summed displacement, scaled by the gain.
result.ox[t] = gain(t) * (px - qx)
result.oy[t] = gain(t) * (py - qy)
proc mkState*(t: int, x, y, hx, hy, sp: float): WorldState =
WorldState(
enemyX: x, enemyY: y,
enemyHeading: radToDeg(arctan2(hy, hx)), enemySpeed: sp, enemyEnergy: 100.0,
selfX: BenchSelfX, selfY: BenchSelfY, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: ArenaW, arenaHeight: ArenaH, tick: t,
enemies: @[EnemyInfo(id: 1, x: x, y: y, energy: 100.0,
heading: radToDeg(arctan2(hy, hx)), speed: sp,
lastSeenTick: t)])
# ── the benchmark ────────────────────────────────────────────────────────────
type
BenchResult* = object
rms*: float ## px, eval window
hitRate*: float ## whole stream
shots*: int
labels*: int ## samples that actually reached beta
rejected*: int ## samples the validity gate threw away
BenchCfg* = object
name*: string
seed*: int64
lagK*: int ## number of scan-to-scan displacements in the features
relm*: float ## RELM gain, 0.0 = no recurrence
hiddenDim*: int ## hidden nodes (the (C) capacity probe)
# ── the tunable axes (0 / negative = module default) ──────────────────
lambda*: float ## ridge
rho*: float ## forgetting factor
maxResidual*: float ## validity gate, negative = no gate
maxOffset*: float ## offset clamp, negative = no clamp
gateAdapt*: float ## adapting-gate factor, 0 = fixed gate
aimErr*: float ## px: turret error — the bullet flies to aimPoint +
## aimErr*rotating unit vector, so a CONFIRMED hit can
## carry a residual well outside BotRadius. 0 = the
## gun is perfect, in which case a hit implies
## |residual| <= BotRadius and WaveMaxResidual (>=
## BotRadius) can never bind at all.
proc runRegime*(r: Regime, cfg: BenchCfg, jitter: bool, seed: int64,
lag = LagTicks): BenchResult =
let tr = buildTraj(r, jitter, lag)
var g = initWaveElmGun(seed, lagK = cfg.lagK, relm = cfg.relm,
hiddenDim = if cfg.hiddenDim > 0: cfg.hiddenDim
else: WaveHiddenDim,
lambda = if cfg.lambda > 0: cfg.lambda else: WaveLambda,
rho = if cfg.rho > 0: cfg.rho else: WaveRho,
maxResidual = if cfg.maxResidual != 0: cfg.maxResidual
else: WaveMaxResidual,
maxOffset = if cfg.maxOffset != 0: cfg.maxOffset
else: WaveMaxOffset,
gateAdapt = cfg.gateAdapt)
var sq = 0.0
var n = 0
var hits = 0
var shots = 0
var labels = 0
for t in 0..<BenchTicks:
# the SAME velocity derivation the gun does: the displacement between the
# last two scans (one tick apart), else heading*speed before the 2nd scan.
let hdg = radToDeg(arctan2(tr.hy[t], tr.hx[t]))
var vx = cos(degToRad(hdg)) * tr.sp[t]
var vy = sin(degToRad(hdg)) * tr.sp[t]
if t >= 1:
vx = tr.px[t] - tr.px[t - 1]
vy = tr.py[t] - tr.py[t - 1]
let st = mkState(t, tr.px[t], tr.py[t], tr.hx[t], tr.hy[t], tr.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# THE BASE is the gun's own RING RECONSTRUCTION (what used to be the
# intercept solver's aim point): the measurement decoded into a position,
# with NO learned correction on it. Identical inputs, identical code path —
# the metric is the learner's error, not the base's.
let (bx, by) = ringDecode(g.ringFor(st.enemies[0].id),
BenchSelfX, BenchSelfY)
# The truth is clamped exactly as the gun clamps its own aim point, so
# that no metric can be inflated by an asymmetry between the two.
let truthX = clamp(bx + tr.ox[t], BotRadius, ArenaW - BotRadius)
let truthY = clamp(by + tr.oy[t], BotRadius, ArenaH - BotRadius)
let res = hypot(truthX - pr.x, truthY - pr.y)
inc shots
# The BULLET does not fly to the aim point: the turret was pointing
# somewhere else when the trigger broke. `aimErr` rotates slowly so every
# sample lands on a different residual, which is what lets a confirmed
# hit carry a residual LARGER than BotRadius — i.e. what the validity
# gate actually exists to filter.
let ea = cfg.aimErr * 0.7 * t.float
let hitX = pr.x + cfg.aimErr * cos(ea)
let hitY = pr.y + cfg.aimErr * sin(ea)
let didHit = hypot(truthX - hitX, truthY - hitY) <= BotRadius
if didHit: inc hits
if t >= BenchBurnIn:
sq += res * res
inc n
# Feed the shot back EXACTLY as the live loop does: the true target
# position, hit iff the residual is inside the hit circle. A miss is
# counted, never trained on — that is the gun's own guard 1.
let before = g.trainedShots
g.onResult(FeedbackEvent(
prediction: pr, actualX: truthX, actualY: truthY,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: res, hit: didHit, confidence: pr.confidence))
labels += g.trainedShots - before
if n > 0: result.rms = sqrt(sq / n.float)
result.hitRate = (if shots > 0: hits.float / shots.float else: 0.0)
result.shots = shots
result.labels = labels
result.rejected = g.rejectedShots
proc describeGroundTruth() =
echo "── ground truth ──"
echo &" L ticks stale, turn quantised to {HeadStep} deg"
for lag in [LagTicks, LongLagTicks]:
echo " --- L = " & $lag & " ticks" &
(if lag > WaveLagKMax: " (> WaveLagKMax = " & $WaveLagKMax &
": NO lag window can represent it exactly ---)" else: "")
for j in [false, true]:
for r in Regime:
let tr = buildTraj(r, j, lag)
var sq = 0.0
var hi = 0.0
var loV = Inf
var hiV = 0.0
for t in 0..<BenchTicks:
let m = hypot(tr.ox[t], tr.oy[t])
sq += m * m
hi = max(hi, m)
loV = min(loV, tr.sp[t]); hiV = max(hiV, tr.sp[t])
var loX = Inf
var hiX = 0.0
var loY = Inf
var hiY = 0.0
for t in 0..<BenchTicks:
loX = min(loX, tr.px[t]); hiX = max(hiX, tr.px[t])
loY = min(loY, tr.py[t]); hiY = max(hiY, tr.py[t])
echo &" {tr.name:<7} burst={j:<5} |offset| rms={sqrt(sq/BenchTicks.float):5.1f}" &
&" max={hi:5.1f} px speed {loV:.1f}..{hiV:.1f}" &
&" pos x {loX:.0f}..{hiX:.0f} y {loY:.0f}..{hiY:.0f}"
when isMainModule:
describeGroundTruth()
echo &"── benchmark (RMS px over t >= {BenchBurnIn}, hit rate over the stream," &
&" mean of {BenchSeeds.len} seeds) ──"
let cfgs = [
BenchCfg(name: "baseline lagK2", seed: 42, lagK: 2, relm: 0.0),
BenchCfg(name: "lagK4", seed: 42, lagK: 4, relm: 0.0),
BenchCfg(name: "lagK6", seed: 42, lagK: 6, relm: 0.0),
BenchCfg(name: "lagK8", seed: 42, lagK: 8, relm: 0.0),
BenchCfg(name: "relm0.3", seed: 42, lagK: 2, relm: 0.3),
BenchCfg(name: "relm0.6", seed: 42, lagK: 2, relm: 0.6),
BenchCfg(name: "lagK6+relm0.3", seed: 42, lagK: 6, relm: 0.3)]
var base: array[2, array[Regime, tuple[rms, hit: float]]]
for j in 0..1:
let jitter = j == 1
for r in Regime:
for ci, c in cfgs:
var sr = 0.0
var sh = 0.0
for sd in BenchSeeds:
let b = runRegime(r, c, jitter, sd)
sr += b.rms
sh += b.hitRate
sr /= BenchSeeds.len.float
sh /= BenchSeeds.len.float
if ci == 0: base[j][r] = (rms: sr, hit: sh)
let drms = 100.0 * (sr - base[j][r].rms) / max(1e-9, base[j][r].rms)
let dhit = 100.0 * (sh - base[j][r].hit) / max(1e-9, base[j][r].hit)
let jn = if jitter: "burst" else: "smooth"
echo &" {jn:<6} {regimeName(r):<7} {c.name:<14} rms={sr:7.3f}" &
&" ({drms:+6.1f}%) hit={sh*100:6.2f}% ({dhit:+6.1f}%)"
# ── the fair test for RECURRENCE ───────────────────────────────────────────
# With L = 4 the truth is a 4-tick window, which an explicit lag window can
# represent exactly and a recurrence has nothing left to add. Re-run with
# L = 12: longer than any window the feature map can carry (WaveLagKMax = 8),
# so the only way to build the quantity is to INTEGRATE over time — which is
# precisely what the RELM hidden state does. If recurrence is worth anything
# it has to show up here.
# ── (C) CAPACITY PROBE: is hidden capacity the bottleneck at all? ──────────
# Growing hidden nodes is the Igelnik & Jemcevski / Huang-Wang-Lan option. It
# is only worth it if more capacity moves the number, so measure that FIRST.
echo &"\n── (C) CAPACITY PROBE (long memory, burst) ──"
for hd in [8, 16, 32, 64]:
var sr = 0.0
var sh = 0.0
for r in Regime:
for sd in BenchSeeds:
let b = runRegime(r, BenchCfg(name: "h", seed: sd, lagK: 8, relm: 0.0,
hiddenDim: hd), true, sd, LongLagTicks)
sr += b.rms
sh += b.hitRate
sr /= ((ord(rAbrupt) - ord(rSmooth) + 1).float * BenchSeeds.len.float)
sh /= ((ord(rAbrupt) - ord(rSmooth) + 1).float * BenchSeeds.len.float)
echo &" hiddenDim={hd:<4} mean rms={sr:7.3f} mean hit={sh*100:6.2f}%"
echo &"\n── LONG MEMORY (L = {LongLagTicks} ticks > WaveLagKMax = {WaveLagKMax}) ──"
let lcfgs = [cfgs[0], cfgs[1], cfgs[3], cfgs[4], cfgs[6]]
var lbase: array[Regime, tuple[rms, hit: float]]
for r in Regime:
for ci, c in lcfgs:
var sr = 0.0
var sh = 0.0
for sd in BenchSeeds:
let b = runRegime(r, c, true, sd, LongLagTicks)
sr += b.rms
sh += b.hitRate
sr /= BenchSeeds.len.float
sh /= BenchSeeds.len.float
if ci == 0: lbase[r] = (rms: sr, hit: sh)
let drms = 100.0 * (sr - lbase[r].rms) / max(1e-9, lbase[r].rms)
let dhit = 100.0 * (sh - lbase[r].hit) / max(1e-9, lbase[r].hit)
echo &" burst {regimeName(r):<7} {c.name:<14} rms={sr:7.3f}" &
&" ({drms:+6.1f}%) hit={sh*100:6.2f}% ({dhit:+6.1f}%)"
+24
View File
@@ -0,0 +1,24 @@
## Cross-check probe for `measure_gk_residual.py`: it prints the PRODUCTION aim
## base of `guns/gun_knowledge.nim` -- the exact angle `KnowledgeGun.predict`
## turns into its prediction point -- for every
## ex ey eh es sx sy power
## line on stdin, one float per line on stdout. The measurement script replays
## the aim offline and asserts that its replay equals THIS, so the offline
## numbers cannot silently drift away from the shipped code again.
##
## Build: nim c --path:common_libs common_libs/tests/gk_aim_probe.nim
## (the script builds it itself and skips the cross-check with a loud warning
## if the binary is missing).
import std/[os, strutils]
import guns/gun_knowledge
for line in stdin.lines:
let f = line.splitWhitespace()
if f.len < 7: continue
let feat = GkFeatures(
enemyX: parseFloat(f[0]), enemyY: parseFloat(f[1]),
enemyHeading: parseFloat(f[2]), enemySpeed: parseFloat(f[3]),
selfX: parseFloat(f[4]), selfY: parseFloat(f[5]),
power: parseFloat(f[6]), hasTarget: true)
echo forecastBase(feat, 0.0)
File diff suppressed because it is too large Load Diff
+732
View File
@@ -0,0 +1,732 @@
#!/usr/bin/env python3
"""MEASURE: the gun-knowledge learned ANGULAR RESIDUAL vs the bare
`forecastLinear` base, over VIRTUAL BULLETS on the recorded corpus.
`measure_gk_residual.py` measured the residual on REAL FIRED SHOTS (~55k). This
script re-measures it on the thing the module actually learns from in battle:
VIRTUAL BULLETS. `gun_harness/virtual_bullets.nim` spawns one bullet per power
bin per gun per tick, so the knowledge gun gets 4 resolutions per tick against
the 1/tick a real shot gives it — the offline table was starved by ~63x.
WHAT IS SIMULATED (mirrors virtual_bullets.nim `bmPath` exactly)
---------------------------------------------------------------
PowerBins = [1.0, 1.5, 2.0, 3.0], bulletSpeed = 20 - 3p
every tick with a live target, per power bin:
aim = production base (forecastLinear, ABSOLUTE world bearing,
gkm.production_base) + residual from the table row
spawn a bullet at the shooter position, direction = aim, speed = v
advance it EVERY tick (spawn-then-tick, as the live bot does: the rack
calls spawnBullets before tickBullets on the same tick)
each tick: swept segment vs the RECORDED enemy position of that tick,
hit iff distPointToSegment(...) < BotRadius (18.0) [bmPath]
resolve ONLY at the wall, exactly once, recording hit or miss
on resolution: table update, crediting the usedBin on a hit
a bullet whose target dies, or that is in flight at a round boundary, is
dropped WITHOUT scoring (bmPath's dead-target branch, and
KnowledgeGun.onRoundBoundary clears `pending`, so a post-boundary feedback
updates nothing — and the corpus records the enemy every tick, so there is
no staleness gap to interpolate)
LEARNING POLICY
---------------
The epsilon-greedy policy is NOT in the shipped `gun_knowledge.nim` (that file
documents "The module itself never invents a random bin"); it is applied here
exactly as specified for this measurement:
row.attempts < --explore-attempts -> with p = --eps pick a UNIFORM
random residual bin, else the argmax. At or above the threshold: argmax.
Every resolution increments row.attempts, and `aim` increments it below the
trust threshold (exactly as the module's `inc gk.globalRows[key].attempts`
does). A shot taken with no residual (usedBin -1) is filed under bin 0, the
0 deg NULL, exactly as `update` does. The trust threshold that gates the
argmax is GK_GLOBAL_MIN_ATTEMPTS = 5 in both `aim` and `update`.
SPLIT: held out BY BATTLE, 2-fold, `run1..run7` = fold 0 and `run8..run14` =
fold 1, identical to measure_gk_residual.py. Every virtual bullet is tested
exactly once (each battle is in exactly one held-out fold).
ARMS
base residual 0, i.e. bare `forecastLinear`, through the same spawn/flight
learn residual from the table, frozen at test time
A tick whose learned residual is 0 has a byte-identical ray, so ONE flight is
simulated and credited to both arms (it IS the same bullet, not an average).
Every band/rms number is measured on the SAME set of held-out ticks.
KEY CONFIGS
full the production 15-bit key: band x space x turn x trend x heat x radial
(gun heat is not in the corpus -> pinned to quarter 0, so this key is
COARSER than in battle, never finer)
dt band x turn — the config that won the real-shot sweep (SWEEP F/J)
"""
from __future__ import annotations
import collections
import glob
import json
import math
import os
import random
import statistics
import sys
import time
from multiprocessing import Process, Pool
# reuse the previous script's PRODUCTION-AIM ports verbatim (one definition of
# forecastLinear / production_base / bandOf / spaceOf / the bin layout)
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
_ARGV = sys.argv
sys.argv = [sys.argv[0]]
import measure_gk_residual as gkm # noqa: E402
sys.argv = _ARGV
ROOT = os.environ.get("GK_CORPUS", "/tmp/tfil_ab2/out")
GK_NBINS = 32
GK_NULL_BIN = 0
GK_MIN_BIN_HITS = 3
GK_GLOBAL_MIN_ATTEMPTS = 5
CENTRE = gkm.CENTRE # bin b -> residual degrees
BOT_RADIUS = 18.0
ARENA_W, ARENA_H = 800.0, 600.0
POWER_BINS = [1.0, 1.5, 2.0, 3.0]
SPEEDS = [20.0 - 3.0 * p for p in POWER_BINS] # 17.0 15.5 14.0 11.0
MAX_FLIGHT = 300
BAND_LAB = gkm.BAND_LAB
N_BAND = len(BAND_LAB)
GK_STRAIGHT, GK_RIGHT, GK_LEFT, GK_UNKNOWN = 0, 1, 2, 3
GK_ACCEL, GK_CONST, GK_DECEL = 0, 1, 2
GK_TURN_DEAD, GK_TREND_DEAD = 2.0, 0.05
VEL_WINDOW, RADIAL_WINDOW = 16, 32
ARM_BASE, ARM_BOTH, ARM_LEARN = 0, 2, 1
def key_of(band, space, turning, trend, rad, arm):
if arm == "full":
return ((((band * 3 + space) * 4 + turning) * 4 + trend) * 4 + 0) * 4 + rad
return band * 4 + turning
def nrows(arm):
return 5 * 3 * 4 * 4 * 4 * 4 if arm == "full" else 5 * 4
def best_residual(row):
"""Port of gun_knowledge.bestResidual: argmax over the bins clearing
GK_MIN_BIN_HITS, tie-broken toward the 0 deg NULL. Returns (deg, bin)."""
if row is None:
return 0.0, -1
best_b, best_h = -1, 0
for b in range(GK_NBINS):
h = row[b]
if h < GK_MIN_BIN_HITS:
continue
if h > best_h or (h == best_h and best_b >= 0 and abs(b) < abs(best_b)):
best_h, best_b = h, b
if best_b < 0:
return 0.0, -1
return CENTRE[best_b], best_b
class Table:
def __init__(self, n):
self.n = n
self.att = [0] * n
self.hits = [None] * n
def row(self, k):
r = self.hits[k]
if r is None:
r = self.hits[k] = [0] * GK_NBINS
return r
def residual(self, k):
"""What `aim` returns for this row: below GK_GLOBAL_MIN_ATTEMPTS the
module returns the NULL residual (it only counts the attempt)."""
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
return 0.0, -1
return best_residual(self.hits[k])
def stats(self):
nz, trusted, s = 0, 0, 0.0
for k in range(self.n):
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
continue
trusted += 1
d, _ = best_residual(self.hits[k])
if d != 0.0:
nz += 1
s += abs(d)
return nz, trusted, (s / nz if nz else 0.0)
# ─────────────────────────────────────────────────────────────────────────────
# corpus
# ─────────────────────────────────────────────────────────────────────────────
_CACHE = {}
def battle_files(root):
out = []
for p in sorted(glob.glob(os.path.join(root, "*", "*.jsonl"))):
if p.endswith(".events.jsonl"):
continue
rj, ev = p + ".rounds.json", p[:-6] + ".events.jsonl"
if not (os.path.exists(rj) and os.path.exists(ev)):
continue
tag = os.path.basename(os.path.dirname(p)) + "/" + os.path.basename(p)[:-6]
out.append(dict(tag=tag, path=p, rj=rj, ev=ev,
fold=0 if int(tag.split("run")[1]) <= 7 else 1))
return out
def load_battle(bf):
rounds = json.load(open(bf["rj"]))["rounds"]
starts = [(r["startTick"], r["startTick"] + r["count"]) for r in rounds]
T, EX, EY, EH, ES, SX, SY, SE, EE = [], [], [], [], [], [], [], [], []
RND = []
r = 0
with open(bf["path"]) as f:
for line in f:
if '"tick"' not in line:
continue
o = json.loads(line)
while r + 1 < len(starts) and o["tick"] >= starts[r + 1][0]:
r += 1
RND.append(r)
T.append(o["tick"])
EX.append(o["ex"]); EY.append(o["ey"])
EH.append(o["eh"]); ES.append(o["es"])
SX.append(o["sx"]); SY.append(o["sy"])
SE.append(o["se"]); EE.append(o["ee"])
return dict(T=T, ex=EX, ey=EY, eh=EH, es=ES, sx=SX, sy=SY, se=SE, ee=EE,
rnd=RND, starts=starts)
def get_battle(bf):
b = _CACHE.get(bf["tag"])
if b is None:
b = _CACHE[bf["tag"]] = load_battle(bf)
return b
def cadence(bfs):
gaps = collections.Counter()
rows = 0
for bf in bfs:
prev = None
for line in open(bf["path"]):
if '"tick"' not in line:
continue
t = json.loads(line)["tick"]
rows += 1
if prev is not None:
gaps[t - prev] += 1
prev = t
return rows, gaps
def real_shots(bfs):
"""US (= the `s*` adversary, ModularBot) fired shots, by the same
energy-drop attribution measure_gk_residual.py uses."""
per_run = {}
for bf in bfs:
b = load_battle(bf)
pos = {t: i for i, t in enumerate(b["T"])}
votes = collections.defaultdict(collections.Counter)
def match(t, side, ev):
i, i1 = pos.get(t), pos.get(t + 1)
if i is None or i1 is None:
return False
if abs(b[side + "x"][i] - ev["x"]) > 0.02 or \
abs(b[side + "y"][i] - ev["y"]) > 0.02:
return False
ef = "ee" if side == "e" else "se"
return abs((b[ef][i] - b[ef][i1]) - ev["power"]) < 0.02
for ev in (json.loads(l) for l in open(bf["ev"]) if l.strip()):
if ev.get("type") != "fire":
continue
g = ev.get("tick", 0)
for t in range(g - 8, g + 9):
for side in ("e", "s"):
if match(t, side, ev):
votes[ev["owner"]][side] += 1
n = 0
for o, c in votes.items():
if c and c.most_common(1)[0][0] == gkm.US_SIDE:
n += sum(c.values())
per_run[bf["tag"]] = n
_CACHE.pop(bf["tag"], None)
return per_run
# ─────────────────────────────────────────────────────────────────────────────
# the replay
# ─────────────────────────────────────────────────────────────────────────────
class Acc:
__slots__ = ("n", "tk", "eb2", "eab", "el2", "eal", "hb", "nb", "hl", "nl",
"hd", "hbp", "hlp", "cov", "res")
def __init__(self):
for s in self.__slots__:
setattr(self, s, 0.0)
def add(self, o):
for s in self.__slots__:
setattr(self, s, getattr(self, s) + getattr(o, s))
def as_dict(self):
return {s: getattr(self, s) for s in self.__slots__}
def replay(b, arm, table, learn, thr, eps, rng, test):
"""One battle. learn=True: training replay (learns, scores nothing).
test=True: held-out replay, table frozen, base and learn flown side by side.
Returns (per-band Acc list, counters)."""
T, EX, EY, EH, ES = b["T"], b["ex"], b["ey"], b["eh"], b["es"]
SX, SY, SE, EE = b["sx"], b["sy"], b["se"], b["ee"]
rnd, starts = b["rnd"], b["starts"]
n = len(T)
acc = [Acc() for _ in range(N_BAND)]
c = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0)
a_fx, a_fy, a_ux, a_uy, a_tr, a_sp = [], [], [], [], [], []
a_hit, a_key, a_bn, a_arm, a_bd, a_pi = [], [], [], [], [], []
bh = [0.0] * (n + 1) # per spawn tick: did the BASE flight hit?
prev_t = -10
rr = -1
prev_ex = prev_ey = prev_eh = prev_es = 0.0
has_prev = False
rad_ring = [0.0] * VEL_WINDOW
rad_head = rad_count = 0
fB, band_of = gkm.production_base, gkm.band_of
space_of, wrap180 = gkm.space_of, gkm.wrap180
atan2d = math.degrees
R2 = BOT_RADIUS * BOT_RADIUS
for j in range(n):
t = T[j]
if rnd[j] != rr or t != prev_t + 1:
if a_fx:
c["round"] += len(a_fx)
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
rr = rnd[j]
has_prev = False
rad_count = rad_head = 0
prev_t = t
ex, ey, eh, es = EX[j], EY[j], EH[j], ES[j]
sx, sy = SX[j], SY[j]
e_alive = EE[j] > 0.0
s_alive = SE[j] > 0.0
end = starts[rr][1] if rr >= 0 else t
if e_alive and s_alive:
dx, dy = ex - sx, ey - sy
dist = math.sqrt(dx * dx + dy * dy)
if dist > 1e-6:
c["ticks"] += 1
if has_prev:
rate = wrap180(eh - prev_eh)
turning = GK_LEFT if rate > GK_TURN_DEAD else (
GK_RIGHT if rate < -GK_TURN_DEAD else GK_STRAIGHT)
dv = es - prev_es
trend = GK_ACCEL if dv > GK_TREND_DEAD else (
GK_DECEL if dv < -GK_TREND_DEAD else GK_CONST)
ddx, ddy = ex - prev_ex, ey - prev_ey
spd = math.sqrt(ddx * ddx + ddy * ddy)
frac = 0.0
if spd > 0.1:
frac = abs((ddx * (sx - ex) + ddy * (sy - ey)) / dist) / spd
rad_ring[rad_head] = frac
rad_head = (rad_head + 1) % VEL_WINDOW
if rad_count < VEL_WINDOW:
rad_count += 1
else:
turning = trend = GK_UNKNOWN
prev_ex, prev_ey, prev_eh, prev_es = ex, ey, eh, es
has_prev = True
rf = 0.0
if rad_count:
nn = min(RADIAL_WINDOW, rad_count)
s = 0.0
for i in range(nn):
s += rad_ring[(rad_head - 1 - i) % VEL_WINDOW]
rf = s / nn
band = band_of(dist)
sp = space_of(ex, ey, sx, sy)
rad = 0 if rf < 0.25 else 1 if rf < 0.5 else 2 if rf < 0.75 else 3
k = key_of(band, sp, turning, trend, rad, arm)
# ---- what aim() applies this tick ----
if learn:
if table.att[k] < thr:
res, ub = 0.0, -1
table.att[k] += 1
if eps > 0.0 and rng.random() < eps:
ub = rng.randrange(GK_NBINS)
res = CENTRE[ub]
c["explore"] += 1
else:
res, ub = best_residual(table.hits[k])
else:
res, ub = table.residual(k)
if test:
A = acc[band]
A.tk += 1
A.cov += 1.0 if res != 0.0 else 0.0
A.res += abs(res)
los = atan2d(math.atan2(dy, dx))
for bi in range(4):
A.n += 1
v = SPEEDS[bi]
kk = 1
kst = -1
while kk <= MAX_FLIGHT and t + kk < end and j + kk < n \
and T[j + kk] == t + kk:
qx = EX[j + kk] - sx
qy = EY[j + kk] - sy
if math.sqrt(qx * qx + qy * qy) <= v * kk:
kst = kk
break
kk += 1
if kst < 0:
c["skip"] += 1
continue
req = wrap180(atan2d(math.atan2(EY[j + kst] - sy,
EX[j + kst] - sx)) - los)
bl = wrap180(fB(ex, ey, eh, es, sx, sy, v) - los)
eb = wrap180(bl - req)
el = wrap180(bl + res - req)
A.eb2 += eb * eb
A.eab += abs(eb)
A.el2 += el * el
A.eal += abs(el)
# ---- spawnBullets ----
for bi in range(4):
v = SPEEDS[bi]
bse = fB(ex, ey, eh, es, sx, sy, v)
a_fx.append(sx); a_fy.append(sy)
a_tr.append(0.0); a_sp.append(v)
a_hit.append(False); a_key.append(k); a_bn.append(ub)
a_bd.append(band); a_pi.append(j)
a_ux.append(math.cos(math.radians(bse)))
a_uy.append(math.sin(math.radians(bse)))
if res != 0.0:
a_arm.append(ARM_BASE)
c["split"] += 1
a_fx.append(sx); a_fy.append(sy)
a_tr.append(0.0); a_sp.append(v)
a_hit.append(False); a_key.append(k); a_bn.append(ub)
a_bd.append(band); a_pi.append(j)
a_ux.append(math.cos(math.radians(bse + res)))
a_uy.append(math.sin(math.radians(bse + res)))
a_arm.append(ARM_LEARN)
else:
a_arm.append(ARM_BOTH)
c["shared"] += 1
# ---- tickBullets: advance every bullet one tick ----
if a_fx:
if not e_alive:
c["dead"] += len(a_fx)
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
else:
w = 0
for i in range(len(a_fx)):
sp = a_sp[i]
tr = a_tr[i] + sp
fx, fy = a_fx[i], a_fy[i]
ux, uy = a_ux[i], a_uy[i]
ddx = ex - fx
ddy = ey - fy
along = ux * ddx + uy * ddy
perp = -uy * ddx + ux * ddy
hit = a_hit[i]
if not hit and perp * perp < R2:
prev_d = tr - sp
if along > prev_d - BOT_RADIUS and along < tr + BOT_RADIUS:
seg = along - (prev_d if along < prev_d else
(tr if along > tr else along))
if seg * seg + perp * perp < R2:
hit = True
bx = fx + ux * tr
by = fy + uy * tr
if bx < 0.0 or bx > ARENA_W or by < 0.0 or by > ARENA_H:
c["resolved"] += 1
if learn:
k = a_key[i]
table.att[k] += 1
if hit:
b = a_bn[i]
table.row(k)[b if b >= 0 else GK_NULL_BIN] += 1
c["learn_hits"] += 1
else:
A = acc[a_bd[i]]
am = a_arm[i]
hv = 1.0 if hit else 0.0
if am == ARM_LEARN:
A.nl += 1
A.hl += hv
# PAIRED: the baseline flight for THIS spawn tick
A.hd += 1
A.hbp += bh[a_pi[i]]
A.hlp += hv
elif am == ARM_BOTH:
A.nb += 1; A.hb += hv
A.nl += 1; A.hl += hv
bh[a_pi[i]] = hv
else:
A.nb += 1; A.hb += hv
bh[a_pi[i]] = hv
continue
a_fx[w] = fx; a_fy[w] = fy; a_ux[w] = ux; a_uy[w] = uy
a_tr[w] = tr; a_sp[w] = sp; a_hit[w] = hit
a_key[w] = a_key[i]; a_bn[w] = a_bn[i]; a_arm[w] = a_arm[i]
a_bd[w] = a_bd[i]; a_pi[w] = a_pi[i]
w += 1
del a_fx[w:]; del a_fy[w:]; del a_ux[w:]; del a_uy[w:]
del a_tr[w:]; del a_sp[w:]; del a_hit[w:]
del a_key[w:]; del a_bn[w:]; del a_arm[w:]; del a_bd[w:]
del a_pi[w:]
c["inflight"] = len(a_fx)
return acc, c
# ─────────────────────────────────────────────────────────────────────────────
# driver
# ─────────────────────────────────────────────────────────────────────────────
_G = {}
def _test_one(bf):
b = get_battle(bf)
acc, c = replay(b, _G["arm"], _G["table"], False, 0, 0.0, None, True)
return bf["tag"], [a.as_dict() for a in acc], c
def run_config(arm, thr, eps, bfs, outdir):
t0 = time.time()
res = dict(arm=arm, thr=thr, eps=eps, folds=[])
for fold in (0, 1):
table = Table(nrows(arm))
rng = random.Random(1234 + fold)
ctr = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
ticks=0, explore=0, learn_hits=0, inflight=0)
for bf in bfs: # TRAINING: sequential, table evolves
if bf["fold"] == fold:
continue
_, c = replay(get_battle(bf), arm, table, True, thr, eps, rng, False)
for k in ctr:
ctr[k] += c[k]
nz, trusted, mean_abs = table.stats()
_G["arm"], _G["table"] = arm, table
with Pool(4) as pool: # TEST: frozen table, battles parallel
out = pool.map(_test_one, [bf for bf in bfs if bf["fold"] != fold])
pooled = [Acc() for _ in range(N_BAND)]
ctest = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
ticks=0, explore=0, learn_hits=0, inflight=0)
battles = []
for tag, bands, c in out:
A = []
for a in bands:
A.append(_mk(a))
pooled[len(A) - 1].add(A[-1])
for k in ctest:
ctest[k] += c[k]
tb = Acc()
for a in A:
tb.add(a)
battles.append(dict(tag=tag, n=tb.n, tk=tb.tk, eb2=tb.eb2, el2=tb.el2,
nb=tb.nb, hb=tb.hb, nl=tb.nl, hl=tb.hl,
hd=tb.hd, hbp=tb.hbp, hlp=tb.hlp,
cov=tb.cov, res=tb.res))
res["folds"].append(dict(fold=fold, nz=nz, trusted=trusted,
mean_abs=mean_abs, train=ctr, test=ctest,
bands=[a.as_dict() for a in pooled],
battles=battles))
_G.clear()
json.dump(res, open(os.path.join(outdir, "gk_%s_%d.json" % (arm, thr)), "w"))
return time.time() - t0
def rms(x):
return math.sqrt(x) if x >= 0 else float("nan")
def mean_sd(xs):
if len(xs) < 2:
return 0.0, 0.0
m = statistics.fmean(xs)
return m, math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1))
def report(cfg_path, real_n, rows, gaps, bfs):
r = json.load(open(cfg_path))
print("=" * 100)
print("CONFIG key=%s explore-attempts=%d eps=%.2f" % (r["arm"], r["thr"], r["eps"]))
tt = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0, inflight=0)
cte = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0, inflight=0)
for f in r["folds"]:
for k in tt:
tt[k] += f["train"][k]
cte[k] += f["test"][k]
ntr = len(bfs) // 2 * 2
print(" TRAINING (the %d held-in battles of each of the 2 folds, replayed"
" sequentially, table rebuilt per fold):" % (ntr // 2))
print(" virtual bullets spawned %d resolved %d in flight at battle end %d"
% (4 * tt["ticks"] + tt["split"], tt["resolved"], tt["inflight"]))
print(" dropped unscored: target dead %d, round boundary %d of which the"
" two arms flew ONE identical ray: %d" % (tt["dead"], tt["round"], tt["shared"]))
print(" resolutions credited as HITS: %d epsilon-greedy draws: %d"
% (tt["learn_hits"], tt["explore"]))
tot = [Acc() for _ in range(N_BAND)]
bl = []
for f in r["folds"]:
for i, a in enumerate(f["bands"]):
tot[i].add(_mk(a))
bl += f["battles"]
for f in r["folds"]:
print(" fold %d: rows above the trust threshold %d, with a NON-ZERO"
" argmax %d, mean |residual| of those %+.2f deg"
% (f["fold"], f["trusted"], f["nz"], f["mean_abs"]))
ntest = sum(b["tk"] for b in bl)
nvb = sum(b["nb"] for b in bl)
nvl = sum(b["nl"] for b in bl)
cov = sum(b["cov"] for b in bl)
rr = sum(b["res"] for b in bl)
print(" HELD-OUT (2-fold by battle, both folds pooled, every bullet tested once):")
print(" virtual bullets TESTED: base arm %d, learned arm %d"
" (%.1fx the %d real fired shots)" % (nvb, nvl, nvl / max(real_n, 1), real_n))
print(" held-out target ticks (both bots alive): %d x4 power bins = %d aim"
" decisions skipped (no interception before the round end): %d"
% (ntest, int(sum(a.n for a in tot)), cte["skip"]))
print(" held-out ticks carrying a NON-ZERO residual: %d (%.2f%%) mean"
" |residual| applied %.3f deg"
% (int(cov), 100.0 * cov / max(ntest, 1), rr / max(ntest, 1)))
print(" %-8s %9s %8s %8s %8s | %8s %8s %8s %8s | %10s"
% ("band", "aims", "rms_b", "mabs_b", "hit_b%", "rms_l", "mabs_l",
"hit_l%", "dhit_pp", "paired_n"))
for i, lab in enumerate(BAND_LAB):
a = tot[i]
if a.n <= 0:
continue
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
% (lab, int(a.n), rms(a.eb2 / a.n), a.eab / a.n, 100.0 * a.hb / max(a.nb, 1),
rms(a.el2 / a.n), a.eal / a.n, 100.0 * a.hl / max(a.nl, 1),
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
a = Acc()
for x in tot:
a.add(x)
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
% ("ALL", int(a.n), rms(a.eb2 / a.n), a.eab / a.n,
100.0 * a.hb / max(a.nb, 1), rms(a.el2 / a.n), a.eal / a.n,
100.0 * a.hl / max(a.nl, 1),
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
print(" PAIRED (only the ticks where the two arms flew DIFFERENT rays):"
" base %d/%d hit, learned %d/%d hit -> %+.3f pp"
% (int(a.hbp), int(a.hd), int(a.hlp), int(a.hd),
100.0 * (a.hlp - a.hbp) / max(a.hd, 1)))
# clustered, per-battle paired statistics
dh, de = [], []
for b in bl:
if b["hd"]:
dh.append((b["hlp"] - b["hbp"]) / b["hd"])
if b["n"]:
de.append((b["el2"] - b["eb2"]) / b["n"])
mh, sh = mean_sd(dh)
me, se = mean_sd(de)
th = mh / (sh / math.sqrt(len(dh))) if sh > 0 else 0.0
te = me / (se / math.sqrt(len(de))) if se > 0 else 0.0
print(" CLUSTERED by battle (%d battles): dHit %+0.3f pp (sd %0.3f, t=%+.2f)"
" dMeanSqErr %+8.2f deg2 (sd %8.2f, t=%+.2f)"
% (len(dh), 100 * mh, 100 * sh, th, me, se, te))
return r
def _mk(d):
a = Acc()
for s in Acc.__slots__:
setattr(a, s, d[s])
return a
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--root", default=ROOT)
ap.add_argument("--arms", default="full,dt")
ap.add_argument("--thresholds", default="5,100")
ap.add_argument("--eps", type=float, default=0.25)
ap.add_argument("--limit", type=int, default=0, help="first N battles (smoke)")
ap.add_argument("--out", default="/tmp/gk_virtual")
a = ap.parse_args()
bfs = battle_files(a.root)
if a.limit:
bfs = bfs[:a.limit]
if not bfs:
print("NO CORPUS at %s" % a.root)
return 1
os.makedirs(a.out, exist_ok=True)
rows, gaps = cadence(bfs)
real = real_shots(bfs)
real_n = sum(real.values())
print("CORPUS %s" % a.root)
print(" battles: %d worldstate rows: %d" % (len(bfs), rows))
print(" TICK CADENCE: inter-row deltas %s"
% (dict(gaps) if gaps else "none (one row per tick, contiguous)"))
print(" -> NO interpolation needed: every tick is recorded, so a virtual"
" bullet's swept segment is tested against the enemy position of that"
" exact tick.")
print(" REAL fired shots by the US bot (energy-drop attribution): %d"
% real_n)
print(" power bins %s -> bullet speeds %s ; BotRadius %.1f ; arena %.0fx%.0f"
% (POWER_BINS, SPEEDS, BOT_RADIUS, ARENA_W, ARENA_H))
print()
arms = a.arms.split(",")
thrs = [int(x) for x in a.thresholds.split(",")]
procs = []
for arm in arms:
for thr in thrs:
p = Process(target=run_config,
args=(arm, thr, a.eps, bfs, a.out))
p.start()
procs.append(p)
for p in procs:
p.join()
if p.exitcode:
print("!! a config process exited %d" % p.exitcode)
print()
for arm in arms:
for thr in thrs:
f = os.path.join(a.out, "gk_%s_%d.json" % (arm, thr))
if os.path.exists(f):
report(f, real_n, rows, gaps, bfs)
return 0
if __name__ == "__main__":
sys.exit(main())
+227
View File
@@ -0,0 +1,227 @@
## Unit tests for the online sequential ELM (common_libs/guns/elm.nim).
##
## Covers what the guns actually rely on: fitting a known function, streaming
## convergence, the forgetting factor tracking a drifting target, the
## NaN/Inf guards, and seed reproducibility.
##
## Run: nim c -r common_libs/tests/test_elm.nim
import std/[math, random, strformat]
import guns/elm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc rmse(net: ElmNet, samples: seq[tuple[x: seq[float], t: seq[float]]]): float =
## Prediction RMSE over a held-out sample set (net used read-only).
var s = 0.0
for smp in samples:
let p = net.predict(smp.x)
for o in 0..<net.outputDim: s += (p[o] - smp.t[o]) ^ 2
sqrt(s / (samples.len.float * net.outputDim.float))
# ── 1. linear fit y = 2x + 1, noisy ──────────────────────────────────────────
proc testLinearFit() =
block:
let n = 400
var rng = initRand(7)
var net = init(inputDim = 1, hiddenDim = 12, seed = 42)
for i in 0..<n:
let x = @[rand(rng, 1.0) * 2.0 - 1.0]
let t = @[2.0 * x[0] + 1.0 + (rand(rng, 1.0) * 2.0 - 1.0) * 0.02]
discard net.train(x, t)
var grid: seq[tuple[x: seq[float], t: seq[float]]] = @[]
for i in 0..<100:
let x = @[-1.0 + 2.0 * float(i) / 100.0]
grid.add((x: x, t: @[2.0 * x[0] + 1.0]))
let e = rmse(net, grid)
echo &" linear y=2x+1: grid RMSE = {e:.5f}"
check "linear: RMSE on [-1,1] grid < 0.05", e < 0.05
# ── 2. 2D input -> 2D output ───────────────────────────────────────────────
block:
let n = 600
var rng = initRand(11)
var net = init(inputDim = 2, hiddenDim = 20, seed = 7, outputDim = 2)
proc target(x: openArray[float]): seq[float] =
@[x[0] + 0.5 * x[1] - 1.0, -0.3 * x[0] + 2.0 * x[1] + 0.25]
for i in 0..<n:
let x = @[rand(rng, 1.0) * 2.0 - 1.0, rand(rng, 1.0) * 2.0 - 1.0]
var t = target(x)
for o in 0..<1:
t[o] += (rand(rng, 1.0) * 2.0 - 1.0) * 0.01
discard net.train(x, t)
var grid: seq[tuple[x: seq[float], t: seq[float]]] = @[]
for i in 0..<60:
let x = @[-1.0 + 2.0 * float(i) / 60.0, 1.0 - 2.0 * float(i) / 60.0]
grid.add((x: x, t: target(x)))
let e = rmse(net, grid)
echo &" 2D->2D: grid RMSE = {e:.5f}"
check "2D->2D: RMSE < 0.05", e < 0.05
# ── 3. online / streaming convergence ────────────────────────────────────────
proc testStreaming() =
## RLS is prequential: every sample is predicted once, then trained on. The
## net converges in a handful of samples (that is the point of RLS), so the
## trend has to be measured against the FIRST samples, not the first 100.
var rng = initRand(3)
var net = init(inputDim = 1, hiddenDim = 16, seed = 99)
var firstErr = 0.0
var headErr = 0.0
var tailErr = 0.0
var worstTail = 0.0
for i in 0..<600:
let x = @[rand(rng, 1.0) * 2.0 - 1.0]
let t = @[2.0 * x[0] + 1.0]
if i == 0: firstErr = (net.predict(x)[0] - t[0]) ^ 2 # untrained: predicts 0
discard net.train(x, t)
let err = (net.predict(x)[0] - t[0]) ^ 2
if i < 5:
headErr += err
elif i >= 500:
tailErr += err
worstTail = max(worstTail, err)
headErr /= 5.0
tailErr /= 100.0
echo &" streaming: 1st sample MSE = {firstErr:.6f}, first-5 MSE = {headErr:.6f}, " &
&"last-100 MSE = {tailErr:.6f}"
check "streaming: last-100 MSE << first-sample MSE (>=100x better)",
tailErr < firstErr / 100.0
check "streaming: running error keeps trending down (last-100 <= first-5)",
tailErr <= headErr
# Floor: ~2e-6 MSE is the lambda = 1e-3 ridge bias, not a learning failure.
check "streaming: last-100 MSE < 1e-4", tailErr < 1e-4
check "streaming: no single late sample worse than 100x the last-100 mean",
worstTail < tailErr * 100.0
# ── 4. forgetting factor tracks a drifting target ────────────────────────────
proc testForgetting() =
block:
## Target jumps sign/slope halfway through. Two numbers per net: the mean
## RMSE over all post-jump samples (transient included) and the tail RMSE
## (adaptation quality once it has settled). rho = 1 averages the whole
## history and never leaves the old function; rho > 1 must track.
let n = 800
proc drift(net: var ElmNet): tuple[mean, tail: float] =
var re = initRand(1)
var e2 = 0.0
var eTail = 0.0
for i in 0..<n:
let x = @[rand(re, 1.0) * 2.0 - 1.0]
let t = @[if i < n div 2: 2.0 * x[0] + 1.0 else: -1.5 * x[0] + 0.5]
discard net.train(x, t)
if i >= n div 2:
let e = (net.predict(x)[0] - t[0]) ^ 2
e2 += e
if i >= n - 200: eTail += e
(sqrt(e2 / float(n div 2)), sqrt(eTail / 200.0))
var plain = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.0)
var forget = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.02)
let ePlain = drift(plain)
let eForget = drift(forget)
echo &" drifting target, post-jump mean RMSE: rho=1.0 -> {ePlain.mean:.5f}, " &
&"rho=1.02 -> {eForget.mean:.5f}"
echo &" drifting target, post-jump TAIL RMSE: rho=1.0 -> {ePlain.tail:.5f}, " &
&"rho=1.02 -> {eForget.tail:.5f}"
check "forgetting: rho=1.02 halves the mean post-jump RMSE on a drifting target",
eForget.mean < ePlain.mean * 0.5
check "forgetting: rho=1.02 tracks the new target (tail RMSE >=20x better)",
eForget.tail < ePlain.tail / 20.0
check "forgetting: rho=1.02 settles on the new target (tail RMSE < 0.05)",
eForget.tail < 0.05
# ── 5. numerical guards ──────────────────────────────────────────────────────
proc testGuards() =
block:
var net = init(inputDim = 1, hiddenDim = 8, seed = 42)
for i in 0..<200:
let x = @[float(i) / 200.0 - 0.5]
discard net.train(x, @[2.0 * x[0]])
check "guards: net is sane after 200 clean updates", net.isSane()
# a NaN sample must be rejected without poisoning the net
let rejected = net.train(@[0.5], @[NaN])
check "guards: NaN target is rejected", not rejected
check "guards: net still sane after a rejected NaN sample", net.isSane()
check "guards: NaN input is rejected", not net.train(@[Inf], @[1.0])
check "guards: net still sane after Inf input", net.isSane()
# many updates with an extreme input: prediction must stay finite
var wild = init(inputDim = 1, hiddenDim = 8, seed = 42, rho = 1.01)
for i in 0..<5000:
let x = @[sin(float(i)) * 1e6]
discard wild.train(x, @[x[0]])
let p = wild.predict(x)
if p[0].classify in {fcNan, fcInf, fcNegInf}:
check "guards: prediction stays finite over 5000 wild updates", false
return
check "guards: prediction stays finite over 5000 wild updates",
classify(wild.predict(@[1.0])[0]) notin {fcNan, fcInf, fcNegInf}
# poisoned state is detected and reset away from
var broken = init(inputDim = 1, hiddenDim = 4, seed = 42)
discard broken.train(@[0.5], @[1.0])
broken.beta[0][0] = NaN
check "guards: isSane detects a poisoned beta", not broken.isSane()
check "guards: predict returns zeros instead of NaN",
broken.predict(@[0.5]) == @[0.0]
discard broken.train(@[0.5], @[1.0])
check "guards: training a poisoned net soft-resets it", broken.isSane() and
broken.resets > 0 and broken.samples == 1
broken.softReset()
check "guards: explicit softReset zeroes beta and P",
broken.samples == 0 and broken.beta[0][0] == 0.0 and
broken.P[0][0] == 1.0 / broken.lambda
# ── 6. seed reproducibility ──────────────────────────────────────────────────
proc testReproducible() =
block:
var a = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2)
var b = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2)
var c = init(inputDim = 2, hiddenDim = 12, seed = 4321, outputDim = 2)
var rng = initRand(17)
for i in 0..<50:
let x = @[rand(rng, 1.0), rand(rng, 1.0)]
let t = @[x[0] - x[1], 2.0 * x[0] + 3.0 * x[1]]
discard a.train(x, t)
discard b.train(x, t)
discard c.train(x, t)
let q = @[0.3, -0.7]
check "seed: same seed => identical predictions", a.predict(q) == b.predict(q)
check "seed: different seed => different predictions", a.predict(q) != c.predict(q)
check "activation: sigmoid option is actually used",
init(1, 12, seed = 1, act = eaSigmoid).act == eaSigmoid
var sg = init(inputDim = 1, hiddenDim = 12, seed = 1, act = eaSigmoid)
for i in 0..<300:
let x = @[float(i) / 300.0 - 0.5]
discard sg.train(x, @[2.0 * x[0]])
check "activation: sigmoid ELM also fits y=2x (RMSE < 0.05)",
rmse(sg, @[(x: @[-0.5], t: @[-1.0]), (x: @[0.5], t: @[1.0])]) < 0.05
proc main() =
echo "── linear fit ──"; testLinearFit()
echo "── streaming convergence ──"; testStreaming()
echo "── forgetting factor ──"; testForgetting()
echo "── numerical guards ──"; testGuards()
echo "── reproducibility ──"; testReproducible()
echo ""
if failures > 0:
echo &"{failures}/{checks} check(s) FAILED"
quit(1)
echo &"All {checks} ELM checks passed."
when isMainModule:
main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,325 @@
## 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."
+547
View File
@@ -0,0 +1,547 @@
## Offline tests for the WaveElm gun (common_libs/guns/waveelm.nim): the
## simulated expanding RING, the probe geometry, the polar bias learning and
## every guard path.
##
## Run: nim c -r --path:common_libs common_libs/tests/test_waveelm.nim
import std/[math, strformat, times, sequtils]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/elm
import guns/waveelm
import guns/linear
import gun_harness/offline_range
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
# ── a local WorldState builder (offline_range's mkState is private) ───────────
proc mkState(tick: int, ex, ey, eh, es: float, sx = 100.0, sy = 300.0,
id = 1, w = 800.0, h = 600.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: w, arenaHeight: h, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
proc finite(p: GunPrediction): bool =
classify(p.x) notin {fcNan, fcInf, fcNegInf} and
classify(p.y) notin {fcNan, fcInf, fcNegInf} and
classify(p.confidence) notin {fcNan, fcInf, fcNegInf}
# ── the target the learning tests fly ─────────────────────────────────────────
#
# A STRAIGHT RUN at 2 px/tick (a realistic tickRate-limited bot speed) that fits
# inside the arena for the whole run, so it never bounces. Straight, and never
# bouncing, for two reasons that are properties of ANY constant-velocity lead —
# the ring's and the old intercept's alike:
# * a target that TURNS: the lead is straight, so the base is wrong by more
# than BotRadius for the whole flight, no shot is ever a confirmed hit, no
# label is ever produced, and the gun learns nothing (asserted explicitly in
# `testSupervision`, not hidden by feeding it synthetic hits);
# * a target that BOUNCES off a wall: the lead is straight through the wall.
const
TrajSpeed = 2.0
TrajX0 = 150.0
TrajY = 300.0
proc trajPos(tick: int): tuple[x, y, heading: float] =
(TrajX0 + TrajSpeed * tick.float, TrajY, 0.0)
proc traj(tick: int): WorldState =
let (x, y, hd) = trajPos(tick)
mkState(tick, x, y, hd, TrajSpeed)
const
TruthLag* = 4.0 ## the turret-lag model the bench uses: the aim solution that
## was actually used is `TruthLag` ticks stale, by this gain
TruthGain* = 1.0
proc biasedTruth(tick: int, biasX, biasY: float): tuple[x, y: float] =
## Where the bullet really arrives, under the turret-lag model the gun is
## built to absorb: the aim in force was the solution for the target
## `TruthLag` ticks ago, so the truth is displaced by that much motion on top
## of the constant systematic `bias`.
let now = traj(tick)
let past = traj(tick - int(TruthLag))
(now.enemyX + biasX + TruthGain * (now.enemyX - past.enemyX),
now.enemyY + biasY + TruthGain * (now.enemyY - past.enemyY))
proc orbitState(tick: int, degPerTick: float, radius: float): WorldState =
## A hard-turning target: the regime in which the constant-velocity base has no
## supervision at all.
let a = degToRad(tick.float * degPerTick)
mkState(tick, 400.0 + radius * cos(a), 300.0 + radius * sin(a),
tick.float * degPerTick, TrajSpeed)
const
TrainTicks* = 200 ## learnLoop drives ticks 0 ..< TrainTicks
HeldOutTick* = TrainTicks + 5 ## a tick the net was never trained on
# ── 1. the power ladder and the 20 - 3*power bullet-speed formula ──────────────
proc testLadder() =
check "ladder: bulletSpeed(1.0) == 17.0 (20 - 3*power)", bulletSpeed(1.0) == 17.0
check "ladder: bulletSpeed(2.0) == 14.0", bulletSpeed(2.0) == 14.0
check "ladder: bulletSpeed(3.0) == 11.0", bulletSpeed(3.0) == 11.0
var allDistinct = true
for i in 0..<WaveRungs:
for j in i + 1..<WaveRungs:
if abs(bulletSpeed(WavePowers[i]) - bulletSpeed(WavePowers[j])) < 1e-9:
allDistinct = false
check "ladder: every rung is a distinct bullet speed", allDistinct
var legal = true
for p in WavePowers:
if p > 3.0: legal = false
check "ladder: every power is legal for Tank Royale (<= 3.0)", legal
# A wave on a STATIONARY target: each rung's ring reaches a different radius,
# so the three rungs measure the target at three different flight times. The
# contact radius is the smallest multiple of the rung speed within BotRadius of
# the true distance.
let ex = 500.0
let ey = 300.0
let d = hypot(ex - 100.0, ey - 300.0)
var hits: seq[RingHit]
# a stationary target, sampled long enough for the slowest rung's flight
var px = newSeq[float](200)
var py = newSeq[float](200)
for t in 0..<200: px[t] = ex; py[t] = ey
for p in WavePowers:
hits.add ringFire(100.0, 300.0, p, px, py, 0)
check "wave: every rung's ring intercepts a stationary in-range target",
hits[0].found and hits[1].found and hits[2].found
var threeRungs = true
for i in 0..<3:
if abs(hits[i].dist - d) > BotRadius: threeRungs = false
check &"wave: the three rungs measure the SAME {d:.1f} px target (all within BotRadius)",
threeRungs
check "wave: three rungs, three distinct contact ticks (three flight times)",
hits[0].tick != hits[1].tick and hits[1].tick != hits[2].tick
check "wave: the fastest rung contacts first", hits[0].tick < hits[2].tick
# ── 2. the ring: probe geometry, interception, decoding ───────────────────────
proc ey0(): float = 300.0 ## a stationary target's y, for the out-of-range block
proc testRing() =
# N derivation: no angular gap wider than a bot at the arena diagonal.
check &"ring: N = {RingProbes} for rMax = {RingRMax:.0f} px (800x600 diagonal)",
RingProbes == ringProbeCount(RingRMax)
check &"ring: the gap at rMax is {2.0*PI*RingRMax/RingProbes.float:.2f} px, inside BotRadius {BotRadius}",
2.0 * PI * RingRMax / RingProbes.float < BotRadius
check "ring: N grows with the range assumption (bigger map -> more probes)",
ringProbeCount(2000.0) > RingProbes and
ringProbeCount(500.0) <= RingProbes
# Interception is guaranteed for an in-range target, at ANY bearing and range.
var found = 0
var tried = 0
for deg in countup(0, 359, 7):
let a = degToRad(deg.float)
for r in [50.0, 150.0, 300.0, 500.0, 700.0, 950.0]:
let ex = 400.0 + r * cos(a)
let ey = 300.0 + r * sin(a)
let n = int(ceil(r / 11.0)) + 2
var px = newSeq[float](n)
var py = newSeq[float](n)
for t in 0..<n: px[t] = ex; py[t] = ey
let h = ringFire(400.0, 300.0, 3.0, px, py, 0)
inc tried
if h.found: inc found
check &"ring: {found}/{tried} in-range interceptions across 52 bearings x 6 ranges",
found == tried
# Decoding: a contact at (radius, bearing) IS the target's position.
block:
let ex = 400.0 + 321.0 * cos(degToRad(37.0))
let ey = 300.0 + 321.0 * sin(degToRad(37.0))
var px = newSeq[float](60); var py = newSeq[float](60)
for t in 0..<60: px[t] = ex; py[t] = ey
let h = ringFire(400.0, 300.0, 2.0, px, py, 0)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: decode(radius, bearing) lands within BotRadius of the target " &
&"({hypot(dx-ex, dy-ey):.2f} px)",
hypot(dx - ex, dy - ey) <= BotRadius
check "ring: the decoded bearing is the probe ray's bearing",
abs(h.bearing - degToRad(37.0)) <= PI / RingProbes.float
# Out of range: nothing is claimed.
block:
let ex = 400.0 + 1800.0
var px = newSeq[float](80); var py = newSeq[float](80)
for t in 0..<80: px[t] = ex; py[t] = ey0()
let h = ringFire(400.0, 300.0, 1.0, px, py, 0)
check "ring: no interception is claimed for an out-of-range target", not h.found
check "ring: an out-of-range contact reports NaN distance, not a number",
classify(h.dist) == fcNan
# Edge cases: no crash, no NaN, and an enemy ON the shooter is still hit (the
# first annulus at 17 px is inside the 18 px radius).
block:
var px = newSeq[float](200)
var py = newSeq[float](200)
for t in 0..<200: px[t] = 400.0; py[t] = 300.0
let h = ringFire(400.0, 300.0, 1.0, px, py, 0)
check "ring: an enemy at the shooter's own position is contacted, not NaN",
h.found and h.dist == bulletSpeed(1.0)
check "ring: a zero bullet speed (power 20/3) claims nothing",
not ringFire(400.0, 300.0, 20.0 / 3.0, px, py, 0).found
# a trajectory that ENDS before the ring can reach the enemy claims nothing
var fx = @[700.0, 700.0, 700.0]
var fy = @[300.0, 300.0, 300.0]
check "ring: a trajectory that runs out before contact claims nothing",
not ringFire(400.0, 300.0, 1.0, fx, fy, 0).found
# ── 3. ELM bias learning on a KNOWN systematic bias ───────────────────────────
#
# IMPORTANT — why the feedback is fed from the TRUE position and not from the
# prediction. The obvious driver (`actual = prediction + bias`) is a POSITIVE
# FEEDBACK LOOP under any implementation: the label is then `correction +
# bias`, so the net is trained to output strictly more than it just output, and
# it walks straight into the offset clamp. A real FeedbackEvent carries the
# enemy's actual position, which does not depend on what we aimed at, and that is
# what is fed here. (Measured: with the prediction-relative driver the net
# saturates at +-36 px within 40 ticks.)
proc learnLoop(g: var WaveElmGun, ticks: int, biasX, biasY: float,
feedHits = true, tick0 = 0): tuple[shots, hits: int] =
## Drive the gun over a moving target exactly as the harness would: one predict
## per rung per tick, then an event whose ACTUAL position is the target's TRUE
## position AT THE BULLET'S ARRIVAL (the ring's contact is a lead: it is the
## target's position `flight` ticks from now, which is where a bullet fired now
## lands) plus the systematic `bias`. `hit` is TRUE only when the target was
## inside BotRadius of the aim point — the virtual-bullet resolver's own
## criterion, and the reason a miss carries no label.
for i in 0..<ticks:
let t = tick0 + i
let st = traj(t)
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let truth = biasedTruth(t + k, (if feedHits: biasX else: 0.0),
(if feedHits: biasY else: 0.0))
let (ax, ay) = truth
let res = hypot(pr.x - ax, pr.y - ay)
let hit = feedHits and res <= BotRadius
inc result.shots
if hit: inc result.hits
g.onResult(FeedbackEvent(
prediction: pr, actualX: ax, actualY: ay,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: res, hit: hit, confidence: pr.confidence))
## RMS aim error of the gun over a held-out window, and of the RAW ring
## reconstruction it sits on (bias 0). The ELM earns its place only if the
## second is strictly worse than the first.
proc heldOutRms(g: var WaveElmGun, fromTick, n: int, biasX, biasY: float): float =
## The aim is scored against where the bullet ARRIVES: the ring's contact is a
## LEAD, so scoring it against the target's current position would charge the
## gun for the lead it is supposed to apply.
var sq = 0.0
for t in fromTick..<(fromTick + n):
let st = traj(t)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let (tx, ty) = biasedTruth(t + k, biasX, biasY)
sq += (pr.x - tx) ^ 2 + (pr.y - ty) ^ 2
sqrt(sq / (n.float * WaveRungs.float))
proc rawRms(fromTick, n: int, biasX, biasY: float): float =
## Same window, same bias, but a gun that never learned anything: the aim is
## the bare ring reconstruction.
var g = initWaveElmGun()
var sq = 0.0
for t in fromTick..<(fromTick + n):
let st = traj(t)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let (tx, ty) = biasedTruth(t + k, biasX, biasY)
sq += (pr.x - tx) ^ 2 + (pr.y - ty) ^ 2
sqrt(sq / (n.float * WaveRungs.float))
proc testLearning() =
block:
var g = initWaveElmGun()
let cnt = learnLoop(g, TrainTicks, 5.0, 0.0)
echo &" trained={g.trainedShots} traceMisses={g.traceMisses} " &
&"rejected={g.rejectedShots} misses={g.missShots} netSamples={g.net.samples} " &
&"rings={g.ringContacts}/{g.ringFires} hits={cnt.hits}/{cnt.shots}"
check "learning: every CONFIRMED hit trained (no fabricated, no lost samples)",
g.trainedShots == cnt.hits and g.traceMisses == 0
check "learning: misses are counted and never trained",
g.missShots + g.trainedShots + g.rejectedShots == cnt.shots
check "learning: the ring fired and found a contact on essentially every tick",
g.ringContacts >= g.ringFires - 2 and g.ringFires > 0
check "learning: net is still sane after 200 RLS updates", g.net.isSane()
# HELD-OUT window: the net has never seen these ticks.
let base = rawRms(TrainTicks, 60, 5.0, 0.0)
let got = heldOutRms(g, TrainTicks, 60, 5.0, 0.0)
echo &" held-out aim RMS vs truth (bias 5 px + turret lag): ring alone {base:.2f} px -> with the ELM {got:.2f} px"
# An ABSOLUTE margin, not a percentage: the bare ring's error on a given tick
# is dominated by the annulus quantisation (+-spd/2), which the bias happens
# to cancel or double, so a ratio threshold measures the target's luck.
check &"learning: the ELM beats the bare ring reconstruction ({got:.2f} < {base:.2f} px)",
got < base - 0.5
# LABEL SURVIVAL, the number the directed design was killed for: only
# confirmed hits carry a label, so the survival rate IS the interception
# rate. The directed design measured 21.5%.
let surv = cnt.hits.float / cnt.shots.float
echo &" label survival = {surv*100:.1f}% (directed design measured 21.5%)"
check &"learning: label survival beats the directed design ({surv*100:.1f}% > 21.5%)",
surv > 0.215
block:
# A 2-D bias: the two outputs are independent, neither steals the other.
var g = initWaveElmGun()
discard learnLoop(g, TrainTicks, -4.0, 7.0)
let st = traj(HeldOutTick)
let pr = g.predict(st, bulletSpeed(2.0))
echo &" 2-D bias, held-out correction: ({g.lastDx:.3f}, {g.lastDy:.3f}), truth (-4, 7)"
check "learning: the 2-D correction points along the bias it was trained on",
(g.lastDx * -4.0 + g.lastDy * 7.0) > 0.0
let base = rawRms(TrainTicks, 60, -4.0, 7.0)
let got = heldOutRms(g, TrainTicks, 60, -4.0, 7.0)
echo &" held-out aim RMS vs truth (bias (-4,7) + turret lag): ring alone {base:.2f} px -> with the ELM {got:.2f} px"
check &"learning: the ELM beats the bare ring on a 2-D bias too ({got:.2f} < {base:.2f} px)",
got < base - 0.5
proc testSupervision() =
## THE STARVATION LIMITATION, asserted rather than hidden: on a target that
## turns hard every tick the ring's constant-velocity base is wrong by more
## than BotRadius for the whole flight, so not one shot is a confirmed hit and
## the net gets no labels. The directed design had the same failure (its
## measured label survival was 21.5%); the ring's failure is sharper, because
## its base error grows with the turn.
block: # the straight-line target DOES supervise
var g = initWaveElmGun()
let c = learnLoop(g, TrainTicks, 5.0, 0.0)
echo &" straight target: labels {c.hits}/{c.shots} ({c.hits*100/c.shots}%)"
check "supervision: the straight-line target supervises the net (> 80% labels)",
c.hits.float / c.shots.float > 0.8
block: # a hard turner does not, and that is a documented ceiling
var g = initWaveElmGun()
var shots = 0
var hits = 0
for t in 0..<TrainTicks:
let st = orbitState(t, 6.0, 48.0)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let truth = orbitState(t + k, 6.0, 48.0)
let res = hypot(pr.x - truth.enemyX, pr.y - truth.enemyY)
inc shots
if res <= BotRadius: inc hits
g.onResult(FeedbackEvent(prediction: pr, actualX: truth.enemyX,
actualY: truth.enemyY, bulletPower: p, fireTick: t,
powerBin: waveBinForSpeed(bulletSpeed(p)), missDistance: res,
hit: res <= BotRadius, confidence: pr.confidence))
echo &" 6 deg/tick orbit: labels {hits}/{shots}"
check "supervision: a 6 deg/tick orbit yields no usable labels (known ceiling)",
hits == 0 and g.trainedShots == 0
# ── 4. guard paths ────────────────────────────────────────────────────────────
proc testGuards() =
block:
# Implausibly large residual: a "hit" 500 px from the aim point is not this
# gun's model, so it must never reach beta.
var g = initWaveElmGun()
discard learnLoop(g, 60, 5.0, 0.0)
let before = g.trainedShots
let st = mkState(500, 400.0, 300.0, 0.0, 5.0)
let big = 500.0
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# the label is (actual - ring reconstruction), so the residual is injected
# at the RECONSTRUCTION, not at the already-corrected aim point
let (bx, by) = ringDecode(g.ringFor(1), st.selfX, st.selfY)
g.onResult(FeedbackEvent(prediction: pr,
actualX: bx + big, actualY: by,
bulletPower: p, fireTick: 500, powerBin: waveBinForSpeed(spd),
hit: true, confidence: pr.confidence))
check &"guard: a {WaveMaxResidual:.0f} px residual is rejected ({big:.0f} px fed)",
g.trainedShots == before and g.rejectedShots == WaveRungs
check "guard: a residual exactly at the limit ({3.0*BotRadius:.0f} px) is still accepted",
(block:
var g2 = initWaveElmGun()
discard learnLoop(g2, 40, 0.0, 0.0)
let b2 = g2.trainedShots
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g2.predict(st, spd)
let (bx, by) = ringDecode(g2.ringFor(1), st.selfX, st.selfY)
let d = 3.0 * BotRadius - 0.001
g2.onResult(FeedbackEvent(prediction: pr,
actualX: bx + d, actualY: by,
bulletPower: p, fireTick: st.tick, powerBin: waveBinForSpeed(spd),
hit: true, confidence: pr.confidence))
g2.trainedShots > b2)
block:
# A MISS carries no label: it says the aim was wrong, not where.
var g = initWaveElmGun()
let c = learnLoop(g, 40, 0.0, 0.0, feedHits = false)
check "guard: misses are never trained on", g.trainedShots == 0
check "guard: misses are counted", g.missShots == c.shots
block:
# An orphaned event (no trace in the ring) must be counted, not fabricated.
var g = initWaveElmGun()
discard learnLoop(g, 10, 5.0, 0.0)
let st = mkState(77, 400.0, 300.0, 0.0, 5.0)
let pr = g.predict(st, bulletSpeed(2.0))
let before = g.trainedShots
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0, actualY: pr.y,
bulletPower: 2.0, fireTick: 999999, powerBin: 2, hit: true,
confidence: pr.confidence)) # orphan: the trace lookup fails first
check "guard: an orphaned hit (unknown fireTick) is counted, not fabricated",
g.trainedShots == before and g.traceMisses == 1
block:
# A brand new gun, no history at all.
var g = initWaveElmGun()
let st = mkState(0, 500.0, 300.0, 45.0, 6.0)
let pr = g.predict(st, bulletSpeed(1.0))
check "guard: a fresh bot with no scan history predicts without crashing",
pr.finite and pr.x > 0.0 and pr.y > 0.0
check "guard: a fresh bot is not warmed up (needs 2 scans for a velocity)",
not g.isWarmedUp()
let st2 = mkState(1, 506.0, 300.0, 45.0, 6.0)
discard g.predict(st2, bulletSpeed(1.0))
check "guard: two scans make it warm", g.isWarmedUp()
block:
# NaN / Inf must never escape the gun, in the state or in the net.
var g = initWaveElmGun()
let nan = 0.0 / 0.0
let inf = 1.0 / 0.0
for bad in [nan, inf, -inf]:
let st = mkState(1, bad, 300.0, bad, bad)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
if not pr.finite:
check &"guard: NaN/Inf in the state never escapes (bad={bad})", false
return
check "guard: NaN/Inf in the state never escapes the prediction", true
check "guard: features of a degenerate state are all finite",
(block:
let st = mkState(1, nan, nan, nan, nan)
let f = g.waveFeatures(st, 0.0, 0.0, 0.0)
var ok = true
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
ok)
# ── 5. Gun-concept conformance ────────────────────────────────────────────────
proc testGunConcept() =
var g = initWaveElmGun()
var x = 300.0
var y = 300.0
var sawDistinct = false
var last: seq[GunPrediction]
for t in 0..<12:
let st = mkState(t, x, y, 30.0, 6.0)
var preds: seq[GunPrediction]
for p in WavePowers: preds.add g.predict(st, bulletSpeed(p))
if last.len == preds.len and last.len > 0:
for i in 0..<preds.len:
if hypot(preds[i].x - last[i].x, preds[i].y - last[i].y) > 1.0:
sawDistinct = true
last = preds
for i, p in WavePowers:
let spd = bulletSpeed(p)
let pr = preds[i]
g.onResult(FeedbackEvent(prediction: pr,
actualX: pr.x + 6.0, actualY: pr.y - 2.0,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
hit: true, confidence: pr.confidence))
x += 5.2
check "gun: predict/onResult are a valid Gun pair (isGun template)",
isGun(WaveElmGun)
check "gun: the ring-tracked aim moves as the target moves", sawDistinct
check "gun: the wave trained on every rung", g.trainedShots == 12 * WaveRungs
check "gun: net sane", g.net.isSane()
# ── 6. it produces a usable aim point on every rung of a straight target ─────
proc testAgainstLinear() =
## Same convention as the other offline gun tests: replaying a stream through
## the real VirtualTracker is the online hit rate. Compared against Linear as
## the closed-form baseline.
var states: seq[WorldState]
var x = 100.0
for t in 0..<240:
states.add mkState(t, x, 300.0, 0.0, 4.0)
x = (x + 4.0).clamp(BotRadius, 800.0 - BotRadius)
var meta = initMeta(source = "synthetic")
meta.adversary = "constant-velocity"
meta.note = "constant-velocity reference stream for WaveElm"
let fx = initFixture(states, meta)
let reps = replayFixture(fx, @[makeDriver("WaveElm", initWaveElmGun()),
makeDriver("Linear", LinearGun())])
echo &" {reps[0].name} {reps[0].hits}/{reps[0].shots} ({reps[0].hitRate()*100:.1f}%)" &
&" {reps[1].name} {reps[1].hits}/{reps[1].shots} ({reps[1].hitRate()*100:.1f}%)"
check "replay: the wave was actually shot at over the whole stream",
reps[0].shots > 100
check "replay: WaveElm is not worse than the closed-form Linear baseline",
reps[0].hitRate() >= reps[1].hitRate() - 0.02
# ── 7. REGRESSION: non-finite state must not hang the gun ────────────────────
proc testNonFiniteState() =
## enemyHeading = ±Inf used to hang the bot outright: the angle wrap was
## `while hdelta > 180: hdelta -= 360`, and `Inf - 360.0 == Inf`, so the body
## made no progress and the loop never left (100% CPU, no output). Every FLOAT
## field of the state is now non-finite in turn, and predict must both return
## promptly and return finite numbers.
var g = initWaveElmGun()
let nan = 0.0 / 0.0
for (label, bad) in [("NaN", nan), ("+Inf", 1.0 / 0.0), ("-Inf", -1.0 / 0.0)]:
for field in ["enemyX", "enemyY", "enemyHeading", "enemySpeed",
"selfX", "selfY", "arenaWidth", "arenaHeight"]:
var st = mkState(3, 420.0, 260.0, 35.0, 5.0)
case field
of "enemyX": st.enemyX = bad
of "enemyY": st.enemyY = bad
of "enemyHeading": st.enemyHeading = bad
of "enemySpeed": st.enemySpeed = bad
of "selfX": st.selfX = bad
of "selfY": st.selfY = bad
of "arenaWidth": st.arenaWidth = bad
else: st.arenaHeight = bad
var ok = true
let t0 = epochTime()
for p in WavePowers:
if not g.predict(st, bulletSpeed(p)).finite: ok = false
let f = g.waveFeatures(st, 1.0, 1.0, 30.0)
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
check &"nonfinite: {label} in {field} -> finite prediction and features",
ok
check &"nonfinite: {label} in {field} returns promptly",
epochTime() - t0 < 1.0
when isMainModule:
testLadder()
testRing()
testLearning()
testSupervision()
testGuards()
testGunConcept()
testAgainstLinear()
testNonFiniteState()
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nAll WaveElm checks passed."
@@ -0,0 +1,287 @@
## test_waveelm_flighttime.nim — regression test for the LEFT/RIGHT OVERSHOOT,
## against the RING base (common_libs/guns/waveelm.nim).
##
## BUG (fixed by WaveResolveFeatures): a shot fired at tick T resolves at
## T + flightTime (the ring's contact, 3-90 ticks, far longer than the RLS memory
## 1/(rho-1) ~ 12 ticks). onResult trained the label -- which describes the aim
## bias at the ARRIVAL tick -- on the FIRE-time features. The net was therefore
## fitted to a map that extrapolates the bias a whole flight time forward, and
## then applied it to fire-time features, where it would only have to read it off.
## A short-memory RLS fits the bias to the target's PAST motion and swings the
## correction sideways as the target strafes: the reported "continuously
## overshooting left and right".
##
## WHAT IS ASSERTED: with the feedback DELAYED by the real flight time, the
## gun's aim error measured PERPENDICULAR to the true offset direction (the
## lateral / left-right component, the one the user saw) collapses. The
## perpendicular component is the oscillation: an along-track error is just an
## under/over-lead, a lateral one is the aim crossing to the other side.
##
## THE IDEAL CORRECTOR (the ground truth of the aim) is now the RING
## RECONSTRUCTION plus the turret-lag bias — the same quantity the bench
## (bench_waveelm_temporal.nim) uses, with the ring's decoding standing in for
## the intercept solver that used to provide the base.
##
## Run: nim c -r common_libs/tests/test_waveelm_flighttime.nim
import std/[math, strformat]
import gun_harness/gun_interface
import guns/waveelm
const
Ticks = 240
SelfX = 100.0
SelfY = 300.0
AW = 800.0
AH = 600.0
Lag = 4
BurnIn = 60
SelfR = BotRadius
type
Regime = enum rSmooth, rAccel, rAbrupt
Traj = object
px, py, hx, hy, sp, ox, oy: seq[float]
Pending = object
resolveAt: int
pr: GunPrediction
truthX, truthY: float ## where the target really is when the bullet lands
fireTick: int
binIdx: int
power: float
Metrics = object
perp: float ## RMS lateral (perpendicular) gun-only error, px
along: float ## RMS along-track gun-only error, px
hit: float ## fraction of shots that landed inside BotRadius
proc regimeName(r: Regime): string =
case r
of rSmooth: "smooth"
of rAccel: "accel"
of rAbrupt: "abrupt"
proc buildTraj(r: Regime): Traj =
result.px = newSeq[float](Ticks); result.py = newSeq[float](Ticks)
result.hx = newSeq[float](Ticks); result.hy = newSeq[float](Ticks)
result.sp = newSeq[float](Ticks)
var x = 400.0
var y = 300.0
var cmd = degToRad(20.0)
var act = cmd
for t in 0..<Ticks:
var speed, turn: float
case r
of rSmooth: speed = 4.0; turn = 3.0
of rAccel:
speed = 2.5 + 0.013 * t.float
turn = 2.0 + 0.018 * t.float
of rAbrupt:
speed = (if t < 150: 4.5 else: 5.5)
turn = (if t < 150: 3.0 else: -3.0)
if speed > 10.0: speed = 10.0
act = degToRad(round(radToDeg(act)) * 1.0)
result.px[t] = x; result.py[t] = y
result.hx[t] = cos(act); result.hy[t] = sin(act); result.sp[t] = speed
x += cos(cmd) * speed
y += sin(cmd) * speed
if x < 150 or x > AW - 150 or y < 150 or y > AH - 150:
cmd = arctan2(AH / 2 - y, AW / 2 - x)
else:
cmd = turn
let gain = proc(t: int): float =
case r
of rSmooth: 1.0
of rAccel: 0.9 + 0.0015 * t.float
of rAbrupt: (if t < 150: 1.0 else: 1.6)
result.ox = newSeq[float](Ticks); result.oy = newSeq[float](Ticks)
for t in 0..<Ticks:
let a = max(0, t - Lag)
result.ox[t] = gain(t) * (result.px[t] - result.px[a])
result.oy[t] = gain(t) * (result.py[t] - result.py[a])
proc mkState(t: int, x, y, hx, hy, sp: float): WorldState =
WorldState(
enemyX: x, enemyY: y,
enemyHeading: radToDeg(arctan2(hy, hx)), enemySpeed: sp, enemyEnergy: 100,
selfX: SelfX, selfY: SelfY, arenaWidth: AW, arenaHeight: AH, tick: t,
enemies: @[EnemyInfo(id: 1, x: x, y: y, energy: 100,
heading: radToDeg(arctan2(hy, hx)), speed: sp,
lastSeenTick: t)])
proc base(g: WaveElmGun, sx = SelfX, sy = SelfY): tuple[x, y: float] =
## THE RING RECONSTRUCTION: the gun's aim with NO learned correction. This is
## what the intercept solver used to provide and what the ELM's offset sits on.
ringDecode(g.ringFor(1), sx, sy)
## The live loop, faithfully: predict at tick t, the label comes back `flight`
## ticks later, and only a HIT is trained on.
proc run(r: Regime, resolveFeat: bool): Metrics =
let tj = buildTraj(r)
var g = initWaveElmGun(resolveFeat = resolveFeat)
var pend: seq[Pending] = @[]
var sqPerp = 0.0
var sqAlong = 0.0
var n = 0
var hits = 0
var shots = 0
for t in 0..<Ticks:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# the ring's own contact tick, clamped into the trajectory
let ring = g.ringFor(1)
let tof = if ring.valid: max(1, min(Ticks - 1, ring.flight.int))
else: 1
let ta = min(Ticks - 1, t + tof)
let (bx, by) = g.base()
let hitX = clamp(bx + tj.ox[ta], BotRadius, AW - BotRadius)
let hitY = clamp(by + tj.oy[ta], BotRadius, AH - BotRadius)
inc shots
# GUN-ONLY error: what the gun produced against what an IDEAL corrector
# would produce at the FIRE tick (ring reconstruction + bias(t)),
# decomposed along and across the true offset direction.
if t >= BurnIn:
let ix = clamp(bx + tj.ox[t], BotRadius, AW - BotRadius)
let iy = clamp(by + tj.oy[t], BotRadius, AH - BotRadius)
let um = hypot(tj.ox[t], tj.oy[t])
if um > 1.0:
let ex = pr.x - ix
let ey = pr.y - iy
sqAlong += ((ex * tj.ox[t] + ey * tj.oy[t]) / um) ^ 2
sqPerp += ((ex * -tj.oy[t] + ey * tj.ox[t]) / um) ^ 2
inc n
pend.add Pending(resolveAt: t + tof, pr: pr, truthX: hitX, truthY: hitY,
fireTick: t, binIdx: waveBinForSpeed(spd), power: p)
# HARNESS ORDER, and it matters: the bullets are resolved AFTER predict, so
# the flight-time feature refresh (which runs inside predict, for the traces
# due on THIS tick) has already rebuilt their features before onResult trains
# on them. Resolving before predict would silently test the un-refreshed path
# and make the A/B below a no-op.
var keep: seq[Pending] = @[]
for p in pend:
if p.resolveAt <= t:
let res = hypot(p.truthX - p.pr.x, p.truthY - p.pr.y)
let didHit = res <= BotRadius
if didHit: inc hits
g.onResult(FeedbackEvent(
prediction: p.pr, actualX: p.truthX, actualY: p.truthY,
bulletPower: p.power, fireTick: p.fireTick, powerBin: p.binIdx,
missDistance: res, hit: didHit, confidence: p.pr.confidence))
else:
keep.add p
pend = keep
if n > 0:
result.perp = sqrt(sqPerp / n.float)
result.along = sqrt(sqAlong / n.float)
result.hit = (if shots > 0: hits.float / shots.float else: 0.0)
# ── the assertions ───────────────────────────────────────────────────────────
var failures = 0
proc check(name: string, ok: bool, detail: string) =
if ok: echo " ok ", name, " — ", detail
else:
echo " FAIL ", name, " — ", detail
inc failures
block:
echo "── flight-time feature mismatch: lateral (left-right) aim error ──"
echo " (diagnostic A/B: the right column is the fix forced OFF, i.e. what"
echo " the gun did before; the ASSERTIONS below are on the SHIPPED default)"
for r in Regime:
let on = run(r, resolveFeat = WaveResolveFeatures)
let off = run(r, resolveFeat = false)
echo &" {regimeName(r):<7} default: perp={on.perp:6.2f} along={on.along:6.2f} hit={on.hit*100:6.2f}%" &
&" | fire-time feats (before): perp={off.perp:6.2f} along={off.along:6.2f} hit={off.hit*100:6.2f}%"
# The oscillation is the LATERAL component: an along-track error is just an
# under/over-lead, a lateral one is the aim crossing to the other side.
case r
of rSmooth: check("smooth: lateral error stays negligible",
on.perp < 1.0, &"{on.perp:.2f} px")
of rAccel: check("accel: lateral error under 8 px (was 10.9 px without the refresh)",
on.perp < 8.0, &"{on.perp:.2f} px")
of rAbrupt: check("abrupt: lateral error under 3 px (was 1.6 px without the refresh)",
on.perp < 3.0, &"{on.perp:.2f} px")
check(&"{regimeName(r)}: hit rate does not regress",
on.hit >= off.hit, &"{on.hit*100:.2f}% vs {off.hit*100:.2f}%")
check(&"{regimeName(r)}: the ring intercepts enough shots to supervise at all",
on.hit > 0.0, &"{on.hit*100:.2f}%")
block:
# The fix must be a NO-OP when the feedback is not delayed (the offline
# benchmark's shape): then the fire tick IS the label tick and there is nothing
# to realign.
echo "── no-op when the label arrives on the fire tick ──"
let r = rAccel
let tj = buildTraj(r)
var a = initWaveElmGun(resolveFeat = true)
var b = initWaveElmGun(resolveFeat = false)
for t in 0..<120:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pa = a.predict(st, spd)
let pb = b.predict(st, spd)
let (bx, by) = a.base()
let truthX = clamp(bx + tj.ox[t], BotRadius, AW - BotRadius)
let truthY = clamp(by + tj.oy[t], BotRadius, AH - BotRadius)
let ev = FeedbackEvent(
prediction: pa, actualX: truthX, actualY: truthY, bulletPower: p,
fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: hypot(truthX - pa.x, truthY - pa.y),
hit: true, confidence: pa.confidence)
a.onResult(ev)
b.onResult(FeedbackEvent(
prediction: pb, actualX: truthX, actualY: truthY,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: hypot(truthX - pb.x, truthY - pb.y),
hit: true, confidence: pb.confidence))
check("identical corrections when feedback is undelayed",
a.lastDx == b.lastDx and a.lastDy == b.lastDy,
&"({a.lastDx:.6f},{a.lastDy:.6f}) vs ({b.lastDx:.6f},{b.lastDy:.6f})")
block:
# the trace must still be FOUND at the arrival tick (the refresh must not
# break the (fireTick, binIdx) lookup) -- i.e. no label is lost to it.
echo "── probe bookkeeping survives the refresh ──"
let tj = buildTraj(rSmooth)
var g = initWaveElmGun()
var pend: seq[Pending] = @[]
var lost = 0
for t in 0..<Ticks:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
let ring = g.ringFor(1)
let tof = if ring.valid: max(1, min(Ticks - 1, ring.flight.int)) else: 1
let ta = min(Ticks - 1, t + tof)
let (bx, by) = g.base()
pend.add Pending(
resolveAt: t + tof, pr: pr,
truthX: clamp(bx + tj.ox[ta], BotRadius, AW - BotRadius),
truthY: clamp(by + tj.oy[ta], BotRadius, AH - BotRadius),
fireTick: t, binIdx: waveBinForSpeed(spd), power: p)
# resolve after predict, as the harness does (see the note in `run`)
var keep: seq[Pending] = @[]
for p in pend:
if p.resolveAt <= t:
let res = hypot(p.truthX - p.pr.x, p.truthY - p.pr.y)
let before = g.trainedShots
g.onResult(FeedbackEvent(
prediction: p.pr, actualX: p.truthX, actualY: p.truthY,
bulletPower: p.power, fireTick: p.fireTick, powerBin: p.binIdx,
missDistance: res, hit: res <= BotRadius, confidence: p.pr.confidence))
if g.trainedShots == before and res <= BotRadius: inc lost
else:
keep.add p
pend = keep
check("no confirmed hit lost to the trace lookup", lost == 0,
&"{lost} hits lost, {g.trainedShots} trained, {g.traceMisses} trace misses")
echo (if failures == 0: "\nALL OK" else: &"\n{failures} FAILURE(S)")
quit(if failures == 0: 0 else: 1)
@@ -0,0 +1,120 @@
## ONLINE REAL-BATTLE check for the WAVEELM gun (rack id 18,
## `common_libs/guns/waveelm.nim` — the online-ELM gun).
##
## It answers one question the offline suites cannot: does the LIVE ModularBot
## actually DISCOVER and USE the gun? Two short battles (3 rounds each, the
## `maxSpeed` default) force WAVEELM alone in the rack with env vars only —
## `TR_RACK_WAVEELM=both`, every other gun `off` — against the two shared
## adversaries: SittingDuck (passive) and OscillatorBot (fights back).
##
## Each battle is read from the bot's own per-round gun dump
## (`GUN_STATS_PATH`), and the gun is only "discovered and used" if the live
## loop SPAWNED virtual bullets for id 18 (vShots > 0) and the live selector
## SELECTED it (selected > 0).
##
## Run:
## TR_SERVER_JAR=... TR_BATTLE_RUNNER=... \
## nim c -r common_libs/tests/test_waveelm_rack_live.nim
##
## Skips (exit 0) when the TR JARs are absent, matching the other live tests.
import std/[os, json, strutils]
import test_framework/test_framework
import gun_harness/selector
import gun_harness/virtual_bullets
const
repoRoot = currentSourcePath().parentDir.parentDir.parentDir
modularBotDir = repoRoot / "ModularBot_garage"
adversariesDir = repoRoot / "common_libs" / "test_framework" / "adversaries"
statsPath = "/tmp/waveelm_rack_stats.jsonl"
const WaveElmId = 18
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc lastRound(path: string): JsonNode =
result = nil
for line in lines(path):
let s = line.strip()
if s.len == 0: continue
let node = parseJson(s)
if node.hasKey("guns"): result = node
proc runOne(adversary: string) =
let advDir = adversariesDir / adversary
if not dirExists(advDir):
echo "Skipping: adversary not found: ", advDir
quit(0)
if fileExists(statsPath): removeFile(statsPath)
# Force the new gun alone: every other rack entry off, WAVEELM in both racks.
for i, name in RackGunNames:
putEnv("TR_RACK_" & name, if i == WaveElmId: "both" else: "off")
putEnv("GUN_STATS_PATH", statsPath)
defer:
for name in RackGunNames: delEnv("TR_RACK_" & name)
delEnv("GUN_STATS_PATH")
echo "=== live: ModularBot (only WAVEELM racked) vs ", adversary, ", 3 rounds ==="
let battle = runBattle(@[modularBotDir, advDir], rounds = 3)
for res in battle.results:
echo " ", res.name, " rank=", res.rank, " score=", res.totalScore
if not fileExists(statsPath):
echo "FAIL: no gun_stats dump at ", statsPath
inc failures
return
let round = lastRound(statsPath)
check adversary & ": gun_stats.jsonl has a round record", round != nil
if round == nil: return
var shots = 0
var selected = 0
var otherSelected = 0
for g in round["guns"]:
if g["id"].getInt() == WaveElmId:
shots = g["vShots"].getInt()
selected = g["selected"].getInt()
elif g["selected"].getInt() > 0:
otherSelected += g["selected"].getInt()
echo "gun ", WaveElmId, " (WaveElm): vShots=", shots, " selected=", selected,
" other-gun selections=", otherSelected
check adversary & ": the live loop SPAWNED virtual bullets for gun 18 (vShots > 0)",
shots > 0
check adversary & ": the live selector SELECTED gun 18 (selected > 0)",
selected > 0
check adversary & ": no other gun was selected while WAVEELM was forced alone",
otherSelected == 0
proc main() =
let serverJar = getEnv("TR_SERVER_JAR", "")
let runnerJar = getEnv("TR_BATTLE_RUNNER", "")
if serverJar.len == 0 or runnerJar.len == 0:
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
if not fileExists(serverJar) or not fileExists(runnerJar):
echo "Skipping: TR JARs not found (server=", serverJar, ", runner=", runnerJar, ")"
quit(0)
if not fileExists(modularBotDir / "src" / "ModularBot.nim"):
echo "Skipping: ModularBot source not found"
quit(0)
check "rack: WAVEELM is registered at id 18", RackGunNames[WaveElmId] == "WAVEELM"
check "rack: WAVEELM ships `off`, like every gun except Pattern",
ActiveRackMembership[WaveElmId] == rmOff
runOne("SittingDuck")
runOne("OscillatorBot")
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nWaveElm live rack check passed."
when isMainModule:
main()
+331
View File
@@ -0,0 +1,331 @@
## test_waveelm_ring.nim — the SIMULATED EXPANDING RING, on its own terms.
##
## Everything here tests `ringFire` / `ringProbeCount` / the gun's scan-only ring,
## NOT the ELM on top of it (common_libs/tests/test_waveelm.nim covers that):
##
## (a) interception is GUARANTEED for an in-range enemy, across bearings, ranges
## and motion — the 100% claim, asserted rather than assumed;
## (b) the radius -> distance decoding is correct against known geometry;
## (c) N directions leave no angular gap wider than a bot at maximum range;
## (d) nothing is claimed for an enemy that is out of range (or unreachably
## fast, or behind a wall the ring cannot be said to have passed);
## (e) the ELM's bias correction converges OFFLINE on a synthetic bias;
## (f) edge cases: enemy at the shooter's own position, at maximum range, at
## zero velocity — no crash, no NaN, no unbounded loop;
## (g) SCAN-ONLY LEGITIMACY: the live ring's entire input is the selected scan
## plus the velocity derived from that same target's own last two scans.
##
## Run: nim c -r common_libs/tests/test_waveelm_ring.nim
import std/[math, strformat, sequtils]
import gun_harness/gun_interface
import guns/elm
import guns/waveelm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc fin(x: float): bool = classify(x) notin {fcNan, fcInf, fcNegInf}
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
sx = 400.0, sy = 300.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, arenaWidth: 800.0, arenaHeight: 600.0, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
type Traj = object
px, py: seq[float]
## A straight-line trajectory long enough for the slowest rung's flight.
proc trajLine(x0, y0, vx, vy: float, n: int): Traj =
result.px = newSeq[float](n)
result.py = newSeq[float](n)
for t in 0..<n:
result.px[t] = x0 + vx * t.float
result.py[t] = y0 + vy * t.float
# ── (c) the probe count ──────────────────────────────────────────────────────
proc testProbeCount() =
check &"probes: N = {RingProbes} is derived, not hardcoded",
RingProbes == ringProbeCount(RingRMax)
check &"probes: rMax = the {RingArenaW:.0f}x{RingArenaH:.0f} diagonal = {RingRMax:.1f} px",
abs(RingRMax - hypot(RingArenaW, RingArenaH)) < 1e-9
let gap = 2.0 * PI * RingRMax / RingProbes.float
check &"probes: angular gap at max range is {gap:.2f} px < BotRadius {BotRadius}",
gap < BotRadius
check "probes: the raw minimum N = 2*pi*rMax/BotRadius is 350 for 800x600",
int(ceil(2.0 * PI * 1000.0 / BotRadius)) == 350
check "probes: a bigger map yields more probes, a smaller one fewer",
ringProbeCount(2000.0) > RingProbes and
ringProbeCount(400.0) < RingProbes
check "probes: the gap is inside a bot at the SMALL map's diagonal too",
2.0 * PI * hypot(500.0, 300.0) / ringProbeCount(hypot(500.0, 300.0)).float < BotRadius
check "probes: a degenerate range still yields a usable probe count",
ringProbeCount(0.0) >= 60 and ringProbeCount(-5.0) >= 60
check "probes: the bearings cover the full circle without a seam",
abs(RingDirs[0]) < 1e-12 and
abs(RingDirs[RingProbes - 1] - 2.0 * PI * (RingProbes - 1).float /
RingProbes.float) < 1e-12
# the worst gap is between ADJACENT probes: no bearing has a wider one
var worst = 0.0
for i in 0..<RingProbes:
let a = RingDirs[i]
let b = RingDirs[(i + 1) mod RingProbes]
worst = max(worst, if i == RingProbes - 1: 2.0 * PI - a + b else: b - a)
check &"probes: the widest adjacent gap is {worst*RingRMax:.2f} px at max range",
worst * RingRMax < BotRadius
# ── (a) interception is guaranteed ───────────────────────────────────────────
proc testInterception() =
block: # static targets, every bearing, every range
var found = 0
var tried = 0
var worstRadial = 0.0
for deg in countup(0, 359, 3):
let a = degToRad(deg.float)
for r in [BotRadius, 50.0, 137.0, 300.0, 601.0, 900.0, RingRMax]:
let tj = trajLine(400.0 + r * cos(a), 300.0 + r * sin(a), 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 2.0, tj.px, tj.py, 0)
inc tried
if h.found:
inc found
worstRadial = max(worstRadial, abs(h.dist - r))
check &"ring: {found}/{tried} static interceptions (120 bearings x 7 ranges)",
found == tried
check &"ring: every measurement is within BotRadius of the true range (worst {worstRadial:.2f} px)",
worstRadial <= BotRadius
block: # a MOVING target, faster than the slowest rung, every bearing
var found = 0
var tried = 0
for deg in countup(0, 359, 11):
let a = degToRad(deg.float)
# every velocity is SLOWER than the 11 px/tick rung of this block, which is
# the condition for interception to be guaranteed at all (a target fleeing
# faster than the ring expands is physically unreachable — see
# testNoClaim / the "faster than the bullet" case below)
for (vx, vy) in [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0), (-7.0, 3.0)]:
let tj = trajLine(400.0 + 300.0 * cos(a), 300.0 + 300.0 * sin(a),
vx, vy, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
inc tried
if h.found: inc found
check &"ring: {found}/{tried} moving interceptions (33 bearings x 4 velocities)",
found == tried
block: # a target fleeing at close to the bullet's speed: the ring closes only
# `spd - v` px/tick, so whether it is reached inside the ring's reach is
# an arithmetic question, and the ring must answer it honestly in BOTH
# directions (caught -> contact; out of reach -> nothing claimed).
var caught = 0
var fled = 0
for vx in [-15.0, -12.0, 12.0, 15.0]:
let tj = trajLine(200.0, 300.0, vx, 0.0, 400)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
# The target starts 200 px WEST of the shooter, so vx > 0 is APPROACHING:
# the gap closes at (17 + vx) px/tick, and the contact is reachable only if
# the 200 px close within the ring's own reach (maxK = rMax/17 ticks).
let reachable = 200.0 / (17.0 + vx) <= RingRMax / 17.0
if h.found: inc caught
if not h.found and not reachable: inc fled
check &"ring: a target at vx={vx:.0f} px/tick -> " &
(if h.found: "intercepted" else: "correctly out of reach"),
h.found == reachable
check &"ring: the slow-flee cases are intercepted and the fast-flee ones are not",
caught == 3 and fled == 1
# ── (b) decoding ─────────────────────────────────────────────────────────────
proc testDecoding() =
for r in [60.0, 250.0, 640.0]:
for deg in countup(0, 350, 17):
let a = degToRad(deg.float)
let ex = 400.0 + r * cos(a)
let ey = 300.0 + r * sin(a)
let tj = trajLine(ex, ey, 0.0, 0.0, 300)
let h = ringFire(400.0, 300.0, 2.0, tj.px, tj.py, 0)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: decode at r={r:.0f} deg={deg} is within BotRadius of the target",
h.found and hypot(dx - ex, dy - ey) <= BotRadius
if not (h.found and hypot(dx - ex, dy - ey) <= BotRadius): break
# a moving target: the contact is its position at the FLIGHT TIME, which is the
# lead a bullet fired now must be given.
block:
let tj = trajLine(400.0, 300.0, 6.0, 0.0, 300)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
let k = float(h.tick)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: the decoding is the target's position at the contact tick " &
&"(k={k.int}, err={hypot(dx - tj.px[k.int], dy - tj.py[k.int]):.2f} px)",
h.found and hypot(dx - tj.px[k.int], dy - tj.py[k.int]) <= BotRadius
check "ring: the flight time is reported in ticks, not as an absolute tick",
h.tick > 0 and h.tick < 100 and fin(h.dist) and fin(h.bearing)
# ── (d) out of range, and the other "no" cases ───────────────────────────────
proc testNoClaim() =
block:
let tj = trajLine(400.0 + RingRMax + 250.0, 300.0, 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
check "ring: nothing is claimed past the ring's reach", not h.found
check "ring: a missed ring reports NaN distance, not a plausible number",
classify(h.dist) == fcNan and fin(h.missDist)
block:
# receding faster than the ring expands, starting inside the reach: the ring
# never catches it, and the ring says so.
let tj = trajLine(900.0, 300.0, 20.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
check "ring: a target outrunning the ring is NOT claimed", not h.found
block:
# the trajectory ends before contact
let tj = trajLine(600.0, 300.0, 0.0, 0.0, 2)
check "ring: a trajectory that ends early is not claimed",
not ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0).found
check "ring: a fire tick past the end of the trajectory is not claimed",
not ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 5).found
# ── (f) edge cases ───────────────────────────────────────────────────────────
proc testEdgeCases() =
block: # enemy ON the shooter
let tj = trajLine(400.0, 300.0, 0.0, 0.0, 100)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
check "edge: an enemy at the shooter's own position is contacted on tick 1",
h.found and h.tick == 1 and abs(h.dist - 17.0) < 1e-9
let (dx, dy) = ringDecode(h, 400.0, 300.0)
# it decodes to the first annulus (radius 17 px along bearing 0), not to the
# shooter's own point — the ring measures a DISC, and a disc of radius 18
# centred on the shooter is touched by the 17 px annulus.
check "edge: and it decodes to the touched annulus (17 px out), without NaN",
fin(dx) and fin(dy) and abs(hypot(dx - 400.0, dy - 300.0) - 17.0) < 1e-9
block: # zero velocity
let tj = trajLine(700.0, 300.0, 0.0, 0.0, 200)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
check "edge: a zero-velocity target is intercepted normally",
h.found and fin(h.dist) and fin(h.bearing) and fin(h.missDist)
block: # maximum range, both extremes of the ladder
for p in WavePowers:
let tj = trajLine(400.0 + RingRMax, 300.0, 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, p, tj.px, tj.py, 0)
check &"edge: a target at exactly rMax is intercepted on power {p}",
h.found and abs(h.dist - RingRMax) <= BotRadius
block: # non-finite input to the LIVE ring
var g = initWaveElmGun()
let nan = 0.0 / 0.0
let inf = 1.0 / 0.0
for bad in [nan, inf, -inf]:
let st = mkState(1, bad, bad, bad, bad)
let h = g.ringFireFromScan(st, bad, bad, 17.0)
check &"edge: a NaN/Inf scan makes the live ring claim nothing, not crash",
(not h.found) or (fin(h.dist) and fin(h.bearing))
let h0 = g.ringFireFromScan(mkState(1, 600.0, 300.0, 0.0, 5.0), 5.0, 0.0, 0.0)
check "edge: a zero bullet speed claims nothing", not h0.found
# ── (g) SCAN-ONLY LEGITIMACY ─────────────────────────────────────────────────
proc testScanOnly() =
## PROOF, not a promise: the live ring is fed a WorldState and reads the
## SELECTED SCAN. Every other enemy's information in `state.enemies` is
## replaced with garbage — and the ring's output does not move. If the ring
## were using omniscient positions (or any other enemy's), this fails.
var g1 = initWaveElmGun()
var g2 = initWaveElmGun()
var decoy1 = 700.0
var decoy2 = 120.0
for t in 0..<40:
let ex = 300.0 + 4.0 * t.float
var st1 = mkState(t, ex, 300.0, 0.0, 4.0, id = 1)
var st2 = mkState(t, ex, 300.0, 0.0, 4.0, id = 1)
# a second enemy, in two different places, with different velocities
st1.enemies.add EnemyInfo(id: 7, x: decoy1, y: 100.0, heading: 90.0,
speed: 9.0, energy: 100.0, lastSeenTick: t)
st2.enemies.add EnemyInfo(id: 7, x: decoy2, y: 500.0, heading: 270.0,
speed: 1.0, energy: 100.0, lastSeenTick: t)
discard g1.predict(st1, bulletSpeed(1.0))
discard g2.predict(st2, bulletSpeed(1.0))
decoy1 = (decoy1 + 9.0) mod 700.0
decoy2 = (decoy2 - 1.0).mod(700.0)
let r1 = g1.ringFor(1)
let r2 = g2.ringFor(1)
check "scan-only: the ring is byte-identical when every OTHER enemy moves",
r1.dist == r2.dist and r1.bear == r2.bear and r1.tick == r2.tick
# The tracked target is pinned by the rack (targetId), so the ring follows the
# PINNED enemy and not `enemies[0]` either.
block:
var g = initWaveElmGun()
for t in 0..<20:
var st = mkState(t, 300.0 + 3.0 * t.float, 200.0, 0.0, 3.0, id = 1)
st.enemies.add EnemyInfo(id: 9, x: 700.0, y: 100.0, heading: 0.0,
speed: 5.0, energy: 100.0, lastSeenTick: t)
g.targetId = 9
discard g.predict(st, bulletSpeed(1.0))
g.targetId = -1
check "scan-only: with the rack pinning id 9 the ring measures id 9's state",
g.ringFor(9).valid and not g.ringFor(1).valid
# ── (e) the ELM's bias correction converges offline ──────────────────────────
proc testElmConverges() =
## The gun, driven over a straight target (the only regime in which a
## constant-velocity base gets any supervision at all — see
## common_libs/tests/test_waveelm.nim `testSupervision`), with a constant
## systematic bias fed back as CONFIRMED hits. The learned correction must
## converge on it and stay there.
const Speed = 2.0
var g = initWaveElmGun()
var labels = 0
var misses = 0
let (biasX, biasY) = (6.0, -3.0)
for t in 0..<300:
let x = 150.0 + Speed * t.float
let st = mkState(t, x, 300.0, 0.0, Speed)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(1, int(round(g.ringFor(1).flight)))
let ax = 150.0 + Speed * (t + k).float + biasX
let ay = 300.0 + biasY
let res = hypot(pr.x - ax, pr.y - ay)
let hit = res <= BotRadius
if hit: inc labels else: inc misses
g.onResult(FeedbackEvent(prediction: pr, actualX: ax, actualY: ay,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(bulletSpeed(p)),
missDistance: res, hit: hit, confidence: pr.confidence))
echo &" offline convergence: {labels} labels, {misses} misses, " &
&"net samples {g.net.samples}, correction ({g.lastDx:.2f}, {g.lastDy:.2f}) " &
&"(true bias ({biasX}, {biasY}))"
check "elm: the ring supervises the net on a straight target (> 80% labels)",
labels.float / (labels + misses).float > 0.8
check &"elm: the correction converges on the {biasX:.0f}/{biasY:.0f} px bias (< 2 px)",
hypot(g.lastDx - biasX, g.lastDy - biasY) < 2.0
check "elm: no soft reset was needed on a clean stream", g.net.resets == 0
check "elm: the net is sane", g.net.isSane()
# ... and it STAYS there: a cold gun is strictly worse on the same tick.
var cold = initWaveElmGun()
let st = mkState(400, 150.0 + Speed * 400.0, 300.0, 0.0, Speed)
let warm = g.predict(st, bulletSpeed(2.0))
let (cx, cy) = ringDecode(g.ringFor(1), st.selfX, st.selfY)
discard cold.predict(st, bulletSpeed(2.0))
let cool = cold.predict(st, bulletSpeed(2.0))
check "elm: the converged gun aims closer to the biased truth than a cold one",
hypot(warm.x - (cx + biasX), warm.y - (cy + biasY)) <
hypot(cool.x - (cx + biasX), cool.y - (cy + biasY))
when isMainModule:
echo "── (c) probe count ──"; testProbeCount()
echo "── (a) interception ──"; testInterception()
echo "── (b) decoding ──"; testDecoding()
echo "── (d) out of range ──"; testNoClaim()
echo "── (f) edge cases ──"; testEdgeCases()
echo "── (g) scan-only ──"; testScanOnly()
echo "── (e) ELM offline ──"; testElmConverges()
if failures > 0:
echo "\n", failures, " of ", checks, " check(s) FAILED"
quit(1)
echo &"\nAll {checks} WaveElm-ring checks passed."
+354
View File
@@ -0,0 +1,354 @@
## Offline tests for the TEMPORAL extensions of the WaveElm gun:
## (A) the lag-window feature map (guns/waveelm.nim, WaveLagK / waveFeatures)
## (B) the RELM recurrent hidden layer (guns/elm.nim, r / hPrev / predictStep)
## covered here, plus the per-enemy / per-episode state reset and the
## train-on-the-stored-activation path.
##
## Everything is offline and bounded: no server, no java, no runBattle, and
## every loop count is a small constant.
##
## Run: nim c -r common_libs/tests/test_waveelm_temporal.nim
import std/[math, strformat, tables]
import gun_harness/gun_interface
import guns/elm
import guns/waveelm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc fin(x: float): bool =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc allFinite(s: seq[float]): bool =
for v in s:
if not fin(v): return false
true
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
sx = 100.0, sy = 300.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: 800.0, arenaHeight: 600.0, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
# ── (A) the lag window ───────────────────────────────────────────────────────
proc testLagWindow() =
check "lag: waveInputDim(2) is the legacy 10", waveInputDim(2) == 10
check "lag: waveInputDim(4) == 10 + 2*(4-2)", waveInputDim(4) == 14
check "lag: waveInputDim(8) == 10 + 2*(8-2)", waveInputDim(8) == 22
check "lag: WaveTrackCap covers the longest window", WaveTrackCap >= WaveLagKMax + 1
check "lag: init clamps the window to [2, WaveLagKMax]",
initWaveElmGun(42, lagK = 1).lagK == 2 and
initWaveElmGun(42, lagK = 99).lagK == WaveLagKMax
block:
# A straight run of scans: one tick apart, +6 px in x each tick. Every
# window slot must hold THAT tick's displacement / 16 px.
var g = initWaveElmGun(42, lagK = 4)
check "lag: the net is as wide as the window", g.net.inputDim == 14
var f: seq[float]
for t in 0..<6:
let st = mkState(t, 300.0 + 6.0 * t.float, 300.0, 0.0, 6.0)
discard g.predict(st, 17.0)
f = g.waveFeatures(st, 6.0, 0.0, 30.0)
check "lag: the feature vector is exactly waveInputDim(4) long", f.len == 14
var ok = true
for k in 0..<4:
if abs(f[4 + 2 * k] - 6.0 / 16.0) > 1e-12: ok = false
if abs(f[5 + 2 * k] - 0.0) > 1e-12: ok = false
check &"lag: all 4 window slots hold their own displacement / 16 (t={6})", ok
check "lag: the staleness/flight slots moved to the end of the window",
abs(f[4 + 2 * 4] - 0.0) < 1e-12 and f[5 + 2 * 4] > 0.0
block:
# The base 8 features must not depend on the window: a lagK=4 gun fed the
# same scans must agree with a legacy lagK=2 gun on slots 0..7.
var g4 = initWaveElmGun(42, lagK = 4)
var g2 = initWaveElmGun(42, lagK = 2)
for t in 0..<5:
let st = mkState(t, 300.0 + 5.0 * t.float, 300.0 + t.float, 12.0, 5.0)
discard g4.predict(st, 17.0)
discard g2.predict(st, 17.0)
let f4 = g4.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
let f2 = g2.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
var same = true
for i in 0..<8:
if abs(f4[i] - f2[i]) > 1e-12: same = false
check "lag: the base features are unchanged by the window (slots 0..7)", same
block:
# Fewer scans than the window: the missing slots must be ZERO, not garbage.
var g = initWaveElmGun(42, lagK = 6)
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
let f = g.waveFeatures(mkState(0, 300.0, 300.0, 0.0, 5.0), 5.0, 0.0, 30.0)
check "lag: a window longer than the scan history reads zeros",
f.len == waveInputDim(6) and
(block:
var ok = true
for i in 0..<f.len:
if not fin(f[i]): ok = false
ok)
block:
# A late scan (gap = 2 ticks) must be normalised PER TICK, or the window
# silently measures the radar cadence instead of the target.
var g = initWaveElmGun(42, lagK = 2)
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
discard g.predict(mkState(2, 312.0, 300.0, 0.0, 6.0), 17.0) # 12 px in 2 ticks
let f = g.waveFeatures(mkState(2, 312.0, 300.0, 0.0, 6.0), 6.0, 0.0, 30.0)
check &"lag: a 2-tick gap is normalised to px/tick (6/16 = {6.0/16.0})",
abs(f[4] - 6.0 / 16.0) < 1e-12
# ── (B) the RELM recurrence ──────────────────────────────────────────────────
proc testRelm() =
block:
# Gain 0 must be EXACTLY the legacy feed-forward net: g = act(W x + b).
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
recurrentGain = 0.0)
check "relm: gain 0 leaves the net non-recurrent", not net.recurrent()
check "relm: gain 0 leaves every r_j at 0",
(block:
var ok = true
for v in net.r:
if v != 0.0: ok = false
ok)
let x = @[0.3, -0.7, 0.11]
var manual = newSeq[float](8)
for h in 0..<8:
var s = net.b[h]
for i in 0..<3: s += net.W[h][i] * x[i]
manual[h] = tanh(s)
check "relm: gain 0 reproduces act(W x + b) exactly", net.hidden(x) == manual
block:
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
recurrentGain = 0.5)
check "relm: gain > 0 makes the net recurrent", net.recurrent()
check "relm: every |r_j| is inside the contraction range [0, ElmRMax]",
(block:
var ok = true
for v in net.r:
if abs(v) > ElmRMax or abs(v) >= 1.0: ok = false
ok)
check "relm: the recurrence is seeded (not all identical gains)",
(block:
var varies = false
for i in 1..<net.r.len:
if net.r[i] != net.r[0]: varies = true
varies)
block:
# predict is READ-ONLY, predictStep ADVANCES the clock exactly once.
var net = init(inputDim = 2, hiddenDim = 6, seed = 7, outputDim = 1,
recurrentGain = 0.6)
let x = @[0.5, -0.2]
# beta starts at ZERO, so an untrained net predicts 0 whatever the state
# is: train it first or this test would be comparing 0.0 to 0.0.
for i in 0..<20:
let v = float(i) / 20.0
discard net.train(@[v, -v], @[2.0 * v])
let p1 = net.predict(x)
let p2 = net.predict(x)
check "relm: predict does not advance the hidden state", p1 == p2
discard net.predictStep(x)
let p3 = net.predict(x)
check "relm: predictStep advances the state (the next prediction differs)",
p1 != p3
block:
# STABILITY: the contraction argument says |h| <= 1 and no NaN, whatever
# the input does. Wild-but-plausible inputs first (20000 steps): nothing may
# blow up at all, not even a soft reset.
var net = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
var sane = true
var bounded = true
for i in 0..<20000:
let m = if i mod 2 == 0: 20.0 else: -20.0
let y = net.predictStep(@[m, sin(float(i) * 0.01) * m])
discard net.train(@[m, float(i mod 7).float], @[y[0]])
if not net.isSane() or not allFinite(y): sane = false
for h in net.hPrev:
if not fin(h) or abs(h) > 1.0: bounded = false
check "relm: 20000 steps of +-20 stay finite and sane", sane
check "relm: |h| never leaves tanh's range [-1, 1] (the clamp holds)", bounded
# The pre-existing RLS guard soft-resets on an ill-conditioned stream; what
# matters is whether the RECURRENCE causes MORE of them than the identical
# feed-forward loop does. Same seed, same inputs, only r_j differs.
var ff = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = 0.0)
for i in 0..<20000:
let m = if i mod 2 == 0: 20.0 else: -20.0
let y = ff.predictStep(@[m, sin(float(i) * 0.01) * m])
discard ff.train(@[m, float(i mod 7).float], @[y[0]])
echo &" soft resets on the same 20000 steps: RELM {net.resets}, " &
&"feed-forward {ff.resets}"
check "relm: the recurrence does not add a single soft reset",
net.resets <= ff.resets
# Absurd inputs (1e3) DO trip the pre-existing RLS blow-up guard, which
# soft-resets and carries on. What must hold is that the RECURRENCE does
# not diverge: the prediction stays finite and the state stays in range.
var net2 = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
var sane2 = true
var bounded2 = true
for i in 0..<20000:
let m = if i mod 2 == 0: 1.0e3 else: -1.0e3
let y = net2.predictStep(@[m, sin(float(i) * 0.01) * m])
discard net2.train(@[m, float(i mod 7).float], @[y[0]])
if not allFinite(y): sane2 = false
for h in net2.hPrev:
if not fin(h) or abs(h) > 1.0: bounded2 = false
check "relm: 20000 steps of +-1e3 stay finite", sane2
check "relm: the hidden state stays bounded even at +-1e3", bounded2
block:
# The RLS must still reject bad samples on the hidden-vector entry point.
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.4)
let g = net.hidden(@[0.5])
check "relm: trainHidden rejects a NaN hidden vector",
not net.trainHidden(@[NaN, 0.5, 0.5, 0.5], @[1.0])
check "relm: trainHidden rejects a NaN target", not net.trainHidden(g, @[NaN])
check "relm: the net survives both rejections", net.isSane() and net.samples == 0
block:
# A poisoned recurrence must be DETECTED, not propagated.
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
net.r[0] = NaN
check "relm: isSane detects a NaN recurrent gain", not net.isSane()
var net2 = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
net2.r[0] = 1.5
check "relm: isSane rejects a gain outside the contraction range",
not net2.isSane()
# ── per-enemy / per-episode state reset ──────────────────────────────────────
proc testStateReset() =
block:
# A new target is a new SEQUENCE: its first activation must be computed
# from h(0) = 0, not from whatever the previous target left behind.
var g = initWaveElmGun(42, lagK = 4, relm = 0.6)
var x = 300.0
for t in 0..<8:
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 1)
discard g.predict(st, 17.0)
x += 5.0
check "reset: the RELM state is non-zero after a run of ticks",
(block:
var live = false
for h in g.net.hPrev:
if h != 0.0: live = true
live)
# Same scan stream, new enemy id -> the first activation must equal the one
# a FRESH net would produce (i.e. the state really was cleared).
var h = initWaveElmGun(42, lagK = 4, relm = 0.6)
x = 300.0
for t in 0..<8:
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 2)
discard h.predict(st, 17.0)
x += 5.0
# The strongest form of the claim: after the id change, gun A (which has
# just been running another target) must produce BYTE-IDENTICAL aim points
# to a fresh gun B that has only ever seen the new target. Any residue of
# the old sequence — node state, learned beta, scan track — would break it.
let st4 = mkState(9, x, 300.0, 0.0, 5.0, id = 4)
var fresh = initWaveElmGun(42, lagK = 4, relm = 0.6)
var same = true
for p in WavePowers:
let a = h.predict(st4, bulletSpeed(p))
let b = fresh.predict(st4, bulletSpeed(p))
if a.x != b.x or a.y != b.y or a.confidence != b.confidence: same = false
check "reset: a new enemy id starts its sequence from h(0) = 0", same
check "reset: the target change was actually seen (tracks differ)",
h.tracks.hasKey(2) and h.tracks.hasKey(4)
block:
# Per-episode reset clears the state but KEEPS what was learned.
var g = initWaveElmGun(42, lagK = 2, relm = 0.5)
var x = 300.0
for t in 0..<30:
let st = mkState(t, x, 300.0, 0.0, 5.0)
let pr = g.predict(st, 17.0)
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 4.0,
actualY: pr.y, bulletPower: 1.0, fireTick: t, powerBin: 0,
hit: true, confidence: pr.confidence))
x += 5.0
let samples = g.net.samples
let learned = g.net.beta[0][0]
g.resetTemporalState()
var cleared = true
for v in g.net.hPrev:
if v != 0.0: cleared = false
check "reset: resetTemporalState zeroes h(t-1)", cleared
check "reset: it keeps the learned beta and the RLS state",
g.net.samples == samples and g.net.beta[0][0] == learned
check "reset: a RELM gun still trains on the stored activation",
samples == g.trainedShots
# ── end to end with everything on ────────────────────────────────────────────
proc testEndToEnd() =
var g = initWaveElmGun(42, lagK = 8, relm = 0.3)
var x = 200.0
var y = 300.0
var finite = true
for t in 0..<120:
let st = mkState(t, x, y, 30.0, 5.0)
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
if not (fin(pr.x) and fin(pr.y) and fin(pr.confidence)): finite = false
# resolve immediately, so every trace is trained on its own activation
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0,
actualY: pr.y - 1.0, bulletPower: p, fireTick: t,
powerBin: waveBinForSpeed(spd), hit: true, confidence: pr.confidence))
x = (x + 5.0).clamp(BotRadius, 800.0 - BotRadius)
y = (y + 1.0).clamp(BotRadius, 600.0 - BotRadius)
check "e2e: lagK=8 + RELM 0.3 produces only finite aim points", finite
# A rung trains unless its trace lookup missed or the residual gate rejected it
# as implausible (this target accelerates across the arena, so the ring's
# constant-velocity base is not within 3*BotRadius of the truth every tick).
check &"e2e: every rung is accounted for (trained {g.trainedShots} + rejected " &
&"{g.rejectedShots} + misses {g.missShots} + traceMisses {g.traceMisses})",
g.trainedShots + g.rejectedShots + g.missShots + g.traceMisses == 120 * WaveRungs
check "e2e: the great majority of rungs train", g.trainedShots > (120 * WaveRungs) div 2
check "e2e: the net is still sane", g.net.isSane()
check "e2e: no soft reset was needed", g.net.resets == 0
# Degenerate state with every extension on must still not hang or leak NaN.
var h = initWaveElmGun(42, lagK = 8, relm = 0.9)
let nan = 0.0 / 0.0
var ok = true
for bad in [nan, 1.0 / 0.0, -1.0 / 0.0]:
let st = mkState(3, bad, bad, bad, bad, id = 7)
for p in WavePowers:
let pr = h.predict(st, bulletSpeed(p))
if not fin(pr.x): ok = false
let f = h.waveFeatures(st, bad, bad, bad)
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
check "e2e: NaN/Inf state never escapes with lagK=8 + RELM 0.9", ok
check "e2e: the net survives it", h.net.isSane()
when isMainModule:
echo "── (A) lag window ──"; testLagWindow()
echo "── (B) RELM ──"; testRelm()
echo "── state reset ──"; testStateReset()
echo "── end to end ──"; testEndToEnd()
if failures > 0:
echo "\n", failures, " of ", checks, " check(s) FAILED"
quit(1)
echo &"\nAll {checks} WaveElm-temporal checks passed."