firmament: find LED positions from a Stray Scanner capture
Ports the scratch decoder that mapped the first strand, interpolating within each strand rather than across the whole string.

Assisted-by: Claude Opus 5.5 via Claude Code
change mzrvvmlmqupquznyuutwpltpkkvsosps
commit 663223834fc2c25d01f53f9f287d4a71a9146740
author Alpha Chen <alpha@kejadlen.dev>
date
parent wzxtwkuq
diff --git a/firmament/pyproject.toml b/firmament/pyproject.toml
index a128a3f..e54b305 100644
--- a/firmament/pyproject.toml
+++ b/firmament/pyproject.toml
@@ -4,6 +4,8 @@ version = "0.1.0"
 description = "Find each LED's position in 3D from phone captures"
 requires-python = ">=3.13"
 dependencies = [
+    "numpy>=2.5.5",
+    "opencv-python-headless>=5.1.0.95",
     "rerun-sdk>=0.43.2",
 ]
 
diff --git a/firmament/src/firmament/cli.py b/firmament/src/firmament/cli.py
index 1521818..2da072a 100644
--- a/firmament/src/firmament/cli.py
+++ b/firmament/src/firmament/cli.py
@@ -1,4 +1,4 @@
-"""Command-line entry point: `firmament play`, `firmament light`, and `firmament stream`."""
+"""Command-line entry point: `firmament play`, `light`, `stream`, and `solve`."""
 
 import argparse
 import json
@@ -22,7 +22,7 @@ from firmament.pattern import (
     slot_frame,
     strand_frame,
 )
-from firmament.positions import read_leds
+from firmament.positions import read_leds, write_leds
 
 # Resend a static debug frame well inside WLED's 2.5 s realtime timeout.
 LIGHT_RESEND_SECONDS = 1.0
@@ -61,6 +61,8 @@ def main(argv: list[str] | None = None) -> int:
     args = parser.parse_args(argv)
     if args.command == "stream":
         return _stream(parser, args)
+    if args.command == "solve":
+        return _solve(parser, args)
     try:
         frames = _frames(args)
     except ValueError as e:
