Files
JIANT/web/math_test.mjs
T
Claude 2f49580a00 Editor: a formula editor for MATH (MATH tab): write, hear, generate, send
- A VM for MATH's BYTE grammar (eng_lofi.c lofi_byte: a C expression of t and a, unsigned 32-bit): errors said with
  their place, the operators a tap away, the grammar's help; bit for bit the firmware's 48 BYTE formulas (768000
  samples against the C compiled natively), VARIANT's mutation (lofi_mut) and MOTION's speed (lofi_motion) too. A
  formula that is one of the device's (however spaced) is recognised as its ALGO
- Its picture: 128 rows of what it plays (VAR, BEND, LOOP, the start), each sample its heat
- Its sound: the device's formulas (BYTE and FLOAT's 48) through the emulator's own wasm (/emu/felucca.wasm, loaded on
  the first Play: track 1 made MATH as the send does, the note on MIDI channel 1); a formula of one's own through a model
  of the BYTE voice (the firmware's integer time, hold, bits, smoothing); against the emulator, dry, C4: waveform
  correlation median 0.97 (MOTION 0), 0.90 (MOTION 64)
- A seeded generator: formulas built from the families of the firmware's own (nibble-table melodies, Sierpinski,
  multiplied-and-shifted, modulo textures), each kept only if it moves and is not noise; and sounds the device plays
  (a formula of its own, VARIANT, MOTION, BEND, LOOP, CHIP)
- Send to a track (TRACK, SET of G_ENGSEL, the eight values by TRACK_PARAM, read back) and read a MATH track back
- EDITOR_PROTOCOL.md: the proposal for a user formula (100 FORMULA, the bytecode the editor builds and tests: at most 90
  bytes and a stack of 8 for the firmware's 48); no firmware change
- Built when the tab first opens; its sound stops with the tab. English, Spanish, Japanese
- The roll's operations run one after another (a reload never between a batch's writes)
- math_test.mjs (the VM, the bytecode, the generator, the model against the emulator); editor_browser_test.mjs: the MATH
  tab on desktop and phone, and a send to the firmware itself read back

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
2026-11-29 00:44:59 +00:00

