diff --git a/README.md b/README.md index a36e324..bc98e80 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,11 @@ Recognized and rebuilt on the current release: - **Diagnostics**: `freecad/meshtofeatures_wb/scripts/probe_bore_placement.py` runs the full pipeline headlessly inside FreeCAD's Python console and prints quantitative per-feature checks (useful when reporting bugs). +- **Per-feature deviation report**: every rebuild ends (Report view) with + a FEATURE REPORT table — one line per planned feature with its status + (rebuilt / deferred / retried / geometrically dressed / SKIPPED) and the + correction volume measured next to it, plus the overall body/corrected + volume ratios. Nothing is silently missing from the rebuilt part. ## Limitations (please read before filing bugs) @@ -169,8 +174,9 @@ modules for the whole session). for comparing against the snapped result. - **MeshToFeatures panel…** — task panel with options and progress. 4. Watch the **Report view** (View → Panels → Report view): it lists - every recognized pattern/feature, every snap decision, and any - feature the executor had to retry or skip. + every recognized pattern/feature, every snap decision, and — at the + end of a rebuild — the per-feature deviation report (status + measured + deviation for every planned feature, and the overall volume ratios). ## Project layout diff --git a/ROADMAP.md b/ROADMAP.md index 4f18d8c..e1173c1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -103,7 +103,11 @@ Exit criteria: the report renders for a corpus part and for the corner bracket; numbers agree with the probe script's output; no new pipeline math — plumbing only. -Status: not started. +Status: **in development** — branch `feature/deviation-report` +(2026-11-08): `core/status.py` (execution ledger + attribution + table +builder, headless-tested), wired into `build_body` (prints the table to +the Report view, attaches `plan.feature_report` to the plan), +smoke-asserted row-per-feature invariant. ## Phase 4 — Dimensioned, constrained sketches diff --git a/freecad/meshtofeatures_wb/build.py b/freecad/meshtofeatures_wb/build.py index 315aba9..6e4757e 100644 --- a/freecad/meshtofeatures_wb/build.py +++ b/freecad/meshtofeatures_wb/build.py @@ -20,6 +20,8 @@ chamfer_corner_profile, fillet_edge_matches, hole_op_properties) from .core.fitting import _axis_frame +from .core.status import (ExecutionLedger, feature_report, + format_feature_report) # The Part volume of a mesh-converted shape must agree with the trimesh # volume within this relative tolerance, or the conversion is flagged @@ -132,7 +134,8 @@ def _point_placement(plan: BuildPlan, x: float, y: float, def _add_cone(doc, body, plan, name, x, y, z_lo, r_lo, r_hi, height, - additive=False, label="", deferred=None): + additive=False, label="", deferred=None, key=None, + ledger=None): """Cut (or add) a cone as a placed PartDesign primitive. ``Radius1`` is the radius at the BASE and ``Radius2`` at the top, so the @@ -144,6 +147,8 @@ def _add_cone(doc, body, plan, name, x, y, z_lo, r_lo, r_hi, height, cone running to a point) but not both. """ if height <= 0.0 or (r_lo <= 0.0 and r_hi <= 0.0): + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", "degenerate cone") return None kind = "PartDesign::AdditiveCone" if additive \ else "PartDesign::SubtractiveCone" @@ -153,6 +158,9 @@ def _add_cone(doc, body, plan, name, x, y, z_lo, r_lo, r_hi, height, App.Console.PrintError( f"[meshtofeatures] {label or name}: this FreeCAD has no " f"{kind} primitive ({exc}); the conical face is NOT rebuilt\n") + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", + f"no {kind} primitive") return None body.addObject(op) op.Radius1 = float(r_lo) @@ -162,12 +170,13 @@ def _add_cone(doc, body, plan, name, x, y, z_lo, r_lo, r_hi, height, if label: op.Label = label _apply_refine(op) - _rollback_if_broken(doc, body, op, deferred=deferred) + _rollback_if_broken(doc, body, op, deferred=deferred, key=key, + ledger=ledger) return op def _add_sphere(doc, body, plan, name, x, y, face_z, R, r_lo, r_hi, depth, - pad, additive, from_top, label=""): + pad, additive, from_top, label="", key=None, ledger=None): """Add (Revolution) or cut (Groove) a spherical cap about the frame-z axis at (x, y), rim on the face at ``face_z``. @@ -183,6 +192,8 @@ def _add_sphere(doc, body, plan, name, x, y, face_z, R, r_lo, r_hi, depth, """ import numpy as np if depth <= 0.0 or r_lo <= 0.0: + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", "degenerate cap") return None a_lo = math.sqrt(max(R * R - r_lo * r_lo, 0.0)) a_hi = math.sqrt(max(R * R - r_hi * r_hi, 0.0)) @@ -230,6 +241,8 @@ def _add_sphere(doc, body, plan, name, x, y, face_z, R, r_lo, r_hi, depth, f"{kind} feature ({exc}); the spherical face is NOT rebuilt\n") doc.removeObject(sk.Name) doc.recompute() + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", f"no {kind} feature") return None body.addObject(op) op.Profile = sk @@ -238,12 +251,12 @@ def _add_sphere(doc, body, plan, name, x, y, face_z, R, r_lo, r_hi, depth, if label: op.Label = label _apply_refine(op) - _rollback_if_broken(doc, body, op, sk) + _rollback_if_broken(doc, body, op, sk, key=key, ledger=ledger) return op def _add_torus(doc, body, plan, name, x, y, face_z, R, r, a, pad, additive, - from_top, label=""): + from_top, label="", key=None, ledger=None): """Add (Revolution) or cut (Groove) a rounded ring band about the frame-z axis at (x, y), rim annulus on the face at ``face_z``. @@ -259,6 +272,8 @@ def _add_torus(doc, body, plan, name, x, y, face_z, R, r, a, pad, additive, """ import numpy as np if r <= 0.0 or a >= r: + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", "degenerate band") return None s = math.sqrt(max(r * r - a * a, 0.0)) r_outer = R + s @@ -309,6 +324,8 @@ def _add_torus(doc, body, plan, name, x, y, face_z, R, r, a, pad, additive, f"{kind} feature ({exc}); the ring face is NOT rebuilt\n") doc.removeObject(sk.Name) doc.recompute() + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", f"no {kind} feature") return None body.addObject(op) op.Profile = sk @@ -317,7 +334,7 @@ def _add_torus(doc, body, plan, name, x, y, face_z, R, r, a, pad, additive, if label: op.Label = label _apply_refine(op) - _rollback_if_broken(doc, body, op, sk) + _rollback_if_broken(doc, body, op, sk, key=key, ledger=ledger) return op @@ -332,12 +349,16 @@ def _apply_refine(op): pass -def _rollback_if_broken(doc, body, op, sketch=None, deferred=None) -> bool: +def _rollback_if_broken(doc, body, op, sketch=None, deferred=None, key=None, + ledger=None) -> bool: """Recompute; if ``op`` failed, try to RECOVER it before giving up, and - if it must be removed, say so LOUDLY. (Field lesson: the 8th counterbore - shoulder terrace failed to compute on featuretype and was silently - deleted, leaving a standing wall at that one bore for ten versions -- - a silent drop hides the root cause.) Recovery ladder: + if it must be removed, say so LOUDLY. When ``key``=(kind, index) and + ``ledger`` are given, the same outcome is recorded on + :class:`~.core.status.ExecutionLedger` for the per-feature report. + (Field lesson: the 8th counterbore shoulder terrace failed to compute on + featuretype and was silently deleted, leaving a standing wall at that one + bore for ten versions -- a silent drop hides the root cause.) Recovery + ladder: 1. Refine off (Refine occasionally trips OCC on tricky shapes) 2. jitter Length by a relative 1e-4 (sub-mesh-tolerance; dodges boolean tangency/coincidence flakes, the classic OCC failure) @@ -387,7 +408,9 @@ def _is_broken(): print(msg.strip()) doc.removeObject(op.Name) doc.recompute() - deferred.append((sketch, spec)) + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "deferred") + deferred.append((sketch, spec, key)) return True # rung 2 (no-deferral contexts only): relative Length jitter @@ -425,6 +448,9 @@ def _is_broken(): f"was RECOVERED by an epsilon retry\n") App.Console.PrintMessage(msg) print(msg.strip()) + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "recovered", + "in-place boolean failure recovered by retry") return False msg = (f"[meshtofeatures] feature '{op.Label}' FAILED to compute " @@ -433,6 +459,8 @@ def _is_broken(): App.Console.PrintError(msg) App.Console.PrintMessage(msg) # message level: never filtered print(msg.strip()) + if key is not None and ledger is not None: + ledger.record(key[0], key[1], "skipped", "failed to compute") doc.removeObject(op.Name) if sketch is not None: doc.removeObject(sketch.Name) @@ -440,7 +468,7 @@ def _is_broken(): return True -def _lateral_pad(doc, body, plan, pad, k): +def _lateral_pad(doc, body, plan, pad, k, key=None, ledger=None): """A lateral pad (design note 36): material protruding sideways off a wall. The sketch sits on a plane perpendicular to the pad axis -- placement columns (u, v, axis) with the profile in (u, v) -- and the @@ -467,7 +495,7 @@ def _lateral_pad(doc, body, plan, pad, k): op.Length = float(pad.length) op.Label = pad.label or op.Name _apply_refine(op) - _rollback_if_broken(doc, body, op, s) + _rollback_if_broken(doc, body, op, s, key=key, ledger=ledger) def _geometric_blend(doc, body, blend, k, kind): @@ -684,9 +712,17 @@ def _apply_corrections(doc, body, plan: BuildPlan, name: str): def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): - """Create a PartDesign Body implementing ``plan``; returns the body.""" + """Create a PartDesign Body implementing ``plan``; returns the body. + + While building, records each planned op's outcome on an + :class:`~.core.status.ExecutionLedger` and, at the end, prints the + per-feature deviation report (phase 3) to the Report view; the rows are + also attached to ``plan.feature_report`` for programmatic checks. + """ body = doc.addObject("PartDesign::Body", name) + report_name = name # loops below reuse ``name``; keep the body name deferred = [] # failed CUTS to retry at the end of the chain + ledger = ExecutionLedger() base_entries = list(plan.base.profile) for hp in getattr(plan.base, "hole_profiles", []): @@ -714,7 +750,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): if p.label == "Gusset web": gusset_pads.append((k, p)) continue - _lateral_pad(doc, body, plan, p, k) + _lateral_pad(doc, body, plan, p, k, key=("pad", k), + ledger=ledger) continue top = getattr(p, "from_top", True) s = _circle_sketch(doc, body, plan, L if top else 0.0, p.profile, @@ -726,7 +763,7 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): op.Label = p.label or op.Name _apply_refine(op) s.Visibility = False - _rollback_if_broken(doc, body, op, s) + _rollback_if_broken(doc, body, op, s, key=("pad", k), ledger=ledger) for k, p in enumerate(plan.pockets): top = getattr(p, "from_top", True) @@ -753,11 +790,12 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): op.Label = p.label or op.Name _apply_refine(op) s.Visibility = False - _rollback_if_broken(doc, body, op, s, deferred=deferred) + _rollback_if_broken(doc, body, op, s, deferred=deferred, + key=("pocket", k), ledger=ledger) # gusset webs, now that the recess pockets exist to receive them for k, p in gusset_pads: - _lateral_pad(doc, body, plan, p, k) + _lateral_pad(doc, body, plan, p, k, key=("pad", k), ledger=ledger) for k, h in enumerate(plan.holes): import numpy as np @@ -815,9 +853,9 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): op.Profile = s props = hole_op_properties(h) props["Reversed"] = False # side is encoded in the placement - for name, value in props.items(): - if hasattr(op, name): - setattr(op, name, value) + for prop, value in props.items(): + if hasattr(op, prop): + setattr(op, prop, value) op.Label = h.label or op.Name _apply_refine(op) doc.recompute() @@ -837,6 +875,9 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): # bottom-face countersink.) if op is not None: doc.removeObject(op.Name) + if ledger is not None: + ledger.record("hole", k, "fallback", + "PartDesign::Hole unusable; pocket cut") op = doc.addObject("PartDesign::Pocket", f"Hole{k}") body.addObject(op) op.Profile = s @@ -856,7 +897,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): op.Length = float(h.depth) + cb_extra op.Label = h.label or op.Name _apply_refine(op) - _rollback_if_broken(doc, body, op, s, deferred=deferred) + _rollback_if_broken(doc, body, op, s, deferred=deferred, + key=("hole", k), ledger=ledger) if h.counterbore_diameter: # For a BELOW-TOP bore, grow the counterbore circle by the # SAME 1.5*tol buffer the terraces get. The reconstructed @@ -888,7 +930,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): op2.Length = float(h.counterbore_depth) + cb_extra _apply_refine(op2) s2.Visibility = False - _rollback_if_broken(doc, body, op2, s2, deferred=deferred) + _rollback_if_broken(doc, body, op2, s2, deferred=deferred, + key=("counterbore", k), ledger=ledger) if h.countersink_diameter: # The pocket path cuts cylinders only, so the CONICAL entry # of a countersunk or counterdrilled hole used to be dropped @@ -919,7 +962,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): for pos in h.positions: _add_cone(doc, body, plan, f"Countersink{k}", pos[0], pos[1], z_lo, r_lo, r_hi, run, - label=f"Countersink{k}", deferred=deferred) + label=f"Countersink{k}", deferred=deferred, + key=("countersink", k), ledger=ledger) doc.recompute() doc.recompute() @@ -967,7 +1011,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): for pos in c.positions: _add_cone(doc, body, plan, name, pos[0], pos[1], z_lo, r_lo, r_hi, height, additive=c.additive, - label=c.label or name, deferred=deferred) + label=c.label or name, deferred=deferred, + key=("cone", k), ledger=ledger) doc.recompute() # ---- spherical features: revolved arc caps (Revolution/Groove) -------- @@ -986,7 +1031,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): face_z, float(s.radius), float(s.rim_radius), float(s.top_radius), float(s.depth), pad, additive=s.additive, from_top=s.from_top, - label=s.label or name) + label=s.label or name, key=("sphere", k), + ledger=ledger) # ---- ring bands: revolved arc tori (Revolution/Groove) ----------------- for k, t in enumerate(getattr(plan, "tori", [])): try: @@ -1003,7 +1049,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): face_z, float(t.major_radius), float(t.minor_radius), float(t.a_center), pad, additive=t.additive, from_top=t.from_top, - label=t.label or name) + label=t.label or name, key=("torus", k), + ledger=ledger) doc.recompute() # ---- cross-axis holes: through = midplane pocket, blind = Length ------- @@ -1082,7 +1129,8 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): op.Midplane = True op.Label = ch.label or op.Name _apply_refine(op) - _rollback_if_broken(doc, body, op, s, deferred=deferred) + _rollback_if_broken(doc, body, op, s, deferred=deferred, + key=("cross-hole", k), ledger=ledger) # ---- horizontal fillets: geometric edge matching on the sharp body ---- # No topological names are trusted: for each FilletOp, straight edges @@ -1106,7 +1154,12 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): for fo in getattr(plan, "fillets", [])] dressups += [("PartDesign::Chamfer", "Size", co.size, co) for co in getattr(plan, "chamfers", [])] + n_fillets = len(getattr(plan, "fillets", [])) for k, (type_id, prop, value, fo) in enumerate(dressups): + # the row key: a dressup's position within ITS OWN op list, so + # Dressup k maps back to plan.fillets / plan.chamfers correctly + blk = "fillet" if k < n_fillets else "chamfer" + bi = k if k < n_fillets else k - n_fillets names = [] for idx, edge in enumerate(prev.Shape.Edges): try: @@ -1127,12 +1180,16 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): # at the mesh-fit position instead of dropping it. fb = _geometric_blend(doc, body, fo, k, "fillet") if fb is not None: + ledger.record(blk, bi, "geometric", + "no parametric edge; dressed at the " + "mesh-fit edge") prev = fb continue App.Console.PrintWarning( f"[meshtofeatures] no body edge matched " f"{type_id.rsplit('::', 1)[-1].lower()} " f"'{fo.label}'; skipped\n") + ledger.record(blk, bi, "skipped", "no body edge matched") continue op = doc.addObject(type_id, f"Dressup{k}") body.addObject(op) @@ -1146,6 +1203,7 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): App.Console.PrintWarning( f"[meshtofeatures] fillet '{fo.label}' failed to compute; " f"removing\n") + ledger.record(blk, bi, "skipped", "dress-up failed to compute") doc.removeObject(op.Name) doc.recompute() else: @@ -1157,7 +1215,7 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): # is identical to the planned one. The re-add mirrors the field-verified # probe retry EXACTLY: pristine sketch, Profile + Length only (Type set # only when non-default), no Refine, label applied only after validation. - for sketch, spec in deferred: + for sketch, spec, key in deferred: msg = (f"[meshtofeatures] retrying deferred cut " f"'{spec.get('Label')}' at the end of the chain\n") App.Console.PrintMessage(msg) @@ -1193,9 +1251,26 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): f"chain\n") App.Console.PrintMessage(msg) print(msg.strip()) + if key is not None: + ledger.record(key[0], key[1], "deferred", + "rebuilt at the end of the chain") # ---- deviation correction: mesh-accurate terminal shape --------------- - _apply_corrections(doc, body, plan, name) + corr_feat = _apply_corrections(doc, body, plan, name) doc.recompute() + try: + rows, unattr = feature_report(plan, ledger) + plan.feature_report = rows + for ln in format_feature_report( + rows, + src_volume=getattr(plan, "src_volume", None), + body_volume=float(body.Shape.Volume), + corrected_volume=None if corr_feat is None + else float(corr_feat.Shape.Volume), + unattributed=unattr, name=report_name): + App.Console.PrintMessage(f"[meshtofeatures] {ln}\n") + except Exception as exc: # noqa: BLE001 + App.Console.PrintWarning( + f"[meshtofeatures] feature report unavailable: {exc}\n") return body diff --git a/freecad/meshtofeatures_wb/commands.py b/freecad/meshtofeatures_wb/commands.py index 9a6432c..065ea10 100644 --- a/freecad/meshtofeatures_wb/commands.py +++ b/freecad/meshtofeatures_wb/commands.py @@ -160,6 +160,7 @@ def Activated(self): # noqa: N802 feats = detect_features(report, patches) plan = plan_history(report, feats, detect_patterns(feats), patches) + plan.src_volume = float(tm.volume) # feature-report ratio denom try: from .core.solidify import add_corrections add_corrections(plan, tm) diff --git a/freecad/meshtofeatures_wb/core/__init__.py b/freecad/meshtofeatures_wb/core/__init__.py index 2421152..316d381 100644 --- a/freecad/meshtofeatures_wb/core/__init__.py +++ b/freecad/meshtofeatures_wb/core/__init__.py @@ -26,6 +26,8 @@ from .solidify import (CorrectionOp, add_corrections, apply_corrections, boolean_engine_available, plan_corrections, plan_to_mesh) +from .status import (ExecutionLedger, FeatureRow, attribute_corrections, + feature_report, format_feature_report) __version__ = "0.18.0" __all__ = [ @@ -47,4 +49,6 @@ "split_by_planes", "split_by_channels", "CorrectionOp", "boolean_engine_available", "plan_to_mesh", "plan_corrections", "apply_corrections", "add_corrections", + "ExecutionLedger", "FeatureRow", "attribute_corrections", + "feature_report", "format_feature_report", ] diff --git a/freecad/meshtofeatures_wb/core/status.py b/freecad/meshtofeatures_wb/core/status.py new file mode 100644 index 0000000..4f70c84 --- /dev/null +++ b/freecad/meshtofeatures_wb/core/status.py @@ -0,0 +1,378 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Per-feature deviation report (phase 3): the trust data as a table. + +The pipeline already MEASURES its own trust: :func:`.solidify.plan_corrections` +localizes the deviation between the parametric rebuild and the source mesh +as OVER/UNDER patch components; :func:`.build.build_body` records (via the +executor's loud logging, now via an :class:`ExecutionLedger`) which features +were rebuilt, deferred, recovered, dressed geometrically, or skipped; +``plan.unplanned`` and ``plan.undressable`` name what recognition saw but the +model could not rebuild. None of it was ever shown as ONE view. This module +is the plumbing that composes those existing numbers into per-feature rows +-- no new pipeline math: attribution only, matching each already-computed +correction component to the planned feature it lies nearest to. + +Pure Python (numpy only), FreeCAD-free, so the whole report is testable +without the executor. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +__all__ = ["EXECUTION_STATUSES", "ExecutionLedger", "FeatureRow", + "attribute_corrections", "feature_report", + "format_feature_report"] + +#: Executor outcome per planned op. ``rebuilt`` is the default (a feature +#: that computes and stays in the chain); ``deferred`` means it failed in +#: place and was rebuilt at the END of the chain (same solid, later step); +#: ``recovered`` means an epsilon retry fixed an in-place failure; +#: ``geometric`` means a blend dressed at the mesh-fit position because the +#: parametric body had no edge there; ``fallback`` means the semantic +#: PartDesign feature was unavailable and a pocket/primitive cut was used; +#: ``skipped`` means the feature is NOT in the rebuilt part. +EXECUTION_STATUSES = frozenset( + {"rebuilt", "deferred", "recovered", "geometric", "fallback", "skipped"}) + +#: merge priority when several events hit one planned op: failures outrank +#: successes so a skip is never hidden by a sibling sub-op's success +_STATUS_RANK = {"rebuilt": 0, "recovered": 1, "fallback": 1, + "geometric": 1, "deferred": 2, "skipped": 3} + +#: the table prints human status words +_STATUS_LABEL = { + "rebuilt": "rebuilt", + "deferred": "deferred -> rebuilt at chain end", + "recovered": "rebuilt (after retry)", + "geometric": "rebuilt (geometric dress)", + "fallback": "rebuilt (pocket fallback)", + "skipped": "SKIPPED - not in the part", +} + +#: ledger categories that are SUB-cuts of another row's feature: recorded +#: under their own key so a sub-op failure can never mask (or be masked by) +#: the parent feature's own outcome, and rolled up into the parent row's +#: detail (a drop is never silent, but never a lie either). +_SUB_KINDS = {"hole": ("counterbore", "countersink")} + + +class ExecutionLedger: + """What the executor did with each planned op: ``record(kind, k, ...)`` + from the build loops; ``get(kind, k)`` for the report. Ops with no + recorded event default to ``rebuilt``.""" + + def __init__(self): + self._events: dict[tuple[str, int], tuple[str, str]] = {} + + def record(self, kind: str, k: int, status: str, detail: str = "") -> None: + if status not in EXECUTION_STATUSES: + raise ValueError(f"unknown status {status!r}") + key = (kind, k) + cur = self._events.get(key) + if cur is not None: + rank_cur, rank_new = _STATUS_RANK[cur[0]], _STATUS_RANK[status] + if rank_cur > rank_new: + return # never hide the worse outcome + if rank_cur == rank_new and cur[0] == status and cur[1] \ + and detail and cur[1] != detail: + self._events[key] = (status, f"{cur[1]}; {detail}") + return + self._events[key] = (status, detail) + + def get(self, kind: str, k: int) -> tuple[str, str]: + return self._events.get((kind, k), ("rebuilt", "")) + + +@dataclass +class FeatureRow: + """One table line: a planned feature, how the executor treated it, and + the deviation volume attributed to it (mm3; ``+`` = the rebuild lacks + material there (UNDER), ``-`` = the rebuild overshoots (OVER)); ``0`` + when no correction component belongs to this feature.""" + + kind: str # plan category: 'hole', 'pocket', ... + label: str + status: str # EXECUTION_STATUSES member ('unplanned' + # and 'undressable' for never-planned) + detail: str = "" + deviation_mm3: float = 0.0 + + +def _frame_of(plan) -> np.ndarray: + t = np.eye(4) + t[:3, 0] = plan.frame_x + t[:3, 1] = plan.frame_y + t[:3, 2] = plan.frame_z + t[:3, 3] = plan.frame_origin + return t + + +def _to_world(plan, pts) -> list[np.ndarray]: + m = _frame_of(plan) + return [(m @ np.array([p[0], p[1], p[2], 1.0]))[:3] for p in pts] + + +def _loop_centroid(profile): + """Rough in-plane centroid of a sketch profile (its point primitives), + or ``None`` when the profile carries no points at all (a malformed op: + no site, so no deviation can be attributed to it -- never a bogus + point at the frame origin).""" + pts = [] + for p in profile or []: + for attr in ("start", "end"): + q = getattr(p, attr, None) + if q is not None: + pts.append(np.asarray([float(q[0]), float(q[1])])) + c = getattr(p, "center", None) + if c is not None: + pts.append(np.asarray([float(c[0]), float(c[1])])) + if not pts: + return None + return sum(pts) / len(pts) + + +def op_sites(plan) -> list[list[np.ndarray]]: + """Representative WORLD points of every planned op, in :func:`plan_ops` + order: where the feature lives, as a point set the deviation components + can be matched against.""" + L = float(plan.base.length) + sites: list[list[np.ndarray]] = [] + + base_c = _loop_centroid(plan.base.profile) + sites.append([] if base_c is None + else _to_world(plan, [(base_c[0], base_c[1], L / 2.0)])) + + for p in getattr(plan, "pads", []): + if getattr(p, "axis", None) is not None: + po = getattr(p, "plane_origin", None) + # one site per pad row (alignment with plan_ops order is part of + # the contract); a lateral pad without a recorded plane origin + # falls back to the part centre rather than dropping the row + if po is not None: + sites.append([np.asarray(po, dtype=float)]) + else: + sites.append(_to_world(plan, [(0.0, 0.0, L / 2.0)])) + continue + c = _loop_centroid(p.profile) + if c is None: + sites.append([]) + continue + face = L if getattr(p, "from_top", True) else 0.0 + out = face + p.length if getattr(p, "from_top", True) else face - p.length + sites.append(_to_world(plan, [(c[0], c[1], face), (c[0], c[1], out)])) + + for pk in getattr(plan, "pockets", []): + c = _loop_centroid(pk.profile) + if c is None: + sites.append([]) + continue + top = getattr(pk, "from_top", True) + if top: + face, far = L, (0.0 if getattr(pk, "through", False) + else L - float(pk.depth)) + else: + face, far = 0.0, (L if getattr(pk, "through", False) + else float(pk.depth)) + sites.append(_to_world(plan, [(c[0], c[1], face), (c[0], c[1], far)])) + + for h in getattr(plan, "holes", []): + top = getattr(h, "from_top", True) + open_z = (float(h.surface_z) if getattr(h, "surface_z", None) + is not None else (L if top else 0.0)) + if getattr(h, "through", False): + far_z = 0.0 if top else L + else: + far_z = open_z - float(h.depth) if top else open_z + float(h.depth) + pts = [] + for (x, y) in h.positions: + pts.append((float(x), float(y), open_z)) + pts.append((float(x), float(y), far_z)) + cb = getattr(h, "counterbore_depth", None) + if getattr(h, "counterbore_diameter", None) and cb: + pts.append((float(x), float(y), + open_z - float(cb) if top else open_z + float(cb))) + sites.append(_to_world(plan, pts)) + + for ch in getattr(plan, "cross_holes", []): + sites.append([np.asarray(p, dtype=float) for p in ch.positions3d]) + + for op in list(getattr(plan, "cones", [])) \ + + list(getattr(plan, "spheres", [])) \ + + list(getattr(plan, "tori", [])): + face = (float(op.surface_z) if getattr(op, "surface_z", None) + is not None else (L if op.from_top else 0.0)) + pts = [(float(x), float(y), face) for (x, y) in op.positions] + pts += [(float(x) + 0.5 * float(getattr(op, "rim_radius", 0.0)), + float(y), face) for (x, y) in op.positions] + sites.append(_to_world(plan, pts)) + + for op in list(getattr(plan, "fillets", [])) \ + + list(getattr(plan, "chamfers", [])): + mid = 0.5 * (np.asarray(op.edge_start, dtype=float) + + np.asarray(op.edge_end, dtype=float)) + sites.append([mid]) + return sites + + +def plan_ops(plan): + """(category, index, op) for every planned feature, in report order + (matches :func:`op_sites` order).""" + yield ("base", 0, plan.base) + for k, op in enumerate(getattr(plan, "pads", [])): + yield ("pad", k, op) + for k, op in enumerate(getattr(plan, "pockets", [])): + yield ("pocket", k, op) + for k, op in enumerate(getattr(plan, "holes", [])): + yield ("hole", k, op) + for k, op in enumerate(getattr(plan, "cross_holes", [])): + yield ("cross-hole", k, op) + for k, op in enumerate(getattr(plan, "cones", [])): + yield ("cone", k, op) + for k, op in enumerate(getattr(plan, "spheres", [])): + yield ("sphere", k, op) + for k, op in enumerate(getattr(plan, "tori", [])): + yield ("torus", k, op) + for k, op in enumerate(getattr(plan, "fillets", [])): + yield ("fillet", k, op) + for k, op in enumerate(getattr(plan, "chamfers", [])): + yield ("chamfer", k, op) + + +def _diag(plan) -> float: + xs, ys = [0.0], [0.0] + for p in plan.base.profile or []: + for attr in ("start", "end"): + q = getattr(p, attr, None) + if q is not None: + xs.append(float(q[0])) + ys.append(float(q[1])) + diag = float(np.hypot(max(xs) - min(xs), max(ys) - min(ys))) + return max(float(np.hypot(diag, float(plan.base.length))), 1e-9) + + +def attribute_corrections(plan, tol: float | None = None): + """Assign each plan_corrections component to the planned feature whose + site set lies closest to the component's centroid. + + Returns a list sized like :func:`plan_ops`: signed mm3 per feature + (``+`` UNDER -- the rebuild lacks this material there, ``-`` OVER -- + the rebuild overshoots) plus the total unattributed mm3 (a patch too + far from every feature -- a freeform transition no feature owns). + ``tol`` defaults to 10% of the part diagonal: a component beyond every + feature's extent is freeform, not the feature's fault. + """ + ops = list(plan_ops(plan)) + sites = op_sites(plan) + out = [0.0] * len(ops) + unattr_under = unattr_over = 0.0 + if not sites: + return out, (0.0, 0.0) + if tol is None: + tol = 0.10 * _diag(plan) + for corr in getattr(plan, "corrections", None) or []: + comp = getattr(corr, "mesh", None) + if comp is None or len(comp.faces) == 0: + continue + c = np.asarray(comp.centroid, dtype=float) + # an op with no usable site points (malformed plan) can never + # attract a component: +inf so the nearest-feature search skips it + dists = [(min(float(np.linalg.norm(c - p)) for p in s) if s + else float("inf")) for s in sites] + j = int(np.argmin(dists)) + # OVER is 'cut' (remove from rebuild), UNDER is 'add' + signed = float(corr.volume) if corr.kind == "add" \ + else -float(corr.volume) + if dists[j] > tol: + if signed >= 0: + unattr_under += signed + else: + unattr_over += -signed + continue + out[j] += signed + return out, (unattr_under, unattr_over) + + +def _op_label(kind: str, k: int, op) -> str: + lab = getattr(op, "label", "") or "" + return lab or f"{kind.capitalize()} {k}" + + +def feature_report(plan, ledger: ExecutionLedger | None = None): + """One :class:`FeatureRow` per planned feature (executor status + + attributed deviation), then the unplanned/undressable detections, then + the correction-pass summary. Numbers are the ones other pipeline + stages already computed; nothing here re-fits anything.""" + ledger = ledger or ExecutionLedger() + dev, (un_under, un_over) = attribute_corrections(plan) + rows: list[FeatureRow] = [] + for i, (kind, k, op) in enumerate(plan_ops(plan)): + status, detail = ledger.get(kind, k) + # sub-cut failures (counterbore/countersink of a hole) never change + # the parent's status -- they could lie about a recovered bore or + # hide behind one -- they are rolled into the detail instead, loud + # enough that grepping the report for a failure word finds it + subs = [] + for sub in _SUB_KINDS.get(kind, ()): + sst, sdt = ledger.get(sub, k) + if sst != "rebuilt": + subs.append(_STATUS_LABEL.get(sst, sst) + + (f" ({sdt})" if sdt else "") + f" [{sub}]") + if subs: + detail = "; ".join([detail] + subs) if detail else "; ".join(subs) + rows.append(FeatureRow(kind=kind, label=_op_label(kind, k, op), + status=status, detail=detail, + deviation_mm3=dev[i] if i < len(dev) else 0.0)) + for item in getattr(plan, "unplanned", []): + rows.append(FeatureRow(kind="unplanned", label=str(item), + status="unplanned", + detail="outside the single-axis prismatic model")) + for item in getattr(plan, "undressable", []): + rows.append(FeatureRow(kind="blend", label=str(item), + status="undressable", + detail="detected, undressable: degenerate frame")) + return rows, (un_under, un_over) + + +def format_feature_report(rows, *, src_volume=None, body_volume=None, + corrected_volume=None, unattributed=(0.0, 0.0), + name="") -> list[str]: + """The table as plain report-view lines. Overall volume ratios come + from the existing pipeline numbers (source mesh, parameteric body, + corrected solid), never from new measurements.""" + lines = [] + head = "FEATURE REPORT" + (f" for {name}" if name else "") + ratios = [] + if src_volume and body_volume is not None: + ratios.append(f"body {100.0 * body_volume / src_volume:.2f}% " + f"of source volume") + if src_volume and corrected_volume is not None: + ratios.append(f"corrected " + f"{100.0 * corrected_volume / src_volume:.2f}%") + if ratios: + head += " (" + ", ".join(ratios) + ")" + lines.append(head) + un_under, un_over = unattributed + for r in rows: + status = _STATUS_LABEL.get(r.status, r.status) + dev = "" + if abs(r.deviation_mm3) > 0.0: + side = "under" if r.deviation_mm3 > 0 else "over" + dev = f" {abs(r.deviation_mm3):.2f} mm3 {side}" + detail = f" ({r.detail})" if r.detail else "" + lines.append(f" {status:36} {r.label:34}{detail}{dev}") + tail = [] + if any(abs(r.deviation_mm3) > 0.0 for r in rows): + tail.append("mm3: deviation of the parametric model from the " + "source mesh -- exactly the patches the terminal " + "correction pass absorbs; not the body's own error") + if un_under or un_over: + tail.append("freeform deviation carried by the correction pass: " + f"{un_under:.2f} mm3 under, {un_over:.2f} mm3 over") + for t in tail: + lines.append(" " + t) + if not rows: + lines.append(" (nothing planned to rebuild)") + return lines diff --git a/freecad/meshtofeatures_wb/docs/VERIFY.md b/freecad/meshtofeatures_wb/docs/VERIFY.md index 7d5a75d..ad5d88a 100644 --- a/freecad/meshtofeatures_wb/docs/VERIFY.md +++ b/freecad/meshtofeatures_wb/docs/VERIFY.md @@ -95,7 +95,20 @@ as PartDesign body" on a part with horizontal rounded edges should show Fillet features at the end of the tree; report any "no body edge matched" warnings with the part. -## 6. Known limitations (do not report as bugs) +## 6. Per-feature deviation report (v0.19) + +After any **Rebuild as PartDesign body**, the Report view ends with a +FEATURE REPORT table: one line for every planned feature — its executor +status (`rebuilt`, `deferred -> rebuilt at chain end`, `rebuilt (after +retry)`, `SKIPPED - not in the part`, ...) and the deviation the terminal +correction pass carries next to it (mm3, `+` = the rebuild lacks material, +`-` = it overshoots), followed by the unplanned/undressable detections and +the overall volume ratios (parametric body and corrected, vs the source +mesh). Check: the table lists every feature you can see in the body tree; +a feature the executor had to skip says so LOUDLY in the table — never a +silent absence. The smoke test asserts the row-per-feature invariant. + +## 7. Known limitations (do not report as bugs) The rebuild emits an editable PartDesign Body (a real solid with history), not just surface patches. The remaining limitations are documented in the diff --git a/freecad/meshtofeatures_wb/docs/design-notes.md b/freecad/meshtofeatures_wb/docs/design-notes.md index b9ed26c..6c289ee 100644 --- a/freecad/meshtofeatures_wb/docs/design-notes.md +++ b/freecad/meshtofeatures_wb/docs/design-notes.md @@ -716,9 +716,41 @@ v0.15.6 (lateral pads): `apply_corrections` pre-fuses the patches into ONE boolean so the big solid is re-quantized once, not once per patch (bracket: 0.9953 → 0.9995 of the source volume). The safety net is the - volume gate in `_shape_from_mesh`: Part volume vs trimesh volume, - loud warning above 1% drift — a silent wrong-volume Compound is - exactly what the gate exists to make audible. + volume gate in `_shape_from_mesh`: Part volume vs trimesh volume, + loud warning above 1% drift — a silent wrong-volume Compound is + exactly what the gate exists to make audible. + + 53. **The trust numbers become a table: the per-feature deviation + report** (phase 3). Every number the pipeline already computes was + scattered — the correction components (note 44-style OVER/UNDER + volumes), the executor's loud retry/defer/skip lines, the volume + gate, `unplanned`/`undressable` — and none of it reached the user + as ONE view. `core.status` composes them: the executor reports + terminal outcomes into an `ExecutionLedger` keyed by (category, + planned-index) — deferred, recovered, skipped, geometric dress, + pocket fallback — with severity-ranked merge so a later success + can never hide a failure (skipped > deferred > recovered/fallback + > rebuilt); `feature_report` emits exactly one + :class:`core.status.FeatureRow` per planned op (never a silent + partial table), appends the unplanned/undressable entries, and + attributes each `plan_corrections` component by centroid distance + to the nearest op's site set (10% of the part diagonal as the + freeform gate — a patch farther than that from every feature is + freeform transition, not the feature's fault). Sign convention: + `+` mm3 = the rebuild LACKS material there (UNDER), `-` = + OVERSHOOT. Attribution, not new math: no new fitting, sampling or + surface-distance measurement — the components are the already- + computed two-way deviation. `build_body` prints the table to the + Report view and attaches it to `plan.feature_report` so the smoke + test (and bug reports) can assert row-per-feature mechanically. + Sub-cut events (a deferred hole's countersink cone is the field + case) use their OWN ledger keys (`counterbore`/`countersink`, rolled + up into the hole row's DETAIL): a `skipped` sub-cut must never + overwrite the parent's `deferred` status, because the parent's + chain-end recovery is recorded after the cone's failure and the + severity merge would then silence the truth (review finding: the + merge is "worst outcome per KEY", so the key is the unit of the + claim — keep sub-feature events on sub-feature keys). ## Run tests diff --git a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py index 2240ac9..ca16dbe 100644 --- a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py +++ b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py @@ -190,6 +190,19 @@ def check(name, cond, info=""): f"{cbody.Shape.Volume:.2f} vs {cb_solid.Volume:.2f}") check("counterbore body shape is valid", cbody.Shape.isValid()) +# --- per-feature deviation report (phase 3) ---------------------------------- +# build_body must attach one report row per planned feature -- the trust +# table shown in the Report view; never a silent partial table. +freq = getattr(cplan, "feature_report", None) or [] +_planned = (1 + len(cplan.pads) + len(cplan.pockets) + len(cplan.holes) + + len(cplan.cross_holes) + len(cplan.cones) + len(cplan.spheres) + + len(cplan.tori) + len(cplan.fillets) + len(cplan.chamfers)) +check("feature report has one row per planned feature", + len(freq) == _planned + len(cplan.unplanned) + len(cplan.undressable), + f"{len(freq)} rows for {_planned} planned") +check("feature report all-clean: every executed feature rebuilt", + all(r.status == "rebuilt" for r in freq)) + # --- PartDesign Hole feature (countersunk plate) ---------------------------- # drill (d5) through a 5 mm plate with a 90 deg countersink to d10 at the top cs_solid = Part.makeBox(40, 30, 5, App.Vector(-20, -15, 0)) \ diff --git a/freecad/meshtofeatures_wb/tests/test_deviation_report.py b/freecad/meshtofeatures_wb/tests/test_deviation_report.py new file mode 100644 index 0000000..919bcfc --- /dev/null +++ b/freecad/meshtofeatures_wb/tests/test_deviation_report.py @@ -0,0 +1,226 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Per-feature deviation report (phase 3): pure-headless tests. + +Covers the report plumbing (``core.status``): the ledger's merge rules, the +correction-to-feature attribution, the row builder over real plans (corpus +plate + the issue-#5 corner bracket), and the report-view formatting. No +FreeCAD, no executor -- build.py wires this same module in and feeds it the +runtime ledger. +""" + +import numpy as np +import pytest +import trimesh + +from freecad.meshtofeatures_wb.core.emission import plan_patches +from freecad.meshtofeatures_wb.core.features import detect_features +from freecad.meshtofeatures_wb.core.history import plan_history +from freecad.meshtofeatures_wb.core.patterns import detect_patterns +from freecad.meshtofeatures_wb.core.pipeline import reconstruct +from freecad.meshtofeatures_wb.core.snapping import snap_report +from freecad.meshtofeatures_wb.core.solidify import CorrectionOp +from freecad.meshtofeatures_wb.core.status import ( + ExecutionLedger, + attribute_corrections, + feature_report, + format_feature_report, + op_sites, + plan_ops, +) + +from pathlib import Path + +FIXTURES = Path(__file__).resolve().parent / "fixtures" + + +def _plan(name): + mesh = trimesh.load(str(FIXTURES / name), force="mesh") + report = snap_report(reconstruct(mesh)).report + patches = plan_patches(report) + feats = detect_features(report, patches) + return plan_history(report, feats, detect_patterns(feats), patches) + + +@pytest.fixture(scope="module") +def cb_plan(): + return _plan("corpus_plate_counterbored.stl") + + +@pytest.fixture(scope="module") +def bracket_plan(): + return _plan("Simple_Corner_Bracket.stl") + + +def _world(plan, x, y, z): + return (np.asarray(plan.frame_origin, float) + + x * np.asarray(plan.frame_x, float) + + y * np.asarray(plan.frame_y, float) + + z * np.asarray(plan.frame_z, float)) + + +class TestLedger: + def test_default_rebuilt(self): + led = ExecutionLedger() + assert led.get("pocket", 3) == ("rebuilt", "") + + def test_records_win_by_severity(self): + led = ExecutionLedger() + led.record("hole", 0, "fallback", "pocket cut") + led.record("hole", 0, "deferred") + assert led.get("hole", 0)[0] == "deferred" + led.record("hole", 0, "recovered", "retry") + assert led.get("hole", 0)[0] == "deferred" + led.record("hole", 0, "skipped", "failed to compute") + assert led.get("hole", 0)[0] == "skipped" + + def test_details_merge_on_equal_severity(self): + led = ExecutionLedger() + led.record("hole", 1, "skipped", "cone site A") + led.record("hole", 1, "skipped", "cone site B") + status, detail = led.get("hole", 1) + assert status == "skipped" + assert "site A" in detail and "site B" in detail + + def test_unknown_status_rejected(self): + led = ExecutionLedger() + with pytest.raises(ValueError): + led.record("pocket", 0, "exploded") + + +class TestRowBuilding: + def test_one_row_per_planned_op(self, cb_plan): + rows, _ = feature_report(cb_plan) + n_planned = len(list(plan_ops(cb_plan))) + assert len(rows) == n_planned + len(cb_plan.unplanned) \ + + len(cb_plan.undressable) + executed = [r for r in rows + if r.kind in ("hole", "pocket", "pad", "base", + "cross-hole", "cone", "sphere", "torus")] + assert all(r.status == "rebuilt" for r in executed) + + def test_sites_align_with_ops(self, cb_plan, bracket_plan): + for plan in (cb_plan, bracket_plan): + sites = op_sites(plan) + assert len(sites) == len(list(plan_ops(plan))) + assert all(len(s) >= 1 for s in sites) + + def test_ledger_status_flows_to_rows(self, cb_plan): + led = ExecutionLedger() + led.record("hole", 0, "skipped", "failed to compute") + led.record("hole", 1, "geometric", "mesh-fit edge") + rows, _ = feature_report(cb_plan, led) + holes = [r for r in rows if r.kind == "hole"] + assert holes[0].status == "skipped" + assert "failed" in holes[0].detail + assert holes[1].status == "geometric" + + def test_sub_op_failure_cannot_mask_parent_deferral(self, cb_plan): + """Review finding 1: a countersink skip must NOT overwrite the + hole's deferred status -- the bore may be fully recovered while the + cone is gone; the loss belongs in the detail, loud but honest.""" + led = ExecutionLedger() + led.record("hole", 0, "deferred", "rebuilt at the end of the chain") + led.record("countersink", 0, "skipped", "failed to compute") + led.record("counterbore", 0, "skipped", "failed to compute") + rows, _ = feature_report(cb_plan, led) + hole0 = [r for r in rows if r.kind == "hole"][0] + assert hole0.status == "deferred" + assert "SKIPPED" in hole0.detail and "[countersink]" in hole0.detail + assert "[counterbore]" in hole0.detail + # the other hole is untouched + other = [r for r in rows if r.kind == "hole"][1] + assert other.status == "rebuilt" and other.detail == "" + + def test_parent_status_unchanged_by_sub_rollup(self, cb_plan): + led = ExecutionLedger() + led.record("countersink", 1, "skipped", "degenerate cone") + rows, _ = feature_report(cb_plan, led) + hole1 = [r for r in rows if r.kind == "hole"][1] + assert hole1.status == "rebuilt" + assert "degenerate cone" in hole1.detail + + def test_unplanned_rows_render(self, cb_plan): + cb_plan.unplanned.append("test slot") + try: + rows, _ = feature_report(cb_plan) + unpl = [r for r in rows if r.status == "unplanned"] + assert any("test slot" == r.label for r in unpl) + finally: + cb_plan.unplanned.remove("test slot") + + +class TestAttribution: + def test_component_lands_on_nearest_feature(self, cb_plan): + h = cb_plan.holes[0] + z = h.surface_z if h.surface_z is not None else cb_plan.base.length + c = _world(cb_plan, h.positions[0][0], h.positions[0][1], + float(z) - 0.5) + comp = trimesh.creation.box(extents=[0.9] * 3) + comp.apply_translation(c) + cb_plan.corrections = [CorrectionOp(kind="add", mesh=comp, + volume=1.234)] + try: + dev, (un_u, un_o) = attribute_corrections(cb_plan) + ops = list(plan_ops(cb_plan)) + hole_idx = [i for i, (k, _, _) in enumerate(ops) + if k == "hole"][0] + assert dev[hole_idx] == pytest.approx(1.234) + assert sum(abs(d) for i, d in enumerate(dev) if i != hole_idx) \ + == pytest.approx(0.0) + assert un_u == 0.0 and un_o == 0.0 + finally: + cb_plan.corrections = [] + + def test_far_component_is_freeform(self, cb_plan): + c = _world(cb_plan, 0.0, 0.0, cb_plan.base.length + 5000.0) + comp = trimesh.creation.box(extents=[0.1] * 3) + comp.apply_translation(c) + cb_plan.corrections = [CorrectionOp(kind="cut", mesh=comp, + volume=5.5)] + try: + dev, (un_u, un_o) = attribute_corrections(cb_plan) + assert sum(abs(d) for d in dev) == pytest.approx(0.0) + assert un_o == pytest.approx(5.5) and un_u == 0.0 + finally: + cb_plan.corrections = [] + + def test_sign_convention(self, cb_plan): + h = cb_plan.holes[0] + z = h.surface_z if h.surface_z is not None else cb_plan.base.length + c = _world(cb_plan, h.positions[0][0], h.positions[0][1], + float(z) - 0.5) + over = trimesh.creation.box(extents=[0.9] * 3) + over.apply_translation(c) + cb_plan.corrections = [CorrectionOp(kind="cut", mesh=over, + volume=2.0)] + try: + dev, _ = attribute_corrections(cb_plan) + ops = list(plan_ops(cb_plan)) + hole_idx = [i for i, (k, _, _) in enumerate(ops) + if k == "hole"][0] + assert dev[hole_idx] == pytest.approx(-2.0) + finally: + cb_plan.corrections = [] + + +class TestFormat: + def test_table_lines(self, bracket_plan): + led = ExecutionLedger() + led.record("pocket", 0, "skipped", "failed to compute") + rows, (un_u, un_o) = feature_report(bracket_plan, led) + lines = format_feature_report(rows, src_volume=20000.0, + body_volume=19800.0, + corrected_volume=20010.0, + unattributed=(1.5, 0.7), + name="Rebuilt_bracket") + text = "\n".join(lines) + assert "FEATURE REPORT" in text and "body 99.00%" in text + assert "corrected 100.05%" in text + assert "SKIPPED" in text + assert "freeform deviation" in text + assert len(lines) >= len(rows) + 1 + # every executed (planned) feature prints exactly one line: no + # silent drops -- that was the whole point of phase 3 + for r in rows: + if r.kind in ("hole", "pocket", "pad", "fillet", "chamfer"): + assert r.label in text or r.label == "" diff --git a/freecad/meshtofeatures_wb/ui.py b/freecad/meshtofeatures_wb/ui.py index 712774f..bca0480 100644 --- a/freecad/meshtofeatures_wb/ui.py +++ b/freecad/meshtofeatures_wb/ui.py @@ -57,6 +57,7 @@ def sub(lo, hi): except Exception as exc: # noqa: BLE001 - reported, not fatal plan_error = str(exc) if plan is not None: + plan.src_volume = float(tm.volume) # feature-report ratio denominator try: from .core.solidify import add_corrections add_corrections(plan, tm)