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
30 changes: 30 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
name: CI

on:
push:
branches: [main]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
timeout-minutes: 20
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- name: Install
run: |
python -m pip install --upgrade pip
pip install -e .[dev]

- name: Run tests
run: python -m pytest -q --durations=20
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
129 changes: 129 additions & 0 deletions freecad/meshtofeatures_wb/tests/fixtures/generate_corpus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
"""Regenerate the regression corpus STLs in this directory.

Each part is built by exact CSG (boxes, cylinders, cones, an extruded
stepped profile) so its ground-truth feature inventory and volume are
known. The emitted binary STLs are committed; run this script only to
reproduce them after an intentional generator change:

.venv/bin/python freecad/meshtofeatures_wb/tests/fixtures/generate_corpus.py

The corpus is the target of ``tests/test_corpus.py``: every part must
flow through the full pipeline, reproduce its analytic feature set, and
close the volume gate (corrected mesh volume within 1% of the mesh
volume).
"""

from pathlib import Path

import numpy as np
import shapely.geometry as sg
import trimesh

_OUT = Path(__file__).parent
_D2R = np.pi / 180.0


def _save(mesh, name):
mesh.export(str(_OUT / name), file_type="stl")
print(f"{name}: watertight={mesh.is_watertight} volume={mesh.volume:.1f}")


def _cyl(r, h, center, axis="z"):
m = trimesh.creation.cylinder(radius=r, height=h, sections=64)
if axis == "x":
m.apply_transform(trimesh.transformations.rotation_matrix(_D2R * 90, [0, 1, 0]))
elif axis == "y":
m.apply_transform(trimesh.transformations.rotation_matrix(_D2R * 90, [1, 0, 0]))
m.apply_translation(center)
return m


def _box(sx, sy, sz, center):
m = trimesh.creation.box(extents=[sx, sy, sz])
m.apply_translation(center)
return m


def _profile_mesh(poly2d, depth, y_center=0.0):
"""Extrude an XZ profile (2D polygon, y = height) along Y to `depth`,
centered on y = y_center."""
m = trimesh.creation.extrude_polygon(poly2d, depth)
# extrusion ran along +Z: (x, h, t) -> (x, t, h)
m.apply_transform(trimesh.transformations.rotation_matrix(_D2R * 90, [1, 0, 0]))
m.apply_translation([0.0, y_center, 0.0])
return m


def plate_counterbored():
"""60x40x10 plate, four Ø8 through bores, two of them counterbored
Ø14 x 5 deep from the top face."""
plate = _box(60, 40, 10, [0, 0, 0])
tool = trimesh.util.concatenate([_cyl(4.0, 30, [x, y, 0])
for x, y in [(20, 12), (20, -12),
(-20, 12), (-20, -12)]])
for x, y in [(20, 12), (20, -12)]:
tool = tool.union(_cyl(7.0, 5.0, [x, y, 2.5]))
return plate.difference(tool)


def block_countersunk():
"""50x50x20 block, two Ø10 through bores with 90° Ø18 countersinks on
the top face, one Ø12 blind bore 8 deep."""
block = _box(50, 50, 20, [0, 0, 0])
tool = trimesh.util.concatenate([_cyl(5.0, 40, [x, 0, 0]) for x in (15, -15)])
for x in (15, -15):
sink = trimesh.creation.cone(radius=9.0, height=9.0, sections=64)
sink.apply_transform(trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0]))
sink.apply_translation([x, 0, 10.0]) # base (Ø18) at z=10, apex at z=1
tool = tool.union(sink)
tool = tool.union(_cyl(6.0, 8.0, [0, 15, 6.0]))
return block.difference(tool)


def bossed_plate():
"""80x50x8 plate, a 30x20x12 boss on the top face, four Ø6 through
bores (two through boss + plate, two through plate only) and a
36x10 through slot."""
part = _box(80, 50, 8, [0, 0, 0]).union(_box(30, 20, 12, [0, 0, 10]))
tool = trimesh.util.concatenate([
_cyl(3.0, 40, [7, 0, 0]), _cyl(3.0, 40, [-7, 0, 0]),
_cyl(3.0, 40, [33, 0, 0]), _cyl(3.0, 40, [-33, 0, 0]),
_box(36, 10, 40, [0, 17, 0]),
])
return part.difference(tool)


