Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions apps/windows-studio/src/packlab_studio/measure_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
QWidget,
)

from packlab_core.calibration.mat_photo_check import mat_svg_path

from . import measure_design as md
from . import package_families as pf
from .i18n import tr
Expand Down Expand Up @@ -121,6 +123,9 @@ def __init__(
self._choose_save = save_chooser or (
lambda parent, name: QFileDialog.getSaveFileName(parent, "Save", name)[0]
)
self._choose_mat_save: Callable[[QWidget, str], str] = lambda parent, name: (
QFileDialog.getSaveFileName(parent, "Save printable mat", name, "SVG (*.svg)")[0]
)
self.settings = settings or QSettings()
self.model: md.LoadedModel | None = None
self.mesh_model: md.LoadedModel | None = None
Expand Down Expand Up @@ -188,6 +193,9 @@ def button(text: str, name: str, slot: Callable[[], object]) -> QPushButton:
self.marker_button = button(
"2. Scale from mat markers", "marker-scale", self.scale_from_markers
)
self.save_mat_button = button(
"Save printable mat (A4 SVG)…", "save-mat", self.save_printable_mat
)
self.point_a = QLineEdit()
self.point_b = QLineEdit()
self.known_mm = QDoubleSpinBox()
Expand Down Expand Up @@ -231,6 +239,7 @@ def button(text: str, name: str, slot: Callable[[], object]) -> QPushButton:

scale_box = QGroupBox("Scale and upright")
scale_form = QFormLayout(scale_box)
scale_form.addRow(self.save_mat_button)
scale_form.addRow("Mat print check: 100 mm bar measures", self.bar_mm)
scale_form.addRow(self.marker_button)
scale_form.addRow("Manual point A (model units x, y, z)", self.point_a)
Expand Down Expand Up @@ -836,6 +845,25 @@ def action() -> str:

self._run("Measure", action)

def save_printable_mat(self) -> None:
"""PL-0501: the versioned printable target; nominal geometry, never a physical check."""

chosen = self._choose_mat_save(self, "packlab-a4-calibration-mat.svg")
if not chosen:
return
target = Path(chosen)
if target.suffix.lower() != ".svg":
target = target.with_name(target.name + ".svg")

def action() -> str:
target.write_bytes(mat_svg_path("a4").read_bytes())
return (
f"wrote {target.name}: print at 100 % (actual size, no fit to page), "
"then measure the 100 mm bar with a ruler and enter it below"
)

self._run("Printable mat", action)

def export_report(self) -> None:
if self.measurements is None or self.frame is None:
return
Expand Down
21 changes: 21 additions & 0 deletions coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0501_V01.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# CLAUDE_PEER_REVIEW PL-0501 V01
Reviewer: Claude (independent subagent; not the builder).
PR #117, head fbb4130f5d64c3d01aa455fce413c0281f5c8339, base dd828dc2.
Verdict: CHANGES_REQUIRED (minor). Honesty and math PASS; frozen bundle NOT_VERIFIED.
Reviewer-run evidence: pytest tests/calibration + tests/studio/test_measure_design.py + tests/ci/{test_pl0517_capability_reconciliation,test_owner_dev_launcher_contract,test_ci_data_safety}.py = 179 passed; ruff check clean; mypy clean (353 files); CI-mode ruff format clean on changed files.
Independent math: synthetic A4 seed 1, mm/px 0.237038 reported vs 0.237076 from true-homography Jacobian (0.02%); residual 0.15 mm. Single-marker shift trips LAYOUT_INCONSISTENT at 4 mm (about 0.28-0.29 mm residual per mm); documented in code and docs/calibration/mat-assets.md.
Honesty: metric_status METRIC_UNVERIFIED and physical_evidence PHYSICAL_EVIDENCE_PENDING are unconditional; no metric or physical pass possible from synthetic or photo data.
Mutations: threshold and nearest-match killed; mm_per_px inversion and spacing x/y swap survived.
Required: F1 CLI exit 0 despite ruler REJECTED_SCALING (mat_photo_check.py:196); F2 assert mm_per_px_at_mat_centre against ground truth.
Recommended: F3 catch PrintScaleSensitivityError in CLI; F4 pin failed_readings; F5 per-size page corners in test; F6 static spec/bundle assertion or build_smoke check (packaged build is dispatch-only, not run); F7 SVG filter in save dialog.
Limits: no packaged or frozen build run; no real photo or print; PL-0068/PL-0220..PL-0224 hardware evidence stays BLOCKED.
Separate note: 46 untouched files on main fail ruff format even with line-ending=auto (real drift); CI only checks changed files, so CI passes.

## Fix verification (V01-R1)
Reviewer: Claude (independent subagent; not the builder). Not a CHATGPT_AUDIT or CODEX_PEER_REVIEW.
Head a10cc97f18b6e73e3147291012d05324152df435 (fixes in 1a77b1ec; record in a10cc97f).
Verdict: PASS (software). F1-F7 resolved. Physical/hardware evidence (PL-0068, PL-0220..PL-0224) stays BLOCKED; packaged frozen build not run (F6 is a static spec assertion only).
Reviewer-run evidence: pytest tests/calibration + tests/studio/test_measure_design.py + tests/ci/{test_pl0517_capability_reconciliation,test_owner_dev_launcher_contract,test_ci_data_safety}.py = 181 passed; ruff check clean; CI-mode ruff format clean on the 5 changed .py files; mypy clean (353 files).
Fixes checked: F1 CLI exits 1 on REJECTED_SCALING; F2 mm_per_px asserted against true-homography Jacobian (rel 1e-2, formula checked); F3 PrintScaleSensitivityError -> exit 2 + stderr; F4 failed_readings == ["spacing_y"]; F5 per-mat page corners; F6 spec bundles assets/calibration (static test); F7 SVG filter + .svg suffix appended.
Mutations (each applied, run, reverted): mm_per_px inversion killed (3 failed); spacing x/y swap killed (2 failed); F1 exit-code (drop "and not rejected") killed (1 failed); F3 re-raise killed (1 failed); F7 suffix removal killed (1 failed); F6 spec line removal killed (1 failed).
Non-blocking notes: _choose_mat_save not injectable via constructor; Studio cancel path untested; the V01 text above was abridged by the coordinator when relayed (dropped the audit-type line and the "ruff 0.16.8 = lock" note; ruff 0.16.8 matches uv.lock).
207 changes: 207 additions & 0 deletions core/src/packlab_core/calibration/mat_photo_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
"""PL-0501 single-photo check of a printed PackLab calibration mat (software path only).

Run before a scan session: ``python -m packlab_core.calibration.mat_photo_check PHOTO``.
It detects the four mat markers in one photo, fits the planar mat-mm -> pixel homography
to all 16 marker corners and reports layout consistency (corner residual in mm) and the
local image resolution at the mat. Any uniform, anisotropic or projective print error is
absorbed by that homography and is invisible here, exactly as in the scan path; only the
owner ruler reading of the printed mat (``check_printed_mat_spacing``) can catch it. The
result therefore always stays METRIC_UNVERIFIED / PHYSICAL_EVIDENCE_PENDING.
"""

from __future__ import annotations

import argparse
import json
import math
import sys
from collections.abc import Sequence
from pathlib import Path
from typing import Any

import numpy as np

from ..print_scale_sensitivity import (
PHYSICAL_EVIDENCE_PENDING,
CalibrationMatProfile,
PrintScaleSensitivityError,
check_printed_mat_spacing,
load_calibration_mat_profile,
)
from ..resource_paths import packlab_data_root
from .marker_detection import detect_markers

REPORT_CONTRACT = "packlab.mat-photo-check.v1"
# A corner further than this from the nominal layout means a misprinted/warped/occluded mat;
# equal to the provisional centre-distance print tolerance in pre-use-verification.md.
# ponytail: the 8-DOF homography absorbs most of a single misplaced marker (synthetic A4:
# ~0.28 mm residual per mm shift, so only shifts above ~4 mm trip this); the ruler record is
# the real geometry check, a per-marker pose fit would be the upgrade if that matters.
MAX_CORNER_RESIDUAL_MM = 1.0


def mat_svg_path(size: str = "a4") -> Path:
"""The versioned printable mat source (print at 100 %, never fit to page)."""

if size not in {"a4", "a3"}:
raise ValueError("mat size must be a4 or a3")
return packlab_data_root() / "assets" / "calibration" / f"{size}-packlab-calibration-mat.svg"


def _diagonal_centre(corners: np.ndarray) -> np.ndarray:
# The diagonals' intersection is the projected square centre under any perspective.
p, r = corners[0], corners[2] - corners[0]
q, s = corners[1], corners[3] - corners[1]
d = q - p
t = float((d[0] * s[1] - d[1] * s[0]) / (r[0] * s[1] - r[1] * s[0]))
return p + t * r


def _apply(h: np.ndarray, points: np.ndarray) -> np.ndarray:
homogeneous = np.c_[points, np.ones(len(points))] @ h.T
return homogeneous[:, :2] / homogeneous[:, 2:]


def check_mat_photo(
image: Any,
profile: CalibrationMatProfile,
*,
spacing_x_mm: float | None = None,
spacing_y_mm: float | None = None,
marker_side_mm: float | None = None,
) -> dict[str, object]:
"""Detect the mat in one uint8 photo and report layout consistency; never a metric pass."""

import cv2

report: dict[str, object] = {
"contract": REPORT_CONTRACT,
"mat_id": profile.mat_id,
"mat_source_version": profile.source_version,
"mat_source_sha256": profile.source_sha256,
"metric_status": "METRIC_UNVERIFIED",
"physical_evidence": PHYSICAL_EVIDENCE_PENDING,
"print_check": check_printed_mat_spacing(
profile,
spacing_x_mm=spacing_x_mm,
spacing_y_mm=spacing_y_mm,
marker_side_mm=marker_side_mm,
),
}
batch = detect_markers(image)
expected = {marker_id for marker_id, _x, _y in profile.marker_origins_mm}
found = {item.marker_id: np.asarray(item.corners_px, float) for item in batch.observations}
report["detected_marker_ids"] = sorted(found)
report["missing_marker_ids"] = sorted(expected - set(found))
if batch.status not in {"detected", "no_markers"}:
report["status"] = "DETECTION_FAILED"
report["errors"] = list(batch.errors)
return report
if expected - set(found):
report["status"] = "INCOMPLETE"
return report

side = profile.marker_side_mm
origins = {marker_id: np.array([x, y]) for marker_id, x, y in profile.marker_origins_mm}
square = np.array([[0, 0], [side, 0], [side, side], [0, side]], float)
ids = sorted(expected)
centres_mm = np.array([origins[i] + side / 2 for i in ids])
centres_px = np.array([_diagonal_centre(found[i]) for i in ids])
coarse, _ = cv2.findHomography(centres_mm, centres_px, 0)
if coarse is None:
report["status"] = "DETECTION_FAILED"
report["errors"] = ["mat_homography_degenerate"]
return report
# Detector corner order is image-based, so match each corner to its nearest nominal one.
nominal: list[np.ndarray] = []
detected: list[np.ndarray] = []
inverse = np.linalg.inv(coarse)
for marker_id in ids:
nominal_corners = origins[marker_id] + square
back = _apply(inverse, found[marker_id])
for point_px, point_mm in zip(found[marker_id], back, strict=True):
nearest = int(np.argmin(np.linalg.norm(nominal_corners - point_mm, axis=1)))
nominal.append(nominal_corners[nearest])
detected.append(point_px)
fine, _ = cv2.findHomography(np.array(nominal), np.array(detected), 0)
if fine is None:
report["status"] = "DETECTION_FAILED"
report["errors"] = ["mat_homography_degenerate"]
return report
residual = np.linalg.norm(
_apply(np.linalg.inv(fine), np.array(detected)) - np.array(nominal), axis=1
)
centre_mm = np.array([[profile.page_width_mm / 2, profile.page_height_mm / 2]])
# Local px-per-mm Jacobian of the fitted homography at the mat centre (finite difference).
step = 1.0
base = _apply(fine, centre_mm)[0]
jacobian = np.column_stack(
[
_apply(fine, centre_mm + [[step, 0.0]])[0] - base,
_apply(fine, centre_mm + [[0.0, step]])[0] - base,
]
)
px_per_mm = math.sqrt(abs(float(np.linalg.det(jacobian))))
residual_max = float(residual.max())
report.update(
{
"status": (
"LAYOUT_INCONSISTENT"
if residual_max > MAX_CORNER_RESIDUAL_MM
else "DETECTED_LAYOUT_CONSISTENT"
),
"corner_residual_rms_mm": float(np.sqrt(np.mean(residual**2))),
"corner_residual_max_mm": residual_max,
"max_corner_residual_mm": MAX_CORNER_RESIDUAL_MM,
"mm_per_px_at_mat_centre": 1.0 / px_per_mm,
"homography_mm_to_px": fine.tolist(),
"limits": (
"Nominal mat geometry only: print scale errors are invisible to a photo; "
"an owner ruler reading of the printed mat is required and physical accuracy "
"needs the PL-0068/PL-0220 caliper benchmark."
),
}
)
return report


def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Check one photo of a printed PackLab mat.")
parser.add_argument("photo", nargs="?", type=Path, help="photo of the printed mat")
parser.add_argument("--mat", choices=("a4", "a3"), default="a4")
parser.add_argument("--export-mat", type=Path, help="write the printable mat SVG here")
parser.add_argument("--spacing-x-mm", type=float, help="ruler: marker centre distance x")
parser.add_argument("--spacing-y-mm", type=float, help="ruler: marker centre distance y")
parser.add_argument("--marker-side-mm", type=float, help="ruler: printed marker side")
args = parser.parse_args(argv)
source = mat_svg_path(args.mat)
if args.export_mat is not None:
args.export_mat.write_bytes(source.read_bytes())
print(f"wrote {args.export_mat}: print at 100 % (actual size), never fit to page")
if args.photo is None:
return 0 if args.export_mat is not None else 2
import cv2

image = cv2.imdecode(np.fromfile(str(args.photo), dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
if image is None:
print(f"cannot read image {args.photo}", file=sys.stderr)
return 2
try:
report = check_mat_photo(
image,
load_calibration_mat_profile(source),
spacing_x_mm=args.spacing_x_mm,
spacing_y_mm=args.spacing_y_mm,
marker_side_mm=args.marker_side_mm,
)
except PrintScaleSensitivityError as error:
print(f"invalid mat or ruler input: {error}", file=sys.stderr)
return 2
print(json.dumps(report, indent=2))
print_check = report["print_check"]
rejected = isinstance(print_check, dict) and print_check["status"] == "REJECTED_SCALING"
return 0 if report["status"] == "DETECTED_LAYOUT_CONSISTENT" and not rejected else 1


if __name__ == "__main__":
raise SystemExit(main())
7 changes: 7 additions & 0 deletions docs/calibration/mat-assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,10 @@ verified by this builder pass.
- Source version `1.0.1` restores that required black border cell.
- Static regression now checks all four full 8 x 8 `DICT_APRILTAG_36h11` bitmaps, not only page/marker dimensions.
- Any physical print made from v1.0.0 is dimensionally measurable but is not accepted for the four-marker PackLab capture contract; reprint from v1.0.1.

## Getting the mat and checking a photo (PL-0501)

- Studio: Measure & Design, "Save printable mat (A4 SVG)…" writes this versioned A4 source (the frozen build bundles `assets/calibration`).
- CLI: `python -m packlab_core.calibration.mat_photo_check --export-mat mat.svg [--mat a3]` writes the source; `python -m packlab_core.calibration.mat_photo_check PHOTO --spacing-x-mm X --spacing-y-mm Y --marker-side-mm S` detects the four markers in one photo, fits the mat-mm to pixel homography and reports corner residual (mm), mm per pixel at the mat centre and the ruler print gate (`check_printed_mat_spacing`).
- The report is always `METRIC_UNVERIFIED` / `PHYSICAL_EVIDENCE_PENDING`. A photo cannot see uniform or anisotropic print scaling, and the homography absorbs most of a single misplaced marker (only above about 4 mm on A4). The owner ruler record, the pre-use verification and the PL-0068/PL-0220 caliper benchmark stay the only physical evidence.
- Tests (`tests/calibration/test_mat_photo_check.py`) use seeded synthetic renders of the real SVG with known homographies; they check the software math only.
2 changes: 1 addition & 1 deletion docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.csv
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ row_id,title,owner_system,status,task_ids,evidence
78,Photogrammetry Software,PackLab,partial,M07-M08 (checked); PL-0386; PL-0437; PL-0481,COLMAP/OpenMVS chain (core/src/packlab_core/reconstruction_orchestrator.py); 3/17 photos registered on one owner capture (PL-0481); PL-0437 needs physical ground truth
79,Packaging CAD Integration,PackLab,partial,PL-0289..PL-0302 (checked); PL-0498; PL-0471,"STEP import PR #83/#93, NIST 32/33 files imported (docs/ecosystem/PL-0498_NIST_STEP_INTEROP.md, PR #92); Design Model reference record open"
80,Parametric Bottle Designer,PackLab,partial,M11-M12 (checked); PL-0388; PL-0389; PL-0462; PL-0488; PL-0492,core/src/packlab_core/revolved_design_model.py; owner oval fit in real app (M21 REAL-APP CHECK 2026-11-30); PL-0462 repeatability and PL-0492 oval open
81,Packaging Measurement,PackLab,partial,PL-0202..PL-0219 (checked); PL-0068; PL-0220..PL-0224; PL-0387; PL-0446; PL-0501,"every dimension METRIC_UNVERIFIED; PL-0501 software calibration support not started and PL-0387/PL-0446 have open software parts; physical acceptance stays externally gated (printer, caliper; docs/calibration/verification-records/2026-10-04-a4-owner-print-v01.md REJECTED_MARKER_ENCODING)"
81,Packaging Measurement,PackLab,partial,PL-0202..PL-0219 (checked); PL-0068; PL-0220..PL-0224; PL-0387; PL-0446; PL-0501,"every dimension METRIC_UNVERIFIED; PL-0501 software calibration support in progress (printable mat reachable from Studio/CLI; one-photo mat check; result always METRIC_UNVERIFIED) and PL-0387/PL-0446 have open software parts; physical acceptance stays externally gated (printer, caliper; docs/calibration/verification-records/2026-10-04-a4-owner-print-v01.md REJECTED_MARKER_ENCODING)"
82,Label Design Studio,PackLab (geometry) / FormuLab (content),partial,PL-0310..PL-0317 (checked); PL-0497; PL-0487; PL-0475; PL-0511,"sleeve labels PR #80 (core/src/packlab_core/sleeve_label.py), Sleeve dialog not yet checked in real app; labels on every part open; FormuLab text PL-0511 blocked"
83,Dieline Generator,PackLab,partial,"PL-0313, PL-0314, PL-0317 (checked); PL-0496; PL-0497",carton dieline PR #73/#76 (core/src/packlab_core/carton_case.py) seen in real app 2026-11-30; sleeve dieline PR #80; print_ready=false until physical verification
84,Packaging Cost Calculator,ERP (costing),out_of_scope,PL-0500; PL-0510 (feed only),no prices in PackLab by design (docs/audits/PACKLAB_PROPOSED_BACKLOG.md section E); mass/material travel in the spec release
Expand Down
Loading