Metadata-Version: 2.5
Name: flatmat
Version: 0.2.0
Summary: Sheet metal recognition and unfolding for STEP files, on OpenCascade
Project-URL: Source, https://github.com/jeanole/flatmat
Project-URL: Documentation, https://github.com/jeanole/flatmat/blob/main/docs/design.md
Project-URL: Test results, https://github.com/jeanole/flatmat/blob/main/docs/test-results.md
Project-URL: Issues, https://github.com/jeanole/flatmat/issues
Author: flatmat contributors
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: CAD,CAM,DXF,OpenCascade,STEP,flat pattern,sheet metal,unfold
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Manufacturing
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.11
Requires-Dist: cadquery-ocp-novtk<8.1,>=8.0.1
Requires-Dist: ezdxf<2,>=1.1
Requires-Dist: numpy>=1.23
Requires-Dist: shapely<3,>=2.0
Provides-Extra: dev
Requires-Dist: hypothesis>=6.100; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: docs
Requires-Dist: matplotlib>=3.8; extra == 'docs'
Provides-Extra: test
Requires-Dist: hypothesis>=6.100; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# flatmat

[![CI](https://github.com/jeanole/flatmat/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jeanole/flatmat/actions/workflows/ci.yml)

Sheet metal recognition and unfolding for STEP files, in Python on
OpenCascade.

> **Checked, not claimed.** Every test part's flat pattern is compared with one worked
> out by hand, on every push to `main`. **[See the test results](https://github.com/jeanole/flatmat/blob/main/docs/test-results.md)**:
> a picture of each part and its flat, the formula behind the expected flat, and
> flatmat's error against it. No expected value comes from a commercial CAD product.

flatmat is meant to take a bent sheet metal part from a STEP file and:

1. check that it really is sheet metal and measure its thickness;
2. recognise flanges and bends (inner radius, angle, up/down, axis), including
   bends interrupted by cut-outs;
3. unfold it with a K-factor model (scalar, r/t table or DIN 6935) into an
   exact flat pattern: lines, arcs and splines, with holes that cross bends;
4. write a DXF for laser cutting and press-brake software, plus a bend table
   (JSON/CSV);
5. optionally check manufacturability: minimum flange, hole-to-bend
   distance, bend and corner reliefs, and similar rules; with punch and die
   data, tool collisions and a bend order.

Every result carries provenance: each flat edge maps back to the STEP edge it
came from. Anything flatmat cannot handle is refused with a structured
diagnostic that names the faces involved, never silently unfolded wrong.

## Status

**0.2.0, the first release** ([PyPI](https://pypi.org/project/flatmat/)). The package works end to end for planes and
cylindrical bends, joggles (with a shop's joggle table), embosses, extruded holes,
louvres, bridges and lances.
Tested on (latest results, part by part: [`docs/test-results.md`](https://github.com/jeanole/flatmat/blob/main/docs/test-results.md)):

- generated parts and random profiles (hypothesis): exact to 1e-9;
- 6 BenDFM samples: they match BenDFM's own unfolds;
- SolidCraft's 9 analytic sheet metal reference parts, rebuilt as STEP in
  [`tests/data/solidcraft_oracle`](https://github.com/jeanole/flatmat/blob/main/tests/data/solidcraft_oracle/README.md): flat
  area, size and bend allowances exact to 1e-9 against the hand-worked flat;
- 23 hand-worked parts in [`tests/data/handworked`](https://github.com/jeanole/flatmat/blob/main/tests/data/handworked/README.md):
  holes across bends (windows, a notch, a slot, a radial hole, holes cut flat and then
  bent), box corners (open, relieved, closed), hems (open, closed, rolled 270°, a hole
  through both layers), joggles, and countersinks (82° to 120°) and counterbores: exact
  to 1e-9 at three K;
- 4 real SolidWorks 2023/2026 exports.

Needs OCP 8.0 (`cadquery-ocp-novtk` 8.0.x).

| | |
|---|---|
| [`docs/design.md`](https://github.com/jeanole/flatmat/blob/main/docs/design.md) | algorithm, API, diagnostics, tests, hard cases, robustness, manufacturing checks, roadmap |
| [`docs/research.md`](https://github.com/jeanole/flatmat/blob/main/docs/research.md) | the research behind it, with sources |
| [`spike/`](https://github.com/jeanole/flatmat/blob/main/spike/README.md) | the phase-0 prototype and its measurements |

### Usage

```sh
pip install flatmat         # needs Python >= 3.11; pulls cadquery-ocp-novtk
pip install -e .            # or from a checkout of this repository
flatmat unfold part.step -k 0.44 -o part.dxf --table part.json --svg part.svg
flatmat unfold part.step --din  # K per bend from DIN 6935
flatmat unfold part.step --sharp-radius 1.6   # radius the die gives on sharp (r = 0) bends
flatmat unfold part.step --check --material stainless -o part.dxf   # DFM findings, marked in the DXF
flatmat unfold part.step --check --sequence --punch gooseneck_88 --die V12   # collisions and a bend order
flatmat unfold part.step --check --sequence 3,1,2 --tooling tools.json       # check this order with your tools
flatmat unfold part.step --pre-hole 3.2 -o part.dxf   # extruded holes: pre-hole from your table
flatmat unfold part.step --engrave -o part.dxf   # pockets, grooves, text that do not go through: rim on ENGRAVE
flatmat unfold part.step --joggle-table joggles.csv   # joggles laid out by your table: offset,allowance rows
```

```python
import flatmat as fm

sheet = fm.recognize(fm.load_step("part.step"))      # thickness, bends, flanges
pat = fm.unfold(sheet, k=fm.KTable.from_rows([(1, 0.38), (3, 0.43), (99, 0.5)]))
print(pat.size, [(b.direction, b.angle_deg, b.r_in, b.ba) for b in pat.bends])
fm.write_dxf(pat, "part.dxf")          # exact LINE / ARC / CIRCLE / SPLINE, bend lines, Delem-style labels
fm.write_bend_table(pat, "part.json")  # or .csv

report = fm.check(pat, material="steel", die_v=16)  # manufacturability
for d in report.problems:
    print(d.code, d.message, d.data["at"])

tools = fm.Tooling(fm.PUNCHES["gooseneck_88"], fm.Die(v=12, angle_deg=88, shoulder_radius=1.2))
plan = fm.plan_bends(pat, tools)        # collision-free order, or what blocks each bend
print(plan.feasible, plan.order, [c.describe() for c in plan.collisions])
report = fm.check(pat, tooling=tools, sequence=True)   # the same, as DFM_TOOL_COLLISION findings

for j in sheet.joggles:  # two opposite bends offsetting the sheet (offset <= 5 t): their kind is "joggle"
    print(j.bends, j.offset, j.flat, j.run)
pat = fm.unfold(sheet, k=0.44, joggle=fm.JoggleTable.from_rows([(1, 0.1), (3, 0.3), (6, 0.8)], thickness=2))
print([(j.length, j.allowance) for j in pat.joggles])  # laid out run + allowance long

for f in pat.features:  # countersinks, counterbores, embosses, extruded holes, louvres, bridges, lances
    print(f.kind, f.side, f.height, f.orientation_deg, f.size, [pat.holes[i] for i in f.holes])
```

A part flatmat cannot handle raises `fm.FlatmatError`. Its `.diagnostic` has a
code (`VARIABLE_THICKNESS`, `EDGE_FEATURE`, `UNSUPPORTED_SURFACE`,
`CYCLE_INCONSISTENT`, …) and names the faces involved.

### PMI: tolerances from AP242 files

`load_step` reads STEP through XCAF and keeps the file's semantic PMI:
dimensions, GD&T, datums and notes. `recognize` maps it onto the sheet as
`sheet.pmi`, a `SheetPmi`. flatmat does not judge whether a tolerance can be
held. It gives the path each tolerance takes through the part, so the caller
can decide which process determines it:

| `PmiPath.kind` | when | carries |
|---|---|---|
| `laser` | both sides on one flange (cut edges, holes, outer contour) | `flanges` |
| `laser_hole` | a hole diameter or a radius on a cut face | `flanges`; `feature_id` for a countersink or counterbore |
| `bend_chain` | sides on different flanges | `bends` between them, in path order |
| `bend_angle` | an angle, perpendicularity, parallelism or angularity between adjacent flanges | the one bend |
| `flatness` | flatness of one flange | `flanges` |
| `unmapped` | a side on a bend or a formed feature, an angle across several bends, other GD&T | `reason`, in plain English |

```python
sheet = fm.recognize(fm.load_step("part_mbd.step"))
for item, path in sheet.pmi.items:  # status: "none", "semantic", "graphical_only", "failed"
    print(item.kind, item.nominal, item.upper, item.lower, item.tolerance, item.text, path.kind, path.bends)
print(sheet.pmi.general)  # GeneralTolerance("ISO 2768", "m", "K", ...) from a note or a callout
print([(t.designation, t.count, t.face_ids, t.pmi_ids) for t in sheet.pmi.threads])  # "M6 THRU" -> the hole
```

Lengths are in mm and angles in degrees, whatever the file's units.
`PmiItem.tolerance` says what kind of tolerance a dimension has:

| `tolerance` | means | `nominal`, `upper`, `lower` |
|---|---|---|
| `"none"` | no tolerance of its own: the general tolerance applies | the nominal; None, None |
| `"plus_minus"` | a ± tolerance, signs as the file writes them (+0.1/+0.05 stays) | the nominal and the signed deviations |
| `"limits"` | a lower and an upper limit, or a max / min qualifier (`max 20`) | None: `text` holds the limits |
| `"fit"` | an ISO 286 fit: the class is in `text` (`Ø8 H7`) | the nominal; None, None |
| `"unreadable"` | a sign or unit flatmat cannot read, inverted limits, a dimension not found in the file | None for the bounds: `text` keeps what was read |

GD&T items are `"none"` (the zone is `upper`) or `"unreadable"`. A tolerance
that cannot be read keeps its path and its raw text: whether it is checked is
the caller's call, never a guess. OCCT's reader drops a STEP file's signs,
angle units, max / min qualifiers and fit classes, so flatmat reads these from
the file's own entities.

Notes (free text) never survive OCCT's STEP reader: its writer drops them and
its reader fills no notes table. Threads and the general tolerance are parsed
from every text the reader does yield (dimension callouts, presentation
names), and from notes of a document built in memory. A thread
(`Thread.designation`, an ISO 261 size and pitch) counts the larger of the
callout's `4x` and the holes it points at (coaxial walls in one flange are
one hole); `Thread.pmi_ids` names the item it came from, empty for a note.
`SheetPmi.graphical` counts graphical-only annotations beside semantic PMI
that no semantic item repeats: callouts nobody checks.

A PMI problem is a warning (`PMI_READ_FAILED`, `PMI_GRAPHICAL_ONLY`), never a
reason to refuse a part: one bad item loses only itself. A file without PMI
gives `SheetPmi("none")` and the same result as before, byte for byte in the
DXF. `load_step(path, pmi=False)` skips the XCAF read.

### Tests

The latest results, with every sheet metal test part, are in
[`docs/test-results.md`](https://github.com/jeanole/flatmat/blob/main/docs/test-results.md): CI writes it on every push to `main`
and commits it when a result changed
(`pytest tests --results-page docs/test-results.md` writes it locally). Its pictures of the
parts are drawn by `pip install -e ".[docs]" && python tests/render_parts.py` when a part
changes.

```sh
pip install -e ".[test]" && pytest
FLATMAT_BENDFM_DIR=/path/to/bendfm/example_files pytest tests/test_external.py
FLATMAT_PARTS_DIR=/path/to/private/step/files pytest tests/test_external.py   # never committed
```

CI runs lint, mypy and the tests on every pull request and every push to `main`.

### Releasing

`.github/workflows/release.yml` builds the sdist and wheel, checks them (`twine check`,
the wheel's `flatmat --version`, the tests from the unpacked sdist) and publishes with
PyPI trusted publishing: no token is stored. The version lives in one place,
`__version__` in `src/flatmat/__init__.py`.

1. Once: on pypi.org and test.pypi.org, add a pending trusted publisher for `flatmat`
   (owner `jeanole`, repository `flatmat`, workflow `release.yml`, environment `pypi`
   and `testpypi`), and create those two environments under the repository's
   Settings → Environments (give `pypi` a required reviewer to approve each release).
2. Dry run: Actions → Release → Run workflow publishes the current version to TestPyPI.
   A version can be uploaded once, so a second dry run needs a new `.devN`.
3. Release: set `__version__`, merge to `main`, then tag that commit `v<version>` and push the tag.
   The workflow refuses a tag that does not match `__version__`, publishes to PyPI and
   makes a GitHub release with the built files.

## Why another unfolder

No standalone, permissively licensed library does STEP → bend table → DXF
today:

- build123d's new sheet metal module (Apache-2.0) has not been released yet.
  It supports only planes and cylinders, and outputs no bend lines or bend
  table.
- FreeCAD SheetMetal (LGPL) needs the FreeCAD runtime.
- The commercial SDKs (CADEX MTK, the OCCT Sheet Metal component) are priced
  per quote.

## Planned scope

- **v0.1 (released in 0.2.0):** flat faces and cylindrical bends;
  one solid of constant thickness; holes and cut-outs across bends; hems; K as
  a scalar, an r/t table or DIN 6935; exact DXF and bend table.
- **v0.2 (released as 0.2.0):** sharp bends (r = 0, inside or both sides, with an
  optional tooling radius) — done; countersinks and counterbores — done;
  B-spline faces and edges that are really planes, cylinders, cones, lines
  or circles — done; manufacturability checks (flange, radius, holes, reliefs,
  slots, hems, U channels, tonnage) — done; embosses and extruded holes
  (pre-hole from the neutral fibre or your table) — done; louvres, bridges
  and lances, bent or formed, with straight or curved slits (slits cut, rim
  marked; a bent lance's tab developed) — done;
  corner rule (corner
  relief, gap between folded flanges) — done; punch and die data, tool
  collisions and a bend order — done; recesses that do not go through
  (pockets, grooves, engraved text, blind holes) as engravings of their rim,
  with `recognize(engrave=True)` — done.
- **Later:** cones, tubes, assemblies.

## Stack

Python ≥ 3.11 on [`cadquery-ocp-novtk`](https://pypi.org/project/cadquery-ocp-novtk/)
(OCCT 8.0) and [ezdxf](https://ezdxf.mozman.at/). No
FreeCAD and no build123d at runtime.

## License

[Apache-2.0](https://github.com/jeanole/flatmat/blob/main/LICENSE).

flatmat uses Open CASCADE Technology (OCCT) through the OCP bindings. OCCT
is licensed under the LGPL-2.1 with the Open CASCADE exception; its source is
available at <https://github.com/Open-Cascade-SAS/OCCT>.