def cross_holed_block():
"""40x40x40 block: one Ø8 Z through bore, one Ø10 Y through bore
(crossing it), one Ø8 blind X bore 15 deep from the x=-20 face."""
block = _box(40, 40, 40, [0, 0, 0])
tool = _cyl(4.0, 60, [0, 0, 0])
tool = tool.union(_cyl(5.0, 60, [0, 0, 20], axis="y"))
tool = tool.union(_cyl(4.0, 15.0, [-12.5, 0, 10], axis="x"))
return block.difference(tool)


def stepped_chamfered():
"""Stepped block (60/40/20 wide, 6 high each) extruded 40 in Y, with
2 mm chamfers on the top corners of the highest step and one Ø6 Z
through bore at the center."""
poly = sg.Polygon([
(-30, 0), (30, 0), (30, 6), (20, 6), (20, 12), (10, 12),
(10, 16), (8, 18), (-8, 18), (-10, 16), (-10, 12), (-20, 12),
(-20, 6), (-30, 6),
])
part = _profile_mesh(poly, 40, y_center=20.0)
return part.difference(_cyl(3.0, 60, [0, 0, 0]))


def main():
_save(plate_counterbored(), "corpus_plate_counterbored.stl")
_save(block_countersunk(), "corpus_block_countersunk.stl")
_save(bossed_plate(), "corpus_bossed_plate.stl")
_save(cross_holed_block(), "corpus_cross_holed_block.stl")
_save(stepped_chamfered(), "corpus_stepped_chamfered.stl")


if __name__ == "__main__":
main()
213 changes: 213 additions & 0 deletions freecad/meshtofeatures_wb/tests/test_corpus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
"""Regression corpus: five synthetic machined parts with analytic ground truth.

Each STL in ``fixtures/`` is generated by ``fixtures/generate_corpus.py``
(exact CSG, known volume and feature set). These tests pin the STABLE,
CORRECT core of the pipeline on each part:

* the mesh still carries the generated volume (guards against a broken
regeneration of the corpus),
* the feature detector sees the real features with their diameters and
depths,
* the coverage is at or above the recorded floor,
* the executed plan, after the canonical OVER/UNDER corrections
(``plan_to_mesh`` + ``plan_corrections`` + ``apply_corrections``),
reproduces the source mesh within 1% of volume -- the gate the
generator's docstring promises.

Deliberately NOT asserted: artifact-prone flags (through/blind where the
detector truncates a bore at a countersink) and gap-prone features
(countersink cones on ``block_countersunk``; the Ø10 cross bore on
``cross_holed_block`` that lands in ``unplanned`` as an open slot). Those
are known detection gaps, pinned separately when closed.
"""

from pathlib import Path

import numpy as np
import pytest
import trimesh

pytest.importorskip("manifold3d")

from freecad.meshtofeatures_wb.core.emission import plan_patches
from freecad.meshtofeatures_wb.core.features import detect_features
from freecad.meshtofeatures_wb.core.history import plan_history
from freecad.meshtofeatures_wb.core.patterns import detect_patterns
from freecad.meshtofeatures_wb.core.pipeline import reconstruct
from freecad.meshtofeatures_wb.core.snapping import snap_report
from freecad.meshtofeatures_wb.core.solidify import (
apply_corrections,
plan_corrections,
plan_to_mesh,
)

FIXTURES = Path(__file__).resolve().parent / "fixtures"

# Analytic volume of each corpus part (exact CSG, generate_corpus.py).
EXPECTED_VOLUME = {
"corpus_block_countersunk.stl": 45324.45,
"corpus_bossed_plate.stl": 34739.18,
"corpus_cross_holed_block.stl": 59900.16,
"corpus_plate_counterbored.stl": 20957.55,
"corpus_stepped_chamfered.stl": 28131.88,
}

