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
36 changes: 36 additions & 0 deletions docs/examples/quotation_blind_hole.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Quotation blind-hole comparison (#2233)

The original quotation STEP file and edited drawing are not available in this repository.
`quotation_blind_hole.py` therefore uses a public, reproducible 50 mm turned shaft with a
24 mm deep axial blind bore. It exercises the reported drawing decision without claiming to
reproduce the connector or agent that produced the original quotation.

Run from the repository root:

```bash
python docs/examples/quotation_blind_hole.py --out-dir /tmp/draftwright-2233 \
--date 2026-10-07 --sheet 1/1
```

The supplied date and sheet number appear in the title block. Omit them if unknown; the
script does not invent approval, material, revision, or release status. It writes three
PDF/PNG pairs, full drawing reports, and `comparison.json`:

- `baseline`: default planner, which does not request an axial section for this X-axis
blind bore (`section_decision: not_warranted`). This is a planner-policy choice, not a
failed placement of a required section.
- `section-with-iso`: declared required axial section, with the existing hidden-line ISO.
- `section-visible-iso`: the same section and ISO, with
`sheet.add_view("iso").hidden_lines(False)`.

The required section is either placed or the script fails before exporting it. The
comparison also requires the same measured-fact ledger and supplied H7 bore fit in all
three variants. On this fixture the first two ISOs contain 10 hidden edges; the last
contains none while retaining its visible edges and orientation view. The section shows
the blind-hole profile and bottom. Full lint and audited completeness accompany each
PDF; a clean lint alone is not treated as proof of manufacturing completeness.

The printed `30` overall height and `⌀30` head diameter describe the same radial extent
on this fixture. The printed 8 and 42 axial lengths do **not** form a closed three-value
chain because no 50 overall length is printed. This is a review observation, not a
general redundancy deletion rule; functional priority remains an author decision (#941).
183 changes: 183 additions & 0 deletions docs/examples/quotation_blind_hole.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
"""Reproduce the #2233 quotation-sheet comparison on a public synthetic part.

Run from the repository root::

python docs/examples/quotation_blind_hole.py --out-dir /tmp/draftwright-2233 \
--date 2026-10-07 --sheet 1/1

The date and sheet are sample *supplied* metadata, not inferred from geometry.
No approval, material, or manufacturing-release status is invented.
"""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path

from build123d import Align, Axis, Cylinder, Pos

from draftwright import Sheet


def turned_blind_hole():
"""A 50 mm turned shaft with a 24 mm deep axial blind bore."""
align = (Align.CENTER, Align.CENTER, Align.MIN)

def axial(radius: float, length: float):
return Cylinder(radius, length, align=align).rotate(Axis.Y, 90)

return (axial(10, 50) + axial(15, 8)) - Pos(26, 0, 0) * axial(3, 24)


def _sheet(part, *, date: str, sheet_number: str) -> tuple[Sheet, object]:
sheet = Sheet.from_part(
part,
title="QUOTATION SPINDLE",
number="Q-2233",
document_type="QUOTATION",
date=date,
sheet=sheet_number,
revision="",
approved_by="",
)
hole = next(feature for feature in sheet.features if feature.kind == "hole")
sheet.of(hole).fit("H7") # supplied example requirement, not a geometry inference
return sheet, hole


def baseline(part, *, date: str = "", sheet_number: str = ""):
"""Detected dimensions and default view planning: no X-axis blind-hole section."""
sheet, _hole = _sheet(part, date=date, sheet_number=sheet_number)
return sheet.build()


def section_with_iso(part, *, date: str = "", sheet_number: str = ""):
"""Keep automatic dimensions/views but require the axial section by feature."""
sheet, hole = _sheet(part, date=date, sheet_number=sheet_number)
sheet.take_over(dimensions="automatic", principal_views="automatic", derived_views="automatic")
sheet.add_section_view("A", through=sheet.of(hole))
return sheet.build()


def section_visible_iso(part, *, date: str = "", sheet_number: str = ""):
"""Keep the orientation view but hide edges already explained by the section."""
sheet, hole = _sheet(part, date=date, sheet_number=sheet_number)
sheet.take_over(dimensions="automatic", principal_views="automatic", derived_views="automatic")
sheet.add_view("iso").hidden_lines(False)
sheet.add_section_view("A", through=sheet.of(hole))
return sheet.build()


def measurement_ledger(drawing) -> Counter:
"""Compare measured facts, not annotation names or rendered glyphs."""
facts: Counter = Counter()
for name in drawing.registry.names():
for identity in drawing.registry.measurement_of(name):
value = next(
parameter.value
for parameter in identity.feature.parameters()
if parameter.parameter_id == identity.parameter
)
facts[(identity.feature.kind, identity.parameter, round(value, 6))] += 1
return facts


def summary(drawing, *, date: str, sheet_number: str) -> dict:
block = drawing.get_annotation("title_block")
fields = {name: value for name, value, *_rest in block.title_field_specs}
ledger = measurement_ledger(drawing)
report = drawing.report()
completeness = report["lint"]["quality"]["completeness"]
iso = drawing.views.get("iso")
return {
"views": list(drawing.views),
"section_decision": drawing.section_decision,
"iso_hidden_edges": len(iso[1].edges()) if iso and iso[1] else 0,
"measurements": [
{"feature": kind, "parameter": parameter, "value": value, "count": count}
for (kind, parameter, value), count in sorted(ledger.items())
],
"fit_labels": [
drawing.registry.named(name).label
for name in sorted(drawing.registry.names())
if "H7" in getattr(drawing.registry.named(name), "label", "")
],
"title_fields": fields,
"missing_supplied_metadata": [
field for field, supplied in (("date", date), ("sheet", sheet_number)) if not supplied
],
"lint_by_code": drawing.lint_summary()["by_code"],
"audited_completeness": {
"scope": completeness["scope"],
"coverage": completeness["coverage"],
"requirements": completeness["requirements"],
"placed": completeness["placed"],
"dropped": completeness["dropped"],
"missing": completeness["missing"],
},
"page": report["layout"]["page"],
}


def write_comparison(out_dir: Path, *, date: str = "", sheet_number: str = "") -> dict:
"""Write comparable PDFs, full reports and an explicit decision/coverage ledger."""
out_dir.mkdir(parents=True, exist_ok=True)
part = turned_blind_hole()
drawings = {
"baseline": baseline(part, date=date, sheet_number=sheet_number),
"section-with-iso": section_with_iso(part, date=date, sheet_number=sheet_number),
"section-visible-iso": section_visible_iso(part, date=date, sheet_number=sheet_number),
}
expected = measurement_ledger(drawings["baseline"])
for name, drawing in drawings.items():
if name != "baseline" and (
drawing.section_decision["status"] != "placed" or "section_aa" not in drawing.views
):
raise RuntimeError(
f"required axial section was not placed: {drawing.section_decision}"
)
if measurement_ledger(drawing) != expected:
raise RuntimeError(f"{name} changed the measured requirement set")
if len(summary(drawing, date=date, sheet_number=sheet_number)["fit_labels"]) != 1:
raise RuntimeError(f"{name} lost the supplied H7 bore requirement")
drawing.export(str(out_dir / name), formats=("pdf", "png"))
drawing.write_report(out_dir / f"{name}.draftwright.json")
comparison = {
"source": "public programmatic 50 mm turned shaft with axial blind bore",
"status": "QUOTATION / DFM REVIEW - NOT RELEASED FOR MANUFACTURE",
"original_quotation_source_available": False,
"variants": {
name: summary(drawing, date=date, sheet_number=sheet_number)
for name, drawing in drawings.items()
},
"redundancy_review": (
"The baseline prints head outside diameter 30 and overall height 30, which repeat "
"the same radial extent on this turned fixture. It prints 8 and 42 axial lengths "
"but no 50 overall length, so that chain is not closed by a third printed value. "
"No dimension was removed automatically; functional priority needs author review (#941)."
),
"isometric_policy": (
"The section-visible-iso variant retains the optional orientation view but suppresses "
"its hidden edges. Orthographic and section measurements remain unchanged."
),
}
(out_dir / "comparison.json").write_text(
json.dumps(comparison, indent=2, allow_nan=False) + "\n", encoding="utf-8"
)
return comparison


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out-dir", type=Path, required=True)
parser.add_argument("--date", default="", help="Supplied title-block date; blank if unknown")
parser.add_argument("--sheet", default="", help="Supplied sheet field; blank if unknown")
args = parser.parse_args()
result = write_comparison(args.out_dir, date=args.date, sheet_number=args.sheet)
print(json.dumps({name: item["views"] for name, item in result["variants"].items()}))


if __name__ == "__main__":
main()
8 changes: 8 additions & 0 deletions docs/reference/sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,14 @@ refused at declaration and constraints are never silently relaxed. The immutable
snapshot is available as `sheet.view_constraints`, while `drawing.view_plan` is the distinct
resolved result.

Principal and isometric views render hidden edges by default. Use a view handle's
`.hidden_lines(False)` to keep the view but show only visible edges; `.hidden_lines(True)`
restores the default. For example, `sheet.add_view("iso").hidden_lines(False)` selects a
visible-only isometric while retaining automatic principal views (after selecting the
automatic view source). This is a display choice, not a replacement for a section that
must reveal and dimension an internal feature. Section and detail views do not support
this option.

Layout advisories are also available as structured findings from `Drawing.lint()` and
`lint(physical=False)`. `legibility_floor_breached` reports an explicit scale below the
legibility floor when a legible automatic fit exists; `page_fit_uncertain` reports an
Expand Down
4 changes: 4 additions & 0 deletions src/draftwright/drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,10 @@ def _add_view(
scaled=scaled,
bounds_cache=bounds_cache,
)
plan = self._build.view_plan
spec = plan.spec(name) if plan is not None else None
if spec is not None and not spec.hidden_lines:
placed_hid = None
self.views[name] = (placed, placed_hid)
self._coords[name] = coords
return self._coords[name]
Expand Down
16 changes: 14 additions & 2 deletions src/draftwright/sheet_emit.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,12 @@
from draftwright.sheet_object_source import (
_resolve_object_source as _resolve_object_source,
)
from draftwright.view_plan import PRINCIPAL_VIEW_NAMES, ViewConstraints, validate_projection
from draftwright.view_plan import (
PRINCIPAL_VIEW_NAMES,
ViewConstraints,
ViewSpec,
validate_projection,
)

_log = logging.getLogger(__name__)

Expand Down Expand Up @@ -1307,6 +1312,13 @@ def _derived_label(name: str, kind: str) -> str:
raise ValueError(f"cannot emit {kind} view with non-canonical name {name!r}")


def _principal_view_suffix(spec: ViewSpec) -> str:
"""Express independent scale and hidden-edge visibility through view verbs."""
scale = "" if spec.scale_factor is None else f".scale({spec.scale_factor!r})"
hidden = "" if spec.hidden_lines else ".hidden_lines(False)"
return scale + hidden


def _adopted_view_block(constraints: ViewConstraints, names: Mapping[int, str]) -> list[str]:
"""Emit a semantic Sheet request for an adopted view-source state (#1350)."""
principal_source = constraints.principal_source or "automatic"
Expand Down Expand Up @@ -1357,7 +1369,7 @@ def emit_principal(item, verb: str) -> None:
raise ValueError(f"cannot emit principal view {spec.name!r} with a target")
handle = f"{spec.name}_view"
handles[spec.name] = handle
suffix = "" if spec.scale_factor is None else f".scale({spec.scale_factor!r})"
suffix = _principal_view_suffix(spec)
lines.append(f'{handle} = sheet.{verb}("{spec.name}"){suffix}')

def emit_derived(item, verb: str) -> None:
Expand Down
11 changes: 11 additions & 0 deletions src/draftwright/sheet_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,15 @@ def scale(self, factor) -> _View:
record["scale_factor"] = factor
return self

def hidden_lines(self, enabled: bool) -> _View:
"""Choose whether this principal or isometric view renders hidden edges."""
if self._record["kind"] not in {"principal", "pictorial"}:
raise ValueError("hidden_lines() supports principal and isometric views only")
if not isinstance(enabled, bool):
raise TypeError("hidden_lines() needs a bool")
self._record["hidden_lines"] = enabled
return self


class _SheetViewMethods:
# Sheet initializes this state. These declarations let the private view owner
Expand Down Expand Up @@ -217,6 +226,7 @@ def _append_view_record(
"kind": kind,
"target": target,
"scale_factor": None,
"hidden_lines": True,
"source": source,
}
)
Expand Down Expand Up @@ -554,6 +564,7 @@ def _materialized_view_constraint(self, record: dict) -> ViewConstraint:
kind=record["kind"],
target=target,
scale_factor=record["scale_factor"],
hidden_lines=record["hidden_lines"],
),
record["source"],
)
Expand Down
9 changes: 9 additions & 0 deletions src/draftwright/view_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,18 @@ class ViewSpec:
#: Independent scale factor for a detail or orientation view. Principal views share the
#: sheet scale and therefore reject this field.
scale_factor: float | None = None
#: Whether to render hidden edges in a principal or pictorial view.
hidden_lines: bool = True

def __post_init__(self) -> None:
if self.kind not in _KINDS:
raise ValueError(f"unknown view kind {self.kind!r}; expected one of {sorted(_KINDS)}")
if not isinstance(self.hidden_lines, bool):
raise TypeError("hidden_lines must be a bool")
if not self.hidden_lines and self.kind not in {"principal", "pictorial"}:
raise ValueError(
"hidden-line visibility is supported for principal and pictorial views"
)
if self.scale_factor is not None:
if self.kind not in {"detail", "pictorial"}:
raise ValueError(
Expand Down Expand Up @@ -529,6 +537,7 @@ def resolve_from_analysis(analysis) -> ResolvedViewPlan:
page_axes=spec.page_axes,
target=requested_by_name.get(spec.name, spec).target,
scale_factor=requested_by_name.get(spec.name, spec).scale_factor,
hidden_lines=requested_by_name.get(spec.name, spec).hidden_lines,
)
for spec in principals
)
Expand Down
Loading
Loading