@@ -161,6 +163,44 @@ def _stream(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
     return 0
 
 
+def _solve(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
+    if not args.capture.is_dir():
+        parser.error(f"can't find the capture directory {args.capture}")
+    out = args.out if args.out is not None else args.capture / "leds.csv"
+    # Imported here so the other commands don't pay for loading OpenCV.
+    from firmament.solve import read_stray, solve
+
+    print(f"firmament: reading {args.capture}", file=sys.stderr)
+    try:
+        solution = solve(read_stray(args.capture), args.leds, args.strand_length)
+    except ValueError as e:
+        print(f"firmament: {e}", file=sys.stderr)
+        return 1
+
+    placed = sum(1 for led in solution.leds if led.views > 0)
+    print(
+        f"firmament: found {solution.cycles} cycles ({solution.slot_seconds * 1000:.0f} ms "
+        f"slots): {solution.decodes} decodes placed {placed} of {args.leds} LEDs, "
+        f"{solution.rejects} rejected",
+        file=sys.stderr,
+    )
+    if solution.borrowed_strands:
+        borrowed = solution.borrowed_strands
+        label = "strand" if len(borrowed) == 1 else "strands"
+        print(
+            f"firmament: {label} {', '.join(map(str, borrowed))} had fewer than 2 placed LEDs "
+            "each, so they were interpolated from other strands",
+            file=sys.stderr,
+        )
+    try:
+        write_leds(out, solution.leds)
+    except OSError as e:
+        print(f"firmament: can't write {out}: {e.strerror}", file=sys.stderr)
+        return 1
+    print(f"firmament: wrote {out}", file=sys.stderr)
+    return 0
+
+
 def _turn_off(sender: DdpSender, off: bytes) -> None:
     try:
         sender.send(off)
@@ -276,6 +316,24 @@ def _parser() -> argparse.ArgumentParser:
         default=64,
         help="scale for the colors sent to WLED, 0 to 255 (default 64); the preview isn't scaled",
     )
+
+    solve = commands.add_parser("solve", help="find LED positions from a Stray Scanner capture")
+    solve.add_argument("capture", type=Path, help="Stray Scanner capture directory")
+    solve.add_argument(
+        "--leds",
+        type=_ranged(MIN_LEDS, MAX_LEDS),
+        required=True,
+        help=f"number of LEDs the pattern was played on, {MIN_LEDS} to {MAX_LEDS}",
+    )
+    solve.add_argument(
+        "--strand-length",
+        type=_ranged(1, MAX_LEDS),
+        default=50,
+        help="LEDs per strand, for interpolating unplaced LEDs (default 50)",
+    )
+    solve.add_argument(
+        "--out", type=Path, help="positions file to write (default leds.csv in the capture)"
+    )
     return parser
 
 
diff --git a/firmament/src/firmament/positions.py b/firmament/src/firmament/positions.py
index 940d58b..96497ee 100644
--- a/firmament/src/firmament/positions.py
+++ b/firmament/src/firmament/positions.py
@@ -1,4 +1,4 @@
-"""Read LED positions, as defined in SPEC.md (LED positions)."""
+"""Read and write LED positions, as defined in SPEC.md (LED positions)."""
 
 import csv
 import math
@@ -36,6 +36,14 @@ def read_leds(path: Path) -> list[Led]:
     return leds
 
 
+def write_leds(path: Path, leds: list[Led]) -> None:
+    with open(path, "w", newline="", encoding="utf-8") as f:
+        writer = csv.writer(f, lineterminator="\n")
+        writer.writerow(COLUMNS)
+        for led in leds:
+            writer.writerow([led.index, *(f"{v:.4f}" for v in (led.x, led.y, led.z)), led.views])
+
+
 def _led(row: dict[str, str], line: int, path: Path) -> Led:
     try:
         index, views = int(row["index"]), int(row["views"])
diff --git a/firmament/src/firmament/solve.py b/firmament/src/firmament/solve.py
new file mode 100644
index 0000000..cd15bcb
--- /dev/null
+++ b/firmament/src/firmament/solve.py
@@ -0,0 +1,339 @@
+"""Find each LED's position from a Stray Scanner capture of the ID pattern.
+
+Each LED is found lit in an all-on slot, placed in 3D from that pixel's depth and the camera
+pose, then followed through the cycle's other slots by projecting that point into each frame.
+Stations aren't needed, so this reads a walking capture, not the session format in SPEC.md.
+"""
+
+import csv
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from firmament.codes import BITS, WEIGHT, code
+from firmament.pattern import ALL_OFF, ALL_ON, SLOT_COUNT
+from firmament.positions import Led
+
+# A lit LED saturates to a small, roughly round blob on a dark surround.
+LIT_LEVEL = 235
+BLOB_AREA = (4, 150)
+BLOB_MAX_ASPECT = 3
+SURROUND_SIZE = 31
+SURROUND_MAX = 170
+
+# A frame is part of an all-off slot when its blob count drops below this share of the nearby
+# median.
+OFF_SHARE = 0.6
+OFF_MIN_FRAMES = 3
+COUNT_WINDOW_FRAMES = 60
+
+# Frames this close to a slot boundary, as a fraction of a slot, may straddle two slots.
+BOUNDARY_MARGIN = 0.2
+SAMPLE_RADIUS = 6
+EDGE_MARGIN = 8
+MIN_DEPTH = 0.05
+
+# A decode needs this much on/off contrast, and this gap between the 6th and 7th brightest data
+# slots relative to that contrast.
+MIN_CONTRAST = 40
+MIN_GAP = 0.3
+
+
+@dataclass(frozen=True)
+class Capture:
+    """Per-frame poses, intrinsics, and images, with depth loaded on demand."""
+
+    times: np.ndarray  # (n,) seconds.
+    rotations: np.ndarray  # (n, 3, 3) camera to world, OpenCV camera axes (x right, y down).
+    positions: np.ndarray  # (n, 3) meters, gravity-aligned world with y up.
+    intrinsics: np.ndarray  # (n, 4) fx, fy, cx, cy in pixels.
+    frames: list[np.ndarray]  # (n,) grayscale uint8 images.
+    depth: Callable[[int], np.ndarray]  # Frame index to a depth map in meters.
+
+
+@dataclass(frozen=True)
+class Solution:
+    leds: list[Led]
+    cycles: int
+    slot_seconds: float
+    decodes: int
+    rejects: int
+    borrowed_strands: list[int]  # Strands placed from other strands' LEDs.
+
+
+def read_stray(path: Path) -> Capture:
+    """Read a Stray Scanner capture directory, raising ValueError if it's incomplete."""
+    odometry = path / "odometry.csv"
+    video = path / "rgb.mp4"
+    depth_dir = path / "depth"
+    for needed in (odometry, video, depth_dir):
+        if not needed.exists():
+            raise ValueError(f"{path}: missing {needed.name}; is this a Stray Scanner capture?")
+    times, rotations, positions, intrinsics = read_odometry(odometry)
+    frames = _read_video(video, limit=len(times))
+    n = len(frames)
+
+    def depth(i: int) -> np.ndarray:
+        image = cv2.imread(str(depth_dir / f"{i:06d}.png"), cv2.IMREAD_UNCHANGED)
+        if image is None:
+            raise ValueError(f"{path}: can't read depth/{i:06d}.png")
+        return image.astype(np.float64) / 1000.0
+
+    return Capture(times[:n], rotations[:n], positions[:n], intrinsics[:n], frames, depth)
+
+
+def read_odometry(path: Path) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+    """Read Stray Scanner's `odometry.csv` into times, rotations, positions, and intrinsics."""
+    with open(path, newline="", encoding="utf-8") as f:
+        reader = csv.reader(f, skipinitialspace=True)
+        header = next(reader, None)
+        columns = ["timestamp", "x", "y", "z", "qx", "qy", "qz", "qw", "fx", "fy", "cx", "cy"]
+        if header is None or any(c not in header for c in columns):
+            raise ValueError(f"{path}: expected the columns {', '.join(columns)}")
+        at = [header.index(c) for c in columns]
+        try:
+            rows = np.array([[float(row[i]) for i in at] for row in reader])
+        except (IndexError, ValueError):
+            raise ValueError(f"{path}, line {reader.line_num}: expected numbers") from None
+    if len(rows) == 0:
+        raise ValueError(f"{path}: no frames")
+    rotations = np.array([quaternion_rotation(q) for q in rows[:, 4:8]])
+    return rows[:, 0], rotations, rows[:, 1:4], rows[:, 8:12]
+
+
+def quaternion_rotation(q: np.ndarray) -> np.ndarray:
+    """Rotation matrix for a unit quaternion given as (x, y, z, w)."""
+    x, y, z, w = q / np.linalg.norm(q)
+    return np.array(
+        [
+            [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
+            [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
+            [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
+        ]
+    )
+
+
+def _read_video(path: Path, limit: int) -> list[np.ndarray]:
+    video = cv2.VideoCapture(str(path))
+    frames = []
+    try:
+        while len(frames) < limit:
+            ok, image = video.read()
+            if not ok:
+                break
+            frames.append(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY))
+    finally:
+        video.release()
+    if not frames:
+        raise ValueError(f"{path}: can't read any video frames")
+    return frames
+
+
+def solve(capture: Capture, led_count: int, strand_length: int) -> Solution:
+    """Decode and place every LED, interpolating the ones never decoded along their strand."""
+    off_starts, slot = find_cycles(capture)
+    table = {code(i): i for i in range(led_count)}
+    seen: dict[int, list[np.ndarray]] = {}
+    rejects = 0
+    cycles = 0
+    for off in off_starts:
+        decoded = _decode_cycle(capture, capture.times[off] - slot, slot, table)
+        if decoded is None:
+            continue
+        cycles += 1
+        for index, point in decoded:
+            if index is None:
+                rejects += 1
+            else:
+                seen.setdefault(index, []).append(point)
+    if len(seen) < 2:
+        raise ValueError(
+            f"decoded {len(seen)} LEDs; need at least 2 to place the rest. "
+            "Check that the pattern was playing and the LEDs aren't too bright."
+        )
+
+    to_start_view = start_view(capture.rotations[0])
+    known = {i: to_start_view @ np.median(points, axis=0) for i, points in seen.items()}
+    xyz, borrowed = interpolate(known, led_count, strand_length)
+    leds = [Led(i, *map(float, xyz[i]), len(seen.get(i, []))) for i in range(led_count)]
+    decodes = sum(len(points) for points in seen.values())
+    return Solution(leds, cycles, slot, decodes, rejects, borrowed)
+
+
+def find_cycles(capture: Capture) -> tuple[list[int], float]:
+    """Find the first frame of each all-off slot, and the slot length in seconds."""
+    counts = np.array([len(blobs(frame)) for frame in capture.frames])
+    n = len(counts)
+    nearby = np.array(
+        [
+            np.median(counts[max(0, i - COUNT_WINDOW_FRAMES) : i + COUNT_WINDOW_FRAMES])
+            for i in range(n)
+        ]
+    )
+    low = counts < OFF_SHARE * nearby
+    off_starts = [
+        i
+        for i in range(1, n - OFF_MIN_FRAMES + 1)
+        if low[i] and not low[i - 1] and low[i : i + OFF_MIN_FRAMES].all()
+    ]
+    if len(off_starts) < 2:
+        raise ValueError(
+            f"found {len(off_starts)} all-off slots; need at least 2. "
+            "Record at least two cycles (4.2 s) of the pattern with the LEDs in view."
+        )
+    period = float(np.median(np.diff(capture.times[off_starts])))
+    return off_starts, period / SLOT_COUNT
+
+
+def blobs(gray: np.ndarray) -> list[tuple[float, float]]:
+    """Pixel centers of the lit LEDs in a frame."""
+    lit = (gray > LIT_LEVEL).astype(np.uint8)
+    count, _, stats, centers = cv2.connectedComponentsWithStats(lit)
+    surround = cv2.blur(gray, (SURROUND_SIZE, SURROUND_SIZE))
+    found = []
+    for i in range(1, count):
+        _, _, w, h, area = stats[i]
+        if not BLOB_AREA[0] <= area <= BLOB_AREA[1] or max(w, h) > BLOB_MAX_ASPECT * min(w, h):
+            continue
+        u, v = centers[i]
+        if surround[int(v), int(u)] < SURROUND_MAX:
+            found.append((float(u), float(v)))
+    return found
+
+
+def _decode_cycle(
+    capture: Capture, cycle_start: float, slot: float, table: dict[int, int]
+) -> list[tuple[int | None, np.ndarray]] | None:
+    """Decode each LED lit in the cycle's all-on slot, or None if that slot wasn't recorded."""
+    times = capture.times
+    middle = (times >= cycle_start + 0.25 * slot) & (times <= cycle_start + 0.75 * slot)
+    on_frames = np.flatnonzero(middle)
+    if len(on_frames) == 0:
+        return None
+    reference = int(on_frames[len(on_frames) // 2])
+    depth = capture.depth(reference)
+
+    # Sample half a cycle either side of this one, so each slot has more than one chance to be
+    # in view.
+    first, last = np.searchsorted(
+        times, [cycle_start - SLOT_COUNT / 2 * slot, cycle_start + 1.5 * SLOT_COUNT * slot]
+    )
+    window = [
+        (i, int(np.floor(k)) % SLOT_COUNT)
+        for i in range(first, last)
+        if abs((k := (times[i] - cycle_start) / slot) - round(k)) >= BOUNDARY_MARGIN
+    ]
+
+    decoded: list[tuple[int | None, np.ndarray]] = []
+    for u, v in blobs(capture.frames[reference]):
+        point = _unproject(capture, reference, depth, u, v)
+        if point is None:
+            continue
+        per_slot: list[list[float]] = [[] for _ in range(SLOT_COUNT)]
+        for i, s in window:
+            uv = _project(capture, i, point)
+            if uv is not None:
+                per_slot[s].append(_sample(capture.frames[i], uv))
+        if not all(per_slot):
+            decoded.append((None, point))
+            continue
+        level = [float(np.median(samples)) for samples in per_slot]
+        decoded.append((decode(level, table), point))
+    return decoded
+
+
+def decode(level: list[float], table: dict[int, int]) -> int | None:
+    """The LED index for one LED's brightness in each slot, or None if it doesn't decode."""
+    on, off = level[ALL_ON], level[ALL_OFF]
+    data = np.array(level[2 : 2 + BITS])
+    order = np.argsort(data, kind="stable")[::-1]
+    word = sum(1 << int(b) for b in order[:WEIGHT])
+    gap = (data[order[WEIGHT - 1]] - data[order[WEIGHT]]) / max(on - off, 1)
+    if on - off < MIN_CONTRAST or gap < MIN_GAP:
+        return None
+    return table.get(word)
+
+
+def _unproject(
+    capture: Capture, i: int, depth: np.ndarray, u: float, v: float
+) -> np.ndarray | None:
+    height, width = capture.frames[i].shape
+    du, dv = int(u * depth.shape[1] / width), int(v * depth.shape[0] / height)
+    patch = depth[max(0, dv - 1) : dv + 2, max(0, du - 1) : du + 2]
+    d = float(np.median(patch))
+    # LiDAR reports 0 where it has no reading.
+    if not d > MIN_DEPTH:
+        return None
+    fx, fy, cx, cy = capture.intrinsics[i]
+    camera = np.array([(u - cx) / fx * d, (v - cy) / fy * d, d])
+    return capture.rotations[i] @ camera + capture.positions[i]
+
+
+def _project(capture: Capture, i: int, point: np.ndarray) -> tuple[float, float] | None:
+    camera = capture.rotations[i].T @ (point - capture.positions[i])
+    if camera[2] <= MIN_DEPTH:
+        return None
+    fx, fy, cx, cy = capture.intrinsics[i]
+    u, v = cx + fx * camera[0] / camera[2], cy + fy * camera[1] / camera[2]
+    height, width = capture.frames[i].shape
+    if not (EDGE_MARGIN <= u < width - EDGE_MARGIN and EDGE_MARGIN <= v < height - EDGE_MARGIN):
+        return None
+    return u, v
+
+
+def _sample(frame: np.ndarray, uv: tuple[float, float]) -> float:
+    u, v = round(uv[0]), round(uv[1])
+    r = SAMPLE_RADIUS
+    return float(frame[v - r : v + r + 1, u - r : u + r + 1].max())
+
+
+def start_view(rotation: np.ndarray) -> np.ndarray:
+    """World-to-start-view rotation (SPEC.md, LED positions) for the first frame's camera."""
+    forward = rotation[:, 2]
+    back = -np.array([forward[0], 0.0, forward[2]])
+    length = np.linalg.norm(back)
+    if length < 1e-6:
+        raise ValueError("the capture starts looking straight up or down; start facing the LEDs")
+    back /= length
+    up = np.array([0.0, 1.0, 0.0])
+    return np.stack([np.cross(up, back), up, back])
+
+
+def interpolate(
+    known: dict[int, np.ndarray], led_count: int, strand_length: int
+) -> tuple[list[np.ndarray], list[int]]:
+    """Fill in every unknown LED linearly by index from known LEDs on its strand.
+
+    Past a strand's last known LED, the line through its two nearest known LEDs continues. A
+    strand with fewer than two known LEDs borrows from the whole string instead, and is
+    returned in the second list.
+    """
+    if len(known) < 2:
+        raise ValueError(f"need at least 2 known LEDs to interpolate, got {len(known)}")
+    everywhere = sorted(known)
+    xyz: list[np.ndarray] = []
+    borrowed = []
+    for start in range(0, led_count, strand_length):
+        strand = range(start, min(start + strand_length, led_count))
+        anchors = [i for i in everywhere if i in strand]
+        if len(anchors) < 2:
+            anchors = everywhere
+            borrowed.append(start // strand_length)
+        for i in strand:
+            xyz.append(known[i] if i in known else _along(known, anchors, i))
+    return xyz, borrowed
+
+
+def _along(known: dict[int, np.ndarray], anchors: list[int], i: int) -> np.ndarray:
+    below = [k for k in anchors if k < i]
+    above = [k for k in anchors if k > i]
+    if below and above:
+        a, b = below[-1], above[0]
+    elif above:
+        a, b = above[0], above[1]
+    else:
+        a, b = below[-2], below[-1]
+    return known[a] + (known[b] - known[a]) * (i - a) / (b - a)
diff --git a/firmament/tests/test_cli.py b/firmament/tests/test_cli.py
index a72f02b..982ccb9 100644
--- a/firmament/tests/test_cli.py
+++ b/firmament/tests/test_cli.py
@@ -171,3 +171,15 @@ def test_stream_rejects_a_missing_effect_file(tmp_path, capsys):
     with pytest.raises(SystemExit):
         main(["stream", "nope.py", "--map", str(leds), "--host", "127.0.0.1"])
     assert "can't find the effect file nope.py" in capsys.readouterr().err
+
+
+def test_solve_rejects_a_missing_capture(tmp_path, capsys):
+    with pytest.raises(SystemExit) as exit_info:
+        main(["solve", str(tmp_path / "nope"), "--leds", "50"])
+    assert exit_info.value.code == 2
+    assert "can't find the capture directory" in capsys.readouterr().err
+
+
+def test_solve_reports_a_directory_that_isnt_a_capture(tmp_path, capsys):
+    assert main(["solve", str(tmp_path), "--leds", "50"]) == 1
+    assert "missing odometry.csv; is this a Stray Scanner capture?" in capsys.readouterr().err
diff --git a/firmament/tests/test_solve.py b/firmament/tests/test_solve.py
new file mode 100644
index 0000000..59d40ad
--- /dev/null
+++ b/firmament/tests/test_solve.py
@@ -0,0 +1,194 @@
+import math
+
+import numpy as np
+import pytest
+
+from firmament.codes import bit, code
+from firmament.pattern import ALL_ON, SLOT_COUNT, SLOT_SECONDS
+from firmament.positions import Led, read_leds, write_leds
+from firmament.solve import (
+    Capture,
+    decode,
+    interpolate,
+    quaternion_rotation,
+    read_odometry,
+    solve,
+    start_view,
+)
+
+WIDTH, HEIGHT = 320, 240
+FX, CX, CY = 200.0, 160.0, 120.0
+DEPTH = 2.0
+FPS = 30
+# Camera to world for an upright camera looking down world -z, in OpenCV camera axes.
+UPRIGHT = np.diag([1.0, -1.0, -1.0])
+
+
+def _synthetic(led_count: int, hidden: set[int], cycles: int = 4) -> tuple[Capture, np.ndarray]:
+    """A still camera watching LEDs in a row, 30 px apart, playing the ID pattern."""
+    pixels = [(40 + 30 * i, 60 + 12 * i) for i in range(led_count)]
+    truth = np.array(
+        [UPRIGHT @ [(u - CX) / FX * DEPTH, (v - CY) / FX * DEPTH, DEPTH] for u, v in pixels]
+    )
+    n = int(cycles * SLOT_COUNT * SLOT_SECONDS * FPS)
+    # Start partway into a cycle, as a real capture would.
+    times = 100.0 + 0.4 + np.arange(n) / FPS
+    frames = []
+    for t in times:
+        slot = int((t - 100.0) / SLOT_SECONDS) % SLOT_COUNT
+        frame = np.zeros((HEIGHT, WIDTH), np.uint8)
+        for i, (u, v) in enumerate(pixels):
+            lit = slot == ALL_ON or (slot >= 2 and bit(i, slot - 2))
+            if lit and i not in hidden:
+                frame[v - 1 : v + 2, u - 1 : u + 2] = 255
+        frames.append(frame)
+    capture = Capture(
+        times=times,
+        rotations=np.repeat(UPRIGHT[None], n, axis=0),
+        positions=np.zeros((n, 3)),
+        intrinsics=np.tile([FX, FX, CX, CY], (n, 1)),
+        frames=frames,
+        depth=lambda _: np.full((HEIGHT // 4, WIDTH // 4), DEPTH),
+    )
+    return capture, truth
+
+
+def test_solve_places_each_lit_led_where_it_is():
+    capture, truth = _synthetic(8, hidden=set())
+
+    solution = solve(capture, led_count=8, strand_length=50)
+
+    assert solution.cycles == 4
+    assert solution.slot_seconds == pytest.approx(SLOT_SECONDS, rel=0.05)
+    # The capture ends during the last cycle, so only 3 decode.
+    assert solution.rejects == 8
+    assert all(led.views == 3 for led in solution.leds)
+    placed = np.array([(led.x, led.y, led.z) for led in solution.leds])
+    np.testing.assert_allclose(placed, truth, atol=0.01)
+
+
+def test_solve_interpolates_a_hidden_led_along_the_strand():
+    capture, truth = _synthetic(8, hidden={3})
+
+    solution = solve(capture, led_count=8, strand_length=50)
+
+    hidden = solution.leds[3]
+    assert hidden.views == 0
+    np.testing.assert_allclose((hidden.x, hidden.y, hidden.z), truth[3], atol=0.01)
+
+
+def test_solve_rejects_a_capture_without_the_pattern():
+    capture, _ = _synthetic(8, hidden=set(range(8)))
+
+    with pytest.raises(ValueError, match="found 0 all-off slots"):
+        solve(capture, led_count=8, strand_length=50)
+
+
+def _levels(index: int, on: float = 250, off: float = 10) -> list[float]:
+    word = code(index)
+    return [on, off] + [on if word >> b & 1 else off for b in range(12)]
+
+
+TABLE = {code(i): i for i in range(50)}
+
+
+def test_decode_reads_each_leds_codeword():
+    assert [decode(_levels(i), TABLE) for i in range(50)] == list(range(50))
+
+
+@pytest.mark.parametrize(
+    "level",
+    [
+        _levels(7, on=40, off=10),  # Too little contrast.
+        [250, 10] + [250] * 6 + [200] + [10] * 5,  # 6th and 7th brightest too close.
+        _levels(60),  # A codeword beyond the LED count.
+    ],
+)
+def test_decode_rejects_unclear_readings(level):
+    assert decode(level, TABLE) is None
+
+
+def _known(*indices: int) -> dict[int, np.ndarray]:
+    return {i: np.array([float(i), 0.0, 0.0]) for i in indices}
+
+
+def test_interpolate_fills_between_and_past_known_leds():
+    xyz, borrowed = interpolate(_known(2, 4, 5), led_count=8, strand_length=8)
+
+    assert [p[0] for p in xyz] == pytest.approx(range(8))
+    assert borrowed == []
+
+
+def test_interpolate_stays_within_each_strand():
+    known = {0: np.zeros(3), 1: np.array([1.0, 0, 0]), 2: np.array([0, 5.0, 0])}
+    known[3] = np.array([0, 6.0, 0])
+
+    xyz, borrowed = interpolate(known | {5: np.array([0, 8.0, 0])}, led_count=6, strand_length=3)
+
+    # LED 4 lies between 3 and 5 on the second strand, ignoring the first strand's LEDs.
+    np.testing.assert_allclose(xyz[4], [0, 7.0, 0])
+    assert borrowed == []
+
+
+def test_interpolate_borrows_for_a_strand_with_too_few_known_leds():
+    xyz, borrowed = interpolate(_known(0, 1, 5), led_count=6, strand_length=3)
+
+    np.testing.assert_allclose([p[0] for p in xyz], range(6))
+    assert borrowed == [1]
+
+
+def test_quaternion_rotation_turns_about_y():
+    half = math.radians(90) / 2
+    rotation = quaternion_rotation(np.array([0, math.sin(half), 0, math.cos(half)]))
+
+    np.testing.assert_allclose(rotation @ [1, 0, 0], [0, 0, -1], atol=1e-12)
+
+
+def test_start_view_faces_the_first_camera():
+    # A camera tilted down still gives a level view: z back toward it, y up.
+    tilt = math.radians(30)
+    tilted = UPRIGHT @ np.array(
+        [[1, 0, 0], [0, math.cos(tilt), -math.sin(tilt)], [0, math.sin(tilt), math.cos(tilt)]]
+    )
+
+    np.testing.assert_allclose(start_view(tilted), np.eye(3), atol=1e-12)
+
+
+def test_read_odometry_reads_stray_scanners_columns(tmp_path):
+    path = tmp_path / "odometry.csv"
+    path.write_text(
+        "timestamp, frame, x, y, z, qx, qy, qz, qw, fx, fy, cx, cy, distortion_center_x\n"
+        "10.5, 000000, 1, 2, 3, 0, 0, 0, 1, 1369.1, 1369.2, 965.5, 726.0, \n"
+    )
+
+    times, rotations, positions, intrinsics = read_odometry(path)
+
+    assert times.tolist() == [10.5]
+    np.testing.assert_allclose(rotations[0], np.eye(3))
+    assert positions.tolist() == [[1, 2, 3]]
+    assert intrinsics.tolist() == [[1369.1, 1369.2, 965.5, 726.0]]
+
+
+@pytest.mark.parametrize(
+    ("text", "match"),
+    [
+        ("timestamp, x, y\n", "expected the columns"),
+        ("timestamp, x, y, z, qx, qy, qz, qw, fx, fy, cx, cy\n", "no frames"),
+        ("timestamp, x, y, z, qx, qy, qz, qw, fx, fy, cx, cy\n1, 2\n", "line 2: expected numbers"),
+    ],
+)
+def test_read_odometry_rejects_malformed_files(tmp_path, text, match):
+    path = tmp_path / "odometry.csv"
+    path.write_text(text)
+
+    with pytest.raises(ValueError, match=match):
+        read_odometry(path)
+
+
+def test_write_leds_round_trips(tmp_path):
+    leds = [Led(0, 0.1234, -0.5, 2.0, 3), Led(1, 1.0, 0.0, -1.25, 0)]
+    path = tmp_path / "leds.csv"
+
+    write_leds(path, leds)
+
+    assert read_leds(path) == leds
diff --git a/firmament/uv.lock b/firmament/uv.lock
index 35d59aa..b26201a 100644
--- a/firmament/uv.lock
+++ b/firmament/uv.lock
@@ -25,6 +25,8 @@ name = "firmament"
 version = "0.1.0"
 source = { editable = "." }
 dependencies = [
+    { name = "numpy" },
+    { name = "opencv-python-headless" },
     { name = "rerun-sdk" },
 ]
 
@@ -36,7 +38,11 @@ dev = [
 ]
 
 [package.metadata]
-requires-dist = [{ name = "rerun-sdk", specifier = ">=0.43.2" }]
+requires-dist = [
+    { name = "numpy", specifier = ">=2.5.5" },
+    { name = "opencv-python-headless", specifier = ">=5.1.0.95" },
+    { name = "rerun-sdk", specifier = ">=0.43.2" },
+]
 
 [package.metadata.requires-dev]
 dev = [
@@ -116,6 +122,26 @@ wheels = [
     { url = "https://files.pythonhosted.org/packages/36/7b/935a5896b0bd441c6dd6da81f39bc5ebf8d5da891b7dcff768e1e1c088b5/numpy-2.5.5-cp315-cp315t-win_arm64.whl", hash = "sha256:b6ecbc1ff292c6799067d8064a4dd35cd25ba9d1a24aa41dd635d701691a49b5", size = 10891314, upload-time = "2026-11-15T21:32:26.357Z" },
 ]
 
+[[package]]
+name = "opencv-python-headless"
+version = "5.1.0.95"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+    { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6b/51/33b8c7255f3bdd920d6238aa478faf1e2136d5a51f17d826c13902ca7195/opencv_python_headless-5.1.0.95.tar.gz", hash = "sha256:9002add14b121b9a0d64dcaff48e5cac69a7987efcf2847f7db075c2d3b9633b", size = 83423991, upload-time = "2026-11-17T18:19:14.93Z" }
+wheels = [
+    { url = "https://files.pythonhosted.org/packages/a7/76/95bb6ecdb317bf839fc653d26055df7355b9290876ffebc0a8a68f0c8740/opencv_python_headless-5.1.0.95-cp37-abi3-macosx_15_0_arm64.whl", hash = "sha256:512f5c704eeedd0c550cf2daca42e4312f6d30bb047680f1563c661eb9ee7e82", size = 25824488, upload-time = "2026-11-17T17:40:36.008Z" },
+    { url = "https://files.pythonhosted.org/packages/e7/ba/e4773fad5195bbb33e4acbec6710315e90b487c23d101f8b886d8341ed7c/opencv_python_headless-5.1.0.95-cp37-abi3-macosx_15_0_x86_64.whl", hash = "sha256:1193ffb8a60d0496dbac652f052791dc0f0da6a298e215c93d1d8c9dd67b89e9", size = 47012519, upload-time = "2026-11-17T17:40:59.708Z" },
+    { url = "https://files.pythonhosted.org/packages/8c/2a/e42c34358d69a26bd5e88ba9241437c58b78876cf0d13ecc09df9042ed4f/opencv_python_headless-5.1.0.95-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58835db7491d6564e816c4fbbedffe72afa3976dc19ccd7439916ec0e534f6c2", size = 35797194, upload-time = "2026-11-17T18:17:12.136Z" },
+    { url = "https://files.pythonhosted.org/packages/37/63/6f18cf6b25aca818c5432317f9c9db3ee87d9f03d576d1e5953910429be3/opencv_python_headless-5.1.0.95-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:93cc83677f07791a9d3284bb6b9bbf7c2ffcca05aabcee239e68ca4abaf50aa1", size = 57722171, upload-time = "2026-11-17T18:17:22.507Z" },
+    { url = "https://files.pythonhosted.org/packages/26/db/73313673e5c07eb4023c929022e6ef5f7cfd7885f7ea14019b1e1f74540a/opencv_python_headless-5.1.0.95-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:11d9753e15b8b3c56e6aa765139f722ca19ff26016d43bc81035f5d122731a81", size = 40022516, upload-time = "2026-11-17T18:17:30.669Z" },
+    { url = "https://files.pythonhosted.org/packages/c2/be/cdf44e32b580af6c0e8f237665c538e6a5a37872f865e92e08fb854d5fd9/opencv_python_headless-5.1.0.95-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7d387d4a64abe0c737440d38b5a90822f9bbcc10c8ce06a35904d6ecf7a2fb30", size = 63704594, upload-time = "2026-11-17T18:17:50.623Z" },
+    { url = "https://files.pythonhosted.org/packages/a0/fb/2a03c688595f0c1541c31fe5a767072102f7bed82e3122e9348723c347fb/opencv_python_headless-5.1.0.95-cp37-abi3-win32.whl", hash = "sha256:3d57365e8050a968a60095fa78a108f765b094914f5ad863c45ff5cef8844069", size = 37076072, upload-time = "2026-11-17T14:37:37.864Z" },
+    { url = "https://files.pythonhosted.org/packages/26/d1/a52c8d8e1cecf86725930170dfba1c7c1f59674ac8f131e96583aa41433d/opencv_python_headless-5.1.0.95-cp37-abi3-win_amd64.whl", hash = "sha256:2fd11ce2e88feb28869ad5762a31546ce0062e7c55c130c425ccd3918a19e4fa", size = 47789463, upload-time = "2026-11-17T14:37:33.153Z" },
+    { url = "https://files.pythonhosted.org/packages/a5/72/0af4755ec5ea9fd7d478900405193f6e2d895383f26a31875e7fc7d22a12/opencv_python_headless-5.1.0.95-cp37-abi3-win_arm64.whl", hash = "sha256:a508c7c30815ccb5990d15427daf1397e33c850d8aab6efc3a5eaff035bebc80", size = 15631616, upload-time = "2026-11-17T14:37:27.735Z" },
+]
+
 [[package]]
 name = "packaging"
 version = "26.3"