From e0d5b2bf0eb08c04d715d98d847d6ead421f7589 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Sun, 4 Oct 2026 22:22:09 +0100 Subject: [PATCH 1/3] Let authored AP242 dimensions cover planned measurements --- src/draftwright/annotations/_step_lengths.py | 19 + src/draftwright/builder.py | 33 + src/draftwright/drawing.py | 10 + src/draftwright/linting/coverage.py | 157 +++- .../linting/turned_step_coverage.py | 14 +- src/draftwright/model/callout.py | 3 + src/draftwright/model/compiled.py | 46 +- src/draftwright/model/declare.py | 2 + src/draftwright/model/ir_foundation.py | 53 +- src/draftwright/model/planner.py | 456 +++++++++- src/draftwright/model/pmi_lowering.py | 383 ++++++--- src/draftwright/reporting.py | 92 ++ src/draftwright/sheet.py | 18 +- src/draftwright/sheet_emit.py | 45 +- src/draftwright/sheet_feature_lines.py | 11 +- tests/_complexity_baseline.json | 3 +- tests/_function_length_baseline.json | 2 +- tests/test_authored_pmi_precedence.py | 786 ++++++++++++++++++ 18 files changed, 1945 insertions(+), 188 deletions(-) create mode 100644 tests/test_authored_pmi_precedence.py diff --git a/src/draftwright/annotations/_step_lengths.py b/src/draftwright/annotations/_step_lengths.py index 5d76bc8ac..f0244d60b 100644 --- a/src/draftwright/annotations/_step_lengths.py +++ b/src/draftwright/annotations/_step_lengths.py @@ -425,6 +425,7 @@ def _render_single_profile( ) -> int: """Place one axial profile and request details for crowded shoulders.""" rows: list[tuple[str, _StepChainSegment]] = [] + has_baseline_position = False step_origins = [] step_geometry = [] for g in plan.of_kind("step"): @@ -435,6 +436,9 @@ def _render_single_profile( length = g.dim(kind="length") if length is None or length.span is None: continue + has_baseline_position |= ( + length.id is not None and length.id.parameter == "step_position.length" + ) rows.append( ( g.facts.frame.axis, @@ -512,6 +516,21 @@ def _render_single_profile( else _profile_bounds_hint ) + if has_baseline_position: + # The crowded-head and repeated-run transforms describe a contiguous + # step chain. A datum-to-shoulder baseline has different witnesses. + return _draw_step_chain( + dwg, + view, + fsegs, + "m_steplen", + allow_collapse=False, + ctx=ctx, + start=start, + profile_bounds=profile_bounds, + placement_bounds=_profile_bounds_hint, + ) + y_result = _render_y_profile( dwg, view, diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index fea7cb8d5..ed17bb973 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -723,6 +723,39 @@ def preserve_declaration_identity(source, replacements, _member_groups) -> None: else () ), ) + # A caller may supply a PartModel that already contains raw imported PMI. That + # path skips the extraction/lowering branch above but still needs baseline gap + # identities before the compiled plan is built. + if any(feature.kind == "authored_dimension" for feature in pm.features): + from draftwright.model.pmi_lowering import add_authored_step_positions + + identities = pm.declaration_identities + identity_by_feature = { + id(feature): identity + for feature, identity in ( + zip(pm.features, identities, strict=True) if identities else () + ) + if identity is not None + } + step_remapped_identities: dict[int, DeclarationIdentity] = {} + + def preserve_step_identity(source, replacements, _member_groups) -> None: + identity = identity_by_feature.get(id(source)) + if identity is not None and replacements: + step_remapped_identities[id(replacements[0])] = identity + + updated = add_authored_step_positions( + pm, feature_remap=preserve_step_identity if identities else None + ) + if updated is not pm and identities: + updated = replace( + updated, + declaration_identities=tuple( + identity_by_feature.get(id(feature), step_remapped_identities.get(id(feature))) + for feature in updated.features + ), + ) + pm = updated return _with_blind_axial_bore_support(pm, a.cyls) diff --git a/src/draftwright/drawing.py b/src/draftwright/drawing.py index dc4a81909..d1e0c4f11 100644 --- a/src/draftwright/drawing.py +++ b/src/draftwright/drawing.py @@ -735,6 +735,16 @@ def report(self) -> dict[str, object]: return self._diagnostics().report() + def dimension_sources(self) -> list[dict[str, object]]: + """Placed measurements and their exact AP242 or planner provenance. + + One row is returned per measured term, including each term of a compound + callout. This is a read-only inventory for inspection-list consumers. + """ + from draftwright.reporting import placed_dimension_sources + + return placed_dimension_sources(self._part_model, self._registry) + def requirement_snapshot(self, *, include_lint=False): return self._diagnostics().requirement_snapshot(include_lint=include_lint) diff --git a/src/draftwright/linting/coverage.py b/src/draftwright/linting/coverage.py index 0f265e327..770d3667b 100644 --- a/src/draftwright/linting/coverage.py +++ b/src/draftwright/linting/coverage.py @@ -1909,18 +1909,122 @@ def _profile_projection(dwg, view: str, origin, axis: str) -> tuple[bool, float] def _step_length_owners(dwg, name: str) -> tuple[object, ...]: - """Exact step features whose compiled length claim produced annotation *name*.""" + """Exact step features whose axial claim produced annotation *name*.""" registry = getattr(dwg, "registry", None) if registry is None: return () return tuple( identity.feature for identity in registry.measurement_of(name) - if getattr(identity, "parameter", None) == "step.length" + if getattr(identity, "parameter", None) in {"step.length", "step_position.length"} and getattr(identity.feature, "kind", None) == "step" ) +def _authored_axial_witness_on_profile(dwg, name: str, prof, origin, tol: float) -> bool: + """Check a source dimension's two witnesses against this profile's shoulder faces.""" + feature = dwg.registry.feature_of(name) + points: tuple = tuple(getattr(feature, "ref_pts", ())) + if ( + getattr(feature, "kind", None) != "authored_dimension" + or getattr(feature, "dimension_kind", None) != "linear" + or getattr(feature, "dominant_axis", None) != prof.axis.upper() + or len(points) != 2 + ): + return False + axis = "xyz".index(prof.axis) + if abs(abs(float(points[1][axis]) - float(points[0][axis])) - float(feature.value)) > tol: + return False + transverse = tuple(index for index in range(3) if index != axis) + for point in points: + station = float(point[axis]) + touching = [ + step + for step in prof.steps + if abs(float(step.lo) - station) <= tol or abs(float(step.hi) - station) <= tol + ] + if not touching: + return False + radius = max(float(step.diameter) / 2 for step in touching) + radial = sqrt( + sum((float(point[index]) - float(origin[index])) ** 2 for index in transverse) + ) + if radial > radius + tol: + return False + return True + + +def _axial_view_dimensions(part, dwg, prof, view, base, shoulder_c, sibling_profiles, tol): + horizontal, own_cross = _profile_projection(dwg, view, base, prof.axis) + eligible = [] + station_edges = set() + for name, ann in dwg.annotations_in_view(view): + if not isinstance(ann, Dimension): + continue + vertices = _dim_vertices(ann, dwg.registry.dimension_spec_of(name)) + cs = {x if horizontal else y for x, y in vertices} + cross_coords = {y if horizontal else x for x, y in vertices} + owners = _step_length_owners(dwg, name) + if owners and not any(_feature_on_turned_axis(owner, prof) for owner in owners): + continue + authored = getattr(dwg.registry.feature_of(name), "kind", None) == "authored_dimension" + if authored and not _authored_axial_witness_on_profile(dwg, name, prof, base, tol): + continue + if not owners and getattr(prof, "profile", None) is not None and cross_coords: + dim_cross = sum(cross_coords) / len(cross_coords) + own_distance = abs(dim_cross - own_cross) + sibling_distances = [ + abs( + dim_cross + - _profile_projection( + dwg, view, _turned_axis_origin(part, sibling), sibling.axis + )[1] + ) + for sibling in sibling_profiles + if sibling is not prof and sibling.axis == prof.axis + ] + if any(distance <= own_distance + tol for distance in sibling_distances): + continue + eligible.append((name, str(getattr(ann, "label", "") or ""), cs)) + if len(cs) != 2 or not (owners or authored): + continue + stations = [] + for coordinate in sorted(cs): + matches = [ + station + for station, projected in shoulder_c.items() + if abs(coordinate - projected) <= tol + ] + if len(matches) != 1: + break + stations.append(matches[0]) + if len(stations) == 2 and stations[0] != stations[1]: + station_edges.add(tuple(sorted(stations))) + return eligible, station_edges + + +def _axial_connected_steps(prof, station_edges) -> set[int]: + linked = {station: {station} for station in prof.shoulders} + for first, second in station_edges: + linked[first].add(second) + linked[second].add(first) + connected = set() + for index, step in enumerate(prof.steps): + start, end = float(step.lo), float(step.hi) + if start not in linked or end not in linked: + continue + reached = {start} + pending = [start] + while pending: + current = pending.pop() + for neighbour in linked[current] - reached: + reached.add(neighbour) + pending.append(neighbour) + if end in reached: + connected.add(index) + return connected + + def _axial_covered_from_drawing( part, dwg, prof, *, sibling_profiles=(), tol: float = 0.6 ) -> set[int]: @@ -1934,12 +2038,6 @@ def _axial_covered_from_drawing( idx = "xyz".index(prof.axis) base = list(_turned_axis_origin(part, prof)) - def profile_cross(profile, view: str) -> float: - _horizontal, cross = _profile_projection( - dwg, view, _turned_axis_origin(part, profile), profile.axis - ) - return cross - def shoulder_coord(view: str, s: float, *, horizontal: bool) -> float: pt = list(base) pt[idx] = s @@ -1952,26 +2050,14 @@ def shoulder_coord(view: str, s: float, *, horizontal: bool) -> float: views = [view for view in _turned_profile_views(prof.axis) if view in dwg.views] views += sorted(v for v in dwg.views if v.startswith("detail_")) covered_steps: set[int] = set() + station_edges: set[tuple[float, float]] = set() for view in views: horizontal, _own_cross = _profile_projection(dwg, view, base, prof.axis) shoulder_c = {s: shoulder_coord(view, s, horizontal=horizontal) for s in prof.shoulders} - dims = [ - ( - name, - str(getattr(ann, "label", "") or ""), - { - (x if horizontal else y) - for x, y in _dim_vertices(ann, dwg.registry.dimension_spec_of(name)) - }, - { - (y if horizontal else x) - for x, y in _dim_vertices(ann, dwg.registry.dimension_spec_of(name)) - }, - _step_length_owners(dwg, name), - ) - for name, ann in dwg.annotations_in_view(view) - if isinstance(ann, Dimension) - ] + eligible, edges = _axial_view_dimensions( + part, dwg, prof, view, base, shoulder_c, sibling_profiles, tol + ) + station_edges.update(edges) for i, step in enumerate(prof.steps): clo, chi = shoulder_c.get(step.lo), shoulder_c.get(step.hi) if clo is None or chi is None: @@ -1984,26 +2070,9 @@ def shoulder_coord(view: str, s: float, *, horizontal: bool) -> float: # An end-on detail projects both shoulder stations onto one # point. Coincident witnesses cannot establish an axial length. continue - for name, label, cs, cross_coords, owners in dims: + for name, label, cs in eligible: if not cs: continue - if owners and not any(_feature_on_turned_axis(owner, prof) for owner in owners): - continue - # Parallel profiles can have identical axial ordinates. A dimension belongs to - # the nearest visible axis line in this profile view; without this gate one - # shaft's two witnesses would certify every sibling at the same stations. - if not owners and getattr(prof, "profile", None) is not None and cross_coords: - dim_cross = sum(cross_coords) / len(cross_coords) - own_distance = abs(dim_cross - profile_cross(prof, view)) - sibling_distances = [ - abs(dim_cross - profile_cross(sibling, view)) - for sibling in sibling_profiles - if sibling is not prof and sibling.axis == prof.axis - ] - if any(distance < own_distance - tol for distance in sibling_distances) or any( - abs(distance - own_distance) <= tol for distance in sibling_distances - ): - continue # A plain dim locates the step when it has a witness at each shoulder. if any(abs(v - clo) <= tol for v in cs) and any(abs(v - chi) <= tol for v in cs): covered_steps.add(i) @@ -2022,7 +2091,7 @@ def shoulder_coord(view: str, s: float, *, horizontal: bool) -> float: ): covered_steps.add(i) break - return covered_steps + return covered_steps | _axial_connected_steps(prof, station_edges) def _overall_axial_extent_is_dimensioned( diff --git a/src/draftwright/linting/turned_step_coverage.py b/src/draftwright/linting/turned_step_coverage.py index f484e24ac..b49ff029a 100644 --- a/src/draftwright/linting/turned_step_coverage.py +++ b/src/draftwright/linting/turned_step_coverage.py @@ -272,10 +272,16 @@ def physical_turned_steps(recognition: RecognitionResult) -> tuple[tuple[object, def _has_parameters(feature) -> bool: try: - return {parameter.parameter_id for parameter in feature.parameters()} == { - "step.length", - "step.diameter", - } + parameters = {parameter.parameter_id for parameter in feature.parameters()} + return ( + {"step.length", "step.diameter"} + <= parameters + <= { + "step.length", + "step.diameter", + "step_position.length", + } + ) except (AttributeError, TypeError): return False diff --git a/src/draftwright/model/callout.py b/src/draftwright/model/callout.py index 8292e096e..9f4f10633 100644 --- a/src/draftwright/model/callout.py +++ b/src/draftwright/model/callout.py @@ -102,6 +102,8 @@ def _merge_member_pattern_batches(batches: list[HoleCalloutBatch]) -> list[HoleC def bore_callout_value(spec: dict, tolerance_suffix=lambda _value: "") -> str: """Format the bore value after the callout's leading diameter symbol.""" + if spec.get("authored_diameter_label") and spec.get("tolerance") is None: + return str(spec["authored_diameter_label"])[1:] if limits := spec.get("diameter_limits"): lower, upper = limits nominal = spec["diameter"] @@ -797,6 +799,7 @@ def _tol_of(planned): ) spec = { "diameter": bore, + "authored_diameter_label": bore_pd.param.source_label if bore_pd is not None else None, "diameter_decimals": _display_decimals(group, "diameter", "bore"), "count": count if count and count > 1 else None, "through": hole.through, # the feature's fact, not the param list's shape (#868) diff --git a/src/draftwright/model/compiled.py b/src/draftwright/model/compiled.py index 4cd188898..0dc3a22f3 100644 --- a/src/draftwright/model/compiled.py +++ b/src/draftwright/model/compiled.py @@ -65,6 +65,7 @@ from draftwright.model.callout import resolved_through_indicator from draftwright.model.ir import ( AngularReference, + AuthoredDimension, ChamferFeature, CircularChannelFeature, EnvelopeFeature, @@ -89,6 +90,9 @@ CORRELATED_SETS, DimensionId, _authored_for, + _authored_linear_stations, + _authored_location_matches, + _authored_same_span, _decorated, _extent_can_convey, _is_zero_step_position, @@ -1212,7 +1216,9 @@ def _compile_overall_height( return None, None, [] mark = marked.get((id(env), "height.length")) if env is not None else None if env is not None: - if mark is not None and mark[1] == _AUTHORED_OMISSION: + if mark is not None and ( + mark[1] == _AUTHORED_OMISSION or mark[1].startswith("authored PMI dimension ") + ): return None, None, [Omission(env, "height.length", mark[0], mark[1])] elif model.authored_dimensions is not None: # No `EnvelopeFeature`, so the height falls back to the bounding box and no @@ -2062,6 +2068,44 @@ def compile_dimensions( off_axis, off_axis_omissions = _compile_off_axis_hole_locations(model) locations.extend(off_axis) location_omissions.extend(off_axis_omissions) + # A source location may cover one directional component without covering its + # orthogonal sibling. Only exact witness correspondence can remove that component. + sources = tuple(f for f in model.features if isinstance(f, AuthoredDimension)) + if sources and model.authored_dimensions is None: + unique_cover: dict[int, list[AuthoredDimension]] = {} + for source in sources: + stations = _authored_linear_stations(source) + if stations is None: + continue + matching = [ + location + for location in locations + if location.discriminator == "xyz"[stations[0]] + and location.span is not None + and ( + _authored_same_span(source, location.span, location.value) + or _authored_location_matches( + source, location.span, location.discriminator, location.value + ) + ) + ] + if len(matching) == 1: + unique_cover.setdefault(id(matching[0]), []).append(source) + uncovered = [] + for location in locations: + covering = unique_cover.get(id(location), []) + if len(covering) != 1 or location.id is None: + uncovered.append(location) + else: + location_omissions.append( + Omission( + location.id.feature, + location.id.parameter, + location.value, + f"authored PMI dimension {covering[0].source_id} covers this location", + ) + ) + locations = uncovered result = RenderableDimensionPlan( groups=tuple(groups_out), ladders=tuple(ladders), diff --git a/src/draftwright/model/declare.py b/src/draftwright/model/declare.py index 883fd3c0d..54bc956b2 100644 --- a/src/draftwright/model/declare.py +++ b/src/draftwright/model/declare.py @@ -525,6 +525,7 @@ def step( at=None, axis=None, span=None, + position_span=None, thread=None, knurl=None, profile_group=None, @@ -558,6 +559,7 @@ def step( length=length, diameter=diameter, span=span, + position_span=position_span, thread=thread, knurl=knurl, profile_group=profile_group, diff --git a/src/draftwright/model/ir_foundation.py b/src/draftwright/model/ir_foundation.py index 820c4a5b0..68485b8f1 100644 --- a/src/draftwright/model/ir_foundation.py +++ b/src/draftwright/model/ir_foundation.py @@ -6,6 +6,7 @@ from __future__ import annotations +import re from dataclasses import dataclass, replace from math import atan2, cos, hypot, isfinite, pi, radians, sin from typing import TYPE_CHECKING, ClassVar, Literal, Protocol, runtime_checkable @@ -370,6 +371,9 @@ class DimParameter: # deciding whether otherwise identical physical callouts may be consolidated. source_ids: tuple[str, ...] = () limit_bounds: tuple[float, float] | None = None + # Exact AP242 wording when a canonical hole callout carries an authored + # nominal whose printed form differs from the default numeric formatter. + source_label: str | None = None @property def parameter_id(self) -> ParameterId: @@ -413,15 +417,14 @@ class ToleranceDecoration: class NominalRequirement: """External ownership of an already-canonical nominal dimension. - Unlike :class:`ToleranceDecoration`, this adds no printed suffix: the feature's normal - planned diameter is already the truthful visual annotation. The wrapper records which - imported semantic sources own that existing annotation, so provenance survives lowering, - lint reconciliation, and generated-Sheet round trips without creating a duplicate. + The canonical parameter carries the imported source identity without creating a duplicate. + An optional diameter label preserves authored numeric precision or a short fit class. """ value: float source: str source_ids: tuple[str, ...] + label: str | None = None def agrees_with(self, value: float) -> bool: """Whether a canonical value can carry this nominal without changing its meaning.""" @@ -441,6 +444,15 @@ def __post_init__(self) -> None: ) if not ids: raise ValueError("nominal requirement needs at least one source id") + if self.label is not None and (not isinstance(self.label, str) or not self.label.strip()): + raise ValueError("nominal requirement label must be non-empty text") + if self.label is not None: + match = re.fullmatch( + r"[øØ⌀]\s*(\d+(?:\.\d+)?)(?:\s+[A-Za-z]{1,2}\d{1,2})?", + self.label, + ) + if match is None or abs(float(match.group(1)) - value) > 1e-6: + raise ValueError("nominal requirement label must agree with its diameter") object.__setattr__(self, "value", value) object.__setattr__(self, "source", source) object.__setattr__(self, "source_ids", ids) @@ -840,13 +852,41 @@ class StepFeature: #: this opaque token instead of exposing the provider's ``TurnedProfileKey``; ordinary #: declarations may omit it and retain geometric grouping. profile_group: str | None = None + # A planner-filled datum-to-shoulder measurement. The geometric ``step.length`` + # remains the local segment; this is a separate, addressable position fact. + position_span: tuple[Point, Point] | None = None kind: ClassVar[str] = "step" + def __post_init__(self) -> None: + if self.position_span is None: + return + first = _finite_point3("step position start", self.position_span[0]) + second = _finite_point3("step position end", self.position_span[1]) + axis = "xyz".index(self.frame.axis) + if abs(second[axis] - first[axis]) <= 1e-9 or any( + abs(first[index] - second[index]) > 1e-6 for index in range(3) if index != axis + ): + raise ValueError("step position must run along the step axis") + if not any(abs(second[axis] - point[axis]) <= 0.01 for point in self.span): + raise ValueError("step position must end at one of its step's shoulders") + def parameters(self) -> list[DimParameter]: - return [ + parameters = [ DimParameter("length", "step", self.length, span=self.span), DimParameter("diameter", "step", self.diameter), ] + if self.position_span is not None: + axis = "xyz".index(self.frame.axis) + first, second = self.position_span + parameters.append( + DimParameter( + "length", + "step_position", + abs(second[axis] - first[axis]), + span=self.position_span, + ) + ) + return parameters def references(self) -> list[Datum]: return [] @@ -914,6 +954,9 @@ def parameters(self) -> list[DimParameter]: requirement.value if isinstance(requirement, ToleranceDecoration) else None ), source_ids=requirement.source_ids if requirement is not None else (), + source_label=( + requirement.label if isinstance(requirement, NominalRequirement) else None + ), limit_bounds=( requirement.limit_bounds if isinstance(requirement, ToleranceDecoration) diff --git a/src/draftwright/model/planner.py b/src/draftwright/model/planner.py index b1169a26e..7d9615b70 100644 --- a/src/draftwright/model/planner.py +++ b/src/draftwright/model/planner.py @@ -27,6 +27,7 @@ from __future__ import annotations from dataclasses import dataclass, replace +from math import hypot from typing import Any, Literal from draftwright._geometry import _EDGE_ON, _END_ON, HoleRef, _fmt, _fmt_angle @@ -36,17 +37,20 @@ PLACEMENT_VIEWS, AngleFeature, AnglePatternFeature, + AuthoredDimension, BlendFeature, ChamferFeature, ChannelFeature, CircularChannelFeature, Datum, DimParameter, + EnvelopeFeature, Feature, FilletFeature, FlatFeature, HexPocketFeature, HoleFeature, + NominalRequirement, OrientedSlotFeature, PadFeature, ParameterId, @@ -63,6 +67,7 @@ ScheduleRow, SlotFeature, SlotPatternFeature, + StepFeature, StepLevelFeature, validate_authored_dimension_placement, ) @@ -80,6 +85,427 @@ _SCHEDULE_REPRESENTATION = "selected for a feature schedule" +def _authored_linear_stations(source: AuthoredDimension) -> tuple[int, float, float] | None: + """Return the proved normal stations of one renderable imported length.""" + if ( + source.source != "ap242_pmi" + or source.dimension_kind != "linear" + or source.dominant_axis not in ("X", "Y", "Z") + or len(source.ref_pts) != 2 + or source.rendering_blockers + ): + return None + axis = "XYZ".index(source.dominant_axis) + first, second = (float(point[axis]) for point in source.ref_pts) + if abs(abs(second - first) - source.value) > 1e-6: + return None + return axis, first, second + + +def _source_on_turned_profile( + source: AuthoredDimension, steps: list[StepFeature], axis: int +) -> bool: + """Require both source witnesses to lie on this one axial body's end planes.""" + transverse = tuple(index for index in range(3) if index != axis) + line = tuple(float(steps[0].frame.origin[index]) for index in transverse) + if any( + step.frame.axis != "xyz"[axis] + or step.span is None + or any( + abs(step.frame.origin[index] - line[i]) > 0.01 for i, index in enumerate(transverse) + ) + for step in steps + ): + return False + for point in source.ref_pts: + at = float(point[axis]) + touching = [ + step + for step in steps + if step.span is not None + and any(abs(float(end[axis]) - at) <= 0.01 for end in step.span) + ] + if not touching: + return False + radius = max(float(step.diameter) / 2 for step in touching) + offset = hypot(*(float(point[index]) - line[i] for i, index in enumerate(transverse))) + if offset > radius + 0.01: + return False + return True + + +def _authored_step_groups(model: PartModel) -> list[list[StepFeature]]: + """Partition coaxial steps into connected physical runs.""" + groups: list[list[StepFeature]] = [] + keys: list[tuple[object, ...]] = [] + for feature in model.features: + if not isinstance(feature, StepFeature): + continue + axis_index = "xyz".index(feature.frame.axis) + key = ( + feature.frame.axis, + feature.profile, + feature.profile_group, + *(round(float(feature.frame.origin[i]), 6) for i in range(3) if i != axis_index), + ) + if key in keys: + groups[keys.index(key)].append(feature) + else: + keys.append(key) + groups.append([feature]) + connected_groups: list[list[StepFeature]] = [] + for group in groups: + axis_index = "xyz".index(group[0].frame.axis) + ordered = sorted(group, key=lambda step: min(point[axis_index] for point in step.span)) + run: list[StepFeature] = [] + previous_hi = None + for step in ordered: + lo, hi = sorted(float(point[axis_index]) for point in step.span) + if previous_hi is not None and abs(lo - previous_hi) > 0.01: + connected_groups.append(run) + run = [] + run.append(step) + previous_hi = hi + if run: + connected_groups.append(run) + return connected_groups + + +def _authored_baseline_candidates(model, steps, groups, axis, intervals, ends): + candidates: dict[float, dict[float, str]] = {} + established: set[float] = set() + for source in model.features: + if not isinstance(source, AuthoredDimension): + continue + stations = _authored_linear_stations(source) + if stations is None or stations[0] != axis: + continue + if not _source_on_turned_profile(source, steps, axis): + continue + if sum(_source_on_turned_profile(source, group, axis) for group in groups) != 1: + continue + first, second = stations[1:] + for base, target_station in ((first, second), (second, first)): + end = next((end for end in ends if abs(base - end) <= 0.01), None) + if end is None or not any( + abs(target_station - station) <= 0.01 for pair in intervals for station in pair + ): + continue + candidates.setdefault(end, {})[round(target_station, 6)] = source.source_id + if not any( + abs(min(base, target_station) - lo) <= 0.01 + and abs(max(base, target_station) - hi) <= 0.01 + for lo, hi in intervals + ): + established.add(end) + return candidates, established + + +def _authored_step_baseline( + model: PartModel, + target: StepFeature | None = None, + *, + groups: list[list[StepFeature]] | None = None, +) -> tuple[int, float, dict[float, str]] | None: + """Find one unambiguous authored end reference for a turned profile. + + The raw source's references establish the scheme; its nominal alone never does. + Each physical profile is considered separately. A source that could belong to + two profiles, or opposing references with equal support, leaves its chain alone. + """ + if groups is None: + groups = _authored_step_groups(model) + if target is None: + if len(groups) != 1: + return None + steps = groups[0] + else: + steps = next((group for group in groups if any(step is target for step in group)), []) + if not steps: + return None + axis = "xyz".index(steps[0].frame.axis) + transverse = tuple(i for i in range(3) if i != axis) + line = tuple(steps[0].frame.origin[i] for i in transverse) + if any( + step.span is None + or any(abs(step.frame.origin[i] - line[j]) > 0.01 for j, i in enumerate(transverse)) + for step in steps + ): + return None + intervals = sorted( + tuple(sorted((float(step.span[0][axis]), float(step.span[1][axis])))) for step in steps + ) + if any( + abs(left[1] - right[0]) > 0.01 + for left, right in zip(intervals, intervals[1:], strict=False) + ): + return None + ends = (intervals[0][0], intervals[-1][1]) + candidates, established = _authored_baseline_candidates( + model, steps, groups, axis, intervals, ends + ) + if not established: + return None + leaders = sorted(candidates, key=lambda base: len(candidates[base]), reverse=True) + if len(leaders) > 1 and len(candidates[leaders[0]]) == len(candidates[leaders[1]]): + # A lone end-to-end source names both end planes but no preferred datum. + # Either end gives the same authored overall; use the lower station as a + # stable reference for uncovered levels, avoiding a redundant full chain. + whole_span = ( + len(leaders) == 2 + and len(candidates[leaders[0]]) == 1 + and len(candidates[leaders[1]]) == 1 + and candidates[leaders[0]].get(round(leaders[1], 6)) + == candidates[leaders[1]].get(round(leaders[0], 6)) + ) + if not whole_span: + return None + base = min(leaders) + else: + base = leaders[0] + covered = candidates[base] + return axis, base, covered + + +def _authored_same_span( + source: AuthoredDimension, span: tuple[Point, Point], value: float +) -> bool: + if abs(source.value - value) > 1e-6: + return False + return any( + all( + all(abs(a - b) <= 0.01 for a, b in zip(point, end, strict=True)) + for point, end in zip(points, span, strict=True) + ) + for points in (source.ref_pts, tuple(reversed(source.ref_pts))) + ) + + +def _authored_location_matches( + source: AuthoredDimension, span: tuple[Point, Point], axis: str, value: float +) -> bool: + """Match one datum-to-feature component with its actual source witnesses.""" + stations = _authored_linear_stations(source) + if stations is None or axis != "xyz"[stations[0]] or abs(source.value - value) > 1e-6: + return False + index = stations[0] + target = span[1] + return any( + all(abs(a - b) <= 0.01 for a, b in zip(point, target, strict=True)) + and abs(float(other[index]) - float(span[0][index])) <= 0.01 + and all(abs(float(other[i]) - float(target[i])) <= 0.01 for i in range(3) if i != index) + for point, other in ( + (source.ref_pts[0], source.ref_pts[1]), + (source.ref_pts[1], source.ref_pts[0]), + ) + ) + + +def _authored_linear_covers( + source: AuthoredDimension, + feature: Feature, + parameter: DimParameter, + steps: list[StepFeature], +) -> bool: + if parameter.kind != "length" or parameter.span is None: + return False + stations = _authored_linear_stations(source) + if stations is None: + return False + if _authored_same_span(source, parameter.span, parameter.value): + return True + return ( + isinstance(feature, StepFeature) + and feature.frame.axis == "xyz"[stations[0]] + and abs(source.value - parameter.value) <= 1e-6 + and all( + abs(a - b) <= 0.01 + for a, b in zip( + sorted(stations[1:]), + sorted(float(point[stations[0]]) for point in parameter.span), + strict=True, + ) + ) + and bool(steps) + and _source_on_turned_profile(source, steps, stations[0]) + ) + + +def _authored_diameter_coverage( + model: PartModel, feature: Feature, parameter: DimParameter +) -> str | None: + """Keep a noncanonical source label and withhold its proved canonical duplicate.""" + if parameter.kind != "diameter" or parameter.tolerance is not None: + return None + requirement = model.decorations.get((feature, "nominal_requirement", parameter.parameter_id)) + if not isinstance(requirement, NominalRequirement) and isinstance(feature, RotationalFeature): + groups = _authored_step_groups(model) + if len(groups) != 1: + return None + axis = "xyz".index(feature.frame.axis) + profile = groups[0] + stations = [float(point[axis]) for step in profile for point in (step.span or ())] + if ( + not stations + or not min(stations) - 0.01 <= feature.frame.origin[axis] <= max(stations) + 0.01 + ): + return None + inherited = { + source_id + for step in profile + if step.frame.axis == feature.frame.axis + and abs(step.diameter - parameter.value) <= 1e-6 + and all( + abs(step.frame.origin[i] - feature.frame.origin[i]) <= 0.01 + for i in range(3) + if i != axis + ) + for step_diameter in step.parameters() + if step_diameter.parameter_id == "step.diameter" + if (source_id := _authored_diameter_coverage(model, step, step_diameter)) is not None + } + return next(iter(inherited)) if len(inherited) == 1 else None + if isinstance(feature, PatternFeature) and parameter.discriminator is not None: + member = parameter.discriminator.removeprefix("member_") + if parameter.discriminator.startswith("member_") and member.isdecimal(): + index = int(member) + if index < len(feature.member_size_requirements): + requirement = feature.member_size_requirements[index] + if not isinstance(requirement, NominalRequirement): + return None + matching = [ + source + for source in model.features + if isinstance(source, AuthoredDimension) + and source.source == "ap242_pmi" + and source.dimension_kind == "diameter" + and source.source_id in requirement.source_ids + and not source.rendering_blockers + and abs(source.value - parameter.value) <= 1e-6 + ] + return matching[0].source_id if len(matching) == 1 else None + + +def _authored_envelope_faces(source, feature, parameter) -> bool: + axis = {"width": 0, "depth": 1, "height": 2}.get(parameter.role) + stations = _authored_linear_stations(source) + if axis is None or stations is None or stations[0] != axis: + return False + if abs(source.value - parameter.value) > 1e-6: + return False + lo, hi = sorted(stations[1:]) + if abs(lo - feature.bbox_min[axis]) > 0.01 or abs(hi - feature.bbox_max[axis]) > 0.01: + return False + return all( + feature.bbox_min[i] - 0.01 <= float(point[i]) <= feature.bbox_max[i] + 0.01 + for point in source.ref_pts + for i in range(3) + if i != axis + ) + + +def _authored_envelope_coverage(model, feature, parameter, baseline) -> str | None: + if baseline is not None: + axis, _base, covered = baseline + envelope_role = ("width", "depth", "height")[axis] + if parameter.role == envelope_role: + extent_hi = max(float(point[axis]) for point in parameter.span) + extent_lo = min(float(point[axis]) for point in parameter.span) + source_id = covered.get(round(extent_hi, 6)) or covered.get(round(extent_lo, 6)) + if source_id is not None and abs(parameter.value - abs(extent_hi - extent_lo)) <= 1e-6: + return f"authored PMI dimension {source_id} covers this extent" + for source in model.features: + if not isinstance(source, AuthoredDimension): + continue + stations = _authored_linear_stations(source) + if stations is None: + continue + axis, first, second = stations + if ( + model.orientation == "xyz"[axis] + and parameter.role == ("width", "depth", "height")[axis] + and (steps := [item for item in model.features if isinstance(item, StepFeature)]) + and _source_on_turned_profile(source, steps, axis) + and abs(source.value - parameter.value) <= 1e-6 + and all( + abs(a - b) <= 0.01 + for a, b in zip( + sorted((first, second)), + sorted(point[axis] for point in parameter.span), + strict=True, + ) + ) + ): + return f"authored PMI dimension {source.source_id} covers this extent" + if _authored_same_span(source, parameter.span, parameter.value): + return f"authored PMI dimension {source.source_id} covers this extent" + if ( + _authored_envelope_faces(source, feature, parameter) + and sum(isinstance(item, EnvelopeFeature) for item in model.features) == 1 + ): + return f"authored PMI dimension {source.source_id} covers this extent" + return None + + +def _authored_pmi_overlay( + model: PartModel, + feature: Feature, + parameter: DimParameter, + baseline: tuple[int, float, dict[float, str]] | None, + step_groups: dict[int, list[StepFeature]], +) -> tuple[DimParameter, str | None]: + """Let imported references cover automatic measurements before compilation.""" + if model.authored_dimensions is not None: + return parameter, None + if parameter.kind == "diameter": + source_id = _authored_diameter_coverage(model, feature, parameter) + return ( + (parameter, f"authored PMI dimension {source_id} covers this diameter") + if source_id is not None + else (parameter, None) + ) + if parameter.kind != "length" or parameter.span is None: + return parameter, None + if parameter.tolerance is None: + steps = step_groups.get(id(feature), []) + for source in model.features: + if not isinstance(source, AuthoredDimension): + continue + if not _authored_linear_covers(source, feature, parameter, steps): + continue + matches = sum( + _authored_linear_covers(source, other, candidate, step_groups.get(id(other), [])) + for other in model.features + if type(other) is type(feature) + for candidate in other.parameters() + if candidate.role == parameter.role + ) + if matches == 1: + return ( + parameter, + f"authored PMI dimension {source.source_id} covers this measurement", + ) + if isinstance(feature, StepFeature) and baseline is not None: + axis, base, covered = baseline + if feature.frame.axis != "xyz"[axis] or parameter.parameter_id != "step.length": + return parameter, None + step_stations = sorted(float(point[axis]) for point in parameter.span) + target = ( + step_stations[1] + if abs(base - step_stations[0]) <= abs(base - step_stations[1]) + else step_stations[0] + ) + source_id = covered.get(round(target, 6)) + if source_id is not None and parameter.tolerance is None: + return parameter, f"authored PMI dimension {source_id} covers this station" + if feature.position_span is not None: + return parameter, "authored baseline uses step_position.length" + return parameter, None + if not isinstance(feature, EnvelopeFeature) or parameter.tolerance is not None: + return parameter, None + return parameter, _authored_envelope_coverage(model, feature, parameter, baseline) + + def _is_zero_step_position(value: float) -> bool: """Whether a shoulder measures no distance from its datum. @@ -93,6 +519,7 @@ def _is_zero_step_position(value: float) -> bool: _CONVENTION = { ("included", "angle"): "angular", ("step", "length"): "chain", + ("step_position", "length"): "linear", ("step", "diameter"): "leader", ("bore", "diameter"): "leader", ("bore", "depth"): "leader", @@ -610,6 +1037,9 @@ def _decorated(model: PartModel, feature: Feature, param: DimParameter) -> DimPa f"{nominal.source} nominal requirement {nominal.value:g} disagrees with " f"{param.parameter_id}={param.value:g}" ) + nominal_ids = nominal.source_ids if isinstance(nominal, NominalRequirement) else () + if isinstance(nominal, NominalRequirement): + param = replace(param, source_label=nominal.label, source_ids=nominal_ids) tol = ( model.decorations.get((feature, param.kind, param.role, param.discriminator)) @@ -623,10 +1053,10 @@ def _decorated(model: PartModel, feature: Feature, param: DimParameter) -> DimPa # Imported AP242 provenance belongs to the authored aspect, not to geometry and not to # the renderer's tolerance algebra. Unwrap it at the planner waist so every downstream # label/render path continues to see the established float/tuple/FitClass contract. - source_ids: tuple[str, ...] = () + source_ids: tuple[str, ...] = nominal_ids limit_bounds = None if isinstance(tol, ToleranceDecoration): - source_ids = tol.source_ids + source_ids = tuple(dict.fromkeys((*source_ids, *tol.source_ids))) limit_bounds = tol.limit_bounds tol = tol.value return ( @@ -1982,10 +2412,25 @@ def plan_dimensions(model: PartModel, *, planned_views=None) -> list[DimensionGr selection = authored_dimension_requests(model) # validate even without scalar parameters _check_intent_policy_conflicts(model) model = _selection_model(model, selection) + has_imported_dimensions = any( + isinstance(feature, AuthoredDimension) for feature in model.features + ) + profile_groups = _authored_step_groups(model) if has_imported_dimensions else [] + step_groups = {id(step): group for group in profile_groups for step in group} + baselines: dict[int, tuple[int, float, dict[float, str]] | None] = {} + for profile_group in profile_groups: + baseline = _authored_step_baseline(model, profile_group[0], groups=profile_groups) + baselines.update((id(step), baseline) for step in profile_group) + authored_baseline = ( + baselines.get(id(profile_groups[0][0])) if len(profile_groups) == 1 else None + ) if model.authored_dimensions is not None: _check_authored_targets(model) groups: list[DimensionGroup] = [] for feature in model.features: + feature_baseline = ( + baselines.get(id(feature)) if isinstance(feature, StepFeature) else authored_baseline + ) dims = [] for p in feature.parameters(): if p.kind == "location": @@ -2010,6 +2455,13 @@ def plan_dimensions(model: PartModel, *, planned_views=None) -> list[DimensionGr display_intent = request if request is not None: suppressed, reason, conveyed_by = False, None, None + p, authored_coverage = ( + _authored_pmi_overlay(model, feature, p, feature_baseline, step_groups) + if has_imported_dimensions + else (p, None) + ) + if authored_coverage is not None: + suppressed, reason, conveyed_by = True, authored_coverage, None if model.authored_dimensions is not None: # An authored set REPLACES the rule set rather than adding to it: what the # script lists is what the drawing carries, and everything else is omitted. diff --git a/src/draftwright/model/pmi_lowering.py b/src/draftwright/model/pmi_lowering.py index ad0713528..a0760a837 100644 --- a/src/draftwright/model/pmi_lowering.py +++ b/src/draftwright/model/pmi_lowering.py @@ -14,9 +14,9 @@ from collections.abc import Callable, Iterable from dataclasses import replace from decimal import Decimal -from typing import Literal, cast +from typing import Literal, TypeGuard, cast -from draftwright._geometry import _cylindrical_finish_site +from draftwright._geometry import _cylindrical_finish_site, _fmt from draftwright.model.ir import ( AuthoredDimension, BossFeature, @@ -87,6 +87,24 @@ def _source_ids(dim: AuthoredDimension) -> tuple[str, ...]: return (dim.source_id,) if dim.source_id else () +def _plain_cylinder_source(feature: Feature) -> TypeGuard[AuthoredDimension]: + return ( + isinstance(feature, AuthoredDimension) + and feature.dimension_kind == "diameter" + and feature.source == "ap242_pmi" + and bool(feature.cylindrical_refs) + and all( + value is None + for value in ( + feature.lower_tol, + feature.upper_tol, + feature.lower_bound, + feature.upper_bound, + ) + ) + ) + + def _limit_bounds(dim: AuthoredDimension) -> tuple[float, float] | None: if dim.lower_bound is None or dim.upper_bound is None: return None @@ -464,6 +482,33 @@ def _nominal_owner_key(feature) -> tuple: return (feature, "nominal_requirement", parameter) +def _canonical_nominal_diameter_label(dimension: AuthoredDimension) -> bool: + """The plain source value has the same wording as the canonical diameter size.""" + return dimension.label == f"ø{_fmt(dimension.value)}" + + +def _callout_nominal_label(dimension: AuthoredDimension) -> str | None: + """Keep source wording that can head the existing diameter callout.""" + match = re.fullmatch(r"[øØ⌀]\s*(\d+(?:\.\d+)?)(?:\s+[A-Za-z]{1,2}\d{1,2})?", dimension.label) + if match is None or abs(float(match.group(1)) - dimension.value) > 1e-6: + return None + return dimension.label + + +def _nominal_label_for_owner( + dimension: AuthoredDimension, owner: Feature +) -> tuple[bool, str | None]: + if not isinstance(owner, HoleFeature | PatternFeature): + return True, None + bore = owner.member if isinstance(owner, PatternFeature) else owner + if _canonical_nominal_diameter_label(dimension) or ( + bore.through and dimension.label == f"ø{_fmt(dimension.value)} THRU" + ): + return True, None + label = _callout_nominal_label(dimension) + return label is not None, label + + def _standalone_cylinder_blocker(references: tuple[CylindricalReference, ...]) -> str: """Why a cylinder group cannot truthfully anchor one standalone diameter mark.""" if len(references) < 2: @@ -598,6 +643,65 @@ def _pattern_nominal_members( return tuple(sorted(covered)) +def _pattern_nominal_owner(dimension, features, bbox): + matches = [ + (index, feature, member_indices) + for index, feature in enumerate(features) + if isinstance(feature, PatternFeature) + and (member_indices := _pattern_nominal_members(dimension, feature, bbox)) + and (len(member_indices) < feature.count or feature.member_size_requirements) + ] + if not matches: + return None + other_matches = [ + feature + for feature in features + if isinstance(feature, StepFeature | BossFeature | HoleFeature | RotationalFeature) + and _nominal_owner_matches(dimension, feature, bbox) + ] + if len(matches) != 1 or other_matches: + return "ambiguous diameter ownership: source cylinders match multiple features" + return matches[0] + + +def _pattern_nominal_conflict(requirements, member_indices, nominal) -> bool: + return any( + requirement is not None + and ( + requirement.source != "ap242_pmi" + or ( + isinstance(requirement, NominalRequirement) + and ( + not requirement.agrees_with(nominal.value) + or requirement.label != nominal.label + ) + ) + or (isinstance(requirement, ToleranceDecoration) and nominal.label is not None) + ) + for index in member_indices + if (requirement := requirements[index]) is not None + ) + + +def _merged_pattern_requirements(requirements, member_indices, nominal): + for index in member_indices: + requirement = requirements[index] + if requirement is None: + requirements[index] = nominal + elif isinstance(requirement, NominalRequirement): + requirements[index] = replace( + requirement, + source_ids=tuple(dict.fromkeys((*requirement.source_ids, *nominal.source_ids))), + label=requirement.label or nominal.label, + ) + else: + requirements[index] = replace( + requirement, + source_ids=tuple(dict.fromkeys((*requirement.source_ids, *nominal.source_ids))), + ) + return requirements + + def _lower_pattern_nominal_diameters( model: PartModel, *, feature_remap: FeatureRemap | None ) -> PartModel: @@ -608,45 +712,27 @@ def _lower_pattern_nominal_diameters( blocked: dict[int, str] = {} for dim_index, dimension in enumerate(model.features): if not ( - isinstance(dimension, AuthoredDimension) - and dimension.dimension_kind == "diameter" - and dimension.source == "ap242_pmi" - and dimension.cylindrical_refs + _plain_cylinder_source(dimension) and not dimension.lowering_blockers and not dimension.rendering_blockers - and all( - value is None - for value in ( - dimension.lower_tol, - dimension.upper_tol, - dimension.lower_bound, - dimension.upper_bound, - ) - ) ): continue - matches = [ - (index, feature, member_indices) - for index, feature in enumerate(features) - if isinstance(feature, PatternFeature) - and (member_indices := _pattern_nominal_members(dimension, feature, model.bbox)) - and (len(member_indices) < feature.count or feature.member_size_requirements) - ] - if not matches: + owner_match = _pattern_nominal_owner(dimension, features, model.bbox) + if owner_match is None: continue - other_matches = [ - feature - for feature in features - if isinstance(feature, StepFeature | BossFeature | HoleFeature | RotationalFeature) - and _nominal_owner_matches(dimension, feature, model.bbox) - ] - if len(matches) != 1 or other_matches: - blocked[dim_index] = ( - "ambiguous diameter ownership: source cylinders match multiple features" - ) + if isinstance(owner_match, str): + blocked[dim_index] = owner_match continue - owner_index, owner, member_indices = matches[0] - nominal = NominalRequirement(dimension.value, "ap242_pmi", _source_ids(dimension)) + owner_index, owner, member_indices = owner_match + supported, label = _nominal_label_for_owner(dimension, owner) + if not supported: + continue + nominal = NominalRequirement( + dimension.value, + "ap242_pmi", + _source_ids(dimension), + label=label, + ) if not nominal.agrees_with(owner.member.diameter): blocked[dim_index] = ( f"source nominal {dimension.value!r} disagrees with canonical " @@ -659,26 +745,17 @@ def _lower_pattern_nominal_diameters( ) continue requirements = list(owner.member_size_requirements or (None,) * owner.count) - if any( - requirement is not None and requirement.source != "ap242_pmi" - for index in member_indices - if (requirement := requirements[index]) is not None - ): - blocked[dim_index] = "ambiguous diameter ownership: member has an authored aspect" - continue - for index in member_indices: - requirement = requirements[index] - requirements[index] = ( - nominal - if requirement is None - else replace( - requirement, - source_ids=tuple( - dict.fromkeys((*requirement.source_ids, *nominal.source_ids)) - ), - ) + if _pattern_nominal_conflict(requirements, member_indices, nominal): + blocked[dim_index] = ( + "ambiguous diameter ownership: member has a conflicting authored aspect" ) - replacement = replace(owner, member_size_requirements=tuple(requirements)) + continue + replacement = replace( + owner, + member_size_requirements=tuple( + _merged_pattern_requirements(requirements, member_indices, nominal) + ), + ) for key, value in tuple(decorations.items()): if key[0] is owner: del decorations[key] @@ -687,7 +764,13 @@ def _lower_pattern_nominal_diameters( feature_remap(owner, (replacement,), (tuple(range(owner.count)),)) features[owner_index] = replacement consumed.add(dim_index) - if not consumed and not blocked: + if ( + not consumed + and not blocked + and all( + current is original for current, original in zip(features, model.features, strict=True) + ) + ): return model return replace( model, @@ -827,6 +910,45 @@ def _external_diameter_parameter(feature: StepFeature | BossFeature | Rotational ) +def _nominal_diameter_owner(dimension, targets, bbox): + matches = [ + feature for _index, feature in targets if _nominal_owner_matches(dimension, feature, bbox) + ] + if any(isinstance(feature, StepFeature) for feature in matches): + matches = [feature for feature in matches if isinstance(feature, StepFeature)] + elif any(isinstance(feature, RotationalFeature) for feature in matches): + matches = [feature for feature in matches if isinstance(feature, RotationalFeature)] + if not matches: + return "unmatched diameter ownership: no canonical feature matches the source cylinder topology" + if len(matches) != 1: + return ( + "ambiguous diameter ownership: source cylinder topology matches " + f"{len(matches)} canonical features" + ) + return matches[0] + + +def _nominal_source_consumed(owner, dimension) -> bool: + return isinstance(owner, HoleFeature | PatternFeature) or _canonical_nominal_diameter_label( + dimension + ) + + +def _nominal_rebuilt_features(model, consumed, blocked, nominal_conflicts): + rebuilt: list[Feature] = [] + for index, feature in enumerate(model.features): + if index in consumed: + continue + if index in blocked and isinstance(feature, AuthoredDimension): + feature = _block(feature, blocked[index]) + if index in nominal_conflicts: + feature = replace( + feature, rendering_blockers=(*feature.rendering_blockers, blocked[index]) + ) + rebuilt.append(feature) + return rebuilt + + def lower_ap242_nominal_diameters( model: PartModel, *, feature_remap: FeatureRemap | None = None ) -> PartModel: @@ -854,19 +976,7 @@ def lower_ap242_nominal_diameters( dimensions = { index: feature for index, feature in enumerate(model.features) - if isinstance(feature, AuthoredDimension) - and feature.dimension_kind == "diameter" - and feature.source == "ap242_pmi" - and feature.cylindrical_refs - and not any( - value is not None - for value in ( - feature.lower_tol, - feature.upper_tol, - feature.lower_bound, - feature.upper_bound, - ) - ) + if _plain_cylinder_source(feature) } if not dimensions: return _apply_standalone_cylinder_blockers(model) @@ -876,6 +986,7 @@ def lower_ap242_nominal_diameters( tuple[ StepFeature | BossFeature | HoleFeature | PatternFeature | RotationalFeature, tuple, + NominalRequirement, ], ] = {} blocked: dict[int, str] = {} @@ -883,31 +994,19 @@ def lower_ap242_nominal_diameters( for dimension_index, dimension in dimensions.items(): if dimension.lowering_blockers or dimension.rendering_blockers: continue - matches = [ - feature - for _feature_index, feature in targets - if _nominal_owner_matches(dimension, feature, model.bbox) - ] - if any(isinstance(feature, StepFeature) for feature in matches): - matches = [feature for feature in matches if isinstance(feature, StepFeature)] - elif any(isinstance(feature, RotationalFeature) for feature in matches): - matches = [feature for feature in matches if isinstance(feature, RotationalFeature)] - if not matches: - blocked[dimension_index] = ( - "unmatched diameter ownership: no canonical feature matches the source " - "cylinder topology" - ) + owner = _nominal_diameter_owner(dimension, targets, model.bbox) + if isinstance(owner, str): + blocked[dimension_index] = owner continue - if len(matches) != 1: - blocked[dimension_index] = ( - f"ambiguous diameter ownership: source cylinder topology matches " - f"{len(matches)} canonical features" - ) + supported, label = _nominal_label_for_owner(dimension, owner) + if not supported: continue - owner = matches[0] key = _nominal_owner_key(owner) nominal = NominalRequirement( - value=dimension.value, source="ap242_pmi", source_ids=_source_ids(dimension) + value=dimension.value, + source="ap242_pmi", + source_ids=_source_ids(dimension), + label=label, ) parameter = next(p for p in owner.parameters() if p.parameter_id == key[2]) if not nominal.agrees_with(parameter.value): @@ -917,42 +1016,38 @@ def lower_ap242_nominal_diameters( f"{parameter.parameter_id}={parameter.value!r}" ) continue - proposals[dimension_index] = (owner, key) + proposals[dimension_index] = (owner, key, nominal) decorations = dict(model.decorations) consumed: set[int] = set() - for dimension_index, (owner, key) in proposals.items(): + for dimension_index, (owner, key, nominal) in proposals.items(): dimension = dimensions[dimension_index] incoming_ids = _source_ids(dimension) existing = decorations.get(key) if existing is None: - decorations[key] = NominalRequirement( - value=dimension.value, source="ap242_pmi", source_ids=incoming_ids - ) - consumed.add(dimension_index) + decorations[key] = nominal + if _nominal_source_consumed(owner, dimension): + consumed.add(dimension_index) continue if isinstance(existing, NominalRequirement) and existing.agrees_with(dimension.value): + if existing.label != nominal.label: + blocked[dimension_index] = ( + "ambiguous diameter ownership: conflicting authored labels" + ) + continue decorations[key] = replace( existing, source_ids=tuple(dict.fromkeys((*existing.source_ids, *incoming_ids))), + label=existing.label or nominal.label, ) - consumed.add(dimension_index) + if _nominal_source_consumed(owner, dimension): + consumed.add(dimension_index) continue blocked[dimension_index] = ( f"ambiguous diameter ownership: {owner.kind} diameter already has an authored aspect" ) - rebuilt: list[Feature] = [] - for index, feature in enumerate(model.features): - if index in consumed: - continue - if index in blocked and isinstance(feature, AuthoredDimension): - feature = _block(feature, blocked[index]) - if index in nominal_conflicts: - feature = replace( - feature, rendering_blockers=(*feature.rendering_blockers, blocked[index]) - ) - rebuilt.append(feature) + rebuilt = _nominal_rebuilt_features(model, consumed, blocked, nominal_conflicts) return _apply_standalone_cylinder_blockers( replace(model, features=rebuilt, decorations=decorations) ) @@ -985,6 +1080,7 @@ def lower_ap242_nominal_step_lengths(model: PartModel) -> PartModel: and re.fullmatch(r"\s*\d+(?:\.\d+)?\s*", dimension.label) and len(dimension.ref_pts) == 2 and abs(float(dimension.label) - dimension.value) <= 1e-6 + and dimension.label.strip() == _fmt(dimension.value) ): continue matches = [] @@ -1028,6 +1124,74 @@ def lower_ap242_nominal_step_lengths(model: PartModel) -> PartModel: ) +def add_authored_step_positions( + model: PartModel, *, feature_remap: FeatureRemap | None = None +) -> PartModel: + """Give automatic baseline gap fillers their own datum-to-shoulder IR identity.""" + from draftwright.model.planner import _authored_step_baseline, _authored_step_groups + + if model.authored_dimensions is not None or not any( + isinstance(feature, AuthoredDimension) for feature in model.features + ): + return model + features = list(model.features) + profile_groups = _authored_step_groups(model) + baselines: dict[int, tuple[int, float, dict[float, str]] | None] = {} + for group in profile_groups: + baseline = _authored_step_baseline(model, group[0], groups=profile_groups) + baselines.update((id(step), baseline) for step in group) + decorations = dict(model.decorations) + replacements: dict[int, StepFeature] = {} + for index, feature in enumerate(features): + if not isinstance(feature, StepFeature): + continue + baseline = baselines.get(id(feature)) + if baseline is None: + continue + axis, base, covered = baseline + if feature.position_span is not None: + continue + stations = sorted(float(point[axis]) for point in feature.span) + target = stations[1] if abs(base - stations[0]) <= abs(base - stations[1]) else stations[0] + if ( + round(target, 6) in covered + or abs(base - (stations[0] if target == stations[1] else stations[1])) <= 0.01 + ): + continue + if (feature, "nominal_requirement", "step.length") in decorations or any( + key[0] is feature and key[1] == "length" for key in decorations + ): + continue + start = list(feature.span[0]) + end = list(feature.span[1]) + start[axis] = base + end[axis] = target + replacement = replace( + feature, + position_span=((start[0], start[1], start[2]), (end[0], end[1], end[2])), + ) + replacements[id(feature)] = replacement + features[index] = replacement + if feature_remap is not None: + feature_remap(feature, (replacement,), None) + if not replacements: + return model + for key, value in tuple(decorations.items()): + updated = replacements.get(id(key[0])) + if updated is not None: + del decorations[key] + decorations[(updated, *key[1:])] = value + requested = tuple( + replace(request, feature=replacements[id(request.feature)]) + if id(request.feature) in replacements + else request + for request in model.requested_dimensions + ) + return replace( + model, features=features, decorations=decorations, requested_dimensions=requested + ) + + _EXTERNAL_THREAD = re.compile( r"^(?PM(?P\d+(?:\.\d+)?)\s*x\s*" r"(?P\d+(?:\.\d+)?)-(?P[A-Za-z0-9]+)\s+" @@ -2184,4 +2348,7 @@ def lower_ap242_dimensions( ) manufacturing = lower_ap242_manufacturing_requirements(dimensions, feature_remap=feature_remap) chamfers = lower_ap242_chamfer_requirements(manufacturing, feature_remap=feature_remap) - return lower_ap242_document_requirements(lower_ap242_face_finishes(chamfers)) + return add_authored_step_positions( + lower_ap242_document_requirements(lower_ap242_face_finishes(chamfers)), + feature_remap=feature_remap, + ) diff --git a/src/draftwright/reporting.py b/src/draftwright/reporting.py index f2b37faa8..ee1813625 100644 --- a/src/draftwright/reporting.py +++ b/src/draftwright/reporting.py @@ -28,6 +28,97 @@ REPORT_SCHEMA_VERSION = 3 _DECLARED_REPORT_SCHEMA_VERSION = 8 + +def placed_dimension_sources(model, registry) -> list[dict[str, object]]: + """Project settled measurement ownership without guessing from annotation text.""" + from draftwright.model.ir import AuthoredDimension, NominalRequirement, ToleranceDecoration + + if model is None: + raise ReportUnavailableError("dimension source inventory needs a built PartModel") + decorations = model.decorations + rows: list[dict[str, object]] = [] + for name in sorted(registry.names()): + owner = registry.feature_of(name) + identities = registry.measurement_of(name) + seen: set[tuple[int, str]] = set() + for identity in identities: + key = (id(identity.feature), identity.parameter) + if key in seen: + continue + seen.add(key) + feature = identity.feature + parameter = identity.parameter + source_records: list[tuple[str, str]] = [] + + def record(aspect, into=source_records) -> None: + into.extend((aspect.source, source_id) for source_id in aspect.source_ids) + + nominal = decorations.get((feature, "nominal_requirement", parameter)) + if isinstance(nominal, NominalRequirement): + record(nominal) + if parameter == "thread.depth": + thread = getattr(feature, "thread", None) + if getattr(thread, "source_ids", ()) and getattr(thread, "source", None): + record(thread) + parts = parameter.split(".") + role, kind = (parts[0], parts[1]) if len(parts) >= 2 else (parameter, "") + discriminator = parts[2] if len(parts) >= 3 else None + if role == "bore" and kind == "diameter" and discriminator is not None: + member_index = discriminator.removeprefix("member_") + requirements = getattr(feature, "member_size_requirements", ()) + if discriminator.startswith("member_") and member_index.isdecimal(): + index = int(member_index) + if index < len(requirements) and requirements[index] is not None: + record(requirements[index]) + decoration_keys = ( + (feature, kind, role, discriminator) if discriminator is not None else (), + (feature, kind, role), + (feature, kind), + ) + aspect = next( + (decorations[key] for key in decoration_keys if key and key in decorations), None + ) + if isinstance(aspect, ToleranceDecoration): + record(aspect) + source_records = list(dict.fromkeys(source_records)) + origins = {origin for origin, _source_id in source_records} + rows.append( + { + "annotation": name, + "view": registry.view_of(name), + "parameter_id": parameter, + "origin": next(iter(origins)) + if len(origins) == 1 + else "mixed" + if origins + else "planner", + "source_ids": list( + dict.fromkeys(source_id for _, source_id in source_records) + ), + "sources": [ + {"origin": origin, "source_id": source_id} + for origin, source_id in source_records + ], + } + ) + if not identities and isinstance(owner, AuthoredDimension): + rows.append( + { + "annotation": name, + "view": registry.view_of(name), + "parameter_id": None, + "origin": owner.source, + "source_ids": [owner.source_id] if owner.source_id else [], + "sources": ( + [{"origin": owner.source, "source_id": owner.source_id}] + if owner.source_id + else [] + ), + } + ) + return rows + + _LAYOUT_REMEDIES = ( "page", "scale", @@ -2871,6 +2962,7 @@ def write_json_document(report: Mapping[str, object], path: str | PathLike[str]) # made to no one. "json_value", "producer", + "placed_dimension_sources", "project_occurrences", "project_feature_occurrence_ids", "validate_report_inputs", diff --git a/src/draftwright/sheet.py b/src/draftwright/sheet.py index 92824e033..d111963a4 100644 --- a/src/draftwright/sheet.py +++ b/src/draftwright/sheet.py @@ -238,9 +238,9 @@ def _tolerance_decoration(lo, hi, *, source, source_ids, limit_bounds=None): ) -def _nominal_requirement(value, *, source, source_ids): +def _nominal_requirement(value, *, source, source_ids, label=None): """Build the provenance-only aspect used by generated imported-PMI scripts.""" - return NominalRequirement(value=value, source=source, source_ids=source_ids) + return NominalRequirement(value=value, source=source, source_ids=source_ids, label=label) _NOMINAL_REQUIREMENT_PARAMETERS = { @@ -394,14 +394,16 @@ def fit(self, code: str, *, show: str = "class") -> _Hole: ) return self - def requirement(self, value: float, *, source: str, source_ids: tuple[str, ...]) -> _Hole: + def requirement( + self, value: float, *, source: str, source_ids: tuple[str, ...], label: str | None = None + ) -> _Hole: """Claim this existing bore diameter for external semantic source identities. - This changes no label: the canonical hole callout already prints the nominal value. Generated AP242 scripts use it to retain ownership without adding a duplicate dim. + An optional label preserves the source's bore wording. """ self._sheet._tolerances[(self._token, "nominal_requirement", "bore.diameter")] = ( - _nominal_requirement(value, source=source, source_ids=source_ids) + _nominal_requirement(value, source=source, source_ids=source_ids, label=label) ) return self @@ -558,12 +560,13 @@ def requirement( on: str | None = None, source: str, source_ids: tuple[str, ...], + label: str | None = None, ) -> _Dim: """Claim a canonical nominal parameter for external source identities.""" target = on or self._kind parameter = _requirement_parameter(self._sheet._features[self._i], target) self._sheet._tolerances[(self._token, "nominal_requirement", parameter.parameter_id)] = ( - _nominal_requirement(value, source=source, source_ids=source_ids) + _nominal_requirement(value, source=source, source_ids=source_ids, label=label) ) return self @@ -811,11 +814,12 @@ def requirement( on: str, source: str, source_ids: tuple[str, ...], + label: str | None = None, ) -> _Params: """Claim the feature's canonical diameter for external semantic source identities.""" parameter = _requirement_parameter(self._sheet._features[self._i], on) self._sheet._tolerances[(self._token, "nominal_requirement", parameter.parameter_id)] = ( - _nominal_requirement(value, source=source, source_ids=source_ids) + _nominal_requirement(value, source=source, source_ids=source_ids, label=label) ) return self diff --git a/src/draftwright/sheet_emit.py b/src/draftwright/sheet_emit.py index 70cbaf540..35f6b03f4 100644 --- a/src/draftwright/sheet_emit.py +++ b/src/draftwright/sheet_emit.py @@ -1006,6 +1006,33 @@ def detected_profile_token() -> str: return profile_group_by_feature +def _nominal_requirement_calls( + nominal: object, + step_length_nominal: object, + nominal_parameter: str | None, + kind: str, +) -> str: + calls = "" + if isinstance(nominal, NominalRequirement): + provenance = f"source={nominal.source!r}, source_ids={nominal.source_ids!r}" + if nominal.label is not None: + provenance += f", label={nominal.label!r}" + on = f", on={nominal_parameter!r}" if kind in ("step", "pattern", "rotational") else "" + calls += f".requirement({_authored_n(nominal.value)}{on}, {provenance})" + if isinstance(step_length_nominal, NominalRequirement): + label = ( + f", label={step_length_nominal.label!r}" + if step_length_nominal.label is not None + else "" + ) + calls += ( + f".requirement({_authored_n(step_length_nominal.value)}, " + f"on='step.length', source={step_length_nominal.source!r}, " + f"source_ids={step_length_nominal.source_ids!r}{label})" + ) + return calls + + def _feature_block( features, part_envelope=None, @@ -1094,7 +1121,9 @@ def _feature_block( # Keep the numeric declaration for exact-owned parameters. object_ref = ( None - if exact_parameter is not None or exact_step_length + if exact_parameter is not None + or exact_step_length + or (f.kind == "step" and f.position_span is not None) else (object_refs or {}).get(id(f)) ) line = _feature_line( @@ -1208,17 +1237,9 @@ def _feature_block( provenance += f", limit_bounds={tolerance.limit_bounds!r}" line += f".tolerance({args}, on={parameter.parameter_id!r}{provenance})" - if isinstance(nominal, NominalRequirement): - provenance = f"source={nominal.source!r}, source_ids={nominal.source_ids!r}" - on_target = nominal_parameter - on = f", on={on_target!r}" if f.kind in ("step", "pattern", "rotational") else "" - line += f".requirement({_authored_n(nominal.value)}{on}, {provenance})" - if isinstance(step_length_nominal, NominalRequirement): - line += ( - f".requirement({_authored_n(step_length_nominal.value)}, " - f"on='step.length', source={step_length_nominal.source!r}, " - f"source_ids={step_length_nominal.source_ids!r})" - ) + line += _nominal_requirement_calls( + nominal, step_length_nominal, nominal_parameter, f.kind + ) name = _binding(f, line, counts) if name is not None: metadata = (declaration_metadata or {}).get(id(f)) diff --git a/src/draftwright/sheet_feature_lines.py b/src/draftwright/sheet_feature_lines.py index 824be5734..6f9a8a3dd 100644 --- a/src/draftwright/sheet_feature_lines.py +++ b/src/draftwright/sheet_feature_lines.py @@ -704,8 +704,14 @@ def _stock_feature_line( ) # external thread (#859) knurl = f", knurl={_knurl_arg(f.knurl)}" if getattr(f, "knurl", None) else "" group = f", profile_group={profile_group!r}" if profile_group is not None else "" + position = ( + f", position_span=({_authored_pt(f.position_span[0])}, " + f"{_authored_pt(f.position_span[1])})" + if f.position_span is not None + else "" + ) if object_ref is not None: - return f"sheet.step({object_ref}{thr}{knurl}{group})" + return f"sheet.step({object_ref}{thr}{knurl}{group}{position})" return ( "sheet.step(" f"diameter={_parameter_n(f.diameter, 'step.diameter', exact_parameter)}, " @@ -713,7 +719,8 @@ def _stock_feature_line( # Public shoulder stations are at 0.001 mm, so an odd-thousandth span has a # half-thousandth midpoint. Preserve that coupled fact: independently rounding # ``length`` and ``at`` would reconstruct both endpoints 0.0005 mm away. - f'at={_authored_pt(f.frame.origin)}, axis="{f.frame.axis}"{thr}{knurl}{group})' + f'at={_authored_pt(f.frame.origin)}, axis="{f.frame.axis}"' + f"{thr}{knurl}{group}{position})" ) raise AssertionError(f"unexpected stock feature kind: {k}") diff --git a/tests/_complexity_baseline.json b/tests/_complexity_baseline.json index f72dd96b4..3d3892344 100644 --- a/tests/_complexity_baseline.json +++ b/tests/_complexity_baseline.json @@ -107,7 +107,6 @@ "model/planner.py:plan_locations": 17, "model/pmi_lowering.py:lower_ap242_hole_tolerances": 25, "model/pmi_lowering.py:lower_ap242_manufacturing_requirements": 19, - "model/pmi_lowering.py:lower_ap242_nominal_diameters": 16, "oriented_slot_contract.py:oriented_slot_provider_key": 19, "pdf_text.py:pdf_text_runs": 27, "pmi.py:_angular_reference_from_shapes": 18, @@ -126,7 +125,7 @@ "section_recess_contract.py:section_recess_fields": 21, "section_recess_contract.py:section_recess_pocket_fields": 21, "sheet_emit.py:_adopted_view_block": 26, - "sheet_emit.py:_feature_block": 29, + "sheet_emit.py:_feature_block": 27, "sheet_emit.py:_feature_line": 18, "sheet_emit.py:_model_constructor_imports": 16, "sheet_emit.py:_short_label": 25, diff --git a/tests/_function_length_baseline.json b/tests/_function_length_baseline.json index 27a64227e..2b1495c32 100644 --- a/tests/_function_length_baseline.json +++ b/tests/_function_length_baseline.json @@ -43,7 +43,7 @@ "reporting.py:_raw_report_assessment": 218, "reporting.py:_requirements": 212, "reporting.py:document_report": 273, - "sheet_emit.py:_feature_block": 233, + "sheet_emit.py:_feature_block": 227, "sheet_emit.py:emit_sheet_script": 287 } } diff --git a/tests/test_authored_pmi_precedence.py b/tests/test_authored_pmi_precedence.py new file mode 100644 index 000000000..ff4c02467 --- /dev/null +++ b/tests/test_authored_pmi_precedence.py @@ -0,0 +1,786 @@ +"""Imported lengths cover automatic stations without changing a PMI-free chain.""" + +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from build123d import Box, Cylinder, Pos + +from draftwright import build_drawing +from draftwright.linting.coverage import _authored_axial_witness_on_profile +from draftwright.model.compiled import compile_dimensions +from draftwright.model.ir import ( + AuthoredDimension, + CylindricalReference, + Datum, + EnvelopeFeature, + Frame, + HoleFeature, + NominalRequirement, + PartModel, + PatternFeature, + RotationalFeature, + StepFeature, + ToleranceDecoration, +) +from draftwright.model.planner import DimensionId, plan_dimensions +from draftwright.model.pmi_lowering import ( + add_authored_step_positions, + lower_ap242_nominal_diameters, + lower_ap242_nominal_step_lengths, +) +from draftwright.registry import AnnotationRegistry +from draftwright.reporting import ReportUnavailableError, placed_dimension_sources +from draftwright.sheet_emit import emit_sheet_script + + +def _step(start: float, end: float, diameter: float) -> StepFeature: + return StepFeature( + Frame(((start + end) / 2, 0, 0), "x"), + end - start, + diameter, + ((start, 0, 0), (end, 0, 0)), + ) + + +def _source(start: float, end: float, source_id: str) -> AuthoredDimension: + return AuthoredDimension( + Frame(((start + end) / 2, 0, 0), "x"), + "linear", + end - start, + f"{end - start:g}", + "X", + ref_pts=((start, 0, 0), (end, 0, 0)), + source_id=source_id, + ) + + +def _model(*sources: AuthoredDimension) -> PartModel: + bbox = (Pos(26, 0, 0) * Box(52, 30, 30)).bounding_box() + envelope = EnvelopeFeature(Frame((26, 0, 0), "x"), 52, 30, 30, (0, -15, -15), (52, 15, 15)) + return PartModel( + bbox, + "x", + [ + envelope, + _step(0, 15, 30), + _step(15, 40, 20), + _step(40, 52, 12), + *sources, + ], + ) + + +def _step_lengths(model: PartModel) -> list[tuple[float, tuple | None, bool]]: + return [ + (dimension.param.value, dimension.param.span, dimension.suppressed) + for group in plan_dimensions(model) + if isinstance(group.feature, StepFeature) + for dimension in group.dims + if dimension.param.parameter_id == "step.length" + ] + + +def test_imported_baseline_covers_its_station_and_planner_fills_from_same_end(): + exact = _source(0, 15, "dimension:15") + baseline = _source(0, 40, "dimension:40") + model = add_authored_step_positions(lower_ap242_nominal_step_lengths(_model(exact, baseline))) + + # The exact first source has a canonical owner; the 0→40 source remains raw PMI. + assert [f.source_id for f in model.features if isinstance(f, AuthoredDimension)] == [ + "dimension:40" + ] + assert _step_lengths(model) == [ + (15, ((0, 0, 0), (15, 0, 0)), False), + (25, ((15, 0, 0), (40, 0, 0)), True), + (12, ((40, 0, 0), (52, 0, 0)), True), + ] + compiled = compile_dimensions(model) + assert [ + (dimension.parameter_id, dimension.value, dimension.span) + for group in compiled.of_kind("step") + for dimension in group.dims + if dimension.kind == "length" + ] == [ + ("step.length", 15, ((0, 0, 0), (15, 0, 0))), + ("step_position.length", 52, ((0, 0, 0), (52, 0, 0))), + ] + assert compiled.of_kind("step")[-1].dim(kind="length").id.feature.length == 12 + + +def test_single_authored_baseline_makes_uncovered_stations_baselines(): + model = add_authored_step_positions(_model(_source(0, 40, "dimension:40"))) + assert _step_lengths(model) == [ + (15, ((0, 0, 0), (15, 0, 0)), False), + (25, ((15, 0, 0), (40, 0, 0)), True), + (12, ((40, 0, 0), (52, 0, 0)), True), + ] + position = next( + dimension + for group in plan_dimensions(model) + for dimension in group.dims + if dimension.param.parameter_id == "step_position.length" + ) + assert (position.param.value, position.param.span, position.suppressed) == ( + 52, + ((0, 0, 0), (52, 0, 0)), + False, + ) + + +def test_one_toleranced_step_source_covers_only_that_chain_segment(): + source = replace(_source(0, 15, "dimension:15"), upper_tol=0.1, lower_tol=-0.1) + assert _step_lengths(_model(source)) == [ + (15, ((0, 0, 0), (15, 0, 0)), True), + (25, ((15, 0, 0), (40, 0, 0)), False), + (12, ((40, 0, 0), (52, 0, 0)), False), + ] + + +def test_offset_parallel_face_witnesses_cover_the_same_axial_step(): + source = replace( + _source(0, 15, "dimension:offset-15"), + ref_pts=((0, -10, 0), (15, 10, 0)), + ) + assert [(value, withheld) for value, _span, withheld in _step_lengths(_model(source))] == [ + (15, True), + (25, False), + (12, False), + ] + + +def test_offset_face_source_still_covers_its_step_beside_another_body(): + source = replace(_source(0, 15, "dimension:first"), ref_pts=((0, -10, 0), (15, 10, 0))) + model = _model(source) + model.features.extend( + replace( + _step(start, end, diameter), + frame=Frame(((start + end) / 2, 50, 0), "x"), + span=((start, 50, 0), (end, 50, 0)), + profile_group="second-body", + ) + for start, end, diameter in ((0, 15, 30), (15, 40, 20), (40, 52, 12)) + ) + assert _step_lengths(model)[0] == (15, ((0, 0, 0), (15, 0, 0)), True) + + +def test_source_precision_is_kept_when_plain_label_differs_from_planner(): + source = replace(_source(0, 15, "dimension:15.0"), label="15.0") + model = lower_ap242_nominal_step_lengths(_model(source)) + assert any( + isinstance(feature, AuthoredDimension) + and feature.source_id == source.source_id + and feature.label == source.label + for feature in model.features + ) + assert _step_lengths(model)[0][2] + + +def test_noncanonical_diameter_label_stays_authored_and_covers_step_diameter(): + step = _step(0, 15, 30) + source = AuthoredDimension( + Frame((7.5, 0, 0), "x"), + "diameter", + 30, + "ø30.0", + "X", + ref_pts=((7.5, 0, 0),), + source_id="dimension:od-precision", + cylindrical_refs=(CylindricalReference((0, 0, 0), (1, 0, 0), 15, (0, 15), "external"),), + ) + model = lower_ap242_nominal_diameters( + PartModel(Box(15, 30, 30).bounding_box(), "x", [step, source]) + ) + assert source in model.features + diameter = next( + dimension + for group in plan_dimensions(model) + if group.feature is step + for dimension in group.dims + if dimension.param.parameter_id == "step.diameter" + ) + assert diameter.suppressed + part = Pos(7.5, 0, 0) * Cylinder(15, 15, rotation=(0, 90, 0)) + drawing = build_drawing( + part, model=model, pmi="annotate", page="A3", scale=1, detail_view=False, repair=False + ) + diameter_labels = [ + drawing.registry.named(name).label + for name in drawing.registry.names() + if str(getattr(drawing.registry.named(name), "label", "")).startswith("ø30") + ] + assert diameter_labels == ["ø30.0"] + + +def test_step_diameter_source_does_not_cover_another_bodys_rotational_od(): + source = AuthoredDimension( + Frame((7.5, 0, 0), "x"), + "diameter", + 30, + "ø30.0", + "X", + ref_pts=((7.5, 0, 0),), + source_id="dimension:first-body", + cylindrical_refs=(CylindricalReference((0, 0, 0), (1, 0, 0), 15, (0, 15), "external"),), + ) + distant = RotationalFeature(Frame((107.5, 0, 0), "x"), od=30) + model = lower_ap242_nominal_diameters( + PartModel(Box(120, 30, 30).bounding_box(), "x", [_step(0, 15, 30), distant, source]) + ) + diameter = next( + dimension + for group in plan_dimensions(model) + if group.feature is distant + for dimension in group.dims + if dimension.param.parameter_id == "od.diameter" + ) + assert not diameter.suppressed + + +def test_step_diameter_source_covers_whole_bodys_rotational_od(): + source = AuthoredDimension( + Frame((7.5, 0, 0), "x"), + "diameter", + 30, + "ø30.0", + "X", + ref_pts=((7.5, 0, 0),), + source_id="dimension:body-od", + cylindrical_refs=(CylindricalReference((0, 0, 0), (1, 0, 0), 15, (0, 15), "external"),), + ) + rotational = RotationalFeature(Frame((26, 0, 0), "x"), od=30) + model = _model(source) + model.features.append(rotational) + lowered = lower_ap242_nominal_diameters(model) + diameter = next( + dimension + for group in plan_dimensions(lowered) + if group.feature is rotational + for dimension in group.dims + if dimension.param.parameter_id == "od.diameter" + ) + assert diameter.suppressed + assert diameter.reason == "authored PMI dimension dimension:body-od covers this diameter" + + +def test_noncanonical_member_diameter_heads_its_own_callout(): + members = ((0, -5, 0), (0, 5, 0)) + hole = HoleFeature(Frame(members[0], "x"), 4, depth=20, through=True) + pattern = PatternFeature( + Frame((0, 0, 0), "x"), + "linear", + 2, + hole, + members=members, + pitch=10, + direction=(0, 1, 0), + ) + source = AuthoredDimension( + Frame(members[0], "x"), + "diameter", + 4, + "ø4 H7", + "X", + ref_pts=(members[0],), + source_id="dimension:fit", + cylindrical_refs=(CylindricalReference(members[0], (1, 0, 0), 2, (-10, 10), "internal"),), + ) + model = lower_ap242_nominal_diameters( + PartModel(Box(20, 20, 20).bounding_box(), "x", [pattern, source]) + ) + assert not any(isinstance(feature, AuthoredDimension) for feature in model.features) + owned = next(feature for feature in model.features if isinstance(feature, PatternFeature)) + assert owned.member_size_requirements[0].label == "ø4 H7" + group = next( + group for group in plan_dimensions(model) if isinstance(group.feature, PatternFeature) + ) + member_diameters = [ + dimension + for dimension in group.dims + if dimension.param.parameter_id.startswith("bore.diameter.member_") + ] + assert [dimension.suppressed for dimension in member_diameters] == [False, False] + from draftwright.model.callout import bore_callout_value, hole_callout_batches + + batches = hole_callout_batches(plan_dimensions(model)) + assert [bore_callout_value(batch.spec) for batch in batches] == ["4 H7", "4"] + part = ( + Box(20, 20, 20) + - Pos(0, -5, 0) * Cylinder(2, 20, rotation=(0, 90, 0)) + - Pos(0, 5, 0) * Cylinder(2, 20, rotation=(0, 90, 0)) + ) + drawing = build_drawing( + part, model=model, pmi="annotate", page="A3", scale=1, detail_view=False, repair=False + ) + assert sorted( + drawing.registry.named(name).label + for name in drawing.registry.names() + if name.startswith("hc_") + ) == ["⌀4 H7 THRU", "⌀4 THRU"] + + +def test_conflicting_member_labels_do_not_claim_the_same_callout(): + members = ((0, -5, 0), (0, 5, 0)) + hole = HoleFeature(Frame(members[0], "x"), 4, depth=20, through=True) + pattern = PatternFeature( + Frame((0, 0, 0), "x"), + "linear", + 2, + hole, + members=members, + pitch=10, + direction=(0, 1, 0), + ) + refs = (CylindricalReference(members[0], (1, 0, 0), 2, (-10, 10), "internal"),) + sources = [ + AuthoredDimension( + Frame(members[0], "x"), + "diameter", + 4, + label, + "X", + ref_pts=(members[0],), + source_id=f"dimension:{label}", + cylindrical_refs=refs, + ) + for label in ("ø4 H7", "ø4 G7") + ] + model = lower_ap242_nominal_diameters( + PartModel(Box(20, 20, 20).bounding_box(), "x", [pattern, *sources]) + ) + owned = next(feature for feature in model.features if isinstance(feature, PatternFeature)) + assert owned.member_size_requirements[0].label == "ø4 H7" + (unclaimed,) = [ + feature for feature in model.features if isinstance(feature, AuthoredDimension) + ] + assert unclaimed.source_id == "dimension:ø4 G7" + assert any("conflicting authored aspect" in reason for reason in unclaimed.lowering_blockers) + + +def test_distinct_hole_sources_keep_their_own_labels(): + members = ((0, -5, 0), (0, 5, 0)) + holes = [HoleFeature(Frame(point, "x"), 4, depth=20, through=True) for point in members] + sources = [ + AuthoredDimension( + Frame(point, "x"), + "diameter", + 4, + label, + "X", + ref_pts=(point,), + source_id=f"dimension:{index}", + cylindrical_refs=(CylindricalReference(point, (1, 0, 0), 2, (-10, 10), "internal"),), + ) + for index, (point, label) in enumerate(zip(members, ("ø4 H7", "ø4 G7"), strict=True)) + ] + model = lower_ap242_nominal_diameters( + PartModel(Box(20, 20, 20).bounding_box(), "x", [*holes, *sources]) + ) + assert [ + model.decorations[(hole, "nominal_requirement", "bore.diameter")] for hole in holes + ] == [ + NominalRequirement(4, "ap242_pmi", ("dimension:0",), "ø4 H7"), + NominalRequirement(4, "ap242_pmi", ("dimension:1",), "ø4 G7"), + ] + + +def test_nominal_requirement_refuses_a_label_that_states_another_diameter(): + with pytest.raises(ValueError, match="label must agree"): + NominalRequirement(4, "ap242_pmi", ("dimension:wrong",), "ø5 H7") + with pytest.raises(ValueError, match="label must agree"): + NominalRequirement(4, "ap242_pmi", ("dimension:compound",), "ø4 THRU") + + +def test_authored_through_bore_label_folds_into_one_matching_callout(): + point = (0, 0, 0) + hole = HoleFeature(Frame(point, "x"), 4, depth=20, through=True) + source = AuthoredDimension( + Frame(point, "x"), + "diameter", + 4, + "ø4 THRU", + "X", + ref_pts=(point,), + source_id="dimension:through", + cylindrical_refs=(CylindricalReference(point, (1, 0, 0), 2, (-10, 10), "internal"),), + ) + part = Box(20, 20, 20) - Cylinder(2, 20, rotation=(0, 90, 0)) + model = lower_ap242_nominal_diameters(PartModel(part.bounding_box(), "x", [hole, source])) + drawing = build_drawing( + part, model=model, pmi="annotate", page="A3", scale=1, detail_view=False, repair=False + ) + labels = [ + drawing.registry.named(name).label + for name in drawing.registry.names() + if name.startswith(("hc_", "pmi_d_")) + ] + assert labels == ["⌀4 THRU"] + + +def test_ambiguous_identical_step_spans_are_not_both_claimed_by_one_source(): + first = replace(_step(0, 15, 30), profile_group="body-a") + second = replace(_step(0, 15, 30), profile_group="body-b") + model = _model(_source(0, 15, "dimension:one")) + model.features[1:3] = [first, second] + assert [ + dimension.suppressed + for group in plan_dimensions(model) + if group.feature is first or group.feature is second + for dimension in group.dims + if dimension.param.parameter_id == "step.length" + ] == [False, False] + + +def test_authored_chain_does_not_get_misread_as_a_baseline(): + first = replace(_source(0, 15, "dimension:15"), upper_tol=0.1, lower_tol=-0.1) + second = replace(_source(15, 40, "dimension:25"), upper_tol=0.1, lower_tol=-0.1) + assert [ + (value, withheld) for value, _span, withheld in _step_lengths(_model(first, second)) + ] == [ + (15, True), + (25, True), + (12, False), + ] + + +def test_touching_distinct_profiles_do_not_share_an_authored_baseline(): + model = _model(_source(0, 40, "dimension:40")) + model.features[2] = replace(model.features[2], profile_group="body-b") + separated = add_authored_step_positions(model) + assert not any( + step.position_span is not None + for step in separated.features + if isinstance(step, StepFeature) + ) + + +def test_second_parallel_body_does_not_disable_first_bodys_baseline(): + model = _model(_source(0, 40, "dimension:body-a")) + siblings = [ + replace( + _step(start, end, diameter), + frame=Frame(((start + end) / 2, 50, 0), "x"), + span=((start, 50, 0), (end, 50, 0)), + profile_group="body-b", + ) + for start, end, diameter in ((0, 15, 30), (15, 40, 20), (40, 52, 12)) + ] + model.features.extend(siblings) + prepared = add_authored_step_positions(model) + assert any( + step.position_span == ((0, 0, 0), (52, 0, 0)) + for step in prepared.features + if isinstance(step, StepFeature) + ) + assert all(step.position_span is None for step in prepared.features if step in siblings) + + +def test_disconnected_coaxial_body_does_not_disable_first_bodys_baseline(): + model = _model(_source(0, 40, "dimension:first-run")) + distant = [ + _step(start, end, diameter) + for start, end, diameter in ((100, 115, 30), (115, 140, 20), (140, 152, 12)) + ] + model.features.extend(distant) + prepared = add_authored_step_positions(model) + assert any( + step.position_span == ((0, 0, 0), (52, 0, 0)) + for step in prepared.features + if isinstance(step, StepFeature) + ) + assert all(step.position_span is None for step in prepared.features if step in distant) + + +def test_one_authored_overall_does_not_leave_a_redundant_complete_chain(): + prepared = add_authored_step_positions(_model(_source(0, 52, "dimension:overall"))) + plan = compile_dimensions(prepared) + approved = [ + (dimension.parameter_id, dimension.value) + for group in plan.of_kind("step") + for dimension in group.dims + if dimension.kind == "length" + ] + assert approved == [("step.length", 15), ("step_position.length", 40)] + + +def test_no_pmi_keeps_the_original_chain(): + assert [(value, withheld) for value, _span, withheld in _step_lengths(_model())] == [ + (15, False), + (25, False), + (12, False), + ] + + +def test_unproved_or_off_axis_source_does_not_cover_a_step(): + source = _source(0, 40, "dimension:40") + for other in ( + replace(source, dominant_axis="Y"), + replace(source, ref_pts=((0, 0, 0), (39, 0, 0))), + replace(source, ref_pts=((0, 100, 0), (40, 100, 0))), + replace(source, rendering_blockers=("unproved",)), + ): + assert [(value, withheld) for value, _span, withheld in _step_lengths(_model(other))] == [ + (15, False), + (25, False), + (12, False), + ] + + +def test_axial_lint_rejects_a_transverse_source_with_same_end_stations(): + source = replace( + _source(0, 15, "dimension:transverse"), + dominant_axis="Y", + value=10, + label="10", + ref_pts=((0, -5, 0), (15, 5, 0)), + ) + drawing = SimpleNamespace(registry=SimpleNamespace(feature_of=lambda name: source)) + profile = SimpleNamespace(axis="x", steps=[SimpleNamespace(lo=0, hi=15, diameter=30)]) + assert not _authored_axial_witness_on_profile(drawing, "source", profile, (0, 0, 0), 0.6) + + +def test_exact_imported_overall_extent_replaces_automatic_envelope_width(): + source = replace( + _source(0, 52, "dimension:overall"), + ref_pts=((0, -15, -15), (52, -15, -15)), + ) + model = _model(source) + width = next( + dimension + for group in plan_dimensions(model) + for dimension in group.dims + if dimension.param.parameter_id == "width.length" + ) + assert width.suppressed + assert width.reason == "authored PMI dimension dimension:overall covers this measurement" + + +def test_offset_face_witnesses_replace_automatic_envelope_width(): + bbox = (Pos(10, 5, 2.5) * Box(20, 10, 5)).bounding_box() + envelope = EnvelopeFeature(Frame((10, 5, 2.5), "x"), 20, 5, 10, (0, 0, 0), (20, 10, 5)) + source = AuthoredDimension( + Frame((10, 5, 2.5), "x"), + "linear", + 20, + "20", + "X", + ref_pts=((0, 5, 2.5), (20, 5, 2.5)), + source_id="dimension:face-width", + ) + plan = plan_dimensions(PartModel(bbox, "x", [envelope, source])) + width = next( + dimension + for group in plan + if group.feature is envelope + for dimension in group.dims + if dimension.param.parameter_id == "width.length" + ) + assert width.suppressed + assert width.reason == "authored PMI dimension dimension:face-width covers this extent" + + +def test_authored_overall_baseline_does_not_restore_a_duplicate_envelope_width(): + source = _source(0, 52, "dimension:overall") + model = _model(source) + width = next( + dimension + for group in plan_dimensions(model) + for dimension in group.dims + if dimension.param.parameter_id == "width.length" + ) + assert width.suppressed + assert width.reason == "authored PMI dimension dimension:overall covers this extent" + + +def test_authored_z_height_does_not_reappear_as_an_overall_ladder(): + bbox = (Pos(5, 5, 5) * Box(10, 10, 10)).bounding_box() + envelope = EnvelopeFeature(Frame((5, 5, 5), "z"), 10, 10, 10, (0, 0, 0), (10, 10, 10)) + source = AuthoredDimension( + Frame((10, 0, 5), "z"), + "linear", + 10, + "10", + "Z", + ref_pts=((10, 0, 0), (10, 0, 10)), + source_id="dimension:height", + ) + model = PartModel(bbox, "z", [envelope, source]) + plan = compile_dimensions(model) + assert plan.ladder("overall_height") is None + assert any( + omission.parameter_id == "height.length" and "dimension:height" in omission.reason + for omission in plan.diagnostics + ) + + +def test_authored_hole_x_location_covers_only_the_x_component(): + bbox = (Pos(20, 15, 2.5) * Box(40, 30, 5)).bounding_box() + hole = HoleFeature(Frame((10, 5, 2), "z"), 4, depth=None, through=True) + source = AuthoredDimension( + Frame((5, 5, 2), "x"), + "linear", + 10, + "10", + "X", + ref_pts=((0, 5, 2), (10, 5, 2)), + source_id="dimension:hole-x", + ) + model = PartModel(bbox, "z", [hole, source], datums=[Datum("datum_xy", "point", (0, 0, 0))]) + plan = compile_dimensions(model) + hole_locations = [location for location in plan.locations if location.id.feature is hole] + assert [(location.discriminator, location.value) for location in hole_locations] == [("y", 5)] + assert any( + omission.feature is hole + and omission.parameter_id.endswith(".x") + and "dimension:hole-x" in omission.reason + for omission in plan.diagnostics + ) + overlapping_hole = replace(hole, diameter=6) + ambiguous = compile_dimensions(replace(model, features=[hole, overlapping_hole, source])) + assert ( + len([location for location in ambiguous.locations if location.discriminator == "x"]) == 2 + ) + + +def test_pattern_member_provenance_is_per_measurement(): + hole = HoleFeature(Frame((0, 0, 0), "z"), 4, depth=None, through=True) + pattern = PatternFeature( + Frame((0, 5, 0), "z"), + "linear", + 2, + hole, + members=((0, 0, 0), (0, 10, 0)), + pitch=10, + direction=(0, 1, 0), + member_size_requirements=( + NominalRequirement(4, "ap242_pmi", ("dimension:first-member",)), + None, + ), + ) + model = PartModel(Box(20, 20, 5).bounding_box(), "z", [pattern]) + registry = AnnotationRegistry() + registry.add( + object(), + "hole_terms", + "plan", + feature=pattern, + measurement=( + DimensionId(pattern, "bore.diameter.member_0"), + DimensionId(pattern, "bore.diameter.member_1"), + ), + ) + rows = [ + row + for row in placed_dimension_sources(model, registry) + if row["annotation"] == "hole_terms" + ] + assert [(row["parameter_id"], row["source_ids"]) for row in rows] == [ + ("bore.diameter.member_0", ["dimension:first-member"]), + ("bore.diameter.member_1", []), + ] + + +def test_manual_source_is_not_misreported_as_ap242_and_missing_model_refuses(): + step = _step(0, 15, 30) + model = PartModel( + Box(15, 30, 30).bounding_box(), + "x", + [step], + decorations={ + (step, "length", "step"): ToleranceDecoration(0.1, "authored", ("manual-1",)), + (step, "length"): ToleranceDecoration(0.2, "ap242_pmi", ("shadowed",)), + }, + ) + registry = AnnotationRegistry() + registry.add( + object(), + "step_length", + "front", + feature=step, + measurement=DimensionId(step, "step.length"), + ) + (row,) = placed_dimension_sources(model, registry) + assert row["origin"] == "authored" + assert row["sources"] == [{"origin": "authored", "source_id": "manual-1"}] + with pytest.raises(ReportUnavailableError, match="needs a built PartModel"): + placed_dimension_sources(None, registry) + + +def test_finished_turned_drawing_has_one_plain_mark_per_baseline_station(): + part = ( + Pos(7.5, 0, 0) * Cylinder(15, 15, rotation=(0, 90, 0)) + + Pos(27.5, 0, 0) * Cylinder(10, 25, rotation=(0, 90, 0)) + + Pos(46, 0, 0) * Cylinder(6, 12, rotation=(0, 90, 0)) + ) + model = add_authored_step_positions( + lower_ap242_nominal_step_lengths( + _model(_source(0, 15, "dimension:15"), _source(0, 40, "dimension:40")) + ) + ) + drawing = build_drawing( + part, model=model, pmi="annotate", page="A3", scale=1, detail_view=False, repair=False + ) + labels = [ + drawing.registry.named(name).label + for name in drawing.registry.names() + if name.startswith(("m_steplen", "pmi_x_")) + ] + assert sorted(labels) == ["15", "40", "52"] + assert not [issue for issue in drawing.lint() if issue.code == "axial_length_missing"] + sources = { + row["annotation"]: row + for row in drawing.dimension_sources() + if row["annotation"].startswith(("m_steplen", "pmi_x_")) + } + assert { + (row["parameter_id"], row["origin"], tuple(row["source_ids"])) for row in sources.values() + } == { + ("step.length", "ap242_pmi", ("dimension:15",)), + (None, "ap242_pmi", ("dimension:40",)), + ("step_position.length", "planner", ()), + } + + +def test_direct_part_model_with_imported_pmi_gets_baseline_gap_preparation(): + part = ( + Pos(7.5, 0, 0) * Cylinder(15, 15, rotation=(0, 90, 0)) + + Pos(27.5, 0, 0) * Cylinder(10, 25, rotation=(0, 90, 0)) + + Pos(46, 0, 0) * Cylinder(6, 12, rotation=(0, 90, 0)) + ) + drawing = build_drawing( + part, + model=_model(_source(0, 40, "dimension:40")), + pmi="annotate", + page="A3", + scale=1, + detail_view=False, + repair=False, + ) + assert any( + step.position_span == ((0, 0, 0), (52, 0, 0)) + for step in drawing.model().features + if isinstance(step, StepFeature) + ) + + +def test_baseline_gap_replays_with_a_distinct_step_position_identity(): + model = add_authored_step_positions(_model(_source(0, 40, "dimension:40"))) + source = emit_sheet_script( + model, + "from build123d import Box, Pos\npart = Pos(26, 0, 0) * Box(52, 30, 30)", + "baseline", + title="Baseline", + number="B-1", + formats=(), + ) + assert "position_span=((0, 0, 0), (52, 0, 0))" in source + assert 'sheet.dimension(step3, "step_position.length")' in source + namespace = {} + exec(compile(source.split("# ── Build")[0], "", "exec"), namespace) + replayed = namespace["sheet"].model() + position = next( + step.position_span + for step in replayed.features + if isinstance(step, StepFeature) and step.position_span is not None + ) + assert position == ((0, 0, 0), (52, 0, 0)) From 53d7f41d031388b2eb0143747d70d4edc6637395 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Mon, 5 Oct 2026 09:07:14 +0100 Subject: [PATCH 2/3] Keep report-only PMI out of dimension precedence --- src/draftwright/analysis.py | 20 ++++++- src/draftwright/builder.py | 9 +++ src/draftwright/model/compiled.py | 8 ++- src/draftwright/model/ir.py | 6 ++ src/draftwright/model/ir_foundation.py | 2 + src/draftwright/model/planner.py | 41 +++++++++++-- src/draftwright/model/pmi_lowering.py | 11 +++- tests/_tier_manifest.py | 1 + tests/test_authored_pmi_precedence.py | 82 +++++++++++++++++++++++++- 9 files changed, 170 insertions(+), 10 deletions(-) diff --git a/src/draftwright/analysis.py b/src/draftwright/analysis.py index b68d21788..8be782934 100644 --- a/src/draftwright/analysis.py +++ b/src/draftwright/analysis.py @@ -1566,6 +1566,22 @@ def _with_blind_axial_bore_support(model: PartModel, cyls) -> PartModel: ) +def _sizing_model_pmi_visibility(model, cyls, layout_model, pmi_mode, document_input): + hidden = ( + frozenset(id(feature) for feature in document_input.source_annotations()) + if document_input is not None and pmi_mode != "annotate" + else frozenset() + ) + prepared = replace( + _with_blind_axial_bore_support(model, cyls), + pmi_annotations_enabled=layout_model is not None or pmi_mode == "annotate", + hidden_authored_dimension_ids=hidden, + ) + from draftwright.model.pmi_lowering import add_authored_step_positions + + return add_authored_step_positions(prepared) + + def _build_sizing_model(r: _AnalysisRequest, s: _SourceState) -> _ModelState: text_position = r.metadata.text_position text_orientation = r.metadata.text_orientation @@ -1732,7 +1748,9 @@ def _build_sizing_model(r: _AnalysisRequest, s: _SourceState) -> _ModelState: cyls=shared_cyls, ) ) - sizing_model = _with_blind_axial_bore_support(sizing_model, shared_cyls) + sizing_model = _sizing_model_pmi_visibility( + sizing_model, shared_cyls, layout_model, pmi_mode, _document_input + ) recognition_ownership = ( None if layout_model is not None diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index ed17bb973..9976c83f8 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -723,6 +723,15 @@ def preserve_declaration_identity(source, replacements, _member_groups) -> None: else () ), ) + pm = replace( + pm, + pmi_annotations_enabled=model is not None or a.pmi_mode == "annotate", + hidden_authored_dimension_ids=( + frozenset(id(feature) for feature in a.document_source_annotations) + if a.document_member and a.pmi_mode != "annotate" + else frozenset() + ), + ) # A caller may supply a PartModel that already contains raw imported PMI. That # path skips the extraction/lowering branch above but still needs baseline gap # identities before the compiled plan is built. diff --git a/src/draftwright/model/compiled.py b/src/draftwright/model/compiled.py index 0dc3a22f3..4e26ce576 100644 --- a/src/draftwright/model/compiled.py +++ b/src/draftwright/model/compiled.py @@ -2070,7 +2070,13 @@ def compile_dimensions( location_omissions.extend(off_axis_omissions) # A source location may cover one directional component without covering its # orthogonal sibling. Only exact witness correspondence can remove that component. - sources = tuple(f for f in model.features if isinstance(f, AuthoredDimension)) + sources = tuple( + f + for f in model.features + if isinstance(f, AuthoredDimension) + and model.pmi_annotations_enabled + and id(f) not in model.hidden_authored_dimension_ids + ) if sources and model.authored_dimensions is None: unique_cover: dict[int, list[AuthoredDimension]] = {} for source in sources: diff --git a/src/draftwright/model/ir.py b/src/draftwright/model/ir.py index af6069c78..de0c9ea73 100644 --- a/src/draftwright/model/ir.py +++ b/src/draftwright/model/ir.py @@ -2851,6 +2851,12 @@ class PartModel: # Derived from the build's cached cylinder substrate before planning. It carries # physical correspondence, not a rendering decision or a second feature inventory. blind_axial_bore_supports: tuple[BlindAxialBoreSupport, ...] = () + # Report-only PMI stays in the inventory for diagnostics but must not take + # precedence over dimensions that will actually reach the sheet. + pmi_annotations_enabled: bool = True + # A Document member may also contain caller-declared PMI. Hide only source + # annotations excluded by that member's mode, using their exact feature identity. + hidden_authored_dimension_ids: frozenset[int] = frozenset() def __post_init__(self) -> None: if self.declaration_identities and len(self.declaration_identities) != len(self.features): diff --git a/src/draftwright/model/ir_foundation.py b/src/draftwright/model/ir_foundation.py index 68485b8f1..1d37736fb 100644 --- a/src/draftwright/model/ir_foundation.py +++ b/src/draftwright/model/ir_foundation.py @@ -855,6 +855,8 @@ class StepFeature: # A planner-filled datum-to-shoulder measurement. The geometric ``step.length`` # remains the local segment; this is a separate, addressable position fact. position_span: tuple[Point, Point] | None = None + # An imported baseline created this position; member sheets can hide its source. + position_derived_from_pmi: bool = False kind: ClassVar[str] = "step" def __post_init__(self) -> None: diff --git a/src/draftwright/model/planner.py b/src/draftwright/model/planner.py index 7d9615b70..d42a0d2be 100644 --- a/src/draftwright/model/planner.py +++ b/src/draftwright/model/planner.py @@ -175,7 +175,10 @@ def _authored_baseline_candidates(model, steps, groups, axis, intervals, ends): candidates: dict[float, dict[float, str]] = {} established: set[float] = set() for source in model.features: - if not isinstance(source, AuthoredDimension): + if ( + not isinstance(source, AuthoredDimension) + or id(source) in model.hidden_authored_dimension_ids + ): continue stations = _authored_linear_stations(source) if stations is None or stations[0] != axis: @@ -377,6 +380,7 @@ def _authored_diameter_coverage( source for source in model.features if isinstance(source, AuthoredDimension) + and id(source) not in model.hidden_authored_dimension_ids and source.source == "ap242_pmi" and source.dimension_kind == "diameter" and source.source_id in requirement.source_ids @@ -415,7 +419,10 @@ def _authored_envelope_coverage(model, feature, parameter, baseline) -> str | No if source_id is not None and abs(parameter.value - abs(extent_hi - extent_lo)) <= 1e-6: return f"authored PMI dimension {source_id} covers this extent" for source in model.features: - if not isinstance(source, AuthoredDimension): + if ( + not isinstance(source, AuthoredDimension) + or id(source) in model.hidden_authored_dimension_ids + ): continue stations = _authored_linear_stations(source) if stations is None: @@ -455,7 +462,7 @@ def _authored_pmi_overlay( step_groups: dict[int, list[StepFeature]], ) -> tuple[DimParameter, str | None]: """Let imported references cover automatic measurements before compilation.""" - if model.authored_dimensions is not None: + if model.authored_dimensions is not None or not model.pmi_annotations_enabled: return parameter, None if parameter.kind == "diameter": source_id = _authored_diameter_coverage(model, feature, parameter) @@ -469,7 +476,10 @@ def _authored_pmi_overlay( if parameter.tolerance is None: steps = step_groups.get(id(feature), []) for source in model.features: - if not isinstance(source, AuthoredDimension): + if ( + not isinstance(source, AuthoredDimension) + or id(source) in model.hidden_authored_dimension_ids + ): continue if not _authored_linear_covers(source, feature, parameter, steps): continue @@ -2413,8 +2423,11 @@ def plan_dimensions(model: PartModel, *, planned_views=None) -> list[DimensionGr _check_intent_policy_conflicts(model) model = _selection_model(model, selection) has_imported_dimensions = any( - isinstance(feature, AuthoredDimension) for feature in model.features + isinstance(feature, AuthoredDimension) + and id(feature) not in model.hidden_authored_dimension_ids + for feature in model.features ) + has_imported_dimensions = has_imported_dimensions and model.pmi_annotations_enabled profile_groups = _authored_step_groups(model) if has_imported_dimensions else [] step_groups = {id(step): group for group in profile_groups for step in group} baselines: dict[int, tuple[int, float, dict[float, str]] | None] = {} @@ -2462,6 +2475,24 @@ def plan_dimensions(model: PartModel, *, planned_views=None) -> list[DimensionGr ) if authored_coverage is not None: suppressed, reason, conveyed_by = True, authored_coverage, None + if ( + isinstance(feature, StepFeature) + and feature.position_derived_from_pmi + and p.parameter_id == "step_position.length" + and request is None + and model.authored_dimensions is None + and ( + feature_baseline is None + or p.span is None + or "xyz"[feature_baseline[0]] != feature.frame.axis + or abs(feature_baseline[1] - p.span[0][feature_baseline[0]]) > 0.01 + ) + ): + suppressed, reason, conveyed_by = ( + True, + "its authored baseline is hidden from this sheet", + None, + ) if model.authored_dimensions is not None: # An authored set REPLACES the rule set rather than adding to it: what the # script lists is what the drawing carries, and everything else is omitted. diff --git a/src/draftwright/model/pmi_lowering.py b/src/draftwright/model/pmi_lowering.py index a0760a837..64f58ae57 100644 --- a/src/draftwright/model/pmi_lowering.py +++ b/src/draftwright/model/pmi_lowering.py @@ -1130,8 +1130,14 @@ def add_authored_step_positions( """Give automatic baseline gap fillers their own datum-to-shoulder IR identity.""" from draftwright.model.planner import _authored_step_baseline, _authored_step_groups - if model.authored_dimensions is not None or not any( - isinstance(feature, AuthoredDimension) for feature in model.features + if ( + model.authored_dimensions is not None + or not model.pmi_annotations_enabled + or not any( + isinstance(feature, AuthoredDimension) + and id(feature) not in model.hidden_authored_dimension_ids + for feature in model.features + ) ): return model features = list(model.features) @@ -1169,6 +1175,7 @@ def add_authored_step_positions( replacement = replace( feature, position_span=((start[0], start[1], start[2]), (end[0], end[1], end[2])), + position_derived_from_pmi=True, ) replacements[id(feature)] = replacement features[index] = replacement diff --git a/tests/_tier_manifest.py b/tests/_tier_manifest.py index 6872cbb6c..14289ab66 100644 --- a/tests/_tier_manifest.py +++ b/tests/_tier_manifest.py @@ -808,6 +808,7 @@ class ContractGroup: ), "src/draftwright/model/manufacturing_schedule.py": ("test_manufacturing_schedule.py",), "src/draftwright/model/pmi_lowering.py": ( + "test_authored_pmi_precedence.py", "test_issue_1296_cylindrical_diameter_pmi.py", "test_manufacturing_pmi_lowering.py", "test_nominal_step_pmi.py", diff --git a/tests/test_authored_pmi_precedence.py b/tests/test_authored_pmi_precedence.py index ff4c02467..774947e87 100644 --- a/tests/test_authored_pmi_precedence.py +++ b/tests/test_authored_pmi_precedence.py @@ -1,12 +1,14 @@ """Imported lengths cover automatic stations without changing a PMI-free chain.""" from dataclasses import replace +from pathlib import Path from types import SimpleNamespace import pytest from build123d import Box, Cylinder, Pos from draftwright import build_drawing +from draftwright.builder import detect_part_model from draftwright.linting.coverage import _authored_axial_witness_on_profile from draftwright.model.compiled import compile_dimensions from draftwright.model.ir import ( @@ -31,7 +33,7 @@ ) from draftwright.registry import AnnotationRegistry from draftwright.reporting import ReportUnavailableError, placed_dimension_sources -from draftwright.sheet_emit import emit_sheet_script +from draftwright.sheet_emit import emit_sheet_script, generate_sheet_script def _step(start: float, end: float, diameter: float) -> StepFeature: @@ -511,6 +513,84 @@ def test_no_pmi_keeps_the_original_chain(): ] +@pytest.mark.parametrize("mode", ["off", "report"]) +def test_explicit_model_pmi_still_takes_precedence_in_non_annotation_modes(mode): + part = ( + Pos(7.5, 0, 0) * Cylinder(15, 15, rotation=(0, 90, 0)) + + Pos(27.5, 0, 0) * Cylinder(10, 25, rotation=(0, 90, 0)) + + Pos(46, 0, 0) * Cylinder(6, 12, rotation=(0, 90, 0)) + ) + drawing = build_drawing( + part, + model=_model(_source(0, 40, "dimension:report-only")), + pmi=mode, + page="A3", + scale=1, + detail_view=False, + repair=False, + ) + assert drawing.model().pmi_annotations_enabled + assert any(feature.kind == "authored_dimension" for feature in drawing.model().features) + assert [(value, withheld) for value, _span, withheld in _step_lengths(drawing.model())] == [ + (15, False), + (25, True), + (12, True), + ] + assert sorted( + drawing.registry.named(name).label + for name in drawing.registry.names() + if name.startswith(("m_steplen", "pmi_x_")) + ) == ["15", "40", "52"] + + +def test_hidden_document_source_does_not_leave_an_inherited_baseline_mark(): + source = _source(0, 40, "dimension:document-source") + acquired = add_authored_step_positions(_model(source)) + assert any( + step.position_derived_from_pmi and step.position_span is not None + for step in acquired.features + if isinstance(step, StepFeature) + ) + report_member = replace(acquired, hidden_authored_dimension_ids=frozenset({id(source)})) + approved = [ + (dimension.param.parameter_id, dimension.param.value) + for group in plan_dimensions(report_member) + for dimension in group.dims + if isinstance(group.feature, StepFeature) + and dimension.param.kind == "length" + and not dimension.suppressed + ] + assert approved == [("step.length", 15), ("step.length", 25), ("step.length", 12)] + member_source = _source(0, 40, "dimension:member-source") + member = replace( + report_member, + features=[*report_member.features, member_source], + ) + assert [ + (dimension.param.parameter_id, dimension.param.value) + for group in plan_dimensions(member) + for dimension in group.dims + if isinstance(group.feature, StepFeature) + and dimension.param.kind == "length" + and not dimension.suppressed + ] == [("step.length", 15), ("step_position.length", 52)] + + +def test_report_only_detected_pmi_keeps_generated_step_chain(tmp_path): + fixture = Path(__file__).parent / "fixtures/grm03_thumbwheel_drive_screw_ap242_pmi.step" + detected = detect_part_model(str(fixture), pmi="report") + assert any(isinstance(feature, AuthoredDimension) for feature in detected.features) + script_path = generate_sheet_script( + str(fixture), out=str(tmp_path / "report.py"), pmi="report", inspect=False, formats=() + ) + script = Path(script_path).read_text() + assert [ + line + for line in script.splitlines() + if '"step.length"' in line and line.startswith("sheet.dimension(step") + ] == [f'sheet.dimension(step{index}, "step.length")' for index in range(1, 6)] + + def test_unproved_or_off_axis_source_does_not_cover_a_step(): source = _source(0, 40, "dimension:40") for other in ( From 51a342dfc8d9203c529fb0f4fe989c8ac52e645e Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Mon, 5 Oct 2026 10:03:22 +0100 Subject: [PATCH 3/3] Preserve cached model identity and inspection footprint --- src/draftwright/analysis.py | 21 ++++++++++++++++----- src/draftwright/builder.py | 19 ++++++++++--------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/draftwright/analysis.py b/src/draftwright/analysis.py index 8be782934..a685c5286 100644 --- a/src/draftwright/analysis.py +++ b/src/draftwright/analysis.py @@ -1572,11 +1572,22 @@ def _sizing_model_pmi_visibility(model, cyls, layout_model, pmi_mode, document_i if document_input is not None and pmi_mode != "annotate" else frozenset() ) - prepared = replace( - _with_blind_axial_bore_support(model, cyls), - pmi_annotations_enabled=layout_model is not None or pmi_mode == "annotate", - hidden_authored_dimension_ids=hidden, - ) + prepared = _with_blind_axial_bore_support(model, cyls) + enabled = layout_model is not None or pmi_mode == "annotate" + if ( + prepared.pmi_annotations_enabled != enabled + or prepared.hidden_authored_dimension_ids != hidden + ): + prepared = replace( + prepared, + pmi_annotations_enabled=enabled, + hidden_authored_dimension_ids=hidden, + ) + if not enabled or not any( + feature.kind == "authored_dimension" and id(feature) not in hidden + for feature in prepared.features + ): + return prepared from draftwright.model.pmi_lowering import add_authored_step_positions return add_authored_step_positions(prepared) diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index 9976c83f8..7973c8098 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -723,15 +723,16 @@ def preserve_declaration_identity(source, replacements, _member_groups) -> None: else () ), ) - pm = replace( - pm, - pmi_annotations_enabled=model is not None or a.pmi_mode == "annotate", - hidden_authored_dimension_ids=( - frozenset(id(feature) for feature in a.document_source_annotations) - if a.document_member and a.pmi_mode != "annotate" - else frozenset() - ), - ) + if model is not None or a.model is None: + pm = replace( + pm, + pmi_annotations_enabled=model is not None or a.pmi_mode == "annotate", + hidden_authored_dimension_ids=( + frozenset(id(feature) for feature in a.document_source_annotations) + if a.document_member and a.pmi_mode != "annotate" + else frozenset() + ), + ) # A caller may supply a PartModel that already contains raw imported PMI. That # path skips the extraction/lowering branch above but still needs baseline gap # identities before the compiled plan is built.