SIZE_TOL = 0.3 # diameter / size / width
DEPTH_TOL = 1.5


def _load(name):
mesh = trimesh.load(str(FIXTURES / name))
if isinstance(mesh, trimesh.Scene):
mesh = mesh.dump(concatenate=True)
return mesh


def _full(mesh):
report = snap_report(reconstruct(mesh)).report
patches = plan_patches(report)
feats = detect_features(report, patches)
plan = plan_history(report, feats, detect_patterns(feats), patches)
return report, feats, plan


def _check_fixture_volume(name, mesh):
expected = EXPECTED_VOLUME[name]
got = float(mesh.volume)
assert abs(got - expected) / expected < 0.01, (
f"{name}: mesh volume {got:.2f} drifted from analytic {expected:.2f}")


def _gate(mesh, plan):
"""The executed plan must reproduce the source mesh within 1% volume
after the canonical OVER/UNDER corrections."""
solid = plan_to_mesh(plan)
assert solid is not None, "plan could not be executed headlessly"
corrected = apply_corrections(solid, mesh, plan_corrections(plan, mesh))
ratio = abs(float(corrected.volume) - float(mesh.volume)) / float(mesh.volume)
assert ratio < 0.01, f"corrected volume off by {ratio:.2%}"


def _axis_close(axis, ref, tol=0.9):
a = np.asarray(axis, dtype=float)
return abs(float(np.dot(a, ref))) / float(np.linalg.norm(a)) > tol


class TestBlockCountersunk:
"""Countersunk bores + one blind Ø12 bore + a pocket. The countersink
cones are a known detection gap (see module docstring)."""

def test_corpus_and_core(self):
name = "corpus_block_countersunk.stl"
mesh = _load(name)
_check_fixture_volume(name, mesh)
report, feats, plan = _full(mesh)
assert report.coverage >= 0.95
holes = feats.by_kind("hole")
assert len(holes) == 3
diameters = sorted(h.params["diameter"] for h in holes)
assert np.allclose(diameters, [10, 10, 12], atol=SIZE_TOL)
deep = max(holes, key=lambda h: h.params["diameter"])
assert abs(deep.params["depth"] - 8.0) <= DEPTH_TOL, \
f"Ø12 blind bore depth {deep.params['depth']}, expected 8"
_gate(mesh, plan)


class TestBossedPlate:
"""Plate with a boss: four Ø6 holes (two through, two to the pocket
floor) and a 36x10 slot pocket."""

def test_corpus_and_core(self):
name = "corpus_bossed_plate.stl"
mesh = _load(name)
_check_fixture_volume(name, mesh)
report, feats, plan = _full(mesh)
assert report.coverage >= 0.99
holes = feats.by_kind("hole")
assert len(holes) == 4
for h in holes:
assert abs(h.params["diameter"] - 6.0) <= SIZE_TOL
assert h.params["through"] is True
depths = sorted(h.params["depth"] for h in holes)
assert np.allclose(depths, [8, 8, 20, 20], atol=DEPTH_TOL)
slots = [p for p in feats.by_kind("pocket")
if p.params.get("opening_size")]
assert len(slots) == 1
opening = sorted(float(v) for v in slots[0].params["opening_size"])
assert np.allclose(opening, [10, 36], atol=0.5), \
f"slot opening {opening}, expected [10, 36]"
_gate(mesh, plan)


class TestCrossHoledBlock:
"""Block with a Z bore, a blind X bore, and a Ø10 through Y bore. The
Y bore lands in ``unplanned`` as an open slot (known gap); the X bore
and the Z cross-hole are pinned."""

