Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update lab hardware CAD skill documentation and standards

Timothy Kassis336c4f838a6c
diff --git a/skills/lab-hardware-cad/SKILL.md b/skills/lab-hardware-cad/SKILL.md
index 0d509277..97f003ef 100644
--- a/skills/lab-hardware-cad/SKILL.md
+++ b/skills/lab-hardware-cad/SKILL.md
@@ -5,9 +5,9 @@ license: MIT
compatibility: Python 3.10-3.14 with build123d 0.11.1 and matplotlib for snapshots. Geometry commands require build123d; the standards lookup and the interface check run on the standard library alone. No network access needed.
allowed-tools: Read Write Edit Bash Glob Grep
metadata:
- version: "1.1"
+ version: "1.2"
skill-author: K-Dense Inc.
- last-reviewed: "2026-08-14"
+ last-reviewed: "2026-08-15"
build123d-version: "0.11.1"
---
@@ -93,6 +93,17 @@ python scripts/check.py standards --list
python scripts/check.py standards --show slas-microplate-footprint
```
+The bundled standard IDs (exact strings; do not guess variants): `slas-microplate-footprint`,
+`slas-microplate-height`, `slas-microplate-flange`, `slas-well-positions-96`,
+`slas-well-positions-384`, `slas-well-positions-1536`, `cuvette-standard-10mm`,
+`optical-breadboard-metric`, `optical-breadboard-imperial`, `cage-system-30mm`,
+`sm1-lens-tube-thread`.
+
+If the part mates with nothing in this list, that is common and fine: declare no interfaces,
+and name every interface dimension with its source (user spec, vendor drawing, measurement) as
+**unchecked** in the report. Never declare against an unrelated standard to fill the gap — a
+fabricated declaration is worse than an honest "nobody checked this".
+
### 3. Choose the process before choosing the geometry
Read `references/fabrication-limits.md`. Process determines minimum wall, minimum feature,
@@ -116,6 +127,20 @@ Requirements:
overrides actually reach it.
- Declare an `interfaces()` function returning the dimensions the part must fit, each with its
standard ID and intent. This is what makes the interface machine-checkable in step 5.
+ `intent` is `"envelope"` when the feature must **accept** any conforming part (a pocket, bore,
+ or slot — checked one-sided at maximum material condition plus your clearance) and `"match"`
+ when this part must itself conform (symmetric band). `clearance` is the total intended
+ clearance in mm and must be non-negative. Declare only dimensions that constrain *this part's
+ mating features* — a property of the mating equipment (a table's edge border, a typical plate
+ thickness) is not an interface of yours. If no bundled standard applies, return `[]`.
+- Declare a `checks()` function of **go/no-go gauges measured from the built solid**: a `clear`
+ region for everything that must pass through or fit in (screw shafts, beam corridors, the
+ mating part at maximum material condition dropping into its pocket), a `material` region for
+ everything that must remain (a ridge, a ledge, a screw seat), and a `bbox_*` bound for every
+ size limit the user stated. Map **every geometric requirement in the request** to one entry;
+ these catch the errors that `is_valid`, the bounding box, and declared numbers cannot see.
+ `gen.py` runs them on every generation and fails the build when one fails. Schema and worked
+ examples: `references/build123d-patterns.md`.
- Put the process, material, and every interface source in the module docstring.
```python
@@ -161,10 +186,24 @@ def interfaces() -> list[dict]:
]
+def checks() -> list[dict]:
+ """Gauges measured from the built solid. Sized from the REQUIREMENT's numbers
+ (plate MMC, the user's height limit), not from the pocket parameters, so a
+ wrong parameter cannot shrink the gauge to match the wrong geometry."""
+ depth = body_h_mm - floor_t_mm
+ return [
+ {"feature": "plate at MMC drops into the pocket",
+ "clear": {"box": (plate_l_mm + plate_tol_mm, plate_w_mm + plate_tol_mm, depth),
+ "at": [(0.0, 0.0, floor_t_mm + depth / 2)]}},
+ {"feature": "under 15 mm for the stage", "bbox_z": {"max": 15.0}},
+ ]
+
+
def build() -> Part:
pocket_l, pocket_w = pocket_mm()
with BuildPart() as carrier:
- Box(pocket_l + 2 * wall_t_mm, pocket_w + 2 * wall_t_mm, body_h_mm)
+ Box(pocket_l + 2 * wall_t_mm, pocket_w + 2 * wall_t_mm, body_h_mm,
+ align=(Align.CENTER, Align.CENTER, Align.MIN))
with Locations((0, 0, floor_t_mm)):
Box(pocket_l, pocket_w, body_h_mm, mode=Mode.SUBTRACT,
align=(Align.CENTER, Align.CENTER, Align.MIN))
@@ -174,14 +213,24 @@ def build() -> Part:
See `references/build123d-patterns.md` for the builder-vs-algebra choice, the `interfaces()`
contract, sketching, selectors, fillets, and threaded-insert bores.
-### 5. Generate and check the interfaces
+### 5. Generate and run the checks
```bash
python scripts/gen.py carrier_model.py --outdir out/
python scripts/check.py facts out/carrier.step
python scripts/check.py interfaces out/carrier.manifest.json
+python scripts/check.py geometry out/carrier.step --model carrier_model.py
```
+`gen.py` also evaluates the model's `checks()` gauges against the solid it just built, prints
+each PASS/FAIL, records them in the manifest, and exits non-zero on a failure — so a part that
+violates its own declared geometry never silently becomes an artifact. `check.py geometry`
+re-runs the same gauges against the exported STEP, which is the authoritative artifact.
+
+`out/` is a scratch convention, not a requirement. When the user asked for deliverables in a
+specific place, generate there (`--outdir .`) or copy the STEP, manifest, and DXF to it before
+finishing — a deliverable that exists only inside `out/` has not been delivered.
+
`gen.py` writes `carrier.step` (authoritative), `carrier.stl` (mesh preview and printing), and
`carrier.manifest.json` recording the source hash, resolved parameters, declared interfaces,
library versions, and measured bounding box, volume, and validity. The manifest is the provenance
@@ -191,19 +240,19 @@ record — keep it with the artifact.
solid count. A part that reports `is_valid: false` is broken geometry; fix the source before going
further.
-`check.py interfaces` is the check that gates fabrication. It evaluates every entry the model
-declared against the standards database and exits non-zero on failure. Use it rather than
-`check.py fit` for anything internal: **the interface is almost always a pocket, bore, or slot,
-and none of those appear in the part's outer bounding box.** `fit` measures that outer envelope, so
-running it on a carrier reports the outside of the walls and fails against the plate footprint.
-Reach for `fit` only to check one number by hand, or when the part's own outline is the interface —
-a gasket cut to a plate footprint, for instance:
+`check.py interfaces` evaluates every entry the model declared against the standards database
+and exits non-zero on failure. **Be clear about what it does and does not verify:** it checks the
+*declared numbers* — catching a transcribed dimension, the wrong standard, and
+nominal-instead-of-MMC sizing — but it never measures the built geometry, and a value computed
+from the same constants it is checked against passes with zero headroom by construction. Do not
+cite it as evidence the geometry is right; `facts` and the snapshot are the geometry checks.
+An empty declaration list passes: a part that mates with nothing in the bundled database has
+nothing to declare, and its interface dimensions are instead named as unchecked in the report.
-```bash
-# check one dimension by hand, without a geometry kernel
-python scripts/check.py fit --standard slas-microplate-footprint \
- --intent envelope --clearance 0.8 --value footprint_length=128.81
-```
+Use `interfaces` rather than `check.py fit` for anything internal — a pocket, bore, or slot does
+not appear in the part's outer bounding box, which is what `fit` measures. Reach for `fit` only
+to check one number by hand (`--value footprint_length=128.81`), or when the part's own outline
+is the interface, such as a gasket cut to a plate footprint.
For assemblies, check that parts do not interfere:
@@ -219,9 +268,17 @@ python scripts/snapshot.py out/carrier.step --out out/carrier.png
Then **read the PNG**. This step is mandatory after every generation and every modification.
Deterministic checks passing is not a reason to skip it: `is_valid` and a correct bounding box are
-both fully consistent with a pocket cut on the wrong face, an inverted mold polarity, a boss
-placed outside the body, or a fillet that ate a feature. Those errors are obvious in a picture and
-invisible in the numbers.
+both fully consistent with a pocket cut on the wrong face, a boss placed outside the body, or a
+fillet that ate a feature. Those errors are obvious in a picture and invisible in the numbers.
+
+Know the render's limits too. A feature much smaller than the frame — a 0.3 mm mold ridge on a
+40 mm part, a counterbore step on a plate — may not be decidable from the views at all. Do not
+report seeing something the image cannot resolve; that is worse than not looking. For such
+features the skill has instruments: `check.py bores` prints every cylindrical face (diameter,
+axis, position, span, sweep) so you can reconcile the drilling against the model's intent, and
+`check.py probe` answers a one-off "is this region clear / is material present here" without
+editing the model. Cite the measured numbers; report from the picture only what the picture
+actually shows.
The six views are true orthographic projections, and the outlines are the model's real edges drawn
**without hidden-line removal**. So a circle visible "through" material is a bore on the far side,
@@ -302,7 +359,10 @@ recommend printing a test coupon of the critical interface before committing to
| `gen.py <model.py> --outdir DIR` | Run `build()`, export STEP and STL, write the provenance manifest |
| `gen.py <model.py> --dxf [--dxf-z MM]` | Also slice a 2D DXF profile for laser cutting (default plane: mid-height) |
| `check.py facts <step>` | Validity, bounding box, volume, area, centre of mass, solid count |
-| `check.py interfaces <manifest\|model.py>` | Check every interface the model declares; non-zero exit on failure |
+| `check.py interfaces <manifest\|model.py>` | Check every declared interface number against its standard; non-zero exit on failure |
+| `check.py geometry <model.py\|step --model M>` | Evaluate the model's `checks()` gauges against the built solid — measured, not declared |
+| `check.py probe <step> --cyl D\|--box X,Y,Z --at ...` | One ad-hoc gauge: is this region clear of material, or filled with it |
+| `check.py bores <step>` | Census of every cylindrical face: diameter, axis, position, span, sweep |
| `check.py fit --standard ID --value DIM=MM` | Check one dimension by hand, or a part whose outer envelope is the interface |
| `check.py clearance <a> <b> --min MM` | Minimum distance between two solids; detects interference |
| `check.py standards [--list\|--show ID]` | Browse the bundled standards data (standard library only) |
diff --git a/skills/lab-hardware-cad/assets/standards.json b/skills/lab-hardware-cad/assets/standards.json
index 4a87c0d7..1e7db8d4 100644
--- a/skills/lab-hardware-cad/assets/standards.json
+++ b/skills/lab-hardware-cad/assets/standards.json
@@ -2,7 +2,7 @@
"schema_version": "1.0",
"units": "mm",
"note": "Dimensional standards for lab-hardware interfaces. Every entry carries a source. Entries with verified=false were not confirmed against the primary document during authoring and must be checked before use.",
- "last_reviewed": "2026-08-13",
+ "last_reviewed": "2026-08-15",
"standards": {
"slas-microplate-footprint": {
"title": "Microplate footprint (base outline)",
@@ -27,7 +27,7 @@
"nominal": 3.18,
"tol_plus": 1.6,
"tol_minus": 1.6,
- "note": "Outside radius of the four bottom-flange corners. The wide tolerance means a pocket must be cut to the maximum radius, not the nominal."
+ "note": "Outside radius of the four bottom-flange corners (convex). A receiving pocket's internal fillet must be no LARGER than the minimum (1.58) or it bulges into the plate corner and binds; a sharp pocket corner or a corner-relief cut always clears. Do not size the pocket fillet to the maximum radius."
}
},
"fit_checks": [
@@ -142,7 +142,8 @@
"clearance_hole_close": {"nominal": 6.4, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Close-fit clearance for an M6 cap screw."},
"clearance_hole_normal": {"nominal": 6.6, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Normal-fit clearance for M6. Prefer this on printed parts."},
"counterbore_dia": {"nominal": 11.0, "tol_plus": 0.0, "tol_minus": 0.0, "note": "For an M6 socket head cap screw head (nominal head dia 10 mm)."},
- "border": {"nominal": 12.5, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Typical edge-to-first-hole distance."}
+ "screw_head_height": {"nominal": 6.0, "tol_plus": 0.0, "tol_minus": 0.0, "note": "M6 socket head cap screw head height (ISO 4762). A counterbore shallower than this leaves the head proud, not flush."},
+ "border": {"nominal": 12.5, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Typical edge-to-first-hole distance. A property of the TABLE, not of your part: your plate's edge margin is a free design choice, so do not declare this as an interface."}
},
"fit_checks": [],
"design_note": "Slot rather than hole one of any pair of mounting features to absorb grid and print tolerance."
@@ -158,7 +159,8 @@
"thread_major_dia": {"nominal": 6.35, "tol_plus": 0.0, "tol_minus": 0.0, "note": "1/4-20 UNC: 0.25 inch major diameter, 20 threads per inch."},
"clearance_hole_normal": {"nominal": 6.8, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Normal-fit clearance for a 1/4-20 screw."},
"counterbore_dia": {"nominal": 11.2, "tol_plus": 0.0, "tol_minus": 0.0, "note": "For a 1/4-20 socket head cap screw head."},
- "border": {"nominal": 12.7, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Typical 0.5 inch edge-to-first-hole distance."}
+ "screw_head_height": {"nominal": 6.35, "tol_plus": 0.0, "tol_minus": 0.0, "note": "1/4-20 socket head cap screw head height (0.25 inch). A counterbore shallower than this leaves the head proud, not flush."},
+ "border": {"nominal": 12.7, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Typical 0.5 inch edge-to-first-hole distance. A property of the TABLE, not of your part: your plate's edge margin is a free design choice, so do not declare this as an interface."}
},
"fit_checks": [],
"design_note": "Ask which table the user has. Assuming the wrong system is the most common optomechanical design error."
@@ -172,11 +174,10 @@
"dimensions": {
"rod_spacing": {"nominal": 30.0, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Rod centre to rod centre, on a square pattern. 1.18 inch."},
"rod_diameter": {"nominal": 6.0, "tol_plus": 0.0, "tol_minus": 0.0, "note": "ER series cage rods."},
- "rod_bore_clearance": {"nominal": 6.1, "tol_plus": 0.0, "tol_minus": 0.0, "note": "Suggested bore for a printed plate to slide on 6 mm rods. Widen for FDM; see fabrication-limits.md."},
- "plate_thickness_typical": {"nominal": 8.9, "tol_plus": 0.0, "tol_minus": 0.0, "note": "0.35 inch, the CP33 standard cage plate. Not a constraint on custom plates, but matching it keeps optical path budgets simple."}
+ "plate_thickness_typical": {"nominal": 8.9, "tol_plus": 0.0, "tol_minus": 0.0, "note": "0.35 inch, the CP33 standard cage plate. Informational, not a mating dimension: custom plates may be any thickness, but matching it keeps optical path budgets simple."}
},
"fit_checks": [],
- "design_note": "The 30 mm rod square is centred on the optical axis. A custom plate must place its aperture at the centroid of the four rod bores."
+ "design_note": "The 30 mm rod square is centred on the optical axis. A custom plate must place its aperture at the centroid of the four rod bores. Bore diameter is rod_diameter plus twice the free-sliding per-side clearance for YOUR process (fabrication-limits.md): about 6.2 CNC, 6.4 SLA, 6.8 FDM. 6.1 is a reamed-metal number and binds on printed parts. Four bores on a common square over-constrain each other, so do not go tighter than the fits table. Declare the bore against rod_diameter with intent envelope and the clearance you chose."
},
"sm1-lens-tube-thread": {
"title": "SM1 lens tube thread",
diff --git a/skills/lab-hardware-cad/references/build123d-patterns.md b/skills/lab-hardware-cad/references/build123d-patterns.md
index ce557c5f..44f11406 100644
--- a/skills/lab-hardware-cad/references/build123d-patterns.md
+++ b/skills/lab-hardware-cad/references/build123d-patterns.md
@@ -40,7 +40,7 @@ from build123d import *
# --- INTERFACE (fixed; do not tune) ---
rod_spacing_mm = 30.0 # cage-system-30mm
-rod_bore_d_mm = 6.1 # cage-system-30mm, clearance on 6.0 mm rods
+rod_bore_d_mm = 6.4 # rod_diameter 6.0 + 2 x 0.20 SLA free-sliding (fabrication-limits.md)
# --- DESIGN (free) ---
plate_t_mm = 8.9
aperture_d_mm = 25.4
@@ -52,7 +52,7 @@ def interfaces() -> list[dict]:
"dimension": "rod_spacing", "value": rod_spacing_mm, "intent": "match"},
{"feature": "cage rod bore diameter", "standard": "cage-system-30mm",
"dimension": "rod_diameter", "value": rod_bore_d_mm,
- "intent": "envelope", "clearance": 0.1},
+ "intent": "envelope", "clearance": 0.4},
]
@@ -102,6 +102,68 @@ def pocket_l_mm() -> float:
`gen.py` warns when it sees a static `INTERFACES` list together with `--param`.
+## Declaring geometry checks
+
+`interfaces()` compares declared numbers against the standards database; it never touches the
+solid. `checks()` is its measured counterpart: a list of **go/no-go gauges** evaluated by boolean
+intersection against the part `build()` actually produced. `gen.py` runs them on every
+generation and fails the build if one fails; `check.py geometry` re-runs them against an
+exported STEP.
+
+The principle: **every geometric requirement in the request maps to one entry.** Something must
+pass through (a screw, a beam, a probe) → a `clear` region. Something must fit into a void (a
+plate into a pocket) → a `clear` box the size of the mating part at maximum material condition.
+Something must remain (a ridge, a ledge, a screw seat) → a `material` region. A stated size
+limit → a `bbox_*` bound. These are exactly the errors `is_valid`, the bounding box, and a
+declared-number check cannot see.
+
+```python
+def checks() -> list[dict]:
+ top = plate_t_mm / 2
+ return [
+ # a clear region: no material may intrude (screw shafts, through the part)
+ {"feature": "M6 screws pass all four bores",
+ "clear": {"cylinder": 6.0, "axis": "z", "at": bolt_xy()}},
+ # a keep-out with an explicit span (a beam corridor along x at height z)
+ {"feature": "beam clear at 15 mm above the bench",
+ "clear": {"cylinder": 5.0, "axis": "x", "at": [(0.0, 15.0)]}},
+ # a gauge part that must drop into a pocket: the mating part at MMC
+ {"feature": "SLAS plate at MMC drops into the pocket",
+ "clear": {"box": (128.01, 85.73, pocket_depth_mm()),
+ "at": [(0.0, 0.0, floor_t_mm + pocket_depth_mm() / 2)]}},
+ # a counterbore that really is a counterbore: recess open, seat present.
+ # The second entry is what catches a recess that punched through.
+ {"feature": "counterbore recess open at the top",
+ "clear": {"cylinder": cbore_d_mm - 0.2, "axis": "z", "at": bolt_xy(),
+ "span": (top - cbore_depth_mm + 0.1, top + 0.1)}},
+ {"feature": "screw seat present below the recess",
+ "material": {"cylinder": cbore_d_mm - 0.2, "axis": "z", "at": bolt_xy(),
+ "span": (-top + 0.1, top - cbore_depth_mm - 0.1)},
+ "min_mm3": 50.0},
+ # a user-stated hard limit, measured from the solid
+ {"feature": "clears the objective turret", "bbox_z": {"max": 15.0}},
+ ]
+```
+
+Semantics:
+
+| Key | Meaning |
+| --- | --- |
+| `clear` / `material` | region that must contain no material / must contain material |
+| `{"cylinder": DIA, "axis": "x"\|"y"\|"z", "at": [(a, b), ...], "span": (lo, hi)}` | `at` is 2D in the plane perpendicular to the axis — axis `z`: (x, y); axis `x`: (y, z); axis `y`: (x, z). Omit `span` to run through the whole part |
+| `{"box": (dx, dy, dz), "at": [(x, y, z), ...]}` | axis-aligned box gauges centred at each position |
+| `tol_mm3` / `min_mm3` | pass thresholds per position (both default 0.01) |
+| `bbox_x`…`bbox_z`, `bbox_min/mid/max` | `{"min": mm, "max": mm}` bounds on the measured bounding box |
+
+Size the gauges from the same named constants as the geometry **only when the requirement is
+relational** (the recess sits above the seat). When the requirement is absolute — a mating part's
+MMC, a user's height limit, a beam position — write the gauge from the requirement's own numbers,
+so a wrong parameter cannot shrink the gauge to match the wrong geometry.
+
+For a one-off question without editing the model, `check.py probe` runs a single gauge from the
+command line, and `check.py bores` prints a census of every cylindrical face (diameter, axis,
+position, span, sweep) to reconcile against the model's intent.
+
## Positioning
`Locations` places the objects created inside it. It is the workhorse for bolt patterns.
@@ -149,13 +211,28 @@ snapshot catches.
`Hole` cuts through the whole part; `CounterBoreHole` and `CounterSinkHole` add a head recess.
+**`CounterBoreHole` cuts downward from the workplane it is placed on, with the recess at that
+plane.** On a centred `Box` the default workplane is the mid-height of the part, so a 2-tuple
+location buries the screw seat inside the plate — or, on a thin plate, lets the recess swallow the
+top entirely, leaving a straight bore the screw head falls through. Place it on the **top face**
+(or give the location an explicit z at the top):
+
```python
with BuildPart() as plate:
- Box(60.0, 60.0, 10.0)
- with Locations((20.0, 20.0)):
- CounterBoreHole(radius=6.6 / 2, counter_bore_radius=11.0 / 2, counter_bore_depth=4.0)
+ Box(60.0, 60.0, 10.0) # spans z = -5 .. +5
+ top = plate.faces().sort_by(Axis.Z)[-1]
+ with Locations(top):
+ with Locations((20.0, 20.0)):
+ CounterBoreHole(radius=6.6 / 2, counter_bore_radius=11.0 / 2,
+ counter_bore_depth=6.5)
```
+Size `counter_bore_depth` from the **screw head height**, not from habit: an M6 socket head cap
+screw head is 6.0 mm tall, a 1/4-20 head 6.35 mm (`screw_head_height` in the breadboard
+standards). A 4 mm counterbore leaves either head 2 mm proud — do not call that flush. After
+generating, confirm in the snapshot (or a section) that the recess is at the top face and the
+seat ledge exists; both failure modes here pass `is_valid` and the bounding box untouched.
+
Remember that printed holes come out undersize — see `references/fabrication-limits.md`.
## Selectors
@@ -179,9 +256,20 @@ with BuildPart() as ex:
fillet(ex.edges().filter_by(Axis.Z), radius=5.0) # round the vertical corners
```
-**Fillet last, and check the snapshot.** A radius larger than the adjacent feature silently
-consumes it, or throws a kernel error. Fillet radii should be named parameters so they are easy to
-back off.
+**These broad selectors are only safe on a part that is still a plain box.** Once the part has
+pockets, bores, notches, or micro-relief, `filter_by(Axis.Z)` and `group_by(Axis.Z)[-1]` also
+select the edges of those features, and the fillet either throws a kernel error
+(`Failed creating a fillet`, `BRep_API: command not done`) or — worse — succeeds and silently eats
+a wall or a 0.3 mm ridge. Both happen in practice. So:
+
+- Fillet or chamfer the **outer body before adding internal features**, or filter the selection
+ down deliberately (by position, length, or `GeomType`) so only the intended edges remain.
+- Bound the radius with `part.max_fillet(edges)` when the nearby geometry is tight — it returns
+ the largest radius the kernel can actually build on that edge set.
+- Make every fillet/chamfer radius a named parameter, and on a kernel failure back the value off
+ rather than fighting the selector.
+- Then check the snapshot: a consumed feature is obvious in the picture and invisible in
+ `is_valid`.
## Sketch then extrude
@@ -208,9 +296,14 @@ export_stl(part, "part.stl", tolerance=1e-3, angular_tolerance=0.1)
# 2D profile for laser cutting. section() is a module-level operation, NOT a
# method on the shape -- part.section(...) raises AttributeError.
+from build123d.exporters import ColorIndex # NOT exported by `from build123d import *`
+
profile = section(part, Plane.XY.offset(z_mm), mode=Mode.PRIVATE)
+profile = profile.moved(Location((0, 0, -z_mm))) # back to z = 0, or the DXF writer
+ # warns about a non-planar shape
exporter = ExportDXF(unit=Unit.MM)
-exporter.add_shape(profile)
+exporter.add_layer("CUT", color=ColorIndex.RED) # laser shops key power/speed to layers
+exporter.add_shape(profile, layer="CUT")
exporter.write("part.dxf")
```
@@ -249,6 +342,16 @@ some documentation. Access it without parentheses.
- **Builder objects are not parts.** Return `builder.part`, not the builder.
- **`Mode.SUBTRACT` needs an existing body.** Subtracting from an empty context does nothing
silently.
+- **A swept or extruded profile is centred on its path/plane unless you align it.** Sweeping a
+ `Rectangle(w, h)` along a path on a surface leaves half the profile below the surface — a
+ "0.3 mm ridge" that is really 0.15 mm proud. Pass `align=` (and an explicit `x_dir` on the
+ profile plane) so the profile sits where you think it does, then measure the result.
+- **`Curve` has no `.length`.** Sum the edges instead: `sum(e.length for e in curve.edges())`.
+- **The boolean of touching or disjoint solids is empty, not an error.** Depending on the path you
+ get `None`, an empty `Compound`, or a `ShapeList` with no `.volume` — guard before reading
+ `.volume` in any interference check.
+- **`ColorIndex` and `LineType` live in `build123d.exporters`**, not in the top-level namespace;
+ `from build123d import *` does not bring them in, and `add_layer(color=1)` fails.
- The OpenCascade kernel raises assorted exception types. Catch broadly around boolean operations
and report the failure rather than letting a traceback escape.
diff --git a/skills/lab-hardware-cad/references/fabrication-limits.md b/skills/lab-hardware-cad/references/fabrication-limits.md
index 1bead21f..890ca647 100644
--- a/skills/lab-hardware-cad/references/fabrication-limits.md
+++ b/skills/lab-hardware-cad/references/fabrication-limits.md
@@ -22,8 +22,27 @@ Two consequences that catch people:
- **Holes print undersize** on both FDM and SLA. A 6.0 mm modelled hole typically measures under
6.0 mm. Oversize functional bores, or plan to ream them.
- **Internal corners cannot be sharp in milling.** If a milled pocket must accept a square part,
- add corner relief cuts. This is the same problem as the microplate corner radius in
- `references/labware-adapters.md`, from the other direction.
+ add corner relief cuts. (For a part with *rounded* corners the tool radius is harmless as long
+ as it stays at or below the part's minimum corner radius — see the corner-radius rule in
+ `references/labware-adapters.md`.)
+
+### Laser cutting
+
+- **Kerf direction is fixed by the physics, so get it right in the handover.** The beam removes a
+ strip of width k (~0.1–0.3 mm) centred on the drawn line. Cutting on the line therefore makes
+ **holes and internal cutouts come out oversize by ~k, and the part's outer outline undersize by
+ ~k**. Say which convention the DXF uses (on-the-line is the default assumption) and let the shop
+ offset, or offset the geometry yourself and say so — never both.
+- **Put cut geometry on a named layer** (one layer per operation: `CUT`, `ENGRAVE`). Shops key
+ power and speed to layer or colour; geometry on layer 0 forces them to guess.
+- **Cut order matters:** internal features before the outer outline, or the part shifts once it is
+ freed from the sheet.
+- **Sheet stock is not its nominal thickness.** "3 mm" acrylic commonly runs ~2.8–3.2 mm; slots
+ sized for nominal will be loose or tight. For solvent-welded joints prefer **cast** acrylic over
+ extruded — cleaner cut edge, less vapour crazing — and remember alcohols craze acrylic either
+ way (see Chemical, below).
+- Laser-cut edges are sharp and slightly tapered; call out deburring or flame-polishing for
+ anything handled or animal-facing.
## Fits and clearances
diff --git a/skills/lab-hardware-cad/references/labware-adapters.md b/skills/lab-hardware-cad/references/labware-adapters.md
index db1f15d4..a28aa825 100644
--- a/skills/lab-hardware-cad/references/labware-adapters.md
+++ b/skills/lab-hardware-cad/references/labware-adapters.md
@@ -38,15 +38,30 @@ fit_clearance_mm = 0.40 # per side; FDM, see fabrication-limits.md
pocket_l_mm = plate_l_mm + plate_tol_mm + 2 * fit_clearance_mm # 128.81
```
-**2. The corner radius tolerance is enormous.** 3.18 ±1.6 mm means a real plate corner is anywhere
-from 1.58 to 4.78 mm. A pocket with sharp internal corners will not seat a plate with 4.78 mm
-corners. Cut the pocket corners to at least the maximum, 4.78 mm — or relieve them entirely with a
-corner slot, which is more forgiving and prints better than a large internal fillet.
+**2. The corner radius tolerance is enormous — and it bounds the pocket radius from above,
+not below.** 3.18 ±1.6 mm means a real plate corner is anywhere from 1.58 to 4.78 mm. Get the
+direction right: a plate corner is **convex**, a pocket fillet is **concave material bulging
+inward**, so a *sharp* internal pocket corner always clears a rounded plate — the unused corner is
+empty space. It is a pocket fillet *larger* than the plate's corner radius that binds: the bulge
+occupies space the plate needs. Sizing the fillet to the plate's maximum corner radius is
+therefore exactly backwards — it binds every plate except those at the top of the corner
+tolerance.
+
+The safe options, best first:
+
+- **Corner relief** (a small slot or bore cut past each corner) — always clears, prints and mills
+ cleanly, and is the standard fix.
+- **Fillet no larger than the plate's minimum corner radius** (1.58 mm for SLAS plates) — clears
+ every conforming plate in every position.
+- A larger fillet only if `R ≤ r_min + ~3.4 × per-side clearance` — the geometry only recovers the
+ intrusion when the plate stays roughly centred, so treat this as a last resort and say so.
```python
with BuildPart() as pocket:
# ... pocket geometry ...
- fillet(pocket.edges().filter_by(Axis.Z).group_by(Axis.Z)[-1], radius=5.0)
+ # relief bores just outside each pocket corner: clears any conforming corner radius
+ with Locations(*corner_relief_centres()):
+ Hole(radius=2.0)
```
**3. Height depends on the flange, not just the plate.** ANSI/SLAS 3 standardises three flange
diff --git a/skills/lab-hardware-cad/references/microfluidics.md b/skills/lab-hardware-cad/references/microfluidics.md
index a81e366d..d782c5d0 100644
--- a/skills/lab-hardware-cad/references/microfluidics.md
+++ b/skills/lab-hardware-cad/references/microfluidics.md
@@ -14,8 +14,16 @@ called "the chip":
| **Directly-fabricated chip** | **Recessed grooves or enclosed lumens** | Printed, milled, or laser-cut directly |
A model that is correct as a chip is exactly wrong as a mold. Put the polarity in the module
-docstring and in a named parameter, and **verify it in the snapshot** — inverted polarity is
-invisible in the bounding box, the volume, and the validity check, and obvious in the render.
+docstring and in a named parameter, and **verify it numerically, not by eye**: inverted polarity
+is invisible in the bounding box, the volume, and the validity check — and at typical channel
+scale (a 0.3 mm ridge on a 40+ mm part) it is invisible in an outline render too, because raised
+and recessed features draw the same edges. Declare it as geometry checks instead
+(`references/build123d-patterns.md`): a `material` region where the ridge must stand above the
+casting surface, and a `clear` region over the rest of that layer — a groove fails the first,
+an inverted full-area layer fails the second. For a one-off question,
+`check.py probe <step> --box ... --expect material` answers it without editing the model. State
+the measured relief height in the report. Use the snapshot for layout and connectivity, which
+it does show well.
```python
polarity = "mold" # "mold" = raised ridges; "chip" = recessed grooves
diff --git a/skills/lab-hardware-cad/references/optomechanics.md b/skills/lab-hardware-cad/references/optomechanics.md
index b8574cc6..9163b9dd 100644
--- a/skills/lab-hardware-cad/references/optomechanics.md
+++ b/skills/lab-hardware-cad/references/optomechanics.md
@@ -65,9 +65,11 @@ The dominant convention for small free-space assemblies:
- Standard cage plates are 0.35 inch (8.9 mm) thick.
For a custom cage plate: place four bores on a 30 mm square, put the aperture at the **centroid**
-of those four bores, and bore them slightly oversize — around 6.1 mm as a starting point, more for
-FDM. A cage plate that binds on the rods is worse than useless because it transmits stress into
-the whole assembly.
+of those four bores, and bore them for a free-sliding fit **at your process's clearance**
+(fabrication-limits.md): about 6.2 mm CNC, 6.4 mm SLA, 6.8 mm FDM. 6.1 mm is a reamed-metal
+number — printed bores come out undersize, and four bores on a common square over-constrain each
+other, so tighter is not better here. A cage plate that binds on the rods is worse than useless
+because it transmits stress into the whole assembly.
Cage plates stack along the rods, so a custom plate's thickness directly consumes optical path
length. Budget it.
diff --git a/skills/lab-hardware-cad/references/validation.md b/skills/lab-hardware-cad/references/validation.md
index 528c2826..fae57579 100644
--- a/skills/lab-hardware-cad/references/validation.md
+++ b/skills/lab-hardware-cad/references/validation.md
@@ -9,9 +9,12 @@ it catches, because a checklist without consequences gets skipped.
*Catches: a stale artifact that no longer matches the code you just edited.*
- [ ] A `*.manifest.json` exists alongside it, and its `source.sha256` matches the model file.
*Catches: silently editing an exported STEP, which makes the design unreproducible.*
-- [ ] The manifest's `interfaces` block is non-empty and its values are the ones the model
- computed after any `--param` override.
- *Catches: a static `INTERFACES` list frozen at import, recording pre-override numbers.*
+- [ ] The manifest's `interfaces` block lists every dimension a bundled standard covers, and its
+ values are the ones the model computed after any `--param` override. Empty is correct only
+ when nothing on the part mates with a bundled standard — and then every interface dimension
+ is named as unchecked in the report instead.
+ *Catches: a static `INTERFACES` list frozen at import, recording pre-override numbers; and
+ an interface that silently escaped checking.*
- [ ] Every parameter in the model is named with units.
*Catches: the bare `12.7` nobody can later identify as half an inch.*
@@ -28,9 +31,16 @@ python scripts/gen.py part_model.py --outdir out/
the body.*
- [ ] Volume is plausible for the part's size and wall thickness.
*Catches: a cavity modelled solid, or a subtract that did nothing.*
+- [ ] Every geometric requirement in the request is declared in `checks()` and passes — clear
+ regions for what must pass through or fit in, material regions for what must remain,
+ bbox bounds for stated size limits.
+ *Catches: a recess that swallowed its screw seat, a pocket the mating part cannot enter,
+ a beam corridor with a wall in it, a feature a fillet silently ate — all invisible to
+ `is_valid` and the bounding box.*
```bash
python scripts/check.py facts out/part.step
+python scripts/check.py geometry out/part.step --model part_model.py
```
## 3. Interfaces
diff --git a/skills/lab-hardware-cad/scripts/_common.py b/skills/lab-hardware-cad/scripts/_common.py
index c4322797..82adf4be 100644
--- a/skills/lab-hardware-cad/scripts/_common.py
+++ b/skills/lab-hardware-cad/scripts/_common.py
@@ -13,6 +13,10 @@ import sys
from pathlib import Path
from typing import Any
+# Model files are imported from the user's working directory; leaving compiled
+# bytecode there puts a __pycache__ next to the deliverables.
+sys.dont_write_bytecode = True
+
SKILL_ROOT = Path(__file__).resolve().parent.parent
STANDARDS_PATH = SKILL_ROOT / "assets" / "standards.json"
@@ -228,6 +232,327 @@ def normalise_interfaces(declared: Any) -> list[dict]:
return entries
+def model_checks(module) -> list[dict]:
+ """Collect the geometry checks a model declares about itself.
+
+ A model exposes a ``checks()`` callable (or a ``CHECKS`` list) of go/no-go
+ gauge assertions evaluated against the BUILT solid -- unlike ``interfaces()``,
+ which only compares declared numbers against the standards database. Each
+ entry asserts one of:
+
+ clear - a region must contain no material (a screw shaft, a beam
+ corridor, a gauge part dropping into a pocket)
+ material - a region must contain material (a ridge, a ledge, a boss)
+ bbox_* - a bounding-box measure must sit inside [min, max]
+
+ See ``normalise_checks`` for the entry schema.
+ """
+ declared = getattr(module, "checks", None)
+ if callable(declared):
+ declared = declared()
+ elif declared is None:
+ declared = getattr(module, "CHECKS", None)
+ if declared is None:
+ return []
+ return normalise_checks(declared)
+
+
+_MEASURE_NAMES = ("bbox_x", "bbox_y", "bbox_z", "bbox_min", "bbox_mid", "bbox_max")
+
+
+def _normalise_region(raw: dict, index: int) -> dict:
+ """Validate one region spec: {"cylinder": dia, ...} or {"box": (dx,dy,dz), ...}."""
+ if "cylinder" in raw:
+ try:
+ dia = float(raw["cylinder"])
+ except (TypeError, ValueError) as exc:
+ raise LabCadError(f"CHECKS[{index}]: cylinder diameter must be a number") from exc
+ if dia <= 0:
+ raise LabCadError(f"CHECKS[{index}]: cylinder diameter must be > 0")
+ axis = str(raw.get("axis", "z")).lower()
+ if axis not in ("x", "y", "z"):
+ raise LabCadError(f"CHECKS[{index}]: axis must be 'x', 'y', or 'z', got {axis!r}")
+ at = raw.get("at", [(0.0, 0.0)])
+ positions = []
+ for pos in at:
+ try:
+ a, b = (float(pos[0]), float(pos[1]))
+ except (TypeError, ValueError, IndexError) as exc:
+ raise LabCadError(
+ f"CHECKS[{index}]: cylinder 'at' entries are 2D positions in the "
+ "plane perpendicular to the axis (axis z: (x, y); axis x: (y, z); "
+ f"axis y: (x, z)), got {pos!r}"
+ ) from exc
+ positions.append([a, b])
+ span = raw.get("span")
+ if span is not None:
+ try:
+ span = [float(span[0]), float(span[1])]
+ except (TypeError, ValueError, IndexError) as exc:
+ raise LabCadError(f"CHECKS[{index}]: span must be (start, end) along the axis") from exc
+ return {"shape": "cylinder", "dia": dia, "axis": axis, "at": positions, "span": span}
+ if "box" in raw:
+ size = raw["box"]
+ try:
+ size = [float(size[0]), float(size[1]), float(size[2])]
+ except (TypeError, ValueError, IndexError) as exc:
+ raise LabCadError(f"CHECKS[{index}]: box must be (dx, dy, dz)") from exc
+ if min(size) <= 0:
+ raise LabCadError(f"CHECKS[{index}]: box dimensions must be > 0")
+ at = raw.get("at", [(0.0, 0.0, 0.0)])
+ positions = []
+ for pos in at:
+ try:
+ positions.append([float(pos[0]), float(pos[1]), float(pos[2])])
+ except (TypeError, ValueError, IndexError) as exc:
+ raise LabCadError(
+ f"CHECKS[{index}]: box 'at' entries are 3D centres (x, y, z), got {pos!r}"
+ ) from exc
+ return {"shape": "box", "size": size, "at": positions}
+ raise LabCadError(
+ f"CHECKS[{index}]: a region needs 'cylinder': diameter or 'box': (dx, dy, dz)"
+ )
+
+
+def normalise_checks(declared: Any) -> list[dict]:
+ """Validate and fill in defaults for declared geometry-check entries.
+
+ Raw entry forms::
+
+ {"feature": "M6 screws pass", "clear": {"cylinder": 6.6, "axis": "z",
+ "at": [(37.5, 37.5), (-37.5, 37.5), (37.5, -37.5), (-37.5, -37.5)]}}
+ {"feature": "plate at MMC drops in", "clear": {"box": (128.01, 85.73, 6.0),
+ "at": [(0.0, 0.0, 7.0)]}}
+ {"feature": "ridge stands proud", "material": {"box": (40.0, 0.8, 0.28),
+ "at": [(0.0, 0.0, 4.15)]}, "min_mm3": 5.0}
+ {"feature": "clears the turret", "bbox_z": {"max": 15.0}}
+
+ A cylinder with no ``span`` runs through the whole part. ``tol_mm3`` (clear,
+ default 0.01) and ``min_mm3`` (material, default 0.01) tune the pass volume.
+ """
+ if isinstance(declared, dict):
+ declared = [declared]
+ if not isinstance(declared, (list, tuple)):
+ raise LabCadError("CHECKS must be a list of dicts")
+
+ entries: list[dict] = []
+ for index, raw in enumerate(declared):
+ if not isinstance(raw, dict):
+ raise LabCadError(f"CHECKS[{index}] must be a dict, got {type(raw).__name__}")
+ kinds = [k for k in ("clear", "material", *_MEASURE_NAMES) if k in raw]
+ if len(kinds) != 1:
+ raise LabCadError(
+ f"CHECKS[{index}] needs exactly one of 'clear', 'material', or a bbox "
+ f"measure ({', '.join(_MEASURE_NAMES)}), got {kinds or 'none'}"
+ )
+ kind = kinds[0]
+ entry: dict = {"feature": str(raw.get("feature", kind))}
+ if kind in ("clear", "material"):
+ region = raw[kind]
+ if not isinstance(region, dict):
+ raise LabCadError(f"CHECKS[{index}]: {kind!r} must be a region dict")
+ entry["kind"] = kind
+ entry["region"] = _normalise_region(region, index)
+ entry["tol_mm3"] = float(raw.get("tol_mm3", 0.01))
+ entry["min_mm3"] = float(raw.get("min_mm3", 0.01))
+ else:
+ bounds = raw[kind]
+ if not isinstance(bounds, dict) or not (
+ "min" in bounds or "max" in bounds
+ ):
+ raise LabCadError(
+ f"CHECKS[{index}]: {kind!r} needs a dict with 'min' and/or 'max' in mm"
+ )
+ entry["kind"] = "measure"
+ entry["measure"] = kind
+ entry["min"] = None if bounds.get("min") is None else float(bounds["min"])
+ entry["max"] = None if bounds.get("max") is None else float(bounds["max"])
+ entries.append(entry)
+ return entries
+
+
+def intersection_volume(shape_a, shape_b) -> float:
+ """Volume of the boolean intersection, tolerant of the kernel's return types.
+
+ Touching or disjoint solids yield ``None``, an empty ``Compound``, or a
+ ``ShapeList`` with no ``.volume`` depending on the path taken; all of those
+ count as zero.
+ """
+ try:
+ result = shape_a & shape_b
+ except Exception: # noqa: BLE001 - kernel raises assorted OCCT errors
+ try:
+ result = shape_a.intersect(shape_b)
+ except Exception as exc: # noqa: BLE001
+ raise LabCadError(f"boolean intersection failed: {exc}") from exc
+ if result is None:
+ return 0.0
+ volume = getattr(result, "volume", None)
+ if volume is not None:
+ return float(volume)
+ return float(sum(float(getattr(item, "volume", 0.0) or 0.0) for item in result))
+
+
+def _region_solids(build123d, region: dict, part_bbox) -> list:
+ """Materialise a region spec into one solid per 'at' position."""
+ solids = []
+ if region["shape"] == "box":
+ dx, dy, dz = region["size"]
+ for x, y, z in region["at"]:
+ solids.append(build123d.Pos(x, y, z) * build123d.Box(dx, dy, dz))
+ return solids
+
+ dia = region["dia"]
+ axis = region["axis"]
+ span = region["span"]
+ if span is None:
+ lo = {"x": part_bbox.min.X, "y": part_bbox.min.Y, "z": part_bbox.min.Z}[axis] - 2.0
+ hi = {"x": part_bbox.max.X, "y": part_bbox.max.Y, "z": part_bbox.max.Z}[axis] + 2.0
+ else:
+ lo, hi = sorted(span)
+ length = hi - lo
+ mid = (hi + lo) / 2.0
+ for a, b in region["at"]:
+ cyl = build123d.Cylinder(dia / 2.0, length)
+ if axis == "z":
+ solid = build123d.Pos(a, b, mid) * cyl
+ elif axis == "x":
+ solid = build123d.Pos(mid, a, b) * build123d.Rot(0, 90, 0) * cyl
+ else: # y; 'at' is (x, z)
+ solid = build123d.Pos(a, mid, b) * build123d.Rot(90, 0, 0) * cyl
+ solids.append(solid)
+ return solids
+
+
+def evaluate_checks(part, declared: list[dict]) -> list[dict]:
+ """Evaluate normalised geometry checks against a built solid."""
+ build123d = require_build123d()
+ facts = shape_facts(part)
+ bbox = part.bounding_box()
+ results = []
+ for entry in declared:
+ result = dict(entry)
+ if entry["kind"] == "measure":
+ actual = measure(facts, entry["measure"])
+ ok = True
+ if entry["min"] is not None and actual < entry["min"] - 1e-9:
+ ok = False
+ if entry["max"] is not None and actual > entry["max"] + 1e-9:
+ ok = False
+ result.update({"actual_mm": round(actual, 4), "pass": ok})
+ else:
+ volumes = [
+ round(intersection_volume(part, solid), 4)
+ for solid in _region_solids(build123d, entry["region"], bbox)
+ ]
+ total = round(sum(volumes), 4)
+ if entry["kind"] == "clear":
+ ok = all(v <= entry["tol_mm3"] for v in volumes)
+ else:
+ ok = all(v >= entry["min_mm3"] for v in volumes)
+ result.update({"volumes_mm3": volumes, "total_mm3": total, "pass": ok})
+ results.append(result)
+ return results
+
+
+def format_check_result(item: dict) -> list[str]:
+ """Human-readable lines for one evaluated geometry-check result."""
+ mark = "PASS" if item["pass"] else "FAIL"
+ if item["kind"] == "measure":
+ bounds = []
+ if item.get("min") is not None:
+ bounds.append(f">= {item['min']:.3f}")
+ if item.get("max") is not None:
+ bounds.append(f"<= {item['max']:.3f}")
+ return [f" [{mark}] {item['feature']:<38} {item['measure']} "
+ f"{item['actual_mm']:.3f} mm expected {' and '.join(bounds)}"]
+ region = item["region"]
+ if region["shape"] == "cylinder":
+ where = f"cyl d{region['dia']:g} axis {region['axis']} x{len(region['at'])}"
+ else:
+ dx, dy, dz = region["size"]
+ where = f"box {dx:g}x{dy:g}x{dz:g} x{len(region['at'])}"
+ if item["kind"] == "clear":
+ detail = f"intruding {item['total_mm3']:.3f} mm^3 (tol {item['tol_mm3']:g}/position)"
+ else:
+ detail = (f"material {item['total_mm3']:.3f} mm^3 "
+ f"(min {item['min_mm3']:g}/position)")
+ lines = [f" [{mark}] {item['feature']:<38} {item['kind']} {where} {detail}"]
+ if not item["pass"]:
+ lines.append(f" per position (mm^3): {item['volumes_mm3']}")
+ return lines
+
+
+def cylinder_census(part) -> list[dict]:
+ """Every cylindrical face in the part: radius, axis, extent, sweep.
+
+ This is the instrument for reconciling what a render appears to show with
+ what the solid actually contains: a bore is a ~360 degree sweep, an edge
+ fillet ~90, and a counterbore is two coaxial full sweeps stacked along the
+ axis with different radii.
+ """
+ build123d = require_build123d()
+ from OCP.BRepAdaptor import BRepAdaptor_Surface # noqa: PLC0415
+ import math # noqa: PLC0415
+
+ rows = []
+ for face in part.faces():
+ if face.geom_type != build123d.GeomType.CYLINDER:
+ continue
+ cyl = BRepAdaptor_Surface(face.wrapped).Cylinder()
+ ax = cyl.Axis()
+ loc, direction = ax.Location(), ax.Direction()
+ d = (direction.X(), direction.Y(), direction.Z())
+ point = (loc.X(), loc.Y(), loc.Z())
+
+ axis_name = None
+ for name, vec in (("x", (1, 0, 0)), ("y", (0, 1, 0)), ("z", (0, 0, 1))):
+ if abs(abs(d[0] * vec[0] + d[1] * vec[1] + d[2] * vec[2]) - 1.0) < 1e-6:
+ axis_name = name
+ # Canonicalise to the +axis direction so spans read in real coordinates
+ # instead of sign-flipping for bores cut top-down.
+ if axis_name is not None:
+ d = {"x": (1, 0, 0), "y": (0, 1, 0), "z": (0, 0, 1)}[axis_name]
+
+ bb = face.bounding_box()
+ corners = [
+ (x, y, z)
+ for x in (bb.min.X, bb.max.X)
+ for y in (bb.min.Y, bb.max.Y)
+ for z in (bb.min.Z, bb.max.Z)
+ ]
+ proj = [x * d[0] + y * d[1] + z * d[2] for x, y, z in corners]
+ extent = max(proj) - min(proj)
+ radius = float(cyl.Radius())
+ sweep = (
+ math.degrees(float(face.area) / (radius * extent)) if radius * extent > 1e-12 else 0.0
+ )
+ # In-plane position, ordered like probe positions: axis z -> (x, y),
+ # axis x -> (y, z), axis y -> (x, z). The axis point's own component
+ # along the axis is arbitrary, so it is not reported for aligned axes.
+ if axis_name == "z":
+ at = [round(point[0], 4), round(point[1], 4)]
+ elif axis_name == "x":
+ at = [round(point[1], 4), round(point[2], 4)]
+ elif axis_name == "y":
+ at = [round(point[0], 4), round(point[2], 4)]
+ else:
+ at = [round(c, 4) for c in point]
+ rows.append({
+ "radius_mm": round(radius, 4),
+ "diameter_mm": round(2 * radius, 4),
+ "axis": axis_name or [round(c, 4) for c in d],
+ "at_mm": at,
+ "extent_mm": round(extent, 4),
+ "span_min_mm": round(min(proj), 4),
+ "span_max_mm": round(max(proj), 4),
+ "sweep_deg": round(sweep, 1),
+ "full": sweep >= 355.0,
+ })
+ rows.sort(key=lambda r: (str(r["axis"]), r["at_mm"], r["radius_mm"]))
+ return rows
+
+
def load_shape(path: Path):
"""Load a STEP or STL file, or build a model, into a build123d shape."""
path = Path(path)
diff --git a/skills/lab-hardware-cad/scripts/check.py b/skills/lab-hardware-cad/scripts/check.py
index 5010a9ea..d3b7f860 100644
--- a/skills/lab-hardware-cad/scripts/check.py
+++ b/skills/lab-hardware-cad/scripts/check.py
@@ -5,6 +5,9 @@
python scripts/check.py standards --show slas-microplate-footprint
python scripts/check.py facts out/carrier.step
python scripts/check.py interfaces out/carrier.manifest.json
+ python scripts/check.py geometry out/carrier.step --model carrier_model.py
+ python scripts/check.py probe out/carrier.step --cyl 6.6 --at 37.5,37.5 --at -37.5,37.5
+ python scripts/check.py bores out/carrier.step
python scripts/check.py fit --standard slas-microplate-footprint \
--intent envelope --clearance 0.8 --value footprint_length=128.81
python scripts/check.py clearance out/carrier.step out/lid.step --min 0.3
@@ -25,15 +28,21 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from _common import ( # noqa: E402
LabCadError,
+ cylinder_census,
emit,
eprint,
+ evaluate_checks,
+ format_check_result,
get_standard,
import_model,
+ intersection_volume,
load_shape,
load_standards,
main_guard,
measure,
+ model_checks,
model_interfaces,
+ normalise_checks,
normalise_interfaces,
shape_facts,
)
@@ -104,20 +113,30 @@ def cmd_facts(args) -> int:
def _evaluate(
entry, dimension: str, actual: float, offset: float, measure_label: str, intent: str
) -> dict:
- """Compare one measured dimension against a standard.
+ """Compare one declared dimension against a standard.
Two intents, because they are different questions:
``match`` - this part must itself conform to the standard. Symmetric band
- around nominal, widened by ``offset``.
+ around nominal, widened (never shifted) by ``offset``.
``envelope`` - this feature must accept ANY conforming part (a pocket, bore,
or slot). One-sided minimum at maximum material condition plus
the clearance. Designing such a feature to nominal fits only
the smallest half of conforming parts.
+
+ ``offset`` must be non-negative: a negative clearance would let a declaration
+ move its own acceptance band and certify a nonconforming value.
"""
if dimension not in entry["dimensions"]:
known = ", ".join(sorted(entry["dimensions"]))
raise LabCadError(f"unknown dimension {dimension!r}. Available: {known}")
+ if offset < 0:
+ raise LabCadError(
+ f"{dimension}: clearance must be >= 0, got {offset}. A clearance widens the "
+ "acceptance band; it cannot shift it. If the feature is deliberately "
+ "undersized, say so in the report instead of encoding it as a negative "
+ "clearance."
+ )
dim = entry["dimensions"][dimension]
nominal = float(dim["nominal"])
tol_plus = float(dim.get("tol_plus", 0.0))
@@ -129,7 +148,7 @@ def _evaluate(
passed = actual >= low - 1e-9
headroom = round(actual - low, 4)
else:
- low = nominal - tol_minus + offset
+ low = nominal - tol_minus - offset
high = nominal + tol_plus + offset
passed = low - 1e-9 <= actual <= high + 1e-9
headroom = None
@@ -240,22 +259,9 @@ def _declared_interfaces(target: Path) -> tuple[list[dict], str]:
payload = json.loads(target.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise LabCadError(f"{target} is not valid JSON: {exc}") from exc
- declared = payload.get("interfaces")
- if not declared:
- raise LabCadError(
- f"{target.name} records no declared interfaces. Add an INTERFACES list "
- "to the model (see references/build123d-patterns.md) and rerun gen.py."
- )
- return normalise_interfaces(declared), "manifest"
+ return normalise_interfaces(payload.get("interfaces") or []), "manifest"
if suffix == ".py":
- declared = model_interfaces(import_model(target))
- if not declared:
- raise LabCadError(
- f"{target.name} declares no INTERFACES. Add an INTERFACES list naming "
- "each standard, dimension, and computed value the part must satisfy "
- "(see references/build123d-patterns.md)."
- )
- return declared, "model"
+ return model_interfaces(import_model(target)), "model"
raise LabCadError(
f"unsupported input {suffix!r}. Pass a *.manifest.json written by gen.py, or a "
"*_model.py."
@@ -265,12 +271,28 @@ def _declared_interfaces(target: Path) -> tuple[list[dict], str]:
def cmd_interfaces(args) -> int:
"""Check every interface a model declares about itself.
- This is the check that gates a fabrication decision, because the dimensions
- that have to be right are almost always internal features the outer bounding
- box cannot see.
+ This verifies the DECLARED numbers against the standards database: it catches
+ a transcribed dimension, the wrong standard, and nominal-instead-of-MMC
+ sizing. It does not measure the built geometry -- ``facts`` and the snapshot
+ do that -- so a passing result here is necessary, not sufficient.
+
+ A model whose part mates with nothing in the bundled database correctly
+ declares no interfaces; that is a passing state, not an error. Every such
+ unchecked dimension must then be named in the report.
"""
declared, source = _declared_interfaces(args.target)
+ if not declared:
+ payload = {"target": str(args.target), "source": source, "checks": [], "pass": True}
+ emit(payload, args.as_json, (
+ f"{args.target.name}: 0 declared interfaces - nothing in this part mates "
+ "with a bundled standard.\n"
+ "That is fine IF it is true. Do not invent a declaration to fill the gap; "
+ "instead name every interface dimension and its source (user spec, vendor "
+ "drawing, measurement) as UNCHECKED in the report."
+ ))
+ return 0
+
results = []
for entry in declared:
standard = get_standard(entry["standard"])
@@ -315,11 +337,134 @@ def cmd_interfaces(args) -> int:
)
if not item["verified_source"]:
lines.append(" WARNING: standard entry is not verified against the document.")
- lines.append("Reminder: a passing interface check is not a passing part. Run snapshot.py.")
+ lines.append(
+ "Note: this checks the values the model DECLARED, not the built geometry. "
+ "A declaration computed from the same constants it is checked against will "
+ "pass with zero headroom by construction. Run check.py facts and snapshot.py "
+ "on the exported STEP to verify the geometry itself."
+ )
+ emit(payload, args.as_json, "\n".join(lines))
+ return 0 if passed else 1
+
+
+def cmd_geometry(args) -> int:
+ """Evaluate a model's declared geometry checks against the built solid.
+
+ Unlike ``interfaces``, which compares declared numbers against the standards
+ database, this measures the geometry itself: material really is absent from
+ every declared clear region, present in every material region, and the
+ bounding box sits inside its declared bounds.
+ """
+ target = args.target
+ if target.suffix.lower() == ".py":
+ module = import_model(target)
+ declared = model_checks(module)
+ part = load_shape(target)
+ geometry_source = target.name
+ else:
+ if args.model is None:
+ raise LabCadError(
+ "checking a STEP needs the model that declares the checks: "
+ "check.py geometry out/part.step --model part_model.py"
+ )
+ declared = model_checks(import_model(args.model))
+ part = load_shape(target)
+ geometry_source = target.name
+
+ if not declared:
+ emit({"target": str(target), "checks": [], "pass": True}, args.as_json, (
+ f"{target.name}: no declared geometry checks.\n"
+ "Declare a checks() function for every geometric requirement in the "
+ "request - clearance holes, keep-out corridors, a gauge part that must "
+ "drop into a pocket, a feature that must stand proud, a size limit. "
+ "See references/build123d-patterns.md."
+ ))
+ return 0
+
+ results = evaluate_checks(part, declared)
+ passed = all(item["pass"] for item in results)
+ payload = {"target": str(target), "checks": results, "pass": passed}
+
+ lines = [f"{geometry_source}: {len(results)} geometry check(s), measured from the solid"]
+ for item in results:
+ lines.extend(format_check_result(item))
+ if not passed:
+ lines.append("Fix the model source and regenerate; never patch the STEP.")
emit(payload, args.as_json, "\n".join(lines))
return 0 if passed else 1
+def cmd_probe(args) -> int:
+ """One ad-hoc region probe against a solid, without editing the model."""
+ if (args.cyl is None) == (args.box is None):
+ raise LabCadError("pass exactly one of --cyl DIA or --box DX,DY,DZ")
+
+ region: dict = {}
+ if args.cyl is not None:
+ region["cylinder"] = args.cyl
+ region["axis"] = args.axis
+ if args.span:
+ region["span"] = _parse_floats(args.span, 2, "--span")
+ region["at"] = [_parse_floats(a, 2, "--at") for a in (args.at or ["0,0"])]
+ else:
+ region["box"] = _parse_floats(args.box, 3, "--box")
+ region["at"] = [_parse_floats(a, 3, "--at") for a in (args.at or ["0,0,0"])]
+
+ entry = {"feature": args.feature or f"probe ({args.expect})", args.expect: region}
+ if args.expect == "material" and args.min_mm3 is not None:
+ entry["min_mm3"] = args.min_mm3
+ if args.expect == "clear" and args.tol_mm3 is not None:
+ entry["tol_mm3"] = args.tol_mm3
+
+ part = load_shape(args.target)
+ results = evaluate_checks(part, normalise_checks([entry]))
+ payload = {"target": str(args.target), "checks": results, "pass": results[0]["pass"]}
+ emit(payload, args.as_json, "\n".join(
+ [f"{args.target.name}: probe"] + format_check_result(results[0])
+ ))
+ return 0 if results[0]["pass"] else 1
+
+
+def _parse_floats(raw: str, count: int, flag: str) -> list[float]:
+ parts = [p for p in raw.replace(" ", "").split(",") if p]
+ if len(parts) != count:
+ raise LabCadError(f"{flag} expects {count} comma-separated numbers, got {raw!r}")
+ try:
+ return [float(p) for p in parts]
+ except ValueError as exc:
+ raise LabCadError(f"{flag}: {raw!r} is not numeric") from exc
+
+
+def cmd_bores(args) -> int:
+ """List every cylindrical face: the census for reconciling render vs solid."""
+ part = load_shape(args.target)
+ rows = cylinder_census(part)
+ payload = {"target": str(args.target), "cylindrical_faces": rows}
+
+ if not rows:
+ emit(payload, args.as_json, f"{args.target.name}: no cylindrical faces.")
+ return 0
+ lines = [
+ f"{args.target.name}: {len(rows)} cylindrical face(s). Full ~360 degree sweeps "
+ "are bores/bosses; ~90 degree sweeps are edge fillets.",
+ ]
+ for r in rows:
+ axis = r["axis"] if isinstance(r["axis"], str) else str(r["axis"])
+ at = ", ".join(f"{v:g}" for v in r["at_mm"])
+ kind = "full" if r["full"] else f"{r['sweep_deg']:g} deg"
+ lines.append(
+ f" d {r['diameter_mm']:>8.3f} axis {axis:<12} at ({at})"
+ f" span {r['span_min_mm']:g}..{r['span_max_mm']:g} {kind}"
+ )
+ lines.append(
+ "Reconcile this against the model's intent before trusting a render: a missing "
+ "diameter or an unexpected span here is a real feature error, whatever the "
+ "picture appears to show."
+ )
+ emit(payload, args.as_json, "\n".join(lines))
+ return 0
+
+
def _min_distance(shape_a, shape_b) -> float | None:
for method in ("distance_to", "distance"):
func = getattr(shape_a, method, None)
@@ -337,37 +482,15 @@ def _min_distance(shape_a, shape_b) -> float | None:
return None
-def _volume_of(result) -> float:
- """Total volume of an intersection result.
-
- ``Shape.intersect()`` returns a ShapeList with no ``.volume`` in build123d
- 0.11.1, while the ``&`` operator returns a Solid that has one. Handle both.
- """
- if result is None:
- return 0.0
- volume = getattr(result, "volume", None)
- if volume is not None:
- return float(volume)
- total = 0.0
- for item in result:
- item_volume = getattr(item, "volume", None)
- if item_volume:
- total += float(item_volume)
- return total
-
-
def cmd_clearance(args) -> int:
shape_a = load_shape(args.a)
shape_b = load_shape(args.b)
overlap_volume = 0.0
try:
- overlap_volume = _volume_of(shape_a & shape_b)
- except Exception: # noqa: BLE001 - kernel raises assorted OCCT errors
- try:
- overlap_volume = _volume_of(shape_a.intersect(shape_b))
- except Exception as exc: # noqa: BLE001
- eprint(f"warning: intersection test failed ({exc}); relying on distance only")
+ overlap_volume = intersection_volume(shape_a, shape_b)
+ except LabCadError as exc:
+ eprint(f"warning: {exc}; relying on distance only")
interferes = overlap_volume > 1e-6
gap = None if interferes else _min_distance(shape_a, shape_b)
@@ -437,6 +560,55 @@ def main() -> int:
help="a *.manifest.json written by gen.py, or a *_model.py")
p_int.set_defaults(func=cmd_interfaces)
+ p_geo = sub.add_parser(
+ "geometry",
+ help="evaluate the model's declared geometry checks against the built solid",
+ description="Run every checks() entry -- clear regions, material regions, bbox "
+ "bounds -- as boolean gauges against the actual geometry. This is "
+ "the measured counterpart to `interfaces`, which only compares "
+ "declared numbers.",
+ )
+ p_geo.add_argument("target", type=Path, help="a *_model.py, or a STEP with --model")
+ p_geo.add_argument("--model", type=Path, default=None,
+ help="the *_model.py declaring checks(), when target is a STEP")
+ p_geo.set_defaults(func=cmd_geometry)
+
+ p_probe = sub.add_parser(
+ "probe",
+ help="ad-hoc region gauge: is this cylinder/box clear of (or filled with) material?",
+ )
+ p_probe.add_argument("target", type=Path, help="STEP, STL, or *_model.py")
+ p_probe.add_argument("--cyl", type=float, metavar="DIA",
+ help="cylindrical gauge of this diameter in mm")
+ p_probe.add_argument("--box", metavar="DX,DY,DZ", help="box gauge, size in mm")
+ p_probe.add_argument("--axis", choices=("x", "y", "z"), default="z",
+ help="cylinder axis (default: z); runs through the part unless "
+ "--span is given")
+ p_probe.add_argument("--at", action="append", metavar="A,B[,C]",
+ help="position, repeatable. Cylinder: 2D in the plane "
+ "perpendicular to the axis (axis z: x,y; axis x: y,z; "
+ "axis y: x,z). Box: 3D centre x,y,z.")
+ p_probe.add_argument("--span", metavar="A,B",
+ help="cylinder extent along its axis (default: through the part)")
+ p_probe.add_argument("--expect", choices=("clear", "material"), default="clear",
+ help="'clear': no material in the region (default); "
+ "'material': the region must contain material")
+ p_probe.add_argument("--tol-mm3", type=float, default=None,
+ help="max intruding volume per position for 'clear' (default 0.01)")
+ p_probe.add_argument("--min-mm3", type=float, default=None,
+ help="min material volume per position for 'material' (default 0.01)")
+ p_probe.add_argument("--feature", help="label for the output")
+ p_probe.set_defaults(func=cmd_probe)
+
+ p_bores = sub.add_parser(
+ "bores",
+ help="census of every cylindrical face: diameter, axis, span, sweep",
+ description="The reconciliation instrument for step 6: compare what the render "
+ "appears to show against what the solid actually contains.",
+ )
+ p_bores.add_argument("target", type=Path, help="STEP, STL, or *_model.py")
+ p_bores.set_defaults(func=cmd_bores)
+
p_fit = sub.add_parser("fit", help="check one dimension against a standard by hand")
p_fit.add_argument("target", type=Path, nargs="?",
help="STEP, STL, or *_model.py; omit when using --value")
diff --git a/skills/lab-hardware-cad/scripts/gen.py b/skills/lab-hardware-cad/scripts/gen.py
index 47d275e0..540c86b1 100644
--- a/skills/lab-hardware-cad/scripts/gen.py
+++ b/skills/lab-hardware-cad/scripts/gen.py
@@ -24,8 +24,11 @@ from _common import ( # noqa: E402
LabCadError,
emit,
eprint,
+ evaluate_checks,
+ format_check_result,
import_model,
main_guard,
+ model_checks,
model_interfaces,
model_parameters,
parse_params,
@@ -67,8 +70,19 @@ def _export_dxf(part, path: Path, build123d, height: float | None) -> float:
"that actually cuts material."
)
+ # Translate the section back to z = 0: DXF is a 2D format, and handing it a
+ # profile at the section height makes the exporter warn about a non-planar
+ # shape even though the written entities would be flat anyway.
+ if abs(height) > 1e-9:
+ profile = profile.moved(build123d.Location((0.0, 0.0, -height)))
+
+ from build123d.exporters import ColorIndex # noqa: PLC0415 - not in the top-level namespace
+
exporter = build123d.ExportDXF(unit=build123d.Unit.MM)
- exporter.add_shape(profile)
+ # Cut geometry goes on a named layer: laser shops key power and speed to
+ # layer or colour, and geometry on layer 0 forces them to guess.
+ exporter.add_layer("CUT", color=ColorIndex.RED)
+ exporter.add_shape(profile, layer="CUT")
exporter.write(str(path))
return height
@@ -103,7 +117,22 @@ def main() -> int:
builder = getattr(module, "build", None)
if builder is None or not callable(builder):
raise LabCadError(f"{args.model.name} must define a callable build() that returns a Part")
- part = builder()
+ try:
+ part = builder()
+ except LabCadError:
+ raise
+ except Exception as exc: # noqa: BLE001 - model code raises arbitrary errors
+ import traceback # noqa: PLC0415
+
+ frames = traceback.extract_tb(exc.__traceback__)
+ model_frames = [f for f in frames if f.filename == str(args.model.resolve())]
+ where = (
+ f" at {args.model.name}:{model_frames[-1].lineno} ({model_frames[-1].name})"
+ if model_frames else ""
+ )
+ raise LabCadError(
+ f"build() failed{where}: {type(exc).__name__}: {exc}"
+ ) from exc
if part is None:
raise LabCadError(f"{args.model.name}: build() returned None")
params = model_parameters(module)
@@ -159,6 +188,25 @@ def main() -> int:
"Fix the model source before fabricating."
)
+ # Evaluate the model's declared geometry checks against the solid just built.
+ # These are measured, so a failure here is a real feature error, not a
+ # declaration mismatch.
+ declared_checks = model_checks(module)
+ check_results = []
+ checks_pass = True
+ if declared_checks:
+ check_results = evaluate_checks(part, declared_checks)
+ checks_pass = all(item["pass"] for item in check_results)
+ eprint(f"geometry checks: {len(check_results)}")
+ for item in check_results:
+ for line in format_check_result(item):
+ eprint(line)
+ if not checks_pass:
+ eprint(
+ "WARNING: geometry check(s) FAILED. The exported STEP does not meet "
+ "the model's own declared requirements; fix the source and rerun."
+ )
+
manifest = {
"artifact_name": stem,
"source": {
@@ -168,6 +216,8 @@ def main() -> int:
"parameters": params,
"overrides": overrides,
"interfaces": interfaces,
+ "geometry_checks": {"declared": declared_checks, "results": check_results,
+ "pass": checks_pass},
"geometry": facts,
"artifacts": artifacts,
"dxf_section_z_mm": dxf_z,
@@ -186,15 +236,19 @@ def main() -> int:
if not interfaces:
eprint(
- "note: this model declares no INTERFACES, so no interface can be checked "
- "automatically. See references/build123d-patterns.md."
+ "note: no declared interfaces. Correct if nothing here mates with a bundled "
+ "standard - do not invent one; name unchecked interface dimensions in the report."
)
box = facts["bounding_box_mm"]
+ checks_note = (
+ f"geometry checks: {sum(1 for c in check_results if c['pass'])}/{len(check_results)} pass"
+ if check_results else "geometry checks: none declared"
+ )
lines = [
f"{stem}: {box['x']:.2f} x {box['y']:.2f} x {box['z']:.2f} mm, "
f"volume {facts['volume_mm3']:.1f} mm^3, valid={facts['is_valid']}, "
- f"declared interfaces: {len(interfaces)}",
+ f"declared interfaces: {len(interfaces)}, {checks_note}",
f"Next: python scripts/check.py facts {step_path}",
]
if interfaces:
@@ -203,7 +257,7 @@ def main() -> int:
f" python scripts/snapshot.py {step_path} --out {outdir / (stem + '.png')}"
)
emit(manifest, args.as_json, "\n".join(lines))
- return 0 if facts["is_valid"] and dxf_error is None else 1
+ return 0 if facts["is_valid"] and dxf_error is None and checks_pass else 1
if __name__ == "__main__":