Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/draftwright/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1566,6 +1566,33 @@ 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 = _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)


def _build_sizing_model(r: _AnalysisRequest, s: _SourceState) -> _ModelState:
text_position = r.metadata.text_position
text_orientation = r.metadata.text_orientation
Expand Down Expand Up @@ -1732,7 +1759,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
Expand Down
19 changes: 19 additions & 0 deletions src/draftwright/annotations/_step_lengths.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
43 changes: 43 additions & 0 deletions src/draftwright/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,49 @@ def preserve_declaration_identity(source, replacements, _member_groups) -> None:
else ()
),
)
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.
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)


Expand Down
10 changes: 10 additions & 0 deletions src/draftwright/drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
157 changes: 113 additions & 44 deletions src/draftwright/linting/coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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(
Expand Down
14 changes: 10 additions & 4 deletions src/draftwright/linting/turned_step_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions src/draftwright/model/callout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading