From bc67405a4d783905ef40cae7dab53aacd68cbaa0 Mon Sep 17 00:00:00 2001 From: "openbotgit[bot]" <335604065+openbotgit[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:04:22 +0100 Subject: [PATCH 01/11] =?UTF-8?q?RL=203=20:=20budget=20d=C3=A9clar=C3=A9?= =?UTF-8?q?=20et=20banc=20de=20g=C3=A9n=C3=A9ralisation=20(avant=20tout=20?= =?UTF-8?q?entra=C3=AEnement)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit experiment.json fige le budget (100 000 pas par graine), le réseau DQN [64, 64], les hyperparamètres et les graines 11, 29, 47 avant toute exécution. Le protocole circuit-evaluation-v1 est utilisé sans changement. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- packages/demo-car-circuit/package.json | 8 +- .../rl3-generalisation-experiment.json | 62 ++++ .../demo-car-circuit/scripts/rl3-bench.mts | 286 ++++++++++++++++++ .../src/generalisation/results.ts | 209 +++++++++++++ .../src/generalisation/training.ts | 195 ++++++++++++ pnpm-lock.yaml | 3 + 6 files changed, 761 insertions(+), 2 deletions(-) create mode 100644 packages/demo-car-circuit/rl3-generalisation-experiment.json create mode 100644 packages/demo-car-circuit/scripts/rl3-bench.mts create mode 100644 packages/demo-car-circuit/src/generalisation/results.ts create mode 100644 packages/demo-car-circuit/src/generalisation/training.ts diff --git a/packages/demo-car-circuit/package.json b/packages/demo-car-circuit/package.json index 0185ce4..ed78da4 100644 --- a/packages/demo-car-circuit/package.json +++ b/packages/demo-car-circuit/package.json @@ -7,7 +7,10 @@ "dev": "vite", "build": "vite build", "test": "vitest run", - "e2e:human-race": "node e2e/human-race.mjs" + "e2e:human-race": "node e2e/human-race.mjs", + "rl3:train": "tsx --tsconfig ../../scripts/tsconfig.racing.json scripts/rl3-bench.mts train", + "rl3:eval": "tsx --tsconfig ../../scripts/tsconfig.racing.json scripts/rl3-bench.mts eval", + "rl3:manifest": "tsx --tsconfig ../../scripts/tsconfig.racing.json scripts/rl3-bench.mts manifest" }, "dependencies": { "@ignitionai/backend-tfjs": "workspace:*", @@ -29,6 +32,7 @@ "typescript": "~5.7.2", "vite": "^6.3.1", "playwright": "^1.56.1", - "vitest": "^3.1.1" + "vitest": "^3.1.1", + "tsx": "^4.19.3" } } diff --git a/packages/demo-car-circuit/rl3-generalisation-experiment.json b/packages/demo-car-circuit/rl3-generalisation-experiment.json new file mode 100644 index 0000000..4288c88 --- /dev/null +++ b/packages/demo-car-circuit/rl3-generalisation-experiment.json @@ -0,0 +1,62 @@ +{ + "experiment": "rl3-generalisation", + "declaredBeforeExecution": true, + "declaredAt": "2026-11-30T09:04:15Z", + "note": "Budget, network, hyperparameters and seeds are frozen before the training command that produces src/public/rl3-generalisation/. All three seeds use exactly the same values; only the seed changes. Results must come from the raw JSONL logs; numbers are not edited after the run.", + "gitBase": "cb9e04c", + "protocolId": "circuit-evaluation-v1", + "protocolRule": "circuit-evaluation-v1 (src/evaluation.ts) is used unchanged: training circuit 10/4/2, test circuit 6/6/2, starts 0/16/32, 1500 steps, 3 laps, greedy actions only. The test circuit is never built during training.", + "seeds": [ + 11, + 29, + 47 + ], + "algorithm": "dqn", + "algorithmChoice": "DQN (DQNAgent, doubleQ false), the baseline of RL 2: seeded weights, seeded exploration and replay sampling, discrete actions (CircuitEnv has 3), and the frozen-weights checks of RL 2 (save, reload in a new process, compare). The RL 1 PPO set-up was written for the 1-D task and has no per-seed replay determinism check in this package.", + "training": { + "circuit": "training", + "startWaypoints": "uniform", + "startSeedRule": "new start waypoint at every training episode, uniform over 0..63, drawn from mulberry32(seed * 7919 + 13)", + "maxStepsPerEpisode": 1500, + "targetLaps": 3 + }, + "budget": { + "envStepsPerRun": 100000, + "unit": "environment steps through IgnitionEnv.step() (one train() call per step once the replay holds a batch). An episode still running when the budget ends is not logged as an episode; its length is in run.json partialEpisodeAtBudget.", + "choice": "Measured before declaring, on scratch seeds outside the declared ones (seed 1 and seed 2, outputs discarded): about 6 ms per env step on this machine (tfjs cpu backend, node v22). A 60000-step probe on seed 1 completed its first 3-lap training episode near step 16700 and 59 of its last 100 training episodes; only training-circuit episodes were looked at, the probe was never evaluated on the test circuit. 100000 steps is about 10 minutes per seed, 3 seeds run in parallel.", + "checkpointSelection": "none: the evaluated policy is the network after exactly envStepsPerRun steps" + }, + "agent": { + "class": "DQNAgent (packages/backend-tfjs/src/agents/dqn.ts)", + "inputSize": 5, + "actionSize": 3, + "hiddenLayers": [ + 64, + 64 + ], + "lr": 0.0005, + "gamma": 0.99, + "epsilon": 1.0, + "epsilonDecay": 0.99992, + "minEpsilon": 0.05, + "batchSize": 32, + "memorySize": 50000, + "targetUpdateFrequency": 1000, + "backend": "cpu", + "doubleQ": false + }, + "agentNotes": { + "epsilonSchedule": "epsilon multiplied by epsilonDecay after each train() call: 0.05 is reached after about 37400 train calls (37 % of the budget)", + "targetUpdateUnit": "train() calls (hard copy of the online weights)", + "optimizer": "adam, mean squared error, 1 epoch per train() call, shuffle off (seeded)" + }, + "evaluation": { + "policies": [ + "trained", + "untrained" + ], + "untrainedReference": "the same seeded network before any training step, evaluated with the same protocol, as a reference only", + "process": "new process: weights reloaded from trained/ and untrained/, sha256 of the weights compared before and after evaluation and with the training process", + "trajectories": "x, y of the car at every step, recorded by a second deterministic drive of the same frozen policy and checked against the protocol episode (endReason, transitions, laps)" + } +} diff --git a/packages/demo-car-circuit/scripts/rl3-bench.mts b/packages/demo-car-circuit/scripts/rl3-bench.mts new file mode 100644 index 0000000..9c0b7ee --- /dev/null +++ b/packages/demo-car-circuit/scripts/rl3-bench.mts @@ -0,0 +1,286 @@ +/** + * RL 3 — generalisation bench: same frozen policy, training circuit vs unseen circuit. + * + * Reads the declared budget in packages/demo-car-circuit/rl3-generalisation-experiment.json + * (committed before any training run) and writes everything under + * packages/demo-car-circuit/src/public/rl3-generalisation/ (served by the page). + * + * pnpm --filter demo-car-circuit rl3:train [--seed 11] # DQN on the training circuit only + * pnpm --filter demo-car-circuit rl3:eval [--seed 11] # new process: frozen weights, circuit-evaluation-v1 + * pnpm --filter demo-car-circuit rl3:manifest # summary.json, experiment.json, manifest.json (sha256) + * + * Probe (not an artifact): rl3:train --seed 1 --steps 5000 --out /tmp/rl3-probe + * + * gitSha is `git rev-parse HEAD` at train time (same rule as RL 1 and RL 2). + */ +import { createHash } from 'node:crypto'; +import { execSync } from 'node:child_process'; +import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; +import * as tf from '@tensorflow/tfjs'; +import { DQNAgent } from '@ignitionai/backend-tfjs'; +import { fileSystemModelProvider } from '../../backend-tfjs/scripts/fs-provider.mjs'; +import { CircuitEnv } from '../src/circuit-env'; +import { CIRCUIT_PROTOCOL, evaluateCircuit, type CircuitEvaluationReport } from '../src/evaluation'; +import { buildAgentConfig, runTraining, type Rl3Experiment } from '../src/generalisation/training'; +import { + parseEvalLog, RL3_CIRCUITS, RL3_POLICIES, summarizePolicy, summaryFile, + type EvalEpisodeRow, type Rl3Circuit, type Rl3Policy, +} from '../src/generalisation/results'; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgRoot = join(here, '..'); +const repoRoot = join(pkgRoot, '../..'); +const DECLARED = 'packages/demo-car-circuit/rl3-generalisation-experiment.json'; +const OUT_DIR = 'packages/demo-car-circuit/src/public/rl3-generalisation'; + +const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { seed: { type: 'string' }, steps: { type: 'string' }, out: { type: 'string' } }, +}); +const command = positionals[0]; +const experiment = JSON.parse(readFileSync(join(repoRoot, DECLARED), 'utf8')) as Rl3Experiment; +const outRoot = values.out ?? join(repoRoot, OUT_DIR); +const steps = values.steps ? Number(values.steps) : undefined; +if (steps !== undefined && !values.out) throw new Error('--steps overrides the declared budget: pass --out to a scratch directory'); +const seeds = values.seed ? [Number(values.seed)] : experiment.seeds; +if (!values.out) { + for (const seed of seeds) if (!experiment.seeds.includes(seed)) throw new Error(`seed ${seed} is not declared`); +} +if (experiment.protocolId !== CIRCUIT_PROTOCOL.id) { + throw new Error(`experiment declares ${experiment.protocolId}, code is ${CIRCUIT_PROTOCOL.id}`); +} + +await tf.setBackend(experiment.agent.backend); +await tf.ready(); + +const git = (cmd: string) => execSync(cmd, { cwd: repoRoot, encoding: 'utf8' }).trim(); +const runtime = () => ({ + gitSha: git('git rev-parse HEAD'), + gitDirtyAtRunTime: git('git status --porcelain') !== '', + nodeVersion: process.version, + platform: `${process.platform}-${process.arch}`, + tfjsVersion: tf.version.tfjs, + tfjsBackend: tf.getBackend(), +}); +const seedDir = (seed: number) => join(outRoot, `seed-${seed}`); +const writeJson = (path: string, value: unknown) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`); + +/** sha256 over every weight tensor of a model, in layer order. */ +function weightsHash(model: tf.LayersModel): string { + const hash = createHash('sha256'); + for (const w of model.getWeights()) hash.update(Buffer.from((w.dataSync() as Float32Array).buffer)); + return hash.digest('hex'); +} + +// ── train ──────────────────────────────────────────────────────────────────── +async function train(seed: number) { + const dir = seedDir(seed); + mkdirSync(dir, { recursive: true }); + const logPath = join(dir, 'train-episodes.jsonl'); + rmSync(logPath, { force: true }); + const agent = new DQNAgent({ ...buildAgentConfig(experiment, seed), storageProvider: fileSystemModelProvider(dir) }); + const startedAt = new Date().toISOString(); + const t0 = process.hrtime.bigint(); + try { + await agent.saveModel('untrained', { seed, stage: 'untrained' }); + const untrainedHash = weightsHash(agent.getModel()); + let last = Date.now(); + const result = await runTraining({ + experiment, seed, agent, envSteps: steps, + onEpisode: (row) => { + appendFileSync(logPath, `${JSON.stringify(row)}\n`); + if (Date.now() - last > 30_000) { + last = Date.now(); + console.error(JSON.stringify({ seed, envSteps: row.envStepsEnd, episode: row.episode, endReason: row.endReason, laps: row.laps })); + } + }, + }); + const durationMs = Number(process.hrtime.bigint() - t0) / 1e6; + await agent.saveModel('trained', { seed, stage: 'trained', envSteps: result.envSteps }); + const trainedHash = weightsHash(agent.getModel()); + const eps = result.episodes; + const tail = eps.slice(-100); + const run = { + seed, + algorithm: experiment.algorithm, + agentConfig: buildAgentConfig(experiment, seed), + envSteps: result.envSteps, + declaredEnvSteps: experiment.budget.envStepsPerRun, + episodes: eps.length, + partialEpisodeAtBudget: result.partialEpisodeAtBudget, + trainingEndReasons: { + success: eps.filter((e) => e.endReason === 'success').length, + offTrack: eps.filter((e) => e.endReason === 'off-track').length, + timeLimit: eps.filter((e) => e.endReason === 'time-limit').length, + }, + last100: { + episodes: tail.length, + success: tail.filter((e) => e.endReason === 'success').length, + meanLaps: tail.reduce((s, e) => s + e.laps, 0) / Math.max(1, tail.length), + }, + weightsSha256: { untrained: untrainedHash, trained: trainedHash }, + startedAt, + finishedAt: new Date().toISOString(), + durationMs, + msPerEnvStep: durationMs / result.envSteps, + ...runtime(), + }; + writeJson(join(dir, 'run.json'), run); + console.log(JSON.stringify({ seed, durationMs: Math.round(durationMs), msPerEnvStep: run.msPerEnvStep, episodes: run.episodes, endReasons: run.trainingEndReasons, last100: run.last100 })); + } finally { + agent.dispose(); + } +} + +// ── eval (new process, frozen weights) ─────────────────────────────────────── +function greedyPolicy(model: tf.LayersModel) { + // Only getAction: evaluateCircuit cannot reach remember() or train() through it. + return { + async getAction(observation: number[]): Promise { + return tf.tidy(() => (model.predict(tf.tensor2d([observation])) as tf.Tensor).argMax(1).dataSync()[0]); + }, + }; +} + +/** Re-drives one episode outside the protocol to record x/y, and checks it matches the protocol episode. */ +async function replay(policy: ReturnType, circuit: Rl3Circuit, start: number) { + const t = CIRCUIT_PROTOCOL.circuits[circuit]; + const world = new CircuitEnv(t.straightLength, t.radius, t.halfWidth, { + startWaypoint: start, maxSteps: CIRCUIT_PROTOCOL.maxSteps, targetLaps: CIRCUIT_PROTOCOL.targetLaps, + }); + // points[k] = car position after k steps (points[0] = start), one point per step. + const points: [number, number][] = [[round(world.carX), round(world.carY)]]; + const lapEndSteps: number[] = []; + while (!world.done()) { + const laps = world.laps; + world.step(await policy.getAction(world.observe())); + points.push([round(world.carX), round(world.carY)]); + if (world.laps > laps) lapEndSteps.push(world.stepCount); + } + world.reset(); + return { episode: world.lastEpisode!, points, lapEndSteps }; +} +const round = (v: number) => Math.round(v * 1000) / 1000; + +async function evaluate(seed: number) { + const dir = seedDir(seed); + const rows: EvalEpisodeRow[] = []; + const reports: Record = {}; + const trajectories: Record = {}; + const frozen: Record = {}; + const run = JSON.parse(readFileSync(join(dir, 'run.json'), 'utf8')); + const t0 = process.hrtime.bigint(); + for (const policyName of RL3_POLICIES) { + const model = await fileSystemModelProvider(dir).load(policyName) as tf.LayersModel; + try { + const before = weightsHash(model); + const policy = greedyPolicy(model); + for (const circuit of RL3_CIRCUITS) { + const report = await evaluateCircuit(policy, { policyId: `rl3-dqn-seed-${seed}-${policyName}-w${before.slice(0, 12)}`, circuit }); + reports[`${policyName}-${circuit}`] = report; + for (const e of report.episodes) { + rows.push({ + protocolId: report.protocolId, policyId: report.policyId, seed, policy: policyName, circuit, start: e.startWaypoint, + endReason: e.endReason, laps: e.completedLaps, transitions: e.transitions, + lapTimesSeconds: e.lapTimesSeconds, simulationSeconds: e.simulationSeconds, + }); + const r = await replay(policy, circuit, e.startWaypoint); + const same = r.episode.endReason === e.endReason && r.episode.transitions === e.transitions && r.episode.completedLaps === e.completedLaps; + if (!same) throw new Error(`replay differs from protocol episode: seed ${seed} ${policyName} ${circuit} start ${e.startWaypoint}`); + trajectories[`${policyName}/${circuit}/${e.startWaypoint}`] = { + policyId: report.policyId, transitions: e.transitions, completedLaps: e.completedLaps, endReason: e.endReason, + lapEndSteps: r.lapEndSteps, everySteps: 1, points: r.points, + }; + } + } + const after = weightsHash(model); + frozen[policyName] = { before, after, unchanged: before === after, matchesTrainProcess: before === run.weightsSha256[policyName] }; + if (before !== after) throw new Error(`weights changed during evaluation (seed ${seed}, ${policyName})`); + if (before !== run.weightsSha256[policyName]) throw new Error(`loaded weights differ from the training process (seed ${seed}, ${policyName})`); + } finally { + model.dispose(); + } + } + writeFileSync(join(dir, 'eval-episodes.jsonl'), rows.map((r) => JSON.stringify(r)).join('\n') + '\n'); + writeJson(join(dir, 'eval-reports.json'), reports); + writeJson(join(dir, 'trajectories.json'), trajectories); + writeJson(join(dir, 'eval-run.json'), { + process: 'rl3-bench eval (new process, weights loaded from disk)', + seed, protocolId: CIRCUIT_PROTOCOL.id, frozenWeights: frozen, + durationMs: Number(process.hrtime.bigint() - t0) / 1e6, + finishedAt: new Date().toISOString(), ...runtime(), + }); + console.log(JSON.stringify({ seed, rows: rows.map((r) => `${r.policy}/${r.circuit}/${r.start}:${r.endReason}:${r.laps}`) })); +} + +// ── manifest ───────────────────────────────────────────────────────────────── +const RUN_FILES = [ + 'train-episodes.jsonl', 'run.json', 'eval-episodes.jsonl', 'eval-reports.json', 'eval-run.json', 'trajectories.json', + 'untrained/model.json', 'untrained/weights.bin', 'trained/model.json', 'trained/weights.bin', +]; +const GIT_SHA_RULE = `gitSha is git rev-parse HEAD at train time; after the artifacts are committed it is an ancestor of the commit that last modified ${OUT_DIR}/manifest.json`; + +function manifest() { + const missing: string[] = []; + for (const seed of experiment.seeds) for (const f of RUN_FILES) if (!existsSync(join(seedDir(seed), f))) missing.push(`seed-${seed}/${f}`); + if (missing.length) { + console.error(JSON.stringify({ error: 'missing artifacts', missing }, null, 2)); + process.exit(1); + } + const runs = experiment.seeds.map((seed) => JSON.parse(readFileSync(join(seedDir(seed), 'run.json'), 'utf8'))); + const evalRuns = experiment.seeds.map((seed) => JSON.parse(readFileSync(join(seedDir(seed), 'eval-run.json'), 'utf8'))); + const budgets = new Set(runs.map((r) => r.envSteps)); + if (budgets.size !== 1 || !budgets.has(experiment.budget.envStepsPerRun)) throw new Error('runs do not all use the declared budget'); + const rows = experiment.seeds.flatMap((seed) => parseEvalLog(readFileSync(join(seedDir(seed), 'eval-episodes.jsonl'), 'utf8'))); + const options = { seeds: experiment.seeds, protocolId: CIRCUIT_PROTOCOL.id, starts: CIRCUIT_PROTOCOL.startWaypoints, targetLaps: CIRCUIT_PROTOCOL.targetLaps }; + const results = RL3_POLICIES.map((policy: Rl3Policy) => summarizePolicy(rows, { ...options, policy })); + writeJson(join(outRoot, 'summary.json'), { protocolId: CIRCUIT_PROTOCOL.id, source: 'seed-/eval-episodes.jsonl', ...summaryFile(results) }); + writeJson(join(outRoot, 'experiment.json'), { + ...experiment, + declaredPath: DECLARED, + protocol: CIRCUIT_PROTOCOL, + runtime: { + gitSha: runs[0].gitSha, + gitShaRule: GIT_SHA_RULE, + allRunsSameGitSha: new Set(runs.map((r) => r.gitSha)).size === 1, + nodeVersion: runs[0].nodeVersion, + platform: runs[0].platform, + tfjsVersion: runs[0].tfjsVersion, + tfjsBackend: runs[0].tfjsBackend, + trainingDurationMs: runs.reduce((s, r) => s + r.durationMs, 0), + evaluationDurationMs: evalRuns.reduce((s, r) => s + r.durationMs, 0), + }, + runs: runs.map((r, i) => ({ + seed: r.seed, envSteps: r.envSteps, episodes: r.episodes, trainingEndReasons: r.trainingEndReasons, + partialEpisodeAtBudget: r.partialEpisodeAtBudget, startedAt: r.startedAt, finishedAt: r.finishedAt, + durationMs: r.durationMs, msPerEnvStep: r.msPerEnvStep, gitSha: r.gitSha, gitDirtyAtRunTime: r.gitDirtyAtRunTime, + evalGitSha: evalRuns[i].gitSha, frozenWeights: evalRuns[i].frozenWeights, + })), + }); + const artifact = (rel: string) => { + const buf = readFileSync(join(outRoot, rel)); + return { path: rel, bytes: buf.byteLength, sha256: createHash('sha256').update(buf).digest('hex') }; + }; + writeJson(join(outRoot, 'manifest.json'), { + gitSha: runs[0].gitSha, + gitShaRule: GIT_SHA_RULE, + protocolId: CIRCUIT_PROTOCOL.id, + algorithm: experiment.algorithm, + seeds: experiment.seeds, + budget: experiment.budget, + experiment: artifact('experiment.json'), + summary: artifact('summary.json'), + runs: Object.fromEntries(experiment.seeds.map((seed) => [ + String(seed), Object.fromEntries(RUN_FILES.map((f) => [f, artifact(`seed-${seed}/${f}`)])), + ])), + }); + console.log(JSON.stringify({ gitSha: runs[0].gitSha, artifacts: experiment.seeds.length * RUN_FILES.length + 2, out: relative(repoRoot, outRoot) })); +} + +if (command === 'train') for (const seed of seeds) await train(seed); +else if (command === 'eval') for (const seed of seeds) await evaluate(seed); +else if (command === 'manifest') manifest(); +else throw new Error('usage: rl3-bench.mts train|eval|manifest [--seed n] [--steps n --out dir]'); diff --git a/packages/demo-car-circuit/src/generalisation/results.ts b/packages/demo-car-circuit/src/generalisation/results.ts new file mode 100644 index 0000000..f3536f5 --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation/results.ts @@ -0,0 +1,209 @@ +/** + * RL 3 — reading the raw evaluation logs. Pure code, shared by the bench script + * (summary.json) and the page (which recomputes every number from the JSONL logs). + */ + +export const RL3_POLICIES = ['trained', 'untrained'] as const; +export type Rl3Policy = (typeof RL3_POLICIES)[number]; +export const RL3_CIRCUITS = ['training', 'test'] as const; +export type Rl3Circuit = (typeof RL3_CIRCUITS)[number]; +export const RL3_END_REASONS = ['success', 'off-track', 'time-limit'] as const; +export type Rl3EndReason = (typeof RL3_END_REASONS)[number]; + +/** One line of eval-episodes.jsonl: one frozen-policy episode of circuit-evaluation-v1. */ +export interface EvalEpisodeRow { + protocolId: string; + /** Versioned id passed to evaluateCircuit; identical on both circuits for one seed and policy. */ + policyId: string; + seed: number; + policy: Rl3Policy; + circuit: Rl3Circuit; + start: number; + endReason: Rl3EndReason; + laps: number; + transitions: number; + lapTimesSeconds: number[]; + simulationSeconds: number; +} + +export interface CircuitCounts { + episodes: number; + successes: number; + offTrack: number; + truncated: number; + laps: number; + maxLaps: number; + transitions: number; + /** Success share in [0, 1]. */ + successRate: number; + /** Completed laps / (episodes × target laps), in [0, 1]. */ + lapRate: number; +} + +export interface SeedResult { + seed: number; + training: CircuitCounts; + test: CircuitCounts; + /** training − test, success share (positive: worse on the unseen circuit). */ + successGap: number; + /** training − test, completed-lap share. */ + lapGap: number; + episodes: { training: EvalEpisodeRow[]; test: EvalEpisodeRow[] }; +} + +export interface PolicyResult { + policy: Rl3Policy; + seeds: SeedResult[]; + /** Mean over seeds (each seed weighs the same). */ + mean: { + trainingSuccessRate: number; + testSuccessRate: number; + successGap: number; + trainingLapRate: number; + testLapRate: number; + lapGap: number; + }; + totals: { training: CircuitCounts; test: CircuitCounts }; +} + +const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const isInt = (v: unknown): v is number => Number.isInteger(v); + +/** Returns null when the row has the expected shape, otherwise the problem. */ +export function checkEvalRow(raw: unknown): string | null { + const r = raw as Partial | null; + if (!r || typeof r !== 'object') return 'row is not an object'; + if (typeof r.protocolId !== 'string') return 'protocolId missing'; + if (typeof r.policyId !== 'string' || !r.policyId.trim()) return 'policyId missing'; + if (!isInt(r.seed)) return 'seed missing'; + if (!RL3_POLICIES.includes(r.policy as Rl3Policy)) return 'policy is not trained/untrained'; + if (!RL3_CIRCUITS.includes(r.circuit as Rl3Circuit)) return 'circuit is not training/test'; + if (!isInt(r.start)) return 'start missing'; + if (!RL3_END_REASONS.includes(r.endReason as Rl3EndReason)) return 'endReason unknown'; + if (!isInt(r.laps) || !isInt(r.transitions)) return 'laps/transitions missing'; + if (!Array.isArray(r.lapTimesSeconds) || !r.lapTimesSeconds.every(isNum)) return 'lapTimesSeconds missing'; + if (!isNum(r.simulationSeconds)) return 'simulationSeconds missing'; + return null; +} + +/** Strict JSONL parser: throws on the first malformed line (with its number). */ +export function parseEvalLog(text: string): EvalEpisodeRow[] { + if (text.trimStart().startsWith('<')) throw new Error('not a JSONL log'); + const lines = text.split('\n').filter((line) => line.trim() !== ''); + if (lines.length === 0) throw new Error('empty log'); + return lines.map((line, i) => { + let row: unknown; + try { + row = JSON.parse(line); + } catch { + throw new Error(`line ${i + 1} is not JSON`); + } + const issue = checkEvalRow(row); + if (issue) throw new Error(`line ${i + 1}: ${issue}`); + return row as EvalEpisodeRow; + }); +} + +export function countCircuit(rows: EvalEpisodeRow[], targetLaps: number): CircuitCounts { + const episodes = rows.length; + const successes = rows.filter((r) => r.endReason === 'success').length; + const laps = rows.reduce((s, r) => s + r.laps, 0); + const maxLaps = episodes * targetLaps; + return { + episodes, + successes, + offTrack: rows.filter((r) => r.endReason === 'off-track').length, + truncated: rows.filter((r) => r.endReason === 'time-limit').length, + laps, + maxLaps, + transitions: rows.reduce((s, r) => s + r.transitions, 0), + successRate: episodes ? successes / episodes : 0, + lapRate: maxLaps ? laps / maxLaps : 0, + }; +} + +const mean = (values: number[]) => values.reduce((s, v) => s + v, 0) / values.length; + +/** + * Summarises one policy. Fails if a seed lacks episodes on a circuit, if the + * protocol id is not the expected one, or if starts differ from the protocol. + */ +export function summarizePolicy( + rows: EvalEpisodeRow[], + options: { policy: Rl3Policy; seeds: number[]; protocolId: string; starts: readonly number[]; targetLaps: number }, +): PolicyResult { + const own = rows.filter((r) => r.policy === options.policy); + for (const r of own) { + if (r.protocolId !== options.protocolId) throw new Error(`row uses protocol ${r.protocolId}, expected ${options.protocolId}`); + } + const seeds = options.seeds.map((seed): SeedResult => { + const pick = (circuit: Rl3Circuit) => { + const list = own + .filter((r) => r.seed === seed && r.circuit === circuit) + .sort((a, b) => options.starts.indexOf(a.start) - options.starts.indexOf(b.start)); + const starts = list.map((r) => r.start); + if (JSON.stringify(starts) !== JSON.stringify([...options.starts])) { + throw new Error(`seed ${seed}, ${options.policy}, ${circuit}: starts ${JSON.stringify(starts)} differ from the protocol`); + } + return list; + }; + const training = pick('training'); + const test = pick('test'); + const ids = new Set([...training, ...test].map((r) => r.policyId)); + if (ids.size !== 1) throw new Error(`seed ${seed}, ${options.policy}: not the same policyId on both circuits`); + const t = countCircuit(training, options.targetLaps); + const u = countCircuit(test, options.targetLaps); + return { + seed, training: t, test: u, + successGap: t.successRate - u.successRate, + lapGap: t.lapRate - u.lapRate, + episodes: { training, test }, + }; + }); + return { + policy: options.policy, + seeds, + mean: { + trainingSuccessRate: mean(seeds.map((s) => s.training.successRate)), + testSuccessRate: mean(seeds.map((s) => s.test.successRate)), + successGap: mean(seeds.map((s) => s.successGap)), + trainingLapRate: mean(seeds.map((s) => s.training.lapRate)), + testLapRate: mean(seeds.map((s) => s.test.lapRate)), + lapGap: mean(seeds.map((s) => s.lapGap)), + }, + totals: { + training: countCircuit(own.filter((r) => r.circuit === 'training'), options.targetLaps), + test: countCircuit(own.filter((r) => r.circuit === 'test'), options.targetLaps), + }, + }; +} + +/** The versioned summary.json: same numbers as the page, without the episode lists. */ +export function summaryFile(results: PolicyResult[]) { + return Object.fromEntries( + results.map((r) => [ + r.policy, + { + mean: r.mean, + totals: r.totals, + seeds: r.seeds.map(({ episodes: _e, ...rest }) => rest), + }, + ]), + ); +} + +export type Rl3ReadingKey = 'noGap' | 'gapAllSeeds' | 'gapSomeSeeds' | 'testBetter' | 'neverSolved'; + +/** + * Which sentence the logs support, decided on the lap share (finer than the + * success share with 3 episodes per circuit). Never says "generalises" by itself; + * the page always prints the numbers next to the sentence. + */ +export function chooseReading(trained: PolicyResult): Rl3ReadingKey { + const seeds = trained.seeds; + if (seeds.every((s) => s.training.laps === 0)) return 'neverSolved'; + if (seeds.every((s) => s.lapGap === 0)) return 'noGap'; + if (seeds.every((s) => s.lapGap > 0)) return 'gapAllSeeds'; + if (seeds.some((s) => s.lapGap > 0)) return 'gapSomeSeeds'; + return 'testBetter'; +} diff --git a/packages/demo-car-circuit/src/generalisation/training.ts b/packages/demo-car-circuit/src/generalisation/training.ts new file mode 100644 index 0000000..9d3f627 --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation/training.ts @@ -0,0 +1,195 @@ +/** + * RL 3 — training core shared by the bench script and the tests. + * + * Trains one DQN on the TRAINING circuit of `circuit-evaluation-v1` only, through + * the public IgnitionEnv loop (getAction → step → remember → train). The held-out + * test circuit is never instantiated here: it is only seen by evaluateCircuit(), + * after training, on the frozen weights. + * + * No checkpoint selection: the evaluated policy is the network as it stands when + * the declared budget of environment steps is spent. + */ +import { IgnitionEnv, type AgentInterface, type TrainingEnv } from '@ignitionai/core'; +import { CircuitEnv, type CircuitEpisode } from '../circuit-env'; +import { CIRCUIT_PROTOCOL } from '../evaluation'; + +export interface Rl3AgentDeclaration { + class: string; + inputSize: number; + actionSize: number; + hiddenLayers: number[]; + lr: number; + gamma: number; + epsilon: number; + epsilonDecay: number; + minEpsilon: number; + batchSize: number; + memorySize: number; + targetUpdateFrequency: number; + backend: 'cpu'; + doubleQ: boolean; +} + +export interface Rl3Experiment { + experiment: 'rl3-generalisation'; + protocolId: string; + seeds: number[]; + algorithm: 'dqn'; + training: { + circuit: 'training'; + startWaypoints: 'uniform'; + startSeedRule: string; + maxStepsPerEpisode: number; + targetLaps: number; + }; + budget: { envStepsPerRun: number }; + agent: Rl3AgentDeclaration; +} + +export interface TrainingEpisodeRow { + seed: number; + phase: 'train'; + circuit: 'training'; + episode: number; + start: number; + endReason: CircuitEpisode['endReason']; + laps: number; + transitions: number; + return: number; + /** Environment steps done when the episode ended (1-based, cumulative). */ + envStepsEnd: number; +} + +/** Same LCG as the RL 1 / RL 2 scripts and DQNAgent's seeded stream. */ +export function mulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state / 4294967296; + }; +} + +/** Training starts: own seeded stream, independent of the agent's exploration stream. */ +export function trainingStartStream(seed: number): () => number { + return mulberry32(seed * 7919 + 13); +} + +/** DQN config for one run. Everything comes from experiment.json except the seed. */ +export function buildAgentConfig(experiment: Rl3Experiment, seed: number) { + const a = experiment.agent; + return { + inputSize: a.inputSize, + actionSize: a.actionSize, + hiddenLayers: [...a.hiddenLayers], + lr: a.lr, + gamma: a.gamma, + epsilon: a.epsilon, + epsilonDecay: a.epsilonDecay, + minEpsilon: a.minEpsilon, + batchSize: a.batchSize, + memorySize: a.memorySize, + targetUpdateFrequency: a.targetUpdateFrequency, + backend: a.backend, + doubleQ: a.doubleQ, + seed, + }; +} + +/** + * The training circuit of the protocol with a new seeded start waypoint at every + * episode. Delegates physics, reward and episode end to an unmodified CircuitEnv. + */ +export class TrainingCircuit implements TrainingEnv { + readonly actions = ['steer_left', 'straight', 'steer_right']; + world: CircuitEnv; + startWaypoint = 0; + private readonly pickStart: () => number; + private episodeReturn = 0; + + constructor( + private readonly experiment: Rl3Experiment, + seed: number, + private readonly onEpisode?: (episode: CircuitEpisode & { start: number; return: number }) => void, + ) { + if (experiment.training.circuit !== 'training') throw new Error('RL 3 trains on the training circuit only'); + this.pickStart = trainingStartStream(seed); + this.world = this.nextWorld(); + } + + private nextWorld(): CircuitEnv { + const track = CIRCUIT_PROTOCOL.circuits.training; + // OvalTrack has 65 waypoints; CircuitEnv accepts 0..63 as a start. + const probe = new CircuitEnv(track.straightLength, track.radius, track.halfWidth); + const starts = probe.track.waypoints.length - 1; + this.startWaypoint = Math.floor(this.pickStart() * starts); + this.episodeReturn = 0; + return new CircuitEnv(track.straightLength, track.radius, track.halfWidth, { + startWaypoint: this.startWaypoint, + maxSteps: this.experiment.training.maxStepsPerEpisode, + targetLaps: this.experiment.training.targetLaps, + }); + } + + observe(): number[] { return this.world.observe(); } + step(action: number | number[]): void { + this.world.step(action); + this.episodeReturn += this.world.reward(); + } + reward(): number { return this.world.reward(); } + terminated(): boolean { return this.world.terminated(); } + truncated(): boolean { return this.world.truncated(); } + done(): boolean { return this.world.done(); } + + reset(): void { + if (this.world.done()) { + this.world.reset(); + const episode = this.world.lastEpisode; + if (episode) this.onEpisode?.({ ...episode, start: this.startWaypoint, return: this.episodeReturn }); + } + this.world = this.nextWorld(); + } + + /** Steps and return of the episode still running (used when the budget ends mid-episode). */ + partial(): { start: number; transitions: number; laps: number; return: number } { + return { start: this.startWaypoint, transitions: this.world.stepCount, laps: this.world.laps, return: this.episodeReturn }; + } +} + +export interface TrainingResult { + episodes: TrainingEpisodeRow[]; + envSteps: number; + partialEpisodeAtBudget: ReturnType; +} + +/** + * Runs exactly `envSteps` (default: the declared budget) training steps through + * IgnitionEnv.step(). The caller owns the agent and its weights afterwards. + */ +export async function runTraining(options: { + experiment: Rl3Experiment; + seed: number; + agent: AgentInterface; + envSteps?: number; + onEpisode?: (row: TrainingEpisodeRow) => void; +}): Promise { + const { experiment, seed, agent } = options; + const envSteps = options.envSteps ?? experiment.budget.envStepsPerRun; + if (!Number.isInteger(envSteps) || envSteps < 1) throw new Error('envSteps must be a positive integer'); + const episodes: TrainingEpisodeRow[] = []; + let step = 0; + const env = new TrainingCircuit(experiment, seed, (e) => { + const row: TrainingEpisodeRow = { + seed, phase: 'train', circuit: 'training', episode: episodes.length, start: e.start, + endReason: e.endReason, laps: e.completedLaps, transitions: e.transitions, + return: e.return, envStepsEnd: step, + }; + episodes.push(row); + options.onEpisode?.(row); + }); + const loop = new IgnitionEnv(env); + loop.agent = agent; + for (step = 1; step <= envSteps; step++) { + await loop.step(); + } + return { episodes, envSteps, partialEpisodeAtBudget: env.partial() }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 20f4127..82f1dc2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -261,6 +261,9 @@ importers: playwright: specifier: ^1.56.1 version: 1.65.0 + tsx: + specifier: ^4.19.3 + version: 4.19.3 typescript: specifier: ~5.7.2 version: 5.7.3 From 4a6963a1fa17f40ca73074cd48fdbd330e0129c7 Mon Sep 17 00:00:00 2001 From: "openbotgit[bot]" <335604065+openbotgit[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:04:22 +0100 Subject: [PATCH 02/11] =?UTF-8?q?RL=203=20:=20page=20FR/EN=20et=20tests=20?= =?UTF-8?q?(lecture=20des=20journaux,=20=C3=A9valuation=20fig=C3=A9e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- .../src/generalisation-main.tsx | 9 + .../demo-car-circuit/src/generalisation.html | 16 + .../src/generalisation/Rl3App.tsx | 729 ++++++++++++++++++ .../src/generalisation/data.ts | 298 +++++++ .../src/generalisation/i18n.ts | 82 ++ .../src/generalisation/locales/en.json | 78 ++ .../src/generalisation/locales/fr.json | 78 ++ .../test/rl3-generalisation.test.ts | 309 ++++++++ packages/demo-car-circuit/tsconfig.json | 2 +- packages/demo-car-circuit/vite.config.ts | 12 +- 10 files changed, 1611 insertions(+), 2 deletions(-) create mode 100644 packages/demo-car-circuit/src/generalisation-main.tsx create mode 100644 packages/demo-car-circuit/src/generalisation.html create mode 100644 packages/demo-car-circuit/src/generalisation/Rl3App.tsx create mode 100644 packages/demo-car-circuit/src/generalisation/data.ts create mode 100644 packages/demo-car-circuit/src/generalisation/i18n.ts create mode 100644 packages/demo-car-circuit/src/generalisation/locales/en.json create mode 100644 packages/demo-car-circuit/src/generalisation/locales/fr.json create mode 100644 packages/demo-car-circuit/test/rl3-generalisation.test.ts diff --git a/packages/demo-car-circuit/src/generalisation-main.tsx b/packages/demo-car-circuit/src/generalisation-main.tsx new file mode 100644 index 0000000..bf90d71 --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation-main.tsx @@ -0,0 +1,9 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import Rl3App from './generalisation/Rl3App'; + +createRoot(document.getElementById('root')!).render( + + + , +); diff --git a/packages/demo-car-circuit/src/generalisation.html b/packages/demo-car-circuit/src/generalisation.html new file mode 100644 index 0000000..f17272d --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation.html @@ -0,0 +1,16 @@ + + + + + + IgnitionAI — RL 3 + + + +
+ + + diff --git a/packages/demo-car-circuit/src/generalisation/Rl3App.tsx b/packages/demo-car-circuit/src/generalisation/Rl3App.tsx new file mode 100644 index 0000000..ad8baaa --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation/Rl3App.tsx @@ -0,0 +1,729 @@ +import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from 'react'; +import { OvalTrack } from '../track'; +import { CIRCUIT_PROTOCOL } from '../evaluation'; +import { getLanguage, setLanguage, subscribe, t, type Language } from './i18n'; +import { + loadRl3, manifestOverride, rl3ManifestUrl, + type Rl3Data, type Rl3LoadResult, type Rl3Problem, type Trajectory, +} from './data'; +import { RL3_CIRCUITS, type CircuitCounts, type EvalEpisodeRow, type PolicyResult, type Rl3Circuit, type Rl3EndReason } from './results'; + +// Condition hues at equal relative luminance (0.389 / 0.391), same weight everywhere. +export const HUE: Record = { training: '#5eadf5', test: '#e8954a' }; +const TEXT = '#e2e8f0'; +const MUTED = '#94a3b8'; +const BORDER = '#334155'; +const EDGE = '#64748b'; +const ACTIVE = '#4f46e5'; +const NARROW = 720; +const STEPS_PER_FRAME = 4; +/** Tutorial URL; the link is shown only once the tutorial is published. */ +export const RL3_TUTORIAL_URL: string | null = null; + +// ── hooks ──────────────────────────────────────────────────────────────────── + +function useLanguage(): Language { + return useSyncExternalStore(subscribe, getLanguage, getLanguage); +} + +function subscribeResize(listener: () => void) { + window.addEventListener('resize', listener); + return () => window.removeEventListener('resize', listener); +} + +function useWidth(): number { + return useSyncExternalStore(subscribeResize, () => window.innerWidth, () => 1280); +} + +function prefersReducedMotion(): boolean { + return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && + window.matchMedia('(prefers-reduced-motion: reduce)').matches; +} + +// ── formatting ─────────────────────────────────────────────────────────────── + +export function formatDecimal(value: number, lang: Language, digits = 2): string { + const text = value.toFixed(digits); + return lang === 'fr' ? text.replace('.', ',') : text; +} + +export function formatInt(value: number, lang: Language): string { + // fr-FR groups with a narrow no-break space. + return value.toLocaleString(lang === 'fr' ? 'fr-FR' : 'en-US'); +} + +/** Signed integer with a true minus sign: "+2", "−3", "0". */ +export function formatSignedInt(value: number): string { + if (value > 0) return `+${value}`; + if (value < 0) return `−${Math.abs(value)}`; + return '0'; +} + +export function formatSignedDecimal(value: number, lang: Language, digits = 2): string { + const rounded = Number(value.toFixed(digits)); + const body = formatDecimal(Math.abs(rounded), lang, digits); + if (rounded > 0) return `+${body}`; + if (rounded < 0) return `−${body}`; + return body; +} + +const endText = (end: Rl3EndReason) => + end === 'success' ? t('rl3.end.success') : end === 'off-track' ? t('rl3.end.offTrack') : t('rl3.end.timeLimit', { maxSteps: formatInt(CIRCUIT_PROTOCOL.maxSteps, getLanguage()) }); + +const endSymbol = (end: Rl3EndReason) => (end === 'success' ? '●' : end === 'off-track' ? '×' : '□'); + +// ── page ───────────────────────────────────────────────────────────────────── + +type State = { status: 'loading' } | { status: 'done'; result: Rl3LoadResult }; + +export default function Rl3App({ initial }: { initial?: Rl3LoadResult } = {}) { + const lang = useLanguage(); + const width = useWidth(); + const narrow = width < NARROW; + const [state, setState] = useState(initial ? { status: 'done', result: initial } : { status: 'loading' }); + + useEffect(() => { + if (initial) return; + let cancelled = false; + const url = manifestOverride(window.location.search, window.location.href) ?? rl3ManifestUrl(); + loadRl3(url) + .then((result) => { if (!cancelled) setState({ status: 'done', result }); }) + .catch((cause) => { + if (!cancelled) setState({ status: 'done', result: { kind: 'format', problems: [{ url, format: String(cause) }] } }); + }); + return () => { cancelled = true; }; + }, [initial]); + + const result = state.status === 'done' ? state.result : null; + const data = result?.kind === 'loaded' ? result.data : null; + + return ( +
+
+
+

{t('rl3.heading')}

+ {data && ( +

+ {t('rl3.subtitle', { sha: data.manifest.gitSha.slice(0, 12), protocolId: data.manifest.protocolId, seeds: data.manifest.seeds.join(', ') })} +

+ )} +
+ +
+ + {state.status === 'loading' &&

{t('rl3.loading')}

} + {result && result.kind !== 'loaded' && } + {data && } +
+ ); +} + +function problemText(p: Rl3Problem): string { + if (p.format) return t('rl3.error.format', { url: p.url }); + return p.status === undefined ? t('rl3.error.missing', { url: p.url }) : t('rl3.error.missingStatus', { url: p.url, status: p.status }); +} + +function ProblemList({ problems }: { problems: Rl3Problem[] }) { + return ( +
    + {problems.map((p) =>
  • {problemText(p)}
  • )} +
+ ); +} + +function GlobalError({ result }: { result: Exclude }) { + const testId = { missing: 'rl3-error', format: 'rl3-format-error', protocol: 'rl3-protocol-error', policy: 'rl3-policy-error' }[result.kind]; + return ( +
+ {(result.kind === 'missing' || result.kind === 'format') && } + {result.kind === 'protocol' &&

{t('rl3.error.protocol', { protocolId: CIRCUIT_PROTOCOL.id })} ({result.protocolId})

} + {result.kind === 'policy' &&

{t('rl3.error.policy', { seed: result.seed })}

} +

{t('rl3.error.noSimulation')}

+
+ ); +} + +function Loaded({ data, narrow, width, lang }: { data: Rl3Data; narrow: boolean; width: number; lang: Language }) { + const seeds = data.manifest.seeds; + const [seed, setSeed] = useState(seeds[0]); + const [start, setStart] = useState(CIRCUIT_PROTOCOL.startWaypoints[0]); + const select = (s: number, st: number) => { setSeed(s); setStart(st); }; + return ( + <> + + + + + + + ); +} + +// ── A. protocol ────────────────────────────────────────────────────────────── + +function ProtocolBlock({ data, lang }: { data: Rl3Data; lang: Language }) { + const p = data.experiment.protocol; + const c = p.circuits; + return ( +
+

{t('rl3.protocol.title')}

+

+ {t('rl3.protocol.line', { maxSteps: formatInt(p.maxSteps, lang), laps: p.targetLaps, starts: p.startWaypoints.join(', ') })} +

+

{t('rl3.protocol.samePolicy')}

+

+ {t('rl3.protocol.circuits', { + trainingStraight: c.training.straightLength, trainingRadius: c.training.radius, trainingHalf: c.training.halfWidth, + testStraight: c.test.straightLength, testRadius: c.test.radius, testHalf: c.test.halfWidth, + })} +

+

+ {t('rl3.protocol.training', { + algorithm: data.experiment.algorithm.toUpperCase(), + layers: `[${data.experiment.agent.hiddenLayers.join(', ')}]`, + steps: formatInt(data.experiment.budget.envStepsPerRun, lang), + })} +

+
+ ); +} + +// ── B. side-by-side top view ───────────────────────────────────────────────── + +const tracks: Record = { + training: new OvalTrack(CIRCUIT_PROTOCOL.circuits.training.straightLength, CIRCUIT_PROTOCOL.circuits.training.radius, CIRCUIT_PROTOCOL.circuits.training.halfWidth), + test: new OvalTrack(CIRCUIT_PROTOCOL.circuits.test.straightLength, CIRCUIT_PROTOCOL.circuits.test.radius, CIRCUIT_PROTOCOL.circuits.test.halfWidth), +}; + +/** Right-hand unit normal at waypoint i (signedDistance > 0 side in track.ts). */ +function normalAt(track: OvalTrack, i: number): [number, number] { + const w = track.waypoints; + const a = w[i]; + const b = w[(i + 1) % w.length]; + const angle = Math.atan2(b.y - a.y, b.x - a.x); + return [Math.sin(angle), -Math.cos(angle)]; +} + +function edges(track: OvalTrack) { + const left: [number, number][] = []; + const right: [number, number][] = []; + track.waypoints.forEach((p, i) => { + const [nx, ny] = normalAt(track, i); + right.push([p.x + nx * track.halfWidth, p.y + ny * track.halfWidth]); + left.push([p.x - nx * track.halfWidth, p.y - ny * track.halfWidth]); + }); + return { left, right }; +} + +// SVG y points down; the world y points up. +const sv = ([x, y]: [number, number]) => `${x.toFixed(3)},${(-y).toFixed(3)}`; +const pathOf = (pts: [number, number][], close = false) => `M${pts.map(sv).join('L')}${close ? 'Z' : ''}`; + +function splitLaps(traj: Trajectory, upTo: number): [number, number][][] { + const bounds = [0, ...traj.lapEndSteps, traj.points.length - 1]; + const parts: [number, number][][] = []; + for (let i = 0; i < bounds.length - 1; i++) { + const from = bounds[i]; + const to = Math.min(bounds[i + 1], upTo); + if (to > from) parts.push(traj.points.slice(from, to + 1)); + } + return parts; +} + +const lapStyle = (lap: number): { opacity: number; dash?: string } => + // Lap 1 solid, lap 2 faded, lap 3 dashed (index 0 = lap 1). + lap === 1 ? { opacity: 0.55 } : lap === 2 ? { opacity: 1, dash: '6 3' } : { opacity: 1 }; + +function TrackSvg({ circuit, traj, step, start, px, seed }: { circuit: Rl3Circuit; traj: Trajectory | null; step: number; start: number; px: number; seed: number }) { + const track = tracks[circuit]; + const { left, right } = useMemo(() => edges(track), [track]); + const unit = 24 / px; // world units per screen pixel (viewBox is 24 wide) + const hue = HUE[circuit]; + const shown = traj ? Math.min(step, traj.points.length - 1) : 0; + const finished = traj ? shown >= traj.points.length - 1 : false; + const end = traj?.points[shown]; + const mark = 5 * unit; + const centre = track.waypoints.map((p) => [p.x, p.y] as [number, number]); + const top = track.waypoints[8]; + return ( + + + + + + {/* Direction of travel (clockwise seen from above): along +x on the top straight. */} + + {CIRCUIT_PROTOCOL.startWaypoints.map((wp) => { + const p = track.waypoints[wp]; + const [nx, ny] = normalAt(track, wp); + const a: [number, number] = [p.x + nx * track.halfWidth, p.y + ny * track.halfWidth]; + const b: [number, number] = [p.x - nx * track.halfWidth, p.y - ny * track.halfWidth]; + const outer = Math.hypot(...a) > Math.hypot(...b) ? 1 : -1; + const label: [number, number] = [p.x + outer * nx * (track.halfWidth + 0.8), p.y + outer * ny * (track.halfWidth + 0.8)]; + const selected = wp === start; + return ( + + + + {wp} + + + ); + })} + {traj && splitLaps(traj, shown).map((pts, lap) => { + const s = lapStyle(lap); + return ( + + ); + })} + {traj && end && finished && ( + + {traj.endReason === 'success' && } + {traj.endReason === 'off-track' && ( + + )} + {traj.endReason === 'time-limit' && ( + + )} + + )} + {traj && end && !finished && ( + + )} + + ); +} + +function StatusLine({ circuit, traj, row, step, playing, lang }: { circuit: Rl3Circuit; traj: Trajectory; row: EvalEpisodeRow; step: number; playing: boolean; lang: Language }) { + const shown = Math.min(step, row.transitions); + const lapsSoFar = traj.lapEndSteps.filter((s) => s <= shown).length; + const finished = shown >= row.transitions; + const times = row.lapTimesSeconds.map((s) => formatDecimal(s, lang, 2)).join(' · '); + return ( +
+
+ {t('rl3.state.step', { step: formatInt(shown, lang), total: formatInt(row.transitions, lang) })} + {' · '} + {t('rl3.state.laps', { laps: lapsSoFar })} +
+
+ {finished ? `${endSymbol(row.endReason)} ${endText(row.endReason)}` : '…'} + {finished && playing ? ` · ${t('rl3.state.doneAt', { step: formatInt(row.transitions, lang) })}` : ''} +
+
{t('rl3.state.simTime', { seconds: formatDecimal(row.simulationSeconds, lang, 2) })}
+ {row.lapTimesSeconds.length > 0 &&
{t('rl3.state.lapTimes', { times })}
} +
{t('rl3.state.policy', { policyId: row.policyId })}
+
+ ); +} + +function SideBySide({ data, seed, start, select, narrow, width, lang }: { + data: Rl3Data; seed: number; start: number; select: (seed: number, start: number) => void; narrow: boolean; width: number; lang: Language; +}) { + const [step, setStep] = useState(Infinity); + const [playing, setPlaying] = useState(false); + const reduced = prefersReducedMotion(); + const frame = useRef(null); + const seedResult = data.trained.seeds.find((s) => s.seed === seed)!; + const rows = { + training: seedResult.episodes.training.find((r) => r.start === start)!, + test: seedResult.episodes.test.find((r) => r.start === start)!, + }; + const longest = Math.max(rows.training.transitions, rows.test.transitions); + + useEffect(() => { + setPlaying(false); + setStep(Infinity); + }, [seed, start]); + + useEffect(() => { + if (!playing) return; + const tick = () => { + setStep((s) => { + const next = s + STEPS_PER_FRAME; + if (next >= longest) { + setPlaying(false); + return longest; + } + return next; + }); + frame.current = requestAnimationFrame(tick); + }; + frame.current = requestAnimationFrame(tick); + return () => { if (frame.current !== null) cancelAnimationFrame(frame.current); }; + }, [playing, longest]); + + const panelPx = narrow ? Math.max(120, (width - 40 - 8) / 2) : Math.min(612, (width - 40 - 16) / 2); + const traces = data.trajectories; + + return ( +
+
+ {data.manifest.seeds.map((s) => ( + + ))} +
+
+ {CIRCUIT_PROTOCOL.startWaypoints.map((st) => ( + + ))} +
+ {traces.ok ? ( + <> +
+ + +
+ {reduced &&

{t('rl3.reducedMotion')}

} +
+ {RL3_CIRCUITS.map((circuit) => ( +
+

+ {t(`rl3.circuit.${circuit}`)} +

+ + +
+ ))} +
+

+ {t('rl3.lapLegend')} · {t('rl3.samePolicyNote')} +

+ + ) : 'missing' in traces ? ( +
+

{t('rl3.error.trace')}

+ +
+ ) : ( +
+

+ {t('rl3.error.replayMismatch', { field: traces.mismatch.field, replay: traces.mismatch.replay, report: traces.mismatch.report })} +

+

+ {t('rl3.control.seed', { seed: traces.mismatch.seed })} · {t(`rl3.circuit.${traces.mismatch.circuit}`)} · {t('rl3.control.start', { start: traces.mismatch.start })} +

+
+ )} +
+ ); +} + +function Swatch({ circuit }: { circuit: Rl3Circuit }) { + return