brokkr_reference core: fit_runs and fit_sheet, a shell's traced runs fitted through cameras and refused where a trace is not explained

The cage points of a loft's traced hard runs move until the runs, as crease_run builds them and the cameras draw
them, lie on their traces: analytic Jacobian, Gauss-Newton with LM damping, a prior that holds each point to the
sheet as given. A fit is returned only where every point of every trace lies within tol px of its built run;
otherwise the refusal names the trace and the span. Per moved point the report says metres per pixel along its
sight line and the prior's share of that. Runs crease_run does not build (semi-sharp, a dart end, a point held
partway) and free cages are refused before fitting.

FitTests with the Orchid c09 fixture (camera record, frame, two hand traces, a blocking column; no mesh).
core.seen is pinned against project; _off now serves the explained check (follow-up reference-lift-s5-lows).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 04:21:38 +01:00
commit 968208fd36
3 changed files with 717 additions and 0 deletions

View file

@ -30,9 +30,18 @@ A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-t
seen(cam, frame, points) pixels of points of a frame
crease_run(points) where Blender builds the hard crease of a cage column at one level
along(line, segments, height) the flow score: how much of a traced line has a seen edge along it
A shell's cage (brokkr_kitbash's sheet) is fitted to traces of its hard runs: the cage points of the traced runs
are moved until the runs, as Blender builds them and the cameras draw them, lie on the traces. The fit is returned
only where the built runs explain every trace; docs/reference.md, "fit_shell", says what the answer is worth.
fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report
fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet
"""
from __future__ import annotations
import copy
import json
import math
import numpy as np
@ -438,6 +447,270 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05):
return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)}
# --- a shell's traced runs fitted through cameras --------------------------------------------------------------------
LEVELS = 2 # crease_run applied this many times gives the samples of a built run the fit draws: 4k - 3 for k cage points
HARD = 1.0 - 1e-9 # a crease weight from here up is hard: the edge stays sharp at every level, which is what crease_run builds
ROUNDS = 60
RESULT_LIMIT = 16000 # characters of a host result Brokkr copies into a receipt before it truncates (brokkr_bridge's HOST_RESULT_LIMIT; this package imports nothing from Brokkr)
def _drawn(cam, frame, X):
"""Pixels (n, 2) of points of a frame and their derivative (n, 2, 3) by the points' own coordinates; None where
a point stands behind the camera."""
F, R, f = np.asarray(frame, float), np.asarray(cam["R"], float), cam["f"]
A = R @ F[:3, :3]
q = (X @ F[:3, :3].T + F[:3, 3] - np.asarray(cam["C"], float)) @ R.T
z = -q[:, 2]
if z.min() <= 1e-6:
return None
u = np.stack([cam["c"][0] + f * q[:, 0] / z, cam["c"][1] - f * q[:, 1] / z], 1)
du = (f / z)[:, None] * A[0] + (f * q[:, 0] / z ** 2)[:, None] * A[2]
dv = -((f / z)[:, None] * A[1] + (f * q[:, 1] / z ** 2)[:, None] * A[2])
return u, np.stack([du, dv], 1)
def _normal(points, line):
"""Per point: its distance to a polyline and the unit direction that distance grows along (the nearest
segment's normal; from the segment's end where the point is past it)."""
a, d = line[:-1], line[1:] - line[:-1]
length = np.maximum((d * d).sum(1), 1e-18)
t = np.clip(((points[:, None] - a) * d).sum(2) / length, 0, 1)
off = points[:, None] - (a + t[:, :, None] * d)
dist = np.linalg.norm(off, axis=2)
k, i = dist.argmin(1), np.arange(len(points))
dist, off = dist[i, k], off[i, k]
on = dist < 1e-9
n = off / np.maximum(dist, 1e-12)[:, None]
n[on] = (np.stack([-d[k, 1], d[k, 0]], 1) / np.sqrt(length[k])[:, None])[on]
return dist, n
def _hard_runs(cage, runs):
"""Refuse a run crease_run does not build. Blender builds crease_run where every edge of the run is hard, every
point between its ends has those two sharp edges and no other, and each end holds: a hard corner point, three
or more hard or boundary edges, or, on a cage whose Subdivision preserves corners (a loft's; cage.boundary), a
boundary point of two edges."""
weight = {(int(min(a, b)), int(max(a, b))): float(w) for (a, b), w in zip(np.asarray(cage.creases).reshape(-1, 2), cage.weights)}
pinned = {int(v): float(w) for v, w in zip(cage.corners, cage.corner_weights)}
loops, sides = np.asarray(cage.faces), []
for first, size in zip(np.concatenate([[0], np.cumsum(cage.counts)[:-1]]), cage.counts):
face = loops[first:first + size]
sides += [np.sort(np.stack([face, np.roll(face, -1)], 1), axis=1)]
sides = np.concatenate(sides)
pairs, count = np.unique(sides, axis=0, return_counts=True)
at = {} # vertex -> [(weight, on the boundary)] of its edges
for (a, b), faces in zip(pairs, count):
w = weight.get((int(a), int(b)), 0.0)
for v in (int(a), int(b)):
at.setdefault(v, []).append((w, faces == 1))
for run in runs:
name, chain = run["name"], [int(v) for v in run["chain"]]
if len(chain) < 2 or len(set(chain)) != len(chain):
raise ReferenceFitError(f"{name}: its run must be two or more cage points, none twice (a closed loop has no end to hold)")
for m, (a, b) in enumerate(zip(chain, chain[1:])):
w = weight.get((min(a, b), max(a, b)))
if w is None or w < HARD:
raise ReferenceFitError(f"{name}: the edge after point {m} of its run has crease weight {w or 0:g}. Only a hard run (every edge 1) is built where "
"the fit draws it; a semi-sharp or uncreased edge rounds off by an amount the fit does not model. Crease it 1, or leave the run untraced")
for m, v in enumerate(chain):
sharp = [w for w, rim in at[v] if w > 0 or rim]
if 0 < m < len(chain) - 1:
if len(sharp) != 2 or pinned.get(v, 0.0) > 0:
raise ReferenceFitError(f"{name}: point {m} of its run is held or pulled by more than the run (a corner point, or another crease or the rim "
"meeting it there). Trace the run as two, one each side of that point")
elif not (pinned.get(v, 0.0) >= HARD or sum(1 for w, rim in at[v] if w >= HARD or rim) >= 3 or (len(at[v]) == 2 and cage.boundary == "PRESERVE_CORNERS")):
raise ReferenceFitError(f"{name}: the {'first' if m == 0 else 'last'} end of its run does not hold: it is a dart (the crease dies out into the surface "
"there) or runs on, on a mirrored sheet across the middle. An end holds at a corner point of weight 1, where three or "
"more hard edges meet, or on the rim")
def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0):
"""Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces.
views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world
cage the parsed sheet (brokkr_kitbash.core.Sheet's V, faces, counts, creases, weights, corners,
corner_weights, boundary)
runs [{"name", "chain": cage vertices in order, "view": index into views, "line": [[u, v], ...]}]; the
line is drawn from the chain's first point to its last
movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move
mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same
parameters seen again, x negated
share the prior: a move of share x diag from the cage as given costs what one pixel of miss does
tol pixels: every point of every trace must lie this near its built run as drawn
The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the
run's view) to the trace, and the run's two ends against the trace's; no point of the trace is matched to a
point of the run beyond that. Gauss-Newton with Levenberg-Marquardt damping on the analytic Jacobian. Returns
(V, report): the cage's vertices as fitted and {"traces": [{"miss_px": rms of the built points off the trace,
"unexplained_px": the trace's furthest point from the built run}], "points": [{"vertex", "moved_m",
"m_per_px", "prior_share"}], "rounds"}. m_per_px is how far the point slides along its sight line (the worst
of the views that trace it) per pixel of error in the traces, sqrt(r' S r) with S the point's block of the
inverse of J'J, prior included (Triggs et al. 2000, sections 9 and 10); prior_share is that over share x
diag: near 1 the traces say nothing about the point's depth and it stands where it was blocked.
Raises ReferenceFitError for a run it cannot model (_hard_runs), and when a trace is not explained: the error
names the trace and the span of it that lies further than tol from the built run, and carries the rows as
.traces. Nothing is returned as a fit then."""
V0, movable, mirror_of = np.array(cage.V, float), np.asarray(movable, bool), np.asarray(mirror_of, int)
mirrored = mirror_of != np.arange(len(V0))
if (movable & mirrored[:, None]).any() or not movable.any():
raise ReferenceFitError("movable must mark authored vertices, and at least one coordinate")
_hard_runs(cage, runs)
index = np.flatnonzero(movable.ravel())
column = np.full(V0.size, -1)
column[index] = np.arange(len(index))
flip, prior = np.where(mirrored, -1.0, 1.0), 1.0 / (share * diag)
prepared = []
for run in runs:
chain, line = np.asarray(run["chain"], int), np.asarray(run["line"], float)
if not 0 <= run["view"] < len(views):
raise ReferenceFitError(f"{run['name']}: view {run['view']} is none of the {len(views)} views")
if line.ndim != 2 or line.shape[1] != 2 or len(line) < 2 or not np.isfinite(line).all() or np.linalg.norm(np.diff(line, axis=0), axis=1).sum() < 1e-9:
raise ReferenceFitError(f"{run['name']}: its line must be two or more [u, v] points, not all in one place")
W = np.eye(len(chain))
for _ in range(LEVELS):
W = crease_run(W)
source = mirror_of[chain]
prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1),
column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held
p0 = V0.ravel()[index]
def terms(p):
"""(residual, Jacobian, each run's built points as drawn) at parameters p."""
P = V0.copy()
P.ravel()[index] = p
res, rows, drawn = [], [], []
for name, (cam, frame), line, W, source, sign, cols in prepared:
seen_ = _drawn(cam, frame, W @ (P[source] * sign))
if seen_ is None:
raise ReferenceFitError(f"{name}: its run stands behind the camera")
u, Ju = seen_
dist, n = _normal(u, line)
D = np.concatenate([np.einsum("si,sij->sj", n, Ju), Ju[0], Ju[-1]]) # per residual row, its derivative by its own built point
who = np.concatenate([np.arange(len(u)), [0, 0, len(u) - 1, len(u) - 1]])
block = np.zeros((len(D), len(p)))
for m in range(len(source)):
for c in range(3):
if cols[m, c] >= 0:
block[:, cols[m, c]] += W[who, m] * D[:, c] * sign[m, c]
res += [dist, u[0] - line[0], u[-1] - line[-1]]
rows.append(block)
drawn.append((u, dist))
return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn
p, lam, rounds = p0.copy(), 1e-3, 0
r, J, drawn = terms(p)
for rounds in range(1, ROUNDS + 1):
A, g = J.T @ J, J.T @ r
for _ in range(12):
step = np.linalg.solve(A + lam * np.diag(np.diag(A)), -g)
try:
r2, J2, drawn2 = terms(p + step)
except ReferenceFitError:
r2 = None
if r2 is not None and r2 @ r2 < r @ r:
p, r, J, drawn, lam = p + step, r2, J2, drawn2, lam / 3
break
lam *= 4
else:
break
if np.abs(step).max() < 1e-7:
break
V = V0.copy()
V.ravel()[index] = p
V = V[mirror_of] * np.stack([flip, np.ones(len(V)), np.ones(len(V))], 1)
traces, refused = [], None
for (name, _, line, *_), (u, dist) in zip(prepared, drawn):
length = np.linalg.norm(np.diff(line, axis=0), axis=1).sum()
dense = resampled(line, int(min(max(length, len(line)), 4000)) + 1) # a point each pixel along it
off = _off(dense, u)
traces.append({"miss_px": round(float(np.sqrt(np.mean(dist ** 2))), 3), "unexplained_px": round(float(off.max()), 3)})
if off.max() > tol and refused is None:
out = np.flatnonzero(off > tol) * length / (len(dense) - 1)
refused = (f"{name} is not explained: {len(out) * length / (len(dense) - 1):.0f} px of the trace, between {out[0]:.0f} and {out[-1]:.0f} px along it, lie "
f"more than {tol:g} px from the run as built, up to {off.max():.1f} px. Nothing is returned as a fit. The trace draws something this run "
"does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points")
if refused is not None:
error = ReferenceFitError(refused)
error.traces = traces
raise error
S = np.linalg.inv(J.T @ J)
points = []
for a in np.flatnonzero(movable.any(1)):
cols = column.reshape(-1, 3)[a]
block = np.zeros((3, 3))
held = cols >= 0
block[np.ix_(held, held)] = S[np.ix_(cols[held], cols[held])]
worst = 0.0
for _, (cam, frame), _, _, source, sign, _ in prepared:
for m in np.flatnonzero(source == a):
sight = V[a] * sign[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3]
sight = sight / np.linalg.norm(sight) * sign[m] # the sight line of the mirrored point, said in the authored point's coordinates
worst = max(worst, float(np.sqrt(sight @ block @ sight)))
points.append({"vertex": int(a), "moved_m": float(np.linalg.norm(V[a] - V0[a])), "m_per_px": worst, "prior_share": worst * prior})
return V, {"traces": traces, "points": points, "rounds": rounds}
def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=3.0):
"""fit_runs for a shell's sheet. `document` is the sheet as brokkr_kitbash.shell takes it and `cage` what
brokkr_kitbash.core.sheet parses it to; `frame` carries the shell to the world. `traces` is a list of
{"run": {"ring": i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, "side": 1 or -1, "line":
[[u, v], ...]} (authored indices, as the sheet's creases name runs; side -1 is the mirrored half of a mirrored
sheet; the line is drawn from `from` to `to`), and `cams` the camera record of each. The points of the traced
runs move, a mirrored sheet's point 0 only in its plane. Returns {"sheet": the document with those points
moved, "traces": [{"miss_px", "unexplained_px"}], "points": [{"ring", "point", "moved_m", "m_per_px",
"prior_share"}]}; refuses, before fitting, a result that would pass RESULT_LIMIT characters."""
mirror, closed = document.get("mirror", False) is True, bool(document.get("closed", False))
R, N = cage.rings, cage.points
if R is None:
raise ReferenceFitError("the sheet is a free cage: fit_sheet names runs by ring and column, which a loft has and a free cage does not. "
"core.fit_runs takes any cage's vertex chains")
C = (N + 1) // 2 if mirror else N
if not isinstance(traces, list) or not traces:
raise ReferenceFitError("traces must be an array of one or more {camera, box, run, side, line}")
mirror_of = np.arange(R * N)
if mirror:
for i in range(R):
mirror_of[i * N + C - 1 - np.arange(1, C)] = i * N + C - 1 + np.arange(1, C)
movable, runs = np.zeros((R * N, 3), bool), []
for k, trace in enumerate(traces):
where = f"traces[{k}]"
if not isinstance(trace, dict) or not isinstance(trace.get("run"), dict):
raise ReferenceFitError(f"{where} must be an object with a run")
if cams[k] is None:
raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this fit")
run, side = trace["run"], trace.get("side", 1)
if side not in (1, -1) or (side == -1 and not mirror):
raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half of a mirrored sheet, not {side!r}")
ring = "ring" in run
if ring == ("column" in run) or set(run) != {"ring" if ring else "column", "from", "to"}:
raise ReferenceFitError(f"{where}.run must be {{ring, from, to}} or {{column, from, to}}")
across, most = (R, C if closed else C - 1) if ring else (C, R - 1)
numbers_ = [run["ring" if ring else "column"], run["from"], run["to"]]
if any(isinstance(v, bool) or not isinstance(v, int) for v in numbers_) or not (0 <= numbers_[0] < across and 0 <= numbers_[1] < numbers_[2] <= most):
raise ReferenceFitError(f"{where}.run must name a {'ring under ' + str(R) if ring else 'column under ' + str(C)} and from under to, to at most {most}")
fixed, first, last = numbers_
authored = [(fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1)]
chain = [i * N + ((C - 1 + side * j) if mirror else j) for i, j in authored]
for i, j in authored:
movable[i * N + (C - 1 + j if mirror else j)] = (not (mirror and j == 0), True, True)
runs.append({"name": where, "chain": chain, "view": k, "line": trace.get("line")})
moved = [(int(v) // N, int(v) % N - (C - 1 if mirror else 0)) for v in np.flatnonzero(movable.any(1))]
size = len(json.dumps(document, separators=(",", ":"))) + 36 * len(moved) + 45 * len(traces) + 95 * len(moved) + 40
if size > RESULT_LIMIT:
raise ReferenceFitError(f"the fitted sheet and its report would be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was fitted. "
"Fit fewer runs at a time, or a sparser sheet")
V0 = np.array(cage.V, float)
V, report = fit_runs([(cam, frame) for cam in cams], cage, runs, movable, mirror_of, share, float(np.linalg.norm(np.ptp(V0, axis=0))), tol)
out = copy.deepcopy(document)
for i, j in moved:
out["rings"][i][j] = [round(float(x), 6) + 0.0 for x in V[i * N + (C - 1 + j if mirror else j)]]
return {"sheet": out, "traces": report["traces"], "points": [{"ring": i, "point": j, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4),
"prior_share": round(row["prior_share"], 3)} for (i, j), row in zip(moved, report["points"])]}
# --- fields ----------------------------------------------------------------------------------------------------------

View file

@ -0,0 +1,224 @@
{
"what": "Orchid concept c09 (one view): the camera record brokkr_reference.solve_camera solved from hand marks, the frame of the ship's mirror plane, the inboard edge of the two upper petals traced by eye (left is the mirrored half), and a blocking column of 8 stations standing up to a tenth of the ship's length off. No mesh and no hull: the sheet the test builds round the column is a strip that exists to carry it.",
"camera": {
"C": [
-6.168901501633792,
-121.90792252280691,
2.8948965905734094
],
"R": [
[
0.9987259467882663,
-0.05046269128654356,
0.0
],
[
0.0009919726785528231,
0.019632501305770517,
0.9998067717727681
],
[
-0.05045294047016491,
-0.9985329647440779,
0.01965754606547003
]
],
"f": 113777.77777777778,
"c": [
512.0,
512.0
],
"box": [
0.0,
0.0,
1024.0,
1024.0
],
"lens": 4000.0
},
"frame": [
[
0.7946956336528872,
0.5885955750367245,
-0.14837148951272178,
0.03987530991435051
],
[
-0.6006879570259439,
0.7273858746251298,
-0.3317887395313959,
0.013782020658254623
],
[
-0.08736605826654754,
0.35279602951708855,
0.9316126520286978,
0.5812516808509827
],
[
0.0,
0.0,
0.0,
1.0
]
],
"left": [
[
556.3,
34.2
],
[
533.3,
50.0
],
[
518.8,
64.6
],
[
500.0,
89.6
],
[
483.3,
118.8
],
[
466.7,
147.9
],
[
450.0,
178.3
],
[
433.3,
208.3
],
[
408.3,
258.3
],
[
389.6,
295.8
],
[
375.0,
329.2
],
[
356.3,
360.4
],
[
337.5,
389.6
],
[
320.8,
418.8
],
[
306.3,
445.8
]
],
"right": [
[
888.8,
86.7
],
[
853.3,
97.9
],
[
815.8,
112.5
],
[
778.3,
129.2
],
[
740.8,
152.1
],
[
703.3,
179.2
],
[
665.8,
210.4
],
[
636.7,
233.3
],
[
607.5,
262.5
],
[
582.5,
295.8
],
[
559.6,
337.5
],
[
532.5,
395.8
],
[
503.3,
466.7
]
],
"left_side": -1,
"blocking": [
[
0.2278,
0.3586,
0.279
],
[
0.1764,
0.183,
0.3436
],
[
0.1489,
0.0666,
0.297
],
[
0.2226,
0.1029,
0.2136
],
[
0.251,
0.1112,
0.0995
],
[
0.2813,
0.1228,
0.0095
],
[
0.2259,
-0.0472,
0.0286
],
[
0.4158,
0.1062,
-0.1008
]
]
}

View file

@ -44,6 +44,10 @@ if np is not None:
spec = importlib.util.spec_from_file_location("brokkr_reference_core", SURFACE / "brokkr_reference" / "core.py")
core = importlib.util.module_from_spec(spec)
spec.loader.exec_module(core)
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_for_reference", SURFACE / "brokkr_kitbash" / "core.py")
kit = importlib.util.module_from_spec(spec) # the sheet's one parser: fit_sheet takes what it parses
sys.modules[spec.name] = kit
spec.loader.exec_module(kit)
BOX = [100.0, 50.0, 1100.0, 800.0]
NAMES = [f"p{i}" for i in range(13)]
@ -381,6 +385,222 @@ class FlowTests(unittest.TestCase):
self.assertIn(said, str(caught.exception))
FIT_FRAME = [[0.9659258262890683, -0.25881904510252074, 0.0, 0.3], [0.25881904510252074, 0.9659258262890683, 0.0, -0.2], [0.0, 0.0, 1.0, 0.1], [0.0, 0.0, 0.0, 1.0]] # turned 15 degrees about z and moved
FIT_VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35))
FIT_K = 10 # cage points in the traced column
def crease(A, w, n=400):
"""A crease 2 m long on the +x side of a mirror plane, in the shell's frame: the family the fit was mapped on."""
t = np.linspace(0, 1, n)
return np.stack([0.4 + A * np.sin(w * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1)
def overdrawn(line, start, stop, off, kind):
"""A stroke that runs along `line`, and between two shares of it doubles back and over again, each pass `off`
of the line's extent further to one side: a trace drawn twice over."""
n = len(line)
i0, i1 = int(start * (n - 1)), int(stop * (n - 1))
v = line[i1] - line[i0]
d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * off * np.ptp(line, axis=0).max()
forward, back = line[i0:i1 + 1], line[i1:i0 - 1 if i0 > 0 else None:-1]
if kind == "mid":
return np.vstack([line[:i1 + 1], back + d, forward + 2 * d, line[i1 + 1:]])
if kind == "truth-last":
return np.vstack([line[:i0], forward + d, back + 2 * d, line[i0:]])
return np.vstack([line[:i0], forward + d, back + 2 * d, forward, line[i1 + 1:]])
def strip(column, weight=1.0, last=None):
"""A mirrored sheet three points wide whose column 1 is `column`, creased from ring 0 to `last` (the far rim)."""
return {"mirror": True, "rim": 1.0, "creases": [{"column": 1, "from": 0, "to": len(column) - 1 if last is None else last, "weight": weight}],
"rings": [[[0.0, float(p[1]), float(p[2]) + 0.15], [float(v) for v in p], [float(p[0]) + 0.5, float(p[1]), float(p[2]) - 0.2]] for p in column]}
def blocked(A, w, share):
"""(the true crease, a strip whose column stands up to `share` of the crease's 2 m off it)."""
truth, t, r = crease(A, w), np.linspace(0, 1, FIT_K), np.random.default_rng(int(A * 100 + w * 10))
bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t)[:, None] for j in range(2))
return truth, strip(core.resampled(truth, FIT_K) + share * 2.0 * bump / np.abs(bump).max())
def fit_views(truth):
both = np.vstack([truth, truth * [-1, 1, 1]]) @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3]
return [camera(both, *view) for view in FIT_VIEWS]
def pair_traces(a, b=None):
run = {"column": 1, "from": 0, "to": FIT_K - 1}
return [{"camera": "View", "run": run, "side": side, "line": np.asarray(line).tolist()} for side, line in ((1, a), (-1, b)) if line is not None]
def fitted(document, traces, cam, **more):
return core.fit_sheet(document, kit.sheet(document), FIT_FRAME, traces, [cam] * len(traces), **more)
def off_truth(document, truth):
"""The furthest the column's built run stands from the true crease, or the crease's ends from the run."""
run = core.resampled(core.crease_run(core.crease_run(np.array(document["rings"])[:, 1])), 400)
return max(float(core._off(run, truth).max()), float(core._off(truth[[0, -1]], run).max()))
@unittest.skipIf(np is None, "numpy")
class FitTests(unittest.TestCase):
"""fit_runs and fit_sheet: a shell's traced runs fitted through cameras, accepted only where the built runs
explain every trace. Bounds follow lodur:ruling:deterministic-bound-margin. Mutants, each run once on a copy:
F1 no explained check test_an_overdrawn_stroke_is_refused_naming_its_trace
F2 sensitivity across the run's tangent, not the ray test_the_sight_line_reading_holds_the_points_slide_along_its_run
F3 the prior left out of S test_one_trace_alone_reads_as_held_by_the_blocking
F4 no end terms test_a_mirrored_column_is_recovered_from_a_blocking_well_off
F5 a semi-sharp run admitted test_refusals_name_their_field_before_fitting
F6 (the Jacobian by differences) costs time only: tests/live/reference_fit.py's header says how much."""
@classmethod
def setUpClass(cls):
cls.orchid = json.loads((Path(__file__).resolve().parent / "fixtures" / "orchid_c09_traces.json").read_text(encoding="utf-8"))
def test_the_projection_derivative_is_the_projections(self):
cam, X = camera(cloud(), 35, 20, 50), cloud()
u, J = core._drawn(cam, FIT_FRAME, X)
self.assertLess(np.abs(u - core.seen(cam, FIT_FRAME, X)).max(), 1e-9)
self.assertLess(np.abs(core.seen(cam, FIT_FRAME, X) - core.project(cam, X @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3])).max(), 1e-9) # seen is project past the frame
for c in range(3):
step = np.zeros(3)
step[c] = 1e-6
numeric = (core.seen(cam, FIT_FRAME, X + step) - core.seen(cam, FIT_FRAME, X - step)) / 2e-6
self.assertLess(np.abs(numeric - J[:, :, c]).max(), 1e-4 * np.abs(J).max())
self.assertIsNone(core._drawn(cam, np.eye(4), np.array([cam["C"]]) - np.array(cam["R"])[2] * -1.0)) # a point behind it
def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self):
"""fit-recovers, F4: each of three views alone, both halves traced, from blockings 0.10 m and 0.30 m off.
Shipped: the built run ends within 0.67 mm of the true crease (the 3 mm asked is a tolerance round a known
truth) and the worst trace is explained within 0.196 px. F4 (no end terms): the run stops short of its
traces, three fits are refused at 3.6 px and up, and the worst it explains reads 2.06 px: the bound is the
geometric mean of 0.196 and 2.06, separation 3.2 each side."""
worst = 0.0
for A, w in ((0.2, 2.5), (0.1, 5.0), (0.4, 1.0)):
for share in (0.05, 0.15):
truth, document = blocked(A, w, share)
self.assertGreater(off_truth(document, truth), 0.09)
for cam in fit_views(truth):
out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam)
worst = max(worst, off_truth(out["sheet"], truth))
self.assertLess(max(row["unexplained_px"] for row in out["traces"]), 0.64)
self.assertEqual(len(out["points"]), FIT_K)
self.assertLess(worst, 0.003)
def test_an_overdrawn_stroke_is_refused_naming_its_trace(self):
"""overdraw-refused, F1: the mirrored half's trace doubled back over part of itself 3% of its extent off.
All 27 are refused, naming the trace and the span that no built run draws; the least unexplained reads
8.98 px against the 3 asked, separation 3.0. F1 returns all 27 as fits, the worst 0.104 m off the truth."""
truth, document = blocked(0.2, 2.5, 0.05)
least = 1e9
for cam in fit_views(truth):
a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])
for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)):
for kind in ("mid", "truth-last", "truth-first"):
with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[[01]\] is not explained: \d+ px of the trace, between \d+ and \d+ px along it") as caught:
fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.03, kind)), cam)
least = min(least, max(row["unexplained_px"] for row in caught.exception.traces))
self.assertGreater(least, 3.0 * 1.2) # lodur:ruling:deterministic-bound-margin's least separation
def test_an_accepted_fit_is_within_its_own_reported_reach(self):
"""accepted-bounded: the same strokes 0.2% off pass as explained (they are under 3 px from one line), and
every accepted fit stands within tol x the worst m_per_px it reports of the truth: all 27 are accepted,
the worst 8.9 mm off, 0.024 of that reach (F2 reads 0.27 of its own). No mutant claims this bound."""
truth, document = blocked(0.2, 2.5, 0.05)
accepted, most = 0, 0.0
for cam in fit_views(truth):
a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])
for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)):
for kind in ("mid", "truth-last", "truth-first"):
try:
out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam)
except core.ReferenceFitError:
continue
accepted += 1
most = max(most, off_truth(out["sheet"], truth) / (3.0 * max(row["m_per_px"] for row in out["points"])))
self.assertEqual(accepted, 27)
self.assertLess(most, 1.0)
def test_one_trace_alone_reads_as_held_by_the_blocking(self):
"""F3: one half traced in one view decides nothing along the sight line, and the prior is all that holds
each point there: prior_share reads 1.0, its ceiling. F3 (the prior left out of S) reads 771366."""
truth, document = blocked(0.2, 2.5, 0.05)
cam = fit_views(truth)[0]
shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam)["points"]]
self.assertEqual((min(shares), max(shares)), (1.0, 1.0))
def test_the_sight_line_reading_holds_the_points_slide_along_its_run(self):
"""F2: m_per_px is along the sight line whole. This column recedes along the view (its tangent 24 to 38
degrees off the sight line), so with both halves traced, which decide the built run to 0.2 mm, an inner
cage point still slides along its own run on the prior alone and reads a prior_share of 0.633 to 0.88; the
ends, which hold, read 0.024 and under. F2 (the ray's part across the tangent) reads the inner points 0.039
at most: the bound is the geometric mean of 0.633 and 0.039, separation 4.0 each side."""
truth, document = blocked(0.2, 2.5, 0.05)
cam = fit_views(truth)[0]
shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam)["points"]]
self.assertGreater(min(shares[1:-1]), 0.157)
self.assertLess(max(shares[0], shares[-1]), 0.157)
self.assertLessEqual(max(shares), 1.0)
def orchid_strip(self):
return strip(np.array(self.orchid["blocking"]))
def orchid_fit(self, lines, tol):
document, run = self.orchid_strip(), {"column": 1, "from": 0, "to": 7}
traces = [{"camera": "Concept", "run": run, "side": side, "line": line} for side, line in lines]
return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces), tol=tol)
ORCHID_TOL = 18.5 # px: the geometric mean of 9.2, the pair's unexplained reading as drawn, and 37.3, its reading with the right trace moved 40 px: separation 2.0 each side
def test_orchid_c09_hand_traces(self):
"""orchid-c09: the inboard edges of two petals traced by hand on one concept view, through a camera solved
from hand marks (13 px rms). At the default 3 px the pair is refused: the left trace's first 10 px stand up
to 9.2 px off the built run, because the two traces' tips are not one point and its mirror image through
that camera (the right trace reads 2.4 px). Asked at ORCHID_TOL the pair is explained, and the worst
prior_share of its points is 0.119 (0.024 m per px); either trace alone reads 1.0 on every point: the bound
is the geometric mean of 0.119 and 1.0, separation 2.9 each side. The right trace moved 40 px is refused."""
left, right, side = self.orchid["left"], self.orchid["right"], self.orchid["left_side"]
with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained: 11 px of the trace, between 0 and 10 px along it, .* up to 9\.2 px"):
self.orchid_fit([(side, left), (-side, right)], 3.0)
pair = self.orchid_fit([(side, left), (-side, right)], self.ORCHID_TOL)
self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), self.ORCHID_TOL / 2.0)
self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.345)
self.assertEqual(pair["sheet"]["rings"][3][0], self.orchid_strip()["rings"][3][0]) # only the traced column moves
for alone in ([(side, left)], [(-side, right)]):
self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone, self.ORCHID_TOL)["points"]), 0.345)
with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained") as caught:
self.orchid_fit([(side, left), (-side, (np.array(right) + [0.0, 40.0]).tolist())], self.ORCHID_TOL)
self.assertGreater(max(row["unexplained_px"] for row in caught.exception.traces), self.ORCHID_TOL * 2.0)
def test_refusals_name_their_field_before_fitting(self):
"""refusals, F5 (which takes the semi-sharp run as far as its end and refuses it there for another cause)."""
truth, document = blocked(0.2, 2.5, 0.05)
cam = fit_views(truth)[0]
a = core.seen(cam, FIT_FRAME, truth)
column = np.array(document["rings"])[:, 1]
crossed = strip(column)
crossed["creases"].append({"ring": 4, "from": 0, "to": 2, "weight": 1.0})
big = strip(core.resampled(column, 64))
big["rings"] = [[ring[0]] + [[ring[1][0] + 0.01 * j, ring[1][1], ring[1][2]] for j in range(30)] for ring in big["rings"]]
whole = {"column": 1, "from": 0, "to": 63}
for sheet_, traces, cams, message in (
(strip(column, weight=0.6), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 0 of its run has crease weight 0\.6"),
(strip(column, last=FIT_K - 2), [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K - 2})], [cam], r"^traces\[0\]: the last end of its run does not hold: it is a dart"),
(strip(column, last=FIT_K - 2), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 8 of its run has crease weight 0\b"),
(crossed, pair_traces(a), [cam], r"^traces\[0\]: point 4 of its run is held or pulled by more than the run"),
(document, pair_traces(a), [None], r"^traces\[0\]\.camera 'View' is no camera"),
(document, [dict(pair_traces(a)[0], line=[[10.0, 20.0]])], [cam], r"^traces\[0\]: its line must be two or more"),
(document, [dict(pair_traces(a)[0], side=2)], [cam], r"^traces\[0\]\.side must be 1"),
(document, [dict(pair_traces(a)[0], run={"column": 3, "from": 0, "to": 2})], [cam], r"^traces\[0\]\.run must name a column under 3"),
(document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 2})], [cam], r"^traces\[0\]: the first end of its run does not hold"),
({"verts": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "faces": [[0, 1, 2, 3]]}, pair_traces(a), [cam], r"^the sheet is a free cage"),
(big, [dict(pair_traces(a)[0], run=whole)], [cam], r"would be about \d+ characters, over the 16000 a receipt carries: nothing was fitted")):
with self.assertRaisesRegex(core.ReferenceFitError, message):
core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams)
@unittest.skipIf(np is None, "numpy")
class CameraTests(unittest.TestCase):
CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX}