diff --git a/apps/windows-studio/src/packlab_studio/measure_view.py b/apps/windows-studio/src/packlab_studio/measure_view.py index 95a2c347..3ea0e37e 100644 --- a/apps/windows-studio/src/packlab_studio/measure_view.py +++ b/apps/windows-studio/src/packlab_studio/measure_view.py @@ -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 @@ -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 @@ -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() @@ -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) @@ -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 diff --git a/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0501_V01.md b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0501_V01.md new file mode 100644 index 00000000..a94440e2 --- /dev/null +++ b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0501_V01.md @@ -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). diff --git a/core/src/packlab_core/calibration/mat_photo_check.py b/core/src/packlab_core/calibration/mat_photo_check.py new file mode 100644 index 00000000..99cdb85a --- /dev/null +++ b/core/src/packlab_core/calibration/mat_photo_check.py @@ -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()) diff --git a/docs/calibration/mat-assets.md b/docs/calibration/mat-assets.md index 2b05d04d..f34acd65 100644 --- a/docs/calibration/mat-assets.md +++ b/docs/calibration/mat-assets.md @@ -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. diff --git a/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.csv b/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.csv index 67a041b2..fdc1d706 100644 --- a/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.csv +++ b/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.csv @@ -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 diff --git a/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.md b/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.md index 268030f9..97cb85d0 100644 --- a/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.md +++ b/docs/ecosystem/PL-0517_CAPABILITY_RECONCILIATION.md @@ -46,7 +46,7 @@ No row is `done`. Every PackLab row still has at least one open task, or a missi How the 44 PackLab rows split: -- 11 rows (076 to 083, 086, 090, 095) are packaging functions that PackLab owns. 10 are `partial` and 1 is `external`: 086 carton, which waits on a physical sample. 081 measurement is `partial`: PL-0501 software has not started, and PL-0387 and PL-0446 still have software parts. Its physical acceptance stays externally gated as well. +- 11 rows (076 to 083, 086, 090, 095) are packaging functions that PackLab owns. 10 are `partial` and 1 is `external`: 086 carton, which waits on a physical sample. 081 measurement is `partial`: PL-0501 software is in progress (printable mat reachable from Studio/CLI, one-photo mat check, result always METRIC_UNVERIFIED), and PL-0387 and PL-0446 still have software parts. Its physical acceptance stays externally gated as well. - 33 rows are shared or integration rows: PackLab supplies or consumes data and another system owns the capability. Under decision D3, pallet and container loads (085, 087) belong to the single ERP-side optimizer. Most of them depend on M21 tasks PL-0502 to PL-0514. Code for these is merged and tested against mocks and the gate stacks. The rest needs the production IdP and ERP (gates E3 and E4) and the owner as the linked approver. ## PackLab rows (44) @@ -64,7 +64,7 @@ How the 44 PackLab rows split: | 078 | 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 | | 079 | 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 | | 080 | 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 | -| 081 | 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) | +| 081 | 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) | | 082 | 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 | | 083 | 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 | | 084 | 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 | diff --git a/tests/calibration/test_mat_photo_check.py b/tests/calibration/test_mat_photo_check.py new file mode 100644 index 00000000..fa90e97e --- /dev/null +++ b/tests/calibration/test_mat_photo_check.py @@ -0,0 +1,154 @@ +"""PL-0501 mat photo check on seeded synthetic renders of the real SVG (software math only).""" + +from __future__ import annotations + +import math +import re +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pytest + +from packlab_core.calibration.mat_photo_check import check_mat_photo, main, mat_svg_path +from packlab_core.print_scale_sensitivity import load_calibration_mat_profile + +cv2 = pytest.importorskip("cv2") +PX_PER_MM = 6.0 +_CELL = re.compile(r"M([\d.]+),([\d.]+)h([\d.]+)v([\d.]+)") +_RECT = re.compile( + r' np.ndarray: + """Rasterize the mat's black marker cells and bar at PX_PER_MM (text/ticks ignored).""" + + profile = load_calibration_mat_profile(svg) + text = svg.read_text(encoding="utf-8") + page = np.full( + (round(profile.page_height_mm * PX_PER_MM), round(profile.page_width_mm * PX_PER_MM)), + 255, + np.uint8, + ) + for x, y, w, h in [*_CELL.findall(text), *_RECT.findall(text)]: + x0, y0 = round(float(x) * PX_PER_MM), round(float(y) * PX_PER_MM) + page[y0 : y0 + round(float(h) * PX_PER_MM), x0 : x0 + round(float(w) * PX_PER_MM)] = 0 + return page + + +def _capture(svg: Path, seed: int, print_scale: float = 1.0) -> tuple[np.ndarray, np.ndarray]: + """Seeded oblique photo of the mat: returns (image, ground-truth mm->px homography).""" + + rng = np.random.default_rng(seed) + profile = load_calibration_mat_profile(svg) + w, h = profile.page_width_mm, profile.page_height_mm + page_mm = np.float32([[0, 0], [w, 0], [w, h], [0, h]]) + jitter = rng.uniform(-60, 60, (4, 2)) + target = np.float32([[300, 120], [1300, 160], [1420, 1300], [200, 1250]] + jitter) + truth = cv2.getPerspectiveTransform(page_mm, target) + to_mm = np.diag([print_scale / PX_PER_MM, print_scale / PX_PER_MM, 1.0]) + image = cv2.warpPerspective( + _render_mat(svg), truth @ to_mm, (1600, 1400), flags=cv2.INTER_AREA, borderValue=128 + ) + image = cv2.GaussianBlur(image, (3, 3), 0.8) + noise = rng.normal(0, 3.0, image.shape) + return np.clip(image + noise, 0, 255).astype(np.uint8), truth + + +@pytest.mark.parametrize(("size", "seed"), [("a4", 1), ("a4", 7), ("a3", 3)]) +def test_synthetic_capture_recovers_known_mat_geometry(size: str, seed: int) -> None: + svg = mat_svg_path(size) + image, truth = _capture(svg, seed) + report = check_mat_photo(image, load_calibration_mat_profile(svg)) + assert report["status"] == "DETECTED_LAYOUT_CONSISTENT", report + assert report["detected_marker_ids"] == [0, 1, 2, 3] + assert report["corner_residual_max_mm"] < 0.5 + fitted = np.array(report["homography_mm_to_px"]) + profile = load_calibration_mat_profile(svg) + w, h = profile.page_width_mm, profile.page_height_mm + corners = np.array([[0, 0, 1], [w, 0, 1], [w, h, 1], [0, h, 1]], float) + expected = (corners @ truth.T)[:, :2] / (corners @ truth.T)[:, 2:] + got = (corners @ fitted.T)[:, :2] / (corners @ fitted.T)[:, 2:] + assert np.abs(expected - got).max() < 2.0 # px over the whole page + # Ground-truth mm/px: Jacobian of the true homography at the mat centre. + cx, cy = w / 2, h / 2 + denominator = truth[2] @ [cx, cy, 1.0] + u, v = (truth[:2] @ [cx, cy, 1.0]) / denominator + jacobian = (truth[:2, :2] - np.outer([u, v], truth[2, :2])) / denominator + true_mm_per_px = 1.0 / math.sqrt(abs(np.linalg.det(jacobian))) + assert report["mm_per_px_at_mat_centre"] == pytest.approx(true_mm_per_px, rel=1e-2) + # Synthetic truth checks the math; the result never becomes metric or physical evidence. + assert report["metric_status"] == "METRIC_UNVERIFIED" + assert report["physical_evidence"] == "PHYSICAL_EVIDENCE_PENDING" + assert report["print_check"]["status"] == "OWNER_RULER_MEASUREMENT_REQUIRED" + + +def test_occluded_marker_is_incomplete_and_ruler_gate_passes_through() -> None: + svg = mat_svg_path("a4") + image, truth = _capture(svg, 5) + centre = truth @ np.array([180.0, 247.0, 1.0]) # marker 3 centre + u, v = (centre[:2] / centre[2]).astype(int) + image[v - 150 : v + 150, u - 150 : u + 150] = 200 + report = check_mat_photo( + image, + load_calibration_mat_profile(svg), + spacing_x_mm=150.2, + spacing_y_mm=205.0, + marker_side_mm=40.1, + ) + assert report["status"] == "INCOMPLETE" + assert report["missing_marker_ids"] == [3] + assert report["print_check"]["status"] == "REJECTED_SCALING" + assert report["print_check"]["failed_readings"] == ["spacing_y"] + assert report["metric_status"] == "METRIC_UNVERIFIED" + + +def test_uniform_print_scale_error_is_invisible_to_the_photo() -> None: + """A 3 % fit-to-page print still looks consistent: only the ruler gate can catch it.""" + + svg = mat_svg_path("a4") + image, _truth = _capture(svg, 1, print_scale=0.97) + report = check_mat_photo( + image, + load_calibration_mat_profile(svg), + spacing_x_mm=145.5, + spacing_y_mm=200.8, + marker_side_mm=38.8, + ) + assert report["status"] == "DETECTED_LAYOUT_CONSISTENT" + assert report["print_check"]["status"] == "REJECTED_SCALING" + + +def test_cli_exports_printable_mat_and_checks_a_photo(tmp_path: Path, capsys) -> None: + exported = tmp_path / "mat.svg" + assert main(["--export-mat", str(exported)]) == 0 + assert exported.read_bytes() == mat_svg_path("a4").read_bytes() + photo = tmp_path / "photo.png" + image, _truth = _capture(mat_svg_path("a4"), 2) + assert cv2.imwrite(str(photo), image) + assert main([str(photo)]) == 0 + assert '"metric_status": "METRIC_UNVERIFIED"' in capsys.readouterr().out + + +def test_misplaced_marker_is_layout_inconsistent() -> None: + svg = mat_svg_path("a4") + image, _truth = _capture(svg, 4) + profile = load_calibration_mat_profile(svg) + shifted = tuple( + (i, x + 5.0, y) if i == 3 else (i, x, y) for i, x, y in profile.marker_origins_mm + ) + report = check_mat_photo(image, replace(profile, marker_origins_mm=shifted)) + assert report["status"] == "LAYOUT_INCONSISTENT" + assert report["corner_residual_max_mm"] > 1.0 + + +def test_cli_fails_on_rejected_ruler_and_reports_invalid_input(tmp_path: Path, capsys) -> None: + photo = tmp_path / "photo.png" + image, _truth = _capture(mat_svg_path("a4"), 2) + assert cv2.imwrite(str(photo), image) + ruler = ["--spacing-x-mm", "150.2", "--spacing-y-mm", "205.0", "--marker-side-mm", "40.1"] + assert main([str(photo), *ruler]) == 1 # layout consistent, but the print is rejected + assert '"status": "REJECTED_SCALING"' in capsys.readouterr().out + assert main([str(photo), "--spacing-x-mm=-1"]) == 2 + assert "ruler_spacing_x_mm_invalid" in capsys.readouterr().err diff --git a/tests/ci/test_owner_dev_launcher_contract.py b/tests/ci/test_owner_dev_launcher_contract.py index b7e931e2..251feadd 100644 --- a/tests/ci/test_owner_dev_launcher_contract.py +++ b/tests/ci/test_owner_dev_launcher_contract.py @@ -21,6 +21,12 @@ def test_production_spec_embeds_branding_asset_and_executable_icon() -> None: assert 'str(branding_path), "apps/windows-studio/assets/branding"' in spec +def test_production_spec_bundles_printable_calibration_mats() -> None: + # PL-0501: the Studio "Save printable mat" button reads assets/calibration in the frozen app. + spec = (ROOT / "tools/packaging/packlab_studio.spec").read_text(encoding="utf-8") + assert '(str(root / "assets" / "calibration"), "assets/calibration")' in spec + + def test_owner_scripts_use_stable_runtime_and_atomic_staging() -> None: deploy = (ROOT / "tools/dev/update_owner_dev_runtime.ps1").read_text(encoding="utf-8") launcher = (ROOT / "tools/dev/PackLabOwnerLauncher.cs").read_text(encoding="utf-8") diff --git a/tests/studio/test_measure_design.py b/tests/studio/test_measure_design.py index f5a0bf7f..e49e51e0 100644 --- a/tests/studio/test_measure_design.py +++ b/tests/studio/test_measure_design.py @@ -231,6 +231,18 @@ def test_print_correction_persists_and_scales_marker_side(window) -> None: assert reference.side_length == pytest.approx(39.2) +def test_save_printable_mat_writes_the_versioned_svg(window, tmp_path) -> None: + view = window.route_stack.views[Route.MEASURE_DESIGN] + target = tmp_path / "mat.svg" + view._choose_mat_save = lambda _parent, _name: str(tmp_path / "mat") # no suffix typed + view.save_mat_button.click() + source = ( + Path(__file__).resolve().parents[2] / "assets/calibration/a4-packlab-calibration-mat.svg" + ) + assert target.read_bytes() == source.read_bytes() + assert "print at 100 %" in view.status.text() + + def test_marker_scale_without_markers_points_to_manual(tmp_path) -> None: model_path = _scene(tmp_path / "scene") model = md.load_model(model_path) diff --git a/tools/packaging/packlab_studio.spec b/tools/packaging/packlab_studio.spec index 8a4c6fba..28003564 100644 --- a/tools/packaging/packlab_studio.spec +++ b/tools/packaging/packlab_studio.spec @@ -72,6 +72,7 @@ analysis = Analysis( (str(numpy_runtime_evidence), "."), (str(root / "tools" / "packaging" / "windows-runtime-prerequisite.json"), "."), (str(schema_path), "schemas"), + (str(root / "assets" / "calibration"), "assets/calibration"), (str(branding_path), "apps/windows-studio/assets/branding"), *copy_metadata("cadquery-ocp-novtk"), ],