diff --git a/docs/architecture.md b/docs/architecture.md index 6bee1e4f..b84a7097 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -708,11 +708,12 @@ and re-exports the existing private helper names. - **`_pmi_datum_geometry.py`** — exact imported datum face attachment sites and oriented normals in the source or recognition frame. - **`_pmi_linear_geometry.py`** — proves authored linear reference stations and their - principal projection before the PMI extractor lowers dimensions. + principal projection before the PMI extractor lowers dimensions, including thickness wording. - **`_pmi_support_blockers.py`** — pure XCAF source-support and geometric-tolerance - blocker policy, with exact Part21-overlay filters used by the PMI extractor. + blocker policy, with direct-support completeness and exact Part21-overlay filters. - **`_pmi_topology.py`** — exact Part21 support resolvers that verify transferred - faces and edges belong to the imported topology before PMI correlation. + faces and edges belong to the imported topology before PMI correlation, and + planar-face normal and projected-witness evidence for linear PMI. - **`pmi.py`** — PMI (product manufacturing information) extraction from STEP AP242. Defines the public record and source-census types at their established import path, owns the XCAF source census, and overlays `_pmi_part21` facts only after exact diff --git a/src/draftwright/_pmi_linear_geometry.py b/src/draftwright/_pmi_linear_geometry.py index feaab3da..1f5ef826 100644 --- a/src/draftwright/_pmi_linear_geometry.py +++ b/src/draftwright/_pmi_linear_geometry.py @@ -14,7 +14,10 @@ def _linear_reference_stations( - stations: tuple[tuple[float, float, float] | None, ...], nominal: float + stations: tuple[tuple[float, float, float] | None, ...], + nominal: float, + *, + plane_axis: str | None = None, ) -> tuple[tuple[tuple[float, float, float], ...], str, tuple[str, ...]]: """Prove a truthful principal-axis span from the two authored reference groups. @@ -35,14 +38,20 @@ def _linear_reference_stations( first, second = measurable delta = tuple(second[index] - first[index] for index in range(3)) magnitudes = tuple(abs(value) for value in delta) - axis_index = max(range(3), key=magnitudes.__getitem__) + axis_index = ( + "XYZ".index(plane_axis) + if plane_axis is not None + else max(range(3), key=magnitudes.__getitem__) + ) primary = magnitudes[axis_index] if primary <= 1e-9: return measurable, "?", ("linear reference groups occupy the same station",) transverse = max(value for index, value in enumerate(magnitudes) if index != axis_index) direction_tol = max(_LINEAR_AXIS_ABS_TOL, primary * _LINEAR_AXIS_REL_TOL) - oblique = transverse > direction_tol + # Parallel planar supports establish their distance along the plane normal. + # Their finite face centres can be offset arbitrarily within either plane. + oblique = plane_axis is None and transverse > direction_tol if oblique and _linear_projection_view(measurable) is None: return ( measurable, @@ -69,3 +78,22 @@ def _linear_reference_stations( ), ) return measurable, axis, () + + +def _dimension_reference_stations( + stations: tuple[tuple[float, float, float] | None, ...], + nominal: float, + kind: str, + *, + plane_axis: str | None = None, +) -> tuple[tuple[tuple[float, float, float], ...], str, tuple[str, ...]]: + """Apply the dimension kind's wording to the shared station proof.""" + points, axis, reasons = _linear_reference_stations(stations, nominal, plane_axis=plane_axis) + if kind == "thickness": + reasons = tuple( + reason.replace("linear dimension", "thickness dimension").replace( + "linear reference", "thickness reference" + ) + for reason in reasons + ) + return points, axis, reasons diff --git a/src/draftwright/_pmi_support_blockers.py b/src/draftwright/_pmi_support_blockers.py index 4c4782d5..42fe42bc 100644 --- a/src/draftwright/_pmi_support_blockers.py +++ b/src/draftwright/_pmi_support_blockers.py @@ -141,6 +141,23 @@ def _is_direct_xcaf_angular_failure(reason: str) -> bool: return reason.startswith(prefixes) +def _direct_xcaf_support_is_incomplete(record) -> bool: + """Whether direct XCAF failed to supply all support geometry, independent of rendering.""" + reasons = (*record.lowering_blockers, *record.rendering_blockers) + missing_groups = ( + "linear dimension needs two measurable authored reference groups", + "thickness dimension needs two measurable authored reference groups", + "diameter dimension needs a measurable", + ) + return any( + _is_direct_xcaf_reference_failure(reason) + or _is_direct_xcaf_diameter_failure(reason) + or _is_direct_xcaf_angular_failure(reason) + or reason.startswith(missing_groups) + for reason in reasons + ) + + def _without_direct_xcaf_angular_failures(reasons: tuple[str, ...]) -> tuple[str, ...]: """Drop angular XCAF failures superseded by exact Part21 member supports.""" return tuple(reason for reason in reasons if not _is_direct_xcaf_angular_failure(reason)) diff --git a/src/draftwright/_pmi_topology.py b/src/draftwright/_pmi_topology.py index fc5514a3..d71127eb 100644 --- a/src/draftwright/_pmi_topology.py +++ b/src/draftwright/_pmi_topology.py @@ -6,6 +6,7 @@ from __future__ import annotations +from draftwright._pmi_datum_geometry import _frame_vector from draftwright._pmi_support_blockers import _failure_reason try: @@ -17,6 +18,83 @@ pass +def _parallel_planar_reference_support(groups, frame, shape_bbox) -> tuple[str | None, str | None]: + """Find the common principal normal and any required witness view.""" + from OCP.BRepAdaptor import BRepAdaptor_Surface + from OCP.GeomAbs import GeomAbs_Plane + from OCP.TopoDS import TopoDS + + if len(groups) != 2 or not all(groups): + return None, None + axes: list[int] = [] + group_boxes = [] + for shapes in groups: + group_axis = None + group_station = None + boxes = [] + for shape in shapes: + try: + if shape.ShapeType() != TopAbs_FACE: + return None, None + surface = BRepAdaptor_Surface(TopoDS.Face_s(shape)) + if surface.GetType() != GeomAbs_Plane: + return None, None + direction = surface.Plane().Axis().Direction() + local = _frame_vector((direction.X(), direction.Y(), direction.Z()), frame) + axis_index = max(range(3), key=lambda index: abs(local[index])) + if abs(abs(local[axis_index]) - 1.0) > 1e-6: + return None, None + if any(abs(local[index]) > 1e-6 for index in range(3) if index != axis_index): + return None, None + box = shape_bbox(shape) if frame is None else shape_bbox(shape, frame) + boxes.append(box) + station = (box[axis_index] + box[axis_index + 3]) / 2 + if box[axis_index + 3] - box[axis_index] > 1e-5: + return None, None + except Exception: + return None, None + if group_axis is not None and group_axis != axis_index: + return None, None + if group_station is not None and abs(group_station - station) > 1e-5: + return None, None + group_axis, group_station = axis_index, station + assert group_axis is not None # Each validated source group contains a face. + axes.append(group_axis) + group_boxes.append(boxes) + if axes[0] != axes[1]: + return None, None + return _supported_planar_view("XYZ"[axes[0]], group_boxes) + + +def _supported_planar_view(axis: str, group_boxes) -> tuple[str | None, str | None]: + """Select only projection views whose shared witness touches both groups.""" + if axis in {"X", "Z"}: + return ( + (axis, None) + if _midpoint_witness_supported(group_boxes, 2 if axis == "X" else 0) + else (None, None) + ) + side = _midpoint_witness_supported(group_boxes, 2) + plan = _midpoint_witness_supported(group_boxes, 0) + if side and plan: + return axis, None + if side or plan: + return axis, "side" if side else "plan" + return None, None + + +def _midpoint_witness_supported(group_boxes, index: int) -> bool: + """Require a projected face in each group at the renderer's bbox midpoint.""" + all_boxes = [box for boxes in group_boxes for box in boxes] + midpoint = ( + min(box[index] for box in all_boxes) + max(box[index + 3] for box in all_boxes) + ) / 2 + return all( + any(box[index] - 1e-6 <= midpoint <= box[index + 3] + 1e-6 for box in boxes) + for boxes in group_boxes + ) + + class _DatumTopologyResolver: """Resolve Part21 face labels through OCCT's native transfer binders. diff --git a/src/draftwright/model/detect.py b/src/draftwright/model/detect.py index 9484050f..a2cc5967 100644 --- a/src/draftwright/model/detect.py +++ b/src/draftwright/model/detect.py @@ -404,6 +404,7 @@ def build_pmi_features( upper_bound=r.upper_bound, ref_bbox=r.ref_bbox, ref_pts=tuple(r.ref_pts), + view=r.view, source_kind=r.kind, source_id=r.source_id, lowering_blockers=r.lowering_blockers, diff --git a/src/draftwright/pmi.py b/src/draftwright/pmi.py index f38e9244..8c5cc9d3 100644 --- a/src/draftwright/pmi.py +++ b/src/draftwright/pmi.py @@ -52,7 +52,10 @@ _LINEAR_VALUE_REL_TOL as _LINEAR_VALUE_REL_TOL, ) from draftwright._pmi_linear_geometry import ( - _linear_reference_stations, + _dimension_reference_stations, +) +from draftwright._pmi_linear_geometry import ( + _linear_reference_stations as _linear_reference_stations, ) from draftwright._pmi_part21 import ( CommonLabelFact, @@ -103,12 +106,10 @@ _circular_diameter_blockers, _diameter_reference_blockers, _dimension_geometry_blockers, + _direct_xcaf_support_is_incomplete, _failure_reason, _geometric_tolerance_modifiers, _geometric_tolerance_qualifiers, - _is_direct_xcaf_angular_failure, - _is_direct_xcaf_diameter_failure, - _is_direct_xcaf_reference_failure, _unpreserved_geometric_tolerance_fields, _without_direct_xcaf_angular_failures, _without_direct_xcaf_diameter_failures, @@ -120,6 +121,9 @@ _DimensionSupportResolver, _SurfaceLabelTopologyResolver, ) +from draftwright._pmi_topology import ( + _parallel_planar_reference_support as _topology_parallel_planar_reference_support, +) from draftwright.model.ir import ( AngularReference, CircularReference, @@ -238,6 +242,7 @@ class PmiRecord: structured_fields: tuple[tuple[str, str | float], ...] = () reference_surface_kind: str = "" reference_normal: tuple[float, ...] = () + view: str | None = None # Witness view forced only when one Y projection has support. PmiExtractionOutcome = Literal[ @@ -398,23 +403,6 @@ def _dominant_from_bbox(bbox: tuple[float, float, float, float, float, float]) - return dom[0] if dom[1] > 1e-6 else "?" -def _direct_xcaf_support_is_incomplete(record: PmiRecord) -> bool: - """Whether direct XCAF failed to supply all support geometry, independent of rendering.""" - reasons = (*record.lowering_blockers, *record.rendering_blockers) - missing_groups = ( - "linear dimension needs two measurable authored reference groups", - "thickness dimension needs two measurable authored reference groups", - "diameter dimension needs a measurable", - ) - return any( - _is_direct_xcaf_reference_failure(reason) - or _is_direct_xcaf_diameter_failure(reason) - or _is_direct_xcaf_angular_failure(reason) - or reason.startswith(missing_groups) - for reason in reasons - ) - - def _make_label( kind: str, value: float, @@ -490,10 +478,12 @@ def _reference_geometry_with_groups(label, shape_tool, frame: PartFrame | None = points: list[tuple[float, float, float]] = [] boxes: list[tuple[float, float, float, float, float, float]] = [] group_stations: list[tuple[float, float, float] | None] = [] + group_shapes: list[tuple] = [] partial_reasons: list[str] = [] reference_count = first_refs.Length() + second_refs.Length() for refs in (first_refs, second_refs): group_boxes: list[tuple[float, float, float, float, float, float]] = [] + shapes = [] for index in range(1, refs.Length() + 1): shape = shape_tool.GetShape_s(refs.Value(index)) if shape is None or shape.IsNull(): @@ -505,6 +495,7 @@ def _reference_geometry_with_groups(label, shape_tool, frame: PartFrame | None = point = _bbox_centroid(bbox) points.append(point) group_boxes.append(bbox) + shapes.append(shape) except Exception as exc: partial_reasons.append( f"one referenced shape could not be measured ({_failure_reason(exc)})" @@ -513,6 +504,7 @@ def _reference_geometry_with_groups(label, shape_tool, frame: PartFrame | None = # merged-envelope centre is invariant to that segmentation; averaging item centres # would move merely because one face was split into two (#1209). group_stations.append(_bbox_centroid(_merge_bboxes(group_boxes)) if group_boxes else None) + group_shapes.append(tuple(shapes)) if reference_count == 0: partial_reasons.append("referenced geometry is unavailable") @@ -524,16 +516,24 @@ def _reference_geometry_with_groups(label, shape_tool, frame: PartFrame | None = dominant_axis, tuple(dict.fromkeys(partial_reasons)), tuple(group_stations), + tuple(group_shapes), ) def _reference_geometry(label, shape_tool, frame: PartFrame | None = None): """Compatible flattened geometry projection shared by non-dimensional PMI.""" geometry = _reference_geometry_with_groups(label, shape_tool, frame) - points, ref_bbox, dominant_axis, reasons, _groups = geometry + points, ref_bbox, dominant_axis, reasons, _groups, _shapes = geometry return points, ref_bbox, dominant_axis, reasons +def _parallel_planar_reference_support( + groups: tuple[tuple, ...], frame: PartFrame | None = None +) -> tuple[str | None, str | None]: + """Measure a planar support and its drawable view in the extraction frame.""" + return _topology_parallel_planar_reference_support(groups, frame, _shape_bbox) + + def _angular_reference_from_planes( planes: tuple[ tuple[tuple[float, float, float], tuple[float, float, float]], @@ -1294,20 +1294,19 @@ def _dimension_record( reference_geometry = _reference_geometry_with_groups(label, shape_tool) else: reference_geometry = _reference_geometry_with_groups(label, shape_tool, frame) - points, ref_bbox, dominant_axis, reference_reasons, group_stations = reference_geometry + points, ref_bbox, dominant_axis, reference_reasons, group_stations, group_shapes = ( + reference_geometry + ) partial_reasons.extend(reference_reasons) rendering_blockers: tuple[str, ...] = () cylindrical_refs: tuple[CylindricalReference, ...] = () angular_reference: AngularReference | None = None + support_view = None if kind in ("linear", "thickness"): - points, dominant_axis, station_reasons = _linear_reference_stations(group_stations, value) - if kind == "thickness": - station_reasons = tuple( - reason.replace("linear dimension", "thickness dimension").replace( - "linear reference", "thickness reference" - ) - for reason in station_reasons - ) + plane_axis, support_view = _parallel_planar_reference_support(group_shapes, frame) + points, dominant_axis, station_reasons = _dimension_reference_stations( + group_stations, value, kind, plane_axis=plane_axis + ) rendering_blockers = _dimension_geometry_blockers(kind, reference_reasons, station_reasons) elif type_code == 15: # XCAFDimTolObjects_DimensionType_Size_Diameter if frame is None: @@ -1411,6 +1410,7 @@ def _dimension_record( source_value_blockers=tuple(dict.fromkeys(tolerance_read_reasons)), cylindrical_refs=cylindrical_refs, angular_reference=angular_reference, + view=support_view, ), blockers, ) @@ -2062,22 +2062,20 @@ def _dimension_support_topology( ) continue - points, dominant_axis, station_reasons = _linear_reference_stations( - tuple(stations), record.value + plane_axis, support_view = _parallel_planar_reference_support(tuple(group_shapes), frame) + points, dominant_axis, station_reasons = _dimension_reference_stations( + tuple(stations), + record.value, + record.kind, + plane_axis=plane_axis, ) - if record.kind == "thickness": - station_reasons = tuple( - reason.replace("linear dimension", "thickness dimension").replace( - "linear reference", "thickness reference" - ) - for reason in station_reasons - ) projected.append( replace( record, ref_pts=points, ref_bbox=ref_bbox, dominant_axis=dominant_axis, + view=support_view, lowering_blockers=tuple( dict.fromkeys( ( diff --git a/tests/_complexity_baseline.json b/tests/_complexity_baseline.json index d4faead2..f72dd96b 100644 --- a/tests/_complexity_baseline.json +++ b/tests/_complexity_baseline.json @@ -111,8 +111,8 @@ "oriented_slot_contract.py:oriented_slot_provider_key": 19, "pdf_text.py:pdf_text_runs": 27, "pmi.py:_angular_reference_from_shapes": 18, - "pmi.py:_dimension_record": 29, - "pmi.py:_dimension_support_topology": 19, + "pmi.py:_dimension_record": 28, + "pmi.py:_dimension_support_topology": 18, "pmi.py:_extract_xcaf_dimensions": 23, "profile_angles.py:profile_angle_repetitions": 19, "projection.py:_exactify_silhouettes": 21, diff --git a/tests/test_issue_1209_linear_pmi_witnesses.py b/tests/test_issue_1209_linear_pmi_witnesses.py index 908daefb..0e2a1817 100644 --- a/tests/test_issue_1209_linear_pmi_witnesses.py +++ b/tests/test_issue_1209_linear_pmi_witnesses.py @@ -68,6 +68,145 @@ def test_an_incomplete_or_wrong_length_relationship_fails_without_nominal_guessi assert blockers == ("linear reference-station span 10 mm differs from nominal 20 mm",) +def test_offset_parallel_faces_use_their_proven_normal_issue_2184(monkeypatch): + from build123d import Axis, Box, Pos + from quiddity import FrameGauge, PartFrame + + import draftwright.pmi as pmi_module + + first = Box(2, 10, 10).faces().sort_by(Axis.X)[0].wrapped + second = (Pos(10, 20, 0) * Box(2, 10, 10)).faces().sort_by(Axis.X)[0].wrapped + groups = ((first,), (second,)) + stations = tuple( + pmi_module._bbox_centroid(pmi_module._shape_bbox(shape)) for shape in (first, second) + ) + + assert stations == ((-1.0, 0.0, 0.0), (9.0, 20.0, 0.0)) + assert _linear_reference_stations(stations, 10)[2] + axis, view = pmi_module._parallel_planar_reference_support(groups) + assert (axis, view) == ("X", None) + frame = PartFrame( + origin=(0.0, 0.0, 0.0), + x=(0.0, 0.0, -1.0), + y=(0.0, 1.0, 0.0), + z=(1.0, 0.0, 0.0), + gauge=FrameGauge.FULL, + ) + assert pmi_module._parallel_planar_reference_support(groups, frame) == ("Z", None) + perpendicular = (Pos(10, 20, 0) * Box(2, 10, 10)).faces().sort_by(Axis.Y)[0].wrapped + assert pmi_module._parallel_planar_reference_support(((first,), (perpendicular,))) == ( + None, + None, + ) + assert pmi_module._parallel_planar_reference_support(((first, second), (second,))) == ( + None, + None, + ) + detached = (Pos(10, 0, 20) * Box(2, 10, 2)).faces().sort_by(Axis.X)[0].wrapped + assert pmi_module._parallel_planar_reference_support(((first,), (detached,))) == (None, None) + shifted_midpoint = (Pos(10, 0, 17) * Box(2, 10, 26)).faces().sort_by(Axis.X)[0].wrapped + assert pmi_module._parallel_planar_reference_support(((first,), (shifted_midpoint,))) == ( + None, + None, + ) + assert _linear_reference_stations(stations, 10, plane_axis=axis) == (stations, "X", ()) + assert _linear_reference_stations(stations, 11, plane_axis=axis)[2] == ( + "linear reference-station span 10 mm differs from nominal 11 mm", + ) + + class Sequence: + def __init__(self): + self.items = [] + + def Append(self, item): + self.items.append(item) + + def Length(self): + return len(self.items) + + def Value(self, index): + return self.items[index - 1] + + def get_refs(_label, first_refs, second_refs): + first_refs.Append(first) + second_refs.Append(second) + + monkeypatch.setattr(pmi_module, "TDF_LabelSequence", Sequence) + monkeypatch.setattr( + pmi_module, + "XCAFDoc_DimTolTool", + SimpleNamespace(GetRefShapeLabel_s=get_refs), + ) + source = SimpleNamespace( + GetValue=lambda: 10.0, + IsDimWithPlusMinusTolerance=lambda: False, + IsDimWithRange=lambda: False, + GetSemanticName=lambda: None, + ) + direct, blockers = pmi_module._dimension_record( + object(), source, 2, SimpleNamespace(GetShape_s=lambda shape: shape), "dimension:planes" + ) + assert direct.ref_pts == stations + assert direct.dominant_axis == "X" + assert blockers == () + + class Resolver: + def __init__(self, _reader): + pass + + def resolve_group(self, aspect_id, _item_ids): + return groups[0 if aspect_id == "#10" else 1], () + + monkeypatch.setattr(pmi_module, "_DimensionSupportResolver", Resolver) + record = PmiRecord( + kind="linear", + type_code=2, + value=10, + shape_aspect_ids=("#10", "#20"), + reference_item_groups=(("#100",), ("#200",)), + ) + projected = _dimension_support_topology((record,), object())[0] + assert projected.ref_pts == stations + assert projected.dominant_axis == "X" + assert projected.lowering_blockers == projected.rendering_blockers == () + + first = Box(10, 2, 10).faces().sort_by(Axis.Y)[0].wrapped + second = (Pos(20, 10, 0) * Box(10, 2, 10)).faces().sort_by(Axis.Y)[0].wrapped + groups = ((first,), (second,)) + assert pmi_module._parallel_planar_reference_support(groups) == ("Y", "side") + both_views = (Pos(0, 10, 0) * Box(10, 2, 10)).faces().sort_by(Axis.Y)[0].wrapped + assert pmi_module._parallel_planar_reference_support(((first,), (both_views,))) == ( + "Y", + None, + ) + plan_only = (Pos(0, 10, 20) * Box(10, 2, 10)).faces().sort_by(Axis.Y)[0].wrapped + assert pmi_module._parallel_planar_reference_support(((first,), (plan_only,))) == ("Y", "plan") + neither_view = (Pos(20, 10, 20) * Box(10, 2, 10)).faces().sort_by(Axis.Y)[0].wrapped + assert pmi_module._parallel_planar_reference_support(((first,), (neither_view,))) == ( + None, + None, + ) + side_record, blockers = pmi_module._dimension_record( + object(), source, 2, SimpleNamespace(GetShape_s=lambda shape: shape), "dimension:side" + ) + assert blockers == () + assert side_record.dominant_axis == "Y" and side_record.view == "side" + side_projected = _dimension_support_topology((record,), object())[0] + assert side_projected.dominant_axis == "Y" and side_projected.view == "side" + from draftwright.model.detect import build_pmi_features + + part_bbox = Box(60, 60, 60).bounding_box() + assert build_pmi_features((side_projected,), part_bbox)[0].view == "side" + second = plan_only + plan_record, blockers = pmi_module._dimension_record( + object(), source, 2, SimpleNamespace(GetShape_s=lambda shape: shape), "dimension:plan" + ) + assert blockers == () and plan_record.view == "plan" + assert build_pmi_features((plan_record,), part_bbox)[0].view == "plan" + groups = ((first,), (second,)) + assert _dimension_support_topology((record,), object())[0].view == "plan" + + def test_a_partially_measured_group_cannot_render_from_its_incomplete_subset(): missing = "one referenced shape is unavailable" assert _dimension_geometry_blockers("linear", (missing,), ()) == (missing,) @@ -147,13 +286,14 @@ def test_exact_part21_groups_supersede_direct_xcaf_reference_failures(monkeypatc original = pmi_module._reference_geometry_with_groups def incomplete_xcaf_geometry(*args, **kwargs): - points, bbox, axis, reasons, stations = original(*args, **kwargs) + points, bbox, axis, reasons, stations, shapes = original(*args, **kwargs) return ( points, bbox, axis, (*reasons, "one referenced shape is unavailable"), stations, + shapes, ) monkeypatch.setattr(pmi_module, "_reference_geometry_with_groups", incomplete_xcaf_geometry)