mirror of
https://github.com/juanjiant-bit/JIANT.git
synced 2026-12-05 20:34:27 +01:00
mathGenerate in the editor's MATH section (which JIANT Studio also loads from the published editor page) now builds
formulas by family and by CHAOS, and checks every one against the device (V10.8.75 MATH USER).
- MATH_FAMILIES, each with an id and EN/ES/JA labels: sierpinski (classic bit patterns, xor), melodic (scales as
string tables, plucks, sine echoes, arpeggios, hex nibble tables), fm (FIX: sin(w) phase modulation, index
envelopes, stepped carriers, harmonic stacks, ring), glitch (stutters, random grains, reversed and modulo-chopped
t, bit-crush), drone (FIX: detuned saws and sines, slow LFO phase modulation, beating chords; a detuned INT pair),
rhythm (a falling-pitch sine kick, hashed-noise hats and snares, pattern masks, toms), chip (pulses and PWM, fast
arpeggios, triangle bass, noise).
- mathGenerate(seed, {family, chaos}) -> {src, fix, wave (5 INT / 6 FIX), family, chaos, bytes, stack}; one
(seed, family, chaos) is one formula; "any" takes the seed's family whatever the CHAOS. mathGenerate(seed) is the
old call: a text, the seed's family at CHAOS 40. mathGenerate.FAMILIES too, for Studio's loader.
- CHAOS changes the build: at 0, one of the family's shapes with musical numbers; above, odd numbers and more rewrites
(each kept only while the formula still fits 64 bytes and sounds): a gate or a second voice (15), the family's own
idioms: t bent, crush, xor, phase modulation, octave jumps, vibrato, swing, layers (30); modulo, waveshapers,
switching to another formula, other families mixed in, odd constants (55); t replaced by a whole formula, every t
bent, formulas multiplied, other families' idioms (80).
- Every formula: FVM compiles it, at most 64 B and a stack of 12, no ph lp hp eu nor FUNC calls, only t w a n v; heard
with FVM.run in four windows (sounding, not stuck at full-scale DC, not white noise, changing); else the next try.
- The MATH tab: a Family selector (Any and the seven) and a Chaos slider (0..100) by Generate formula, EN/ES/JA,
40 px touch targets; the status names the family and the CHAOS. A FIX result is shown as FIX -> FLOAT and sent on
WAVE 6, as one's own FIX formulas are.
- math_test.mjs: 1056 formulas (7 families and any x CHAOS 0..100 x 12 seeds) all valid, 0 silent; determinism;
variety (10 seeds a family at CHAOS 50, eleven audio features: every family's median pair distance 4.0..6.1x a
formula's distance from itself 4 s later, 76..98% of pairs past that one's 90th percentile, high-passed waveform
correlation at most 0.43); families apart (nearest family centroid right for 48/70 at CHAOS 0, 37/70 at 50, chance
10/70; 26/70 at 90, the families mixed); CHAOS 0 -> 100 terms 1.5..3.9x and nesting 3..6 levels deeper; the old
call as Studio loads it; with EMU_WASM, 28 generated formulas sent to the V10.8.75 emulator: all taken and heard.
- editor_browser_test.mjs: the family and CHAOS controls (FM 80: FIX, RHYTHM 0: INT, seeded), the slider's height on
a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
322 lines
26 KiB
JavaScript
322 lines
26 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: its families and CHAOS; 1000 and more formulas all the device's (compiled, 64 B, a stack of 12, none of
|
|
// the calls it lacks); seeded; 10 seeds a family heard and measured apart, the families apart; CHAOS deepening the
|
|
// build; the old call (a text) as before, as JIANT Studio loads it
|
|
// - (V10.8.75) MATH USER: FVM, the port of JIANT BYTE's compiler, against BYTE's own (web/math_fvm_gold.json: 142 texts
|
|
// compiled by BYTE's fvm_compile, serialized, run by its fvm_run): the same bytes for every one, the same values from
|
|
// FVM.run (JIANT FM's math_user.c) at three a's; the refused ones refused; pack7 both ways; given EMU_WASM, a formula sent with FORMULA (100) to the emulator plays and reads back
|
|
// - 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, FVM, mathMut, mathMotion, mathGenerate, mathScore, mathRenderByte, mathEmuRender, mathValues, MATH_FAMILIES, mathGenHear };")();
|
|
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 device's 48 and the generator's formulas the old VM's grammar has) */
|
|
{
|
|
const gen = Array.from({ length: 40 }, (_, k) => X.mathGenerate(k + 1)).filter((f) => X.MathVM.compile(f).ok);
|
|
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 ${48 + gen.length} formulas (at most ${maxLen} bytes, stack ${maxSt})`);
|
|
}
|
|
/* ---- (V10.8.75) MATH USER: the port of BYTE's compiler against BYTE's */
|
|
{
|
|
const G = JSON.parse(fs.readFileSync(path.join(HERE, "math_fvm_gold.json"), "utf8"));
|
|
let same = 0, bad = [], vals = 0, refused = 0;
|
|
for (const x of G) {
|
|
const c = X.FVM.compile(x.src);
|
|
if (!x.code || x.code.length > 64) { if (c.ok) bad.push(x.src); else refused++; continue; }
|
|
if (!c.ok || c.code.join() !== x.code.join()) { bad.push(x.src); continue; }
|
|
same++;
|
|
let k = 0;
|
|
for (; k < 3; k++) {
|
|
let h = 2166136261;
|
|
const a = [1, 7, 16][k];
|
|
for (let i = 0; i < 4160; i++) {
|
|
const t = i < 4096 ? Math.imul(i, k + 1) >>> 0 : X.FVM.hash((Math.imul(i, 7919) + k) >>> 0);
|
|
h = fnv(h, X.FVM.run(c.code, t, Math.imul(t, 2654435761) >>> 0, a));
|
|
}
|
|
if (h !== x.hash[k]) break;
|
|
}
|
|
if (k === 3) vals++;
|
|
}
|
|
ok(!bad.length && same >= 135, `FVM: JIANT BYTE's fvm_compile's bytes for ${same} formulas (93 of BYTE's 96 factory, every operator)${bad.length ? " NOT: " + bad.slice(0, 3).join(" | ") : ""}`);
|
|
ok(vals === same, `FVM.run: BYTE's fvm_run's values for all ${vals} (3 x 4160 each)`);
|
|
ok(refused >= 7, `FVM: BYTE's ph() lp() eu() and the ones over 64 bytes refused (${refused})`);
|
|
const e1 = X.FVM.compile("t * (42 & t >> 10"), e2 = X.FVM.compile("t + q"), e3 = X.FVM.compile("lp(sin(w), 0.5)");
|
|
ok(!e1.ok && e1.pos === 17 && !e2.ok && e2.pos === 4 && !e3.ok, `FVM: errors say what and where (${e1.error} ${e1.pos}, ${e2.error} ${e2.pos}, ${e3.error})`);
|
|
const p = Array.from({ length: 64 }, (_, i) => (i * 37 + 5) & 255);
|
|
ok(X.FVM.unpack7(X.FVM.pack7(p)).join() === p.join() && X.FVM.pack7(p).every((b) => b < 128), "pack7: 64 bytes there and back, every byte 7-bit");
|
|
}
|
|
/* ---- the generator (the owner: "poco versátiles, cambios muy suaves"): families, CHAOS, every formula the device's */
|
|
const SHAPE = (s) => { /* a text's terms (numbers, names, operators) and its nesting */
|
|
const tk = s.replace(/"[^"]*"/g, "S").match(/0x[0-9a-fA-F]+|\d+\.\d+|\d+|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|&&|\|\||[-+*/%&|^~!<>?:()[\],]/g) || [];
|
|
let d = 0, depth = 0, nodes = 0;
|
|
for (const k of tk) { if (k === "(" || k === "[") depth = Math.max(depth, ++d); else if (k === ")" || k === "]") d--; else if (k !== "," && k !== ":") nodes++; }
|
|
return { nodes, depth };
|
|
};
|
|
/* heard as the device's VM plays it at C4 (t at 8 kHz, w = t << 11 the phase), 4 s from t0, a 5 -> -1 .. 1 */
|
|
const GSR = 8000, GN = GSR * 4;
|
|
function genRender(src, t0 = 0, a = 5) {
|
|
const c = X.FVM.compile(src), code = c.code, x = new Float32Array(GN);
|
|
for (let i = 0; i < GN; i++) { const t = t0 + i; x[i] = c.fix ? X.FVM.sample(code, X.FVM.run(code, t, (t << 11) >>> 0, a)) / 32768 : ((X.FVM.run(code, t, 0, a) & 255) - 127.5) / 128; }
|
|
return x;
|
|
}
|
|
function fft(re, im) {
|
|
const n = re.length;
|
|
for (let i = 1, j = 0; i < n; i++) { let b = n >> 1; for (; j & b; b >>= 1) j ^= b; j ^= b; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } }
|
|
for (let len = 2; len <= n; len <<= 1) {
|
|
const ang = -2 * Math.PI / len, wr = Math.cos(ang), wi = Math.sin(ang);
|
|
for (let i = 0; i < n; i += len) for (let k = 0, cr = 1, ci = 0; k < len / 2; k++) {
|
|
const h = i + k + len / 2, vr = re[h] * cr - im[h] * ci, vi = re[h] * ci + im[h] * cr;
|
|
re[h] = re[i + k] - vr; im[h] = im[i + k] - vi; re[i + k] += vr; im[i + k] += vi;
|
|
const nr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = nr;
|
|
}
|
|
}
|
|
}
|
|
/* eleven numbers a sound: its level, zero crossings, spectral centroid, flatness, flux and roll-off (512-sample frames),
|
|
its envelope's spread and rhythm (the frames' levels' autocorrelation, 128 ms .. 2 s), its pitch (the wave's
|
|
autocorrelation, lags 8 .. 600), crest, and the entropy of its levels */
|
|
function genFeatures(x) {
|
|
const n = x.length; let m = 0; for (const v of x) m += v; m /= n;
|
|
const y = Float64Array.from(x, (v) => v - m);
|
|
let s2 = 0, z = 0, pk = 0;
|
|
for (let i = 0; i < n; i++) { s2 += y[i] * y[i]; pk = Math.max(pk, Math.abs(y[i])); if (i && (y[i] > 0) !== (y[i - 1] > 0)) z++; }
|
|
const rms = Math.sqrt(s2 / n) + 1e-6, F = 512, env = [];
|
|
let cen = 0, flat = 0, flux = 0, roll = 0, nf = 0, prev = null;
|
|
for (let o = 0; o + F <= n; o += F) {
|
|
const re = new Float64Array(F), im = new Float64Array(F); let e = 0;
|
|
for (let i = 0; i < F; i++) { re[i] = y[o + i] * (0.5 - 0.5 * Math.cos(2 * Math.PI * i / F)); e += y[o + i] ** 2; }
|
|
env.push(Math.sqrt(e / F));
|
|
fft(re, im);
|
|
const mag = new Float64Array(F / 2); let tot = 0, ws = 0, lg = 0;
|
|
for (let k = 1; k < F / 2; k++) { mag[k] = Math.hypot(re[k], im[k]); tot += mag[k]; ws += k * mag[k]; lg += Math.log(mag[k] + 1e-9); }
|
|
if (tot < 1e-6) continue;
|
|
cen += ws / tot / (F / 2); flat += Math.log(Math.exp(lg / (F / 2 - 1)) / (tot / (F / 2 - 1)) + 1e-6);
|
|
let acc = 0, k85 = 1; for (let k = 1; k < F / 2; k++) { acc += mag[k]; if (acc < 0.85 * tot) k85 = k; }
|
|
roll += k85 / (F / 2);
|
|
const nm = mag.map((v) => v / tot);
|
|
if (prev) { let d = 0; for (let k = 1; k < F / 2; k++) d += Math.abs(nm[k] - prev[k]); flux += d; }
|
|
prev = nm; nf++;
|
|
}
|
|
nf = nf || 1;
|
|
const em = env.reduce((a, b) => a + b, 0) / env.length, ec = env.map((v) => v - em), e0 = ec.reduce((a, b) => a + b * b, 0) + 1e-9;
|
|
let rh = 0, best = 0, w0 = 0;
|
|
for (let lag = 2; lag <= 32; lag++) { let s = 0; for (let i = 0; i + lag < ec.length; i++) s += ec[i] * ec[i + lag]; rh = Math.max(rh, s / e0); }
|
|
for (let i = 0; i < 4096; i++) w0 += y[4000 + i] ** 2;
|
|
for (let lag = 8; lag <= 600; lag++) { let s = 0; for (let i = 0; i < 4096; i++) s += y[4000 + i] * y[4000 + i + lag]; best = Math.max(best, s / (w0 + 1e-9)); }
|
|
const hist = new Float64Array(64); for (const v of x) hist[Math.max(0, Math.min(63, Math.floor((v + 1) * 32)))]++;
|
|
let ent = 0; for (const h of hist) if (h) ent -= h / n * Math.log2(h / n);
|
|
return [Math.log(rms), z / n, cen / nf, flat / nf, flux / nf, roll / nf, Math.sqrt(ec.reduce((a, b) => a + b * b, 0) / ec.length) / (em + 1e-6), rh, best, pk / rms, ent];
|
|
}
|
|
/* the waves' likeness: the best |normalized correlation| within +-16 samples, high-passed (~40 Hz: the bars' and the
|
|
envelopes' slow shapes, which bytebeats share, left out) */
|
|
function genCorr(x0, y0) {
|
|
const hp = (x) => { const o = new Float32Array(x.length); let px = 0, py = 0; for (let i = 0; i < x.length; i++) { py = 0.97 * (py + x[i] - px); px = x[i]; o[i] = py; } return o; };
|
|
const x = hp(x0), y = hp(y0); let best = 0;
|
|
for (let lag = -16; lag <= 16; lag++) { let ab = 0, aa = 0, bb = 0; for (let i = 16; i < x.length - 16; i++) { ab += x[i] * y[i + lag]; aa += x[i] * x[i]; bb += y[i + lag] ** 2; } best = Math.max(best, Math.abs(ab) / Math.sqrt(aa * bb + 1e-12)); }
|
|
return best;
|
|
}
|
|
const quant = (a, q) => { const s = [...a].sort((p, r) => p - r); return s[Math.min(s.length - 1, Math.floor(q * s.length))]; };
|
|
{
|
|
const FAM = X.MATH_FAMILIES.map((f) => f.id);
|
|
ok(FAM.length >= 6 && X.MATH_FAMILIES.every((f) => f.id && f.en && f.es && f.ja && typeof f.fix === "boolean") && X.mathGenerate.FAMILIES === X.MATH_FAMILIES,
|
|
`generator: ${FAM.length} families (${FAM.join(" ")}), labelled EN/ES/JA, also as mathGenerate.FAMILIES`);
|
|
/* 1. 1000 and more: every family and "any", CHAOS 0 .. 100 by 10, 12 seeds each */
|
|
let n = 0, bad = [], quiet = 0, maxB = 0, maxS = 0, fixes = 0, ms = Date.now();
|
|
for (const fam of [...FAM, "any"]) for (let ch = 0; ch <= 100; ch += 10) for (let s = 1; s <= 12; s++) {
|
|
const seed = Math.imul(s, 7919) + ch, g = X.mathGenerate(seed, { family: fam, chaos: ch }), c = X.FVM.compile(g.src);
|
|
n++;
|
|
const names = g.src.replace(/"[^"]*"/g, "").match(/\b[A-Za-z_]\w*\b/g) || [];
|
|
if (!c.ok || c.code.length > 64 || c.depth > 12 || /\b(ph|lp|hp|eu|note|chord|kick|snare|hat)\s*\(/.test(g.src) ||
|
|
names.some((x) => !/^(t|w|a|n|v|sin|cos|tri|saw|sqr|abs|min|max|floor|int|fix|rnd|sat|clip)$/.test(x) && !/^0x/i.test(x)) ||
|
|
c.fix !== g.fix || g.wave !== (g.fix ? 6 : 5) || g.bytes !== c.code.length || (fam !== "any" && g.family !== fam) || g.chaos !== ch) { bad.push(`${fam} ${ch} ${seed}: ${g.src}`); continue; }
|
|
maxB = Math.max(maxB, c.code.length); maxS = Math.max(maxS, c.depth); fixes += g.fix;
|
|
const h = X.mathGenHear(c.code);
|
|
if (h.loud < 3 || h.dc >= 0.85) quiet++;
|
|
}
|
|
ok(!bad.length && n >= 1000, `generator: ${n} formulas (8 x CHAOS 0..100 x 12 seeds) compile, at most ${maxB} B and a stack of ${maxS}, no ph lp hp eu nor FUNC, only t w a n v; ${fixes} FIX (WAVE 6), the rest INT (WAVE 5) (${((Date.now() - ms) / n).toFixed(0)} ms each)${bad.length ? "\n NOT: " + bad.slice(0, 3).join("\n ") : ""}`);
|
|
ok(quiet <= n * 0.02, `generator: silent or stuck (full-scale DC) in at most 2%: ${quiet} of ${n}`);
|
|
/* 2. determinism */
|
|
const a1 = X.mathGenerate(4242, { family: "glitch", chaos: 73 }), a2 = X.mathGenerate(4242, { family: "glitch", chaos: 73 });
|
|
const anyFam = [0, 30, 60, 100].map((ch) => X.mathGenerate(99, { chaos: ch }).family);
|
|
ok(JSON.stringify(a1) === JSON.stringify(a2) && X.mathGenerate(7, { family: "fm", chaos: 50 }).src !== X.mathGenerate(7, { family: "fm", chaos: 51 }).src &&
|
|
X.mathGenerate(7, { family: "fm", chaos: 50 }).src !== X.mathGenerate(8, { family: "fm", chaos: 50 }).src && new Set(anyFam).size === 1,
|
|
`generator: one (seed, family, CHAOS) is one formula; another CHAOS or seed another; "any" takes the seed's family whatever the CHAOS (${anyFam[0]})`);
|
|
/* 3. variety: 10 seeds a family at CHAOS 50 (and at 0, 90), heard 4 s, eleven features z-scored over the 70 */
|
|
const sep = {};
|
|
for (const ch of [0, 50, 90]) {
|
|
const rows = [], lab = [], waves = [], self = [], srcs = [];
|
|
for (const f of FAM) for (let s = 1; s <= 10; s++) {
|
|
const src = X.mathGenerate(s, { family: f, chaos: ch }).src, w = genRender(src);
|
|
srcs.push(src); waves.push(w); rows.push(genFeatures(w)); lab.push(f);
|
|
if (ch === 50) self.push(genFeatures(genRender(src, GN))); /* (the same formula, its next 4 s) */
|
|
}
|
|
const D = rows[0].length, mu = [], sd = [];
|
|
for (let k = 0; k < D; k++) { const c = rows.map((r) => r[k]); mu[k] = c.reduce((p, q) => p + q) / c.length; sd[k] = Math.sqrt(c.reduce((p, q) => p + (q - mu[k]) ** 2, 0) / c.length) || 1; }
|
|
const dist = (p, q) => Math.sqrt(p.reduce((s, v, k) => s + ((v - q[k]) / sd[k]) ** 2, 0) / D);
|
|
/* families apart: each sound's nearest family centroid (itself left out) is its own */
|
|
let hit = 0;
|
|
rows.forEach((p, i) => {
|
|
let bf = null, bd = 1e9;
|
|
for (const f of FAM) { const m = rows.filter((_, j) => j !== i && lab[j] === f), c = p.map((_, k) => m.reduce((s, r) => s + r[k], 0) / m.length), d = dist(p, c); if (d < bd) { bd = d; bf = f; } }
|
|
if (bf === lab[i]) hit++;
|
|
});
|
|
sep[ch] = hit;
|
|
if (ch !== 50) continue;
|
|
const sd0 = rows.map((r, i) => dist(r, self[i])), selfMed = quant(sd0, 0.5), selfP90 = quant(sd0, 0.9), lines = [];
|
|
let worst = 1, allOk = true;
|
|
for (const f of FAM) {
|
|
const ix = lab.map((l, i) => (l === f ? i : -1)).filter((i) => i >= 0), d = [], cc = [];
|
|
for (let p = 0; p < ix.length; p++) for (let q = p + 1; q < ix.length; q++) { d.push(dist(rows[ix[p]], rows[ix[q]])); cc.push(genCorr(waves[ix[p]], waves[ix[q]])); }
|
|
const above = d.filter((x) => x > selfP90).length / d.length, med = quant(d, 0.5), cmax = Math.max(...cc), texts = new Set(ix.map((i) => srcs[i])).size;
|
|
worst = Math.min(worst, above);
|
|
const fine = texts === 10 && cmax < 0.6 && above >= 2 / 3 && med >= 3 * selfMed;
|
|
allOk = allOk && fine;
|
|
lines.push(` ${f.padEnd(11)} distance median ${med.toFixed(2)} (${(med / selfMed).toFixed(1)}x itself), ${Math.round(above * 100)}% of pairs past itself's p90, waves' correlation at most ${cmax.toFixed(2)}${fine ? "" : " <-"}`);
|
|
}
|
|
ok(allOk, `generator, variety: 10 seeds a family at CHAOS 50, all 45 pairs a family: 10 texts, the waves' correlation under 0.6, the features' distance\n (z-scored) at its median 3x or more a formula's from itself 4 s later (${selfMed.toFixed(2)}), 2/3 of the pairs past that one's 90th percentile (${selfP90.toFixed(2)})\n${lines.join("\n")}`);
|
|
}
|
|
/* (chance: 1 in 7, 10 of 70) */
|
|
ok(sep[0] >= 40 && sep[50] >= 30, `generator, families apart: the nearest family centroid is its own for ${sep[0]} of 70 at CHAOS 0 (40: 4x chance), ${sep[50]} at 50 (30: 3x chance); at 90, the families mixed: ${sep[90]}`);
|
|
/* 4. CHAOS changes the build: terms and nesting, 20 seeds a family */
|
|
const lines = []; let grows = true;
|
|
for (const f of FAM) {
|
|
const at = (ch) => { let nd = 0, dp = 0; for (let s = 1; s <= 20; s++) { const q = SHAPE(X.mathGenerate(s, { family: f, chaos: ch }).src); nd += q.nodes / 20; dp += q.depth / 20; } return { nd, dp }; };
|
|
const z = at(0), m = at(50), h = at(100);
|
|
const g = h.nd >= 1.5 * z.nd && h.dp >= z.dp + 2 && m.nd > z.nd && h.nd >= m.nd * 0.95;
|
|
grows = grows && g;
|
|
lines.push(` ${f.padEnd(11)} terms ${z.nd.toFixed(1)} -> ${m.nd.toFixed(1)} -> ${h.nd.toFixed(1)}, nesting ${z.dp.toFixed(1)} -> ${m.dp.toFixed(1)} -> ${h.dp.toFixed(1)}${g ? "" : " <-"}`);
|
|
}
|
|
ok(grows, `generator, CHAOS 0 -> 50 -> 100 (20 seeds a family, means): the terms 1.5x or more, the nesting 2 levels deeper\n${lines.join("\n")}`);
|
|
/* 5. the old call: a text, a family from the seed at CHAOS 40, as JIANT Studio calls it (its mathLib's own loading) */
|
|
const old = Array.from({ length: 40 }, (_, k) => X.mathGenerate(k + 1));
|
|
const S = new Function(core + "; return { FVM, MathVM, mathGenerate };")(), st = S.mathGenerate(12345), sc = S.FVM.compile(st);
|
|
ok(old.every((s, k) => typeof s === "string" && s === X.mathGenerate(k + 1, { chaos: 40 }).src && X.FVM.compile(s).ok) && new Set(old).size === 40 &&
|
|
new Set(old.map((s, k) => X.mathGenerate(k + 1, { chaos: 40 }).family)).size >= 6 && typeof st === "string" && sc.ok && S.mathGenerate.FAMILIES.length === FAM.length &&
|
|
String(X.mathGenerate(3, { family: "drone", chaos: 10 })) === X.mathGenerate(3, { family: "drone", chaos: 10 }).src,
|
|
`generator, the old call mathGenerate(seed): a text (40 seeds, 40 formulas, ${new Set(old.map((s, k) => X.mathGenerate(k + 1, { chaos: 40 }).family)).size} families), as Studio loads it too (FAMILIES on it)`);
|
|
console.log(` e.g. ${FAM.map((f) => `${f} 0: ${X.mathGenerate(1, { family: f, chaos: 0 }).src}\n ${f} 90: ${X.mathGenerate(1, { family: f, chaos: 90 }).src}`).join("\n e.g. ")}`);
|
|
}
|
|
/* ---- 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(" ")}`);
|
|
{ /* (V10.8.75) a formula of one's own: FORMULA (100) to the emulator, ALGO USER: it plays; B01's text as USER: B01's samples */
|
|
const ex2 = await fresh(), b01 = X.FVM.compile(X.MATH_BYTE[0]).code;
|
|
const o2 = { wave: 5, f: 0, chip: 2, var: 0, motion: 0, note: 60, secs: 0.6, dry: true };
|
|
const u = X.mathEmuRender(ex2, { ...o2, user: true, code: b01 }), s0 = X.mathEmuRender(await fresh(), o2);
|
|
if (!u.formula) console.log("MATH USER on the emulator: its firmware has no FORMULA (before V10.8.75)".padEnd(96) + " skip");
|
|
else {
|
|
let d = 0; for (let i = 0; i < u.l.length; i++) d = Math.max(d, Math.abs(u.l[i] - s0.l[i]));
|
|
ok(d === 0, `MATH USER on the emulator: B01's bytecode at ALGO USER plays B01's samples, bit for bit (C4: under the 11 kHz cap)`);
|
|
const q = [100, 0, 0]; new Uint8Array(ex2.memory.buffer, ex2.web_ed_buf(), 3).set(q);
|
|
const n = ex2.web_ed(3), a = Array.from(new Uint8Array(ex2.memory.buffer, ex2.web_ed_reply(), n));
|
|
ok(a[1] === 0 && a[2] === b01.length && X.FVM.unpack7(a.slice(3)).slice(0, a[2]).join() === b01.join(), `FORMULA 0 0: the formula read back (${a[2]} B)`);
|
|
const f20 = X.FVM.compile(X.MATH_FLOAT[19][0] === "odd partials, built up" ? "(sin(w)+((t>>11&3)>0?sin(w*3)/3:0.)+((t>>11&3)>1?sin(w*5)/5:0.)+((t>>11&3)>2?sin(w*7)/7:0.))*3/4" : "sin(w)");
|
|
const uf = X.mathEmuRender(await fresh(), { ...o2, wave: 6, user: true, code: f20.code });
|
|
ok(f20.ok && f20.fix && uf.formula && uf.l.some((x) => Math.abs(x) > 1e-3), `MATH USER, FIX on WAVE FLOAT (F20's text in BYTE's FIX, ${f20.code && f20.code.length} B): it sounds`);
|
|
/* the generator's formulas on the emulator: each family at CHAOS 20 and 90, two seeds, sent as the editor sends them
|
|
(FORMULA, ALGO USER, the WAVE the generator says): taken and heard */
|
|
const res = [];
|
|
for (const f of X.MATH_FAMILIES) for (const chaos of [20, 90]) for (const seed of [1, 2]) {
|
|
const g = X.mathGenerate(seed, { family: f.id, chaos }), code = X.FVM.compile(g.src).code;
|
|
const e = X.mathEmuRender(await fresh(), { ...o2, wave: g.wave, user: true, code, secs: 1.5, gate: 1.5 });
|
|
let pk = 0; for (let i = 4410; i < e.l.length; i++) pk = Math.max(pk, Math.abs(e.l[i]));
|
|
res.push({ f: f.id, chaos, seed, ok: e.formula, pk });
|
|
}
|
|
const heard = res.filter((x) => x.ok && x.pk > 2e-3).length;
|
|
ok(res.every((x) => x.ok) && heard >= res.length - 2, `MATH USER: the generator's formulas on the emulator (7 families x CHAOS 20, 90 x 2 seeds): ${res.filter((x) => x.ok).length} of ${res.length} taken, ${heard} heard${res.filter((x) => !(x.ok && x.pk > 2e-3)).map((x) => ` (quiet: ${x.f} ${x.chaos} ${x.seed})`).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);
|