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:
@@ -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).
|
||||
Executable
+52
@@ -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"
|
||||
@@ -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
@@ -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
|
||||
Reference in New Issue
Block a user