115 lines
8.8 KiB
JavaScript

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
// (the formula editor) editor.html's MATH section (between MATH-BEGIN / MATH-END) against the firmware:
// node web/math_test.mjs
// - the VM: the grammar, its errors and where they are; every one of the firmware's 48 BYTE formulas (eng_lofi.c
// lofi_byte) bit for bit: their samples' hashes over 16000 (t, a) each, taken from the firmware's C compiled natively
// (V10.8.74); VAR's mutation (lofi_mut) and MOTION's speed (lofi_motion) the same way. FIRMWARE_SRC=.../eng_lofi.c and
// a C compiler: the hashes made again from that source
// - the proposed bytecode (EDITOR_PROTOCOL.md "a user formula"): the same samples as the VM, its size and stack
// - the generator: seeded (one seed, one formula), every formula valid and moving
// - EMU_WASM (default build/emu/felucca.wasm): the BYTE model against the emulator's own samples, formula by formula
// (the waveforms' correlation), and the eight values a send writes, read back
import fs from "fs";
import path from "path";
import { execFileSync } from "child_process";
const HERE = path.dirname(new URL(import.meta.url).pathname);
const html = fs.readFileSync(path.join(HERE, "editor.html"), "utf8");
const core = html.slice(html.indexOf("/*MATH-BEGIN*/"), html.indexOf("/*MATH-END*/"));
const X = new Function(core + "; return { MATH_BYTE, MATH_FLOAT, MathVM, mathMut, mathMotion, mathGenerate, mathScore, mathRenderByte, mathEmuRender, mathValues };")();
let fails = 0;
const ok = (c, what) => { console.log(`${what.padEnd(96)} ${c ? "ok" : "FAIL"}`); if (!c) fails++; };
const fnv = (h, x) => Math.imul(h ^ x, 16777619) >>> 0;
/* the samples the hashes cover: f, a 1 6 11 16, t 0..1999 x 37 then 2000 spread over 32 bits */
const SAMPLE_T = (i, f) => (i < 2000 ? i * 37 : (Math.imul(i, 2654435761) + f) >>> 0);
const BYTE_HASH = [242086445, 582409269, 2775287381, 947135173, 495738245, 2211565701, 2596376949, 438985765, 2282081181, 2549055893, 1457526661, 2061544245, 2633081133, 2898665829, 1122579133, 3002132165, 4187706811, 4262248330, 3341324481, 2218714499, 2476142609, 1061348845, 3915694821, 2047500439, 2253473162, 149204812, 1152284677, 1173597842, 2608852433, 1045119341, 3973695903, 2109218995, 488461709, 1212083197, 1237344109, 4232385389, 659021989, 1906829989, 2782905541, 1179991381, 2949286917, 2147962981, 225962673, 3708983153, 1322780669, 3252066965, 7766818, 2179502982];
const MUT_HASH = 3332514091;
/* ---- the grammar */
{
const V = X.MathVM;
const e1 = V.compile("t * (42 & t >> 10"), e2 = V.compile("t + x"), e3 = V.compile("t >> > 2"), e4 = V.compile("0x1FFFFFFFF");
ok(!e1.ok && e1.pos === 17 && !e2.ok && e2.pos === 4 && !e3.ok && e3.pos === 5 && !e4.ok, `VM: errors say what and where (${[e1, e2, e3, e4].map((e) => e.pos).join(" ")})`);
const c = V.compile("t * (42 & t >> 10)");
ok(c.ok && c.fn(1 << 13, 1) === ((Math.imul(1 << 13, 42 & (1 << 13) >>> 10) >>> 0) & 255) && c.stock === -1, "VM: a formula of one's own compiles and runs");
const p = V.compile("-t & 4095u ? t < 5 : !t || a == 3 && t % 0 == 0 ? t / 0 : 7");
ok(p.ok && p.fn(10, 3) === 0 && p.fn(4096, 3) === 0 && p.fn(4096, 2) === 7, "VM: unary, ?:, && || precedence, / and % by 0 (0), u suffix");
ok(V.compile("t*((t>>12|t>>8)&63&t>>4)").stock === 33 && V.compile(" ( t * ( (t >> 12 | t >> 8) & 63 & t >> 4 ) ) ").stock === 33,
"VM: one of the firmware's formulas recognised however it is spaced (B34: sendable)");
}
/* ---- the 48 BYTE formulas, bit for bit */
{
let src = null;
if (process.env.FIRMWARE_SRC) {
try {
const s = fs.readFileSync(process.env.FIRMWARE_SRC, "utf8");
const body = s.slice(s.indexOf("static __attribute__((noinline)) uint32_t lofi_byte("), s.indexOf("/* (JIANT 0.5.1; 0.5.6 a floatbeat"));
const c = `#include <stdint.h>\n#include <stdio.h>\n${body.replace("__attribute__((noinline))", "")}\nint main(void){for(uint32_t f=0;f<48;f++){uint32_t h=2166136261u;for(uint32_t a=1;a<=16;a+=5)for(uint32_t i=0;i<4000;i++){uint32_t t=i<2000?i*37u:i*2654435761u+f;h=(h^(lofi_byte(f,t,a)&255u))*16777619u;}printf("%u\\n",h);}return 0;}`;
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || "/tmp", "mathc-"));
fs.writeFileSync(path.join(dir, "lb.c"), c);
execFileSync("cc", ["-O1", "-w", "-o", path.join(dir, "lb"), path.join(dir, "lb.c")]);
src = execFileSync(path.join(dir, "lb"), { encoding: "utf8" }).trim().split("\n").map(Number);
} catch (e) { console.log("(FIRMWARE_SRC: not compiled: " + e.message.split("\n")[0] + ")"); }
}
const ref = src || BYTE_HASH, bad = [];
X.MATH_BYTE.forEach((f, k) => {
const c = X.MathVM.compile(f);
let h = 2166136261;
for (let a = 1; a <= 16; a += 5) for (let i = 0; i < 4000; i++) h = fnv(h, c.fn(SAMPLE_T(i, k), a));
if (!c.ok || c.stock !== k || h !== ref[k]) bad.push(k + 1);
});
ok(!bad.length, `VM: the 48 BYTE formulas == the firmware's lofi_byte, 768000 samples (${src ? "compiled from FIRMWARE_SRC" : "V10.8.74's hashes"})${bad.length ? " B" + bad : ""}`);
let h = 2166136261;
for (let v = 0; v < 128; v++) for (let i = 0; i < 500; i++) h = fnv(h, X.mathMut((Math.imul(i, 2654435761) + v) >>> 0, v));
for (let m = 0; m < 256; m++) h = fnv(h, X.mathMotion(m));
ok(h === MUT_HASH, "VM: VARIANT's mutation (lofi_mut, 64000 values) and MOTION's speed (lofi_motion) == the firmware's");
ok(X.MATH_FLOAT.length === 48 && X.MATH_FLOAT.every(([d, c]) => c.includes("return")), "the 48 FLOAT formulas listed with their source");
}
/* ---- the proposal's bytecode, the generator */
{
const gen = Array.from({ length: 40 }, (_, k) => X.mathGenerate(k + 1));
let bad = 0, maxLen = 0, maxSt = 0;
for (const f of X.MATH_BYTE.concat(gen)) {
const c = X.MathVM.compile(f), r = X.MathVM.rpn(f);
maxLen = Math.max(maxLen, r.code.length); maxSt = Math.max(maxSt, r.stack);
if (r.code.some((b) => b > 127)) bad++;
for (let i = 0; i < 2000; i++) for (const a of [1, 9, 16]) { const t = Math.imul(i, 2654435761) >>> 0; if (c.fn(t, a) !== X.MathVM.run(r.code, t, a)) bad++; }
}
ok(!bad, `bytecode (the proposal): 7-bit bytes, the same samples as the VM for 88 formulas (at most ${maxLen} bytes, stack ${maxSt})`);
ok(X.mathGenerate(7) === X.mathGenerate(7) && new Set(gen).size >= 36, `generator: a seed is one formula, 40 seeds ${new Set(gen).size} formulas`);
const moving = gen.filter((f) => { const c = X.MathVM.compile(f); return c.ok && X.mathScore(c.fn, 5) > 0; }).length;
ok(moving >= 36, `generator: every formula valid, ${moving} of 40 changing over time without being noise`);
console.log(" e.g. seed 1: " + gen[0] + "\n seed 2: " + gen[1]);
}
/* ---- the model against the emulator */
const WASM = process.env.EMU_WASM || path.join(HERE, "..", "build", "emu", "felucca.wasm");
if (fs.existsSync(WASM)) {
const mod = await WebAssembly.compile(fs.readFileSync(WASM));
const fresh = async () => (await WebAssembly.instantiate(mod, {})).exports;
const corr = (a, b, lag) => { let ab = 0, aa = 0, bb = 0; for (let i = 11025; i < a.length - 500; i++) { const x = a[i], y = b[i + lag]; ab += x * y; aa += x * x; bb += y * y; } return { r: ab / Math.sqrt(aa * bb + 1e-12), e: bb / (a.length - 11525) }; };
for (const motion of [0, 64]) {
const rs = [];
let silent = 0;
for (let f = 0; f < 48; f++) {
const o = { f, note: 60, chip: 2, var: 0, motion, wave: 5, secs: 1.2, gate: 1.2, dry: true };
const w = X.mathEmuRender(await fresh(), o).l, js = X.mathRenderByte({ ...o, fn: X.MathVM.compile(X.MATH_BYTE[f]).fn });
let best = -1, en = 0;
for (let lag = -8; lag <= 8; lag++) { const c = corr(js, w, lag); if (c.r > best) best = c.r; en = c.e; }
if (en < 1e-6) { silent++; continue; }
rs.push(best);
}
rs.sort((a, b) => a - b);
const med = rs[rs.length >> 1];
ok(med > 0.85, `model vs emulator (C4, MOTION ${motion}, 8BIT, VAR 0, dry): ${rs.length} formulas sounding, correlation median ${med.toFixed(3)}, ` +
`${rs.filter((x) => x > 0.9).length} over 0.9, lowest ${rs[0].toFixed(2)}${silent ? ` (${silent} silent in their first second)` : ""}`);
}
const ex = await fresh(), o = { wave: 5, f: 47, chip: 1, var: 77, motion: 200, grit: 9, bend: 33, loop: 66, note: 48, secs: 0.5 };
const r = X.mathEmuRender(ex, o);
const back = (k) => { const q = [31, 0, 115 + k]; new Uint8Array(ex.memory.buffer, ex.web_ed_buf(), 3).set(q); const n = ex.web_ed(3); const a = new Uint8Array(ex.memory.buffer, ex.web_ed_reply(), n); return (a[2] | a[3] << 7) - 8192; };
const want = X.mathValues(o), got = want.map((_, k) => back(k));
ok(got.join() === want.join() && r.l.some((x) => Math.abs(x) > 1e-3), `the emulator takes a send's eight values (ALGO 188 = B48, MOTION 200: SYNC) and sounds: ${got.join(" ")}`);
} else console.log(`model vs emulator: no ${WASM} (EMU_WASM=...)`.padEnd(96) + " skip");
console.log(fails ? `MATH TESTS FAILED (${fails})` : "math tests passed");
process.exit(fails ? 1 : 0);