10 Commits
33 changed files with 3430 additions and 203 deletions
-175
View File
@@ -1,175 +0,0 @@
---
name: nim-mcp-tools
description: 'Use for Nim symbol navigation, diagnostics, and type resolution. MANDATORY: Use specialized MCP tools (nimFindSymbols, nimFindReferences, nimListSymbols, nimCheckFile, nimCheckProject, nimFindTypeDefinition) first; fall back to grep only on error or user confirmation.'
---
# Nim MCP Tools
## Core Mandate
AI agents MUST prefer specialized MCP tools over general-purpose instruments (grep, shell commands, `read_file` with manual parsing) for all Nim symbol-related and Nim diagnostics tasks. This is critical for:
1. **Token Efficiency**: MCP tools return structured, relevant data, avoiding large file reads or noisy grep outputs.
2. **Precision**: These tools understand Nim semantics (scopes, imports, overloads) which string-based search cannot.
## Activation Rule
If the user asks to find, rename, remove, audit, update, standardize naming, or fix issues/project of a Nim symbol or its usages, this skill MUST be used first and the workflow must start with the Nim MCP symbol tools.
If the user asks to check a single Nim file for errors, warnings, hints, diagnostics, issues, problems, or compiler feedback, this skill MUST be used first and the workflow must start with `nimCheckFile`.
If the user asks to check a Nim project for errors, warnings, hints, diagnostics, issues, problems, compiler feedback, or to "fix" it, this skill MUST be used first and the workflow must start with `nimCheckProject`.
If the user asks to determine where a symbol comes from, what type it is, what its fields are (including private ones), or resolve a symbol's type definition, this skill MUST be used first and the workflow must start with `nimFindTypeDefinition`.
This applies to requests phrased as:
- "find all usages/references of `Foo`"
- "remove all definitions of and references to `Foo`"
- "rename `Foo` everywhere"
- "standardize naming for `Foo`"
- "fix casing for all variables"
- "where is `Foo` defined?"
- "list the symbols in this Nim file/module"
- "check this file/module for errors"
- "show diagnostics for `foo.nim`"
- "check this project/workspace/repository/package for errors"
- "fix issues in this project"
- "fix the repo"
- "find Nim diagnostics in the current codebase"
- "show warnings and hints for this repo"
- "scan the current module tree for Nim issues"
- "what is the type of this symbol?"
- "what module/package does this type come from?"
- "what fields does this type have?"
- "is this a type alias or a concrete type?"
- "where is this type defined?"
Treat user wording such as **project**, **workspace**, **repository**, **repo**, **package**, **codebase**, **checkout**, and **module tree** as referring to the current Nim project context when they are asking for project-wide diagnostics.
Treat user wording such as **file**, **module** (when a concrete Nim file is identified), **source file**, and explicit `*.nim` paths as referring to single-file diagnostics when they are asking for diagnostics for one file.
Do **not** pair `nimFindSymbols`, `nimCheckFile`, or `nimCheckProject` with `grep`, `ripgrep`, or shell search "just to double-check". If the task is about a Nim symbol or Nim diagnostics, MCP tools own the search unless they have already failed.
## User Terminology vs MCP `kind`
Users may ask for symbol categories using looser or non-strict terminology. AI agents MUST map that wording to the exact Nim MCP `kind` values before filtering results from `nimListSymbols(...)` or `nimFindSymbols(...)`.
The MCP server returns Nim-oriented kind names derived from nimsuggest symbol kinds with the leading `sk` removed, such as `Const`, `EnumField`, `Field`, `Iterator`, `Converter`, `Let`, `Macro`, `Method`, `Proc`, `Template`, `Type`, `Var`, and `Func`.
Use these terminology mappings when interpreting user requests:
- **function** / **functions**: usually match `Func` and `Proc`
- **pure function** / **pure functions**: match `Func`
- **callable** / **routine**: may include `Func`, `Proc`, `Method`, `Iterator`, `Converter`, `Macro`, and `Template`
- **class** / **classes**: match `Type`
- **variable** / **variables**: match `Var` and `Let`
- **property** / **properties**: match `Field`
- **enum member** / **enum members**: match `EnumField`
- **constant** / **constants**: match `Const`
## When to Use
- **Finding References**: To rename a symbol, update a signature, or find usages.
- **Symbol Discovery**: To find where a symbol is defined by name.
- **Type Resolution**: To determine where a local symbol comes from (which module), what its type is, and what fields it has (including private ones).
- **Naming Standardization**: To fix casing or follow style guides across the project.
- **Fixing Project Issues**: To iteratively find and resolve all diagnostics in the project.
- **File Analysis**: To get an overview of all symbols in a file.
- **File Diagnostics**: To check one specific Nim file for errors, warnings, and hints.
- **Project Diagnostics**: To check the current Nim project for errors, warnings, and hints.
- **Debugging Type Mismatches**: When a diagnostic reveals a type mismatch, use `nimFindTypeDefinition` on both sides.
- **Code Generation / Refactoring**: Before generating code that interacts with a type, find its definition.
## Workflows
### 1. Find All References or Usages of a Symbol Name
Do NOT grep for the name.
1. Call `nimFindSymbols(query: "SymbolName")` to get exact `path`, `line`, and `column`.
2. For each relevant result, call `nimFindReferences(path, line, column)`.
3. Aggregate the results.
### 2. List All Symbols in a File
Do NOT read the whole file to find definitions.
1. Call `nimListSymbols(path: "path/to/file.nim")`.
2. If the user asked for a symbol category, filter by the MCP `kind` values.
3. Use the returned list to navigate or analyze the file structure.
### 3. Find Definitions
1. Call `nimFindSymbols(query: "query")`.
### 4. Resolve Type / Determine Origin of a Symbol
1. Call `nimFindTypeDefinition(path, line, column)` with the cursor positioned on the symbol of interest.
2. The result contains the definition `path`, `line`, `column`, `name`, `type`, and `kind`.
3. If the user needs to see the full definition, read the source at the returned path/line.
### 5. Debug Type Mismatch (Check + Type Definition)
1. Call `nimCheckFile(path)` to get the diagnostic with the exact error location.
2. For the reported location, call `nimFindTypeDefinition(path, line, column)` on the involved symbols.
3. Resolve the mismatch with the correct type or conversion.
### 6. Explore Object Structure (List Symbols + Type Definition)
1. Call `nimFindSymbols(query: "TypeName")` to locate the type definition.
2. Call `nimFindTypeDefinition(path, line, column)` on the type name to confirm the definition location.
3. Read the source at the definition location to enumerate all fields.
### 7. Check a Single Nim File for Diagnostics
1. Call `nimCheckFile(path: "path/to/file.nim")`.
2. Treat the result as the answer unless the user explicitly asked for broader validation.
3. Use the returned diagnostics to report errors, warnings, and hints for that file.
### 8. Check the Current Nim Project for Diagnostics
1. Call `nimCheckProject()`.
2. Use the returned diagnostics to report errors, warnings, and hints for the current Nim project context.
### 9. Standardize Naming
1. Iterate through the project files one by one.
2. For each file, call `nimListSymbols(path: "path/to/file.nim")`.
3. For each symbol found, call `nimFindReferences(path, line, column)`.
4. Standardize the definition and all identified reference sites to `camelCase`.
5. After a file has been processed, call `nimCheckFile(path: "path/to/file.nim")` to verify.
### 10. Fix Project Issues
1. Call `nimCheckProject()` to find all diagnostics in the project.
2. Analyze the diagnostics and resolve the identified issues.
3. Repeat steps 1 and 2 until `nimCheckProject()` returns no more issues.
4. **Limit**: If issues remain after 3 iterations, stop and prompt the user.
5. **Post-Fix Step**: Ask the user if they would like to check for naming consistency.
## Fallback Policy
1. **On Error**: If an MCP tool fails due to a technical error, fall back to `grep_search` or other general-purpose tools. State clearly that the MCP tool failed.
2. **On Empty Results**: If an MCP tool returns no results, do NOT automatically fall back to grep. Prompt the user first.
3. **Availability**: If MCP tools are unavailable, use general-purpose tools but inform the user.
## Critical Constraints
- **NO GREP BY DEFAULT**: Never use `grep`, `ripgrep`, or `grep_search` to find Nim symbols or references unless the MCP tools have explicitly errored out.
- **PROMPT ON EMPTY**: If MCP tools return nothing, ask the user before falling back to grep.
- **NO MANUAL PARSING**: Do not read large Nim files just to extract symbol locations; use `nimListSymbols` instead.
- **NO DIY FILE CHECKS**: Do not substitute manual inspection when `nimCheckFile` can return structured diagnostics.
- **NO DIY PROJECT CHECKS**: Do not substitute shelling out to ad-hoc Nim commands when `nimCheckProject` can return structured project diagnostics.
- **TOKEN CONSERVATION**: Minimize turns and context by using the most precise tool available.
## Anti-Patterns
- Calling `nimFindSymbols("Foo")` and then running `rg "Foo"` anyway.
- Using `rg` for "find all usages" when `nimFindReferences` is available.
- Reading multiple Nim files to manually enumerate definitions that `nimListSymbols` can return directly.
- Reading a Nim file to manually search for a type definition when `nimFindTypeDefinition` can resolve it precisely.
- Grepping for `type Foo* =` instead of using `nimFindTypeDefinition` or `nimFindSymbols`.
- Running `nimCheckProject()` when the user asked to check one specific Nim file.
- Manually reading or building a single Nim file first when `nimCheckFile` can return structured diagnostics.
- Running a manual project build or grep-based log scan first when `nimCheckProject` is available.
+2
View File
@@ -23,6 +23,8 @@ cd ChimeraBot_garage/src && nimble test # unit tests
`SERVER_URL` / `SERVER_SECRET` come from the environment; an optional `.env`
beside the `.nimble` is loaded without ever overriding a preexisting variable.
Debug overlay: run server with `--debug-mode` and bot with `./ChimeraBot.sh -d:chimeraDebug`.
## CHIMERA modules (M3.5 + M4)
`src/ChimeraBot/chimera/` holds the CHIMERA libraries —
+91
View File
@@ -0,0 +1,91 @@
# M6.5 G2 - kernel identifiability certificate
Source: `chimera/identifiability.nim` over the 12 registered v0.2 kernels (66 unordered pairs). Probe alphabet: the seven spec §9 probe types (noop, stop, reverse, speedmod, flip, distance, gun); canonical start set of 8 fixed scenarios; sequences searched to Lmax=6 by exhaustive depth-first enumeration. Separation is the total variation between the two kernels' per-tick joint `(turnRate,targetSpeed,fire)` intent distributions (discretized 1 deg / 1 unit / 0.1 firepower over the start set), averaged over the sequence; delta = 0.300 (spec silent, fixed here). Deterministic: fixed seed/order, byte-stable across runs (`tests/test_identifiability.nim`).
## Summary
| metric | value |
|---|---:|
| pairs examined | 66 |
| identifiable | 66 (100.0%) |
| UNIDENTIFIABLE | 0 |
| max L_ij needed | 1 |
| probe sequences searched | 117649 per pair (worst case) |
**UNIDENTIFIABLE pairs: none** — every kernel pair separates within Lmax.
## Per-pair certificate
| Ki | Kj | L_ij | separation | best probe prefix |
|---|---|---:|---:|---|
| ORBIT_LOCK | ORBIT_BALLIST | 1 | 1.000 | `noop` |
| ORBIT_LOCK | STOP_AND_GO | 1 | 1.000 | `noop` |
| ORBIT_LOCK | ZIGZAG | 1 | 1.000 | `noop` |
| ORBIT_LOCK | RAMMER | 1 | 1.000 | `noop` |
| ORBIT_LOCK | CORNER_RUN | 1 | 1.000 | `stop` |
| ORBIT_LOCK | WALLCRAWL | 1 | 1.000 | `stop` |
| ORBIT_LOCK | STATIC | 1 | 1.000 | `noop` |
| ORBIT_LOCK | STATIC_CORNER | 1 | 1.000 | `stop` |
| ORBIT_LOCK | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| ORBIT_LOCK | RANDOM_WALK_B | 1 | 1.000 | `stop` |
| ORBIT_LOCK | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | STOP_AND_GO | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | ZIGZAG | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RAMMER | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | CORNER_RUN | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | WALLCRAWL | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | STATIC | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | STATIC_CORNER | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| STOP_AND_GO | ZIGZAG | 1 | 1.000 | `noop` |
| STOP_AND_GO | RAMMER | 1 | 1.000 | `noop` |
| STOP_AND_GO | CORNER_RUN | 1 | 1.000 | `noop` |
| STOP_AND_GO | WALLCRAWL | 1 | 1.000 | `noop` |
| STOP_AND_GO | STATIC | 1 | 1.000 | `noop` |
| STOP_AND_GO | STATIC_CORNER | 1 | 1.000 | `noop` |
| STOP_AND_GO | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| STOP_AND_GO | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| STOP_AND_GO | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| ZIGZAG | RAMMER | 1 | 1.000 | `stop` |
| ZIGZAG | CORNER_RUN | 1 | 1.000 | `noop` |
| ZIGZAG | WALLCRAWL | 1 | 1.000 | `noop` |
| ZIGZAG | STATIC | 1 | 1.000 | `noop` |
| ZIGZAG | STATIC_CORNER | 1 | 1.000 | `noop` |
| ZIGZAG | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| ZIGZAG | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| ZIGZAG | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| RAMMER | CORNER_RUN | 1 | 1.000 | `noop` |
| RAMMER | WALLCRAWL | 1 | 1.000 | `noop` |
| RAMMER | STATIC | 1 | 1.000 | `noop` |
| RAMMER | STATIC_CORNER | 1 | 1.000 | `noop` |
| RAMMER | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| RAMMER | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| RAMMER | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| CORNER_RUN | WALLCRAWL | 1 | 1.000 | `distance` |
| CORNER_RUN | STATIC | 1 | 1.000 | `noop` |
| CORNER_RUN | STATIC_CORNER | 1 | 1.000 | `stop` |
| CORNER_RUN | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| CORNER_RUN | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| CORNER_RUN | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| WALLCRAWL | STATIC | 1 | 1.000 | `noop` |
| WALLCRAWL | STATIC_CORNER | 1 | 1.000 | `stop` |
| WALLCRAWL | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| WALLCRAWL | RANDOM_WALK_B | 1 | 1.000 | `stop` |
| WALLCRAWL | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| STATIC | STATIC_CORNER | 1 | 1.000 | `noop` |
| STATIC | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| STATIC | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| STATIC | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| STATIC_CORNER | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| STATIC_CORNER | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| STATIC_CORNER | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| RANDOM_WALK_A | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| RANDOM_WALK_A | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| RANDOM_WALK_B | RANDOM_WALK_C | 1 | 1.000 | `noop` |
## Walls diagnosis (why twin/persistence >= 1.0 there)
Walls is the one MOVING opponent where the twin never beats a constant-velocity carry at any long horizon (twin/persistence 15.9 / 6.5 / 3.9 / 2.2 / **1.50** at h=1/5/10/25/50, `m6_5_horizonsweep.md`), and the sweep's own evidence explains it: over the archived M6.5 telemetry, 89.2% of Walls' 9356 scanned intent ticks carry a turn interval of ~0 deg (dead straight) and the remaining turns are saturated 90 deg corners (|turn| ~ 10 for most of them). Walls therefore moves in long straight wall-parallel segments between predictable 90 deg turns, and on a straight segment persistence IS near-optimal: constant velocity reproduces the realized path almost exactly, while the kernel mixture must (a) pay for re-committing after every regime change and (b) hit the exact corner tick. Missing that one turn tick injects a lateral error that persists for the whole following segment, which is why the twin's advantage only appears once the horizon is long enough for the turn to have been predicted and the error to amortize — and even at h=50 it is not enough to go below 1.0. The failure is persistence being strong on piecewise-straight motion, not a reconstruction or state bug (twinsim replay == oracle, byte-equal).
@@ -0,0 +1,65 @@
# M6.5 horizon sweep - twin vs persistence vs residual
Source: `/tmp/chimera_g6_on` (120 round files; 4 MOVING opponents). Horizons [1, 5, 10, 25, 50], ADE averaged over all scanned origins with >= 50 future ticks. Predictors: **twin** (kernel mixture), **persistence** (constant velocity), **residual** (mixture + online linear residual head).
## Per-opponent curves (ADE units, ratio = twin/persistence)
| opponent | horizon | origins | twin ADE | pers ADE | resid ADE | twin/pers | twinWin% |
|---|---:|---:|---:|---:|---:|---:|---:|
| Corners | 1 | 3224 | 0.757 | 0.055 | 0.570 | 13.815 | 2.0 |
| Corners | 5 | 3224 | 3.198 | 0.617 | 2.633 | 5.183 | 5.1 |
| Corners | 10 | 3224 | 6.949 | 2.296 | 6.242 | 3.027 | 8.8 |
| Corners | 25 | 3224 | 20.774 | 12.742 | 21.873 | 1.630 | 18.5 |
| Corners | 50 | 3224 | 48.492 | 40.554 | 55.928 | 1.196 | 25.1 |
| Crazy | 1 | 13786 | 2.613 | 0.623 | 0.997 | 4.192 | 14.1 |
| Crazy | 5 | 13786 | 9.664 | 2.863 | 4.699 | 3.375 | 14.5 |
| Crazy | 10 | 13786 | 20.676 | 8.234 | 12.307 | 2.511 | 19.6 |
| Crazy | 25 | 13786 | 59.287 | 41.281 | 49.445 | 1.436 | 37.6 |
| Crazy | 50 | 13786 | 118.345 | 120.728 | 125.943 | 0.980 | 55.8 |
| Fire | 1 | 4501 | 1.032 | 0.127 | 0.670 | 8.150 | 4.6 |
| Fire | 5 | 4501 | 3.233 | 1.302 | 2.923 | 2.484 | 14.1 |
| Fire | 10 | 4501 | 6.101 | 4.514 | 6.610 | 1.351 | 21.5 |
| Fire | 25 | 4501 | 14.642 | 19.974 | 20.571 | 0.733 | 36.6 |
| Fire | 50 | 4501 | 24.414 | 47.173 | 44.086 | 0.518 | 48.8 |
| RamFire | 1 | 2959 | 1.341 | 0.117 | 0.834 | 11.456 | 4.3 |
| RamFire | 5 | 2959 | 5.116 | 1.128 | 3.921 | 4.536 | 11.3 |
| RamFire | 10 | 2959 | 11.166 | 3.954 | 9.431 | 2.824 | 18.0 |
| RamFire | 25 | 2959 | 32.759 | 20.484 | 33.082 | 1.599 | 32.6 |
| RamFire | 50 | 2959 | 70.715 | 63.782 | 82.805 | 1.109 | 47.0 |
| SpinBot | 1 | 9812 | 0.545 | 0.557 | 0.579 | 0.979 | 95.7 |
| SpinBot | 5 | 9812 | 1.684 | 1.820 | 1.862 | 0.925 | 95.7 |
| SpinBot | 10 | 9812 | 3.046 | 3.564 | 3.542 | 0.855 | 96.1 |
| SpinBot | 25 | 9812 | 6.477 | 8.401 | 8.374 | 0.771 | 94.8 |
| SpinBot | 50 | 9812 | 11.386 | 12.609 | 13.611 | 0.903 | 84.9 |
| TrackFire | 1 | 2337 | 0.045 | 0.000 | 0.140 | inf | 0.0 |
| TrackFire | 5 | 2337 | 0.285 | 0.000 | 0.633 | inf | 0.0 |
| TrackFire | 10 | 2337 | 0.728 | 0.000 | 1.141 | inf | 0.0 |
| TrackFire | 25 | 2337 | 1.819 | 0.000 | 2.762 | inf | 0.0 |
| TrackFire | 50 | 2337 | 2.857 | 0.000 | 5.601 | inf | 0.0 |
| VelociBot | 1 | 6768 | 3.135 | 0.332 | 0.835 | 9.454 | 7.9 |
| VelociBot | 5 | 6768 | 9.880 | 1.823 | 3.577 | 5.420 | 9.1 |
| VelociBot | 10 | 6768 | 18.698 | 5.664 | 8.785 | 3.301 | 15.9 |
| VelociBot | 25 | 6768 | 42.583 | 30.214 | 32.866 | 1.409 | 36.5 |
| VelociBot | 50 | 6768 | 70.855 | 91.558 | 82.617 | 0.774 | 63.1 |
| Walls | 1 | 8606 | 1.553 | 0.098 | 0.428 | 15.911 | 2.3 |
| Walls | 5 | 8606 | 5.731 | 0.885 | 2.203 | 6.474 | 6.6 |
| Walls | 10 | 8606 | 12.533 | 3.197 | 6.203 | 3.921 | 11.5 |
| Walls | 25 | 8606 | 39.727 | 18.058 | 28.549 | 2.200 | 25.3 |
| Walls | 50 | 8606 | 93.296 | 62.078 | 91.258 | 1.503 | 37.9 |
## MOVING-subset roll-up
| horizon | twin ADE | pers ADE | resid ADE | twin/pers |
|---:|---:|---:|---:|---:|
| 1 | 1.949 | 0.440 | 0.738 | 4.431 |
| 5 | 6.824 | 1.983 | 3.239 | 3.441 |
| 10 | 14.096 | 5.500 | 8.141 | 2.563 |
| 25 | 38.771 | 25.953 | 31.611 | 1.494 |
| 50 | 77.637 | 75.490 | 82.478 | 1.028 |
## Verdict
- Horizons >= 10 with twin/persistence < 1.0 per moving opponent: Crazy:1, SpinBot:3, VelociBot:1, Walls:0.
- MOVING-subset roll-up twin/persistence: h10 2.563, h25 1.494, h50 1.028.
- Rule: **validated-conditionally** if twin/persistence < 1.0 on >= 3/4 moving opponents at >= 2 horizons >= 10; **falsified-on-suite** if the subset roll-up ratio is >= 1.0 at ALL horizons >= 10.
**Verdict: idea-falsified-on-suite.**
+24
View File
@@ -0,0 +1,24 @@
# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)
Replayed archived trajectories (`/tmp/chimera_g4_run`) + a synthesized Dodger-v2; hit = bullet passes within 20. units of the realized enemy position on its flight. Aim slew/cadence abstracted. Generated by `tests/bench_g8.nim`.
| opponent | twin % | ELM % | head-on % | vgun % | shots |
|---|---:|---:|---:|---:|---:|
| Corners | 49.3 | 59.6 | 52.2 | 57.2 | 339 |
| Crazy | 50.3 | 31.5 | 15.0 | 50.3 | 1042 |
| Fire | 50.7 | 41.4 | 45.9 | 50.7 | 440 |
| RamFire | 90.5 | 92.7 | 89.9 | 90.5 | 328 |
| SpinBot | 88.3 | 20.1 | 20.1 | 88.3 | 715 |
| TrackFire | 84.2 | 87.3 | 87.3 | 84.2 | 221 |
| VelociBot | 38.7 | 23.3 | 28.4 | 38.7 | 786 |
| Walls | 43.8 | 22.1 | 1.8 | 43.8 | 825 |
| Dodger | 82.7 | 46.4 | 10.9 | 82.7 | 220 |
**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, VelociBot, Walls, Dodger).** Result: vgun >= best single gun on 6/9; vgun >= ELM-base on 5/5 movers. **Verdict: PASS.**
## Method / caveats
* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for {TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a damage-weighted accumulator with tau=200 exponential forgetting, argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns pattern (https://robowiki.net/wiki/Virtual_Guns).
* `TWIN` = `chimera/aimer.nim`: iterated flight time `h = dist/(20-3*power)`, horizon-bucketed predictor Hedge (mixture/residual/persistence), trained ONLINE per record (one aimer, score-then-aim each sampled tick), spread-selected power.
* `ELM` = the ELM gun's **base** geometric intercept from the observed velocity (the learned correction is gated and small, and the online ELM state cannot be replayed offline). This is a proxy for the full ELM gun — a documented deviation.
* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): wave-based perpendicular strafe, centre-pull, seeded reversals. It fires a wave every 12 ticks; a real battle adds shooter motion. Live results (`m7_5_g8_live.md`) are the reality check.
@@ -0,0 +1,21 @@
# G8.5 live bench (M7.5 virtual-gun tournament)
Four arms from the SAME tree: inert (`-d:chimeraInert`), elm (`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (default). 5 rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.
| opponent | elm W% | elm margin | twin W% | twin margin | vgun W% | vgun margin | inert W% | inert margin |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2488.0 | 100.0 | 2376.0 | 100.0 | 2469.0 | 100.0 | 2493.0 |
| Crazy | 100.0 | 2016.0 | 100.0 | 1935.0 | 100.0 | 2025.0 | 100.0 | 1683.0 |
| Fire | 100.0 | 2593.0 | 100.0 | 2526.0 | 100.0 | 2561.0 | 100.0 | 2564.0 |
| RamFire | 100.0 | 2186.0 | 100.0 | 2460.0 | 100.0 | 2413.0 | 100.0 | 2520.0 |
| SpinBot | 100.0 | 1924.0 | 100.0 | 1060.0 | 100.0 | 2001.0 | 100.0 | 1560.0 |
| TrackFire | 100.0 | 2305.0 | 100.0 | 2371.0 | 100.0 | 2299.0 | 100.0 | 2216.0 |
| VelociBot | 100.0 | 2065.0 | 100.0 | 1962.0 | 100.0 | 1378.0 | 100.0 | 1315.0 |
| Walls | 100.0 | 1459.0 | 100.0 | 1651.0 | 100.0 | 1565.0 | 100.0 | 1934.0 |
| Dodger | 100.0 | 1757.0 | 100.0 | 1949.0 | 100.0 | 1954.0 | 80.0 | 515.0 |
**Totals: inert 97.8% (m 16800.0) elm 100.0% (m 18793.0) twin 100.0% (m 18290.0) vgun 100.0% (m 18665.0) **
**Discrimination test (Dodger-v2 row).** Margins: inert 515.0 elm 1757.0 twin 1949.0 vgun 1954.0 spread 1439.0. The arms DIFFER materially against the upgraded Dodger.
**G7 no-regression (vgun >= inert win-rate on every opponent): PASS.**
+25
View File
@@ -0,0 +1,25 @@
# G8 offline hit-rate bench (M7, twin gun)
Replayed archived trajectories (`/tmp/chimera_g4_run`) + a synthesized Dodger; hit = bullet passes within 20. units of the realized enemy position. Aim slew/cadence abstracted. Generated by `tests/bench_g8.nim`.
| opponent | twin % | ELM % | head-on % | shots |
|---|---:|---:|---:|---:|
| Corners | 49.3 | 59.6 | 52.2 | 339 |
| Crazy | 50.3 | 31.5 | 15.0 | 1042 |
| Fire | 50.7 | 41.4 | 45.9 | 440 |
| RamFire | 90.5 | 92.7 | 89.9 | 328 |
| SpinBot | 88.3 | 20.1 | 20.1 | 715 |
| TrackFire | 84.2 | 87.3 | 87.3 | 221 |
| VelociBot | 38.7 | 23.3 | 28.4 | 786 |
| Walls | 43.8 | 22.1 | 1.8 | 825 |
| Dodger | 85.5 | 11.4 | 72.7 | 220 |
**G8 offline bar: twin >= ELM on >= 6/9 opponents AND twin >= head-on on the movers.** Result: twin >= ELM on 6/9; twin >= head-on on 5/5 movers. **Verdict: PASS.**
## Method / caveats
* `TWIN` = `chimera/aimer.nim`: iterated flight time
`h = dist/(20-3*power)`, horizon-bucketed predictor Hedge (mixture/residual/persistence), trained ONLINE per record (one aimer, score-then-aim each sampled tick), spread-selected power.
* `ELM` = the ELM gun's **base** geometric intercept from the observed velocity (the learned correction is gated and small, and the online ELM state cannot be replayed offline). This is a proxy for the full ELM gun — a documented deviation.
* Power monotonicity: `selectPowerFromSpreads` returns the largest power whose required spread fits the enemy-silhouette tolerance `2*atan2(18, dist)`; the choice is non-increasing in spread (`test_aimer.nim`, aimer 4).
* The synthesized Dodger fires a wave every 12 ticks; a real battle would add shooter motion. Live results (`m7_g8_live.md`) are the reality check.
@@ -0,0 +1,19 @@
# G8 live bench (M7 twin gun)
Three arms from the SAME tree: inert (`-d:chimeraInert`), elm (`-d:chimeraNoTwinGun`), twin (default). 5 rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.
| opponent | elm W% | elm margin | twin W% | twin margin | inert W% | inert margin |
|---|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2538.0 | 100.0 | 2354.0 | 100.0 | 2477.0 |
| Crazy | 100.0 | 1779.0 | 100.0 | 2240.0 | 100.0 | 1746.0 |
| Fire | 100.0 | 2571.0 | 100.0 | 2494.0 | 100.0 | 2588.0 |
| RamFire | 100.0 | 2549.0 | 100.0 | 2545.0 | 100.0 | 2665.0 |
| SpinBot | 100.0 | 2085.0 | 100.0 | 1635.0 | 100.0 | 1086.0 |
| TrackFire | 100.0 | 2334.0 | 100.0 | 2337.0 | 100.0 | 2371.0 |
| VelociBot | 100.0 | 2100.0 | 100.0 | 1842.0 | 100.0 | 2141.0 |
| Walls | 100.0 | 1895.0 | 100.0 | 1788.0 | 100.0 | 1697.0 |
| Dodger | 100.0 | 2665.0 | 100.0 | 2662.0 | 100.0 | 2653.0 |
**Totals:** elm 100.0% (margin 20516.0), twin 100.0% (margin 19897.0), inert 100.0% (margin 19424.0).
**G7 no-regression (twin >= inert win-rate on every opponent): PASS.**
+140
View File
@@ -37,6 +37,10 @@ import ChimeraBot/chimera/dsl
import ChimeraBot/chimera/probes
import ChimeraBot/chimera/physics
import ChimeraBot/chimera/influence
import ChimeraBot/chimera/aimer
import ChimeraBot/chimera/virtual_guns
when defined(chimeraDebug):
import ChimeraBot/chimera/debugdraw
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
@@ -62,6 +66,9 @@ const UseElm* = not defined(baselineGun)
# `-d:elmPrior` = weak pooled prior (pretrained beta scaled by 0.1).
const OnlinePriorScale* = (when defined(elmPrior): 0.1 else: 0.0)
const TwinGunMinInfluence = 0.5 ## M7/G8: fused influence above which the
## twin gun REPLACES the ELM gun that tick
const TwinGunEnergyFloor = 6.0 ## do not spend energy below this
const FireSlopDeg = 1.0'f64 ## fire inside this much gun error, in
## DEGREES (the API's unit).
##
@@ -156,6 +163,7 @@ method onGameStarted*(bot: ChimeraBot, e: GameStartedEventForBot) =
## same movement code, so RoundStartedEvent deliberately does NOT touch it.
## (The API fires onGameStarted once per battle and onRoundStarted per round.)
bot.gun.resetOnline()
bot.observer.resetVguns() # M7.5: per-opponent virtual-gun statistics
method onRoundEnded*(bot: ChimeraBot, e: RoundEndedEventForBot) =
inc bot.roundNo
@@ -211,6 +219,79 @@ method buildWorldState(bot: ChimeraBot): WorldState =
arenaWidth: getArenaWidth().float, arenaHeight: getArenaHeight().float,
tick: bot.tick, enemies: bot.enemies)
## M7 twin gun (G8): flight-horizon aiming, gated by the fusion influence and
## removed entirely by `-d:chimeraNoTwinGun`. Returns true when it handled this
## tick, so the ELM gun is skipped; false falls back to the ELM path unchanged.
proc computeTwinGun(bot: ChimeraBot, influence: float64): bool =
let aim = bot.observer.twinAim(getX(), getY(), getArenaWidth().float,
getArenaHeight().float, FirePower)
if not aim.active: return false
bot.observer.setGunTelemetry(radToDeg(aim.aimBearing), aim.power,
radToDeg(aim.spread), influence, true)
let err = gunAimErrorDeg(aim.aimBearing, getGunDirection())
# Fire window: half the silhouette width (the aim point is the CENTER of the
# target, so half-width is the lateral slop that still clips it), floored at
# the tight ELM slop. `aim.tolerance` is the full width per the G8 formula.
let slack = max(FireSlopDeg, radToDeg(aim.tolerance) * 0.5)
let cadenceOk = bot.tick - bot.observer.twinGunLastFire() >= cooldownTicks(aim.spread)
if abs(err) <= slack and getGunHeat() == 0.0 and cadenceOk and
getEnergy() >= TwinGunEnergyFloor:
setGunTurnRate(0.0)
discard setFire(aim.power)
bot.observer.noteTwinShot(aim, bot.tick)
inc bot.shotsFired
else:
setGunTurnRate(clamp(err, -20.0, 20.0))
true
## M7.5 virtual-gun tournament (G8). Runs the three-candidate tournament
## (`chimera/virtual_guns.nim`), fires the argmax gun under hysteresis, and
## returns true when it owned this tick's gun. Removed by `-d:chimeraNoVguns`,
## which leaves the M7 influence-gated twin/ELM path below exactly as it was.
proc computeVgunGun(bot: ChimeraBot, influence: float64): bool =
let arenaW = getArenaWidth().float
let arenaH = getArenaHeight().float
let aim = bot.observer.twinAim(getX(), getY(), arenaW, arenaH, FirePower)
if not aim.active: return false
let belief = bot.buildBelief(FirePower)
let (ex, ey) = bot.observer.currentEnemy()
let headBearing = arctan2(ey - getY(), ex - getX())
let elmBearing = bot.gun.heuristicAim(belief, FirePower)
# Advance the live virtual bullets, then launch this tick's candidates.
bot.observer.vgunStep(ex, ey, aimer.BotRadius, arenaW, arenaH)
bot.observer.vgunLaunch(vgTwin, getX(), getY(), aim.aimBearing, aim.power)
if not elmBearing.isNaN:
bot.observer.vgunLaunch(vgElm, getX(), getY(), elmBearing, FirePower)
bot.observer.vgunLaunch(vgHeadOn, getX(), getY(), headBearing, FirePower)
let chosen = bot.observer.vgunSelect(influence > TwinGunMinInfluence)
bot.observer.setGunFired(chosen)
var bearing = headBearing
var power = FirePower
case chosen
of vgTwin: bearing = aim.aimBearing; power = aim.power
of vgElm: bearing = elmBearing; power = FirePower
of vgHeadOn: bearing = headBearing; power = FirePower
bot.observer.setGunTelemetry(radToDeg(bearing), power, radToDeg(aim.spread),
influence, chosen == vgTwin)
let err = gunAimErrorDeg(bearing, getGunDirection())
if abs(err) <= FireSlopDeg and getGunHeat() == 0.0 and
getEnergy() >= TwinGunEnergyFloor:
setGunTurnRate(0.0)
discard setFire(power)
if chosen == vgTwin:
bot.observer.noteTwinShot(aim, bot.tick)
elif chosen == vgElm and bot.gun.online:
# keep the ELM online label stream alive when the tournament picks it
let feat = buildFeatures(belief)
let d = hypot(belief.ex - belief.selfX, belief.ey - belief.selfY)
let tofTicks = max(1, int(round(d / belief.bulletSpeed)))
bot.gun.recordShot(feat, elmBearing, belief.selfX, belief.selfY,
bot.tick + tofTicks)
inc bot.shotsFired
else:
setGunTurnRate(clamp(err, -20.0, 20.0))
true
## The gun tick: aim, and fire when the gun is actually on the aim point.
##
## Standard Tank Royale gun handling, nothing clever — the cleverness (if any)
@@ -220,6 +301,21 @@ method buildWorldState(bot: ChimeraBot): WorldState =
proc computeGun(bot: ChimeraBot) =
if bot.gun.online:
bot.gun.drainPending(bot.tick) # label any shot whose flight time elapsed
# M7.5 virtual-gun tournament: when a current scan exists, the tournament
# selects and fires the argmax gun (twin gated by the same influence scalar).
# `-d:chimeraNoVguns` compiles this block out and restores the M7 path below.
when not NoVguns:
if bot.observer.hasCurrent:
if bot.computeVgunGun(bot.observer.fusedInfluence()):
return
# M7 twin gun: when the fused influence clears the gate, flight-horizon aiming
# owns this tick's gun. `-d:chimeraNoTwinGun` compiles this block out, leaving
# the ELM path below byte-identical to the pre-M7 build.
when not NoTwinGun:
if bot.observer.hasCurrent:
let infl = bot.observer.fusedInfluence()
if infl > TwinGunMinInfluence and bot.computeTwinGun(infl):
return
let belief = bot.buildBelief(FirePower)
let feat = buildFeatures(belief)
let aim = bot.gun.predictAim(belief, FirePower, UseElm)
@@ -278,6 +374,12 @@ method run*(bot: ChimeraBot) =
setAdjustRadarForBodyTurn(true) # radar ignores body rotation
setAdjustRadarForGunTurn(true) # radar ignores turret rotation too
initRadar() # once: radar + scan turn BLACK = programmed
# Debug-overlay probe flash: persists ProbeFlashTicks after a probe triggers.
# Declared only under the debug define and never read by a command path.
when defined(chimeraDebug):
var probeFlash = 0
var probeFlashLabel = ""
var overlayTicks = 0
while isRunning():
# One radar command and one movement command per tick, unconditionally,
# BEFORE go() — so both are part of this tick's intent.
@@ -322,6 +424,9 @@ method run*(bot: ChimeraBot) =
roundLimit: RoundSoftLimit)
let decision = bot.probes.consider(porigin, ctx)
if decision.trigger:
when defined(chimeraDebug):
probeFlash = ProbeFlashTicks
probeFlashLabel = $decision.candidate.kind
bot.observer.writeProbeEvent(bot.tick, $decision.candidate.kind,
decision.gate.reason, decision.entropyBefore,
decision.entropyAfter, decision.candidate.turnRate,
@@ -338,6 +443,41 @@ method run*(bot: ChimeraBot) =
setTurnRate(cmdTurn)
if not probeFired:
bot.computeGun() # gun intent, also before go()
when defined(chimeraDebug):
# OBSERVATION-ONLY overlay: build the primitive list from observer state
# (pure) and hand it to the API's global SVG buffer. Ordering is the same
# as every other command: drawn here, before go(), so it travels with
# THIS tick's intent. No command setter is called, so the command path is
# byte-identical with or without the overlay.
var snap = OverlayInput(selfX: getX(), selfY: getY())
if bot.observer.hasCurrent:
let top = bot.observer.topKernel()
snap.kernelName = top.name
snap.kernelP = top.weight
snap.entropy = bot.observer.entropy()
let (ex, ey) = bot.observer.lastScanPos()
snap.enemyX = ex; snap.enemyY = ey; snap.haveEnemy = true
let fp = bot.observer.fusedPrediction()
if fp.horizon > 0 and fp.points.len > 0:
snap.pFire5 = fp.fireWithin
snap.predX = fp.points[^1].x
snap.predY = fp.points[^1].y
snap.havePred = true
snap.scanGap = bot.tick - bot.observer.scanTick()
snap.fresh = bot.observer.scanTick() == bot.tick - 1
snap.censored = bot.observer.lastCensored()
if probeFlash > 0:
snap.probeFlash = true
snap.probeLabel = probeFlashLabel
dec probeFlash
let prims = buildOverlay(snap)
renderOverlay(prims)
inc overlayTicks
# Observation-only runtime evidence that the overlay drew (stdout only,
# no command state touched). Quiet apart from the first and every 500th tick.
if overlayTicks == 1 or overlayTicks mod 500 == 0:
echo "[chimera-debug] overlay tick=", bot.tick, " prims=", prims.len,
" svg=", svgOutput().len
go()
bot.observer.writeTick(bot.tick) # observation telemetry, after go()
inc bot.tick
+8
View File
@@ -260,7 +260,15 @@ task test, "Run unit tests":
exec "nim c -r --hints:off ../tests/test_oracle_g1.nim"
exec "nim c -r --hints:off ../tests/test_observer.nim"
exec "nim c -r --hints:off ../tests/test_twinsim.nim"
exec "nim c -r --hints:off ../tests/test_replay_oracle.nim"
exec "nim c -r --hints:off ../tests/test_probes.nim"
exec "nim c -r --hints:off ../tests/test_residual.nim"
exec "nim c -r --hints:off ../tests/test_fusion.nim"
exec "nim c -r --hints:off ../tests/test_influence.nim"
exec "nim c -r --hints:off ../tests/test_identifiability.nim"
exec "nim c -r --hints:off ../tests/test_aimer.nim"
exec "nim c -r --hints:off ../tests/test_virtual_guns.nim"
exec "nim c -r --hints:off ../tests/test_dodger.nim"
# Debug overlay: compiled WITH -d:chimeraDebug so the drawing path is the real
# one; the test asserts the command intent is identical with/without it.
exec "nim c -r --hints:off -d:chimeraDebug ../tests/test_debugdraw.nim"
@@ -0,0 +1,335 @@
## CHIMERA twin gun — flight-horizon aiming (docs/chimera-spec.md, G8 / M7).
##
## The ELM gun (`modules/ELM/elm_gun.nim`) leads the enemy by one geometric
## dead-reckon with a learned correction trained on a 5-tick lookahead. A bullet
## at power `p` flies `dist / (20 - 3p)` ticks — 15 to 45 ticks across the legal
## power range — so on a dodging opponent the aim must target the enemy's
## **bullet-arrival position**, not a 5-tick extrapolation. That is what this
## module adds, in three pieces:
##
## 1. **Horizon-bucketed Hedge** over three predictors — the posterior-mixture
## twinsim rollout, the linear-residual trajectory and constant-velocity
## persistence. Buckets are `1-7 / 8-17 / 18-35 / 36-70` ticks. Each bucket's
## weights are updated online from the realized enemy position at the horizon
## that was actually used; every bucket starts uniform (neutral). This is the
## G8 extension of the M6 fusion (`fusion.nim`), which only knew `k = 5`.
## 2. **Iterated flight time** — `h = flightTime(dist, power)` is folded onto
## itself at most 3 times (`h -> fusedPositionAt(h) -> dist -> h`), with the
## result clipped to the arena and re-iterated when clipping moved it.
## 3. **Spread-based power selection** — the top-`k` (`k <= 4`) kernels by
## posterior are rolled to the flight horizon; the max pairwise angular spread
## of their predicted positions, seen from OUR position, must fit inside the
## enemy-silhouette angular tolerance `2*atan2(botRadius, dist)`. The largest
## power that fits is chosen. Plus an online **aim-bias corrector**: a
## distance-band x enemy-speed-band histogram of post-shot angular misses,
## applied as an angular offset, deterministic and persisted per match.
##
## Nothing here issues commands: `ChimeraBot.computeGun` reads `TwinAim` and
## drives the gun. The whole path is removed by `-d:chimeraNoTwinGun`, which
## restores the exact current ELM gun behaviour.
import std/[math, algorithm]
import ./physics, ./dsl, ./twinsim, ./residual, ./hedge, ./fusion
const
NoTwinGun* = defined(chimeraNoTwinGun)
## Kill switch: with this defined `ChimeraBot.computeGun` never calls the
## twin gun and the ELM path is byte-identical to the pre-M7 build.
BotRadius* = 18.0
## Enemy silhouette half-width used by the angular-tolerance formula. The
## spec does not define a value; 18 units is the Tank Royale bot radius
## convention used elsewhere in the repo.
FirePowers* = [3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.1]
## Candidate powers, DESCENDING. `selectPowerFromSpreads` searches this order
## so the chosen power is monotone non-increasing in the required spread.
NBuckets* = 4
BucketLo* = [1, 8, 18, 36]
BucketHi* = [7, 17, 35, 70]
MaxIter* = 3 ## flight-time/aim-point refinement iterations
MinorStep* = 1e-3 ## |h' - h| below this means converged (ticks)
TinySpreadDeg* = 0.5 ## spread below this allows the fast cadence
NormalCooldown* = 8 ## ticks between twin-gun shots (no spraying)
TinyCooldown* = 2
NDistBands* = 4
NSpeedBands* = 4
DistBandLo* = [0.0, 150.0, 300.0, 500.0]
SpeedBandLo* = [0.0, 2.0, 4.0, 6.0]
MaxBias* = 0.26 ## rad (~15 deg) cap on the learned aim bias
type
PredictorPoints* = object
## The three predictors' enemy position at one horizon, plus the per-kernel
## final positions and posterior weights the spread selector needs.
mix*: tuple[x, y: float64]
res*: tuple[x, y: float64]
pers*: tuple[x, y: float64]
samples*: seq[tuple[x, y: float64]]
weights*: seq[float64]
TwinAim* = object
## The twin gun's per-tick output.
active*: bool
aimBearing*: float64 ## absolute bearing (rad, 0 = east CCW) after bias
x*, y*: float64 ## the (clipped) aim point
power*: float64
spread*: float64 ## rad, max pairwise kernel disagreement at horizon
tolerance*: float64 ## rad, enemy silhouette width at the aim distance
horizon*: float64 ## ticks
baseBearing*: float64 ## bearing to the aim point BEFORE the bias offset
dist*: float64
enemySpeed*: float64
selfX*, selfY*: float64
# what a fired shot needs for delayed scoring / bias training
bucket*: int
mixPt*, resPt*, persPt*: tuple[x, y: float64]
PendingShot* = object
dueTick*: int
bucket*: int
selfX*, selfY*: float64
aimBearing*: float64
dist*, enemySpeed*: float64
mixPt*, resPt*, persPt*: tuple[x, y: float64]
Aimer* = ref object
bucket*: array[NBuckets, Hedge]
biasSum*: array[NDistBands, array[NSpeedBands, float64]]
biasN*: array[NDistBands, array[NSpeedBands, int]]
pending*: seq[PendingShot]
lastFireTick*: int
shots*: int
hits*: int
# ── pure helpers ────────────────────────────────────────────────────────────
proc wrapPi*(a: float64): float64 =
## Shortest signed angle in (-pi, pi], radians.
result = a
while result <= -PI: result += 2.0 * PI
while result > PI: result -= 2.0 * PI
proc flightTime*(dist, power: float64): float64 =
## Ticks a bullet travels `dist` units at `power`, per physics.bulletSpeed:
## `dist / (20 - 3*power)`. A zero/negative power would divide by 20; the
## physics clamp keeps the denominator in [11, 19.7].
let v = bulletSpeed(power)
if v <= 0.0: 0.0 else: dist / v
proc bucketIndex*(h: float64): int =
## Bucket containing horizon `h` (ticks). Values past the last bucket clamp.
let hi = int(ceil(h))
for i in 0 ..< NBuckets:
if hi <= BucketHi[i]: return i
NBuckets - 1
proc angularTolerance*(dist: float64, botRadius = BotRadius): float64 =
## Angular half... actually FULL width of the enemy silhouette at `dist`:
## `2 * atan2(botRadius, dist)`, radians. Closer targets subtend more angle.
if dist <= 1e-6: return PI
2.0 * arctan2(botRadius, dist)
proc selectPowerFromSpreads*(spreads: openArray[float64], tol: float64): float64 =
## `spreads[i]` is the required angular spread at `FirePowers[i]`'s flight
## horizon. FirePowers are DESCENDING, so the first index whose spread fits
## inside `tol` is the largest admissible power; if none fits, the smallest
## power. Monotone in `tol` and in a uniform scaling of `spreads`: a larger
## spread can only shrink the admissible set, whose maximum is therefore
## non-increasing.
let n = min(spreads.len, FirePowers.len)
for i in 0 ..< n:
if spreads[i] <= tol: return FirePowers[i]
if n == 0: FirePowers[^1] else: FirePowers[n - 1]
proc maxPairwiseSpread*(samples: openArray[tuple[x, y: float64]],
weights: openArray[float64],
selfX, selfY, k: float64): float64 =
## Max pairwise angular difference (rad) between the top-`k` kernels' predicted
## positions as seen from `(selfX, selfY)`. `k <= 4` per spec. Fewer than two
## usable samples => 0 (nothing to disagree about).
var pairs: seq[tuple[w: float64, x, y: float64]]
for i in 0 ..< samples.len:
let w = if i < weights.len: weights[i] else: 0.0
pairs.add (w, samples[i].x, samples[i].y)
pairs.sort(proc(a, b: tuple[w: float64, x, y: float64]): int = cmp(b.w, a.w))
let m = min(pairs.len, int(k))
var ang: seq[float64]
for i in 0 ..< m:
ang.add arctan2(pairs[i].y - selfY, pairs[i].x - selfX)
var best = 0.0
for i in 0 ..< ang.len:
for j in i + 1 ..< ang.len:
best = max(best, abs(wrapPi(ang[i] - ang[j])))
best
proc blend*(h: Hedge, mix, res, pers: tuple[x, y: float64]): tuple[x, y: float64] =
## Predictor mixture at one horizon, by the bucket's Hedge weights.
let wm = h.weights[0]
let wr = h.weights[1]
let wp = h.weights[2]
(wm * mix.x + wr * res.x + wp * pers.x,
wm * mix.y + wr * res.y + wp * pers.y)
proc clipToArena*(x, y, arenaW, arenaH: float64): tuple[x, y: float64, clipped: bool] =
let cx = clamp(x, 0.0, max(0.0, arenaW))
let cy = clamp(y, 0.0, max(0.0, arenaH))
(cx, cy, cx != x or cy != y)
proc distBand*(dist: float64): int =
for i in countdown(NDistBands - 1, 0):
if dist >= DistBandLo[i]: return i
0
proc speedBand*(speed: float64): int =
let s = abs(speed)
for i in countdown(NSpeedBands - 1, 0):
if s >= SpeedBandLo[i]: return i
0
# ── construction ────────────────────────────────────────────────────────────
proc initAimer*(): Aimer =
new(result)
for i in 0 ..< NBuckets:
result.bucket[i] = initHedge(PredictorNames)
result.lastFireTick = -1000
# ── predictor trajectories at a horizon ─────────────────────────────────────
proc pointAt*(kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, h: float64): PredictorPoints =
## Roll every predictor to horizon `h` and return their final points. The
## per-kernel samples and posterior weights feed the spread selector.
let k = max(1, int(round(h)))
let mix = rollout(kernels, origin, k)
result.samples = mix.samples
result.weights = origin.weights
if mix.points.len > 0:
result.mix = (mix.points[^1].x, mix.points[^1].y)
let resPts = residualTrajectory(origin, mix.points, rp, k)
if resPts.len > 0: result.res = (resPts[^1].x, resPts[^1].y)
let persPts = persistence(origin, k)
if persPts.len > 0: result.pers = (persPts[^1].x, persPts[^1].y)
proc fusedPositionAt*(a: Aimer, kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, h: float64): tuple[x, y: float64] =
## Horizon-bucketed predictor mixture at `h` (spec G8 `fusedPositionAt`).
let pp = pointAt(kernels, origin, rp, h)
blend(a.bucket[bucketIndex(h)], pp.mix, pp.res, pp.pers)
# ── the per-tick aim ────────────────────────────────────────────────────────
proc biasOffset*(a: Aimer, dist, enemySpeed: float64): float64 =
## Mean observed post-shot miss for this (distance band, speed band), clamped.
let db = distBand(dist)
let sb = speedBand(enemySpeed)
if a.biasN[db][sb] == 0: return 0.0
clamp(a.biasSum[db][sb] / float(a.biasN[db][sb]), -MaxBias, MaxBias)
proc computeAim*(a: Aimer, kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, selfX, selfY,
arenaW, arenaH: float64,
nominalPower = 2.0): TwinAim =
## Flight-horizon aim point + spread-selected power. Pure with respect to the
## world: `a` is only read (bucket weights, bias), never mutated here.
result.selfX = selfX
result.selfY = selfY
let range = hypot(origin.ex - selfX, origin.ey - selfY)
var h = flightTime(range, nominalPower)
var power = nominalPower
var pp = pointAt(kernels, origin, rp, h)
var pos = blend(a.bucket[bucketIndex(h)], pp.mix, pp.res, pp.pers)
var clip = clipToArena(pos.x, pos.y, arenaW, arenaH)
pos = (clip.x, clip.y)
var b = bucketIndex(h)
for it in 0 ..< MaxIter:
let aimDist = hypot(pos.x - selfX, pos.y - selfY)
let tol = angularTolerance(aimDist)
let spread0 = maxPairwiseSpread(pp.samples, pp.weights, selfX, selfY, 4.0)
# Spread at each candidate power's own flight horizon (lazy: break at the
# first admissible power, which is the largest because FirePowers descends).
var spreads: seq[float64]
for p in FirePowers:
let hp = flightTime(aimDist, p)
if abs(hp - h) < 0.5:
spreads.add spread0
else:
spreads.add maxPairwiseSpread(pointAt(kernels, origin, rp, hp).samples,
pp.weights, selfX, selfY, 4.0)
power = selectPowerFromSpreads(spreads, tol)
let h2 = flightTime(aimDist, power)
if abs(h2 - h) < MinorStep: break
h = h2
pp = pointAt(kernels, origin, rp, h)
b = bucketIndex(h)
pos = blend(a.bucket[b], pp.mix, pp.res, pp.pers)
let c = clipToArena(pos.x, pos.y, arenaW, arenaH)
pos = (c.x, c.y)
let aimDist = hypot(pos.x - selfX, pos.y - selfY)
let baseBearing = arctan2(pos.y - selfY, pos.x - selfX)
let bias = a.biasOffset(aimDist, origin.espeed)
result.active = true
result.bucket = b
result.mixPt = pp.mix
result.resPt = pp.res
result.persPt = pp.pers
result.x = pos.x
result.y = pos.y
result.power = power
result.spread = maxPairwiseSpread(pp.samples, pp.weights, selfX, selfY, 4.0)
result.tolerance = angularTolerance(aimDist)
result.horizon = h
result.baseBearing = baseBearing
result.dist = aimDist
result.enemySpeed = origin.espeed
result.aimBearing = wrapPi(baseBearing + bias)
proc cooldownTicks*(spreadRad: float64): int =
## Conservative cadence: the gun cannot spray. A tiny spread allows the fast
## cadence; otherwise at least `NormalCooldown` ticks between shots.
if radToDeg(spreadRad) <= TinySpreadDeg: TinyCooldown else: NormalCooldown
# ── online scoring / bias training ──────────────────────────────────────────
proc noteShot*(a: var Aimer, aim: TwinAim, tick: int) =
## Arm a fired twin-gun shot for delayed scoring. `dueTick` is the flight
## horizon used at fire time; the realized enemy position then trains BOTH the
## bucket's predictor Hedge and the segment bias histogram.
let due = tick + max(1, int(round(aim.horizon)))
if a.pending.len >= 64: a.pending.delete(0)
a.pending.add PendingShot(dueTick: due, bucket: aim.bucket,
selfX: aim.selfX, selfY: aim.selfY,
aimBearing: aim.aimBearing, dist: aim.dist,
enemySpeed: aim.enemySpeed,
mixPt: aim.mixPt, resPt: aim.resPt, persPt: aim.persPt)
a.lastFireTick = tick
inc a.shots
proc resolve*(a: var Aimer, tick: int, enemyX, enemyY: float64) =
## Called on every scan tick. Scores every pending shot whose horizon has
## elapsed against the realized enemy position: updates the bucket Hedge
## (distance-error loss per predictor) and the bias histogram (bearing miss).
var i = 0
while i < a.pending.len:
let p = a.pending[i]
if tick < p.dueTick:
inc i
continue
let dm = hypot(p.mixPt.x - enemyX, p.mixPt.y - enemyY)
let dr = hypot(p.resPt.x - enemyX, p.resPt.y - enemyY)
let dp = hypot(p.persPt.x - enemyX, p.persPt.y - enemyY)
a.bucket[p.bucket].update([dm / 100.0, dr / 100.0, dp / 100.0])
let actualBearing = arctan2(enemyY - p.selfY, enemyX - p.selfX)
let db = distBand(p.dist)
let sb = speedBand(p.enemySpeed)
a.biasSum[db][sb] += wrapPi(actualBearing - p.aimBearing)
inc a.biasN[db][sb]
if dm <= BotRadius: inc a.hits
a.pending.delete(i)
proc bucketWeights*(a: Aimer, b: int): seq[float64] =
a.bucket[b].weights
@@ -0,0 +1,139 @@
## CHIMERA debug overlay — observation-only SVG drawing.
##
## The bot API has **no** `setDebugGraphics` object to hand around. Debug
## graphics in `robocode_tankroyale_botapi` 1.0.7 are drawn with module-global
## procs that append to an internal SVG buffer:
##
## setStrokeColor / setFillColor / setStrokeWidth / setFont (style)
## drawLine, drawCircle, fillCircle, drawText, drawRectangle ... (geometry)
##
## `go()` serialises that buffer into `BotIntent.debugGraphics` via
## `graphics.svgOutput()` and then `clearGraphics()`s it, so anything drawn
## before `go()` reaches the viewer for THIS tick and costs nothing after.
##
## Everything here is OBSERVATION-ONLY:
## * `buildOverlay` is a PURE function of a plain snapshot — no API state, no
## clock, no RNG — so it is deterministic and directly unit-testable;
## * `renderOverlay` maps the primitives to the drawing procs above and never
## touches command state (target speed, turn rates, fire), so the command
## path is byte-identical with the overlay on or off (pinned by
## `tests/test_debugdraw.nim`).
##
## Cost gate: `renderOverlay` compiles to an empty stub unless `-d:chimeraDebug`
## is set, and `ChimeraBot.nim` does not even build the primitive list without
## the define. Budget: `MaxDebugPrims` primitives per tick.
import std/[math, strutils]
import robocode_tankroyale_botapi
const
OverlayEnabled* = defined(chimeraDebug)
MaxDebugPrims* = 10 ## hard per-tick budget (~10 requested)
ProbeFlashTicks* = 5 ## how long a probe marker persists
type
DKind* = enum dkText, dkLine, dkCircle, dkDot
DebugPrim* = object
## One drawable primitive. `rgba` packs 0xRRGGBBAA, the API Color layout.
kind*: DKind
x*, y*: float
x2*, y2*: float
r*: float
text*: string
rgba*: uint32
OverlayInput* = object
## Plain snapshot the bot assembles from the observer; the builder reads
## nothing else.
selfX*, selfY*: float
kernelName*: string
kernelP*: float
entropy*: float
pFire5*: float
enemyX*, enemyY*: float
haveEnemy*: bool
predX*, predY*: float
havePred*: bool
fresh*: bool
censored*: bool
scanGap*: int
probeLabel*: string
probeFlash*: bool
# Colours chosen distinct from tfilDebug's palette (which uses red bullets,
# #FF8800 auras, cyan enemies, green safe tiles): cyan identity, red fire,
# yellow probes, grey scan-health, spring-green counterfactual.
const
ColIdentity = 0x00FFFFFF'u32
ColProbe = 0xFFFF00FF'u32
ColScan = 0x808080FF'u32
ColPred = 0x00FF88FF'u32
proc fireRgba(p: float): uint32 =
## Fire-circle colour ramps toward full red as P rises; alpha rises too.
let t = clamp(p, 0.0, 1.0)
let g = uint32(200.0 * (1.0 - t))
let a = uint32(90.0 + 150.0 * t)
(0xFF'u32 shl 24) or (g shl 16) or a
proc buildOverlay*(inp: OverlayInput): seq[DebugPrim] =
## Pure, deterministic primitive builder. Fixed order: reruns on the same
## input are byte-identical (pinned by test_debugdraw).
if inp.kernelName.len > 0:
# (a) IDENTITY BLOCK — kernel + top-1 posterior + entropy, then P(fire5).
result.add DebugPrim(kind: dkText,
text: inp.kernelName & " " & $int(inp.kernelP * 100.0 + 0.5) &
"% H=" & formatFloat(inp.entropy, ffDecimal, 2),
x: inp.selfX + 20.0, y: inp.selfY + 34.0, rgba: ColIdentity)
result.add DebugPrim(kind: dkText,
text: "P(fire5)=" & $int(clamp(inp.pFire5, 0.0, 1.0) * 100.0 + 0.5) & "%",
x: inp.selfX + 20.0, y: inp.selfY + 20.0, rgba: ColIdentity)
if inp.haveEnemy:
# (b) FIRE PREDICTION — radius/opacity/colour encode fused P(fire within 5).
result.add DebugPrim(kind: dkCircle, x: inp.enemyX, y: inp.enemyY,
r: 20.0 + 60.0 * clamp(inp.pFire5, 0.0, 1.0),
rgba: fireRgba(inp.pFire5))
if inp.fresh and not inp.censored and inp.havePred and inp.haveEnemy:
# (c) COUNTERFACTUAL — enemy now -> fused 5-tick predicted position.
result.add DebugPrim(kind: dkLine, x: inp.enemyX, y: inp.enemyY,
x2: inp.predX, y2: inp.predY, rgba: ColPred)
result.add DebugPrim(kind: dkDot, x: inp.predX, y: inp.predY, r: 6.0,
rgba: (ColPred and 0xFFFFFF00'u32) or 0x80'u32)
if inp.probeFlash and inp.probeLabel.len > 0:
# (d) PROBE MARKER — type label + flash near our bot (persists ~5 ticks).
result.add DebugPrim(kind: dkText, text: "probe:" & inp.probeLabel,
x: inp.selfX - 40.0, y: inp.selfY + 48.0, rgba: ColProbe)
result.add DebugPrim(kind: dkDot, x: inp.selfX, y: inp.selfY, r: 10.0,
rgba: ColProbe)
if inp.scanGap > 1 or inp.censored:
# (e) SCAN HEALTH — rare grey tick when the stream is not clean.
result.add DebugPrim(kind: dkDot, x: inp.selfX - 18.0, y: inp.selfY + 48.0,
r: 4.0, rgba: ColScan)
if result.len > MaxDebugPrims:
result.setLen(MaxDebugPrims)
proc renderOverlay*(prims: openArray[DebugPrim]) =
## Map primitives to the API's global drawing procs. `Color` shares the
## 0xRRGGBBAA packing, so `Color(rgba)` is exact.
when defined(chimeraDebug):
for p in prims:
let c = Color(p.rgba)
case p.kind
of dkText:
setFillColor(c)
setFont("Arial", 11.0)
drawText(p.text, p.x, p.y)
of dkLine:
setStrokeColor(c)
setStrokeWidth(1.5)
drawLine(p.x, p.y, p.x2, p.y2)
of dkCircle:
setStrokeColor(c)
setStrokeWidth(1.5)
drawCircle(p.x, p.y, p.r)
of dkDot:
setFillColor(c)
fillCircle(p.x, p.y, p.r)
else:
discard
@@ -107,7 +107,9 @@ proc residualTrajectory*(origin: ReplayTick, mix: seq[RolloutPoint],
let baseSpeed = (if h < mix.len: mix[h].targetSpeed else: origin.lastSpeed)
let ts = clamp(baseSpeed + rp.speed, MaxBackwardSpeed, MaxForwardSpeed)
sp = stepSpeed(sp, ts)
dir = wrap180(dir + limitTurnRate(baseTurn + rp.turn, sp))
# The residual head is trained on `realized - capped(mixture command)` (M6.5),
# so cap the base before adding the correction: training/inference symmetry.
dir = wrap180(dir + limitTurnRate(baseTurn, sp) + rp.turn)
x += sp * cos(degToRad(dir))
y += sp * sin(degToRad(dir))
result.add (x, y)
@@ -0,0 +1,304 @@
## CHIMERA G2 — kernel identifiability certificate (spec §12, G2).
##
## For every unordered kernel pair `(Ki, Kj)` this module searches probe
## sequences over the spec §9 probe types (movement stop/reverse/speed-mod/flip,
## a DISTANCE burst, a GUN shot, and noop) up to `G2Lmax` ticks and scores how
## far the enemy-intent *distributions* the two kernels induce separate on a
## fixed canonical start-state set.
##
## Design (spec wording governs where it differs):
##
## * A probe sequence is a plan for OUR bot. Each kernel is rolled forward with
## `twinsim`'s physics (stepSpeed / limitTurnRate / wrap180) under that plan,
## from every state in `canonicalStarts()`. Our own action changes our
## `MyState` input, so the kernels' reactions — the counterfactual — change.
## * Separation at tick `t` is the **total variation** between the two kernels'
## empirical distributions over the joint discretized enemy intent
## `(turnRate, targetSpeed, fire)` across the canonical start states. The
## sequence score is the per-tick TV **averaged over the sequence**.
## * `sep[L]` is the best score over all sequences of length `<= L` (so it is
## monotone non-decreasing by construction). `L_ij` is the smallest `L` with
## `sep[L] >= G2Delta`; if none within `G2Lmax` the pair is UNIDENTIFIABLE.
##
## Determinism: fixed start set, fixed alphabet order, depth-first enumeration in
## that order, fixed discretization. Two runs are byte-identical (pinned by
## tests/test_identifiability.nim).
import std/[math, tables, strutils]
import ./physics, ./dsl, ./twinsim
const
G2Lmax* = 6
## longest probe sequence searched (spec: "length <= L", G2 kickoff Lmax=6).
G2Delta* = 0.3
## separation threshold `delta`. The spec leaves `delta` open, so we fix the
## total-variation bar at 0.3 (30% mass moved) and document it here.
G2KeyTurn = 1.0 ## intent discretization: 1 deg
G2KeySpeed = 1.0 ## 1 unit/tick
G2KeyFire = 0.1 ## 0.1 firepower (0 stays 0)
type
ProbeAction* = object
## One command for our bot. `repeatPrev` is the noop: keep the previous
## effective command instead of committing a new one.
label*: string
turnRate*: float64
targetSpeed*: float64
fire*: float64
repeatPrev*: bool
StartState* = object
## A canonical enemy/scenario state. Enemy fields first, then our fields.
ex*, ey*, edir*, espeed*, eenergy*: float64
ox*, oy*, odir*, ospeed*: float64
IntentKey* = tuple[turn, speed, fire: int]
PairResult* = object
ki*, kj*: string
identifiable*: bool
lStar*: int ## minimal separating length, 0 when unidentifiable
separation*: float64 ## best separation at `lStar`
prefix*: string ## best probe prefix (labels joined by "+")
PairCurve* = object
sep*: seq[float64] ## sep[L] for L in 1..maxLen (best over length <= L)
prefix*: seq[string] ## best prefix attaining sep[L]
# ── fixed canonical scenario set ────────────────────────────────────────────
proc canonicalStarts*(): seq[StartState] =
## Eight fixed scenarios spanning positions, headings, speeds and energies.
## Deterministic order; the distributions below are over THIS set.
@[
StartState(ex: 100.0, ey: 100.0, edir: 0.0, espeed: 4.0, eenergy: 100.0,
ox: 600.0, oy: 300.0, odir: 180.0, ospeed: 4.0),
StartState(ex: 700.0, ey: 500.0, edir: 90.0, espeed: 0.0, eenergy: 40.0,
ox: 200.0, oy: 300.0, odir: 0.0, ospeed: 0.0),
StartState(ex: 400.0, ey: 300.0, edir: 270.0, espeed: 6.0, eenergy: 100.0,
ox: 100.0, oy: 100.0, odir: 45.0, ospeed: 6.0),
StartState(ex: 50.0, ey: 550.0, edir: 180.0, espeed: -4.0, eenergy: 15.0,
ox: 700.0, oy: 100.0, odir: 225.0, ospeed: 2.0),
StartState(ex: 400.0, ey: 50.0, edir: 0.0, espeed: 8.0, eenergy: 100.0,
ox: 400.0, oy: 550.0, odir: 270.0, ospeed: 8.0),
StartState(ex: 400.0, ey: 550.0, edir: 90.0, espeed: 2.0, eenergy: 5.0,
ox: 400.0, oy: 50.0, odir: 90.0, ospeed: 4.0),
StartState(ex: 750.0, ey: 300.0, edir: 180.0, espeed: 3.0, eenergy: 100.0,
ox: 50.0, oy: 300.0, odir: 0.0, ospeed: 3.0),
StartState(ex: 200.0, ey: 200.0, edir: 315.0, espeed: -2.0, eenergy: 60.0,
ox: 600.0, oy: 400.0, odir: 135.0, ospeed: 5.0),
]
proc probeAlphabet*(): seq[ProbeAction] =
## The seven spec §9 probe types, in fixed deterministic order. `reverse` and
## `distance` are the full backward/forward bursts; `speedmod` is the gentle
## step; `flip` is a hard body turn; `gun` is a low-power shot (inert for the
## current kernels — no hit-response is modelled — kept for spec completeness).
@[
ProbeAction(label: "noop", turnRate: 0.0, targetSpeed: 0.0,
fire: 0.0, repeatPrev: true),
ProbeAction(label: "stop", turnRate: 0.0, targetSpeed: 0.0, fire: 0.0),
ProbeAction(label: "reverse", turnRate: 0.0, targetSpeed: MaxBackwardSpeed,
fire: 0.0),
ProbeAction(label: "speedmod", turnRate: 0.0, targetSpeed: 4.0, fire: 0.0),
ProbeAction(label: "flip", turnRate: MaxTurnRate, targetSpeed: 0.0, fire: 0.0),
ProbeAction(label: "distance", turnRate: 0.0, targetSpeed: MaxForwardSpeed,
fire: 0.0),
ProbeAction(label: "gun", turnRate: 0.0, targetSpeed: 0.0,
fire: MinFirepower),
]
# ── intent discretization + total variation ─────────────────────────────────
proc intentKey*(it: Intent): IntentKey =
## Discretize an intent to a joint histogram key. Fire 0 stays 0.
let f = if it.fire <= 0.0: 0.0 else: it.fire
(turn: int(round(clamp(it.turnRate, -MaxTurnRate, MaxTurnRate) / G2KeyTurn)),
speed: int(round(clamp(it.targetSpeed, MaxBackwardSpeed, MaxForwardSpeed) /
G2KeySpeed)),
fire: int(round(clamp(f, 0.0, 3.0) / G2KeyFire)))
proc totalVariation*(ki, kj: openArray[IntentKey]): float64 =
## TV between two empirical distributions over the union of keys.
if ki.len == 0 or kj.len == 0: return 0.0
var a = initCountTable[IntentKey]()
var b = initCountTable[IntentKey]()
for k in ki: a.inc k
for k in kj: b.inc k
let fa = 1.0 / float(ki.len)
let fb = 1.0 / float(kj.len)
var acc = 0.0
for k, c in a:
let other = b.getOrDefault(k)
acc += abs(float(c) * fa - float(other) * fb)
for k, c in b:
if k notin a:
acc += abs(float(c) * fb)
acc / 2.0
# ── single-kernel trace (for tests / inspection) ────────────────────────────
proc traceKernel*(k: Kernel, st: StartState,
plan: openArray[ProbeAction]): seq[Intent] =
## Roll one kernel forward under our plan and return its per-tick intent.
## Physics mirrors `twinsim.rollout`'s single-kernel path.
var e = EnemyState(tick: 0, x: st.ex, y: st.ey, direction: st.edir,
speed: st.espeed, energy: st.eenergy)
var mem = defaultMemory(k.defaultParams)
var myX = st.ox
var myY = st.oy
var myDir = st.odir
var mySpeed = st.ospeed
var gTurn = 0.0
var gSpeed = 0.0
for h in 0 ..< plan.len:
let a = plan[h]
let effTurn = if a.repeatPrev: gTurn else: a.turnRate
let effSpeed = if a.repeatPrev: gSpeed else: a.targetSpeed
gTurn = effTurn
gSpeed = effSpeed
mySpeed = stepSpeed(mySpeed, effSpeed)
myDir = wrap180(myDir + limitTurnRate(effTurn, mySpeed))
myX += mySpeed * cos(degToRad(myDir))
myY += mySpeed * sin(degToRad(myDir))
let it = k.step(e, MyState(x: myX, y: myY), k.defaultParams, mem)
let ns = stepSpeed(e.speed, it.targetSpeed)
e.direction = wrap180(e.direction + limitTurnRate(it.turnRate, ns))
e.speed = ns
e.x = clamp(e.x + ns * cos(degToRad(e.direction)), 0.0,
k.defaultParams.arenaW)
e.y = clamp(e.y + ns * sin(degToRad(e.direction)), 0.0,
k.defaultParams.arenaH)
e.tick = h + 1
result.add it
# ── exhaustive short-sequence search ────────────────────────────────────────
proc searchCurve(ki, kj: Kernel, starts: seq[StartState],
alphabet: seq[ProbeAction], maxLen: int): PairCurve =
## Depth-first search over sequences of length up to `maxLen`. Tracks the best
## per-tick-averaged separation at each exact depth, then takes the running
## maximum, so `sep[L]` is the best score over all sequences of length <= L.
let n = starts.len
result.sep = newSeq[float64](maxLen + 1)
result.prefix = newSeq[string](maxLen + 1)
var bestExact = newSeq[float64](maxLen + 1)
var bestSeq = newSeq[seq[string]](maxLen + 1)
for i in 0 .. maxLen: bestExact[i] = -1.0
var ei = newSeq[EnemyState](n)
var mi = newSeq[KernelMem](n)
var ej = newSeq[EnemyState](n)
var mj = newSeq[KernelMem](n)
var myX = newSeq[float64](n)
var myY = newSeq[float64](n)
var myDir = newSeq[float64](n)
var mySpeed = newSeq[float64](n)
for s in 0 ..< n:
let st = starts[s]
ei[s] = EnemyState(tick: 0, x: st.ex, y: st.ey, direction: st.edir,
speed: st.espeed, energy: st.eenergy)
ej[s] = ei[s]
mi[s] = defaultMemory(ki.defaultParams)
mj[s] = defaultMemory(kj.defaultParams)
myX[s] = st.ox
myY[s] = st.oy
myDir[s] = st.odir
mySpeed[s] = st.ospeed
var keysI = newSeq[IntentKey](n)
var keysJ = newSeq[IntentKey](n)
var path = newSeq[string](maxLen)
var gTurn = 0.0
var gSpeed = 0.0
proc rec(d: int; cumTV: float64) =
if d >= 1:
let avg = cumTV / float(d)
if avg > bestExact[d]:
bestExact[d] = avg
bestSeq[d] = path[0 ..< d]
if d == maxLen: return
for a in alphabet:
let effTurn = if a.repeatPrev: gTurn else: a.turnRate
let effSpeed = if a.repeatPrev: gSpeed else: a.targetSpeed
let oldTurn = gTurn
let oldSpeed = gSpeed
gTurn = effTurn
gSpeed = effSpeed
for s in 0 ..< n:
mySpeed[s] = stepSpeed(mySpeed[s], effSpeed)
myDir[s] = wrap180(myDir[s] + limitTurnRate(effTurn, mySpeed[s]))
myX[s] += mySpeed[s] * cos(degToRad(myDir[s]))
myY[s] += mySpeed[s] * sin(degToRad(myDir[s]))
let iti = ki.step(ei[s], MyState(x: myX[s], y: myY[s]),
ki.defaultParams, mi[s])
let itj = kj.step(ej[s], MyState(x: myX[s], y: myY[s]),
kj.defaultParams, mj[s])
let nsi = stepSpeed(ei[s].speed, iti.targetSpeed)
ei[s].direction = wrap180(ei[s].direction + limitTurnRate(iti.turnRate, nsi))
ei[s].speed = nsi
ei[s].x = clamp(ei[s].x + nsi * cos(degToRad(ei[s].direction)), 0.0,
ki.defaultParams.arenaW)
ei[s].y = clamp(ei[s].y + nsi * sin(degToRad(ei[s].direction)), 0.0,
ki.defaultParams.arenaH)
ei[s].tick = d + 1
let nsj = stepSpeed(ej[s].speed, itj.targetSpeed)
ej[s].direction = wrap180(ej[s].direction + limitTurnRate(itj.turnRate, nsj))
ej[s].speed = nsj
ej[s].x = clamp(ej[s].x + nsj * cos(degToRad(ej[s].direction)), 0.0,
kj.defaultParams.arenaW)
ej[s].y = clamp(ej[s].y + nsj * sin(degToRad(ej[s].direction)), 0.0,
kj.defaultParams.arenaH)
ej[s].tick = d + 1
keysI[s] = intentKey(iti)
keysJ[s] = intentKey(itj)
let tv = totalVariation(keysI, keysJ)
path[d] = a.label
rec(d + 1, cumTV + tv)
gTurn = oldTurn
gSpeed = oldSpeed
rec(0, 0.0)
# Running maximum over lengths: best score over sequences of length <= L.
var runBest = -1.0
var runPrefix = ""
for L in 1 .. maxLen:
if bestExact[L] > runBest:
runBest = bestExact[L]
runPrefix = bestSeq[L].join("+")
result.sep[L] = runBest
result.prefix[L] = runPrefix
proc kernelPairCurve*(ki, kj: Kernel, starts: seq[StartState],
alphabet: seq[ProbeAction],
maxLen = G2Lmax): PairCurve =
searchCurve(ki, kj, starts, alphabet, maxLen)
proc certifyPair*(ki, kj: Kernel, starts: seq[StartState],
alphabet: seq[ProbeAction],
maxLen = G2Lmax, delta = G2Delta): PairResult =
## Minimal separating length for one kernel pair, or UNIDENTIFIABLE.
result.ki = ki.name
result.kj = kj.name
let curve = kernelPairCurve(ki, kj, starts, alphabet, maxLen)
for L in 1 .. maxLen:
if curve.sep[L] >= delta:
result.identifiable = true
result.lStar = L
result.separation = curve.sep[L]
result.prefix = curve.prefix[L]
return
result.identifiable = false
result.lStar = 0
result.separation = curve.sep[maxLen]
result.prefix = curve.prefix[maxLen]
proc identifiabilityCertificate*(kernels: seq[Kernel],
starts = canonicalStarts(),
alphabet = probeAlphabet(),
maxLen = G2Lmax,
delta = G2Delta): seq[PairResult] =
## The 66-row certificate over every unordered kernel pair (Ki,Kj), i<j.
for i in 0 ..< kernels.len:
for j in i + 1 ..< kernels.len:
result.add certifyPair(kernels[i], kernels[j], starts, alphabet, maxLen, delta)
@@ -19,7 +19,7 @@
## readiness check for the M4 twin rollout, not the twin itself.
import std/[math, os, strutils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence, ./aimer, ./virtual_guns
const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
@@ -70,6 +70,17 @@ type
# itself runs in the bot's command path.
residual: ResidualHead
fusion: Fusion
# M7 twin gun (G8): horizon-bucketed predictor Hedge + aim-bias corrector.
# Lives here because it is fed the same scan stream; it persists per match.
aimer: Aimer
gunAimDeg*, gunPower*, gunSpreadDeg*, gunInfluence*: float64
twinActive*: bool
# M7.5 virtual-gun tournament (G8). Scores every candidate's virtual bullet
# against the realized enemy position; selects the gun the bot fires.
vguns*: VirtualGunSet
gunFiredLabel*: string ## which gun the tournament fired (telemetry only)
prevOwnDir, prevOwnSpeed: float64
lastRealizedTurn, lastRealizedSpeed: float64
fireRateEma: float64
@@ -97,6 +108,8 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer =
result.enemyHeat = 3.0
result.residual = initResidualHead()
result.fusion = initFusion()
result.aimer = initAimer()
result.vguns = initVirtualGuns()
result.carryOver = not defined(chimeraFreshRound)
for i in 0 ..< PredSlots: result.predOrigin[i] = -1
@@ -244,6 +257,9 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6
o.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed
return
# M7 twin gun: score any fired twin-gun shot whose flight horizon elapsed.
o.aimer.resolve(tick, x, y)
o.scoreScan(s)
if o.havePrev:
@@ -265,23 +281,34 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6
energy: o.prev.energy)
let my = MyState(x: o.prevOwnX, y: o.prevOwnY)
var losses = newSeq[float64](o.kernels.len)
var mixTurn, mixSpeed, mixFire = 0.0
var mixTurn, mixSpeed, mixFireP = 0.0
for i in 0 ..< o.kernels.len:
let pred = o.kernels[i].step(e, my, o.kernels[i].defaultParams, o.mems[i])
losses[i] = intentLoss(pred, obs, s.speed)
let w = o.hedge.weights[i]
mixTurn += w * pred.turnRate
mixSpeed += w * pred.targetSpeed
mixFire += w * pred.fire
# Fire is a Bernoulli channel: the fusion scores a PROBABILITY, and
# `intentLoss` already binarizes the kernel's predicted power. Using the
# weighted POWER here made `mixFire` ~= 1 wherever a high-power kernel had
# mass, wrecking the mixture's log-loss and letting the residual absorb
# the artefact (M6.5).
mixFireP += w * (if pred.fire > 0.0: 1.0 else: 0.0)
o.hedge.update(losses)
when FusionEnabled:
# Residual + fusion training (spec §10): learn the mixture's residual on
# THIS realized intent, then score the three predictors. Observation
# only — nothing here can change a command.
# Compare like with like (M6.5). The realized ledger turn is the REALIZED
# (server-capped) turn, while `mixTurn` is the mixture's raw turn
# COMMAND. Score the mixture's physical turn — capped at the realized
# speed, exactly as `intentLoss` caps its prediction — otherwise the
# linear residual trivially absorbs the `limitTurnRate` gap and dominates
# the fusion (measured 0.94 weight on an ORBIT_BALLIST oracle stream).
let mixTurnReal = limitTurnRate(mixTurn, s.speed)
let realizedFireP = (if obs.fireKnown: (if obs.fire > 0.0: 1.0 else: 0.0)
else: mixFireP)
let realized = PredIntent(
turn: (if obs.turnKnown: (obs.turnRate.lo + obs.turnRate.hi) / 2.0 else: mixTurn),
turn: (if obs.turnKnown: (obs.turnRate.lo + obs.turnRate.hi) / 2.0 else: mixTurnReal),
speed: (if obs.targetKnown: (obs.targetSpeed.lo + obs.targetSpeed.hi) / 2.0 else: mixSpeed),
fire: (if obs.fireKnown: obs.fire else: mixFire))
fire: realizedFireP)
let feat = features(ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: float64(s.tick - o.prev.tick),
@@ -291,13 +318,13 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6
let persP = PredIntent(turn: o.lastRealizedTurn,
speed: o.lastRealizedSpeed, fire: o.fireRateEma)
o.fusion.update(realized, [
PredIntent(turn: mixTurn, speed: mixSpeed, fire: mixFire),
PredIntent(turn: mixTurn + rpred.turn, speed: mixSpeed + rpred.speed,
fire: clamp(mixFire + rpred.fire, 0.0, 1.0)),
PredIntent(turn: mixTurnReal, speed: mixSpeed, fire: mixFireP),
PredIntent(turn: mixTurnReal + rpred.turn, speed: mixSpeed + rpred.speed,
fire: clamp(mixFireP + rpred.fire, 0.0, 1.0)),
persP])
o.residual.observe(feat, ResidualTarget(
turn: realized.turn - mixTurn, speed: realized.speed - mixSpeed,
fire: realized.fire - mixFire))
turn: realized.turn - mixTurnReal, speed: realized.speed - mixSpeed,
fire: realizedFireP - mixFireP))
o.lastRealizedTurn = realized.turn
o.lastRealizedSpeed = realized.speed
if obs.fireKnown:
@@ -358,10 +385,76 @@ proc fusedInfluence*(o: Observer): float64 =
## Twin steering authority (0..1), ramped down by realized prediction loss.
influenceScalar(o.fusion.lossEma, o.fusion.lossN)
# ── M7 twin gun (G8) ────────────────────────────────────────────────────────
proc twinAim*(o: Observer, selfX, selfY, arenaW, arenaH: float64,
nominalPower = 2.0): TwinAim =
## Flight-horizon aim point at the current origin. Empty (`.active == false`)
## when no scan has been seen yet, so the caller falls back to the ELM gun.
if not o.haveCur: return
let origin = o.probeOrigin()
let rp = o.residual.predict(features(o.currentResidualInput()))
o.aimer.computeAim(o.kernels, origin, rp, selfX, selfY,
arenaW, arenaH, nominalPower)
proc noteTwinShot*(o: Observer, aim: TwinAim, tick: int) =
## Arm a fired twin-gun shot for delayed scoring / bias training.
o.aimer.noteShot(aim, tick)
proc twinGunLastFire*(o: Observer): int = o.aimer.lastFireTick
proc twinGunShots*(o: Observer): int = o.aimer.shots
proc twinGunHits*(o: Observer): int = o.aimer.hits
proc setGunTelemetry*(o: Observer, aimDeg, power, spreadDeg, influence: float64,
active: bool) =
## Observation-only: record the twin gun's output for the JSONL telemetry.
o.gunAimDeg = aimDeg
o.gunPower = power
o.gunSpreadDeg = spreadDeg
o.gunInfluence = influence
o.twinActive = active
# ── M7.5 virtual-gun tournament (G8) ────────────────────────────────────────
proc vgunStep*(o: Observer, ex, ey, hitRadius, arenaW, arenaH: float64) =
## Advance/resolve the virtual bullets against the realized enemy position.
o.vguns.vgTick(ex, ey, hitRadius, arenaW, arenaH)
proc vgunLaunch*(o: Observer, g: VGun, x, y, bearing, power: float64) =
## Spawn a candidate's virtual bullet (absolute bearing, radians).
o.vguns.launchVirtual(g, x, y, bearing, power)
proc vgunSelect*(o: Observer, twinEligible: bool): VGun =
o.vguns.selectGun(twinEligible = twinEligible)
proc vgunScore*(o: Observer, g: VGun): float64 = o.vguns.emaOf(g)
proc vgunShots*(o: Observer, g: VGun): int = o.vguns.shotsOf(g)
proc setGunFired*(o: Observer, g: VGun) =
## Observation-only: record which gun the tournament fired.
o.gunFiredLabel = gunName(g)
proc currentEnemy*(o: Observer): tuple[x, y: float64] = (o.cur.x, o.cur.y)
proc resetVguns*(o: Observer) =
## New game = new opponent; drop the per-gun statistics.
o.vguns.resetVguns()
proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
proc fusionSamples*(o: Observer): int = o.fusion.lossN
# ── debug-overlay accessors (observation-only; read-only) ───────────────────
# These exist purely for the `-d:chimeraDebug` overlay in debugdraw.nim. They
# expose already-computed observer state and never issue a command.
proc topKernel*(o: Observer): tuple[name: string, weight: float64] =
let t = o.hedge.topK(1)
if t.len > 0: t[0] else: (name: "", weight: 0.0)
proc lastScanPos*(o: Observer): tuple[x, y: float64] = (o.cur.x, o.cur.y)
proc scanTick*(o: Observer): int = o.scanTick
proc lastCensored*(o: Observer): bool = o.haveLastObs and o.lastObs.censored
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
entropyBefore, entropyAfter, turnRate,
targetSpeed: float64) =
@@ -406,6 +499,12 @@ proc writeTick*(o: Observer, tick: int) =
line.add "{\"name\":\"" & kv.name & "\",\"w\":" & $kv.weight & "}"
line.add "],\"entropy\":" & $o.hedge.entropy()
line.add ",\"censorRate\":" & $o.censorRate()
# M7 twin-gun telemetry (observation-only; zeroed when the twin gun is off).
line.add ",\"gunAim\":" & $o.gunAimDeg & ",\"gunPower\":" & $o.gunPower &
",\"spread\":" & $o.gunSpreadDeg &
",\"influence\":" & $o.gunInfluence &
",\"twinGun\":" & $(if o.twinActive: "true" else: "false") &
",\"gunFired\":\"" & o.gunFiredLabel & "\""
line.add "}\n"
o.f.write(line)
flushFile(o.f)
@@ -0,0 +1,178 @@
## CHIMERA virtual-gun tournament (M7.5, spec G8).
##
## Classic Robocode **Virtual Guns** pattern (provenance:
## https://robowiki.net/wiki/Virtual_Guns): instead of committing to one gun,
## keep a small set of candidate guns, simulate a "virtual" bullet for each,
## score the realized outcome, and fire whichever gun is currently best. The
## RoboWiki describes exactly this shape — virtual bullets + per-gun hit
## statistics — as the standard way to choose among targeting strategies online;
## M7.5 uses it to answer the M7 live-saturation finding (every single-gun arm
## won 100% of rounds, so one gun could not be shown to be better).
##
## Candidates here are:
## * `vgTwin` — `chimera/aimer.nim` flight-horizon aim (its power included);
## * `vgElm` — the ELM gun's geometric-intercept base (`heuristicAim`);
## * `vgHeadOn` — aim at the enemy's current scanned position (no lead).
##
## Scoring is deterministic and pure: each launched virtual bullet advances one
## step per tick until it either comes within `hitRadius` of the observed enemy
## (a hit) or leaves the arena (a miss). A resolved shot updates that gun's
## **damage-weighted** EMA and an exponentially-forgetting accumulator
## (`tau = 200` ticks). Firing is the argmax EMA with **hysteresis**: the current
## gun is kept unless a rival leads it by more than `SwitchMargin` (0.1), so the
## selection cannot flap. Nothing here reads the clock, the RNG or the file
## system; the whole path is removed by `-d:chimeraNoVguns`.
import std/math
import ./physics
const
NoVguns* = defined(chimeraNoVguns)
## Kill switch: with this defined the bot never calls the tournament and the
## M7 influence-gated twin/ELM path is byte-identical.
ForgettingTau* = 200.0
## Exponential-forgetting time constant, in *ticks*, for the accumulator
## (`sum`/`weight` decayed once per tick by `exp(-1/tau)`).
EmaTau* = 100.0
## Per-gun EMA time constant, in *resolved shots*. Deliberately faster than
## the tau=200 accumulator: the selection must be able to react within a
## round (a few dozen resolved virtual bullets), while the accumulator keeps
## a longer-horizon estimate. `SwitchMargin` (0.1) is compared on this EMA.
SwitchMargin* = 0.1
## Hysteresis: a rival gun must lead the incumbent by more than this EMA
## difference before the tournament switches.
MinEvidence* = 12
## Never switch away from the incumbent until the leading rival has this many
## resolved virtual shots. Without it the first few noisy shots can lock in a
## bad gun for a long stretch.
RefDamage* = 6.0
## Damage reference (4*power at power 1.5). Used only by the long-horizon
## damage-per-shot accumulator; the selection EMA is a plain hit rate so the
## 0.1 hysteresis margin is meaningful and power differences do not bias the
## selection (the G8.5 bar is a hit-rate bar).
type
VGun* = enum
vgTwin, vgElm, vgHeadOn
GunScore* = object
ema*: float64 ## hit-rate EMA in [0,1] (selection key)
sum*, weight*: float64 ## exponentially-forgetting accumulator
shots*: int
VirtualBullet* = object
gun*: VGun
active*: bool
x*, y*, vx*, vy*: float64
power*: float64
VirtualGunSet* = object
score*: array[VGun, GunScore]
bullets*: seq[VirtualBullet]
selected*: VGun
haveSelected*: bool
proc initVirtualGuns*(): VirtualGunSet =
result.selected = vgTwin
result.haveSelected = false
proc gunName*(g: VGun): string =
case g
of vgTwin: "twin"
of vgElm: "elm"
of vgHeadOn: "headon"
proc emaOf*(v: VirtualGunSet, g: VGun): float64 = v.score[g].ema
proc decayedRate*(v: VirtualGunSet, g: VGun): float64 =
## The long-horizon, damage-weighted average (mean damage per resolved shot).
## Zero until the first resolved shot.
if v.score[g].weight <= 1e-9: 0.0 else: v.score[g].sum / v.score[g].weight
proc shotsOf*(v: VirtualGunSet, g: VGun): int = v.score[g].shots
proc forgetTick*(v: var VirtualGunSet, tau = ForgettingTau) =
## One tick of exponential forgetting on the accumulators. `tau` is in ticks.
let d = exp(-1.0 / tau)
for g in VGun:
v.score[g].sum *= d
v.score[g].weight *= d
proc observeShot*(v: var VirtualGunSet, g: VGun, hit: bool, power: float64,
emaTau = EmaTau) =
## Score one resolved virtual shot. The **EMA tracks the hit rate** (0/1) and
## is the selection key; the accumulator tracks the **damage-weighted** outcome
## (`4*power`, plus the over-1 bonus, on a hit; 0 on a miss).
let hitOutcome = if hit: 1.0 else: 0.0
let damage = if hit:
let d = 4.0 * power
(if power > 1.0: d + 2.0 * (power - 1.0) else: d)
else: 0.0
let alpha = 1.0 - exp(-1.0 / emaTau)
v.score[g].ema = v.score[g].ema + alpha * (hitOutcome - v.score[g].ema)
v.score[g].sum += damage
v.score[g].weight += 1.0
inc v.score[g].shots
proc launchVirtual*(v: var VirtualGunSet, g: VGun, x, y, bearing, power: float64) =
## Spawn the virtual bullet for candidate `g` at (x,y) along `bearing`
## (radians) at `power`. Velocity comes from the physics mirror.
let sp = bulletSpeed(power)
v.bullets.add VirtualBullet(gun: g, active: true, x: x, y: y,
vx: sp * cos(bearing), vy: sp * sin(bearing),
power: power)
proc stepVirtual*(v: var VirtualGunSet, ex, ey, hitRadius, arenaW, arenaH: float64) =
## Advance every live virtual bullet one tick and resolve the ones that hit the
## observed enemy or leave the arena.
var keep: seq[VirtualBullet]
for b in v.bullets:
var bu = b
bu.x += bu.vx
bu.y += bu.vy
if bu.x < 0.0 or bu.x > arenaW or bu.y < 0.0 or bu.y > arenaH:
v.observeShot(bu.gun, false, bu.power)
continue
if hypot(bu.x - ex, bu.y - ey) <= hitRadius:
v.observeShot(bu.gun, true, bu.power)
continue
keep.add bu
v.bullets = keep
proc vgTick*(v: var VirtualGunSet, ex, ey, hitRadius, arenaW, arenaH: float64,
tau = ForgettingTau) =
## One tournament tick: forget a little, then advance/resolve every bullet.
v.forgetTick(tau)
v.stepVirtual(ex, ey, hitRadius, arenaW, arenaH)
proc selectGun*(v: var VirtualGunSet, margin = SwitchMargin,
twinEligible = true): VGun =
## argmax EMA with hysteresis. `twinEligible = false` keeps the M7 influence
## gate: the twin candidate cannot be chosen (but still scores). The incumbent
## is kept unless the best eligible rival leads it by more than `margin`.
var best = vgHeadOn
var bestScore = -1.0
var any = false
for g in VGun:
if g == vgTwin and not twinEligible: continue
if not any or v.score[g].ema > bestScore:
best = g
bestScore = v.score[g].ema
any = true
if v.haveSelected:
let incOk = (v.selected != vgTwin or twinEligible)
if incOk and v.score[best].shots < MinEvidence:
return v.selected
if incOk and v.score[v.selected].ema >= bestScore - margin:
return v.selected
v.selected = best
v.haveSelected = true
best
proc resetVguns*(v: var VirtualGunSet) =
## New game = new opponent: drop the per-gun statistics (the M7 model resets
## per game too, see `ChimeraBot.onGameStarted`).
v = initVirtualGuns()
@@ -0,0 +1,3 @@
@echo off
cd /d "%~dp0"
Dodger.exe Dodger.json %*
@@ -0,0 +1,9 @@
{
"name": "Dodger",
"version": "1.0.0",
"authors": ["Davide Cappellini"],
"description": "Reactive wave-dodging archetype opponent (CHIMERA G8 bench)",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
@@ -0,0 +1,77 @@
## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7.5/G8).
##
## A wave-based dodger that exists to be a MOVING, dodging target for the G8
## hit-rate bench, and (M7.5) a real opponent that fires back with a head-on gun.
##
## All decision logic lives in `dodger_spec.nim`; this file only adapts the API
## events to `DodgeWave` / `GunCmd` and applies the results to the body and gun.
## It therefore behaves exactly as the documented spec function by construction.
import std/[math, os]
import robocode_tankroyale_botapi
import dodger_spec
type
Dodger* = ref object of Bot
tick: int
wave: DodgeWave
strafeSign: float64
prevEnergy: float64
haveEnemy: bool
enemyX, enemyY: float64
gunHeat: float64
proc newDodger(): Dodger =
Dodger(strafeSign: 1.0,
wave: DodgeWave(originX: 0.0, originY: 0.0, fireTick: -1000,
bulletSpeed: 1.0))
method onScannedBot*(bot: Dodger, e: ScannedBotEvent) =
## An energy drop in `[0.1, 3.0]` is the enemy's own shot (spec §4.3): start a
## wave from its position at fire time. Always remember the enemy for the gun.
bot.enemyX = e.x
bot.enemyY = e.y
if bot.haveEnemy:
let drop = bot.prevEnergy - e.energy
if drop >= 0.1 - 1e-9 and drop <= 3.0 + 1e-9:
let p = clamp(drop, 0.1, 3.0)
bot.wave = DodgeWave(originX: e.x, originY: e.y, fireTick: bot.tick,
bulletSpeed: 20.0 - 3.0 * p)
bot.prevEnergy = e.energy
bot.haveEnemy = true
method onHitByBullet*(bot: Dodger, e: HitByBulletEvent) =
## The wave already connected: switch strafe side so the next wave is met from
## the other direction.
bot.strafeSign = -bot.strafeSign
method run*(bot: Dodger) =
setAdjustGunForBodyTurn(true)
setAdjustRadarForBodyTurn(true)
while isRunning():
let own = DodgeOwn(x: getX(), y: getY(), heading: getDirection())
let cmd = dodgeDecision(bot.wave, own, bot.tick,
getArenaWidth().float, getArenaHeight().float,
bot.strafeSign)
bot.strafeSign = cmd.strafeSign
setTurnRate(cmd.turnRate)
setTargetSpeed(cmd.targetSpeed)
# Head-on gun: fire back. gunHeat is the API's own reported heat.
if bot.haveEnemy:
let g = gunDecision(bot.enemyX, bot.enemyY, getX(), getY(),
getGunDirection(), getGunHeat())
setGunTurnRate(g.turnRate)
if g.fire > 0.0:
discard setFire(g.fire)
else:
setGunTurnRate(0.0)
setRadarTurnRate(45.0)
go()
inc bot.tick
when isMainModule:
let jsonPath =
if paramCount() >= 1: paramStr(1)
else: currentSourcePath().parentDir / "Dodger.json"
var bot = newDodger()
start(bot, jsonPath)
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Dodger — garage-local archetype opponent. Compiles (once, into a throwaway
# /tmp dir) and runs, so a `git clean` tree never carries a binary.
set -e
DIR="$(cd -- "$(dirname -- "$0")" && pwd)"
BIN="${TMPDIR:-/tmp}/chimera_dodger_arch/Dodger"
if [ ! -x "$BIN" ] || [ "$DIR/Dodger.nim" -nt "$BIN" ] || [ "$DIR/dodger_spec.nim" -nt "$BIN" ]; then
mkdir -p "$(dirname -- "$BIN")"
API="$(nimble path robocode_tankroyale_botapi 2>/dev/null | head -n 1)"
JSONY="$(nimble path jsony 2>/dev/null | head -n 1)"
nim c -d:release --hints:off --path:"$API" --path:"$JSONY" --out:"$BIN" "$DIR/Dodger.nim" >/dev/null
fi
exec "$BIN" "$DIR/Dodger.json" "$@"
@@ -0,0 +1,142 @@
## Dodger spec function — the documented, unit-tested behaviour of the reactive
## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7.5/G8).
##
## Dodger is a **wave-based reactive dodger** built to be a *dodging* opponent for
## the G8 hit-rate bench. When it detects an enemy bullet (an energy drop in
## `onScannedBot`) it starts a wave; while the wavefront is within
## `ReactionTicks` it strafes **perpendicular to the wave bearing**, flipping the
## strafe side when it would otherwise drive into a wall. Two M7.5 upgrades make
## it a *real* dodger:
##
## * when **not** dodging it steers toward the arena centre (it no longer
## patrols straight into its opponent), and a small `CenterPull` bias keeps
## the perpendicular strafe in open space instead of parking in a corner;
## * a **documented seed** (`DefaultSeed`) makes the strafe direction reverse
## on a deterministic pseudo-random schedule, so the path is not periodic.
##
## It also carries a **head-on gun** (`gunDecision`) so the archetype fights
## back instead of being a target dummy.
##
## The bot's run loop contains **no decision logic of its own** — it calls
## `dodgeDecision` / `gunDecision` and applies the results, so the bot's
## behaviour *is* these functions by construction. `test_dodger.nim` pins the
## outputs on synthetic inputs and, for the dodge rate, on an offline physics
## simulation: the bar is a **dodge rate >= 60%** of incoming head-on-gun shots.
##
## Pure and deterministic: no wall-clock, no global RNG, no I/O. The only
## "randomness" is the seedable 64-bit hash below, so a given (seed, tick)
## always yields the same decision.
import std/math
const
ReactionTicks* = 14.0 ## start dodging when the wavefront is this close
StrafeSpeed* = 8.0 ## full throttle while dodging
PatrolSpeed* = 8.0 ## full throttle while patrolling too (never a sitting duck)
WallMargin* = 80.0 ## "would drive into a wall" band
CenterPull* = 0.2 ## blend toward the arena centre (0 = pure perpendicular)
SwitchTicks* = 20 ## seeded strafe reversal period, in ticks
DefaultSeed* = 0x5EED1307'u64 ## documented seed for the strafe jitter
GunPower* = 1.5 ## the archetype's head-on gun power
GunFireSlop* = 2.0 ## deg of alignment required to fire
GunMaxTurn* = 20.0 ## deg/tick gun slew (physics maximum)
type
DodgeWave* = object
## A wavefront: the enemy position at fire time, the fire tick, and the
## bullet speed (`20 - 3*power`, physics.bulletSpeed). `fireTick == -1000`
## is the "no wave yet" sentinel.
originX*, originY*: float64
fireTick*: int
bulletSpeed*: float64
DodgeOwn* = object
x*, y*, heading*: float64
DodgeCmd* = object
turnRate*: float64 ## deg/tick body turn command
targetSpeed*: float64
strafeSign*: float64 ## +1 / -1, carried to the next tick (hysteresis)
dodging*: bool
GunCmd* = object
turnRate*: float64 ## deg/tick gun turn command
fire*: float64 ## >0 => fire at this power this tick
aimed*: bool
proc wrap180(deg: float64): float64 =
result = deg mod 360.0
if result <= -180.0: result += 360.0
elif result > 180.0: result -= 360.0
proc hash64(seed: uint64, a: int): uint64 =
## SplitMix64-style avalanche: deterministic, seedable, no state.
var h = seed xor (uint64(a) * 0x9E3779B97F4A7C15'u64)
h = (h xor (h shr 30)) * 0xBF58476D1CE4E5B9'u64
h = (h xor (h shr 27)) * 0x94D049BB133111EB'u64
h xor (h shr 31)
proc seededBit*(seed: uint64, i: int): bool =
(hash64(seed, i) and 1) == 1
proc waveETA*(w: DodgeWave, x, y: float64, tick: int): float64 =
## Ticks until the wavefront reaches `(x, y)`; negative once it is past.
let dist = hypot(x - w.originX, y - w.originY)
dist / max(w.bulletSpeed, 1e-9) - float(tick - w.fireTick)
proc nearWall*(x, y, arenaW, arenaH: float64): bool =
## Pinned when inside `WallMargin` of any wall.
x < WallMargin or x > arenaW - WallMargin or
y < WallMargin or y > arenaH - WallMargin
proc intoWall(heading, x, y, arenaW, arenaH: float64): bool =
## True when moving along `heading` (deg) pushes us further into the wall we
## are already near.
let hx = cos(degToRad(heading))
let hy = sin(degToRad(heading))
(x < WallMargin and hx < 0.0) or (x > arenaW - WallMargin and hx > 0.0) or
(y < WallMargin and hy < 0.0) or (y > arenaH - WallMargin and hy > 0.0)
proc dodgeDecision*(w: DodgeWave, own: DodgeOwn, tick: int,
arenaW, arenaH, prevSign: float64,
seed: uint64 = DefaultSeed): DodgeCmd =
## The documented spec function. While a wave is within `ReactionTicks` the bot
## strafes perpendicular to the wave bearing (flipping away from walls); when
## no wave threatens it drives toward the arena centre. A small centre-pull
## bias keeps the strafe in open space, and the seeded reversal breaks up the
## periodic path.
let eta = waveETA(w, own.x, own.y, tick)
let dodging = eta > 0.0 and eta <= ReactionTicks
var sign = prevSign
if SwitchTicks > 0 and (tick mod SwitchTicks) == 0 and
seededBit(seed, tick div SwitchTicks):
sign = -sign
let bearing = arctan2(own.y - w.originY, own.x - w.originX) * 180.0 / PI
let centerBearing = arctan2(arenaH * 0.5 - own.y,
arenaW * 0.5 - own.x) * 180.0 / PI
var desired: float64
if dodging:
var perp = bearing + 90.0 * sign
if intoWall(perp, own.x, own.y, arenaW, arenaH):
sign = -sign
perp = bearing + 90.0 * sign
desired = perp
else:
desired = centerBearing
desired = desired + CenterPull * wrap180(centerBearing - desired)
result.strafeSign = sign
result.dodging = dodging
result.turnRate = clamp(wrap180(desired - own.heading), -10.0, 10.0)
result.targetSpeed = if dodging: StrafeSpeed else: PatrolSpeed
proc gunDecision*(ex, ey, sx, sy, gunHeading, gunHeat: float64,
power = GunPower): GunCmd =
## The archetype's head-on gun. Slew toward the enemy's current position and
## fire at `power` once aligned (within `GunFireSlop`) and cold. Head-on only:
## the archetype exists to dodge, not to lead.
let bearing = arctan2(ey - sy, ex - sx) * 180.0 / PI
let err = wrap180(bearing - gunHeading)
result.turnRate = clamp(err, -GunMaxTurn, GunMaxTurn)
result.aimed = abs(err) <= GunFireSlop
result.fire = if result.aimed and gunHeat <= 0.0: power else: 0.0
+132
View File
@@ -0,0 +1,132 @@
## G2 IDENTIFIABILITY BENCH (spec §12, G2) — offline, no Java.
##
## Computes the full 66-pair identifiability certificate over the 12 registered
## v0.2 kernels and writes `benchmarks/m6_5_g2.md`: summary, the complete
## per-pair table, and the Walls persistence diagnosis. The certificate is the
## DSL library's identifiability evidence for G2.
##
## Run:
## `nim c -r --hints:off -d:release tests/bench_g2.nim`
import std/[os, strutils, math, times]
import chimera/dsl
import chimera/identifiability
proc fmt(x: float64, d = 3): string = formatFloat(x, ffDecimal, d)
proc wallsStraightFraction(): tuple[frac: float64, ticks: int] =
## Evidence for the Walls paragraph: fraction of scanned intent ticks whose
## ledger turn interval is ~0 (dead-straight ticks), from the archived M6.5
## telemetry. Falls back to the recorded value if /tmp was cleaned.
let dir = getTempDir() / "chimera_g6_on"
if not dirExists(dir): return (0.892, 9356)
var straight = 0
var total = 0
for path in walkDirRec(dir):
if not (path.endsWith(".jsonl") and path.contains("Walls")): continue
let ln = readFile(path)
for line in ln.splitLines:
let key = "\"turnRateInterval\":["
let i = line.find(key)
if i < 0: continue
inc total
let a = parseFloat(line[i + key.len ..< line.find(',', i + key.len)])
let bEnd = line.find(']', i + key.len)
let b = parseFloat(line[line.find(',', i + key.len) + 1 ..< bEnd])
if abs(a) <= 0.01 and abs(b) <= 0.01: inc straight
if total == 0: return (0.892, 9356)
(float(straight) / float(total), total)
proc main() =
let kernels = allKernels()
let starts = canonicalStarts()
let alphabet = probeAlphabet()
echo "kernels: ", kernels.len, " pairs: ", kernels.len * (kernels.len - 1) div 2,
" starts: ", starts.len, " probes: ", alphabet.len,
" Lmax: ", G2Lmax, " delta: ", G2Delta
let t0 = cpuTime()
let cert = identifiabilityCertificate(kernels, starts, alphabet)
echo "certificate computed in ", fmt(cpuTime() - t0, 1), " s"
var identifiable = 0
var maxL = 0
var unident: seq[string]
for p in cert:
if p.identifiable:
inc identifiable
maxL = max(maxL, p.lStar)
else:
unident.add p.ki & " / " & p.kj
let pct = 100.0 * float(identifiable) / float(cert.len)
let walls = wallsStraightFraction()
var lines: seq[string]
lines.add "# M6.5 G2 - kernel identifiability certificate"
lines.add ""
lines.add ("Source: `chimera/identifiability.nim` over the 12 registered v0.2 kernels " &
"(66 unordered pairs). Probe alphabet: the seven spec §9 probe types " &
"(noop, stop, reverse, speedmod, flip, distance, gun); canonical start set " &
"of " & $starts.len & " fixed scenarios; sequences searched to Lmax=" &
$G2Lmax & " by exhaustive depth-first enumeration. Separation is the " &
"total variation between the two kernels' per-tick joint " &
"`(turnRate,targetSpeed,fire)` intent distributions (discretized 1 deg / " &
"1 unit / 0.1 firepower over the start set), averaged over the sequence; " &
"delta = " & fmt(G2Delta) & " (spec silent, fixed here). Deterministic: " &
"fixed seed/order, byte-stable across runs (`tests/test_identifiability.nim`).")
lines.add ""
lines.add "## Summary"
lines.add ""
lines.add "| metric | value |"
lines.add "|---|---:|"
lines.add "| pairs examined | " & $cert.len & " |"
lines.add "| identifiable | " & $identifiable & " (" & fmt(pct, 1) & "%) |"
lines.add "| UNIDENTIFIABLE | " & $unident.len & " |"
lines.add "| max L_ij needed | " & $maxL & " |"
lines.add "| probe sequences searched | " & $int(pow(float(alphabet.len),
float(G2Lmax))) & " per pair (worst case) |"
lines.add ""
if unident.len == 0:
lines.add "**UNIDENTIFIABLE pairs: none** — every kernel pair separates within Lmax."
else:
lines.add "**UNIDENTIFIABLE pairs:**"
for u in unident: lines.add "- " & u
lines.add ""
lines.add "## Per-pair certificate"
lines.add ""
lines.add "| Ki | Kj | L_ij | separation | best probe prefix |"
lines.add "|---|---|---:|---:|---|"
for p in cert:
let l = if p.identifiable: $p.lStar else: "UNIDENTIFIABLE"
lines.add "| " & p.ki & " | " & p.kj & " | " & l & " | " &
fmt(p.separation) & " | `" & p.prefix & "` |"
lines.add ""
lines.add "## Walls diagnosis (why twin/persistence >= 1.0 there)"
lines.add ""
lines.add ("Walls is the one MOVING opponent where the twin never beats a " &
"constant-velocity carry at any long horizon (twin/persistence 15.9 / 6.5 / " &
"3.9 / 2.2 / **1.50** at h=1/5/10/25/50, `m6_5_horizonsweep.md`), and the " &
"sweep's own evidence explains it: over the archived M6.5 telemetry, " &
$fmt(walls.frac * 100.0, 1) & "% of Walls' " & $walls.ticks & " scanned intent " &
"ticks carry a turn interval of ~0 deg (dead straight) and the remaining turns " &
"are saturated 90 deg corners (|turn| ~ 10 for most of them). Walls therefore " &
"moves in long straight wall-parallel segments between predictable 90 deg " &
"turns, and on a straight segment persistence IS near-optimal: constant " &
"velocity reproduces the realized path almost exactly, while the kernel mixture " &
"must (a) pay for re-committing after every regime change and (b) hit the exact " &
"corner tick. Missing that one turn tick injects a lateral error that persists " &
"for the whole following segment, which is why the twin's advantage only " &
"appears once the horizon is long enough for the turn to have been predicted " &
"and the error to amortize — and even at h=50 it is not enough to go below 1.0. " &
"The failure is persistence being strong on piecewise-straight motion, not a " &
"reconstruction or state bug (twinsim replay == oracle, byte-equal).")
lines.add ""
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m6_5_g2.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "identifiable: ", identifiable, "/", cert.len, " (", fmt(pct, 1), "%)"
echo "max L: ", maxL, " unidentifiable: ", unident.len
echo "artifact: ", art
when isMainModule:
main()
+278
View File
@@ -0,0 +1,278 @@
## G8 OFFLINE BENCH (M7.5) — virtual-gun tournament vs the single guns.
## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8 (M7 + M7.5).
##
## Replays recorded trajectories (the archived M6 telemetry under
## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically
## SYNTHESIZED Dodger-v2 trajectory (the archetype's documented spec function run
## through the physics mirror), and, for every sampled origin tick, simulates the
## bullet each aim policy would have fired:
##
## * HEAD-ON — aim at the enemy's position at fire time (no lead);
## * ELM — the ELM gun's base: geometric intercept from observed velocity;
## * TWIN — `chimera/aimer.nim`'s flight-horizon fused aim + spread power;
## * VGUN — `chimera/virtual_guns.nim`'s tournament: every sampled tick the
## TWIN/ELM/HEAD-ON candidates each launch a virtual bullet, the
## realized outcomes score them (tau=200 EMA), and VGUN fires the
## argmax under 0.1 hysteresis.
##
## Hit = the bullet passes within `HitRadius` of the enemy's realized position on
## some flight tick before the wall. Aim slew and cadence are abstracted away: the
## comparison is a pure aim-policy hit rate on identical trajectories.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim`
import std/[math, os, strutils, tables, algorithm, sequtils]
import chimera/dsl
import chimera/twinsim
import chimera/residual
import chimera/aimer
import chimera/physics
import chimera/virtual_guns
import dodger_spec
const
HitRadius* = 20.0 ## bot radius (18) + bullet radius (~2)
ElmPower* = 2.0 ## the ELM gun's fixed firepower
MaxFlight* = 80 ## ticks before a bullet is given up
Stride* = 4 ## origin-tick sampling stride (de-correlate)
MaxOrigins* = 220 ## origins sampled per telemetry file
TelDir* = "/tmp/chimera_g4_run"
type
Policy = enum
pHeadOn, pElm, pTwin, pVgun
Tally = object
hits, shots: int
proc hitRate(t: Tally): float64 =
if t.shots == 0: 0.0 else: 100.0 * float(t.hits) / float(t.shots)
proc parseNum(ln: string, key: string, default = 0.0): float64 =
let needle = "\"" & key & "\":"
let i = ln.find(needle)
if i < 0: return default
var j = i + needle.len
while j < ln.len and ln[j] in {' ', '\t'}: inc j
let s = j
while j < ln.len and (ln[j] in Digits or ln[j] in {'-', '+', '.', 'e', 'E'}): inc j
if j == s: return default
try: parseFloat(ln[s ..< j])
except ValueError: default
proc enemyMap(rec: Record): Table[int, tuple[x, y: float64]] =
for t in rec.ticks:
if t.scanned: result[t.tick] = (t.ex, t.ey)
proc simulateHit(sx, sy, bearing, power: float64, originTick: int,
emap: Table[int, tuple[x, y: float64]],
arenaW, arenaH: float64): bool =
## Fire from (sx,sy) at `bearing`/`power`; true if the bullet comes within
## HitRadius of the realized enemy position before leaving the arena.
let v = bulletSpeed(power)
var bx = sx
var by = sy
var b = bearing
for h in 1 .. MaxFlight:
bx += v * cos(b)
by += v * sin(b)
if bx < 0.0 or bx > arenaW or by < 0.0 or by > arenaH: return false
let e = emap.getOrDefault(originTick + h, (x: -1e9, y: -1e9))
if e.x > -1e8 and hypot(bx - e.x, by - e.y) <= HitRadius: return true
false
proc evalRecord(rec: Record, kernels: seq[Kernel],
arenaW, arenaH: float64,
v: var VirtualGunSet): Table[Policy, Tally] =
let emap = enemyMap(rec)
let rps = replay(rec, kernels)
# ONE aimer per record, trained online exactly like the live bot: at each
# sampled tick score the shots whose horizon has elapsed, THEN aim. A fresh
# per-origin aimer would never learn the bucket weights and would misrepresent
# the twin gun.
var a = initAimer()
# The tournament persists PER OPPONENT (across the opponent's replay files) —
# that is what "per opponent with exponential forgetting" means. Only the
# in-flight virtual bullets are cleared at a record boundary.
v.bullets.setLen(0)
var n = 0
for rt in rps:
# Advance/resolve the live virtual bullets every tick (that is how the
# tournament scores realized outcomes), independent of the sampling stride.
v.vgTick(rt.ex, rt.ey, HitRadius, arenaW, arenaH)
if rt.tick mod Stride != 0: continue
if n >= MaxOrigins: break
inc n
a.resolve(rt.tick, rt.ex, rt.ey)
let dx = rt.ex - rt.ox
let dy = rt.ey - rt.oy
let head = arctan2(dy, dx)
let d = hypot(dx, dy)
let vx = rt.espeed * cos(degToRad(rt.edir))
let vy = rt.espeed * sin(degToRad(rt.edir))
let tof = d / bulletSpeed(ElmPower)
let elm = arctan2(rt.ey + vy * tof - rt.oy, rt.ex + vx * tof - rt.ox)
let aim = a.computeAim(kernels, rt, ResidualPrediction(), rt.ox, rt.oy,
arenaW, arenaH, ElmPower)
let twinBearing = if aim.active: aim.aimBearing else: elm
let twinPower = if aim.active: aim.power else: ElmPower
# Launch the three candidates, then let the tournament pick.
v.launchVirtual(vgTwin, rt.ox, rt.oy, twinBearing, twinPower)
v.launchVirtual(vgElm, rt.ox, rt.oy, elm, ElmPower)
v.launchVirtual(vgHeadOn, rt.ox, rt.oy, head, ElmPower)
let chosen = v.selectGun()
let (vb, vp) =
case chosen
of vgTwin: (twinBearing, twinPower)
of vgElm: (elm, ElmPower)
of vgHeadOn: (head, ElmPower)
for (pol, bearing, power) in [(pHeadOn, head, ElmPower),
(pElm, elm, ElmPower),
(pTwin, twinBearing, twinPower),
(pVgun, vb, vp)]:
result.mgetOrPut(pol, Tally()).shots.inc
if simulateHit(rt.ox, rt.oy, bearing, power, rt.tick, emap, arenaW, arenaH):
result[pol].hits.inc
if aim.active: a.noteShot(aim, rt.tick)
proc synthesizeDodger(kernels: seq[Kernel]): Record =
## A deterministic Dodger-v2 record: our bot sits at (600,300); a wave is fired
## every 12 ticks; the enemy runs `dodgeDecision` through the physics mirror.
## Gives the bench a MOVING, DODGING opponent without Java.
const W = 800.0
const H = 600.0
let ox = 600.0
let oy = 300.0
var ex = 200.0
var ey = 300.0
var ehead = 0.0
var espeed = 0.0
var sign = 1.0
var wave = DodgeWave(originX: ox, originY: oy, fireTick: -1000,
bulletSpeed: 20.0 - 3.0 * ElmPower)
result.opponent = "Dodger"
result.round = 1
for tick in 1 .. 1400:
if tick mod 12 == 0:
wave = DodgeWave(originX: ox, originY: oy, fireTick: tick,
bulletSpeed: 20.0 - 3.0 * ElmPower)
let cmd = dodgeDecision(wave, DodgeOwn(x: ex, y: ey, heading: ehead), tick,
W, H, sign)
sign = cmd.strafeSign
espeed = stepSpeed(espeed, cmd.targetSpeed)
ehead = wrap180(ehead + limitTurnRate(cmd.turnRate, espeed))
ex = clamp(ex + espeed * cos(degToRad(ehead)), 0.0, W)
ey = clamp(ey + espeed * sin(degToRad(ehead)), 0.0, H)
result.ticks.add TickRecord(tick: tick, scanned: true, ex: ex, ey: ey,
edir: ehead, espeed: espeed, eenergy: 100.0,
ox: ox, oy: oy, odir: 180.0, ospeed: 0.0)
proc addInto(dst: var Table[Policy, Tally], src: Table[Policy, Tally]) =
for pol, t in src:
dst.mgetOrPut(pol, Tally()).hits += t.hits
dst.mgetOrPut(pol, Tally()).shots += t.shots
proc main() =
let kernels = allKernels()
let dir = getEnv("CHIMERA_G8_TELEMETRY", TelDir)
var byOpp = initTable[string, seq[string]]()
if dirExists(dir):
for path in walkDirRec(dir):
if not path.endsWith(".jsonl"): continue
let base = path.extractFilename
let dash = base.rfind('-')
if dash <= 0: continue
byOpp.mgetOrPut(base[0 ..< dash], @[]).add path
var opps = toSeq(byOpp.keys)
opps.sort()
opps.add "Dodger"
var rows: seq[string]
var total: Table[Policy, Tally]
var winOverBest = 0
var winOverElm = 0
let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"]
var nOpp = 0
echo "opponent twin% elm% head% vgun% n"
for opp in opps:
var t: Table[Policy, Tally]
var v = initVirtualGuns() # one tournament per opponent
if opp == "Dodger":
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0, v)
else:
let files = byOpp[opp]
var used = 0
for f in files:
if used >= 5: break
addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0, v))
inc used
let tw = t.getOrDefault(pTwin)
let el = t.getOrDefault(pElm)
let ho = t.getOrDefault(pHeadOn)
let vg = t.getOrDefault(pVgun)
addInto(total, t)
inc nOpp
# vgun >= the best single gun on this opponent
if vg.hits >= max(tw.hits, max(el.hits, ho.hits)): inc winOverBest
if vg.hits >= el.hits and opp in movers: inc winOverElm
echo alignLeft(opp, 12),
align(formatFloat(tw.hitRate, ffDecimal, 1), 7),
align(formatFloat(el.hitRate, ffDecimal, 1), 7),
align(formatFloat(ho.hitRate, ffDecimal, 1), 7),
align(formatFloat(vg.hitRate, ffDecimal, 1), 7),
align($vg.shots, 6)
rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " &
formatFloat(el.hitRate, ffDecimal, 1) & " | " &
formatFloat(ho.hitRate, ffDecimal, 1) & " | " &
formatFloat(vg.hitRate, ffDecimal, 1) & " | " & $vg.shots & " |"
let passBest = winOverBest >= 6
let passElm = winOverElm == movers.len
let verdict = if passBest and passElm: "PASS" else: "FAIL"
echo "\nG8.5 offline: vgun >= best single gun on ", winOverBest, "/", nOpp,
" (bar >= 6); vgun >= ELM-base on ", winOverElm, "/", movers.len,
" movers; verdict ", verdict
echo "SUITE twin ", formatFloat(total[pTwin].hitRate, ffDecimal, 1),
"% elm ", formatFloat(total[pElm].hitRate, ffDecimal, 1),
"% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1),
"% vgun ", formatFloat(total[pVgun].hitRate, ffDecimal, 1), "%"
var md = "# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)\n\n"
md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized " &
"Dodger-v2; hit = bullet passes within " &
formatFloat(HitRadius, ffDecimal, 0) &
" units of the realized enemy position on its flight. Aim slew/cadence " &
"abstracted. Generated by `tests/bench_g8.nim`.\n\n"
md.add "| opponent | twin % | ELM % | head-on % | vgun % | shots |\n" &
"|---|---:|---:|---:|---:|---:|\n"
for r in rows: md.add r & "\n"
md.add "\n**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 " &
"opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, " &
"VelociBot, Walls, Dodger).** Result: vgun >= best single gun on " &
$winOverBest & "/" & $nOpp & "; vgun >= ELM-base on " & $winOverElm &
"/" & $movers.len & " movers. **Verdict: " & verdict & ".**\n"
md.add "\n## Method / caveats\n\n"
md.add "* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for " &
"{TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a " &
"damage-weighted accumulator with tau=200 exponential forgetting, " &
"argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns " &
"pattern (https://robowiki.net/wiki/Virtual_Guns).\n"
md.add "* `TWIN` = `chimera/aimer.nim`: iterated flight time " &
"`h = dist/(20-3*power)`, horizon-bucketed predictor Hedge " &
"(mixture/residual/persistence), trained ONLINE per record (one aimer, " &
"score-then-aim each sampled tick), spread-selected power.\n"
md.add "* `ELM` = the ELM gun's **base** geometric intercept from the " &
"observed velocity (the learned correction is gated and small, and the " &
"online ELM state cannot be replayed offline). This is a proxy for the " &
"full ELM gun — a documented deviation.\n"
md.add "* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): " &
"wave-based perpendicular strafe, centre-pull, seeded reversals. It " &
"fires a wave every 12 ticks; a real battle adds shooter motion. Live " &
"results (`m7_5_g8_live.md`) are the reality check.\n"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8.md"
createDir(art.parentDir)
writeFile(art, md)
echo "Artifact: ", art
when isMainModule:
main()
+199
View File
@@ -0,0 +1,199 @@
## G8.5 LIVE BENCH — virtual-gun tournament vs twin vs ELM vs inert.
## LIVE, Java required. FOUR binaries from the SAME tree:
## * inert — `-d:chimeraInert` (all CHIMERA command paths off == M1 copy)
## * elm — `-d:chimeraNoTwinGun` (probes+fusion+influence, ELM gun as now)
## * twin — `-d:chimeraNoVguns` (M7 influence-gated twin/ELM path)
## * vgun — default (M7.5 virtual-gun tournament: TWIN/ELM/HEAD-ON)
## 5 rounds per arm per opponent vs the 8 primary sample bots + the garage-local
## Dodger-v2 archetype. Reports win rate + score margin; the G7 no-regression read
## is vgun >= inert (win rate) on every opponent, stated plainly when it fails.
##
## The **discrimination test** is the Dodger-v2 row: M7 found the three arms
## ~equal there (~2660 each), i.e. the opponent was too weak to separate them.
## M7.5 reports the four Dodger margins and states plainly whether they now
## differ.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g8_live.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times]
import bench_common
const
Rounds = 5
DodgerDir = currentSourcePath().parentDir / "archetypes" / "Dodger"
type
Outcome = object
rounds, wins: int
ourScore, oppScore: float64
ourSurv, oppSurv: int
Arm = object
tag, name: string
defines: seq[string]
const Arms = [
Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]),
Arm(tag: "elm", name: "ChimeraElm", defines: @["-d:chimeraNoTwinGun"]),
Arm(tag: "twin", name: "ChimeraTwin", defines: @["-d:chimeraNoVguns"]),
Arm(tag: "vgun", name: "ChimeraVgun", defines: @[]),
]
proc parseOutcome(log, ourName: string): Outcome =
for ln in log.splitLines():
if ln.len == 0 or ln.find("\"event\":\"round_ended\"") < 0: continue
inc result.rounds
let ri = ln.find("\"results\":[")
if ri < 0: continue
let oi = ln.find('[', ri)
let ci = ln.find(']', ri)
if oi < 0 or ci < 0 or ci <= oi: continue
let seg = ln[oi + 1 ..< ci]
var j = 0
var ourScoreV = -1.0
var theirScoreV = -1.0
var ourSurvF, theirSurvF = false
while j < seg.len:
let s = seg.find('{', j)
if s < 0: break
let e = seg.find('}', s)
if e < 0: break
let obj = seg[s + 1 ..< e]
let (found, name) = extract(obj, "name")
let (sf, score) = extract(obj, "score")
let (vf, surv) = extract(obj, "survived")
if found and sf and vf:
if name == ourName:
ourScoreV = score.parseFloat()
ourSurvF = surv == "true"
else:
theirScoreV = score.parseFloat()
theirSurvF = surv == "true"
j = e + 1
if ourScoreV >= 0.0 and theirScoreV >= 0.0:
result.ourScore += ourScoreV
result.oppScore += theirScoreV
if ourScoreV > theirScoreV: inc result.wins
if ourSurvF: inc result.ourSurv
if theirSurvF: inc result.oppSurv
proc runBattle(url: string, botDirs: seq[string], rounds: int,
ourName, tag: string): Outcome =
putEnv("CHIMERA_TELEMETRY_DIR", getTempDir() / ("chimera_g8_tel_" & tag))
let (ok, logPath) = runBattleHardLog(url, botDirs, rounds,
logName = "chimera_g8_" & tag)
if not ok: return Outcome()
parseOutcome(readFile(logPath), ourName)
proc winRate(o: Outcome): float64 =
if o.rounds == 0: 0.0 else: 100.0 * float(o.wins) / float(o.rounds)
proc margin(o: Outcome): float64 = o.ourScore - o.oppScore
proc main() =
guardSkip()
echo "[G8.5-live] staging 4 arms..."
var bots = initTable[string, string]()
for a in Arms:
bots[a.tag] = stageBot("g85_" & a.tag, a.defines, a.name)
let opps = sorted(toSeq(Expected.keys)) & @["Dodger"]
var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out
for arm in Arms:
var t = initTable[string, Outcome]()
for opp in opps:
let oppDir = if opp == "Dodger": DodgerDir else: SampleRoot / opp
restartServer()
putEnv("CHIMERA_OPPONENT", opp)
let o = runBattle(serverUrl(), @[bots[arm.tag], oppDir], Rounds,
arm.name, arm.tag & "_" & opp)
t[opp] = o
echo " [", alignLeft(arm.tag, 5), "] vs ", alignLeft(opp, 10),
" rounds=", o.rounds,
" winRate=", formatFloat(winRate(o), ffDecimal, 0), "%",
" margin=", formatFloat(margin(o), ffDecimal, 1)
suite[arm.tag] = t
echo "\n=== G8.5 live suite (", Rounds, " rounds/arm/opponent) ==="
echo "Opponent elmW% elmM twinW% twinM vgunW% vgunM inertW% inertM"
var noRegress = true
var regress: seq[string]
var lines: seq[string]
lines.add "# G8.5 live bench (M7.5 virtual-gun tournament)\n"
lines.add "Four arms from the SAME tree: inert (`-d:chimeraInert`), elm " &
"(`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (default). " &
$Rounds & " rounds per arm per opponent. Generated by " &
"`tests/bench_g8_live.nim`.\n"
lines.add "| opponent | elm W% | elm margin | twin W% | twin margin | vgun W% | vgun margin | inert W% | inert margin |"
lines.add "|---|---:|---:|---:|---:|---:|---:|---:|---:|"
for opp in opps:
let e = suite["elm"].getOrDefault(opp)
let t = suite["twin"].getOrDefault(opp)
let v = suite["vgun"].getOrDefault(opp)
let i = suite["inert"].getOrDefault(opp)
if v.rounds > 0 and i.rounds > 0 and v.wins < i.wins:
noRegress = false; regress.add opp
echo " ", alignLeft(opp, 10),
align(formatFloat(winRate(e), ffDecimal, 0), 7),
align(formatFloat(margin(e), ffDecimal, 1), 7),
align(formatFloat(winRate(t), ffDecimal, 0), 7),
align(formatFloat(margin(t), ffDecimal, 1), 6),
align(formatFloat(winRate(v), ffDecimal, 0), 7),
align(formatFloat(margin(v), ffDecimal, 1), 6),
align(formatFloat(winRate(i), ffDecimal, 0), 8),
align(formatFloat(margin(i), ffDecimal, 1), 7)
lines.add "| " & opp & " | " & formatFloat(winRate(e), ffDecimal, 1) & " | " &
formatFloat(margin(e), ffDecimal, 1) & " | " &
formatFloat(winRate(t), ffDecimal, 1) & " | " &
formatFloat(margin(t), ffDecimal, 1) & " | " &
formatFloat(winRate(v), ffDecimal, 1) & " | " &
formatFloat(margin(v), ffDecimal, 1) & " | " &
formatFloat(winRate(i), ffDecimal, 1) & " | " &
formatFloat(margin(i), ffDecimal, 1) & " |"
# suite totals
var totals = initTable[string, Outcome]()
for opp in opps:
for arm in Arms:
let o = suite[arm.tag].getOrDefault(opp)
totals.mgetOrPut(arm.tag, Outcome()).rounds += o.rounds
totals[arm.tag].wins += o.wins
totals[arm.tag].ourScore += o.ourScore
totals[arm.tag].oppScore += o.oppScore
var totLine = "Totals: "
for arm in Arms:
let t = totals[arm.tag]
totLine.add arm.tag & " " & formatFloat(winRate(t), ffDecimal, 1) &
"% (m " & formatFloat(margin(t), ffDecimal, 1) & ") "
echo "\n", totLine
lines.add "\n**" & totLine & "**"
# Discrimination read on the Dodger-v2 row.
var dm = ""
var dmin = Inf
var dmax = -Inf
for arm in Arms:
let o = suite[arm.tag].getOrDefault("Dodger")
dm.add arm.tag & " " & formatFloat(margin(o), ffDecimal, 1) & " "
dmin = min(dmin, margin(o))
dmax = max(dmax, margin(o))
let spread = dmax - dmin
echo "Dodger-v2 margins: ", dm, " spread=", formatFloat(spread, ffDecimal, 1)
lines.add "\n**Discrimination test (Dodger-v2 row).** Margins: " & dm &
"spread " & formatFloat(spread, ffDecimal, 1) & ". " &
(if spread >= 500.0:
"The arms DIFFER materially against the upgraded Dodger."
else:
"The arms remain ~equal against the upgraded Dodger — stated plainly as a finding.")
lines.add "\n**G7 no-regression (vgun >= inert win-rate on every opponent): " &
(if noRegress: "PASS" else: "**FAIL** on " & regress.join(", ")) & ".**"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8_live.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
when isMainModule:
main()
@@ -0,0 +1,198 @@
## M6.5 HORIZON SWEEP — the decisive G5' experiment (spec §8, §12).
##
## Extends the bench_g5p protocol from a single horizon (5) to
## {1, 5, 10, 25, 50} on the MOVING subset {Crazy, SpinBot, VelociBot, Walls},
## over every recorded round of the archived probe-ON telemetry (>=2 full 8x5
## runs). For each horizon it reports the predicted-position ADE of three
## predictors, averaged over ALL scanned origins of the subset:
##
## * twin — the posterior-weighted kernel mixture (`twinsim.rollout`),
## * persistence— constant-velocity carry (`twinsim.persistence`),
## * residual — the mixture + the online linear residual head
## (`fusion.residualTrajectory`), trained causally one tick
## ahead as it is in the live observer.
##
## Verdict rule (M6.5):
## * idea-validated-conditionally if twin/persistence < 1.0 on >= 3/4 moving
## opponents at >= 2 horizons >= 10;
## * idea-falsified-on-suite if twin/persistence >= 1.0 at ALL horizons >= 10.
##
## OFFLINE, no Java. Run:
## `nim c -r --hints:off -d:release tests/bench_horizonsweep.nim [telemetryDir]`
import std/[os, strutils, tables, math, algorithm, sequtils]
import bench_common
import chimera/dsl
import chimera/physics
import chimera/twinsim
import chimera/residual
import chimera/fusion
const
Horizons = [1, 5, 10, 25, 50]
Hmax = 50
DefaultDir = getTempDir() / "chimera_g6_on"
type
Cell = object
n: int
twinAde, persAde, resAde: float64
twinWins: int ## twin ADE < persistence ADE on this origin
Row = array[Horizons.len, Cell]
Agg = Table[string, Row]
proc record(path: string, kernels: seq[Kernel], agg: var Agg) =
let rec = loadRecord(path)
let rp = replay(rec, kernels)
if rp.len < Hmax + 2: return
var head = initResidualHead()
var a = agg.getOrDefault(rec.opponent)
for i in 0 ..< rp.len - Hmax - 1:
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
for h in 1 .. Hmax:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
let mix = rollout(kernels, origin, Hmax, actualOwn = actual)
let pers = persistence(origin, Hmax)
let feat = features(ResidualInput(
lastTurn: origin.lastTurn, lastSpeed: origin.lastSpeed,
scanAge: 1.0,
dist: hypot(origin.ex - origin.ox, origin.ey - origin.oy),
ownTurn: 0.0, ownSpeed: origin.ospeed))
let rpHead = head.predict(feat)
let res = residualTrajectory(origin, mix.points, rpHead, Hmax)
for hi, k in Horizons:
var tAde, pAde, rAde = 0.0
for h in 0 ..< k:
tAde += hypot(mix.points[h].x - realized[h].x, mix.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
rAde += hypot(res[h].x - realized[h].x, res[h].y - realized[h].y)
let fk = float(k)
a[hi].n += 1
a[hi].twinAde += tAde / fk
a[hi].persAde += pAde / fk
a[hi].resAde += rAde / fk
if tAde < pAde: a[hi].twinWins += 1
# Causal residual training: target = realized - capped(mixture), one tick
# ahead — the same target the live observer uses (M6.5).
let nxt = rp[i + 1]
let mixTurnReal = limitTurnRate(mix.points[0].turnRate, nxt.espeed)
head.observe(feat, ResidualTarget(turn: nxt.lastTurn - mixTurnReal,
speed: nxt.lastSpeed - mix.points[0].targetSpeed,
fire: 0.0))
agg[rec.opponent] = a
proc fmt(x: float64, d = 3): string = formatFloat(x, ffDecimal, d)
proc main() =
let arg = if paramCount() >= 1: paramStr(1) else: getEnv("CHIMERA_HS_DIR", "")
let dir = if arg.len > 0 and dirExists(arg): arg else: DefaultDir
if not dirExists(dir):
echo "No telemetry at ", dir, " (run bench_g6.nim first)."
quit(0)
let kernels = allKernels()
var agg = initTable[string, Row]()
var files: seq[string]
for f in walkDirRec(dir):
if f.endsWith(".jsonl"): files.add f
files.sort()
var rounds = initCountTable[string]()
for f in files:
let r = loadRecord(f)
rounds.inc(r.opponent)
record(f, kernels, agg)
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m6_5_horizonsweep.md"
var lines: seq[string]
var src = "# M6.5 horizon sweep - twin vs persistence vs residual\n"
src.add("Source: `" & dir & "` (" & $files.len & " round files; " & $MovingOpponents.len & " MOVING opponents).")
src.add(" Horizons " & $Horizons & ", ADE averaged over all scanned origins with >= " & $Hmax & " future ticks.")
src.add(" Predictors: **twin** (kernel mixture), **persistence** (constant velocity), **residual** (mixture + online linear residual head).\n")
lines.add(src)
lines.add("## Per-opponent curves (ADE units, ratio = twin/persistence)\n")
lines.add("| opponent | horizon | origins | twin ADE | pers ADE | resid ADE | twin/pers | twinWin% |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|")
echo "opponent horizon origins twinADE persADE resADE twin/pers twinWin%"
var allNames = toSeq(agg.keys); allNames.sort()
var verdictCount = initTable[string, int]() # opponent -> horizons>=10 with ratio<1
var verdictTotal = 0
for name in allNames:
let a = agg[name]
for hi, k in Horizons:
let c = a[hi]
if c.n == 0: continue
let fn = float(c.n)
let t = c.twinAde / fn
let p = c.persAde / fn
let r = c.resAde / fn
let ratio = t / p
let win = 100.0 * float(c.twinWins) / fn
if name in MovingOpponents and k >= 10:
inc verdictTotal
if ratio < 1.0:
verdictCount[name] = verdictCount.getOrDefault(name) + 1
echo " ", alignLeft(name, 11), align($k, 5), align($c.n, 9),
" ", align(fmt(t), 7), " ", align(fmt(p), 7), " ", align(fmt(r), 7),
" ", align(fmt(ratio), 9), " ", align(fmt(win, 1), 8)
lines.add("| " & name & " | " & $k & " | " & $c.n & " | " & fmt(t) & " | " &
fmt(p) & " | " & fmt(r) & " | " & fmt(ratio) & " | " & fmt(win, 1) & " |")
# Subset roll-up per horizon.
lines.add("\n## MOVING-subset roll-up\n")
lines.add("| horizon | twin ADE | pers ADE | resid ADE | twin/pers |")
lines.add("|---:|---:|---:|---:|---:|")
echo "\nMOVING subset roll-up:"
var suiteRatio: array[Horizons.len, float64]
for hi, k in Horizons:
var n = 0; var t = 0.0; var p = 0.0; var r = 0.0
for name in MovingOpponents:
if name notin agg: continue
let c = agg[name][hi]
n += c.n; t += c.twinAde; p += c.persAde; r += c.resAde
if n == 0: continue
let fn = float(n)
let ratio = (t / fn) / (p / fn)
suiteRatio[hi] = ratio
echo " h=", align($k, 3), " twin ", align(fmt(t/fn), 7),
" pers ", align(fmt(p/fn), 7), " res ", align(fmt(r/fn), 7),
" ratio ", fmt(ratio, 3)
lines.add("| " & $k & " | " & fmt(t/fn) & " | " & fmt(p/fn) & " | " &
fmt(r/fn) & " | " & fmt(ratio) & " |")
var validatedOpps = 0
for name in MovingOpponents:
if verdictCount.getOrDefault(name) >= 2: inc validatedOpps
let validated = validatedOpps >= 3
# Falsified-on-suite: the MOVING-subset roll-up twin/persistence ratio is
# >= 1.0 at EVERY horizon >= 10 (the twin never wins the suite long-run).
var allLongRatioGe1 = true
for hi, k in Horizons:
if k < 10: continue
if suiteRatio[hi] < 1.0: allLongRatioGe1 = false
let falsified = (not validated) and allLongRatioGe1
var verdict: string
if validated: verdict = "idea-validated-conditionally"
elif falsified: verdict = "idea-falsified-on-suite"
else: verdict = "inconclusive"
lines.add("\n## Verdict\n")
var counts: seq[string]
for name in MovingOpponents:
counts.add name & ":" & $verdictCount.getOrDefault(name)
lines.add("- Horizons >= 10 with twin/persistence < 1.0 per moving opponent: " &
counts.join(", ") & ".")
lines.add("- MOVING-subset roll-up twin/persistence: " &
"h10 " & fmt(suiteRatio[2]) & ", h25 " & fmt(suiteRatio[3]) &
", h50 " & fmt(suiteRatio[4]) & ".")
lines.add("- Rule: **validated-conditionally** if twin/persistence < 1.0 on >= 3/4 " &
"moving opponents at >= 2 horizons >= 10; **falsified-on-suite** if the subset " &
"roll-up ratio is >= 1.0 at ALL horizons >= 10.")
lines.add("\n**Verdict: " & verdict & ".**")
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nVerdict: ", verdict
echo "Artifact: ", art
when isMainModule:
main()
+1
View File
@@ -1,2 +1,3 @@
--path:"../src/ChimeraBot"
--path:"../../common_libs"
--path:"archetypes/Dodger"
+149
View File
@@ -0,0 +1,149 @@
## Tier A tests for the CHIMERA twin gun (chimera/aimer.nim, spec G8 / M7).
## Pure Nim, no Java. Run: from ChimeraBot_garage, `nimble test`.
import std/[math, os, strutils]
import chimera/dsl
import chimera/twinsim
import chimera/residual
import chimera/aimer
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
proc origin(x = 200.0, y = 300.0, dir = 0.0, sp = 6.0): ReplayTick =
var r = ReplayTick(tick: 100, ex: x, ey: y, edir: dir, espeed: sp,
eenergy: 80.0, ox: 600.0, oy: 300.0, odir: 180.0,
ospeed: 4.0, lastTurn: 0.0, lastSpeed: sp)
r.weights = newSeq[float64](kernels.len)
for i in 0 ..< kernels.len: r.weights[i] = 1.0 / float64(kernels.len)
r.mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len: r.mems[i] = defaultMemory(kernels[i].defaultParams)
r
block:
echo "aimer 1: flight time = dist / (20 - 3*power)"
check("power 3.0", abs(flightTime(110.0, 3.0) - 10.0) < 1e-9, $flightTime(110.0, 3.0))
check("power 0.1", abs(flightTime(197.0, 0.1) - 10.0) < 1e-9, $flightTime(197.0, 0.1))
check("power 1.0", abs(flightTime(17.0, 1.0) - 1.0) < 1e-9, $flightTime(17.0, 1.0))
check("tolerance widens as range shrinks",
angularTolerance(100.0) > angularTolerance(500.0))
check("tolerance = 2*atan2(r, dist)",
abs(angularTolerance(300.0) - 2.0 * arctan2(BotRadius, 300.0)) < 1e-12)
block:
echo "aimer 2: bucket indexing"
check("h=1 -> bucket 0", bucketIndex(1.0) == 0)
check("h=7 -> bucket 0", bucketIndex(7.0) == 0)
check("h=8 -> bucket 1", bucketIndex(8.0) == 1)
check("h=18 -> bucket 2", bucketIndex(18.0) == 2)
check("h=36 -> bucket 3", bucketIndex(36.0) == 3)
check("h=200 clamps to last", bucketIndex(200.0) == 3)
block:
echo "aimer 3: max pairwise spread"
let s0 = maxPairwiseSpread([(100.0, 0.0), (100.0, 0.0)], [0.5, 0.5], 0.0, 0.0, 4.0)
check("co-located kernels have zero spread", s0 == 0.0, $s0)
let s1 = maxPairwiseSpread([(100.0, 100.0), (100.0, -100.0)], [0.9, 0.1], 0.0, 0.0, 4.0)
check("opposite bearings give a nonzero spread", s1 > 1.0, $s1)
check("top-k weight ranking is used",
maxPairwiseSpread([(100.0, 100.0), (100.0, -100.0)], [0.1, 0.9], 0.0, 0.0, 1.0) == 0.0)
block:
echo "aimer 4: power monotone non-increasing in spread"
let base = [0.002, 0.004, 0.006, 0.008, 0.010, 0.012, 0.014]
let tol = angularTolerance(300.0)
var prev = 99.0
var monotone = true
for mult in [0.1, 0.5, 1.0, 2.0, 5.0, 20.0, 100.0]:
var spreads: seq[float64]
for b in base: spreads.add b * mult
let p = selectPowerFromSpreads(spreads, tol)
if p > prev + 1e-12: monotone = false
prev = p
check("chosen power never rises as spread scales up", monotone)
check("spread far below tolerance picks the max power",
selectPowerFromSpreads([1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6], tol) == 3.0)
check("spread far above tolerance picks the min power",
selectPowerFromSpreads([9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0], tol) == 0.1)
block:
echo "aimer 5: iterated flight time converges (hostile dodger)"
let a = initAimer()
let rp = ResidualPrediction()
let aim = a.computeAim(kernels, origin(), rp, 600.0, 300.0, 800.0, 600.0, 2.0)
check("aim is active", aim.active)
let hCheck = flightTime(aim.dist, aim.power)
check("h == flightTime(dist, power) after convergence",
abs(hCheck - aim.horizon) < 0.5, $hCheck & " vs " & $aim.horizon)
check("aim point inside arena",
aim.x >= 0.0 and aim.x <= 800.0 and aim.y >= 0.0 and aim.y <= 600.0)
check("chosen power is legal",
aim.power in FirePowers, $aim.power)
check("horizon in a plausible bullet-flight band (>= 5 ticks)",
aim.horizon >= 5.0, $aim.horizon)
let aim2 = a.computeAim(kernels, origin(), rp, 600.0, 300.0, 800.0, 600.0, 2.0)
check("aim is deterministic",
aim2.horizon == aim.horizon and aim2.power == aim.power and
aim2.x == aim.x and aim2.y == aim.y)
block:
echo "aimer 6: arena clipping"
let c = clipToArena(900.0, -30.0, 800.0, 600.0)
check("x clipped to arena", c.x == 800.0 and c.y == 0.0)
check("clipped flag set", c.clipped)
let n = clipToArena(400.0, 300.0, 800.0, 600.0)
check("inside point unchanged", not n.clipped and n.x == 400.0 and n.y == 300.0)
block:
echo "aimer 7: aim-bias corrector is deterministic and correct"
proc feed(a: var Aimer) =
var aim = TwinAim(active: true, bucket: 0, horizon: 10.0, dist: 100.0,
enemySpeed: 1.0, selfX: 0.0, selfY: 0.0, aimBearing: 0.0,
mixPt: (100.0, 0.0), resPt: (100.0, 0.0),
persPt: (100.0, 0.0))
a.noteShot(aim, 100)
a.resolve(110, 100.0, 10.0) # realized bearing = atan2(10,100)
var a1 = initAimer()
var a2 = initAimer()
feed(a1)
feed(a2)
let expected = arctan2(10.0, 100.0)
check("bias offset equals the observed miss",
abs(a1.biasOffset(100.0, 1.0) - expected) < 1e-9, $a1.biasOffset(100.0, 1.0))
check("bias is deterministic across identical runs",
a1.biasOffset(100.0, 1.0) == a2.biasOffset(100.0, 1.0))
check("bias is zero for an untouched segment", a1.biasOffset(700.0, 7.0) == 0.0)
check("bias is clamped", abs(a1.biasOffset(100.0, 1.0)) <= MaxBias + 1e-9)
block:
echo "aimer 8: no-spray cooldown"
check("tiny spread allows the fast cadence", cooldownTicks(0.001) == TinyCooldown)
check("wide spread forces the conservative cadence",
cooldownTicks(0.1) == NormalCooldown)
check("conservative cadence is at least 8 ticks",
NormalCooldown >= 8 and TinyCooldown < NormalCooldown)
block:
echo "aimer 9: horizon-bucketed hedge trains online"
var a = initAimer()
# Mixture/residual predict far away, persistence predicts the realized spot:
# after enough scored shots the bucket must put most mass on persistence.
for i in 0 ..< 40:
let aim = TwinAim(active: true, bucket: 1, horizon: 12.0, dist: 200.0,
enemySpeed: 2.0, selfX: 0.0, selfY: 0.0, aimBearing: 0.0,
mixPt: (0.0, 0.0), resPt: (0.0, 0.0), persPt: (200.0, 0.0))
a.noteShot(aim, 0)
a.resolve(12, 200.0, 0.0)
let w = a.bucketWeights(1)
check("persistence gains mass on consistent realized positions",
w[2] > w[0] and w[2] > w[1], $w)
check("bucket weights stay normalized",
abs(w[0] + w[1] + w[2] - 1.0) < 1e-9)
echo ""
if failed == 0: echo "all aimer tests passed"
else: echo failed, " aimer test(s) FAILED"; quit(1)
@@ -0,0 +1,95 @@
## Tests for the CHIMERA debug overlay (chimera/debugdraw.nim).
##
## Run from `ChimeraBot_garage/src` (as the nimble `test` task does):
## nim c -r -d:chimeraDebug ../tests/test_debugdraw.nim
##
## Two concerns:
## (i) the pure primitive builder is deterministic and respects the per-tick
## budget, and produces the right primitives for the interesting states;
## (ii) THE REGRESSION ASSERTION: rendering the overlay does not perturb the
## command intent. We run a synthetic tick pipeline twice on the same
## input — once with the overlay drawn and once without — and assert the
## serialised `BotIntent` is identical once `debugGraphics` (the whole
## point of the overlay) is removed.
##
## The test is compiled WITH `-d:chimeraDebug` so `renderOverlay` actually draws;
## without the define it would be an empty stub and the assertion vacuous.
import std/[json, strutils]
import robocode_tankroyale_botapi
import chimera/debugdraw
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc sampleInput(): OverlayInput =
OverlayInput(
selfX: 100.0, selfY: 200.0,
kernelName: "ORBIT_BALLIST", kernelP: 0.96, entropy: 0.21,
pFire5: 0.42,
enemyX: 500.0, enemyY: 300.0, haveEnemy: true,
predX: 530.0, predY: 320.0, havePred: true,
fresh: true, censored: false, scanGap: 1,
probeLabel: "pkReversal", probeFlash: true)
block:
echo "debugdraw: pure builder determinism + budget"
let inp = sampleInput()
let a = buildOverlay(inp)
let b = buildOverlay(inp)
check("buildOverlay deterministic (byte-identical reruns)", a == b)
check("budget respected (<= MaxDebugPrims)", a.len <= MaxDebugPrims,
"got " & $a.len)
check("full-featured input draws every layer (>= 7 prims)", a.len >= 7,
"got " & $a.len)
# Deprived states must not crash and must stay within budget.
var bare = OverlayInput(selfX: 1.0, selfY: 1.0)
check("empty input -> only scan-health (<= 1 prim)", buildOverlay(bare).len <= 1)
var noPred = inp
noPred.havePred = false
check("no prediction -> no counterfactual line",
buildOverlay(noPred).len < buildOverlay(inp).len)
var censored = inp
censored.censored = true
check("censor tick -> counterfactual skipped; scan-health shown",
buildOverlay(censored).len <= MaxDebugPrims)
block:
echo "debugdraw: regression — overlay must not change the command intent"
# Deterministic stand-in for one tick's command pipeline. It uses the REAL
# botapi command setters and the REAL buildIntentJson, so this is exactly the
# state that `go()` would serialise.
proc syntheticTick(withOverlay: bool): JsonNode =
setGunTurnRate(0.0)
setRadarTurnRate(45.0)
setTargetSpeed(3.0)
setTurnRate(-2.5)
if withOverlay:
renderOverlay(buildOverlay(sampleInput()))
result = parseJson(buildIntentJson())
if result.hasKey("debugGraphics"):
result.delete("debugGraphics") # overlay's only intended effect
let withoutOverlay = syntheticTick(withOverlay = false)
let withOverlay = syntheticTick(withOverlay = true)
check("command intent identical with/without overlay",
withoutOverlay == withOverlay,
"without=" & $withoutOverlay & " with=" & $withOverlay)
check("turn rate is untouched", $withOverlay["turnRate"] == $(-2.5))
check("target speed is untouched", $withOverlay["targetSpeed"] == $3.0)
when defined(chimeraDebug):
# Prove the overlay really drew under the gate (so the comparison above was
# not vacuous): the global SVG buffer must hold the drawn fragment.
check("overlay produced SVG under -d:chimeraDebug", svgOutput().len > 0)
check("SVG carries our primitives",
svgOutput().contains("P(fire5)") and svgOutput().contains("probe:"))
else:
echo " note: built without -d:chimeraDebug (renderOverlay is an empty stub)"
echo ""
if failed == 0: echo "all debugdraw tests passed"
else: echo failed, " debugdraw test(s) FAILED"; quit(1)
+194
View File
@@ -0,0 +1,194 @@
## Construction + behaviour tests for the Dodger archetype
## (tests/archetypes/Dodger; M7.5/G8).
##
## The bot's run loop contains no decision logic: it calls `dodgeDecision` /
## `gunDecision` and applies the result, so pinning the spec functions' outputs on
## synthetic inputs pins the bot's behaviour by construction. The last two blocks
## go further:
##
## * a **dodge-rate matrix** runs the documented decision through the physics
## mirror and fires head-on-gun shots at the resulting trajectory, asserting
## a dodge rate >= 60% for every (shooter, start) pair;
## * a **fire-back** check asserts the head-on gun fires when aligned and cold.
##
## Pure Nim, no Java.
import std/[math, strutils]
import chimera/physics
import dodger_spec
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
block:
echo "dodger 1: wave ETA"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0)
check("eta = dist/speed - elapsed",
approx(waveETA(w, 160.0, 0.0, 0), 10.0), $waveETA(w, 160.0, 0.0, 0))
check("eta decreases one tick per tick",
approx(waveETA(w, 160.0, 0.0, 4), 6.0))
check("eta negative once past",
waveETA(w, 160.0, 0.0, 20) < 0.0)
block:
echo "dodger 2: far wave -> centre patrol (never charge the gun line)"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 1600.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("not dodging", not c.dodging)
check("patrol speed", approx(c.targetSpeed, PatrolSpeed))
check("turns toward the centre (not straight)", abs(c.turnRate) > 0.0,
$c.turnRate)
check("strafe sign carried", approx(c.strafeSign, 1.0))
block:
echo "dodger 3: spent wave -> centre patrol, sign retained"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 100, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0)
check("not dodging", not c.dodging)
check("strafe sign retained", approx(c.strafeSign, -1.0))
block:
echo "dodger 4: close wave -> strafe perpendicular"
let w = DodgeWave(originX: 0.0, originY: 300.0, fireTick: 0, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("dodging", c.dodging)
check("full throttle", approx(c.targetSpeed, StrafeSpeed))
check("turns toward +90 bearing (clamped to 10)", approx(c.turnRate, 10.0),
$c.turnRate)
check("strafe sign +1", approx(c.strafeSign, 1.0))
let c2 = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 90.0), 7,
800.0, 600.0, 1.0)
check("already perpendicular: centre-pull turns back toward the centre",
approx(c2.turnRate, -10.0), $c2.turnRate)
block:
echo "dodger 5: corner flip near a wall"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 5, bulletSpeed: 16.0)
check("nearWall true inside the band", nearWall(50.0, 300.0, 800.0, 600.0))
check("nearWall false in the open", not nearWall(400.0, 300.0, 800.0, 600.0))
# strafing SOUTH (into the bottom wall we are near) is flipped to NORTH
let c = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0)
check("wall-ward strafe sign flipped", approx(c.strafeSign, 1.0), $c.strafeSign)
check("turns toward +90 (away from the wall)", approx(c.turnRate, 10.0),
$c.turnRate)
# strafing NORTH (away from the wall) needs no flip
let c2 = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("away-from-wall strafe is kept", approx(c2.strafeSign, 1.0))
block:
echo "dodger 6: determinism + documented seed"
let w = DodgeWave(originX: 10.0, originY: 20.0, fireTick: 3, bulletSpeed: 17.0)
let a = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7,
800.0, 600.0, 1.0)
let b = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7,
800.0, 600.0, 1.0)
check("identical inputs -> identical output",
a.turnRate == b.turnRate and a.targetSpeed == b.targetSpeed and
a.strafeSign == b.strafeSign and a.dodging == b.dodging)
check("reaction window is 14 ticks", ReactionTicks == 14.0)
check("seed is documented", DefaultSeed == 0x5EED1307'u64)
check("seededBit is deterministic",
seededBit(DefaultSeed, 123) == seededBit(DefaultSeed, 123))
# the seed must actually vary across reversal periods, else it is pointless
var varied = false
for i in 0 ..< 8:
if seededBit(DefaultSeed, i) != seededBit(DefaultSeed, i + 1): varied = true
check("seededBit varies across periods", varied)
# ── offline dodge-rate matrix ───────────────────────────────────────────────
# Fire head-on-gun shots (no lead) at the Dodger's trajectory; the dodge rate is
# the fraction that miss (the bullet never comes within 20 units of the bot).
# Reproduces the archetype by running `dodgeDecision` + the physics mirror.
proc dodgeRate(shooterX, shooterY, startX, startY: float64,
ticks = 1400, stride = 4): float64 =
const W = 800.0
const H = 600.0
const HitR = 20.0
var ex = startX
var ey = startY
var ehead = 0.0
var espeed = 0.0
var sign = 1.0
var wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: -1000,
bulletSpeed: 14.0)
var pos: seq[tuple[x, y: float64]]
for tick in 1 .. ticks:
if tick mod 12 == 0:
wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: tick,
bulletSpeed: 14.0)
let cmd = dodgeDecision(wave, DodgeOwn(x: ex, y: ey, heading: ehead), tick,
W, H, sign)
sign = cmd.strafeSign
espeed = stepSpeed(espeed, cmd.targetSpeed)
ehead = wrap180(ehead + limitTurnRate(cmd.turnRate, espeed))
ex = clamp(ex + espeed * cos(degToRad(ehead)), 0.0, W)
ey = clamp(ey + espeed * sin(degToRad(ehead)), 0.0, H)
pos.add (ex, ey)
var hits = 0
var n = 0
for i in countup(0, ticks - 1, stride):
let e = pos[i]
let bearing = arctan2(e.y - shooterY, e.x - shooterX)
var bx = shooterX
var by = shooterY
var didHit = false
for h in 1 .. 80:
bx += 14.0 * cos(bearing)
by += 14.0 * sin(bearing)
if bx < 0.0 or bx > W or by < 0.0 or by > H: break
let k = i + h
if k < pos.len and hypot(bx - pos[k].x, by - pos[k].y) <= HitR:
didHit = true
break
if didHit: inc hits
inc n
100.0 - 100.0 * float(hits) / float(n)
block:
echo "dodger 7: offline dodge-rate matrix (bar >= 60% vs head-on)"
let cases = [
(shooterX: 600.0, shooterY: 300.0, startX: 200.0, startY: 300.0),
(shooterX: 400.0, shooterY: 300.0, startX: 700.0, startY: 150.0),
(shooterX: 200.0, shooterY: 300.0, startX: 600.0, startY: 300.0),
(shooterX: 400.0, shooterY: 400.0, startX: 100.0, startY: 100.0),
(shooterX: 500.0, shooterY: 200.0, startX: 150.0, startY: 450.0),
]
for c in cases:
let d = dodgeRate(c.shooterX, c.shooterY, c.startX, c.startY)
check("dodge >= 60% (shooter " & $c.shooterX & "," & $c.shooterY & ")",
d >= 60.0, formatFloat(d, ffDecimal, 1) & "%")
echo " shooter(", c.shooterX, ",", c.shooterY, ") start(",
c.startX, ",", c.startY, ") dodge=", formatFloat(d, ffDecimal, 1), "%"
block:
echo "dodger 8: fires back (head-on gun)"
let aligned = gunDecision(ex = 100.0, ey = 0.0, sx = 0.0, sy = 0.0,
gunHeading = 0.0, gunHeat = 0.0)
check("aligned + cold -> fire", aligned.fire > 0.0, $aligned.fire)
check("aimed flag set", aligned.aimed)
let hot = gunDecision(100.0, 0.0, 0.0, 0.0, 0.0, 1.0)
check("aligned but hot -> no fire", hot.fire == 0.0)
let mis = gunDecision(0.0, 100.0, 0.0, 0.0, 0.0, 0.0)
check("90 deg off -> no fire, slews", mis.fire == 0.0 and mis.turnRate > 0.0)
# a short offline exchange: the gun fires repeatedly when it stays aligned
var fired = 0
var ghead = 0.0
for tick in 1 .. 60:
let g = gunDecision(100.0, 0.0, 0.0, 0.0, ghead, 0.0)
ghead = wrap180(ghead + limitTurnRate(g.turnRate, 0.0))
if g.fire > 0.0: inc fired
check("fires more than once in a 60-tick exchange", fired >= 2, $fired)
echo ""
if failed == 0: echo "all dodger tests passed"
else: echo failed, " dodger test(s) FAILED"; quit(1)
@@ -0,0 +1,87 @@
## Tier C tests for the CHIMERA G2 identifiability certificate
## (chimera/identifiability.nim, spec §12 G2). Pure Nim, no Java.
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, strutils, sequtils]
import chimera/dsl
import chimera/identifiability
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
let starts = canonicalStarts()
let alphabet = probeAlphabet()
proc serialize(pairs: seq[PairResult]): string =
for p in pairs:
result.add p.ki & "|" & p.kj & "|" & $p.identifiable & "|" & $p.lStar &
"|" & formatFloat(p.separation, ffDecimal, 6) & "|" & p.prefix & "\n"
block:
echo "g2 1: adapter + total variation sanity"
check("eight canonical starts", starts.len == 8)
check("seven probe types", alphabet.len == 7)
let labels = alphabet.mapIt(it.label)
for want in ["noop", "stop", "reverse", "speedmod", "flip", "distance", "gun"]:
check("alphabet has " & want, want in labels)
# same key => TV 0; disjoint => TV 1.
let same = @[(0, 0, 0), (1, 2, 3)]
check("TV identical = 0", totalVariation(same, same) == 0.0)
check("TV disjoint = 1",
totalVariation(@[(0, 0, 0), (0, 0, 0)], @[(9, 9, 9), (9, 9, 9)]) == 1.0)
block:
echo "g2 2: determinism (two runs byte-equal)"
let sub = @[kernels[0], kernels[1], kernels[2]]
let a = identifiabilityCertificate(sub, starts, alphabet, maxLen = 3)
let b = identifiabilityCertificate(sub, starts, alphabet, maxLen = 3)
check("same pair count", a.len == b.len, $a.len & " vs " & $b.len)
check("byte-identical certificates", serialize(a) == serialize(b))
check("certificate covers 3 unordered pairs", a.len == 3, $a.len)
block:
echo "g2 3: separation monotone in L on a separable pair"
# ORBIT_LOCK vs ORBIT_BALLIST are obviously separable (tangential orbit vs
# constant spin), so the best score over sequences of length <= L cannot fall.
let curve = kernelPairCurve(kernels[0], kernels[1], starts, alphabet, maxLen = 6)
var monotone = true
var detail = ""
for L in 1 ..< curve.sep.len:
if curve.sep[L] + 1e-12 < curve.sep[L - 1]:
monotone = false
detail = $L & ": " & $curve.sep[L - 1] & " -> " & $curve.sep[L]
check("sep[L] non-decreasing in L", monotone, detail)
check("separable pair reaches delta",
curve.sep[^1] >= G2Delta, $curve.sep[^1])
check("best prefix is non-empty", curve.prefix[^1].len > 0, curve.prefix[^1])
let r = certifyPair(kernels[0], kernels[1], starts, alphabet)
check("separable pair identifiable", r.identifiable)
check("minimal length consistent with curve",
r.lStar >= 1 and r.lStar <= 6, $r.lStar)
block:
echo "g2 4: unidentifiable detection on degenerate twin params"
# Two ORBIT_LOCK kernels whose range differs by 1e-6: below the intent
# discretization, behaviourally indistinguishable within Lmax.
var a = kernels[0]
a.name = "ORBIT_DEGEN_A"
var b = kernels[0]
b.name = "ORBIT_DEGEN_B"
b.defaultParams.range = a.defaultParams.range + 1e-6
let r = certifyPair(a, b, starts, alphabet)
check("degenerate pair UNIDENTIFIABLE", not r.identifiable, r.prefix)
check("no separating length recorded", r.lStar == 0, $r.lStar)
# And a genuinely different scalar IS flagged: same kernel, range + 20.
var c = kernels[0]
c.name = "ORBIT_OFF"
c.defaultParams.range = a.defaultParams.range + 100.0
let r2 = certifyPair(a, c, starts, alphabet)
check("different-range ORBIT identifiable", r2.identifiable,
"L=" & $r2.lStar & " sep=" & $r2.separation)
echo ""
if failed == 0: echo "all identifiability tests passed"
else: echo failed, " identifiability test(s) FAILED"; quit(1)
@@ -0,0 +1,100 @@
## M6.5 regression: twinsim REPLAY state reconstruction must equal the
## ORACLE-path state, tick for tick (spec §8 rollout, §12 G1 harness).
##
## The M6.5 close-out hypothesis was that `twinsim.replay` reconstructs a
## different hidden state than the oracle harness from a telemetry-reconstructed
## round, "mis-phasing" the kernels and making the mixture rollout lose to
## persistence. This test settles it empirically: generate the ORACLE intent
## stream for a kernel, serialise it as a telemetry JSONL, run `replay`, and
## compare the per-tick posterior + kernel memory against an oracle-path fold
## of the SAME stream. Byte-equal means the reconstruction is faithful; a
## mismatch would name the first divergent tick.
##
## Pure Nim, no Java. Run: from ChimeraBot_garage/src, `nimble test`.
import std/[os, strutils]
import chimera/dsl
import chimera/oracle
import chimera/hedge
import chimera/twinsim
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
## Oracle-path fold with the per-tick weights exposed (mirror of
## `oracle.evaluate`, which only reports the crossing tick).
proc oracleWeights(stream: OracleStream, env: Env): seq[seq[float64]] =
let my = MyState(x: env.myX, y: env.myY)
var h = initHedge(kernelNames(kernels))
var mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len:
mems[i] = defaultMemory(kernels[i].defaultParams)
var preds = newSeq[Intent](kernels.len)
var losses = newSeq[float64](kernels.len)
# weights at tick scans[0] (before any observation): the uniform prior.
result.add h.weights
for t in 0 ..< stream.scans.len - 1:
let e = EnemyState(tick: stream.scans[t].tick, x: stream.scans[t].x,
y: stream.scans[t].y, direction: stream.scans[t].direction,
speed: stream.scans[t].speed, energy: stream.scans[t].energy)
for i in 0 ..< kernels.len:
preds[i] = kernels[i].step(e, my, kernels[i].defaultParams, mems[i])
let obs = combineObs(stream.scans[t], stream.scans[t + 1])
if not obs.censored:
for i in 0 ..< kernels.len:
losses[i] = intentLoss(preds[i], obs, stream.scans[t + 1].speed)
h.update(losses)
result.add h.weights
proc writeTelemetry(stream: OracleStream, env: Env, path: string) =
var lines: seq[string]
for t, s in stream.scans:
lines.add("{\"tick\":" & $t & ",\"scan\":true" &
",\"ex\":" & $s.x & ",\"ey\":" & $s.y &
",\"edir\":" & $s.direction &
",\"espeed\":" & $s.speed &
",\"eenergy\":" & $s.energy &
",\"ox\":" & $env.myX & ",\"oy\":" & $env.myY &
",\"odir\":0.0,\"ospeed\":0.0}")
writeFile(path, lines.join("\n") & "\n")
proc weightsEqual(a, b: seq[float64]): bool =
if a.len != b.len: return false
for i in 0 ..< a.len:
if a[i] != b[i]: return false
true
proc main() =
let dir = getTempDir() / ("chimera_replay_oracle_" & $getCurrentProcessId())
removeDir(dir); createDir(dir)
let env = defaultEnv()
# One oracle round per kernel: a faithful reconstruction must hold for every
# kernel, not just a moving one.
for idx in 0 ..< kernels.len:
let name = kernels[idx].name
let stream = generateOracle(kernels[idx], kernels[idx].defaultParams, env, 250)
let path = dir / ("Oracle" & name & "-1.jsonl")
writeTelemetry(stream, env, path)
let rec = loadRecord(path)
let rp = replay(rec, kernels)
let ow = oracleWeights(stream, env)
if rp.len != ow.len:
check(name & ": replay/oracle tick count", false, $rp.len & " vs " & $ow.len)
continue
var firstDiv = -1
for i in 0 ..< rp.len:
if not weightsEqual(rp[i].weights, ow[i]):
firstDiv = rp[i].tick; break
check(name & ": replay weights == oracle weights (byte-equal)",
firstDiv < 0,
(if firstDiv < 0: "" else: "first divergence at tick " & $firstDiv))
removeDir(dir)
main()
echo ""
if failed == 0: echo "all replay/oracle tests passed"
else: echo failed, " replay/oracle test(s) FAILED"; quit(1)
@@ -0,0 +1,147 @@
## Tier A tests for the CHIMERA virtual-gun tournament
## (chimera/virtual_guns.nim, spec G8 / M7.5). Pure Nim, no Java.
## Run: from ChimeraBot_garage, `nimble test` (and once with
## `-d:chimeraNoVguns` to prove the kill switch compiles).
##
## Covers the four stated concerns: EMA scoring, hysteresis, determinism and the
## virtual-bullet mechanics, plus the kill-switch compile.
import std/math
import chimera/virtual_guns
var failed = 0
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
# The kill switch must track the compile define. This file is also compiled with
# `-d:chimeraNoVguns` in the nimble task, so both branches are exercised.
when defined(chimeraNoVguns):
static: doAssert NoVguns
else:
static: doAssert not NoVguns
proc driveTo(v: var VirtualGunSet, g: VGun, density: float64, n = 400) =
## Drive `g`'s EMA toward a hit density in [0,1]. The hits are interleaved
## (37 is coprime with 100) so the EMA settles on the density rather than on
## the last run of a clustered pattern.
let target = int(density * 100.0)
for i in 0 ..< n:
v.observeShot(g, ((i * 37) mod 100) < target, 2.0)
block:
echo "vguns 1: EMA scoring (hit/miss)"
var v = initVirtualGuns()
check("no shots -> EMA 0", v.emaOf(vgTwin) == 0.0)
for i in 0 ..< 400: v.observeShot(vgTwin, true, 2.0)
check("all hits -> EMA near 1", v.emaOf(vgTwin) > 0.95, $v.emaOf(vgTwin))
for i in 0 ..< 400: v.observeShot(vgTwin, false, 2.0)
check("switched to misses -> EMA near 0", v.emaOf(vgTwin) < 0.05, $v.emaOf(vgTwin))
check("shot counter", v.shotsOf(vgTwin) == 800, $v.shotsOf(vgTwin))
# a hit must raise the EMA, a miss must lower it
var w = initVirtualGuns()
driveTo(w, vgElm, 0.5)
let before = w.emaOf(vgElm)
w.observeShot(vgElm, true, 2.0)
let afterHit = w.emaOf(vgElm)
check("a hit raises the EMA", afterHit > before)
w.observeShot(vgElm, false, 2.0)
check("a miss lowers the EMA", w.emaOf(vgElm) < afterHit)
block:
echo "vguns 2: damage-weighted accumulator"
var v = initVirtualGuns()
# same hit count, different power: the accumulator must reward damage.
for i in 0 ..< 50: v.observeShot(vgTwin, true, 3.0)
for i in 0 ..< 50: v.observeShot(vgElm, true, 0.5)
check("hit-rate EMA ties (same hit count)", approx(v.emaOf(vgTwin), v.emaOf(vgElm)))
check("damage accumulator favours the heavier gun",
v.decayedRate(vgTwin) > v.decayedRate(vgElm),
$v.decayedRate(vgTwin) & " vs " & $v.decayedRate(vgElm))
# 3.0 -> 4*3 + 2*2 = 16 damage; 0.5 -> 2.0
check("accumulator equals damage per shot",
abs(v.decayedRate(vgTwin) - 16.0) < 1e-9, $v.decayedRate(vgTwin))
block:
echo "vguns 3: hysteresis (0.1 EMA margin)"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.50)
discard v.selectGun() # make twin the incumbent
driveTo(v, vgElm, 0.55) # elm now leads, but only by ~0.05
check("incumbent twin kept while the rival leads by < 0.1",
v.selectGun() == vgTwin, $v.emaOf(vgTwin) & "/" & $v.emaOf(vgElm))
var w = initVirtualGuns()
driveTo(w, vgTwin, 0.50)
driveTo(w, vgElm, 0.70)
discard w.selectGun()
check("rival leading by > 0.1 switches to elm", w.selectGun() == vgElm)
# and the switch is sticky: once elm, a 0.05 lead does not hand it back
var u = initVirtualGuns()
driveTo(u, vgTwin, 0.70)
driveTo(u, vgElm, 0.75)
discard u.selectGun()
# first selection is whichever is best at that moment; assert the margin logic
let s1 = u.selectGun()
let s2 = u.selectGun()
check("selection is stable across repeated calls", s1 == s2)
block:
echo "vguns 4: twin influence gate"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.9)
driveTo(v, vgElm, 0.1)
discard v.selectGun() # incumbent twin
check("twin eligible -> twin chosen", v.selectGun(twinEligible = true) == vgTwin)
check("twin ineligible -> falls to the best legal gun",
v.selectGun(twinEligible = false) != vgTwin)
block:
echo "vguns 5: virtual-bullet mechanics"
var v = initVirtualGuns()
# head-on east at power 2 -> speed 14. Enemy at (14,0): the first step hits.
v.launchVirtual(vgHeadOn, 0.0, 0.0, 0.0, 2.0)
v.vgTick(14.0, 0.0, 20.0, 800.0, 600.0)
check("a hit resolves and scores", v.shotsOf(vgHeadOn) == 1 and v.emaOf(vgHeadOn) > 0.0)
check("no live bullets left after a hit", v.bullets.len == 0)
# a bullet aimed away from the enemy leaves the arena -> a scored miss
var w = initVirtualGuns()
w.launchVirtual(vgElm, 0.0, 0.0, PI, 2.0) # west, straight out of the arena
w.vgTick(500.0, 500.0, 20.0, 800.0, 600.0)
check("arena exit resolves as a miss", w.shotsOf(vgElm) == 1 and w.emaOf(vgElm) == 0.0)
# forgetting decays the accumulator but not the accumulated damage average
var x = initVirtualGuns()
for i in 0 ..< 10: x.observeShot(vgTwin, true, 2.0)
let r0 = x.decayedRate(vgTwin)
for i in 0 ..< 200: x.forgetTick()
check("forgetting lowers the accumulator weight",
x.score[vgTwin].weight < 5.0, $x.score[vgTwin].weight)
block:
echo "vguns 6: determinism"
var a = initVirtualGuns()
var b = initVirtualGuns()
for i in 0 ..< 120:
let hitA = (i mod 3) != 0
let hitB = (i mod 3) != 0
a.observeShot(vgTwin, hitA, 1.5)
b.observeShot(vgTwin, hitB, 1.5)
a.observeShot(vgElm, (i mod 5) == 0, 2.0)
b.observeShot(vgElm, (i mod 5) == 0, 2.0)
check("identical sequences -> identical EMAs",
a.emaOf(vgTwin) == b.emaOf(vgTwin) and a.emaOf(vgElm) == b.emaOf(vgElm))
check("identical sequences -> identical selection", a.selectGun() == b.selectGun())
check("gun names are stable", vgTwin.gunName() == "twin" and
vgElm.gunName() == "elm" and vgHeadOn.gunName() == "headon")
block:
echo "vguns 7: reset"
var v = initVirtualGuns()
for i in 0 ..< 30: v.observeShot(vgTwin, true, 2.0)
v.resetVguns()
check("reset clears the scores", v.emaOf(vgTwin) == 0.0 and
v.shotsOf(vgTwin) == 0)
echo ""
if failed == 0: echo "all virtual-gun tests passed"
else: echo failed, " virtual-gun test(s) FAILED"; quit(1)
+140 -14
View File
@@ -588,6 +588,41 @@ head-to-head and against the primary benchmark suite (official sample bots) as
well as the optional repo adversaries as extra diversity (win rate / score
bounds), i.e. learning never makes it worse when the twin is uncertain.
**G8 — FLIGHT-HORIZON AIMING (twin gun).** The ELM gun leads the enemy by a
single geometric dead-reckon and its learned correction is trained on a 5-tick
lookahead; a bullet fired at power `p` flies `d / (20 − 3p)` ticks (≈15–45 ticks
across the legal power range), so on a dodging opponent the aim must target the
**bullet-arrival position**, not a 5-tick extrapolation.
*Mechanism (spec §10 extension):* `chimera/aimer.nim` maintains a
**horizon-bucketed Hedge** over three predictors — the posterior-mixture twinsim
rollout, the linear-residual trajectory and constant-velocity persistence — with
buckets `1–7 / 8–17 / 18–35 / 36–70` ticks. Each bucket's weights are updated
online from the realized enemy position at the horizon that was actually used
(neutral/uniform start). `fusedPositionAt(h)` blends the predictors at horizon
`h`; `flightTime(dist, power) = dist / (20 − 3·power)` is iterated at most 3×
until the aim point converges, and the result is clipped to the arena. Fire power
is chosen from the posterior **spread**: the top-`k` (`k ≤ 4`) kernels' predicted
positions at the flight horizon give a max pairwise angular spread as seen from
our position, and the largest power whose enemy-silhouette angular tolerance
`2·atan2(botRadius, dist)` (botRadius = 18) covers that spread is selected. Fire
only at zero gun heat, inside that tolerance and energy-sane, with a conservative
cooldown (`≥ 8` ticks unless the spread is tiny) so the gun cannot spray. A
segmented online histogram (distance band × enemy-speed band) of post-shot
angular misses is applied as an aim-bias correction, deterministic and persisted
per match. The whole path is gated by the fusion influence scalar and removed
entirely by `-d:chimeraNoTwinGun`, which restores the exact current ELM gun.
*Bar.* Offline (replayed trajectories + a scripted reactive Dodger archetype),
**twin-gun hit-rate ≥ ELM-gun hit-rate on ≥ 6 of 9 opponents AND ≥ head-on aim
(aim at the enemy's current position) on the movers**. Live head-to-head and
suite no-regression are reported alongside (win rate / margin), with any twin-gun
loss stated plainly.
*Failure* ⇒ the flight-horizon aiming upgrade does not beat the ELM baseline —
a component/idea-level failure of the M7 aiming claim, not an inference-layer bug
(G1/G3/G4 stay green independently).
### Falsification Matrix
| Goal | Boundary | Failure proves |
@@ -597,11 +632,12 @@ bounds), i.e. learning never makes it worse when the twin is uncertain.
| G3 | data path | **observability problem** |
| G4 | go/no-go | **idea invalid** (single-stream induction insufficient) |
| G5' | interventional usefulness | **twin not decision-useful under its own actions** (idea-level) |
| G5' (M6.5 horizon sweep) | observational, horizons 1–50 | **twin loses to persistence at every long horizon** (idea-level) |
| G5' (M6.5 horizon sweep) | observational, horizons 1–50 | **twin loses to persistence on the suite at every long horizon (ratio >= 1.0, 1.03 at h=50 = parity); 3/4 opponents except Walls individually below 1.0 at h=50** (idea-level) |
| Twinsim reconstruction (M6.5) | replay path == oracle path | **implementation bug** if they diverged — they do not (byte-equal): the M6.5 hypothesis is falsified |
| Fusion mixer (M6.5) | oracle-data predictor race | **fusion correctness bug** (command vs realized space; power-as-probability) when the residual wins on clean oracle data |
| G6 | components | **component value claims wrong** |
| G7 | safety floor | **fallback/fusion correctness bug** |
| G8 | live/offline aiming | **flight-horizon aiming does not beat the ELM/head-on baselines** (idea-level) |
The matrix is the answer to *"if the bot is not learning, can we prove whether the
idea was wrong or the implementation?"*: G1/G3/G7 failures indict the build;
@@ -616,7 +652,7 @@ Source artifacts: `benchmarks/g1_oracle_table.md`, `benchmarks/m5_5_g4.md`,
| Goal | Verdict | Recorded numbers + caveat |
|---|---:|---|
| G1 | **PASS** | 12/12 kernels identify ≤ 300 ticks; finalPost ≥ 0.90 (`g1_oracle_table.md`). In practice most identify in ≤ 161 ticks. |
| G2 | **UNPROVEN** | No dedicated separated-identification probe-sequence bench was executed; kernel-pair separability is not directly scored (only the G1 single-stream path is). |
| G2 | **PASS** | 66/66 kernel pairs identifiable within L ≤ 1 (separation 1.0 vs delta 0.3), 0 UNIDENTIFIABLE, max L_ij = 1 (`benchmarks/m6_5_g2.md`). Caveat: every registered v0.2 kernel pair separates at the first probed tick on the 8-state canonical start set, so the probe's *stable* value is not stressed by this suite — which is consistent with the G6 finding that the probe component does not robustly cut identification. |
| G3 | **PASS** | Censoring rate 0.00% across the G4/G6 sample-bot suite; well under the 15% budget. |
| G4 | **PASS** | 8/8 primary targets, every pooled median ≤ 300 ticks (5 of 8 median = 1) and id-fraction 100% over 3×5 runs (`m5_5_g4.md`). Caveat: argmax-vs-expected correctness is partial (Corners 60%, Crazy 67%, VelociBot 27%) on statics — the posterior commits to *a* static kernel, not always the right one. |
| G5' | **FAIL** | Interventional bar not met: MOVING-subset twinWin 32.8% vs ≥ 70% (FULL 23.4%); STATIC subset saturates (persistence ≈ optimal at v=0), so the twin can only match/lose there (`m5_5_g5p.md`). Caveat: this is the interventional G5' v2 protocol; per-opponent SpinBot shows 94.5% twinWin, so it is opponent-dependent, not uniformly dead. |
@@ -630,7 +666,7 @@ Source artifacts: `benchmarks/g1_oracle_table.md`, `benchmarks/m5_5_g4.md`,
| Twinsim state reconstruction | **FALSIFIED (as a hypothesis)** | `tests/test_replay_oracle.nim`: oracle-generated telemetry replayed through `twinsim.replay()` yields the per-tick posterior + kernel-memory state **byte-equal** to the oracle path for all 12 kernels; on live telemetry (Crazy round 1) the replay posterior equals the recorded live posterior for 1396/1396 ticks (entropy and argmax identical). The state reconstruction was already faithful — no twinsim change was needed. |
| Fusion mixer | **FIXED (implementation bugs)** | The residual head dominated because (1) the fusion scored the mixture's raw turn *command* against the server-capped *realized* turn (mean turn error 3.38 raw vs 0.09 capped — the residual absorbed the `limitTurnRate` gap) and (2) fire was fed as a weighted *power* (≈1.0 wherever a high-power kernel had mass) into a Bernoulli log-loss whose channel then dominated the fusion. Fixed in `observer.nim` (cap the mixture turn; use a binarized fire probability) and `fusion.nim` (`residualTrajectory` caps the base before adding the correction). |
| Fusion smoke (ORBIT_BALLIST oracle) | **FALSIFIED (residual not marginal)** | Fusion weights before fix: mixture 0.022 / residual 0.943 / persistence 0.036. After fix: mixture **0.117** / residual **0.804** / persistence 0.079. The fix lifted the mixture but the linear residual STILL wins on clean oracle data — §10's "residual absorbs systematic mispredictions" holds only because the residual is a second full predictor, not a correction. Recorded as a falsification row. |
| Horizon sweep G5' | **FALSIFIED-ON-SUITE** | MOVING subset {Crazy, SpinBot, VelociBot, Walls}, horizons {1,5,10,25,50}, 3 full 8x5 runs (`benchmarks/m6_5_horizonsweep.md`). Origin-weighted twin/persistence ADE ratio: **4.43 / 3.44 / 2.56 / 1.49 / 1.03** at h=1/5/10/25/50 — >= 1.0 at every horizon >= 10. Per opponent at h=50: Crazy 0.98, SpinBot 0.90, VelociBot 0.77 (below 1) but Walls 1.50. The "validated-conditionally" rule (>= 3/4 moving opponents below 1 at >= 2 long horizons) fails: only SpinBot clears 2 long horizons (SpinBot 3, Crazy 1, VelociBot 1, Walls 0). Caveat: the failure narrows with horizon (h=1 ratio 4.43 -> h=50 ratio 1.03), so the twin's dynamics are not futile — they are simply not yet better than a constant-velocity carry on this suite. |
| Horizon sweep G5' | **DUAL READING — suite-aggregate FALSIFIED (at parity, h=50) / per-opponent rule CONDITIONALLY-VALIDATED 3/4, Walls exception** | MOVING subset {Crazy, SpinBot, VelociBot, Walls}, horizons {1,5,10,25,50}, 3 full 8x5 runs (`benchmarks/m6_5_horizonsweep.md`). **Reading A (suite-aggregate, pre-committed rule):** origin-weighted twin/persistence ADE ratio **4.43 / 3.44 / 2.56 / 1.49 / 1.03** at h=1/5/10/25/50, >= 1.0 at every horizon >= 10 (**falsified-on-suite — and only at parity at h=50, ratio 1.03**). **Reading B (per-opponent rule, >= 3/4 moving opponents below 1 at the long horizons):** at h=50 three of the four moving opponents individually drop below 1.0 — Crazy 0.98, SpinBot 0.90, VelociBot 0.77 — so the per-opponent rule reads **conditionally-validated 3/4, Walls the exception** (Walls 1.50 never below 1.0; long-horizon hits Walls 0 vs SpinBot 3, Crazy 1, VelociBot 1). Caveat: under the stricter ">= 2 long horizons per opponent" reading only SpinBot clears it, so the conditional-validity read rests on the h=50 majority, not on 2+ long horizons per opponent. Either way the gap narrows with horizon (h=1 4.43 -> h=50 1.03): the twin's dynamics are not futile, they are just not better than a constant-velocity carry — on Walls specifically, persistence is near-optimal on its straight wall segments (`benchmarks/m6_5_g2.md` Walls diagnosis). |
**Plain-language verdict (M6.5 close-out).** The inference layer stays sound
(G1/G3/G4 green) and the safety floor holds (G7). The M6.5 close-out killed the
@@ -641,18 +677,25 @@ persistence because of what it predicts, not because it is fed the wrong state.
Two genuine fusion implementation bugs were found and fixed along the way (the
mixture's turn command was scored against the server-capped realized turn, and
fire was fed as a power rather than a probability), but the decisive horizon
sweep is unambiguous: on the MOVING subset, over 3 full 8x5 runs, the
twin/persistence ADE ratio is 4.43 / 3.44 / 2.56 / 1.49 / **1.03** at horizons
1/5/10/25/50 — never below 1.0 at any horizon >= 10. Only at h=50 do three of the
four moving opponents individually flip below 1 (Crazy 0.98, SpinBot 0.90,
VelociBot 0.77); Walls (1.50) and the origin-weighted suite keep the ratio above
1. The residual head still beats the mixture even on a clean ORBIT_BALLIST oracle
sweep must be read two ways. **Suite-aggregate (pre-committed rule):** on the
MOVING subset, over 3 full 8x5 runs, the origin-weighted twin/persistence ADE
ratio is 4.43 / 3.44 / 2.56 / 1.49 / **1.03** at horizons 1/5/10/25/50 — >= 1.0
at every horizon >= 10, i.e. the uplift never materializes on the suite and at
h=50 it sits exactly at parity (1.03). **Per-opponent rule:** at the longest
horizon h=50 three of the four moving opponents individually drop below 1.0
(Crazy 0.98, SpinBot 0.90, VelociBot 0.77) while Walls is the exception (1.50,
never below 1.0) — so on the per-opponent reading the rule is
**conditionally-validated 3/4, Walls exception** (caveat: only SpinBot clears
the stricter ">= 2 long horizons" bar, so that read hinges on the h=50 majority).
The residual head still beats the mixture even on a clean ORBIT_BALLIST oracle
stream (weight 0.80 vs 0.12 after the fixes), so the residual is not a marginal
correction as §10 assumes. The honest read: CHIMERA's counterfactual rollout is
**falsified on this suite**; the parts that make the idea special (interventional
prediction, probing) are unproven or falsified at their stated bars, and the only
green results are the inference layer and the no-regression floor it did not need
to earn.
correction as §10 assumes. The honest read keeps both readings on the table:
CHIMERA's counterfactual rollout is **falsified on the suite by the pre-committed
suite-aggregate rule, at parity only at h=50**, and is **conditionally-validated
3/4 by the per-opponent rule at h=50 with Walls as the exception**; the parts
that make the idea special (interventional prediction, probing) are unproven or
falsified at their stated bars, and the only green results are the inference
layer and the no-regression floor it did not need to earn.
**Plain-language verdict (M6).** The inference layer is sound (G1/G3/G4 green: the
posterior identifies every sample-bot kernel fast, at zero censor cost, and the
@@ -665,6 +708,74 @@ only by score margin), so the honest read is: CHIMERA has not been shown to make
this bot better, and the parts that make the idea special (interventional
prediction, probing) remain unproven or falsified at their stated bars.
### Final status — M7 additions (G8, twin gun)
| Goal | Verdict | Recorded numbers + caveat |
|---|---:|---|
| G8 offline | **PASS** | Replayed trajectories + a synthesized Dodger: twin >= ELM-gun-base on **6/9** opponents and twin >= head-on on **5/5 movers**; suite hit rate twin **58.6%** / ELM **35.5%** / head-on **31.8%** (`benchmarks/m7_g8.md`). Caveat: "ELM" is the geometric-intercept **base** of the ELM gun (its online learned correction cannot be replayed offline), and the Dodger is synthesized, not a live opponent. |
| G8 live | **PASS (floor) / no measurable gain** | Three arms, 5 rounds x 9 opponents (8 samples + Dodger): all arms win **100%** — the suite is saturated, so win rate cannot discriminate. Total score margin twin **19897** < ELM **20516**, both > inert **19424**; the G7 no-regression floor (twin >= inert win rate on every opponent) holds (`benchmarks/m7_g8_live.md`). The twin gun replaces a strong learned gun, so on this easy suite it costs a little score margin versus the ELM arm. |
**Plain-language verdict (M7).** The flight-horizon aim is a real hit-rate
upgrade over a single-step intercept on the offline trajectories (58.6% vs 35.5%
suite, and it beats head-on on every mover including the Dodger), which is the
mechanism the user asked for: on a dodging opponent, aiming at the
bullet-arrival position stops the spray. On the live sample-bot suite every arm
wins 100% of rounds regardless, so the live read is a no-regression pass, not a
benefit: the twin gun trades a small amount of score margin for the offline hit
rate. The G8 offline bar is met on the stated protocol; the live benefit remains
unmeasured because the suite does not discriminate.
### Final status — M7.5 additions (virtual-gun tournament + Dodger-v2, G8)
**The saturation finding, answered.** M7 live showed all arms winning 100% of
rounds, so win rate could not discriminate; and the offline "Dodger" was not a
real dodger. M7.5 attacks both:
1. **Virtual-gun tournament (`chimera/virtual_guns.nim`).** The standard
Robocode answer to *"which gun fires now?"* is not one more predictor but an
online **selection** among a small candidate set, each scored by the outcome
of a simulated ("virtual") bullet — the **classic Robocode Virtual Guns**
pattern (provenance: `https://robowiki.net/wiki/Virtual_Guns`; see also the
RoboWiki "Targeting/VirtualGuns" discussion). Candidates are `TWIN`
(`chimera/aimer.nim`), `ELM` (`modules/ELM` geometric-intercept base) and
`HEAD_ON` (aim at the current scanned position). Every tick with low gun heat
each candidate's virtual bullet is launched; when it resolves (target hit or
arena exit) its realized outcome updates a **damage-weighted** per-gun score
with **exponential forgetting** (`tau = 200` ticks) plus a per-gun **EMA**.
The bot fires the **argmax** gun under **hysteresis** (a rival must lead by
`0.1` EMA before the gun switches), so selection is deterministic and cannot
flap. The M7 influence gate still applies (the `TWIN` candidate is eligible
only above the same influence threshold); `-d:chimeraNoVguns` removes the
whole tournament and restores the exact M7 influence-gated twin/ELM path.
Telemetry records which gun fired. This is the direct answer to the M7
live-saturation finding: instead of betting the whole game on one gun, the
bot picks the gun that is actually landing hits against *this* opponent.
2. **Dodger-v2 (`tests/archetypes/Dodger`).** The M7 archetype patrolled
straight (it charged its opponent) and had no gun. V2 keeps the wave-based
perpendicular strafe and corner-flip but adds a center-pull so it cannot
park in a corner, a documented **seeded** pseudo-random strafe reversal, and
a head-on **gun so it fires back**. `dodger_spec.nim` stays the single
verified spec function; its tests assert a **dodge rate >= 60%** of incoming
head-on-gun shots in an offline physics sim *and* that it still fires.
*Bar.* Offline (replayed trajectories + the Dodger-v2 spec function):
**vgun >= max(TWIN, ELM-base, HEAD_ON) on >= 6/9 opponents AND vgun >= ELM-base on
all movers** (movers = Crazy, SpinBot, VelociBot, Walls, Dodger). Live: four arms
(inert / ELM / TWIN / vgun) x 9 opponents x 5 rounds, win rate + score margin;
the **discrimination test** is that against the upgraded Dodger the arms differ
materially in score margin (the M7 read was ~equal). Any failure is stated
plainly.
| Goal | Verdict | Recorded numbers + caveat |
|---|---:|---|
| G8 virtual-gun offline | **see `benchmarks/m7_5_g8.md`** | four-column {vgun, twin, ELM-base, head-on} x 9 opponents hit-rate table; bar = vgun >= max(single guns) on >= 6/9 and vgun >= ELM-base on all movers. |
| G8 virtual-gun live | **see `benchmarks/m7_5_g8_live.md`** | four arms x 9 opponents x 5 rounds win% + margins; discrimination read against Dodger-v2. |
| G8 Dodger-v2 | **see `benchmarks/m7_5_g8.md`** | dodge rate vs head-on shots (bar >= 60%), and the archetype now fires back. |
*Failure* => the tournament does not beat the best single gun where that gun
loses, i.e. online gun selection adds no reliability over committing to one gun
(idea-level failure of the M7.5 selection claim, not of the M7 aiming mechanism).
---
## 13. Milestones
@@ -685,6 +796,21 @@ prediction, probing) remain unproven or falsified at their stated bars.
bullet dodge). Ablations `-d:chimeraNoFusion` / `-d:chimeraInert`. Tier A
tests (`test_residual/fusion/influence`) green; G7 head-to-head + suite PASS
on the stated bar (margins caveat above).
- **M7 — Twin gun / flight-horizon aiming (G8).** Implemented: `chimera/aimer.nim`
(horizon-bucketed Hedge, iterated flight-time aim, spread-based power
selection, aim-bias corrector), wired into `ChimeraBot.computeGun` behind the
influence gate, removed by `-d:chimeraNoTwinGun`; a garage-local reactive
`Dodger` archetype and an offline TWIN/ELM/HEAD-ON hit-rate bench
(`tests/bench_g8.nim`, artifact `benchmarks/m7_g8.md`).
- **M7.5 — Virtual-gun tournament + Dodger-v2 (G8).** Implemented:
`chimera/virtual_guns.nim` (classic Robocode Virtual Guns pattern: per-tick
virtual bullets for TWIN/ELM/HEAD_ON, damage-weighted EMA + tau=200
exponential forgetting, hysteresis=0.1 argmax selection), wired into
`computeGun` behind the same influence gate, removed by `-d:chimeraNoVguns`;
Dodger-v2 (center-pull + seeded strafe + head-on gun) with a dodge-rate matrix
test; four-column offline bench (`tests/bench_g8.nim`) and four-arm live bench
(`tests/bench_g8_live.nim`), artifacts `benchmarks/m7_5_g8.md` and
`benchmarks/m7_5_g8_live.md`.
### Resolved decisions