Ring decoder: local tone split, sharpened crop, frame accumulation, crop scanner

This commit is contained in:
2026-08-16 19:22:24 +01:00
parent 418e7667e5
commit 05cfa36e5b
5 changed files with 265 additions and 26 deletions
+140 -21
View File
@@ -54,11 +54,12 @@ export function rsEncode(msg) {
} }
// port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2) // port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2)
export function rsDecode(cw) { // the whole corrected codeword, or null
function rsFix(cw) {
const n = cw.length; const n = cw.length;
const synd = [0]; const synd = [0];
for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i))); for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i)));
if (Math.max(...synd) === 0) return cw.slice(0, n - NSYM); if (Math.max(...synd) === 0) return cw;
let errLoc = [1], oldLoc = [1]; let errLoc = [1], oldLoc = [1];
for (let i = 0; i < NSYM; i++) { for (let i = 0; i < NSYM; i++) {
const K = i + 1; const K = i + 1;
@@ -100,7 +101,12 @@ export function rsDecode(cw) {
}); });
const fixed = cw.map((c, i) => c ^ E[i]); const fixed = cw.map((c, i) => c ^ E[i]);
for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null; for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null;
return fixed.slice(0, n - NSYM); return fixed;
}
export function rsDecode(cw) {
const fixed = rsFix(cw);
return fixed && fixed.slice(0, cw.length - NSYM);
} }
export function whitening(n) { export function whitening(n) {
@@ -588,7 +594,7 @@ function ringDips(img, cand, span) {
return rings; return rings;
} }
// projective map code space -> image from the two conics, or null // projective map code space -> image coordinates from the two conics, or null
export let lastProjective = null; export let lastProjective = null;
function projective(img, cand) { function projective(img, cand) {
const span = cand.span || 200, disc = discEdge(img, cand, 160), rings = ringDips(img, cand, span); const span = cand.span || 200, disc = discEdge(img, cand, 160), rings = ringDips(img, cand, span);
@@ -654,19 +660,94 @@ function projective(img, cand) {
return [X * sc + mx, Y * sc + my]; return [X * sc + mx, Y * sc + my];
}; };
lastProjective.map = map; lastProjective.map = map;
return (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); }; return map;
} }
// reads one candidate. returns { token, theta, score, scale } or { token: null, ... } or null. // unsharp mask on a small crop: undoes part of the camera blur and flattens slow brightness changes
// (rolling shutter bands, vignetting), which a washed-out projection can't afford
function sharpen(img, passes, amt) {
const { g, w, h } = img, b = Float32Array.from(g), tmp = new Float32Array(w * h);
for (let p = 0; p < passes; p++) {
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) tmp[i] = (b[x > 0 ? i - 1 : i] + 2 * b[i] + b[x < w - 1 ? i + 1 : i]) / 4;
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) b[i] = (tmp[y > 0 ? i - w : i] + 2 * tmp[i] + tmp[y < h - 1 ? i + w : i]) / 4;
}
for (let i = 0; i < b.length; i++) b[i] = g[i] + amt * (g[i] - b[i]);
return { g: b, w, h };
}
// sectors close to each other in code space, across rings: the local reference for dark vs light
const NEAR = (() => {
const pts = [];
RING_SECTORS.forEach((n, k) => { for (let j = 0; j < n; j++) { const a = sectorAngle(0, j, n); pts.push([RADII[k] * Math.sin(a), -RADII[k] * Math.cos(a)]); } });
return pts.map((p, i) => pts.map((_, m) => m).filter((m) => m !== i && Math.hypot(pts[m][0] - p[0], pts[m][1] - p[1]) < 0.5));
})();
// vals: brightness of the 120 sectors, sync ring first. two-means split against nearby sectors, seeded by the
// sync ring whose bits are known. returns data bits and soft values (> 0 dark, ~1 = a clean dash)
function classify(vals) {
const n = vals.length, known = SYNC_BITS.length;
let D = 0, L = 0, nd = 0;
for (let j = 0; j < known; j++) if (SYNC_BITS[j]) { D += vals[j]; nd++; } else L += vals[j];
D /= nd; L /= known - nd;
const swing = L - D;
if (!(swing > 0)) return null;
const bit = new Uint8Array(n), thr = new Float32Array(n).fill((D + L) / 2), half = new Float32Array(n).fill(swing / 2);
for (let i = 0; i < n; i++) bit[i] = i < known ? SYNC_BITS[i] : +(vals[i] < thr[i]);
for (let it = 0; it < 3; it++) {
for (let i = 0; i < n; i++) {
let sd = 0, cd = 0, sl = 0, cl = 0;
for (const m of NEAR[i]) if (bit[m]) { sd += vals[m]; cd++; } else { sl += vals[m]; cl++; }
if (cd < 2 || cl < 2) continue;
const d = sd / cd, l = sl / cl;
if (l - d > 0.35 * swing) { thr[i] = (d + l) / 2; half[i] = (l - d) / 2; }
}
for (let i = known; i < n; i++) bit[i] = +(vals[i] < thr[i]);
}
const soft = new Float32Array(n - known);
for (let i = known; i < n; i++) soft[i - known] = Math.max(-2, Math.min(2, (thr[i] - vals[i]) / half[i]));
return { bits: Array.from(bit.subarray(known)), soft };
}
// bits -> token, or null. soft tells how sure each bit was
function tokenOf(bits, soft, strict = true) {
const cw = bytesFromBits(bits), fixed = rsFix(cw);
if (!fixed) return null;
let bad = 0, flips = 0, shaky = 0, all = 0;
for (let i = 0; i < cw.length; i++) {
if (cw[i] === fixed[i]) continue;
bad++;
for (let k = 0; k < 8; k++) if (((cw[i] ^ fixed[i]) >> (7 - k)) & 1) { flips++; shaky += Math.abs(soft[i * 8 + k]); }
}
for (let i = 0; i < soft.length; i++) all += Math.abs(soft[i]);
// rs "repairs" 1 random word in 80000 at 3 byte errors. noise gets its confident bits flipped as often as
// the shaky ones, a real read only loses shaky ones
if (strict && bad >= 3 && shaky / flips > 0.7 * (all / soft.length)) return null;
return { token: tokenFromPayload(fixed.slice(0, fixed.length - NSYM)), fixes: bad };
}
// reads one candidate. returns { token, theta, score, scale, soft } or { token: null, ... } or null.
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames) // tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) { export function decodeAt(img, cand, opts = {}) {
const [a11, a12, a21, a22] = cand.A; const span = cand.span || 200, unit = Math.sqrt(Math.abs(cand.A[0] * cand.A[3] - cand.A[1] * cand.A[2]));
const affine = (x, y) => bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y); let tone = img, tc = cand;
const span = cand.span || 200; if (opts.sharpen !== false && unit < 70) {
const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean); // small code: work on a sharpened crop
const half = Math.ceil(unit * (DISC + 0.25)) + 4;
const x0 = Math.max(0, Math.round(cand.cx) - half), y0 = Math.max(0, Math.round(cand.cy) - half);
const x1 = Math.min(img.w, Math.round(cand.cx) + half + 1), y1 = Math.min(img.h, Math.round(cand.cy) + half + 1);
const w = x1 - x0, h = y1 - y0, g = new Float32Array(w * h);
for (let y = 0; y < h; y++) g.set(img.g.subarray((y0 + y) * img.w + x0, (y0 + y) * img.w + x1), y * w);
tone = sharpen({ g, w, h }, 6, 2);
tc = { ...cand, cx: cand.cx - x0, cy: cand.cy - y0 };
}
const [a11, a12, a21, a22] = tc.A;
// geometry comes from the plain image, tones from the sharpened one
const proj = opts.projective !== false && projective(img, cand);
const maps = [proj && ((x, y) => { const [u, v] = proj(x, y); return bilinear(tone, u - (cand.cx - tc.cx), v - (cand.cy - tc.cy)); }),
(x, y) => bilinear(tone, tc.cx + a11 * x + a12 * y, tc.cy + a21 * x + a22 * y)].filter(Boolean);
let best = null; let best = null;
for (const S0 of maps) { for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0, span)) || S0; const S = (opts.refine !== false && refine(S0, span * (tone === img ? 1 : 2))) || S0;
const r = readRings(S, { ...opts, span }); const r = readRings(S, { ...opts, span });
if (r && r.token) return r; if (r && r.token) return r;
if (r && (!best || r.score > best.score)) best = r; if (r && (!best || r.score > best.score)) best = r;
@@ -701,12 +782,13 @@ function readRings(S, opts) {
} }
} }
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise // weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
if (!best || best.score < minScore) return best ? { token: null, ...best } : null; if (!best || best.score < minScore) return best ? { token: null, ...best, vals: undefined } : null;
const dark = [], light = []; const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v)); best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length; const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
if (ml - md < Math.max(5, 0.055 * (opts.span || 200))) return { token: null, ...best }; const out = { ...best, vals: undefined, token: null };
const bits = []; if (ml - md < Math.max(5, 0.055 * (opts.span || 200))) return out;
const all = [...best.vals], otsu = [];
for (let k = 1; k < RING_SECTORS.length; k++) { for (let k = 1; k < RING_SECTORS.length; k++) {
// nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split // nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n; const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
@@ -718,11 +800,15 @@ function readRings(S, opts) {
const sp = split(vals); const sp = split(vals);
if (!pick || sp.quality > pick.quality) pick = { ...sp, vals }; if (!pick || sp.quality > pick.quality) pick = { ...sp, vals };
} }
if (!pick) return { token: null, ...best }; if (!pick) return out;
for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0); all.push(...pick.vals);
for (const v of pick.vals) otsu.push(+(v < pick.thr));
} }
const msg = rsDecode(bytesFromBits(bits)); const c = classify(all);
return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null }; if (!c) return out;
// local split first (bands, vignetting), plain per-ring split as a second opinion (strong tilt)
const strict = best.score < 0.92, t = tokenOf(c.bits, c.soft, strict) || tokenOf(otsu, c.soft, strict);
return { ...out, bits: c.bits.join(""), soft: c.soft, token: t ? t.token : null, fixes: t ? t.fixes : null };
} }
// whole frame: find center discs, read the first one that yields a valid token // whole frame: find center discs, read the first one that yields a valid token
@@ -732,10 +818,43 @@ export function decodeFrame(img, opts = {}) {
for (const c of cands) { for (const c of cands) {
const r = decodeAt(img, c, opts); const r = decodeAt(img, c, opts);
if (r && r.token) return { ...r, cand: c, found: cands.length }; if (r && r.token) return { ...r, cand: c, found: cands.length };
last = r || last; if (r && (!last || r.score > last.score)) last = { ...r, cand: c };
} }
return { token: null, found: cands.length, score: last?.score ?? null }; return { token: null, found: cands.length, score: last?.score ?? null, soft: last?.soft, cand: last?.cand || cands[0] };
}
// frame after frame: adds up the soft bits of frames showing the same code, so a code too noisy
// for one frame still gets through, and keeps tokens in line with the previous ones
export function makeReader(opts = {}) {
let acc = null, frames = 0, anchor = null, pending = null;
const similar = (a, b) => { let s = 0, na = 0, nb = 0; for (let i = 0; i < a.length; i++) { s += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } return s / Math.sqrt(na * nb || 1); };
// slots only move forward, about 2 per second: a token far from the last one is noise or a replay
const gate = (token, now) => {
const slot = +token.slice(1).split(".")[0];
const near = (ref) => { const d = ((slot - ref.slot + 98304) % 65536) - 32768; return d >= -8 && d <= 8 + (now - ref.at) / 100; };
if (!anchor || near(anchor)) { anchor = { slot, at: now }; pending = null; return true; }
if (pending && near(pending)) { anchor = { slot, at: now }; pending = null; return true; }
pending = { slot, at: now };
return false;
};
return {
read(img, now = Date.now()) {
const d = decodeFrame(img, opts);
let token = d.token, via = "frame";
if (!token && d.soft && opts.accumulate !== false) {
if (acc && similar(acc, d.soft) > 0.3) { for (let i = 0; i < acc.length; i++) acc[i] += d.soft[i]; frames++; }
else { acc = Float32Array.from(d.soft); frames = 1; }
if (frames > 1) {
const t = tokenOf(Array.from(acc, (v) => +(v > 0)), acc);
// summed frames only get the safe corrections
if (t && t.fixes <= 2) { token = t.token; via = "sum"; }
}
} else if (token) { acc = Float32Array.from(d.soft, (v) => (v > 0 ? 1.5 : -1.5)); frames = 1; }
if (token && opts.gate !== false && !gate(token, now)) token = null;
return { ...d, token, via };
},
};
} }
// internals for the lab bench // internals for the lab bench
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle }; export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf };
+53
View File
@@ -0,0 +1,53 @@
// camera side of the ring code: finds the code on a small copy of the frame, then reads it from a crop
// at full sensor resolution. far codes keep every pixel the camera has, and the cost per frame stays flat
import { makeReader, locate, grayOf, CENTER, DISC } from "./ringcode.js";
const WIDE = 960, CROP = 360;
export function makeRingScanner(opts = {}) {
const reader = makeReader(opts);
const wide = document.createElement("canvas"), wctx = wide.getContext("2d", { willReadFrequently: true });
const crop = document.createElement("canvas"), cctx = crop.getContext("2d", { willReadFrequently: true });
let track = null;
// source px of the square around a code of the given unit
function readAt(src, sw, sh, t, now) {
const half = t.unit * (DISC + 0.9);
const x0 = Math.max(0, Math.round(t.cx - half)), y0 = Math.max(0, Math.round(t.cy - half));
const w = Math.min(sw, Math.round(t.cx + half)) - x0, h = Math.min(sh, Math.round(t.cy + half)) - y0;
if (w < 24 || h < 24) return null;
const k = Math.min(1, CROP / Math.max(w, h));
crop.width = Math.round(w * k); crop.height = Math.round(h * k);
cctx.drawImage(src, x0, y0, w, h, 0, 0, crop.width, crop.height);
const d = reader.read(grayOf(cctx.getImageData(0, 0, crop.width, crop.height)), now);
if (!d.cand) return null;
// only a blob with a sync ring keeps the crop alive, anything else falls back to the whole frame
const at = d.token || d.soft ? now : t.at ?? now - 500;
track = { cx: x0 + (d.cand.cx + 0.5) / k, cy: y0 + (d.cand.cy + 0.5) / k, unit: d.cand.r / CENTER / k, at };
return d;
}
return {
// src: video or canvas of sw x sh. returns { token, ... } with token null when nothing was read
scan(src, sw, sh, now = performance.now()) {
if (track && now - track.at < 700) {
const d = readAt(src, sw, sh, track, now);
if (d) return d;
}
track = null;
const k = Math.min(1, WIDE / sw);
wide.width = Math.round(sw * k); wide.height = Math.round(sh * k);
// plain bilinear at 3x reduction skips pixels and keeps the noise
wctx.imageSmoothingQuality = "high";
wctx.drawImage(src, 0, 0, wide.width, wide.height);
const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 2 });
let last = null;
for (const c of cands) {
const d = readAt(src, sw, sh, { cx: (c.cx + 0.5) / k, cy: (c.cy + 0.5) / k, unit: c.r / CENTER / k }, now);
if (d && d.token) return d;
last = d || last;
}
return last || { token: null, found: cands.length };
},
};
}
+1 -1
View File
@@ -150,6 +150,6 @@ window.debugOne = (trial) => {
} }
return { quad: q, cTrue, cEst, radial, cands: out.map((o) => ({ ...o, r: o.r && { token: o.r.token, score: o.r.score, bits: o.r.bits } })) }; return { quad: q, cTrue, cEst, radial, cands: out.map((o) => ({ ...o, r: o.r && { token: o.r.token, score: o.r.score, bits: o.r.bits } })) };
}; };
window.benchReady = true; globalThis.NOFIT = new URLSearchParams(location.search).has("nofit"); window.benchReady = true; for (const k of new URLSearchParams(location.search).keys()) globalThis[k] = true;
</script></head> </script></head>
<body></body></html> <body></body></html>
+60 -1
View File
@@ -3,6 +3,8 @@ import * as RC from "/static/js/ringcode.js";
import { lcg, makeRoom, frame, jpeg } from "/static/ringlab/synth.js"; import { lcg, makeRoom, frame, jpeg } from "/static/ringlab/synth.js";
import * as V1 from "/static/ringlab/ringcode_v1.js"; import * as V1 from "/static/ringlab/ringcode_v1.js";
import { makeRingScanner } from "/static/js/ringscan.js";
window.makeRingScanner = makeRingScanner;
const { decodeFrame, grayOf, locate, decodeAt, RADII, CENTER, _lab } = RC; const { decodeFrame, grayOf, locate, decodeAt, RADII, CENTER, _lab } = RC;
@@ -21,6 +23,10 @@ const pipes = {
legacy: (canvas) => V1.decodeFrame(grab(canvas, 960).img), // what vote.js shipped with legacy: (canvas) => V1.decodeFrame(grab(canvas, 960).img), // what vote.js shipped with
cap960: (canvas, t) => decodeFrame(grab(canvas, 960).img, t.opts || {}), cap960: (canvas, t) => decodeFrame(grab(canvas, 960).img, t.opts || {}),
native: (canvas, t) => decodeFrame(grab(canvas, 1e9).img, t.opts || {}), native: (canvas, t) => decodeFrame(grab(canvas, 1e9).img, t.opts || {}),
noacc: (canvas, t, key) => {
const s = (scanners[key] ||= window.makeRingScanner({ accumulate: false }));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? null);
},
scan: (canvas, t, key) => { scan: (canvas, t, key) => {
const s = (scanners[key] ||= window.makeRingScanner(t.scanOpts || {})); const s = (scanners[key] ||= window.makeRingScanner(t.scanOpts || {}));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? null); return s.scan(canvas, canvas.width, canvas.height, t.now ?? null);
@@ -58,11 +64,64 @@ function diagnose(img, k, truth, t) {
}); });
let byteErr = 0; let byteErr = 0;
for (let i = 0; i < 96; i += 8) byteErr += byteBits.slice(i, i + 8).some(Boolean); for (let i = 0; i < 96; i += 8) byteErr += byteBits.slice(i, i + 8).some(Boolean);
Object.assign(out, { dprime: dp, bitErr, idealErr, byteErr }); Object.assign(out, { dprime: dp, bitErr, idealErr, byteErr, lab: toneLab(img, T, t) });
out.stage = out.rank < 0 || out.rank >= 4 ? "locate" : out.oracleGeo ? "geometry" : byteErr <= 3 ? "sync/thr" : "tone"; out.stage = out.rank < 0 || out.rank >= 4 ? "locate" : out.oracleGeo ? "geometry" : byteErr <= 3 ? "sync/thr" : "tone";
return out; return out;
} }
// lab only: which bit decision would survive, given the true geometry? and how much do neighbours bleed in?
function sharpen(img, passes, amt) {
const { g, w, h } = img, b = Float32Array.from(g), tmp = new Float32Array(w * h);
for (let p = 0; p < passes; p++) {
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = y * w + x; tmp[i] = (b[i - (x > 0)] + 2 * b[i] + b[i + (x < w - 1)]) / 4; }
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = y * w + x; b[i] = (tmp[i - (y > 0 ? w : 0)] + 2 * tmp[i] + tmp[i + (y < h - 1 ? w : 0)]) / 4; }
}
for (let i = 0; i < b.length; i++) b[i] = g[i] + amt * (g[i] - b[i]);
return { g: b, w, h };
}
function toneLab(img, T, t) {
const rings = RC.ringsOf(t.bits), out = {};
const read = (im) => {
const S = (x, y) => { const [u, v] = T(x, y); return _lab.bilinear(im, u, v); };
return rings.map((ring, ri) => { const n = ring.length, step = (2 * Math.PI) / n; return ring.split("").map((_, j) => _lab.sector(S, RADII[ri], _lab.sectorAngle(t.theta, j, n), step)); });
};
const errs = (vals, thrOf) => { let e = 0; for (let ri = 1; ri < 4; ri++) { const thr = thrOf(ri); vals[ri].forEach((v, j) => { e += (v < thr ? "1" : "0") !== rings[ri][j]; }); } return e; };
const m = (a) => a.reduce((x, y) => x + y, 0) / a.length;
const variants = { raw: img, sh1: sharpen(img, 3, 1), sh2: sharpen(img, 6, 2) };
for (const [name, im] of Object.entries(variants)) {
const vals = read(im);
if (vals.flat().some(Number.isNaN)) continue;
const D = m(vals[0].filter((_, j) => rings[0][j] === "1")), L = m(vals[0].filter((_, j) => rings[0][j] === "0"));
out[name + "Otsu"] = errs(vals, (ri) => _lab.split(vals[ri]).thr);
out[name + "Sync"] = errs(vals, () => (D + L) / 2);
const all = _lab.split(vals.slice(1).flat()).thr;
out[name + "All"] = errs(vals, () => all);
// local: compare each dash with the mean of its ring neighbourhood
let e = 0;
for (let ri = 1; ri < 4; ri++) { const v = vals[ri], n = v.length; v.forEach((x, j) => { let lo = Infinity, hi = -Infinity; for (let d = -3; d <= 3; d++) { const y = v[(j + d + n) % n]; if (y < lo) lo = y; if (y > hi) hi = y; } const thr = hi - lo > 0.5 * (L - D) ? (lo + hi) / 2 : (D + L) / 2; e += (x < thr ? "1" : "0") !== rings[ri][j]; }); }
out[name + "Local"] = e;
if (name !== "raw") continue;
// y = c0 + own*b + ang*mean(ring neighbours) + rad*mean(adjacent rings), in units of the sync ring swing
const rows = [];
rings.forEach((ring, ri) => {
const n = ring.length;
for (let j = 0; j < n; j++) {
const frac = (j + 0.5) / n, nb = (k) => (k < 0 || k > 3 ? 0 : +rings[k][Math.floor(frac * rings[k].length)]);
rows.push([1, +ring[j], (+ring[(j + 1) % n] + +ring[(j + n - 1) % n]) / 2, (nb(ri - 1) + nb(ri + 1)) / 2, (L - vals[ri][j]) / (L - D)]);
}
});
const N = Array.from({ length: 4 }, () => new Array(4).fill(0)), V = new Array(4).fill(0);
for (const r of rows) for (let i = 0; i < 4; i++) { V[i] += r[i] * r[4]; for (let j = 0; j < 4; j++) N[i][j] += r[i] * r[j]; }
for (let i = 0; i < 4; i++) { let p = i; for (let r = i + 1; r < 4; r++) if (Math.abs(N[r][i]) > Math.abs(N[p][i])) p = r; [N[i], N[p]] = [N[p], N[i]]; [V[i], V[p]] = [V[p], V[i]]; for (let r = 0; r < 4; r++) if (r !== i) { const f = N[r][i] / N[i][i]; for (let k = i; k < 4; k++) N[r][k] -= f * N[i][k]; V[r] -= f * V[i]; } }
const co = V.map((v, i) => v / N[i][i]);
let res = 0;
for (const r of rows) res += (r[4] - co[0] - co[1] * r[1] - co[2] * r[2] - co[3] * r[3]) ** 2;
out.isi = [...co, Math.sqrt(res / rows.length)].map((v) => +v.toFixed(3));
}
return out;
}
window.runFar = async (cfg) => { window.runFar = async (cfg) => {
const rnd = lcg(cfg.seed || 4242), results = []; const rnd = lcg(cfg.seed || 4242), results = [];
for (const t of cfg.trials) { for (const t of cfg.trials) {
+10 -2
View File
@@ -95,9 +95,9 @@ def neg_trials(n):
def seqs(n): def seqs(n):
r = random.Random(47) r = random.Random(47)
out = [] out = []
for d, contrast, fps in itertools.product([80, 100, 120, 150], [0.45, 0.3], [15, 7]): for d, contrast, fps in itertools.product([60, 70, 80, 100, 120, 150], [0.45, 0.3], [15, 7]):
for _ in range(n): for _ in range(n):
s = camera(r, d, contrast, 1.0, 1920) s = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920)
s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=500, shake=r.uniform(0.3, 1.2), s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=500, shake=r.uniform(0.3, 1.2),
tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * 500 + r.uniform(0, 400)) tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * 500 + r.uniform(0, 400))
out.append(s) out.append(s)
@@ -168,6 +168,13 @@ async def run_far(p, n, pipes, diag):
print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}" print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}"
f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})" f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})"
f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels") f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels")
print(" bit errors with true geometry per decision rule, and bleed model (own, ring neighbours, adjacent rings, residual):")
for d in sorted({r["d"] for r in res}):
labs = [r["diag"]["lab"] for r in res if r["d"] == d and "isi" in r["diag"]["lab"]]
keys = [k for k in labs[0] if k != "isi"]
isi = [sum(x["isi"][i] for x in labs) / len(labs) for i in range(5)]
print(f" d {d}: " + " ".join(f"{k} {sum(x.get(k, 0) for x in labs) / len(labs):.1f}" for k in keys)
+ f" | own {isi[1]:.2f} ang {isi[2]:.2f} rad {isi[3]:.2f} resid {isi[4]:.2f}")
out = ROOT / "tools" / "bench_out" out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True) out.mkdir(exist_ok=True)
for i, r in enumerate(res[:3]): for i, r in enumerate(res[:3]):
@@ -240,4 +247,5 @@ async def main():
server.terminate() server.terminate()
if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())