def test_corpus_and_core(self):
name = "corpus_cross_holed_block.stl"
mesh = _load(name)
_check_fixture_volume(name, mesh)
report, feats, plan = _full(mesh)
assert report.coverage >= 0.99
x_bore = [h for h in feats.by_kind("hole")
if _axis_close(h.params.get("axis", (1, 0, 0)), (1, 0, 0))]
assert len(x_bore) == 1, "blind X bore not detected"
assert abs(x_bore[0].params["diameter"] - 8.0) <= SIZE_TOL
assert abs(x_bore[0].params["depth"] - 15.0) <= DEPTH_TOL, \
f"X bore depth {x_bore[0].params['depth']}, expected 15"
slots = feats.by_kind("slot")
assert len(slots) == 1, "Y bore not detected as a slot"
assert abs(slots[0].params["width"] - 10.0) <= SIZE_TOL
assert slots[0].params["through"] is True
assert _axis_close(slots[0].params.get("axis", (0, 1, 0)), (0, 1, 0))
z_bores = [ch for ch in plan.cross_holes
if abs(ch.diameter - 8.0) <= SIZE_TOL]
assert z_bores, "Z bore missing from plan.cross_holes"
_gate(mesh, plan)


class TestPlateCounterbored:
"""Plate with two plain Ø8 through holes and two Ø8 counterbores
(Ø14 x 5 deep)."""

def test_corpus_and_core(self):
name = "corpus_plate_counterbored.stl"
mesh = _load(name)
_check_fixture_volume(name, mesh)
report, feats, plan = _full(mesh)
assert report.coverage >= 0.999
plain = feats.by_kind("hole")
cbs = feats.by_kind("counterbore")
assert len(plain) == 2
assert len(cbs) == 2
for h in plain:
assert abs(h.params["diameter"] - 8.0) <= SIZE_TOL
for c in cbs:
assert abs(c.params["diameter"] - 8.0) <= SIZE_TOL
assert abs(c.params["counterbore_diameter"] - 14.0) <= SIZE_TOL
assert abs(c.params["counterbore_depth"] - 5.0) <= DEPTH_TOL
_gate(mesh, plan)


class TestSteppedChamfered:
"""Stepped plate with a Ø6 through bore and two 2x45° chamfers."""

def test_corpus_and_core(self):
name = "corpus_stepped_chamfered.stl"
mesh = _load(name)
_check_fixture_volume(name, mesh)
report, feats, plan = _full(mesh)
assert report.coverage >= 0.999
holes = feats.by_kind("hole")
assert len(holes) == 1
assert abs(holes[0].params["diameter"] - 6.0) <= SIZE_TOL
assert holes[0].params["through"] is True
chams = feats.by_kind("chamfer")
assert len(chams) == 2
for c in chams:
assert abs(c.params["size"] - 2.0) <= SIZE_TOL
assert abs(c.params["angle_deg"] - 45.0) <= 2.0
assert len(plan.pockets) >= 3, "stepped plate lost its steps"
_gate(mesh, plan)
5 changes: 3 additions & 2 deletions freecad/meshtofeatures_wb/tests/test_emission.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,9 @@ def test_cone_ranges(self):
p = [q for q in plan_patches(rep) if q.kind == "cone"][0]
assert p.full_u
v0, v1 = p.v_range # height above apex, along the cone axis
assert np.isclose(v0, 0.0, atol=1e-6)
assert np.isclose(v1, 2.0, atol=1e-6)
# fit precision is ~1e-4 and varies with the numpy/LAPACK build
assert np.isclose(v0, 0.0, atol=1e-3)
assert np.isclose(v1, 2.0, atol=1e-3)
# origin is the apex
assert np.allclose(p.origin, p.primitive.apex)

Expand Down
5 changes: 3 additions & 2 deletions freecad/meshtofeatures_wb/tests/test_freecad_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,9 @@ def test_reconstructed_tip_radius_zero(self, monkeypatch):
spec = [p for p in _patches_for(mesh) if p.kind == "cone"][0]
shape = emit.patch_to_shape(spec)
# the segment reaches the apex, so h0 ~ 0 and the reference radius
# must be ~0 within fit precision (OCC accepts R = 0)
assert shape.surface.Radius == pytest.approx(0.0, abs=1e-6)
# must be ~0 within fit precision (~1e-4, varies with the
# numpy/LAPACK build; OCC accepts R = 0)
assert shape.surface.Radius == pytest.approx(0.0, abs=1e-3)


class TestPlaneShape:
Expand Down
Loading
Loading