Ring code: far/washed projector bench, multi-scale locator with ring check
This commit is contained in:
+168
-26
@@ -1,10 +1,12 @@
|
||||
"""ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome,
|
||||
runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell]"""
|
||||
runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell]
|
||||
env: SUITE=legacy,far,seq,neg (default all) PIPES=legacy,scan DIAG=legacy|native NEG=300 CPU=6 (slow phone)"""
|
||||
import asyncio
|
||||
import base64
|
||||
import collections
|
||||
import itertools
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
@@ -45,8 +47,164 @@ def trials(n):
|
||||
return out
|
||||
|
||||
|
||||
def code(r):
|
||||
secret, slot = r.randbytes(32), r.randrange(1 << 36)
|
||||
return {"bits": ringcode.render_bits(secret, "abcdefgh", 500, slot), "token": ringcode.token(secret, "abcdefgh", 500, slot)}
|
||||
|
||||
|
||||
# washed projector: (black level, white level) of the screen as the camera sees it
|
||||
WASH = {0.45: (80, 195), 0.3: (105, 181)}
|
||||
SENSORS = {1280: (1280, 720), 1920: (1920, 1080)}
|
||||
|
||||
|
||||
def camera(r, d, contrast, blur, sensor):
|
||||
"""one phone looking at a projected code d px wide in a 1280 px frame, plus what a real room adds"""
|
||||
W, H = SENSORS[sensor]
|
||||
return {"W": W, "H": H, "d": d, "frac": d / 1280, "contrast": contrast, "wash": WASH[contrast], "blur": blur, "sensor": sensor,
|
||||
# optical blur is angular, pixel softness (demosaic, video codec) is per sensor pixel
|
||||
"oblur": blur, "pblur": 0.6 + 0.2 * blur,
|
||||
"cast": [r.uniform(0.9, 1.0), 1.0, r.uniform(0.95, 1.1)], "gain": r.uniform(0.85, 1.2),
|
||||
"room": r.choice(["dark", "dark", "bright"]), "band": r.choice([0, 0, 0.06, 0.1]), "bandPeriod": r.uniform(40, 200),
|
||||
"noise": r.uniform(4, 8), "axis": r.uniform(0, 360), "dx": r.uniform(-250, 250) * W / 1280, "dy": r.uniform(-120, 120) * W / 1280,
|
||||
"theta": r.uniform(0, 6.283), "anim": r.uniform(0, 100), "qseed": r.randrange(1 << 20)}
|
||||
|
||||
|
||||
def far_trials(n):
|
||||
r = random.Random(23)
|
||||
out = []
|
||||
for d, contrast, blur, tilt, sensor in itertools.product([80, 100, 120, 150, 180], [0.45, 0.3], [0.7, 1.5], [0, 20], [1280, 1920]):
|
||||
for _ in range(n):
|
||||
t = camera(r, d, contrast, blur, sensor)
|
||||
m = r.uniform(0, 1.5), r.uniform(0, 6.283)
|
||||
t.update(code(r), tilt=tilt, motion=[m[0] * math.cos(m[1]), m[0] * math.sin(m[1])], jpeg=r.choice([0, 0, 0.6]))
|
||||
out.append(t)
|
||||
return out
|
||||
|
||||
|
||||
def neg_trials(n):
|
||||
"""nothing to read: no code on the screen, bare dark discs, discs with pie-like arcs around"""
|
||||
r = random.Random(31)
|
||||
out = []
|
||||
for i in range(n):
|
||||
t = camera(r, r.choice([80, 120, 180, 300]), r.choice([0.45, 0.3]), r.choice([0.7, 1.5]), r.choice([1280, 1920]))
|
||||
t.update(tilt=r.choice([0, 20]), nocode=True, decoy=i % 3)
|
||||
out.append(t)
|
||||
return out
|
||||
|
||||
|
||||
def seqs(n):
|
||||
r = random.Random(47)
|
||||
out = []
|
||||
for d, contrast, fps in itertools.product([80, 100, 120, 150], [0.45, 0.3], [15, 7]):
|
||||
for _ in range(n):
|
||||
s = camera(r, d, contrast, 1.0, 1920)
|
||||
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))
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
def table(rows, keys, pipes):
|
||||
for key in keys:
|
||||
vals = sorted({r[key] for r in rows})
|
||||
for p in pipes:
|
||||
cells = []
|
||||
for v in vals:
|
||||
sub = [r for r in rows if r[key] == v]
|
||||
cells.append(f"{v}: {100 * sum(r[p]['ok'] for r in sub) / len(sub):3.0f}%")
|
||||
print(f" {key:9s}{p:7s}", " ".join(cells))
|
||||
|
||||
|
||||
async def chunks(p, fn, key, items, cfg, size):
|
||||
# cdp calls time out after 60 s
|
||||
out = []
|
||||
for i in range(0, len(items), size):
|
||||
out += await p.js(f"{fn}({json.dumps({**cfg, key: items[i:i + size], 'seed': 1000 + i})})")
|
||||
return out
|
||||
|
||||
|
||||
async def run_legacy(p, n):
|
||||
ts = trials(n)
|
||||
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4, 'v1': bool(os.environ.get('V1'))})})")
|
||||
harsh = [r for r in res if r.get("harsh")]
|
||||
print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}")
|
||||
codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
|
||||
for key in ("d", "tilt", "blur", "contrast"):
|
||||
agg = collections.defaultdict(lambda: [0, 0, 0])
|
||||
for r in codes:
|
||||
a = agg[r[key]]
|
||||
a[0] += 1; a[1] += (r["found"] or 0) > 0; a[2] += r["ok"]
|
||||
print(f"{key:8s}", " ".join(f"{k}: ok {v[2]}/{v[0]}" for k, v in sorted(agg.items())))
|
||||
ok = sum(r["ok"] for r in codes)
|
||||
ms = sorted(r['ms'] for r in res)
|
||||
print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), decode ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}")
|
||||
fails = [r for r in codes if not r["ok"]]
|
||||
print("failures (d, tilt, blur, contrast, found, score, errs):",
|
||||
[(r["d"], r["tilt"], r["blur"], r["contrast"], r["found"], r["score"], r.get("errs")) for r in fails[:16]])
|
||||
wrong = [r for r in res if r["token"] and not r["ok"]]
|
||||
print("false tokens:", len(wrong), "(no-code frames:", sum(1 for r in res if r.get("nocode")), ")")
|
||||
out = ROOT / "tools" / "bench_out"
|
||||
out.mkdir(exist_ok=True)
|
||||
for i, r in enumerate(res[:4]):
|
||||
if r.get("png"):
|
||||
(out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
|
||||
|
||||
|
||||
async def run_far(p, n, pipes, diag):
|
||||
ts = far_trials(n)
|
||||
res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes, "diag": diag, "keep": 3}, 10)
|
||||
print(f"\n== far + washed projector, single frames ({len(res)} frames), d = code diameter in a 1280 px wide frame ==")
|
||||
table(res, ("d", "contrast", "blur", "tilt", "sensor", "room"), pipes)
|
||||
for pn in pipes:
|
||||
ms = sorted(r[pn]["ms"] for r in res)
|
||||
wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"])
|
||||
print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}, false tokens {wrong}")
|
||||
if diag:
|
||||
print(f" where {diag} resolution frames break (truth substituted stage by stage):")
|
||||
for d in sorted({r["d"] for r in res}):
|
||||
sub = [r["diag"] for r in res if r["d"] == d]
|
||||
good = [x for x in sub if x["rank"] in range(4) and x.get("candOk")]
|
||||
st = collections.Counter(x["stage"] for x in sub if x not in good)
|
||||
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" 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")
|
||||
out = ROOT / "tools" / "bench_out"
|
||||
out.mkdir(exist_ok=True)
|
||||
for i, r in enumerate(res[:3]):
|
||||
if r.get("png"):
|
||||
(out / f"far_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
|
||||
return res
|
||||
|
||||
|
||||
async def run_neg(p, n, pipes):
|
||||
ts = neg_trials(n)
|
||||
res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes}, 10)
|
||||
print(f"\n== negatives ({len(res)} frames without a code) ==")
|
||||
for pn in pipes:
|
||||
print(f" {pn}: false tokens {sum(1 for r in res if r[pn]['token'])}")
|
||||
|
||||
|
||||
async def run_seq(p, n, pipes):
|
||||
ss = seqs(n)
|
||||
res = await chunks(p, "runSeq", "seqs", ss, {"pipes": pipes}, 1)
|
||||
print(f"\n== far sequences: 6 s = 12 tokens shown, 1920x1080 sensor, hand shake ({len(res)} sequences) ==")
|
||||
for key in ("d", "contrast", "fps"):
|
||||
for pn in pipes:
|
||||
cells = []
|
||||
for v in sorted({r[key] for r in res}):
|
||||
sub = [r[pn] for r in res if r[key] == v]
|
||||
done = sorted(x["first5"] for x in sub if x["first5"] is not None)
|
||||
med = f"{done[len(done) // 2]:.1f}s" if done else "-"
|
||||
cells.append(f"{v}: {sum(x['got'] for x in sub) / len(sub):4.1f} tok, 5 in 6s {100 * len(done) / len(sub):3.0f}% ({med})")
|
||||
print(f" {key:9s}{pn:7s}", " ".join(cells))
|
||||
for pn in pipes:
|
||||
print(f" {pn}: false tokens {sum(r[pn]['false'] for r in res)}, ms/frame {sum(r[pn]['ms'] for r in res) / len(res):.1f}")
|
||||
|
||||
|
||||
async def main():
|
||||
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
|
||||
suites = os.environ.get("SUITE", "legacy,far,seq,neg").split(",")
|
||||
pipes = os.environ.get("PIPES", "legacy,scan").split(",")
|
||||
env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"}
|
||||
server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
@@ -64,35 +222,19 @@ async def main():
|
||||
if throttle > 1:
|
||||
# rough low-end phone: chrome devtools cpu slowdown factor
|
||||
await p.send("Emulation.setCPUThrottlingRate", {"rate": throttle})
|
||||
await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html")
|
||||
await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html?" + os.environ.get("Q", ""))
|
||||
for _ in range(50):
|
||||
if await p.js("!!window.benchReady"):
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
ts = trials(n)
|
||||
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4})})")
|
||||
harsh = [r for r in res if r.get("harsh")]
|
||||
print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}")
|
||||
codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
|
||||
for key in ("d", "tilt", "blur", "contrast"):
|
||||
agg = collections.defaultdict(lambda: [0, 0, 0])
|
||||
for r in codes:
|
||||
a = agg[r[key]]
|
||||
a[0] += 1; a[1] += (r["found"] or 0) > 0; a[2] += r["ok"]
|
||||
print(f"{key:8s}", " ".join(f"{k}: ok {v[2]}/{v[0]}" for k, v in sorted(agg.items())))
|
||||
ok = sum(r["ok"] for r in codes)
|
||||
ms = sorted(r['ms'] for r in res)
|
||||
print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), decode ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}")
|
||||
fails = [r for r in codes if not r["ok"]]
|
||||
print("failures (d, tilt, blur, contrast, found, score, errs):",
|
||||
[(r["d"], r["tilt"], r["blur"], r["contrast"], r["found"], r["score"], r.get("errs")) for r in fails[:16]])
|
||||
wrong = [r for r in res if r["token"] and not r["ok"]]
|
||||
print("false tokens:", len(wrong), "(no-code frames:", sum(1 for r in res if r.get("nocode")), ")")
|
||||
out = ROOT / "tools" / "bench_out"
|
||||
out.mkdir(exist_ok=True)
|
||||
for i, r in enumerate(res[:4]):
|
||||
if r.get("png"):
|
||||
(out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
|
||||
if "legacy" in suites:
|
||||
await run_legacy(p, n)
|
||||
if "far" in suites:
|
||||
await run_far(p, n, pipes, os.environ.get("DIAG"))
|
||||
if "seq" in suites:
|
||||
await run_seq(p, max(1, n // 2), pipes)
|
||||
if "neg" in suites:
|
||||
await run_neg(p, int(os.environ.get("NEG", "300")), pipes)
|
||||
await b.close()
|
||||
finally:
|
||||
server.terminate()
|
||||
|
||||
Reference in New Issue
Block a user