brokkr_reference fit: a trace is asked at its 90th percentile past 5% at each end (tol 5), the reading is depth across the run, and a free cage is fitted by its vertex chains

The gate on a trace's worst point read the Orchid pair's tip (9.20 px) and its least 1% overdraw (9.12) alike;
the trimmed percentile reads them 0.69 and 4.27, and the pair is accepted at the default. TRIM, PART and TOL
are pinned from Soul's 296 fits by lodur:ruling:deterministic-bound-margin (FitTests' docstring states the
sets, and what the default does not separate). m_per_px leaves a point's slide along its own run out: pairs
read 0.080 at most, a single trace's inner points 0.503 and up. fit_sheet takes {verts: [...]} runs on a free
cage through Sheet.mirror_of; miss_px is gone, worst_px is reported beside the reading.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 05:22:49 +01:00
commit 5b460c5394
4 changed files with 268 additions and 130 deletions

View file

@ -215,10 +215,10 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator):
only where the built runs explain every trace; nothing is written"""
bl_idname = "brokkr_reference.fit_shell"
bl_label = "Fit Shell To Traces"
object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame")
traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to}, side, line: [[u, v], ...]}")
object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame")
traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to} on a loft or {verts: [v, ...]} on a free cage, side, line: [[u, v], ...]}")
share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does")
tol: bpy.props.FloatProperty(name="Tolerance", default=3.0, min=0.09, max=100.0, description="Pixels: every point of every trace must lie this near its built run, or the fit is refused")
tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace, its ends apart, must lie this near its built run, or the fit is refused")
# the action table states share from 0.001 and tol from 0.1: a float property rounds those up, so its bounds stand just under
def work(self, context):

View file

@ -136,7 +136,7 @@
},
{
"name": "brokkr_reference.fit_shell",
"doc": "Fit a kitbash loft shell's sheet to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where every point of every trace lies within tol px of its built run; otherwise it is refused naming the trace and the span. Writes nothing. Per moved point: metres per pixel along its sight line and the prior's share of that (docs/reference.md).",
"doc": "Fit a kitbash shell's sheet (a loft or a free cage) to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where nine tenths of every trace, 5% left out at each end, lies within tol px of its built run; otherwise it is refused naming the trace, its reading and the span. A very unsteady hand and a 1 to 2% overdraw read alike: each trace's reading (unexplained_px) and worst point (worst_px) are in the report to judge by. Writes nothing. Per moved point: metres of depth across its run per pixel, and the prior's share of that: under 0.2 the traces decide the point, over it the blocking holds it (docs/reference.md).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -147,7 +147,7 @@
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "a loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame"
"doc": "a shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame"
},
{
"name": "traces",
@ -155,7 +155,7 @@
"required": true,
"minLength": 2,
"maxLength": 12000,
"doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from `from` to `to`"
"doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} on a loft, {verts: [v, ...]} on a free cage, in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from the run's first point to its last"
},
{
"name": "share",
@ -170,8 +170,8 @@
"type": "number",
"minimum": 0.1,
"maximum": 100,
"default": 3,
"doc": "pixels: every point of every trace must lie this near its built run, or the fit is refused"
"default": 5,
"doc": "pixels: nine tenths of every trace, its ends apart, must lie this near its built run, or the fit is refused"
}
]
}

View file

@ -452,6 +452,9 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05):
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
TRIM = 0.05 # of a trace's length, left out at each end where a trace is asked whether its run explains it: a hand trace's tip is where two traces cannot agree
PART = 90 # the percentile of the rest of the trace's distances from its built run that fit_runs reads against tol
TOL = 5.0 # pixels. tests/test_reference.py FitTests states the sets TRIM, PART and TOL were read from, and what they do not separate
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)
@ -525,7 +528,7 @@ def _hard_runs(cage, runs):
"more hard edges meet, or on the rim")
def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0):
def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL):
"""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
@ -537,21 +540,24 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0):
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
tol pixels: of each trace less TRIM of its length at each end, PART in a hundred 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.
(V, report): the cage's vertices as fitted and {"traces": [{"unexplained_px": the reading tol is asked of,
"worst_px": the whole 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 in depth across its run per pixel of error in
the traces: along the part of its sight line that stands across the run's tangent there (the worst of the
traces that draw it), 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). A point's slide along its own run is left out: the traces do not decide it and it
does not move the built run. prior_share is m_per_px 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."""
names the trace, its reading 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():
@ -626,12 +632,16 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0):
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)
ends = int(TRIM * len(dense))
reading = float(np.percentile(off[ends:len(dense) - ends], PART))
traces.append({"unexplained_px": round(reading, 3), "worst_px": round(float(off.max()), 3)})
if reading > tol and refused is None:
out = (ends + np.flatnonzero(off[ends:len(dense) - ends] > 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")
f"more than {tol:g} px from the run as built ({reading:.1f} px at the {PART}th of a hundred, {TRIM:.0%} of the trace left out at each end; up to "
f"{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. A very unsteady hand reads the same as a slight "
"overdraw: if the trace is one clean stroke, ask again with tol over this reading")
if refused is not None:
error = ReferenceFitError(refused)
error.traces = traces
@ -645,36 +655,37 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0):
block[np.ix_(held, held)] = S[np.ix_(cols[held], cols[held])]
worst = 0.0
for _, (cam, frame), _, _, source, sign, _ in prepared:
run = V[source] * sign
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)))
sight = run[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3]
along = run[min(m + 1, len(run) - 1)] - run[max(m - 1, 0)]
sight = sight - (sight @ along) / (along @ along) * along
if np.linalg.norm(sight) > 1e-9: # a run seen end on has no depth across itself
sight = sight / np.linalg.norm(sight) * sign[m] # 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):
def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL):
"""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",
{"run", "side": 1 or -1, "line": [[u, v], ...]} and `cams` the camera record of each. A loft's run is {"ring":
i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, a free cage's {"verts": [v, ...]}: authored
indices, as the sheet's creases name runs. Side -1 is the mirrored half of a mirrored sheet (cage.mirror_of);
the line is drawn from the run's first point to its last. The points of the traced runs move, one on the
mirror plane only in it. Returns {"sheet": the document with those points moved, "traces": [{"unexplained_px",
"worst_px"}], "points": [{"ring", "point" (a loft) or "vertex" (a free cage), "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
R, N, mirror_of = cage.rings, cage.points, np.asarray(cage.mirror_of)
loft, authored = R is not None, np.flatnonzero(mirror_of == np.arange(len(mirror_of)))
twin = np.arange(len(mirror_of)) # an authored vertex's reflection: itself on the mirror plane
twin[mirror_of[mirror_of != twin]] = np.flatnonzero(mirror_of != twin)
C = ((N + 1) // 2 if mirror else N) if loft else None
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), []
movable, runs = np.zeros((len(mirror_of), 3), bool), []
for k, trace in enumerate(traces):
where = f"traces[{k}]"
if not isinstance(trace, dict) or not isinstance(trace.get("run"), dict):
@ -684,31 +695,40 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=3.0):
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))]
if loft:
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}}: the sheet is a loft")
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_
chain = [i * N + (C - 1 if mirror else 0) + j for i, j in ((fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1))]
else:
chain = run.get("verts")
if set(run) != {"verts"} or not isinstance(chain, list) or any(isinstance(v, bool) or not isinstance(v, int) or not 0 <= v < len(authored) for v in chain):
raise ReferenceFitError(f"{where}.run must be {{verts: [v, ...]}}, authored vertices under {len(authored)} in the run's order: the sheet is a free cage")
for v in chain:
movable[v] = (twin[v] != v or not mirror, True, True)
runs.append({"name": where, "chain": chain if side == 1 else [int(twin[v]) for v in chain], "view": k, "line": trace.get("line")})
moved = [int(v) 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"])]}
out, points = copy.deepcopy(document), []
for v, row in zip(moved, report["points"]):
place = {"ring": v // N, "point": v % N - (C - 1 if mirror else 0)} if loft else {"vertex": v}
point = [round(float(x), 6) + 0.0 for x in V[v]]
if loft:
out["rings"][place["ring"]][place["point"]] = point
else:
out["verts"][v] = point
points.append({**place, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4), "prior_share": round(row["prior_share"], 3)})
return {"sheet": out, "traces": report["traces"], "points": points}
# --- fields ----------------------------------------------------------------------------------------------------------

View file

@ -20,6 +20,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once
"""
from __future__ import annotations
import copy
import importlib.util
import json
import math
@ -444,16 +445,59 @@ def off_truth(document, truth):
return max(float(core._off(run, truth).max()), float(core._off(truth[[0, -1]], run).max()))
def hand(line, sigma, rng, corr=30.0, jitter=0.7, tip=6.0):
"""`line` as a hand draws it: a wander of `sigma` px that holds over `corr` px, a jitter on every point, and
each tip (its 10 px) set off whole by about `tip` px."""
s = np.r_[0, np.cumsum(np.linalg.norm(np.diff(line, axis=0), axis=1))]
grid = np.arange(0, s[-1] + corr, corr / 2)
wander = rng.normal(0, 1, (len(grid), 2))
out = line + sigma * np.stack([np.interp(s, grid, wander[:, k]) for k in range(2)], 1) + rng.normal(0, jitter, line.shape)
out[s < 10] += rng.normal(0, 1, 2) * tip
out[s > s[-1] - 10] += rng.normal(0, 1, 2) * tip
return out
def free_strip(points=6):
"""A mirrored free cage three columns wide (x 0 on the mirror plane, 0.5, 1) whose middle column is a hard
crease, and that column's vertices in order."""
verts = [[x, -1 + 2 * i / (points - 1), 0.5 - x * x + 0.1 * math.sin(3 * i / (points - 1)) * (c == 1)] for c, x in enumerate((0.0, 0.5, 1.0)) for i in range(points)]
faces = [[c * points + i, c * points + i + 1, c * points + i + 1 + points, c * points + i + points] for c in range(2) for i in range(points - 1)]
chain = list(range(points, 2 * points))
return {"verts": verts, "faces": faces, "creases": [[a, b, 1.0] for a, b in zip(chain, chain[1:])], "mirror": True, "rim": 1.0}, chain
@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:
explain the traces. 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."""
G1 m_per_px along the sight line whole test_a_mirrored_column_is_recovered_from_a_blocking_well_off
G2 the gate on the trace's worst point (PART 100) test_hand_traces_are_explained_at_the_default
G3 a point on the mirror plane free to leave it test_a_spine_on_the_mirror_plane_stays_on_it
G4 a run's last index allowed one past the sheet test_refusals_name_their_field_before_fitting
G5 the prior's share not scaled by the diagonal test_one_trace_alone_reads_as_held_by_the_blocking
G6 the gate at 1.2 x tol test_an_overdrawn_stroke_is_refused_naming_its_trace
G7 a free cage's mirrored half read as the authored test_a_free_cage_is_fitted_by_its_vertex_chains
G8 the prior in the Jacobian and not the residual test_one_trace_alone_reads_as_held_by_the_blocking
core.TRIM, core.PART and core.TOL were read from 296 fits kept outside the suite (108 hand traces by `hand`,
wander 1, 2 and 4 px; 108 strokes by `overdrawn` 1, 2, 3 and 5% off; the Orchid pair, moved and overdrawn).
Read as the PART-th percentile past TRIM at each end, the traces to accept read 3.26 px at most (the 72 hand
traces of wander 1 and 2 px; the Orchid pair 0.69) and the least to refuse 7.65 (the Orchid's traces overdrawn
2%; the strokes 3% off 7.83): TOL is their geometric mean, separation 1.53 each side. The trace's worst point,
which that reading replaces, read 9.20 on the Orchid pair against 9.12 on its least 1% overdraw. What TOL does
not separate: 31 of the 36 hand traces of wander 4 px are accepted (they read up to 5.96), 9 of 27 strokes 1%
off and 3 of 18 Orchid 1% overdraws are accepted (from 2.63 and 4.27), and the strokes 2% off are refused from
5.34 with no margin. A very unsteady hand and a slight overdraw read alike; the report carries the reading.
Unclaimed, with readings: TRIM 0 (the hand traces read 3.76 against 3.26, the Orchid 0.80 against 0.69:
separation 1.15); F6, the Jacobian by differences (time only: tests/live/reference_fit.py's header);
the least, in place of the worst, of the traces that draw a point (the 18 pairs' greatest prior_share reads 0.060
against 0.080, both under PAIR_FROM_SINGLE; one point's two readings differ up to 4.3 times); the guard on a run
seen end on (the reading is dropped either way)."""
@classmethod
def setUpClass(cls):
@ -471,28 +515,56 @@ class FitTests(unittest.TestCase):
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
def families(self):
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)
yield truth, document, cam
PAIR_FROM_SINGLE = 0.2 # prior_share: the geometric mean of 0.080, the most any point of the 18 mirrored pairs reads, and 0.503, the least an inner point of the 18 single traces reads: separation 2.5 each side
def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self):
"""fit-recovers, F4 and G1: 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 point of any trace stands 0.196 px off its run. F4 (no end terms): the run stops
short of its traces and the worst reads 2.06 px and up: the bound is the geometric mean of 0.196 and 2.06,
separation 3.2 each side. Every point reads a prior_share under PAIR_FROM_SINGLE: the pair decides it. G1
(the sight line whole, a point's slide along its own run counted in) reads inner points up to 0.95."""
worst = 0.0
for truth, document, cam in self.families():
self.assertGreater(off_truth(document, truth), 0.09)
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["worst_px"] for row in out["traces"]), 0.64)
self.assertEqual(len(out["points"]), FIT_K)
self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE)
self.assertLess(worst, 0.003)
def test_one_trace_alone_reads_as_held_by_the_blocking(self):
"""F3, G5, G8: one half traced in one view decides nothing along the sight line. The same 18 fits with one
trace end 17.6 to 355 mm off the truth (G8, the prior left out of the residual, lets the nearest drift to 11.2:
the bound is their geometric mean, separation 1.25 each side), and every inner point reads a prior_share over PAIR_FROM_SINGLE
(0.503 to 1.0, the sine of the angle its run stands off the sight line; an end seen along its run reads
down to 0.005, and its depth across the run is decided). F3 (the prior left out of S) reads 771366 where
the ceiling is 1. m_per_px is prior_share x share x the sheet's diagonal (2.77 m here); G5 leaves the
diagonal out."""
for truth, document, cam in self.families():
out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam)
shares = [row["prior_share"] for row in out["points"]]
self.assertGreater(min(shares[1:-1]), self.PAIR_FROM_SINGLE)
self.assertLessEqual(max(shares), 1.0)
self.assertGreater(off_truth(out["sheet"], truth), 0.014)
diagonal = float(np.linalg.norm(np.ptp(kit.sheet(document).V, axis=0)))
for row in out["points"][1:-1]:
self.assertAlmostEqual(row["m_per_px"] / row["prior_share"], 0.1 * diagonal, delta=0.01 * diagonal)
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."""
"""overdraw-refused, F1 and G6: 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 reads 7.83 px
against core.TOL, separation 1.57. F1 returns all 27 as fits, the worst 0.104 m off the truth. Asked with
tol 1.1 times its own reading a stroke is accepted, and with tol that reading over 1.1 refused: tol is what
the reading is held to (G6 holds it to 1.2 x tol)."""
truth, document = blocked(0.2, 2.5, 0.05)
least = 1e9
for cam in fit_views(truth):
@ -501,78 +573,119 @@ class FitTests(unittest.TestCase):
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)
self.assertEqual(set(caught.exception.traces[0]), {"unexplained_px", "worst_px"})
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
self.assertGreater(least, core.TOL * 1.2) # lodur:ruling:deterministic-bound-margin's least separation
traces = pair_traces(a, overdrawn(b, 0.3, 0.7, 0.03, "mid"))
with self.assertRaises(core.ReferenceFitError) as caught:
fitted(document, traces, cam)
reading = max(row["unexplained_px"] for row in caught.exception.traces)
self.assertAlmostEqual(max(row["unexplained_px"] for row in fitted(document, traces, cam, tol=reading * 1.1)["traces"]), reading, delta=0.002)
with self.assertRaises(core.ReferenceFitError):
fitted(document, traces, cam, tol=reading / 1.1)
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."""
def test_hand_traces_are_explained_at_the_default(self):
"""G2: both halves traced by `hand` (wander 2 px, tips 6 px off), each of three views. All three are
accepted at core.TOL, reading 2.97 px at most (TOL over 1.68), while the worst point of a trace stands 6.94
px off its run and, the tips left out, still 5.82 to 6.94: G2, which holds that point to TOL, refuses all
three. The fits end 20 to 64 mm off the true crease, up to 1.36 times TOL x the m_per_px they report:
m_per_px is what one pixel of error on a single point moves, and a wander that holds over 30 px moves
more."""
truth, document = blocked(0.2, 2.5, 0.05)
rng, most = np.random.default_rng(1), 0.0
for cam in fit_views(truth):
a, b = hand(core.seen(cam, FIT_FRAME, truth), 2.0, rng), hand(core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]), 2.0, rng)
out = fitted(document, pair_traces(a, b), cam)
self.assertLess(max(row["unexplained_px"] for row in out["traces"]), core.TOL / 1.2)
most = max(most, max(row["worst_px"] for row in out["traces"]))
self.assertGreater(most, core.TOL * 1.2)
def test_a_clean_fit_is_within_its_own_reported_reach(self):
"""accepted-bounded, on clean strokes only: strokes doubled back 0.2% off pass as explained, and each
accepted fit stands within core.TOL x the worst m_per_px it reports of the truth: all 27 are accepted, the
worst 8.9 mm off, 0.161 of that reach. No mutant claims this bound, and hand traces pass it
(test_hand_traces_are_explained_at_the_default)."""
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
out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam)
accepted += 1
most = max(most, off_truth(out["sheet"], truth) / (3.0 * max(row["m_per_px"] for row in out["points"])))
most = max(most, off_truth(out["sheet"], truth) / (core.TOL * 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_a_spine_on_the_mirror_plane_stays_on_it(self):
"""G3: a mirrored sheet's column 0 is on the mirror plane and has no partner; the plane decides its depth.
Traced in one view from a blocking 0.07 m off, its points keep x = 0 and the built run ends 0.15 mm
from the true spine, every point reading a prior_share of 0.019 or under. G3 (x free there) leaves the run as far off as a single trace is."""
t = np.linspace(0, 1, FIT_K)
spine = np.stack([0 * t, -1 + 2 * t, 0.5 + 0.3 * t * t], 1)
sheet_ = {"mirror": True, "rim": 1.0, "creases": [{"column": 0, "from": 0, "to": FIT_K - 1, "weight": 1.0}],
"rings": [[[0.0, float(p[1]) + 0.05, float(p[2]) + 0.05], [0.4, float(p[1]), float(p[2]) - 0.1], [0.9, float(p[1]), float(p[2]) - 0.3]] for p in spine]}
built = core.crease_run(core.crease_run(spine))
cam = fit_views(built)[0]
out = fitted(sheet_, [{"camera": "View", "run": {"column": 0, "from": 0, "to": FIT_K - 1}, "side": 1, "line": core.seen(cam, FIT_FRAME, built).tolist()}], cam)
column = np.array(out["sheet"]["rings"])[:, 0]
self.assertEqual(float(np.abs(column[:, 0]).max()), 0.0)
self.assertLess(float(core._off(core.resampled(core.crease_run(core.crease_run(column)), 400), built).max()), 0.001)
self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE)
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 test_a_free_cage_is_fitted_by_its_vertex_chains(self):
"""free-cage, G7: a mirrored free cage's crease, six vertices, both halves traced in one view from a
blocking 0.057 m off: the built run ends 0.45 mm from the true one, the six traced vertices are the only
ones moved, each with a row naming its vertex and a prior_share under PAIR_FROM_SINGLE (0.036 at most). The
mirrored half is the reflections the cage's own parser lists (Sheet.mirror_of); G7 reads it as the authored
half and the fit is refused, the second trace unexplained."""
truth, chain = free_strip()
run = core.crease_run(core.crease_run(np.array(truth["verts"])[chain]))
cam = fit_views(run)[0]
document, bump = copy.deepcopy(truth), np.random.default_rng(1).normal(0, 0.06, (len(chain), 3))
for v, d in zip(chain, bump):
document["verts"][v] = [float(x) for x in np.array(truth["verts"][v]) + d]
off = lambda sheet_: float(core._off(core.resampled(core.crease_run(core.crease_run(np.array(sheet_["verts"])[chain])), 400), run).max()) # noqa: E731
traces = [{"camera": "View", "run": {"verts": chain}, "side": side, "line": core.seen(cam, FIT_FRAME, run * [side, 1, 1]).tolist()} for side in (1, -1)]
out = fitted(document, traces, cam)
self.assertGreater(off(document), 0.05)
self.assertLess(off(out["sheet"]), 0.001)
self.assertEqual([row["vertex"] for row in out["points"]], chain)
self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE)
self.assertTrue(all(out["sheet"]["verts"][v] == document["verts"][v] for v in range(len(document["verts"])) if v not in chain))
self.assertTrue(np.array_equal(kit.sheet(document).mirror_of, np.r_[np.arange(18), np.arange(6, 18)])) # the six on the mirror plane are shared, the twelve others reflected after them
def orchid_strip(self):
return strip(np.array(self.orchid["blocking"]))
def orchid_fit(self, lines, tol):
def orchid_fit(self, lines):
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
return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces))
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."""
from hand marks (13 px rms). At the default the pair is explained: its traces read 0.69 and 0.64 px (TOL
over 7.2), though 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 gate on the worst point
refused the pair for that. Its points read a prior_share of 0.018 at most; either trace alone reads 0.271
and up on every point: the bound is their geometric mean, separation 3.9 each side. The right trace
overdrawn 2% of its extent is refused nine ways of nine, reading 7.65 px and up."""
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)
pair = self.orchid_fit([(side, left), (-side, right)])
self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), core.TOL / 1.2)
self.assertGreater(pair["traces"][0]["worst_px"], core.TOL * 1.2)
self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.07)
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)
self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone)["points"]), 0.07)
least = 1e9
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\[1\] is not explained") as caught:
self.orchid_fit([(side, left), (-side, overdrawn(np.array(right), start, stop, 0.02, kind))])
least = min(least, caught.exception.traces[1]["unexplained_px"])
self.assertGreater(least, core.TOL * 1.2)
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)."""
@ -595,7 +708,12 @@ class FitTests(unittest.TestCase):
(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"),
(document, [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K})], [cam], r"^traces\[0\]\.run must name a column under 3 and from under to, to at most 9$"),
(document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 3})], [cam], r"^traces\[0\]\.run must name a ring under 10 and from under to, to at most 2$"),
(document, [dict(pair_traces(a)[0], run={"verts": [0, 1]})], [cam], r"^traces\[0\]\.run must be \{ring, from, to\} or \{column, from, to\}: the sheet is a loft"),
(free_strip()[0], pair_traces(a), [cam], r"^traces\[0\]\.run must be \{verts: \[v, \.\.\.\]\}, authored vertices under 18 in the run's order: the sheet is a free cage"),
(free_strip()[0], [dict(pair_traces(a)[0], run={"verts": [6, 18]})], [cam], r"^traces\[0\]\.run must be \{verts"),
(free_strip()[0], [dict(pair_traces(a)[0], run={"verts": [0, 6]})], [cam], r"^traces\[0\]: the first end of its run does not hold"), # a rim run from the mirror plane runs on across it
(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)
@ -687,7 +805,7 @@ class HostFileTests(unittest.TestCase):
with self.assertRaises(at.IntentInvalid):
at.validate({**intent, **bad}, self.host)
fit = {**self.envelope, "action": "brokkr_reference.fit_shell", "object_name": "Plate", "traces": "[{}]"}
self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, 3))
self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, core.TOL))
for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}):
with self.assertRaises(at.IntentInvalid):
at.validate({**fit, **bad}, self.host)