From ef806e57771ca9a86b76f20c5a5920bf2f77119e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:14:45 +0100 Subject: [PATCH] brokkr_reference.core: a reference view's camera solved from marked points Ported from round 9's experiments/mechs/camsolve.py (3f45b67). The focal length is held to 4-4000 mm at the box's width; the record carries lens_band (an equal-error band, walked to the first miss or the bound) and lens_at_bound; square snaps the yaw to a quarter turn; solve refuses by ReferenceError naming the cause; camera_of reads blender() back. Place is solved as a dolly-zoom offset so log f alone is the distance-lens trade, and a parameter held at a bound sits out of the LM step. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 333 ++++++++++++++++++++++ surfaces/blender/tests/test_reference.py | 250 ++++++++++++++++ 2 files changed, 583 insertions(+) create mode 100644 surfaces/blender/brokkr_reference/core.py create mode 100644 surfaces/blender/tests/test_reference.py diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py new file mode 100644 index 0000000..f9f4bf9 --- /dev/null +++ b/surfaces/blender/brokkr_reference/core.py @@ -0,0 +1,333 @@ +"""The camera of a reference view, solved from marked points. numpy and the standard library; no Blender. + +A reference image (a concept sheet, a render, a photograph) draws a view through some camera nobody wrote down. +Given points whose place in the world is known (a build's joints, sockets or vertices) and the pixel where the +image draws each, solve() finds the pinhole camera that draws them there: where it stands, how it is turned and +its focal length, all at once (PnP with the focal length unknown), by Levenberg-Marquardt from a grid of starts +round the points. docs/reference.md says what the answer is worth; in short, six or more points not all in one +plane decide the camera, and a long or square-on view decides everything but how far off it stands: distance and +focal length trade against each other (a dolly zoom), and "lens_band" says how far. + + world x right, y forward, z up, metres + pixels the image's, in whatever unit the points were marked in; v down + camera looks down its own -z, y up (Blender's); "R" turns world to camera; "f" is in pixels; "c" is the + principal point, at the middle of the view's box unless the model solves it (MODELS) + misses are weighed by a pseudo-Huber loss (SOFT pixels): a build poses some points elsewhere than the image + draws them, and those should not turn the camera + lens millimetres on a SENSOR mm sensor across the box's width, held inside LENS_MM + + solve(world, pixels, box, model="auto") the camera record, a dict that goes to JSON + project(cam, points) pixels of world points + ray(cam, pixel) (origin, unit direction) of a pixel's line of sight, in the world + lift(cam, pixel, plane_point, plane_normal) where that line of sight meets a plane: a traced 2D point made 3D + blender(cam, width) what a Blender camera takes to be this one, the frame being the box + camera_of(params, box) the record of a Blender camera: blender() read back + in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders + points(text, size), numbers(text, count) the action's string fields +""" +from __future__ import annotations + +import math + +import numpy as np + +SOFT = 10.0 # pixels: about the error of a point marked by hand; a point the build poses elsewhere misses by several times that +SENSOR = 36.0 # mm, fitted to the box's width +LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a view is orthographic to any marking, and an unbounded solve runs off (docs/reference.md) +BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best +STEP = 0.1 # the band is walked in steps of this in log f +MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead +QUARTER = math.pi / 2 + + +class ReferenceError(ValueError): # noqa: A001 the package's refusal; the builtin of the same name (weakref) is not used here + """solve() or a field parser cannot take what it was given; the message names which.""" + + +def _rotation(yaw, pitch, roll): + """World to camera for a camera whose line of sight is turned `yaw` about the world's z from looking along +y, + pitched up by `pitch`, and rolled about its line of sight.""" + cy, sy, cp, sp, cr, sr = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch), math.cos(roll), math.sin(roll) + look = np.array([-sy * cp, cy * cp, sp]) + right = np.array([cy, sy, 0.0]) + up = np.array([sy * sp, -cy * sp, cp]) # right x look + r, u = cr * right + sr * up, -sr * right + cr * up + return np.stack([r, u, -look]) + + +def project(cam, points): + """Pixels (n, 2) of world points (n, 3). A point behind the camera comes back far off the frame.""" + q = (np.asarray(points, float) - np.asarray(cam["C"], float)) @ np.asarray(cam["R"], float).T + z = np.where(q[:, 2] < -1e-6, -q[:, 2], 1e-6) + return np.stack([cam["c"][0] + cam["f"] * q[:, 0] / z, cam["c"][1] - cam["f"] * q[:, 1] / z], 1) + + +def ray(cam, pixel): + d = np.array([(pixel[0] - cam["c"][0]) / cam["f"], -(pixel[1] - cam["c"][1]) / cam["f"], -1.0]) @ np.asarray(cam["R"], float) + return np.asarray(cam["C"], float), d / np.linalg.norm(d) + + +def lift(cam, pixel, plane_point, plane_normal): + o, d = ray(cam, pixel) + n = np.asarray(plane_normal, float) + return o + d * (((np.asarray(plane_point, float) - o) @ n) / (d @ n)) + + +def lm(residual, p, low=None, high=None, rounds=80): + """Levenberg-Marquardt on a residual function, its Jacobian by differences. `low` and `high` (per parameter, + infinite where free) are bounds: a step is clipped to them, a difference that would cross one is taken the + other way, and a parameter held against one is left out of the step. Returns (p, residual).""" + p = np.array(p, float) + low = np.full(len(p), -np.inf) if low is None else np.asarray(low, float) + high = np.full(len(p), np.inf) if high is None else np.asarray(high, float) + p = np.clip(p, low, high) + r = residual(p) + lam = 1e-3 + for _ in range(rounds): + J = np.empty((len(r), len(p))) + for k in range(len(p)): + h = 1e-6 * max(1.0, abs(p[k])) + if p[k] + h > high[k]: + h = -h + q = p.copy() + q[k] += h + J[:, k] = (residual(q) - r) / h + J[:, ((p <= low) & (J.T @ r > 0)) | ((p >= high) & (J.T @ r < 0))] = 0.0 # a parameter at its bound and pulled past it sits this round out, so the others take their own step + A, g = J.T @ J, J.T @ r + for _ in range(12): + try: + step = np.linalg.solve(A + lam * np.diag(np.diag(A) + 1e-12), -g) + except np.linalg.LinAlgError: + lam *= 10 + continue + q = np.clip(p + step, low, high) + r2 = residual(q) + if r2 @ r2 < r @ r: + gain = (r @ r - r2 @ r2) / max(r @ r, 1e-30) + p, r, lam = q, r2, lam / 3 + break + lam *= 4 + else: + break + if gain < 1e-12: + break + return p, r + + +def _turned(W, turned, angle, pivot): + """W with its `turned` rows turned by `angle` about the vertical through `pivot`.""" + X = W.copy() + if turned.any(): + c, s = math.cos(angle), math.sin(angle) + d = W[turned, :2] - np.asarray(pivot, float) + X[turned, 0], X[turned, 1] = pivot[0] + c * d[:, 0] - s * d[:, 1], pivot[1] + s * d[:, 0] + c * d[:, 1] + return X + + +def _fit(W, P, c0, model, logf, f_fixed=None, near=None, turned=None, pivot=(0.0, 0.0), frame=None): + """The best camera of a model over a grid of starts, or from the one start `near` (the parameter vector of a + solve of nearly the same points): (rms pixels, parameter vector, camera, the points as solved, the turn). + `logf` is (low, high), the bounds of log f. `turned` marks the points that turn together about the vertical + through `pivot` (x, y) by one more unknown angle. The vector is place (3), yaw, pitch, then roll, log f, centre + (2) and the turn, each only when solved. Place is the camera's offset from the points' middle divided by f over + the marks' extent in pixels, so that log f alone is a dolly zoom: the camera backs off as the lens grows and + the picture keeps its size. A long view decides its lens loosely, and with place in metres the solve crawled + along that trade and stopped short of where the error was least. `frame` is the (middle, extent) a `near` + vector was solved in, when its points were not quite these.""" + extra = MODELS[model] + turned = np.zeros(len(W), bool) if turned is None else np.asarray(turned, bool) + twist = bool(turned.any()) + size = np.ptp(W, axis=0).max() + centre, px = (W.mean(0), np.ptp(P, axis=0).max()) if frame is None else frame + at = 5 + ("roll" in extra) # where log f sits when it is solved + + def split(p): + p = list(p) + off, yaw, pitch = np.array(p[:3]), p[3], p[4] + del p[:5] + if "square" in extra: + yaw = QUARTER * round(yaw / QUARTER) # held: a difference of 1e-6 never crosses to the next quarter, so the yaw's column is zero and it stays at its start + roll = p.pop(0) if "roll" in extra else 0.0 + f = f_fixed if f_fixed is not None else math.exp(min(max(p.pop(0), logf[0]), logf[1])) + c = [p.pop(0), p.pop(0)] if "centre" in extra else c0 + return {"C": centre + off * (f / px), "R": _rotation(yaw, pitch, roll), "f": f, "c": np.array(c, float)}, (p.pop(0) if twist else 0.0) + + def residual(p): + cam, angle = split(p) + r = project(cam, _turned(W, turned, angle, pivot)) - P + n = np.maximum(np.hypot(r[:, 0], r[:, 1]), 1e-9) # pseudo-Huber: a miss far past SOFT pixels pulls as its distance, not its square + return (r * (np.sqrt(2 * SOFT * SOFT * (np.sqrt(1 + (n / SOFT) ** 2) - 1)) / n)[:, None]).ravel() + + starts = [] + if near is not None: + starts.append(near) + else: + for az in (range(0, 360, 90) if "square" in extra else range(-180, 180, 45)): + for dist in (1.5, 6.0): + a = math.radians(az) + d = dist * size + starts.append([-size * math.sin(a), size * math.cos(a), 0.0, a + math.pi, 0.0] + [0.0] * ("roll" in extra) + + ([] if f_fixed is not None else [math.log(px * d / size)]) + (list(c0) if "centre" in extra else []) + [0.0] * twist) + low, high = np.full(len(starts[0]), -np.inf), np.full(len(starts[0]), np.inf) + if f_fixed is None: + low[at], high[at] = logf + best = None + for start in starts: + p, r = lm(residual, start, low, high) + if best is None or r @ r < best[0] - 1e-9: + best = (float(r @ r), p) + cam, angle = split(best[1]) + X = _turned(W, turned, angle, pivot) + miss = project(cam, X) - P + return math.sqrt((miss * miss).sum() / len(W)), best[1], cam, X, angle + + +def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot): + """Leave-one-out: each point predicted by the camera solved without it; the rms of those misses, pixels.""" + miss, frame = [], (W.mean(0), np.ptp(P, axis=0).max()) + for k in range(len(W)): + keep = np.arange(len(W)) != k + start = near if turned[keep].any() or not turned.any() else near[:-1] + _, _, cam, _, angle = _fit(W[keep], P[keep], c0, model, logf, f_fixed=f_fixed, near=start, turned=turned[keep], pivot=pivot, frame=frame) + one = _turned(W[k:k + 1], turned[k:k + 1], angle, pivot) + miss.append(np.linalg.norm(project(cam, one)[0] - P[k])) + return float(np.sqrt(np.mean(np.square(miss)))) + + +def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)): + """world {name: [x, y, z]}, pixels {name: [u, v]}: the camera that draws the names both hold. `box` is the + view's box on the image [u0, v0, u1, v1]. `model` is one of MODELS: "upright" holds the camera level and its + centre at the middle of the box, "rolled" lets it roll, "free" solves the centre too (a view cropped off-axis); + "auto" takes whichever of those predicts left-out points best, since a freer model always fits the marked ones + closer. "square" is for a view drawn square-on from far off (a rear or side elevation): there the points lie + nearly in one plane across the line of sight, a turn of the camera and a narrower figure draw the same picture, + and the solve would spend the turn on the build's error in width; so the camera looks straight along a world + axis, whichever quarter turn fits best. `lens` (mm) holds the focal length instead of solving it: for a view + that must agree with another. `turned` names points that turn as one about the vertical through `pivot` (a + torso on its waist ring): the angle is solved with the camera, and "twist" is how far they turn from where + they were given. + + Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that + refit within BAND of the best rms, walked out from the best: an equal-error band, not a confidence interval), + "lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median" + (pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out, + lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll", + "twist" (degrees), "residuals" {name: [du, dv]}}. Refuses with ReferenceError.""" + if model != "auto" and model not in MODELS: + raise ReferenceError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") + box = [float(v) for v in box] + if len(box) != 4 or not all(math.isfinite(v) for v in box) or box[2] - box[0] <= 0 or box[3] - box[1] <= 0: + raise ReferenceError(f"box {box} has no {'width' if len(box) != 4 or not box[2] - box[0] > 0 else 'height'}: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0") + width = box[2] - box[0] + if lens is not None and not LENS_MM[0] <= lens <= LENS_MM[1]: + raise ReferenceError(f"lens {lens} mm is outside {LENS_MM[0]:g} to {LENS_MM[1]:g} mm") + names = [k for k in pixels if k in world] + if len(names) < 6: + raise ReferenceError(f"{len(names)} points are named in both world and pixels; six are needed") + for k in names: + if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])): + raise ReferenceError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") + W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float) + T = np.array([k in turned for k in names]) + c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] + logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR)) + fixed = None if lens is None else lens * width / SENSOR + tried = {} + for m in (("upright", "rolled", "free") if model == "auto" else (model,)): + rms, p, cam, X, angle = _fit(W, P, c0, m, logf, f_fixed=fixed, turned=T, pivot=pivot) + tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, logf, fixed, p, T, pivot)) + kind = min(tried, key=lambda k: tried[k][5]) + rms, p, cam, X, angle, left = tried[kind] + mm = lambda f: min(max(f * SENSOR / width, LENS_MM[0]), LENS_MM[1]) # noqa: E731 an end of the range reads as exactly that end + span, best = [cam["f"]], math.log(cam["f"]) + for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last, to the first that misses or to the bound + q, step = np.delete(p, 5 + ("roll" in MODELS[kind])), 1 + while True: + at = best + STEP * way * step + f = math.exp(min(max(at, logf[0]), logf[1])) + r_f, q = _fit(W, P, c0, kind, logf, f_fixed=f, near=q, turned=T, pivot=pivot)[:2] + if r_f > BAND * rms + 1e-9: + break + span.append(f) + if not logf[0] < at < logf[1]: + break + step += 1 + off = cam["C"] - X.mean(0) + res = project(cam, X) - P + worst = int(np.argmax(np.linalg.norm(res, axis=1))) + edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None + return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]], + "box": box, "lens": float(mm(cam["f"])), "lens_band": [float(mm(min(span))), float(mm(max(span)))], "lens_at_bound": edge, + "rms": float(rms), "median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))], + "left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()}, + "azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))), + "distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)), + "residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}} + + +def blender(cam, width): + """What a Blender camera takes to be this one, the frame being the view's box at `width` pixels across: + {"matrix_world" (rows), "lens" (mm), "shift_x", "shift_y", "sensor_width", "sensor_fit", "resolution" [w, h]}. + The sensor is SENSOR mm, fitted HORIZONTAL, so both shifts are in widths of the frame.""" + R, C = np.asarray(cam["R"], float), np.asarray(cam["C"], float) + M = np.eye(4) + M[:3, :3], M[:3, 3] = R.T, C + u0, v0, u1, v1 = cam["box"] + w, h = u1 - u0, v1 - v0 + return {"matrix_world": [[float(v) for v in row] for row in M], "lens": float(cam["f"] * SENSOR / w), "shift_x": float(((u0 + u1) / 2 - cam["c"][0]) / w), + "shift_y": float((cam["c"][1] - (v0 + v1) / 2) / w), "sensor_width": SENSOR, "sensor_fit": "HORIZONTAL", "resolution": [int(width), int(round(width * h / w))]} + + +def camera_of(params, box=None, width=None): + """The camera record of a Blender camera, blender() read back: {"C", "R", "f", "c", "box", "lens"}. `params` is + what blender() returns (a scene camera's matrix_world rows, lens, shifts, sensor_width and the render's + resolution; the sensor fit must be HORIZONTAL, which is what AUTO means on a frame wider than tall). `box` is + the frame in the image's pixels; without one it is the frame itself from (0, 0), `width` pixels across (the + render's own width when that is not given either).""" + if params.get("sensor_fit", "HORIZONTAL") != "HORIZONTAL": + raise ReferenceError(f"sensor fit {params['sensor_fit']!r}: camera_of reads a HORIZONTAL fit only") + M = np.asarray(params["matrix_world"], float) + if box is None: + rx, ry = params["resolution"] + width = rx if width is None else width + box = [0.0, 0.0, float(width), float(width) * ry / rx] + u0, v0, u1, v1 = (float(v) for v in box) + w = u1 - u0 + return {"C": [float(v) for v in M[:3, 3]], "R": [[float(v) for v in row] for row in M[:3, :3].T], "f": float(params["lens"] * w / params.get("sensor_width", SENSOR)), + "c": [float((u0 + u1) / 2 - params["shift_x"] * w), float((v0 + v1) / 2 + params["shift_y"] * w)], "box": [u0, v0, u1, v1], "lens": float(params["lens"] * SENSOR / params.get("sensor_width", SENSOR))} + + +def in_frame(cam, pixels, width): + """Image pixels as pixels of the frame blender() renders at `width`. The frame's height is a whole number of + pixels, so it stands up to half a pixel taller or shorter than the box about the same middle.""" + u0, v0, u1, v1 = cam["box"] + k = width / (u1 - u0) + return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2]) + + +def numbers(text, count, what): + """'1, 2.5, 3' as `count` finite floats; ReferenceError names `what`.""" + try: + values = [float(v) for v in text.split(",")] + except ValueError: + values = [] + if len(values) != count or not all(math.isfinite(v) for v in values): + raise ReferenceError(f"{what} {text.strip()!r} is not {count} finite numbers with commas between") + return values + + +def points(text, size, what): + """'a=1,2,3; b=4,5,6' as {name: [numbers]}, each of `size` numbers; ReferenceError names `what` and the entry. + A name given twice is refused: which of the two was meant is not this parser's to choose.""" + out = {} + for entry in (piece.strip() for piece in text.split(";")): + if not entry: + continue + name, _, values = entry.partition("=") + name = name.strip() + if not name: + raise ReferenceError(f"{what} entry {entry!r} has no name") + if name in out: + raise ReferenceError(f"{what} names {name!r} twice") + out[name] = numbers(values, size, f"{what} point {name!r}:") + return out diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py new file mode 100644 index 0000000..3462bb2 --- /dev/null +++ b/surfaces/blender/tests/test_reference.py @@ -0,0 +1,250 @@ +"""Reference camera tests. No Blender: brokkr_reference/core.py on seeded points drawn through known cameras, and +the host action file against Brokkr's own checker. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operator and a camera stood in a scene are exercised in a real Blender by tests/live/reference.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: a reading here is the same on every run, so a bound a mutant +claims sits at the geometric mean of the shipped reading and that mutant's, and says both. The other numbers are +tolerances round a known truth that no mutant claims. The mutants, each run once on a scratch copy: + M1 plain squares for the pseudo-Huber loss test_one_point_60_px_off_does_not_turn_the_camera + M2 auto chooses by in-sample rms test_auto_takes_the_model_that_predicts_left_out_points + M3 the lens walk restarts from the grid test_the_band_is_walked_from_the_last_solve + M4 no bound on the focal length test_long_lenses_stay_finite_and_inside_the_range + M5 shift_y's sign flipped in blender() test_blender_params_draw_the_same_pixels + M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist + M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes +""" +from __future__ import annotations + +import importlib.util +import json +import math +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +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) + +BOX = [100.0, 50.0, 1100.0, 800.0] +NAMES = [f"p{i}" for i in range(13)] + + +def cloud(): + """Thirteen points in a box 3 m wide, 5 m long and 2 m tall.""" + return np.random.default_rng(3).uniform([-1.5, -2.5, 0.0], [1.5, 2.5, 2.0], (13, 3)) + + +def camera(points, azimuth, elevation, lens, centre=None): + """A camera `lens` mm long looking at the points' middle from far enough off that they fill most of the box.""" + f = lens * (BOX[2] - BOX[0]) / 36.0 + a, e = math.radians(azimuth), math.radians(elevation) + off = 1.3 * np.ptp(points, axis=0).max() * f / (BOX[2] - BOX[0]) + C = points.mean(0) + off * np.array([-math.sin(a) * math.cos(e), math.cos(a) * math.cos(e), math.sin(e)]) + return {"C": C, "R": core._rotation(a + math.pi, -e, 0.0), "f": f, "c": centre or [(BOX[0] + BOX[2]) / 2, (BOX[1] + BOX[3]) / 2], "box": BOX} + + +def marks(cam, points, noise=1.0, build=0.0, drawn=None): + """(world, pixels): the points as a build has them (`build` metres of error) and as the image draws them.""" + r = np.random.default_rng(5) + P = core.project(cam, points if drawn is None else drawn) + r.normal(0, noise, (len(points), 2)) + W = points + r.normal(0, build, points.shape) if build else points + return dict(zip(NAMES, W.tolist())), dict(zip(NAMES, P.tolist())) + + +def place_error(solved, cam): + return float(np.linalg.norm(np.array(solved["C"]) - cam["C"])) + + +@unittest.skipIf(np is None, "numpy") +class SolveTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.points = cloud() + cls.oblique = camera(cls.points, 35, 20, 50) + cls.world, cls.pixels = marks(cls.oblique, cls.points) + cls.auto = core.solve(cls.world, cls.pixels, BOX) + + def test_an_oblique_50_mm_view_is_recovered(self): + """recovers-oblique: 1 px of marking noise on 13 points. Read 50.22 mm, 0.031 m, 34.99 and 20.08 degrees, rms 1.17.""" + s = self.auto + self.assertAlmostEqual(s["lens"], 50.0, delta=1.0) + self.assertLess(place_error(s, self.oblique), 0.1) + self.assertAlmostEqual(s["azimuth"], 35.0, delta=0.3) + self.assertAlmostEqual(s["elevation"], 20.0, delta=0.3) + self.assertTrue(0.8 < s["rms"] < 1.6, s["rms"]) + self.assertEqual(s["lens_at_bound"], None) + self.assertEqual(sorted(s["residuals"]), sorted(NAMES)) + self.assertEqual(json.loads(json.dumps(s)), s) + + def test_one_point_60_px_off_does_not_turn_the_camera(self): + """M1. Azimuth off by 0.262 degrees shipped, 1.186 with plain squares: bound 0.557. Place off by 0.0411 m + shipped, 0.1401: bound 0.0759. Median miss 1.43 px shipped, 2.82: bound 2.01.""" + pixels = dict(self.pixels, p4=[self.pixels["p4"][0] + 60, self.pixels["p4"][1]]) + s = core.solve(self.world, pixels, BOX, model="upright") + self.assertLess(abs(s["azimuth"] - 35.0), 0.557) + self.assertLess(place_error(s, self.oblique), 0.0759) + self.assertLess(s["median"], 2.01) + self.assertEqual(s["worst"][0], "p4") + + def test_auto_takes_the_model_that_predicts_left_out_points(self): + """M2: on a centred view the free model fits the marks closest (rms 1.10 against upright's 1.17) and predicts + a left-out one worst (1.95 against 1.49); on a view cropped off-centre it is the only one that predicts.""" + self.assertEqual(self.auto["model"], "upright") + tried = self.auto["tried"] + self.assertLess(tried["free"]["rms"], tried["upright"]["rms"]) + self.assertLess(tried["upright"]["left_out"], tried["free"]["left_out"]) + cropped = camera(self.points, 35, 20, 50, centre=[640.0, 400.0]) + s = core.solve(*marks(cropped, self.points), BOX) + self.assertEqual(s["model"], "free") + self.assertAlmostEqual(s["c"][0], 640.0, delta=5.0) + + def test_the_band_is_an_equal_error_band(self): + """band-is-equal-error: a build 4 cm off. Every lens in the band refits within BAND of the best rms, and one + step past each end does not.""" + world, pixels = marks(self.oblique, self.points, build=0.04) + s = core.solve(world, pixels, BOX, model="upright") + low, high = s["lens_band"] + self.assertLess(low, s["lens"] * 0.95) + self.assertGreater(high, s["lens"] * 1.05) + for lens in (low, math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high): + self.assertLessEqual(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"] + 1e-6, lens) + for lens in (low * math.exp(-core.STEP), high * math.exp(core.STEP)): + self.assertGreater(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"], lens) + held = core.solve(world, pixels, BOX, model="upright", lens=low) + self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None)) + + def test_the_band_is_walked_from_the_last_solve(self): + """M3: each step of the walk is one solve started at the one before. Counted: 16 starts, 13 left-out solves, + one per lens inside the band and one past each end; restarting from the grid costs 16 per step.""" + world, pixels = marks(self.oblique, self.points, build=0.04) + calls, lm = [0], core.lm + + def counted(*args, **kwargs): + calls[0] += 1 + return lm(*args, **kwargs) + core.lm = counted + try: + s = core.solve(world, pixels, BOX, model="upright") + finally: + core.lm = lm + inside = round(math.log(s["lens_band"][1] / s["lens_band"][0]) / core.STEP) + self.assertGreater(inside, 2) + self.assertEqual(calls[0], 16 + 13 + inside + 2) + + def test_long_lenses_stay_finite_and_inside_the_range(self): + """long-lens-bounded, M4: with no bound the 400 mm view on a build 4 cm off runs log f to OverflowError and + the orthographic one reads 20208 mm.""" + for lens in (135, 400): + cam = camera(self.points, 35, 20, lens) + for build in (0.0, 0.04): + s = core.solve(*marks(cam, self.points, build=build), BOX, model="upright") + low, high = s["lens_band"] + self.assertTrue(core.LENS_MM[0] <= low <= s["lens"] <= high <= core.LENS_MM[1], (lens, build, s["lens"], s["lens_band"])) + self.assertTrue(low <= lens <= high or build == 0.0, (lens, build, s["lens_band"])) + self.assertTrue(all(math.isfinite(v) for v in s["C"])) + self.assertEqual(s["lens_at_bound"], "long" if s["lens"] == core.LENS_MM[1] else None) + far = camera(self.points, 35, 20, 1e5) # orthographic to any marking + s = core.solve(*marks(far, self.points, noise=0.0), BOX, model="upright") + self.assertEqual((s["lens"], s["lens_at_bound"], s["lens_band"][1]), (core.LENS_MM[1], "long", core.LENS_MM[1])) + self.assertLess(s["rms"], 1.0) + self.assertAlmostEqual(s["azimuth"], 35.0, delta=0.3) + + def test_a_turned_torso_is_recovered_as_twist(self): + """torso-turn, M6: five points drawn turned 12 degrees about a pivot. Twist off by 0.05 degrees shipped and + by 12 untwisted: bound 0.77. rms 1.16 px shipped, 23.5: bound 5.2.""" + turned, pivot = NAMES[:5], (0.2, -0.3) + drawn = core._turned(self.points, np.array([n in turned for n in NAMES]), math.radians(12), pivot) + world, pixels = marks(self.oblique, self.points, drawn=drawn) + s = core.solve(world, pixels, BOX, model="upright", turned=turned, pivot=pivot) + self.assertLess(abs(s["twist"] - 12.0), 0.77) + self.assertLess(s["rms"], 5.2) + + def test_square_solves_elevations_along_both_axes(self): + """square-quarter-turns, M7: a rear elevation (the camera behind, looking along +y) and a side elevation + (looking along x) at 300 mm. rms 1.17 and 1.19 px shipped; a yaw held to y only cannot draw the side view.""" + for azimuth in (180, 90): + cam = camera(self.points, azimuth, 0, 300) + s = core.solve(*marks(cam, self.points), BOX, model="square") + self.assertLess(s["rms"], 2.0, azimuth) + self.assertAlmostEqual(abs(s["azimuth"]), azimuth, delta=0.05) + look = -np.array(s["R"][2]) + self.assertLess(min(abs(look[0]), abs(look[1])), 1e-9) # straight along a world axis + + def test_refusals_name_their_cause(self): + """refusals""" + few = {k: self.pixels[k] for k in NAMES[:5]} + cases = (((self.world, few, BOX), {}, "5 points"), ((dict(self.world, p3=[0.0, float("nan"), 1.0]), self.pixels, BOX), {}, "'p3'"), + ((self.world, self.pixels, [100, 50, 100, 800]), {}, "no width"), ((self.world, self.pixels, [100, 50, 1100, 50]), {}, "no height"), + ((self.world, self.pixels, BOX), {"model": "x"}, "unknown model 'x'"), ((self.world, self.pixels, BOX), {"lens": 5000.0}, "5000")) + for args, kwargs, said in cases: + with self.assertRaises(core.ReferenceError) as caught: + core.solve(*args, **kwargs) + self.assertIn(said, str(caught.exception)) + self.assertTrue(issubclass(core.ReferenceError, ValueError)) + + +@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} + + def setUp(self): + self.cam = dict(self.CAM, R=core._rotation(0.4, -0.2, 0.05).tolist()) + self.points = cloud() + + def blender_pixels(self, params, points): + """Where Blender's camera draws world points, from its own definitions: the sensor spans the frame's width, + shifts are in frame widths, and the frame's middle is the optical axis moved by the shift.""" + M = np.array(params["matrix_world"]) + q = (points - M[:3, 3]) @ M[:3, :3] + w, h = params["resolution"] + x = q[:, 0] / -q[:, 2] * params["lens"] / params["sensor_width"] - params["shift_x"] + y = q[:, 1] / -q[:, 2] * params["lens"] / params["sensor_width"] - params["shift_y"] + return np.stack([(x + 0.5) * w, h / 2 - y * w], 1) + + def test_blender_params_draw_the_same_pixels(self): + """blender-round-trip, M5: the centre is 30 px below the box's middle, so a flipped shift_y moves every + point 72 px at this width.""" + for width in (1200, 777): + params = core.blender(self.cam, width) + self.assertEqual(params["resolution"], [width, round(width * 0.75)]) + ours = core.in_frame(self.cam, core.project(self.cam, self.points), width) + self.assertLess(np.abs(self.blender_pixels(params, self.points) - ours).max(), 1e-6) + + def test_camera_of_reads_blender_back(self): + back = core.camera_of(core.blender(self.cam, 1200), BOX) + for key in ("C", "R", "f", "c", "box"): + self.assertLess(np.abs(np.array(back[key]) - np.array(self.cam[key])).max(), 1e-9, key) + framed = core.camera_of(core.blender(self.cam, 1200)) # no box: the frame itself, in its own pixels + self.assertEqual(framed["box"], [0.0, 0.0, 1200.0, 900.0]) + self.assertLess(np.abs(core.project(framed, self.points) - core.in_frame(self.cam, core.project(self.cam, self.points), 1200)).max(), 1e-6) + with self.assertRaises(core.ReferenceError): + core.camera_of(dict(core.blender(self.cam, 1200), sensor_fit="VERTICAL")) + + def test_a_lifted_pixel_lies_on_its_plane_and_draws_back(self): + point = core.lift(self.cam, [500.0, 300.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]) + self.assertAlmostEqual(point[2], 1.0, places=9) + self.assertLess(np.abs(core.project(self.cam, point[None])[0] - [500.0, 300.0]).max(), 1e-6) + + def test_field_parsers(self): + self.assertEqual(core.points("a=1,2,3; b = 4, 5.5 ,6;", 3, "world"), {"a": [1.0, 2.0, 3.0], "b": [4.0, 5.5, 6.0]}) + self.assertEqual(core.numbers("100, 50,1100,800", 4, "box"), BOX) + for text, size, said in (("a=1,2", 3, "'a'"), ("a=1,2,3; a=4,5,6", 3, "twice"), ("=1,2", 2, "no name"), ("a=1,nan", 2, "'a'"), ("a=1,x", 2, "'a'")): + with self.assertRaises(core.ReferenceError) as caught: + core.points(text, size, "world") + self.assertIn(said, str(caught.exception))