68 Commits

Author SHA1 Message Date
SirStone d3e4540e7f chore: add missing OscillatorBot.nimble 2026-08-27 18:42:35 +02:00
SirStone 259e67d7ff chore: standardize internal bot dir structure (src/, tests/, out/)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-27 18:42:03 +02:00
SirStone c5115fdf61 chore: standardize Nim builds to out/ subdir, simplify .gitignore
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-27 18:35:54 +02:00
SirStone e276548223 chore: remove exported/ from AGENTS.md, generalize binary ignores in .gitignore
- Removed non-existent exported/ directory from layout docs
- Replaced hardcoded bot binary entries with *_garage/out/ pattern for build directories
- Added all known bot binaries (GotoTest, OscillatorBot, PPO_Bot, QBot, SAC_LSTM_Bot)
  to .gitignore with clarifying comment about Nim's compilation target structure

Nim places compiled binaries at bot root (no extension) and in out/ subdirs.
The out/ pattern catches all build outputs; specific bot binaries listed for
root-level executables since gitignore lacks a reliable "no-extension files" glob.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-27 18:32:09 +02:00
SirStone 2097c2e6fa chore: gitignore binaries/artifacts, remove drafts and stale files 2026-08-27 18:28:21 +02:00
SirStone 06ed905033 docs(AGENTS): generalize layout rules, remove hardcoded bot list 2026-08-27 18:22:38 +02:00
SirStone eab85be8b3 docs(AGENTS): update directory layout to match current structure 2026-08-27 18:19:37 +02:00
SirStone b509195ee9 chore: rename libs→common_libs, all bot dirs to _garage suffix, fix all path refs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-27 18:18:41 +02:00
SirStone f8c0c871c6 chore: remove unused prototypes/ and spike/ dirs 2026-08-27 18:16:34 +02:00
SirStone b9877bfff5 chore: add .gitignore 2026-08-27 18:12:08 +02:00
SirStone 8ba4bae21a chore: rename CLAUDE.md → AGENTS.md, move research doc to docs/ 2026-08-27 18:11:56 +02:00
SirStone f5b1ade48c fix(dashboard): harden generation against common failures 2026-08-24 11:10:39 +02:00
SirStone 12a0eca44a docs(dashboard): add health-check reference section 2026-08-24 10:18:43 +02:00
SirStone 08d1c44ca8 docs(dashboard): add how-to-read guide per panel 2026-08-24 09:25:14 +02:00
SirStone f47925eeb0 fix(dashboard): remove redundant standalone alpha panel 2026-08-24 09:22:54 +02:00
SirStone 55d69a9352 fix(dashboard): dual y-axis for losses+alpha panel 2026-08-24 09:21:43 +02:00
SirStone 4a6e3347c6 feat(dashboard): max-score-per-eval-cycle panel 2026-08-24 09:15:24 +02:00
SirStone 8872be3ff6 fix(dashboard): add alpha temperature to training losses panel 2026-08-24 09:10:46 +02:00
SirStone 8eb7c53dd0 fix(dashboard): remove broken unused win%-per-opponent panel 2026-08-24 09:05:41 +02:00
SirStone 51e7f33ecb fix(dashboard): plot live campaign-4 logs; derive ROOT from script location 2026-08-24 08:30:04 +02:00
SirStone d2d205e6f6 Merge branch 'research/ga-parameters' into research/goto-controller 2026-08-24 08:23:25 +02:00
SirStone 3851f28cc5 Merge branch 'worktree-agent-a556517b' into research/goto-controller 2026-08-24 08:23:22 +02:00
SirStone 6241c41e52 Merge branch 'worktree-agent-a4c06ae3' into research/goto-controller 2026-08-24 08:23:19 +02:00
SirStone 156b4ae8db Merge branch 'worktree-agent-af671e69' into research/goto-controller 2026-08-24 08:23:12 +02:00
SirStone eee48dec38 prototype: GA evolution spike -- sin(x) prediction validates pipeline (#66)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-24 08:14:36 +02:00
SirStone eb8faa7c99 prototype: GA evolution spike -- sin(x) prediction validates pipeline (#66)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-24 08:14:32 +02:00
SirStone 96065597c0 fix(divergence): guard reward-normalizer cold start; drop arctanh recovery
Welford variance-collapse divided by 1e-8 producing bit-exact +/−5e8 /
+−1.25e8 poisoned rewards into TD targets; guard skips normalization
until stats meaningful; tanh-inversion removal bounds log-prob path.

Fixes #60.
2026-08-24 01:03:04 +02:00
SirStone cb1bbc35dc docs(adr): Evo_Bot neuroevolution gun architecture (#63)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-24 00:02:47 +02:00
SirStone b7b10af811 feat: OscillatorBot sparring partner for GA gun testing (#64)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-24 00:01:38 +02:00
SirStone e455566c8e docs: CONTEXT.md — Evo_Bot domain vocabulary (#62)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-24 00:00:21 +02:00
SirStone eae6fc15a2 research(Evo_Bot): GA/ES parameter recommendations for ~750-weight neuroevolution (#65)
Extracted concrete numbers from 13 papers in docs/papers/neuroevolution/.
Key findings: use CMA-ES or mutation-only truncation GA, mutate ALL weights
(not 5%), sigma=0.005-0.01, pop=64-200, no crossover, single elite.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-23 23:32:10 +02:00
SirStone 81718e3a4c fix(SAC_LSTM_Bot): un-invert dashboard axes — orientation selftest added 2026-08-23 10:47:48 +02:00
SirStone 04c149ea28 refactor(SAC_LSTM_Bot): reconcile graph tooling — dashboard-only output 2026-08-23 10:30:16 +02:00
SirStone 533a146342 feat(SAC_LSTM_Bot): live campaign dashboard — five panels, auto-reload, run-1 comparison dropped 2026-08-23 10:25:51 +02:00
SirStone 03a1853e57 feat(SAC_LSTM_Bot): embedded plain-English reading guides in graphs 2026-08-23 10:11:44 +02:00
SirStone 002a568c7e fix(SAC_LSTM_Bot): atomic+validated SVG output for progress graphs 2026-08-23 10:06:05 +02:00
SirStone f3ac0888bb feat(SAC_LSTM_Bot): readable eval chart — trends primary, raw dots secondary, v1 comparison separated 2026-08-23 09:59:30 +02:00
SirStone 0b0933294a feat(SAC_LSTM_Bot): progress graph tooling + first graphs 2026-08-23 09:08:53 +02:00
SirStone 781e41595e docs(SAC_LSTM_Bot): simple-words story + dictionary for readability 2026-08-23 08:48:37 +02:00
SirStone 40e074e5a3 docs(SAC_LSTM_Bot): lever-5 trigger + attempt-3 chapter — MA-wipe root cause, LR_CRITIC=1e-4 decision, launch health (#59 #60) 2026-08-23 07:11:09 +02:00
SirStone 167bcc4ce5 fix(SAC_LSTM_Bot): MA history self-truncation — read before > redirect; campaign v2 attempt-3 prep (#60)
$(cat f) inside a command redirected to f saw the already-truncated file,
so every eval cycle wiped ma_history_*.txt back to one leading-space value
and degraded the composite best-gate to last-cycle mean. Read is hoisted
into its own statement; unquoted expansion + tail -n keeps exactly the last
MA_WINDOW values. Verified: fresh/5+/6+ cycle edges reproduce sliding window.
2026-08-23 07:02:36 +02:00
SirStone 1619b86f25 docs(SAC_LSTM_Bot): v2 restart saga, twin-freeze correction, pacing decisions 2026-08-22 21:26:24 +02:00
SirStone 19f34abf0c fix(SAC_LSTM_Bot): freeze mirror-twin via eval-mode gate in twin launcher
SACLSTM_EVAL_MODE=1 in SacTwin.sh suppresses all sendTrainingMsg traffic
(lever-4 gate), so the twin never trains — not even in-RAM within a battle.
Required now that the main bot's SACLSTM_SAVE_INTERVAL drops to 1 (v2 relaunch
after checkpoint-cadence diagnosis): without the gate the twin would persist
per-battle drift and stop being the frozen reproducible opponent #54 specifies.
2026-08-22 21:09:07 +02:00
SirStone bd58794b4c docs(SAC_LSTM_Bot): campaign v2 chapter — locked config, fresh-start archive, twin reseed, ceiling net, launch health evidence (#59) 2026-08-22 20:31:33 +02:00
SirStone 6fc01eb4e5 feat(SAC_LSTM_Bot): campaign v2 levers — aggression/anti-ram reward shaping + stability knob overrides (part 2)
Lever 2 (#59): x1.25 aggression mult on damage dealt, flat +0.5 hit bonus,
-3.0 per bot-bot collision (server deals RAM_DAMAGE=0.6 to both parties but
only notifies the hitter), escalating proximity deterrent below 12% arena
diagonal suppressed while dealing damage. Win/loss terminals unchanged and
dominant. All weights TUNABLE consts marked ponytail. SACLSTM_REWARD_DEBUG=1
env-gated reward_debug.log for calibration greps.

Lever 5 (#59): no code needed — SACLSTM_LR_ACTOR/LR_CRITIC/LR_ALPHA (3e-4)
and SACLSTM_TARGET_ENTROPY (-4.0) were already env-overridable in training.nim.

Smoke vs RamFire+Crazy (hidden=32, random init, isolated weights): 75 ram
penalties, 381 charge events, hit bonuses firing, 0 crashes, metrics JSONL
flowing. Tests: 8/8 suites green incl. new assert-level term math.
2026-08-22 19:44:58 +02:00
SirStone a07e5305f5 feat(SAC_LSTM_Bot): campaign v2 levers — loss metrics, eval-mode gate, eval rotation + MA gating (part 1)
Levers 3, 4, 1 of the #57 sign-off (execution order 3->4->1), tracked in #59.

- Lever 3 (#59): one JSONL line per trainPass in training_metrics.jsonl with
  exactly the scalars sacUpdate already exposes (SACMetrics: critic/actor/alpha
  losses + alpha, averaged per pass) plus epoch, buffer size (replay_buffer.len),
  cumulative steps and drained count. No trainer change needed.
- Lever 4 (#59): sendTrainingMsg drops all training input while SACLSTM_EVAL_MODE=1
  (existing #49 harness mechanism) — eval battles can neither pollute the replay
  buffer nor trigger gradient updates; one-time stderr notice at bot init.
- Lever 1 (#59): sac_train.sh evaluates every SAC_EVAL_OPPONENTS entry per cycle
  (results carry opponent name in eval_log.jsonl); best-gating now uses a
  composite = mean over opponents of the last-5-evals moving average per
  opponent. best_score.txt format change: float composite replaces the
  single-opponent integer win rate semantics (retired).
- Tests: metricsLine JSONL scalars + eval-mode suppression asserts.

Refs: #59, #57
2026-08-22 18:58:47 +02:00
SirStone 2619ba06fc docs(SAC_LSTM_Bot): campaign ending, results table, verdict, hygiene (#57) 2026-08-22 14:40:57 +02:00
SirStone f45e8f2717 fix(SAC_LSTM_Bot): startup sweep of stale .part checkpoint corpses (#57) 2026-08-22 14:40:57 +02:00
SirStone b7492f1080 docs(SAC_LSTM_Bot): notebook — score:60 anatomy, .part forensics+sweep, ceiling defused 2026-08-22 08:08:31 +02:00
SirStone f1962c7506 docs(SAC_LSTM_Bot): backfill shift-1 milestone entry + morning audit 2026-08-22 07:27:37 +02:00
SirStone 05929d2dbd docs(SAC_LSTM_Bot): notebook — shift 1, deferred-intervention milestone 2026-08-22 07:14:35 +02:00
SirStone 4b64bf18ac docs(SAC_LSTM_Bot): campaign-v1 launch record — save-check incident, health check, check-in procedure (#56) 2026-08-22 00:31:47 +02:00
SirStone 26536713ba fix(SAC_LSTM_Bot): checkpoint save check inside gradient-step loop (#56)
Launch finding during campaign-v1 verification: at production sizes
(hidden 256, ~1s/step, ~13s trainer CPU per ~40s chunk process) the
save check ran only between drain-burst passes, so stepCount never
crossed nextSave before the process died — zero checkpoints persisted
across entire runs (masked at #49/#54 smoke sizes where steps were
sub-millisecond). Check now fires mid-loop; with SAVE_INTERVAL<=5
(within the per-process step budget) every chunk persists its chain.
2026-08-22 00:21:43 +02:00
SirStone 2f49cb243f docs(SAC_LSTM_Bot): campaign-v1 notebook — locked config + story so far (#56) 2026-08-21 23:26:31 +02:00
SirStone 6a294ad7ad feat(SAC_LSTM_Bot): mirror-twin sparring partner + readiness check (#54)
- make_twin.sh: generates self-contained SacTwin dir in the sample-bots
  archive (own json/sh identity, own weights dir seeded from a frozen
  sac_best.zip copy, own round_counter) so RunTraining.java resolves it
  like any sample bot; re-running resets the twin to the frozen baseline.
- src/SAC_LSTM_Bot.nim: SACLSTM_BOT_JSON env overrides the baked-in bot
  json (loadBotInfo gives json total precedence, #49) so the same binary
  boots under the twin's name.
- sac_train.sh: chunk loop is a while, not for-over-seq — a crash on the
  FINAL chunk previously fell through ((chunk--);continue on an exhausted
  seq list) and exited 0 with budget incomplete; observed live vs SacTwin.

Readiness dry-run (#54): weighted pool Corners:1,SacTwin:3 picked the twin
in 3/4 chunks; all battles counter-checked; deterministic eval parsed;
main sac_best.zip/counter untouched by twin (twin counter advanced
independently); crash-restart proven end-to-end incl. final-chunk retry.
2026-08-21 23:19:27 +02:00
SirStone edf26aa45d fix(SAC_LSTM_Bot): enforce MaxHidden cap on SACLSTM_HIDDEN_SIZE (review of #48/#49) 2026-08-21 22:17:55 +02:00
SirStone df256b4d3e feat(SAC_LSTM_Bot): training harness (#49)
sac_train.sh orchestrates chunked self-play via tools/training_runner/
RunTraining.java: weighted opponent sampling per chunk, deterministic
eval (SACLSTM_EVAL_MODE=1) every N chunks with win-rate tracking, best
checkpoint (weights/sac_best.zip) by eval score, crash-restart loop on
the runner's liveness detection.

Supporting changes:
- integration.nim: opponentKey() keys the NewBattle buffer-clear rule on
  getBotName(id) with numeric-id fallback (#49 Q14 follow-up);
  bumpRoundCounter() emits the per-round liveness signal.
- SAC_LSTM_Bot.nim: onRoundEnded -> bumpRoundCounter().
- RunTraining.java: BOT_NAME env parameterizes result matching
  (default PPO_Bot, unchanged behavior for PPO).
- Launch packaging: root SAC_LSTM_Bot.json + .sh for the booter;
  src json name aligned to 'SAC_LSTM_Bot' so self-reported identity
  matches the booted identity (mismatch = runner connect timeout).
2026-08-21 21:51:27 +02:00
SirStone 7104645f5d chore(deps): update vendored tankroyale botapi to v1.0.1
Syncs libs/tankroyale_botapi with SirStone/robocode_tankroyale_botapi
v1.0.1 (extracted from tank-royale nim branch @ 03195a814). The local
SIGSEGV fixes (static event queue/SVG/intent buffers) were already
ported upstream in issue #24 — content is otherwise identical.

New capability (upstream #23): opponent name exposure for ticket #49.
- bot.nim: gBotNames id→name table + getBotName(id) / updateBotNames()
- umbrella module: dispatch BotListUpdate messages to updateBotNames()

Vendored layout and wiring unchanged (--path via config.nims, module
name stays tankroyale_botapi).
2026-08-21 21:03:17 +02:00
SirStone 32b71d9fc8 feat(SAC_LSTM_Bot): main bot integration (#48) 2026-08-21 20:19:05 +02:00
SirStone 62a6cc8ccf fix(SAC_LSTM_Bot): training review fixes — hidden state ordering, redundant forwards, actor grad clip (#47)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-21 00:16:47 +02:00
SirStone 415d4e3738 feat(SAC_LSTM_Bot): SAC training module (#47)
Implements sacUpdate with burn-in LSTM warm-up, twin-critic TD update,
actor reparameterization gradient, auto-alpha, and soft target update.
Manual backprop (linear + LSTM single-step, truncated BPTT). 11 new tests
all green; full regression suite (57+ tests) unaffected.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-21 00:11:35 +02:00
SirStone 717ef3ead8 Merge branch 'worktree-agent-a8622248' (ticket #46 weight persistence) 2026-08-20 23:57:53 +02:00
SirStone 54b8139b11 feat(SAC_LSTM_Bot): weight persistence module (#46)
Save/load all SAC-LSTM tensors (actor, 2 critics, 2 target critics,
alpha, Adam states) into a single .zip of .npy files. Atomic write
via temp path + rename. Adam types (AdamVar, SACAdamStates) defined
here for training.nim to use.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-20 23:57:13 +02:00
SirStone 55ef22ff8b Merge branch 'worktree-agent-a3ca3066' (ticket #45 replay buffer) 2026-08-20 23:41:23 +02:00
SirStone 5ea57bcae3 Merge branch 'worktree-agent-a393a8b9' (ticket #44 reward module) 2026-08-20 23:41:23 +02:00
SirStone cb33551621 feat(SAC_LSTM_Bot): replay buffer module (#45)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-20 23:40:17 +02:00
SirStone 4ee0d8272c feat(SAC_LSTM_Bot): action mapping module (#43)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-20 23:38:45 +02:00
SirStone add3e34926 feat(SAC_LSTM_Bot): LSTM network module (#41)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-20 23:38:17 +02:00
851 changed files with 9555 additions and 252 deletions
+36
View File
@@ -0,0 +1,36 @@
# Compiled output
*.out
# Python cache
__pycache__/
*.pyc
*.pyo
# Log files
*.log
# Training logs
*.jsonl
# Test binaries (but keep .nim source files)
**/tests/test_*
!**/tests/test_*.nim
!**/tests/test_*.nims
# User-specific dev environment
.envrc
devbox.json
devbox.lock
# Compiled bot binaries — all builds go to *_garage/out/
*_garage/out/
# Java compiled classes
*.class
# Log and snapshot directories
**/logs/
**/snapshots/
# Git worktrees
worktrees/
+47
View File
@@ -0,0 +1,47 @@
## Agent skills
### Issue tracker
Gitea Issues at git.fossellini.top:SirStone/SirRoboGarage. See `docs/agents/issue-tracker.md`.
### Triage labels
Default label vocabulary. See `docs/agents/triage-labels.md`.
### Domain docs
Single-context layout. See `docs/agents/domain.md`.
### Folders
## SirGarage Directory Layout
**SirGarage** (root directory)
- `botname_garage/` — each bot gets its own directory following this pattern
- src/
- botname.nim
- botname.json
- botname.sh
- config.nim
- botname/ — bot-specific modules
- *.nim files
- tests/
- test*.nim files
- out/
- compiled binaries
- prototypes or spikes for this bot (not at root)
- docs/ — generic project documentation
- tools/ — generic tools valid for all bots (battle runners, scripts, etc.)
- common_libs/ — shared libraries valid for all bots
- worktrees/ — git worktrees (gitignored)
- AGENTS.md
- CONTEXT.md
- README.md
- .gitignore
## How to use
- These indications are for files that are always present, for files not mentioned here should be claer from context where belongs too.
- Each bot development must be done in each folder in isolation.
- If the bot requires extra folders during runtime, these must be created by the bot itself if not present already.
-13
View File
@@ -1,13 +0,0 @@
## Agent skills
### Issue tracker
Gitea Issues at git.fossellini.top:SirStone/SirRoboGarage. See `docs/agents/issue-tracker.md`.
### Triage labels
Default label vocabulary. See `docs/agents/triage-labels.md`.
### Domain docs
Single-context layout. See `docs/agents/domain.md`.
+59
View File
@@ -0,0 +1,59 @@
# Evo_Bot
Robocode Tank Royale bot with a modular gun system where evolved neural networks learn to predict enemy dodge behavior.
## Language
**Evo_Bot**:
The bot itself — handles movement and firing discipline. Guns are pluggable modules.
_Avoid_: robot, tank
**Guess Factor (GF)**:
A value from -1 to +1 representing where on the maximum escape angle arc the enemy is. 0 = directly ahead, -1 = full left dodge, +1 = full right dodge. The gun's prediction target.
_Avoid_: aim offset, dodge index
**Max Escape Angle (MEA)**:
The widest angle the enemy can reach before a bullet arrives, computed from distance and bullet speed. Guess factor is multiplied by MEA to get the aim offset.
**Lateral Velocity**:
Enemy speed projected perpendicular to the line between you and them. The primary signal for guess factor prediction.
_Avoid_: tangential speed, sideways velocity
**Sliding Window**:
The last N ticks (default 30) of enemy state fed as input to the network. Each tick contains lateral velocity, heading delta, and wall distance ahead.
_Avoid_: observation buffer, input history
**Replay Tape**:
Rolling buffer of recorded enemy states (~2000 ticks). The evolution thread evaluates gun fitness against this tape.
_Avoid_: experience buffer, replay buffer
**Virtual Gun**:
A gun that runs in parallel without actually firing. It tracks where it would have aimed and whether a simulated bullet would have hit. Used to compare gun variants.
**Virtual Bullet**:
A simulated bullet fired by a virtual gun. Never actually sent to the game engine.
**TOPO_Gun**:
Fixed-topology ANN gun evolved by GA. Network shape is predetermined (e.g., 91-8-1), only weights are evolved.
_Avoid_: static gun, fixed gun
**NEAT_Gun**:
Variable-topology ANN gun where evolution can add/remove neurons and connections (NEAT algorithm). Deferred — only built if TOPO_Gun hits a ceiling.
**Population**:
The set of candidate networks (default 64-200) being evolved. Each member is a complete set of ANN weights.
**Champion**:
The best-performing network in the current GA population. The champion's weights are pushed to the inference side when it beats the current best.
_Avoid_: best, winner, elite
**Fitness**:
Hit count when a network's aim predictions are evaluated as virtual bullets against sampled ticks from the replay tape.
_Avoid_: score, reward
**Cold Start**:
The first-ever battle with no saved weights. The gun does not fire until the evolution thread produces its first champion. Subsequent battles load persisted weights.
**Weight Persistence**:
Saving evolved weights to disk. Load order: per-opponent file, then global fallback, then random initialization.
_Avoid_: model saving, checkpointing
BIN
View File
Binary file not shown.
@@ -3,6 +3,7 @@ version = "0.1.0"
author = "Davide Cappellini" author = "Davide Cappellini"
description = "GotoTest — throwaway goto(x,y) controller prototype" description = "GotoTest — throwaway goto(x,y) controller prototype"
license = "MIT" license = "MIT"
srcDir = "src"
bin = @["GotoTest"] bin = @["GotoTest"]
# Dependencies # Dependencies
@@ -1,3 +1,4 @@
switch("outdir", "out")
# begin Nimble config (version 2) # begin Nimble config (version 2)
when withDir(thisDir(), system.fileExists("nimble.paths")): when withDir(thisDir(), system.fileExists("nimble.paths")):
include "nimble.paths" include "nimble.paths"
View File
+12
View File
@@ -0,0 +1,12 @@
# Package
version = "0.1.0"
author = "Davide Cappellini"
description = "Oscillator pattern Tank Royale bot"
license = "MIT"
srcDir = "src"
bin = @["OscillatorBot"]
# Dependencies
requires "nim >= 2.0.0"
# tankroyale_botapi and radar_lock are vendored in-tree (common_libs/) and wired via
# config.nims --path; no nimble dependency so builds never touch ~/.nimble/pkgs2.
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
cd "$(dirname "$0")"
exec ./out/OscillatorBot 2>> /tmp/oscillatorbot_stderr.log
+2
View File
@@ -0,0 +1,2 @@
--path:"../common_libs"
switch("outdir", "out")
View File
@@ -0,0 +1,11 @@
{
"name": "OscillatorBot",
"version": "0.1.0",
"authors": ["Davide Cappellini"],
"description": "Predictable zigzag sparring partner for gun testing",
"homepage": "",
"countryCodes": ["IT"],
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
@@ -0,0 +1,48 @@
# OscillatorBot — predictable zigzag sparring partner for GA gun testing.
# Reverses direction + turn every PERIOD ticks. Head-on targeting only.
import std/[math, os]
import tankroyale_botapi
const botJsonPath = currentSourcePath().parentDir / "OscillatorBot.json"
const
SPEED = 7.0 # forward/backward speed
PERIOD = 25 # ticks between direction reversals
type OscillatorBot = ref object of Bot
tickCount: int
moveSign: float # +1 forward, -1 backward
turnSign: float # +1 right, -1 left
method onRoundStarted*(bot: OscillatorBot, e: RoundStartedEvent) =
setAdjustGunForBodyTurn(true)
setAdjustRadarForBodyTurn(true)
setAdjustRadarForGunTurn(true)
bot.tickCount = 0
bot.moveSign = 1.0
bot.turnSign = 1.0
method onScannedBot*(bot: OscillatorBot, e: ScannedBotEvent) =
# Head-on targeting: aim gun directly at enemy, fire medium power
let bearing = directionTo(getX(), getY(), e.x, e.y)
let gunDelta = normalizeRelativeAngle(bearing - getGunDirection())
setGunTurnRate(gunDelta.clamp(-MAX_GUN_TURN_RATE, MAX_GUN_TURN_RATE))
if abs(gunDelta) < 10.0 and getGunHeat() <= 0.0:
discard setFire(2.0)
method run*(bot: OscillatorBot) =
while isRunning():
inc bot.tickCount
if bot.tickCount mod PERIOD == 0:
bot.moveSign *= -1.0
bot.turnSign *= -1.0
setTargetSpeed(bot.moveSign * SPEED)
setTurnRate(bot.turnSign * 4.0)
setRadarTurnRate(45.0) # spin radar to keep scanning
go()
when isMainModule:
var bot = OscillatorBot(moveSign: 1.0, turnSign: 1.0)
start(bot, botJsonPath)
View File
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
@@ -3,10 +3,11 @@ version = "0.1.0"
author = "Davide Cappellini" author = "Davide Cappellini"
description = "PPO-trained Tank Royale bot" description = "PPO-trained Tank Royale bot"
license = "MIT" license = "MIT"
srcDir = "src"
bin = @["PPO_Bot"] bin = @["PPO_Bot"]
# Dependencies # Dependencies
requires "nim >= 2.0.0" requires "nim >= 2.0.0"
# tankroyale_botapi is vendored in-tree (libs/tankroyale_botapi) and wired via # tankroyale_botapi is vendored in-tree (common_libs/tankroyale_botapi) and wired via
# config.nims --path; no nimble dependency so builds never touch ~/.nimble/pkgs2. # config.nims --path; no nimble dependency so builds never touch ~/.nimble/pkgs2.
requires "arraymancer >= 0.7.0" requires "arraymancer >= 0.7.0"
@@ -4,4 +4,4 @@
# which deadlock when called from within a multi-threaded Nim bot process. # which deadlock when called from within a multi-threaded Nim bot process.
export OPENBLAS_NUM_THREADS=1 export OPENBLAS_NUM_THREADS=1
cd -- "$(dirname -- "$0")" cd -- "$(dirname -- "$0")"
exec "./PPO_Bot" exec "./out/PPO_Bot"
@@ -2,12 +2,14 @@
# ponytail: adjust path per machine, or use pkg-config # ponytail: adjust path per machine, or use pkg-config
switch("passL", "-L/nix/store/v07svn2y92bvzjl51aj7c9ca1cwg7rw7-openblas-0.3.32/lib -lopenblas") switch("passL", "-L/nix/store/v07svn2y92bvzjl51aj7c9ca1cwg7rw7-openblas-0.3.32/lib -lopenblas")
switch("threads", "on") switch("threads", "on")
switch("outdir", "out")
switch("path", thisDir() & "/src")
# begin Nimble config (version 2) # begin Nimble config (version 2)
when withDir(thisDir(), system.fileExists("nimble.paths")): when withDir(thisDir(), system.fileExists("nimble.paths")):
include "nimble.paths" include "nimble.paths"
# end Nimble config # end Nimble config
# Use the repo-vendored Tank Royale bot API (libs/) instead of the nimble pkg. # Use the repo-vendored Tank Royale bot API (common_libs/) instead of the nimble pkg.
# The pkg copy lived in ~/.nimble/pkgs2 and was patched ad-hoc; vendoring makes # The pkg copy lived in ~/.nimble/pkgs2 and was patched ad-hoc; vendoring makes
# the build self-contained and keeps the cross-thread Channel fix in-tree. # the build self-contained and keeps the cross-thread Channel fix in-tree.
# Must come AFTER the nimble.paths include: later --path wins the import search. # Must come AFTER the nimble.paths include: later --path wins the import search.
switch("path", thisDir() & "/../libs/tankroyale_botapi") switch("path", thisDir() & "/../common_libs/tankroyale_botapi")
View File
@@ -4,12 +4,12 @@
import std/[os, strformat, strutils, math, times, algorithm] import std/[os, strformat, strutils, math, times, algorithm]
import arraymancer import arraymancer
import tankroyale_botapi import tankroyale_botapi
import network import PPO_Bot/network
import actions import PPO_Bot/actions
import training import PPO_Bot/training
import weights import PPO_Bot/weights
import ./enemy_tracker import PPO_Bot/enemy_tracker
import ./state_vector import PPO_Bot/state_vector
# ── Hyperparameters from env vars (PPOB_ prefix) ───────────────────────────── # ── Hyperparameters from env vars (PPOB_ prefix) ─────────────────────────────
# All optional; defaults match ppoUpdate signature in training.nim. # All optional; defaults match ppoUpdate signature in training.nim.
@@ -64,7 +64,7 @@ proc hyperparmSnapshot(): string =
&"\"logStdFloor\":{logStdFloor},\"logStdCeiling\":{logStdCeiling},\"initialLogStd\":{initialLogStd}" &"\"logStdFloor\":{logStdFloor},\"logStdCeiling\":{logStdCeiling},\"initialLogStd\":{initialLogStd}"
const botJsonPath = currentSourcePath().parentDir / "PPO_Bot.json" const botJsonPath = currentSourcePath().parentDir / "PPO_Bot.json"
const weightsRoot = currentSourcePath().parentDir / "weights" const weightsRoot = currentSourcePath().parentDir / "../weights"
type type
InFlightBullet = object InFlightBullet = object
+2
View File
@@ -0,0 +1,2 @@
switch("path", "../src")
switch("path", "../../common_libs/tankroyale_botapi")
Binary file not shown.
@@ -0,0 +1,36 @@
## diag_ppo_fullbuffer.nim — run ppoUpdate on a FULL 8192-transition buffer.
## Verifies whether the round-10 death (first ppoUpdate at buffer capacity)
## is a real crash in ppoUpdate or purely the saveAdamStates empty-shape bug.
import std/[math, random]
import arraymancer
import PPO_Bot/network
import PPO_Bot/training
var ac = initActorCritic()
var adam: ACAdamStates # uninitialised → ppoUpdate must reinit (fresh-process path)
var buf = initTrajectoryBuffer()
randomize(1)
while buf.len < MAX_TRANSITIONS:
var t: Transition
for i in 0..<STATE_DIM: t.state[i] = rand(1.0'f32) - 0.5'f32
for i in 0..<ACTION_DIM: t.action[i] = rand(1.0'f32) - 0.5'f32
t.logProb = rand(1.0'f32) - 1.0'f32
t.reward = rand(0.02'f32) - 0.01'f32
t.value = rand(0.1'f32)
t.done = buf.len mod 300 == 299
buf.add(t)
echo "buffer.len = ", buf.len, " (MAX=", MAX_TRANSITIONS, ")"
var ac2 = ac
var adam2: ACAdamStates
try:
let m = ppoUpdate(ac2, buf, lastValue = 0.0'f32, adamStates = adam2)
echo "ppoUpdate OK: aLoss=", m.actorLoss, " vLoss=", m.valueLoss, " gNorm=", m.gradNorm
except CatchableError as e:
echo "CAUGHT CatchableError: ", e.msg
echo getStackTrace(e)
except Defect as e:
echo "CAUGHT Defect: ", e.msg
echo getStackTrace(e)
Binary file not shown.
@@ -0,0 +1,31 @@
## diag_savecheckpoint.nim — reproduce the startup+saveCheckpoint path that
## crashes with `io_npy.nim(143, 3) `0 < t.shape.len`` under the boot server.
## Run: nim c -d:release tests/diag_savecheckpoint.nim && ./tests/diag_savecheckpoint
import std/[os]
import arraymancer
import PPO_Bot/network
import PPO_Bot/training
import PPO_Bot/weights
const weightsRoot = currentSourcePath().parentDir.parentDir / "weights"
var ac = initActorCritic()
var adam: ACAdamStates
let loadResult = loadBestAvailable(ac, adam, weightsRoot)
echo "loaded=", loadResult.loaded, " roundNum=", loadResult.roundNum
echo "adam.initialized=", adam.initialized
echo "adam.aw1.m.shape=", adam.aw1.m.shape, " aw1.v.shape=", adam.aw1.v.shape
echo "adam.logStd.m.shape=", adam.logStd.m.shape
echo "adam.aw1.t=", adam.aw1.t
try:
saveCheckpoint(ac, adam, weightsRoot, 1)
echo "saveCheckpoint OK"
except CatchableError as e:
echo "CAUGHT CatchableError: ", e.msg
echo getStackTrace(e)
except Defect as e:
echo "CAUGHT Defect: ", e.msg
echo getStackTrace(e)
@@ -3,7 +3,7 @@
import arraymancer import arraymancer
import std/math import std/math
import "../actions" import PPO_Bot/actions
template check(cond: bool, msg: string) = template check(cond: bool, msg: string) =
if not cond: if not cond:
@@ -2,7 +2,7 @@
## Run: nim c -r tests/test_controllers.nim ## Run: nim c -r tests/test_controllers.nim
import std/math import std/math
import "../controllers" import PPO_Bot/controllers
template check(cond: bool, msg: string) = template check(cond: bool, msg: string) =
if not cond: if not cond:
@@ -3,8 +3,8 @@
import arraymancer import arraymancer
import std/[math, strformat] import std/[math, strformat]
import ../network import PPO_Bot/network
import ../actions import PPO_Bot/actions
func isFiniteF(x: float32): bool = classify(x) notin {fcNan, fcInf, fcNegInf} func isFiniteF(x: float32): bool = classify(x) notin {fcNan, fcInf, fcNegInf}
func isNaNF(x: float32): bool = classify(x) == fcNan func isNaNF(x: float32): bool = classify(x) == fcNan
@@ -2,7 +2,7 @@
## Run: nim c -r tests/test_radar_lock.nim ## Run: nim c -r tests/test_radar_lock.nim
import std/[math, strformat] import std/[math, strformat]
import "../enemy_tracker" import PPO_Bot/enemy_tracker
template check(cond: bool, msg: string) = template check(cond: bool, msg: string) =
if not cond: if not cond:
@@ -5,8 +5,8 @@ import std/[math, strformat]
import arraymancer import arraymancer
# Import from parent dir # Import from parent dir
import "../enemy_tracker" import PPO_Bot/enemy_tracker
import "../state_vector" import PPO_Bot/state_vector
template check(cond: bool, msg: string) = template check(cond: bool, msg: string) =
if not cond: if not cond:
@@ -3,8 +3,8 @@
import std/[math, random] import std/[math, random]
import arraymancer import arraymancer
import "../network" import PPO_Bot/network
import "../training" import PPO_Bot/training
template check(cond: bool, msg: string) = template check(cond: bool, msg: string) =
if not cond: if not cond:
@@ -3,9 +3,9 @@
import std/[os, math] import std/[os, math]
import arraymancer import arraymancer
import "../network" import PPO_Bot/network
import "../training" import PPO_Bot/training
import "../weights" import PPO_Bot/weights
template check(cond: bool, msg: string) = template check(cond: bool, msg: string) =
if not cond: if not cond:

Some files were not shown because too many files have changed in this diff Show More