From 46616ad77b4c0f41fd0a8033513e3008b5f0a03e Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 15:11:08 +0000 Subject: [PATCH 1/2] Preserve AP242 theoretical dimensions as boxed basic ink --- src/draftwright/_pmi_part21.py | 41 +++++++- .../annotations/_pmi_dimensions.py | 95 ++++++++++++------- src/draftwright/model/detect.py | 1 + src/draftwright/model/ir.py | 1 + src/draftwright/model/pmi_lowering.py | 4 + src/draftwright/pmi.py | 18 ++++ tests/test_authored_pmi_precedence.py | 6 ++ tests/test_pmi.py | 83 ++++++++++++++++ tests/test_pmi_part21.py | 38 ++++++++ 9 files changed, 251 insertions(+), 36 deletions(-) diff --git a/src/draftwright/_pmi_part21.py b/src/draftwright/_pmi_part21.py index 0e3dad8a..f17919e6 100644 --- a/src/draftwright/_pmi_part21.py +++ b/src/draftwright/_pmi_part21.py @@ -126,6 +126,7 @@ class DimensionDisplayFact: value_decimals: int | None tolerance_decimals: int | None unit_name: str + basic: bool = False @dataclass(frozen=True) @@ -140,6 +141,7 @@ class DimensionAssociationFact: reference_item_groups: tuple[tuple[str, ...], ...] callout_id: str = "" reason: str = "" + basic: bool = False @dataclass(frozen=True) @@ -1365,6 +1367,14 @@ def read_dimension_display_facts(step_file: str | Path) -> tuple[DimensionDispla if not kind: continue nominal_refs = representations.get(representation_ref, ()) + basic = any( + _text(item.params[0]).casefold() == "dimensional note" + and _text(item.params[1]).casefold() == "theoretical" + for ref in nominal_refs + if (item := _entity_named(step.get(ref), "DESCRIPTIVE_REPRESENTATION_ITEM")) + is not None + and len(item.params) >= 2 + ) nominal_ref = "" for ref in nominal_refs: representation_item = _entity_named(step.get(ref), "REPRESENTATION_ITEM") @@ -1414,6 +1424,7 @@ def read_dimension_display_facts(step_file: str | Path) -> tuple[DimensionDispla _value_format_decimals(step, nominal_ref, qualifications), next(iter(tolerance_decimals)) if len(tolerance_decimals) == 1 else None, unit_name, + basic, ) ) return tuple(facts) @@ -1432,6 +1443,8 @@ def read_dimension_associations(step_file: str | Path) -> tuple[DimensionAssocia aspect_items: dict[str, list[str]] = {} association_callouts: dict[str, list[str]] = {} callout_names: dict[str, str] = {} + dimension_representations: dict[str, list[str]] = {} + representation_items: dict[str, tuple[str, ...]] = {} for section in step.data: for entity_id, instance in section.instances.items(): @@ -1504,6 +1517,18 @@ def read_dimension_associations(step_file: str | Path) -> tuple[DimensionAssocia for ref in _references(association.params[4]) if _instance_is(step, ref, "DRAUGHTING_CALLOUT") ) + representation = _entity_named(instance, "SHAPE_DIMENSION_REPRESENTATION") + if representation is not None and len(representation.params) >= 2: + representation_items[entity_id] = _references(representation.params[1]) + dimension_link = _entity_named(instance, "DIMENSIONAL_CHARACTERISTIC_REPRESENTATION") + if dimension_link is not None and len(dimension_link.params) >= 2: + characteristic_ref, representation_ref = dimension_link.params[:2] + if isinstance(characteristic_ref, p21.Reference) and isinstance( + representation_ref, p21.Reference + ): + dimension_representations.setdefault(str(characteristic_ref), []).append( + str(representation_ref) + ) def related_items(root: str) -> tuple[str, ...]: pending = [root] @@ -1521,6 +1546,16 @@ def related_items(root: str) -> tuple[str, ...]: facts: list[DimensionAssociationFact] = [] for entity_id, kind, semantic_name, shape_aspect_ids, expand_direct_members in characteristics: reasons: list[str] = [] + dimensional_notes = [ + _text(item.params[1]).casefold() + for representation_ref in dimension_representations.get(entity_id, ()) + for item_ref in representation_items.get(representation_ref, ()) + if (item := _entity_named(step.get(item_ref), "DESCRIPTIVE_REPRESENTATION_ITEM")) + is not None + and len(item.params) >= 2 + and _text(item.params[0]).casefold() == "dimensional note" + ] + basic = "theoretical" in dimensional_notes callout_ids = tuple(dict.fromkeys(association_callouts.get(entity_id, ()))) callout_id = callout_ids[0] if len(callout_ids) == 1 else "" if len(callout_ids) != 1: @@ -1549,6 +1584,7 @@ def related_items(root: str) -> tuple[str, ...]: reference_item_groups=item_groups, callout_id=callout_id, reason="; ".join(dict.fromkeys(reasons)), + basic=basic, ) ) return tuple(facts) @@ -1583,7 +1619,10 @@ def match_dimension_display( and fact.kind == kind and math.isclose(fact.authored_value, authored_value, rel_tol=1e-9, abs_tol=1e-12) ] - policies = {(fact.value_decimals, fact.tolerance_decimals, fact.unit_name) for fact in matches} + policies = { + (fact.value_decimals, fact.tolerance_decimals, fact.unit_name, fact.basic) + for fact in matches + } return matches[0] if matches and len(policies) == 1 else None diff --git a/src/draftwright/annotations/_pmi_dimensions.py b/src/draftwright/annotations/_pmi_dimensions.py index 0024a533..c50e21eb 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -466,6 +466,7 @@ class _PmiDimensionBuild: witness: float label: str draft: Any + basic: bool = False def __call__(self, pos: float): # The helper draws one extension gap back toward the witnesses; the strip @@ -475,10 +476,14 @@ def __call__(self, pos: float): if self.side in ("above", "right") else self.witness - pos + self.draft.extension_gap ) - return _dim(self.q1, self.q2, self.side, dist, self.draft, label=self.label) + return _dim( + self.q1, self.q2, self.side, dist, self.draft, label=self.label, basic=self.basic + ) -def _pmi_dim_spec(p1, p2, strip, label, name, view, side, draft, *, leader_fallback=False): +def _pmi_dim_spec( + p1, p2, strip, label, name, view, side, draft, *, leader_fallback=False, basic=False +): if strip is None: return None if side in ("above", "below"): @@ -500,7 +505,7 @@ def _pmi_dim_spec(p1, p2, strip, label, name, view, side, draft, *, leader_fallb order_coord = min(perp) spec = { "name": name, - "build": _PmiDimensionBuild(q1, q2, side, witness, label, draft), + "build": _PmiDimensionBuild(q1, q2, side, witness, label, draft, basic), "strip": strip, "view": view, "side": side, @@ -532,7 +537,7 @@ def _build_routed(bends, elbow, _tip=p2, _label=label): return spec -def _oblique_pmi_dim_spec(p1, p2, strip, label, name, view, side, draft): +def _oblique_pmi_dim_spec(p1, p2, strip, label, name, view, side, draft, *, basic=False): """Place an exact projected span parallel to its two authored witness stations.""" if strip is None: return None @@ -566,7 +571,7 @@ def _oblique_pmi_dim_spec(p1, p2, strip, label, name, view, side, draft): def _build(pos, _component=component, _coordinate=coordinate): distance = abs((pos - _coordinate) / _component) - return _dim(p1, p2, side, max(distance, 1e-6), draft, label=label) + return _dim(p1, p2, side, max(distance, 1e-6), draft, label=label, basic=basic) perp = tuple(sorted((p1[0], p2[0]))) if axis == "y" else tuple(sorted((p1[1], p2[1]))) return { @@ -613,7 +618,17 @@ def _oblique_linear_specs(a: Analysis, rec, label, name, draft): else ("above", "below", "right", "left") ) return [ - _oblique_pmi_dim_spec(p1, p2, getattr(zones, side), label, name, view, side, draft) + _oblique_pmi_dim_spec( + p1, + p2, + getattr(zones, side), + label, + name, + view, + side, + draft, + basic=getattr(rec, "basic", False), + ) for side in sides ] @@ -1120,12 +1135,26 @@ def _pmi_front_linear( return None p1, p2, avg = wp zones = a.pv_zones if view == "plan" else a.fv_zones + + def spec(side): + return _pmi_dim_spec( + p1, + p2, + getattr(zones, side), + label, + name, + view, + side, + draft, + basic=getattr(rec, "basic", False), + ) + if rec.side is not None: sides = [s for s in (primary, secondary) if rec.side == s] return _pmi_queue_options( dwg, ctx, - [_pmi_dim_spec(p1, p2, getattr(zones, s), label, name, view, s, draft) for s in sides], + [spec(side) for side in sides], ax, label, rec, @@ -1136,10 +1165,8 @@ def _pmi_front_linear( dwg, ctx, [ - _pmi_dim_spec(p1, p2, getattr(zones, primary), label, name, view, primary, draft), - _pmi_dim_spec( - p1, p2, getattr(zones, secondary), label, name, view, secondary, draft - ), + spec(primary), + spec(secondary), ], ax, label, @@ -1149,11 +1176,7 @@ def _pmi_front_linear( placed = _pmi_queue_options( dwg, ctx, - [ - _pmi_dim_spec( - p1, p2, getattr(zones, secondary), label, name, view, secondary, draft - ) - ], + [spec(secondary)], ax, label, rec, @@ -1353,7 +1376,7 @@ def _bore_render_options( surface_pg, ): """Choose in-place witnesses or a surface leader for one projected bore.""" - if half_span_pg >= _MIN_INPLACE_BORE_HALF_MM: + if half_span_pg >= _MIN_INPLACE_BORE_HALF_MM or getattr(rec, "basic", False): p1, p2 = cfg["span"](cx, cy, cz, lo, hi) order = tuple( side @@ -1371,7 +1394,8 @@ def _bore_render_options( cfg["view"], side, draft, - leader_fallback=True, + leader_fallback=not getattr(rec, "basic", False), + basic=getattr(rec, "basic", False), ) for side in order ] @@ -1407,6 +1431,10 @@ def _place_pmi_record( _pmi_queue_options = queue_options ax = rec.dominant_axis label = rec.label + + def pmi_spec(*args): + return _pmi_dim_spec(*args, basic=getattr(rec, "basic", False)) + circular_refs = tuple(getattr(rec, "circular_refs", ())) cylindrical_refs = tuple(getattr(rec, "cylindrical_refs", ())) pattern_count = len(circular_refs) or ( @@ -1426,6 +1454,15 @@ def _place_pmi_record( name_y = f"pmi_y_{idx}" name_d = f"pmi_d_{idx}" + # These producers draw unboxed text. Keep source semantics honest until they + # have a basic-frame candidate of their own, rather than emitting plain ink. + if getattr(rec, "basic", False) and ( + rec.pmi_kind == "angular" + or (rec.pmi_kind == "diameter" and cylindrical_refs and ax == "?") + ): + _record_pmi_no_candidate(ctx, label, rec) + return False + if rec.pmi_kind == "angular": references = tuple(getattr(rec, "angular_references", ())) or (rec.angular_reference,) options = [ @@ -1588,7 +1625,7 @@ def _place_pmi_record( else: target_sides = ("right", "left") if avg >= a.PV_X else ("left", "right") options = [ - _pmi_dim_spec( + pmi_spec( p1, p2, getattr(zones, target_side), @@ -1621,12 +1658,8 @@ def _place_pmi_record( dwg, ctx, [ - _pmi_dim_spec( - p1, p2, a.sv_zones.above, label, name_y, "side", "above", draft - ), - _pmi_dim_spec( - p1, p2, a.sv_zones.below, label, name_y, "side", "below", draft - ), + pmi_spec(p1, p2, a.sv_zones.above, label, name_y, "side", "above", draft), + pmi_spec(p1, p2, a.sv_zones.below, label, name_y, "side", "below", draft), ], ax, label, @@ -1636,11 +1669,7 @@ def _place_pmi_record( placed = _pmi_queue_options( dwg, ctx, - [ - _pmi_dim_spec( - p1, p2, a.sv_zones.below, label, name_y, "side", "below", draft - ) - ], + [pmi_spec(p1, p2, a.sv_zones.below, label, name_y, "side", "below", draft)], ax, label, rec, @@ -1653,11 +1682,7 @@ def _place_pmi_record( placed = _pmi_queue_options( dwg, ctx, - [ - _pmi_dim_spec( - p1, p2, a.pv_zones.below, label, name_y, "plan", "below", draft - ) - ], + [pmi_spec(p1, p2, a.pv_zones.below, label, name_y, "plan", "below", draft)], ax, label, rec, diff --git a/src/draftwright/model/detect.py b/src/draftwright/model/detect.py index 8be58007..9507176d 100644 --- a/src/draftwright/model/detect.py +++ b/src/draftwright/model/detect.py @@ -428,6 +428,7 @@ def build_pmi_features( if getattr(r, "angular_references", ()) else () ), + basic=r.basic, ) ) continue diff --git a/src/draftwright/model/ir.py b/src/draftwright/model/ir.py index de0c9ea7..fd838663 100644 --- a/src/draftwright/model/ir.py +++ b/src/draftwright/model/ir.py @@ -2188,6 +2188,7 @@ class AuthoredDimension: angular_references: tuple[AngularReference, ...] = () angular_member_ids: tuple[str, ...] = () angular_reference_item_groups: tuple[tuple[str, ...], ...] = () + basic: bool = False # Source-declared theoretically exact dimension. kind: ClassVar[str] = "authored_dimension" def __post_init__(self) -> None: diff --git a/src/draftwright/model/pmi_lowering.py b/src/draftwright/model/pmi_lowering.py index 64f58ae5..e67d8ce6 100644 --- a/src/draftwright/model/pmi_lowering.py +++ b/src/draftwright/model/pmi_lowering.py @@ -91,6 +91,7 @@ def _plain_cylinder_source(feature: Feature) -> TypeGuard[AuthoredDimension]: return ( isinstance(feature, AuthoredDimension) and feature.dimension_kind == "diameter" + and not feature.basic and feature.source == "ap242_pmi" and bool(feature.cylindrical_refs) and all( @@ -219,6 +220,7 @@ def _is_internal_toleranced_diameter(feature: AuthoredDimension) -> bool: """Select AP242 bore limits without sending external cylinders to the hole join.""" return ( feature.dimension_kind == "diameter" + and not feature.basic and feature.source == "ap242_pmi" and ( not feature.cylindrical_refs @@ -798,6 +800,7 @@ def lower_ap242_external_diameter_tolerances(model: PartModel) -> PartModel: if isinstance(feature, AuthoredDimension) and feature.source == "ap242_pmi" and feature.dimension_kind == "diameter" + and not feature.basic and feature.cylindrical_refs and all(reference.sense == "external" for reference in feature.cylindrical_refs) and any( @@ -1070,6 +1073,7 @@ def lower_ap242_nominal_step_lengths(model: PartModel) -> PartModel: isinstance(dimension, AuthoredDimension) and dimension.source == "ap242_pmi" and dimension.dimension_kind == "linear" + and not dimension.basic and dimension.source_id and not dimension.lowering_blockers and not dimension.rendering_blockers diff --git a/src/draftwright/pmi.py b/src/draftwright/pmi.py index 31be34e2..60588edb 100644 --- a/src/draftwright/pmi.py +++ b/src/draftwright/pmi.py @@ -243,6 +243,7 @@ class PmiRecord: reference_surface_kind: str = "" reference_normal: tuple[float, ...] = () view: str | None = None # Witness view forced only when one Y projection has support. + basic: bool = False # Exact Part21 'dimensional note' = 'theoretical'. PmiExtractionOutcome = Literal[ @@ -1282,6 +1283,13 @@ def _dimension_record( except Exception: semantic_name = "" display_fact = match_dimension_display(display_facts, semantic_name, kind, authored_value) + basic_policies = { + fact.basic + for fact in display_facts + if fact.semantic_name == semantic_name + and fact.kind == kind + and math.isclose(fact.authored_value, authored_value, rel_tol=1e-9, abs_tol=1e-12) + } if kind in _LENGTH_DIMENSION_KINDS: if length_factor_reason: partial_reasons.append(length_factor_reason) @@ -1344,6 +1352,11 @@ def _dimension_record( angular_reference.second, ) lowering_blockers = tuple(dict.fromkeys(partial_reasons)) + if association_fact is None and len(basic_policies) > 1: + rendering_blockers = ( + *rendering_blockers, + "Part21 basic-dimension status is ambiguous for this value", + ) blockers = tuple(dict.fromkeys((*lowering_blockers, *rendering_blockers))) return ( PmiRecord( @@ -1412,6 +1425,11 @@ def _dimension_record( cylindrical_refs=cylindrical_refs, angular_reference=angular_reference, view=support_view, + basic=( + association_fact.basic + if association_fact is not None + else basic_policies == {True} + ), ), blockers, ) diff --git a/tests/test_authored_pmi_precedence.py b/tests/test_authored_pmi_precedence.py index 774947e8..8ac13cfb 100644 --- a/tests/test_authored_pmi_precedence.py +++ b/tests/test_authored_pmi_precedence.py @@ -178,6 +178,12 @@ def test_source_precision_is_kept_when_plain_label_differs_from_planner(): assert _step_lengths(model)[0][2] +def test_basic_source_is_not_lowered_into_an_unboxed_step_dimension(): + source = replace(_source(0, 15, "dimension:basic-15"), basic=True) + lowered = lower_ap242_nominal_step_lengths(_model(source)) + assert source in lowered.features + + def test_noncanonical_diameter_label_stays_authored_and_covers_step_diameter(): step = _step(0, 15, 30) source = AuthoredDimension( diff --git a/tests/test_pmi.py b/tests/test_pmi.py index 61119334..4bd7c9a1 100644 --- a/tests/test_pmi.py +++ b/tests/test_pmi.py @@ -25,10 +25,93 @@ CTC02 = FIXTURES / "nist_ctc_02_asme1_ap242.stp" CTC03 = FIXTURES / "nist_ctc_03_asme1_ap242.stp" CTC04 = FIXTURES / "nist_ctc_04_asme1_ap242.stp" +CTC05 = FIXTURES / "nist_ctc_05_asme1_ap242.stp" pytestmark = pytest.mark.skipif(not _PMI_AVAILABLE, reason="OCP GDT support not available") +def test_ctc05_extracts_theoretical_locations_as_basic_dimensions(): + report = extract_pmi_report(CTC05) + basic = [record for record in report.records if record.basic] + assert {record.part21_id for record in basic} == {"#942", "#943", "#944", "#945"} + assert all(record.kind == "linear" for record in basic) + + +def test_basic_dimension_survives_missing_presentation_name_match(monkeypatch): + import draftwright.pmi as pmi_module + + monkeypatch.setattr( + pmi_module, + "match_dimension_association", + lambda _facts, _name: (None, "presentation name is unavailable"), + ) + report = extract_pmi_report(CTC05) + assert {record.part21_id for record in report.records if record.basic} == {""} + assert len([record for record in report.records if record.basic]) == 4 + + +def test_ambiguous_basic_status_without_identity_is_not_rendered_plain(monkeypatch): + from dataclasses import replace + + import draftwright.pmi as pmi_module + + read_facts = pmi_module.read_dimension_display_facts + + def conflicting_facts(path): + facts = read_facts(path) + first = next(fact for fact in facts if fact.basic) + return (*facts, replace(first, basic=False)) + + monkeypatch.setattr(pmi_module, "read_dimension_display_facts", conflicting_facts) + monkeypatch.setattr( + pmi_module, + "match_dimension_association", + lambda _facts, _name: (None, "presentation name is unavailable"), + ) + report = extract_pmi_report(CTC05) + conflicting = [ + record + for record in report.records + if "Part21 basic-dimension status is ambiguous for this value" in record.rendering_blockers + ] + assert len(conflicting) == 2 + assert all(not record.basic for record in conflicting) + + +def test_authored_basic_dimension_is_boxed_through_ir_and_finished_drawing(): + from draftwright.model import build_pmi_features + from draftwright.model.ir import PartModel + + part = Box(40, 30, 5) + (source,) = build_pmi_features( + ( + PmiRecord( + kind="linear", + type_code=1, + value=20.0, + label="20", + dominant_axis="X", + ref_pts=((-10, 0, 0), (10, 0, 0)), + source_id="dimension:basic", + basic=True, + ), + ), + part.bounding_box(), + ) + assert source.basic + drawing = build_drawing( + part, + model=PartModel(part.bounding_box(), "z", [source]), + pmi="annotate", + page="A4", + scale=2.0, + ) + dimension = drawing.get_annotation("pmi_x_0") + assert dimension.is_basic + assert dimension.placement_spec.kwargs["basic"] + assert len(dimension.segments) >= 4 + + # --------------------------------------------------------------------------- # extract_pmi unit tests # --------------------------------------------------------------------------- diff --git a/tests/test_pmi_part21.py b/tests/test_pmi_part21.py index 146cd44e..77b3b3a3 100644 --- a/tests/test_pmi_part21.py +++ b/tests/test_pmi_part21.py @@ -68,6 +68,35 @@ def _read_datums(tmp_path, name: str, *instances: str): return read_datum_occurrences(step) +def test_theoretical_dimension_note_is_tied_to_its_exact_characteristic(tmp_path): + source = tmp_path / "basic.step" + source.write_text( + _step( + "#1=DIMENSIONAL_LOCATION('linear distance','',#3,#4);", + "#2=DIMENSIONAL_LOCATION('linear distance','',#3,#5);", + "#3=SHAPE_ASPECT('','',#99,.T.);", + "#4=SHAPE_ASPECT('','',#99,.T.);", + "#5=SHAPE_ASPECT('','',#99,.T.);", + "#6=SHAPE_DIMENSION_REPRESENTATION('',(#8),#99);", + "#7=SHAPE_DIMENSION_REPRESENTATION('',(#8,#9),#99);", + "#8=REPRESENTATION_ITEM('nominal value');", + "#9=DESCRIPTIVE_REPRESENTATION_ITEM('dimensional note','theoretical');", + "#10=DIMENSIONAL_CHARACTERISTIC_REPRESENTATION(#1,#7);", + "#11=DIMENSIONAL_CHARACTERISTIC_REPRESENTATION(#2,#6);", + ), + encoding="utf-8", + ) + facts = {fact.entity_id: fact for fact in read_dimension_associations(source)} + assert facts["#1"].basic + assert not facts["#2"].basic + + +def test_nist_theoretical_dimensions_are_recognised_from_real_ap242(): + basic = [fact for fact in read_dimension_associations(CTC05) if fact.basic] + assert len(basic) == 4 + assert all(fact.kind == "location" for fact in basic) + + def test_grm03_material_name_is_owned_by_its_product(): fixture = Path(__file__).parent / "fixtures" / "grm03_thumbwheel_drive_screw_ap242_pmi.step" (fact,) = read_material_properties(fixture) @@ -1484,6 +1513,15 @@ def test_dimension_display_match_rejects_conflicting_source_policies(): ) is None ) + assert ( + match_dimension_display( + (fact, replace(fact, basic=not fact.basic)), + fact.semantic_name, + fact.kind, + fact.authored_value, + ) + is None + ) def test_dimension_display_rejects_unbounded_source_precision(tmp_path): From 3118717c658c5e231894ba6f4332b9919fb8d097 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 15:23:16 +0000 Subject: [PATCH 2/2] Keep PMI basic handling within source-shape budgets --- src/draftwright/_pmi_part21.py | 59 +++++-- src/draftwright/_pmi_schema.py | 45 ++++++ .../annotations/_pmi_dimensions.py | 58 ++++--- src/draftwright/pmi.py | 149 ++++++------------ tests/_function_length_baseline.json | 3 +- 5 files changed, 179 insertions(+), 135 deletions(-) diff --git a/src/draftwright/_pmi_part21.py b/src/draftwright/_pmi_part21.py index f17919e6..1a3c148d 100644 --- a/src/draftwright/_pmi_part21.py +++ b/src/draftwright/_pmi_part21.py @@ -1430,6 +1430,27 @@ def read_dimension_display_facts(step_file: str | Path) -> tuple[DimensionDispla return tuple(facts) +def _collect_dimension_representations( + instance, + entity_id: str, + representation_items: dict[str, tuple[str, ...]], + dimension_representations: dict[str, list[str]], +) -> None: + representation = _entity_named(instance, "SHAPE_DIMENSION_REPRESENTATION") + if representation is not None and len(representation.params) >= 2: + representation_items[entity_id] = _references(representation.params[1]) + dimension_link = _entity_named(instance, "DIMENSIONAL_CHARACTERISTIC_REPRESENTATION") + if dimension_link is None or len(dimension_link.params) < 2: + return + characteristic_ref, representation_ref = dimension_link.params[:2] + if isinstance(characteristic_ref, p21.Reference) and isinstance( + representation_ref, p21.Reference + ): + dimension_representations.setdefault(str(characteristic_ref), []).append( + str(representation_ref) + ) + + def read_dimension_associations(step_file: str | Path) -> tuple[DimensionAssociationFact, ...]: """Read exact Part21 topology groups for size and location characteristics. @@ -1517,18 +1538,9 @@ def read_dimension_associations(step_file: str | Path) -> tuple[DimensionAssocia for ref in _references(association.params[4]) if _instance_is(step, ref, "DRAUGHTING_CALLOUT") ) - representation = _entity_named(instance, "SHAPE_DIMENSION_REPRESENTATION") - if representation is not None and len(representation.params) >= 2: - representation_items[entity_id] = _references(representation.params[1]) - dimension_link = _entity_named(instance, "DIMENSIONAL_CHARACTERISTIC_REPRESENTATION") - if dimension_link is not None and len(dimension_link.params) >= 2: - characteristic_ref, representation_ref = dimension_link.params[:2] - if isinstance(characteristic_ref, p21.Reference) and isinstance( - representation_ref, p21.Reference - ): - dimension_representations.setdefault(str(characteristic_ref), []).append( - str(representation_ref) - ) + _collect_dimension_representations( + instance, entity_id, representation_items, dimension_representations + ) def related_items(root: str) -> tuple[str, ...]: pending = [root] @@ -1626,6 +1638,29 @@ def match_dimension_display( return matches[0] if matches and len(policies) == 1 else None +def dimension_basic_policy( + facts: tuple[DimensionDisplayFact, ...], + semantic_name: str, + kind: str, + authored_value: float, + association: DimensionAssociationFact | None, +) -> tuple[bool, tuple[str, ...]]: + """Return basic status and any ambiguity, preferring exact Part21 identity.""" + if association is not None: + return association.basic, () + policies = { + fact.basic + for fact in facts + if fact.semantic_name == semantic_name + and fact.kind == kind + and math.isclose(fact.authored_value, authored_value, rel_tol=1e-9, abs_tol=1e-12) + } + blockers = ( + ("Part21 basic-dimension status is ambiguous for this value",) if len(policies) > 1 else () + ) + return policies == {True}, blockers + + def read_geometric_tolerances(step_file: str | Path) -> tuple[GeometricToleranceFact, ...]: """Read supported geometric-tolerance facts without inferring entity order. diff --git a/src/draftwright/_pmi_schema.py b/src/draftwright/_pmi_schema.py index d5359b9a..4aeb5cfd 100644 --- a/src/draftwright/_pmi_schema.py +++ b/src/draftwright/_pmi_schema.py @@ -56,6 +56,51 @@ "radius": "R", } + +def _make_label( + kind: str, + value: float, + upper_tol: float | None, + lower_tol: float | None, + *, + lower_bound: float | None = None, + upper_bound: float | None = None, + value_decimals: int | None = None, + tolerance_decimals: int | None = None, + unit_name: str = "", +) -> str: + """Format an XCAF dimension label with optional deviation or limit tolerance.""" + from draftwright._core import _fmt + from draftwright._geometry import _fmt_pmi_magnitude + + prefix = _DIM_PREFIX.get(kind, "") + base = f"{prefix}{_fmt(value, value_decimals)}" + if lower_bound is not None and upper_bound is not None: + base = ( + f"{prefix}{_fmt_pmi_magnitude(lower_bound, value_decimals)} - " + f"{prefix}{_fmt_pmi_magnitude(upper_bound, value_decimals)}" + ) + return f"{base} {unit_name}" if unit_name else base + # OCCT returns unsigned tolerance magnitudes; spell both directions out. + if upper_tol is not None and lower_tol is not None: + if abs(upper_tol) == abs(lower_tol) and abs(upper_tol) > 1e-9: + base += f" ±{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" + elif abs(lower_tol) <= 1e-9: + base += f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}/0" + elif abs(upper_tol) <= 1e-9: + base += f" 0/-{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" + else: + base += ( + f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" + f"/-{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" + ) + elif upper_tol is not None: + base += f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" + elif lower_tol is not None: + base += f" -{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" + return f"{base} {unit_name}" if unit_name else base + + # int → short tag for XCAFDimTolObjects_GeomToleranceType _GTOL_TYPE: dict[int, str] = { 1: "angularity", diff --git a/src/draftwright/annotations/_pmi_dimensions.py b/src/draftwright/annotations/_pmi_dimensions.py index c50e21eb..7dae0e65 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -1418,6 +1418,38 @@ def _bore_render_options( ] +def _basic_unboxed_producer(rec, cylindrical_refs, axis: str) -> bool: + """Identify legacy producers without a boxed basic-ink candidate yet.""" + if not getattr(rec, "basic", False): + return False + return rec.pmi_kind == "angular" or ( + rec.pmi_kind == "diameter" and bool(cylindrical_refs) and axis == "?" + ) + + +def _pmi_label_with_count(rec, circular_refs, cylindrical_refs) -> str: + count = len(circular_refs) or ( + len(cylindrical_refs) + if cylindrical_refs and cylindrical_refs[0].principal_axis == "?" + else 0 + ) + label = str(rec.label) + if rec.pmi_kind == "diameter" and count > 1 and re.match(r"^\s*\d+\s*[xX×]\s*", label) is None: + return f"{count}× {label}" + return label + + +def _place_basic_or_supported_pmi_record( + dwg, a: Analysis, ctx, rec, idx, bore_cfg, draft, *, queue_options=_pmi_queue_options +) -> bool: + # These legacy producers draw unboxed text. Do not silently lose a basic box. + cylindrical_refs = tuple(getattr(rec, "cylindrical_refs", ())) + if _basic_unboxed_producer(rec, cylindrical_refs, rec.dominant_axis): + _record_pmi_no_candidate(ctx, rec.label, rec) + return False + return _place_pmi_record(dwg, a, ctx, rec, idx, bore_cfg, draft, queue_options=queue_options) + + def _place_pmi_record( dwg, a: Analysis, ctx, rec, idx, bore_cfg, draft, *, queue_options=_pmi_queue_options ) -> bool: @@ -1430,39 +1462,19 @@ def _place_pmi_record( """ _pmi_queue_options = queue_options ax = rec.dominant_axis - label = rec.label def pmi_spec(*args): return _pmi_dim_spec(*args, basic=getattr(rec, "basic", False)) circular_refs = tuple(getattr(rec, "circular_refs", ())) cylindrical_refs = tuple(getattr(rec, "cylindrical_refs", ())) - pattern_count = len(circular_refs) or ( - len(cylindrical_refs) - if cylindrical_refs and cylindrical_refs[0].principal_axis == "?" - else 0 - ) - if ( - rec.pmi_kind == "diameter" - and pattern_count > 1 - and re.match(r"^\s*\d+\s*[xX×]\s*", label) is None - ): - label = f"{pattern_count}× {label}" + label = _pmi_label_with_count(rec, circular_refs, cylindrical_refs) placed = False name_x = f"pmi_x_{idx}" name_z = f"pmi_z_{idx}" name_y = f"pmi_y_{idx}" name_d = f"pmi_d_{idx}" - # These producers draw unboxed text. Keep source semantics honest until they - # have a basic-frame candidate of their own, rather than emitting plain ink. - if getattr(rec, "basic", False) and ( - rec.pmi_kind == "angular" - or (rec.pmi_kind == "diameter" and cylindrical_refs and ax == "?") - ): - _record_pmi_no_candidate(ctx, label, rec) - return False - if rec.pmi_kind == "angular": references = tuple(getattr(rec, "angular_references", ())) or (rec.angular_reference,) options = [ @@ -1800,7 +1812,9 @@ def render_pmi( sheet_fallback=sheet_fallback, ) for idx, rec in enumerate(usable): - if _place_pmi_record(dwg, a, ctx, rec, idx, _bore, draft, queue_options=queue_options): + if _place_basic_or_supported_pmi_record( + dwg, a, ctx, rec, idx, _bore, draft, queue_options=queue_options + ): queued += 1 _log.info("PMI annotate: %d/%d dims queued", queued, len(usable)) return queued diff --git a/src/draftwright/pmi.py b/src/draftwright/pmi.py index 60588edb..da824678 100644 --- a/src/draftwright/pmi.py +++ b/src/draftwright/pmi.py @@ -63,6 +63,7 @@ DimensionDisplayFact, GeometricToleranceFact, MaterialFact, + dimension_basic_policy, match_common_label, match_datum_occurrence, match_dimension_association, @@ -82,11 +83,11 @@ read_surface_labels, ) from draftwright._pmi_schema import ( - _DIM_PREFIX, _DIM_TYPE, _GTOL_TYPE, _LENGTH_DIMENSION_KINDS, _PRESENTATION_TYPES, + _make_label, ) from draftwright._pmi_schema import ( _GTOL_MATERIAL_REQUIREMENT as _GTOL_MATERIAL_REQUIREMENT, @@ -404,53 +405,6 @@ def _dominant_from_bbox(bbox: tuple[float, float, float, float, float, float]) - return dom[0] if dom[1] > 1e-6 else "?" -def _make_label( - kind: str, - value: float, - upper_tol: float | None, - lower_tol: float | None, - *, - lower_bound: float | None = None, - upper_bound: float | None = None, - value_decimals: int | None = None, - tolerance_decimals: int | None = None, - unit_name: str = "", -) -> str: - """Format the annotation label with optional deviation or limit tolerance.""" - from draftwright._core import _fmt - from draftwright._geometry import _fmt_pmi_magnitude - - prefix = _DIM_PREFIX.get(kind, "") - base = f"{prefix}{_fmt(value, value_decimals)}" - if lower_bound is not None and upper_bound is not None: - base = ( - f"{prefix}{_fmt_pmi_magnitude(lower_bound, value_decimals)} - " - f"{prefix}{_fmt_pmi_magnitude(upper_bound, value_decimals)}" - ) - return f"{base} {unit_name}" if unit_name else base - # OCCT returns tolerances as positive magnitudes regardless of sign - # convention. upper_tol is always the + deviation; lower_tol is always - # the - deviation stored as a positive magnitude. We add explicit signs - # so the label is unambiguous on the drawing. - if upper_tol is not None and lower_tol is not None: - if abs(upper_tol) == abs(lower_tol) and abs(upper_tol) > 1e-9: - base += f" ±{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" - elif abs(lower_tol) <= 1e-9: - base += f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}/0" - elif abs(upper_tol) <= 1e-9: - base += f" 0/-{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" - else: - base += ( - f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" - f"/-{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" - ) - elif upper_tol is not None: - base += f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" - elif lower_tol is not None: - base += f" -{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" - return f"{base} {unit_name}" if unit_name else base - - def _label_entry(label) -> str: """Return the stable TDF entry path for one XCAF source label.""" entry = TCollection_AsciiString() @@ -1199,6 +1153,39 @@ def _semantic_name(obj) -> tuple[str, str]: return name, "" +def _dimension_label( + kind: str, + value: float, + upper_tol: float | None, + lower_tol: float | None, + lower_bound: float | None, + upper_bound: float | None, + display_fact: DimensionDisplayFact | None, + length_factor_mm: float, + length_factor_reason: str, +) -> str: + if ( + display_fact is not None + and display_fact.unit_name + and not length_factor_reason + and math.isclose(display_fact.unit_factor_mm, length_factor_mm, rel_tol=1e-12) + ): + return _make_label( + kind, + display_fact.authored_value, + upper_tol / length_factor_mm if upper_tol is not None else None, + lower_tol / length_factor_mm if lower_tol is not None else None, + lower_bound=lower_bound / length_factor_mm if lower_bound is not None else None, + upper_bound=upper_bound / length_factor_mm if upper_bound is not None else None, + value_decimals=display_fact.value_decimals, + tolerance_decimals=display_fact.tolerance_decimals, + unit_name=display_fact.unit_name, + ) + return _make_label( + kind, value, upper_tol, lower_tol, lower_bound=lower_bound, upper_bound=upper_bound + ) + + def _dimension_record( label, obj, @@ -1283,13 +1270,9 @@ def _dimension_record( except Exception: semantic_name = "" display_fact = match_dimension_display(display_facts, semantic_name, kind, authored_value) - basic_policies = { - fact.basic - for fact in display_facts - if fact.semantic_name == semantic_name - and fact.kind == kind - and math.isclose(fact.authored_value, authored_value, rel_tol=1e-9, abs_tol=1e-12) - } + basic, basic_blockers = dimension_basic_policy( + display_facts, semantic_name, kind, authored_value, association_fact + ) if kind in _LENGTH_DIMENSION_KINDS: if length_factor_reason: partial_reasons.append(length_factor_reason) @@ -1352,11 +1335,7 @@ def _dimension_record( angular_reference.second, ) lowering_blockers = tuple(dict.fromkeys(partial_reasons)) - if association_fact is None and len(basic_policies) > 1: - rendering_blockers = ( - *rendering_blockers, - "Part21 basic-dimension status is ambiguous for this value", - ) + rendering_blockers = (*rendering_blockers, *basic_blockers) blockers = tuple(dict.fromkeys((*lowering_blockers, *rendering_blockers))) return ( PmiRecord( @@ -1370,40 +1349,16 @@ def _dimension_record( ref_pts=tuple(points), ref_bbox=ref_bbox, dominant_axis=dominant_axis, - label=( - _make_label( - kind, - display_fact.authored_value, - upper_tol / length_factor_mm if upper_tol is not None else None, - lower_tol / length_factor_mm if lower_tol is not None else None, - lower_bound=( - lower_bound / length_factor_mm if lower_bound is not None else None - ), - upper_bound=( - upper_bound / length_factor_mm if upper_bound is not None else None - ), - value_decimals=display_fact.value_decimals, - tolerance_decimals=display_fact.tolerance_decimals, - unit_name=display_fact.unit_name, - ) - if ( - display_fact is not None - and display_fact.unit_name - and not length_factor_reason - and math.isclose( - display_fact.unit_factor_mm, - length_factor_mm, - rel_tol=1e-12, - ) - ) - else _make_label( - kind, - value, - upper_tol, - lower_tol, - lower_bound=lower_bound, - upper_bound=upper_bound, - ) + label=_dimension_label( + kind, + value, + upper_tol, + lower_tol, + lower_bound, + upper_bound, + display_fact, + length_factor_mm, + length_factor_reason, ), source_id=source_id, part21_id=association_fact.entity_id if association_fact is not None else "", @@ -1425,11 +1380,7 @@ def _dimension_record( cylindrical_refs=cylindrical_refs, angular_reference=angular_reference, view=support_view, - basic=( - association_fact.basic - if association_fact is not None - else basic_policies == {True} - ), + basic=basic, ), blockers, ) diff --git a/tests/_function_length_baseline.json b/tests/_function_length_baseline.json index 96394fc9..a1afec74 100644 --- a/tests/_function_length_baseline.json +++ b/tests/_function_length_baseline.json @@ -5,7 +5,7 @@ "annotations/_common.py:solve_corridor": 265, "annotations/_diameters.py:render_diameters": 229, "annotations/_locations.py:render_locations": 258, - "annotations/_pmi_dimensions.py:_place_pmi_record": 277, + "annotations/_pmi_dimensions.py:_place_pmi_record": 258, "annotations/_pmi_dimensions.py:_sheet_leader_fallback": 240, "annotations/_slots.py:_place_slot_dimension": 218, "annotations/_slots.py:_render_slot_dimensions": 204, @@ -38,7 +38,6 @@ "linting/turned_step_coverage.py:turned_step_requirement_outcomes": 232, "model/detect.py:_append_late_feature_families": 220, "pdf_text.py:pdf_text_runs": 229, - "pmi.py:_dimension_record": 217, "pmi.py:_extract_xcaf_dimensions": 249, "reporting.py:_raw_report_assessment": 218, "reporting.py:_requirements": 212,