diff --git a/README.md b/README.md index dd2ef3b9..2710ee14 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,11 @@ incremental assembly solves, and a persistent crash-safe cache for whole parts. See the [full English update notes](docs/updates/2.0.4b3.md) for contracts, cache modes, diagnostics, limitations, and verification coverage. -All formal scripts under `examples/` emit a synchronized `.scadpkg`, AP242 +All formal single-script examples emit a synchronized `.scadpkg`, AP242 `.step`, and editable `.FCStd` from the same product package. Run -`uv run python tools/run_examples.py` to rebuild and validate the complete -example export set. The Gmsh example accepts `--skip-mesh` when only the CAD -artifacts are required. +`uv run python tools/run_examples.py` to rebuild and validate that set. The +split AP242/Gmsh example under `examples/12_ap242_gmsh_volume_mesh/` exposes +each build and export stage as a separate directly runnable script. --- @@ -119,6 +119,7 @@ print("volume", round(result.part.body.get_volume(), 3)) print("tags", scad.list_tags(shape=result.part.body)) scad.exporter.export_product_package_to_step(package_path, out / "bracket.step") scad.exporter.export_product_package_to_stl(package_path, out / "bracket.stl") +scad.exporter.export_product_package_to_obj(package_path, out / "bracket.obj") ``` ## Replayable Operation Graphs @@ -211,14 +212,43 @@ scad.exporter.export_product_package_to_step( scad.exporter.export_product_package_to_stl( "out/mounting_plate.scadpkg", "out/mounting_plate.stl" ) +scad.exporter.export_product_package_to_obj( + "out/mounting_plate.scadpkg", "out/mounting_plate.obj" +) +``` +STL and OBJ share one direct OpenCASCADE tessellation of the evaluated BREP. +Both outputs contain the same oriented triangles and require no optional +remeshing dependency. Control curved-surface accuracy with `linear_deflection` +and `angular_deflection_degrees`. + +The AP242/Gmsh example also includes an optional CalculiX FEM workflow. Install +the Python-side FEM dependencies with `uv sync --extra fem`, and install the +external CalculiX solver separately (on macOS: `brew install +costerwi/homebrew-calculix/calculix-ccx`). The example uses consistent `mm`, +`N`, and `MPa` units: + +```bash +uv run --extra fem python examples/12_ap242_gmsh_volume_mesh/run_calculix.py \ + --ccx "$(brew --prefix calculix-ccx)/bin/ccx_2.23" +uv run --extra fem python examples/12_ap242_gmsh_volume_mesh/visualize_calculix.py +uv run --extra fem python examples/12_ap242_gmsh_volume_mesh/study_mesh_convergence.py \ + --ccx "$(brew --prefix calculix-ccx)/bin/ccx_2.23" \ + --linear-solver "ITERATIVE CHOLESKY" --solver-timeout 2400 ``` -AP242 preserves evaluated BREP, shared definitions, hierarchy, occurrence -names/placements, materials, colors, density, and named SimpleCAD JSON -properties. It does not reconstruct canonical feature history as AP242 -features. For the optional `.step -> .msh` volume-mesh workflow, install -`simplecadapi[gmsh]` and run `examples/12_ap242_gmsh_volume_mesh.py`; use -`--skip-mesh` to export only the synchronized CAD artifacts. +The analysis writes CalculiX `.inp`, `.dat`, `.frd`, solver-log, summary JSON, +ParaView `.vtu`, and displaced von-Mises PNG artifacts. The preview shows the +load physical group's yellow boundary and red `-Z` force arrows without +covering the stress heatmap. The convergence study supports `--resume`; failed +solver levels are reported separately and never enter the numerical sequence. + +The checked-in `-1000 N` study evaluates eleven mesh sizes from `h=3.0 mm` to +`h=0.25 mm`. A platform requires three consecutive refinement pairs below `5%` +maximum-displacement change and `10%` peak integration-point von-Mises change. +The verification level N is `h=0.25 mm` (`0.0331843 mm`, `98.6392 MPa`), so the +recommended production level N-1 is `h=0.27 mm`. Fine levels use iterative +Cholesky after a same-mesh comparison at `h=0.375 mm` matched SPOOLES within +`0.005%`; this avoids the direct solver's in-memory capacity limit. ## STEP/BREP Inspection diff --git a/README.zh-CN.md b/README.zh-CN.md index c5ed2787..b3e6f3bd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -93,6 +93,7 @@ print("volume", round(result.part.body.get_volume(), 3)) print("tags", scad.list_tags(shape=result.part.body)) scad.exporter.export_product_package_to_step(package_path, out / "bracket.step") scad.exporter.export_product_package_to_stl(package_path, out / "bracket.stl") +scad.exporter.export_product_package_to_obj(package_path, out / "bracket.obj") ``` @@ -214,8 +215,38 @@ scad.translator.freecad_translator.translate_product_package_to_fcstd( ) scad.exporter.export_product_package_to_step(package_path, "bracket.step") scad.exporter.export_product_package_to_stl(package_path, "bracket.stl") +scad.exporter.export_product_package_to_obj(package_path, "bracket.obj") ``` +STL 与 OBJ 共用 OpenCASCADE 对求值后 BREP 的直接三角化。两种格式包含相同的 +定向三角面,不再需要可选 remeshing 依赖。曲面精度由 `linear_deflection` 和 +`angular_deflection_degrees` 控制。 + +AP242/Gmsh 示例还包含可选 CalculiX FEM 流程。Python 侧依赖通过 +`uv sync --extra fem` 安装;CalculiX 求解器需要单独安装(macOS: +`brew install costerwi/homebrew-calculix/calculix-ccx`): + +```bash +uv run --extra fem python examples/12_ap242_gmsh_volume_mesh/run_calculix.py \ + --ccx "$(brew --prefix calculix-ccx)/bin/ccx_2.23" +uv run --extra fem python examples/12_ap242_gmsh_volume_mesh/visualize_calculix.py +uv run --extra fem python examples/12_ap242_gmsh_volume_mesh/study_mesh_convergence.py \ + --ccx "$(brew --prefix calculix-ccx)/bin/ccx_2.23" \ + --linear-solver "ITERATIVE CHOLESKY" --solver-timeout 2400 +``` + +分析统一使用 `mm`、`N`、`MPa`,输出 CalculiX `.inp`、`.dat`、`.frd`、求解日志、 +摘要 JSON、ParaView `.vtu` 和位移放大后的 von Mises 云图 PNG。图中用黄色轮廓 +标出载荷 physical group,并用红色 `-Z` 箭头表示载荷方向,不覆盖应力热力图。 +收敛研究支持 `--resume`;失败的求解级别单独记录,不会混入数值序列。 + +仓库中的 `-1000 N` 研究从 `h=3.0 mm` 加密到 `h=0.25 mm`,共 11 级。平台要求 +连续三组细化同时满足最大位移变化低于 `5%`、积分点峰值 von Mises 应力变化低于 +`10%`。第 N 级验证网格为 `h=0.25 mm`(`0.0331843 mm`、`98.6392 MPa`), +因此生产计算推荐第 N-1 级 `h=0.27 mm`。细网格使用迭代 Cholesky;在 +`h=0.375 mm` 同网格上与 SPOOLES 的位移和峰值应力差异均低于 `0.005%`,从而 +绕过直接求解器的内存容量限制。 + ## 文档 - 2.0.4b3 更新说明:[`docs/updates/2.0.4b3.zh-CN.md`](docs/updates/2.0.4b3.zh-CN.md) diff --git a/docs/api/ProductMJCFExportReport.md b/docs/api/ProductMJCFExportReport.md new file mode 100644 index 00000000..8b8ddc71 --- /dev/null +++ b/docs/api/ProductMJCFExportReport.md @@ -0,0 +1,17 @@ +# ProductMJCFExportReport + +## Class Definition + +```python +class ProductMJCFExportReport(output_path: Path, mapping_path: Path, mesh_directory: Path, root_definition_id: str, mesh_count: int, body_count: int, joint_count: int, equality_count: int, grounded_group_count: int, site_count: int, default_density_count: int, limitations: tuple[str, ...]) +``` + +*Source: exporter/mjcf.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.mjcf.ProductMJCFExportReport(...)` + +## Description + +Observed facts and compiler decisions from one MJCF export. diff --git a/docs/api/ProductOBJExportReport.md b/docs/api/ProductOBJExportReport.md new file mode 100644 index 00000000..9e0ea7d5 --- /dev/null +++ b/docs/api/ProductOBJExportReport.md @@ -0,0 +1,17 @@ +# ProductOBJExportReport + +## Class Definition + +```python +class ProductOBJExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, vertex_count: int, triangle_count: int, linear_deflection: float, angular_deflection_degrees: float, relative: bool, tessellation_backend: str = 'opencascade-brep-tessellation') +``` + +*Source: exporter/obj.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.obj.ProductOBJExportReport(...)` + +## Description + +Evidence from direct BREP tessellation and triangle OBJ export. diff --git a/docs/api/ProductSTLExportReport.md b/docs/api/ProductSTLExportReport.md index 66c0e89f..9ef3b9d7 100644 --- a/docs/api/ProductSTLExportReport.md +++ b/docs/api/ProductSTLExportReport.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, quadrilateral_count: int, residual_triangle_count: int, stl_triangle_count: int, quad_fraction: float, mesh_size: float, remesh_backend: str = 'gmsh-quad-dominant') +class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, vertex_count: int, triangle_count: int, linear_deflection: float, angular_deflection_degrees: float, relative: bool, tessellation_backend: str = 'opencascade-brep-tessellation') ``` *Source: exporter/stl.py* @@ -14,4 +14,4 @@ class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_c ## Description -Evidence from quad-dominant product-surface remeshing and STL export. +Evidence from direct BREP tessellation and binary STL export. diff --git a/docs/api/README.md b/docs/api/README.md index 05088233..1a53ee0f 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -91,8 +91,12 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Export +- [ProductMJCFExportReport](ProductMJCFExportReport.md) *(from exporter/mjcf.py)* `exporter namespace` +- [ProductOBJExportReport](ProductOBJExportReport.md) *(from exporter/obj.py)* `exporter namespace` - [ProductSTEPExportReport](ProductSTEPExportReport.md) *(from exporter/step.py)* `exporter namespace` - [ProductSTLExportReport](ProductSTLExportReport.md) *(from exporter/stl.py)* `exporter namespace` +- [export_product_package_to_mjcf](export_product_package_to_mjcf.md) *(from exporter/mjcf.py)* `exporter namespace` +- [export_product_package_to_obj](export_product_package_to_obj.md) *(from exporter/obj.py)* `exporter namespace` - [export_product_package_to_step](export_product_package_to_step.md) *(from exporter/step.py)* `exporter namespace` - [export_product_package_to_stl](export_product_package_to_stl.md) *(from exporter/stl.py)* `exporter namespace` diff --git a/docs/api/export_product_package_to_mjcf.md b/docs/api/export_product_package_to_mjcf.md new file mode 100644 index 00000000..dc48db30 --- /dev/null +++ b/docs/api/export_product_package_to_mjcf.md @@ -0,0 +1,23 @@ +# export_product_package_to_mjcf + +## API Definition + +```python +def export_product_package_to_mjcf(data: ProductPackageInput, output_path: str | Path, *, mesh_directory: str | Path | None = None, mapping_path: str | Path | None = None, linear_deflection: float = 0.15, default_density_kg_m3: float | None = None) -> ProductMJCFExportReport +``` + +*Source: exporter/mjcf.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.mjcf.export_product_package_to_mjcf(...)` + +## Description + +Compile a validated `.scadpkg` assembly into an MJCF model. + +Fixed constraints and attachments through forwarded nested-assembly +connectors create rigid groups. Revolute/prismatic edges form a +deterministic spanning tree. Gear, belt, and rack-pinion relations become +independent fixed-tendon equalities. Root assembly connectors and geometry +names in the ``interface.*`` namespace become MJCF sites. diff --git a/docs/api/export_product_package_to_obj.md b/docs/api/export_product_package_to_obj.md new file mode 100644 index 00000000..4e84a492 --- /dev/null +++ b/docs/api/export_product_package_to_obj.md @@ -0,0 +1,21 @@ +# export_product_package_to_obj + +## API Definition + +```python +def export_product_package_to_obj(data: ProductPackageInput, output_path: str | Path, *, linear_deflection: float = 0.1, angular_deflection_degrees: float = 20.0, relative: bool = False) -> ProductOBJExportReport +``` + +*Source: exporter/obj.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.obj.export_product_package_to_obj(...)` + +## Description + +Export one `.scadpkg` directly from evaluated BREP as triangle OBJ. + +`linear_deflection` is the maximum chordal deviation in product units. +`angular_deflection_degrees` limits angular deviation on curved surfaces. +No remeshing or topology reconstruction is performed. diff --git a/docs/api/export_product_package_to_stl.md b/docs/api/export_product_package_to_stl.md index 922d7308..63c9f908 100644 --- a/docs/api/export_product_package_to_stl.md +++ b/docs/api/export_product_package_to_stl.md @@ -3,7 +3,7 @@ ## API Definition ```python -def export_product_package_to_stl(data: ProductPackageInput, output_path: str | Path, *, mesh_size: float = 1.0, recombination_angle_degrees: float = 45.0) -> ProductSTLExportReport +def export_product_package_to_stl(data: ProductPackageInput, output_path: str | Path, *, linear_deflection: float = 0.1, angular_deflection_degrees: float = 20.0, relative: bool = False) -> ProductSTLExportReport ``` *Source: exporter/stl.py* @@ -14,7 +14,8 @@ def export_product_package_to_stl(data: ProductPackageInput, output_path: str | ## Description -Export one validated `.scadpkg` as a quad-dominant remeshed STL. +Export one `.scadpkg` directly from evaluated BREP as binary STL. -Gmsh recombines each CAD surface into quadrilaterals before its STL writer -splits every quad into two triangles, as required by the STL file format. +`linear_deflection` is the maximum chordal deviation in product units. +`angular_deflection_degrees` limits angular deviation on curved surfaces. +No remeshing or topology reconstruction is performed. diff --git a/docs/guides/cache-build-workflow.md b/docs/guides/cache-build-workflow.md index 50023c37..7edc83f4 100644 --- a/docs/guides/cache-build-workflow.md +++ b/docs/guides/cache-build-workflow.md @@ -150,6 +150,8 @@ downstream target from the consumer contract: | `.scadpkg` | Rebuild, replay, cache, or further SimpleCAD editing is required | Complete durable definition closure, feature graphs, source snapshots, topology, connectors, constraints, and materials | SimpleCAD-specific archive | | `.FCStd` | A FreeCAD user needs an editable native document | Definition-owned, dependency-first native feature graphs; final body links; repeated instances; nested assemblies; names; solved placements; materials; connectors; constraints; grounding; revision; and content hashes | Requires FreeCADCmd/FreeCAD | | AP242 `.step` | Neutral CAD exchange or downstream OpenCASCADE tooling is required | Evaluated BREP, product hierarchy, shared definitions, occurrence names/placements, materials, colors, density, and named SimpleCAD property payloads | Canonical feature history is not reconstructed as AP242 features | +| Triangle `.obj` | Surface inspection or DCC exchange needs an indexed mesh | Direct OpenCASCADE tessellation of evaluated BREP with shared vertices and oriented triangles | Evaluated surface mesh only; no CAD hierarchy, feature semantics, quads, or materials | +| Binary `.stl` | Additive manufacturing or triangle-only consumers | The same direct OpenCASCADE BREP triangles | Facet soup only; no shared vertices, CAD hierarchy, feature semantics, or materials | ```python package_path = assembly_package.artifact_paths["product"] @@ -166,10 +168,21 @@ stl_report = scad.exporter.export_product_package_to_stl( package_path, "out/product.stl", ) +obj_report = scad.exporter.export_product_package_to_obj( + package_path, + "out/product.obj", +) print(step_report.definition_ids, step_report.occurrence_count) -print(stl_report.solid_count, stl_report.stl_triangle_count) +print(stl_report.solid_count, stl_report.triangle_count) +print(obj_report.vertex_count, obj_report.triangle_count) ``` +STL and OBJ use the same direct OpenCASCADE tessellation and parameters. Set +`linear_deflection` to the maximum chordal deviation in product units and +`angular_deflection_degrees` to the curved-surface angular limit. Both formats +contain oriented triangles; OBJ preserves shared vertex indices while binary STL +stores each facet independently. No remeshing or optional dependency is involved. + AP242 definition and occurrence metadata is stored in one standard `PROPERTY_DEFINITION_REPRESENTATION`. Its named `DESCRIPTIVE_REPRESENTATION_ITEM` records use @@ -180,9 +193,11 @@ connectors, constraints, grounding, name, and solved placement. `ProductSTEPExportReport` reports the schema, definition IDs, occurrence count, material IDs, metadata item count, and explicit limitations. -For tetrahedral meshing, install `simplecadapi[gmsh]` and run -`examples/12_ap242_gmsh_volume_mesh.py`. The example exports one `.scadpkg`, -converts it to AP242 STEP, imports it with Gmsh's OpenCASCADE kernel, rejects -imports with no 3D volumes, generates a dimension-3 mesh, writes `.msh`, and -always finalizes Gmsh. Gmsh remains optional and is never imported by the core -SDK or the product exporters. +For tetrahedral meshing, run the split example directly in dependency order: +`model.py` captures `.scadpkg`, `export_step.py` exports AP242 STEP, and +`export_fem_mesh.py` imports that STEP with Gmsh's OpenCASCADE kernel. The FEM +stage rejects imports with no 3D volumes, generates a dimension-3 mesh, writes +`.msh`, and always finalizes Gmsh. Install and invoke the optional dependency +with `uv run --extra gmsh python +examples/12_ap242_gmsh_volume_mesh/export_fem_mesh.py`; Gmsh is never imported +by the core SDK or product exporters. diff --git a/docs/updates/2.0.4b3.md b/docs/updates/2.0.4b3.md index bff8c48e..18ccb128 100644 --- a/docs/updates/2.0.4b3.md +++ b/docs/updates/2.0.4b3.md @@ -81,9 +81,18 @@ definition/occurrence properties. The property descriptions contain canonical sorted JSON for durable IDs and semantics. Feature history is not reconstructed as AP242 features; `.scadpkg` remains the canonical replayable artifact. -The optional `gmsh` extra and `examples/12_ap242_gmsh_volume_mesh.py` demonstrate -`.scadpkg -> AP242 STEP -> tetrahedral .msh` without adding Gmsh to the core -runtime dependency set. +Product mesh export now shares one direct OpenCASCADE tessellation of evaluated +BREP solids. OBJ and binary STL contain the same oriented triangles; OBJ keeps +shared vertex indices while STL stores independent facets. The public accuracy +controls are `linear_deflection`, `angular_deflection_degrees`, and `relative`. +No remeshing dependency or Python 3.11 version gate is involved, so mesh export +works across the package's complete supported Python range. + +The scripts in `examples/12_ap242_gmsh_volume_mesh/` build one `.scadpkg` and +demonstrate every package exporter and translator as independent downstream +commands: AP242 STEP, STL, OBJ, FCStd, FreeCAD, Fusion 360, and SolidWorks. +The optional Gmsh stage continues from AP242 STEP to a tetrahedral `.msh` +without adding Gmsh to the core runtime dependency set. ## 7. Native render crash isolation diff --git a/examples/12_ap242_gmsh_volume_mesh.py b/examples/12_ap242_gmsh_volume_mesh.py deleted file mode 100644 index 9c0ed159..00000000 --- a/examples/12_ap242_gmsh_volume_mesh.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Export one durable SimpleCAD part as FCStd, AP242 STEP, and Gmsh MSH.""" - -from __future__ import annotations -import argparse - -from dataclasses import dataclass -import importlib -from pathlib import Path -from typing import Any - -import simplecadapi as scad - - -OUT_DIR = Path(__file__).resolve().parent / "out" / "ap242_gmsh_volume_mesh" -CACHE = scad.CachePolicy(root=OUT_DIR / ".cache") - - -@dataclass(frozen=True, slots=True) -class GmshMeshReport: - step_path: Path - mesh_path: Path - volume_count: int - node_count: int - element_count: int - - -@scad.part( - id="ap242_gmsh_bracket", - revision="1.0.0", - inputs=(scad.file_input(path="examples/12_ap242_gmsh_volume_mesh.py"),), - cache=CACHE, -) -def build_bracket() -> scad.Part: - body = scad.make_box_rsolid( - width=40.0, - height=24.0, - depth=8.0, - bottom_face_center=(0.0, 0.0, 0.0), - ) - hole = scad.make_cylinder_rsolid( - radius=4.0, - height=12.0, - bottom_face_center=(-12.0, 0.0, -2.0), - ) - slot = scad.make_box_rsolid( - width=14.0, - height=6.0, - depth=12.0, - bottom_face_center=(10.0, 0.0, -2.0), - ) - body = scad.cut_rsolid(body, hole, slot) - part = scad.make_part_rpart( - part_id="ap242_gmsh_bracket", - body=body, - name="AP242 Gmsh bracket", - ) - material = scad.make_material_rmaterial( - material_id="aluminum_6061_t6", - name="Aluminum 6061-T6", - density=2.70e-6, - density_unit="kg/mm^3", - color=(0.72, 0.74, 0.78), - ) - return scad.assign_material_rpart(part, material) - - -def mesh_step_with_gmsh( - step_path: str | Path, - mesh_path: str | Path, - *, - mesh_size: float = 2.0, - gmsh_module: Any | None = None, -) -> GmshMeshReport: - """Import AP242 STEP with Gmsh's OCC kernel and write a 3D MSH mesh.""" - - if mesh_size <= 0.0: - raise ValueError("mesh_size must be positive") - source = Path(step_path).expanduser().resolve() - destination = Path(mesh_path).expanduser().resolve() - if not source.is_file(): - raise FileNotFoundError(source) - destination.parent.mkdir(parents=True, exist_ok=True) - gmsh = gmsh_module - if gmsh is None: - try: - gmsh = importlib.import_module("gmsh") - except ImportError as exc: - raise RuntimeError( - "Gmsh is optional; install it with `pip install simplecadapi[gmsh]`" - ) from exc - - initialized = False - try: - gmsh.initialize() - initialized = True - gmsh.model.add(source.stem) - gmsh.option.setString("Geometry.OCCTargetUnit", "MM") - imported = gmsh.model.occ.importShapes(str(source)) - gmsh.model.occ.synchronize() - volumes = gmsh.model.getEntities(3) - if not volumes: - raise RuntimeError( - f"Gmsh imported no 3D volumes from {source}; imported entities: {imported}" - ) - physical_group = gmsh.model.addPhysicalGroup( - 3, - [tag for _dimension, tag in volumes], - ) - gmsh.model.setPhysicalName(3, physical_group, source.stem) - gmsh.option.setNumber("Mesh.MeshSizeMin", float(mesh_size)) - gmsh.option.setNumber("Mesh.MeshSizeMax", float(mesh_size)) - gmsh.model.mesh.generate(3) - node_tags, _coordinates, _parameters = gmsh.model.mesh.getNodes() - _types, element_tags, _node_tags = gmsh.model.mesh.getElements(3) - element_count = sum(len(tags) for tags in element_tags) - if not len(node_tags) or not element_count: - raise RuntimeError("Gmsh generated an empty 3D mesh") - gmsh.write(str(destination)) - finally: - if initialized: - gmsh.finalize() - - if not destination.is_file() or destination.stat().st_size <= 0: - raise RuntimeError( - f"Gmsh did not create a non-empty mesh file at {destination}" - ) - return GmshMeshReport( - step_path=source, - mesh_path=destination, - volume_count=len(volumes), - node_count=len(node_tags), - element_count=element_count, - ) - - -def main(*, generate_mesh: bool = True) -> None: - result = build_bracket() - package_path = OUT_DIR / "ap242_gmsh_bracket.scadpkg" - scad.capture(result, package_path) - step_path = OUT_DIR / "ap242_gmsh_bracket.step" - mesh_path = OUT_DIR / "ap242_gmsh_bracket.msh" - fcstd_path = OUT_DIR / "ap242_gmsh_bracket.FCStd" - step_report = scad.exporter.export_product_package_to_step(package_path, step_path) - scad.translator.freecad_translator.translate_product_package_to_fcstd( - package_path, - str(fcstd_path), - document_name="AP242GmshBracket", - ) - mesh = mesh_step_with_gmsh(step_path, mesh_path) if generate_mesh else None - print("product_package", package_path) - print("ap242_step", step_report.output_path) - print("fcstd", fcstd_path) - print("ap242_metadata_items", step_report.metadata_item_count) - if mesh is not None: - print("gmsh_mesh", mesh.mesh_path) - print("gmsh_volumes", mesh.volume_count) - print("gmsh_nodes", mesh.node_count) - print("gmsh_3d_elements", mesh.element_count) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--skip-mesh", - action="store_true", - help="Export .scadpkg, AP242 STEP, and FCStd without optional Gmsh meshing.", - ) - args = parser.parse_args() - main(generate_mesh=not args.skip_mesh) diff --git a/examples/12_ap242_gmsh_volume_mesh/export_fcstd.py b/examples/12_ap242_gmsh_volume_mesh/export_fcstd.py new file mode 100644 index 00000000..2eea5962 --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/export_fcstd.py @@ -0,0 +1,27 @@ +"""Translate the captured bracket product package to editable FreeCAD FCStd.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +FCSTD_PATH = OUT_DIR / "ap242_gmsh_bracket.FCStd" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + output = scad.translator.freecad_translator.translate_product_package_to_fcstd( + data=PACKAGE_PATH, + output_path=str(FCSTD_PATH), + document_name="AP242GmshBracket", + ) + print("fcstd", output) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/export_fem_mesh.py b/examples/12_ap242_gmsh_volume_mesh/export_fem_mesh.py new file mode 100644 index 00000000..a940c2aa --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/export_fem_mesh.py @@ -0,0 +1,253 @@ +"""Generate a named three-dimensional Gmsh FEM mesh from AP242 STEP.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import importlib +import json +from pathlib import Path +from typing import Any + +import simplecadapi as scad +from simplecadapi.scene import parse_canonical_json, read_scene_package + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +STEP_PATH = OUT_DIR / "ap242_gmsh_bracket.step" +MESH_PATH = OUT_DIR / "ap242_gmsh_bracket.msh" +MAPPING_PATH = OUT_DIR / "ap242_gmsh_bracket.gmsh.json" + + +@dataclass(frozen=True, slots=True) +class GmshMeshReport: + step_path: Path + mesh_path: Path + mapping_path: Path | None + volume_count: int + node_count: int + element_count: int + interface_count: int + + +def _interface_faces(package_path: Path) -> list[dict[str, Any]]: + package = scad.read_product_package(package_path) + scene = read_scene_package(package.scene_bytes) + result: list[dict[str, Any]] = [] + for record in scene.manifest["entity_assets"]: + document = parse_canonical_json(scene.blobs[record["uri"]]) + for entity in document["entities"]: + if entity["kind"] != "face": + continue + tags = [str(tag) for tag in entity["tags"] if str(tag).startswith("interface.")] + for tag in tags: + result.append( + { + "name": tag, + "definition_id": document["definition_id"], + "entity_id": entity["entity_id"], + "topo_id": entity["topo_id"], + "area": float(entity["properties"]["area"]), + "centroid": [float(value) for value in entity["properties"]["centroid"]], + "bounds": { + key: [float(value) for value in entity["properties"]["bounds"][key]] + for key in ("min", "max") + }, + } + ) + names = [item["name"] for item in result] + if len(names) != len(set(names)): + raise ValueError("interface face tags must be unique within the meshed product") + return sorted(result, key=lambda item: item["name"]) + + +def _surface_signature(gmsh: Any, tag: int) -> dict[str, Any]: + bounds = gmsh.model.getBoundingBox(2, tag) + return { + "area": float(gmsh.model.occ.getMass(2, tag)), + "centroid": [float(value) for value in gmsh.model.occ.getCenterOfMass(2, tag)], + "bounds": { + "min": [float(value) for value in bounds[:3]], + "max": [float(value) for value in bounds[3:]], + }, + } + + +def _signature_error(target: dict[str, Any], candidate: dict[str, Any]) -> tuple[float, float, float]: + area_error = abs(candidate["area"] - target["area"]) / max(1.0, abs(target["area"])) + center_error = max( + abs(candidate["centroid"][index] - target["centroid"][index]) + for index in range(3) + ) + bounds_error = max( + abs(candidate["bounds"][side][index] - target["bounds"][side][index]) + for side in ("min", "max") + for index in range(3) + ) + return area_error, center_error, bounds_error + + +def _match_interface_surfaces(gmsh: Any, interfaces: list[dict[str, Any]]) -> list[dict[str, Any]]: + available = { + int(tag): _surface_signature(gmsh, int(tag)) + for dimension, tag in gmsh.model.getEntities(2) + if dimension == 2 + } + matched: list[dict[str, Any]] = [] + used: set[int] = set() + for interface in interfaces: + candidates = [] + for surface_tag, signature in available.items(): + if surface_tag in used: + continue + error = _signature_error(interface, signature) + candidates.append((error, surface_tag, signature)) + if not candidates: + raise RuntimeError(f"no Gmsh surface remains for {interface['name']}") + error, surface_tag, signature = min( + candidates, + key=lambda item: (item[0][1], item[0][2], item[0][0]), + ) + area_error, center_error, bounds_error = error + if area_error > 1.0e-6 or center_error > 1.0e-5 or bounds_error > 0.05: + raise RuntimeError( + f"could not match {interface['name']} to imported STEP surface: " + f"area_error={area_error:.3g}, center_error={center_error:.3g} mm, " + f"bounds_error={bounds_error:.3g} mm" + ) + used.add(surface_tag) + matched.append( + { + **interface, + "gmsh_surface_tag": surface_tag, + "gmsh_signature": signature, + "match_error": { + "relative_area": area_error, + "centroid_mm": center_error, + "bounds_mm": bounds_error, + }, + } + ) + return matched + + +def mesh_step_with_gmsh( + step_path: str | Path, + mesh_path: str | Path, + *, + package_path: str | Path | None = None, + mapping_path: str | Path | None = None, + mesh_size: float = 2.0, + gmsh_module: Any | None = None, +) -> GmshMeshReport: + """Import STEP, create semantic physical groups, and write a 3D MSH mesh.""" + + if mesh_size <= 0.0: + raise ValueError("mesh_size must be positive") + source = Path(step_path).expanduser().resolve() + destination = Path(mesh_path).expanduser().resolve() + package = Path(package_path).expanduser().resolve() if package_path is not None else None + mapping = Path(mapping_path).expanduser().resolve() if mapping_path is not None else None + if not source.is_file(): + raise FileNotFoundError(f"Run export_step.py first: {source}") + if package is not None and not package.is_file(): + raise FileNotFoundError(f"Run model.py first: {package}") + destination.parent.mkdir(parents=True, exist_ok=True) + if mapping is not None: + mapping.parent.mkdir(parents=True, exist_ok=True) + interfaces = _interface_faces(package) if package is not None else [] + + gmsh = gmsh_module + if gmsh is None: + try: + gmsh = importlib.import_module("gmsh") + except ImportError as exc: + raise RuntimeError( + "Gmsh is optional; install it with `pip install simplecadapi[gmsh]`" + ) from exc + + initialized = False + matched: list[dict[str, Any]] = [] + try: + gmsh.initialize() + initialized = True + gmsh.model.add(source.stem) + gmsh.option.setString("Geometry.OCCTargetUnit", "MM") + imported = gmsh.model.occ.importShapes(str(source)) + gmsh.model.occ.synchronize() + volumes = gmsh.model.getEntities(3) + if not volumes: + raise RuntimeError( + f"Gmsh imported no 3D volumes from {source}; imported entities: {imported}" + ) + volume_group = gmsh.model.addPhysicalGroup(3, [tag for _dimension, tag in volumes]) + gmsh.model.setPhysicalName(3, volume_group, "body.ap242_gmsh_bracket") + matched = _match_interface_surfaces(gmsh, interfaces) + for item in matched: + group = gmsh.model.addPhysicalGroup(2, [item["gmsh_surface_tag"]]) + gmsh.model.setPhysicalName(2, group, item["name"]) + item["physical_group_tag"] = int(group) + gmsh.option.setNumber("Mesh.MeshSizeMin", float(mesh_size)) + gmsh.option.setNumber("Mesh.MeshSizeMax", float(mesh_size)) + gmsh.model.mesh.generate(3) + node_tags, _coordinates, _parameters = gmsh.model.mesh.getNodes() + _types, element_tags, _node_tags = gmsh.model.mesh.getElements(3) + element_count = sum(len(tags) for tags in element_tags) + if not len(node_tags) or not element_count: + raise RuntimeError("Gmsh generated an empty 3D mesh") + gmsh.write(str(destination)) + finally: + if initialized: + gmsh.finalize() + + if not destination.is_file() or destination.stat().st_size <= 0: + raise RuntimeError(f"Gmsh did not create a non-empty mesh file at {destination}") + if mapping is not None: + mapping.write_text( + json.dumps( + { + "schema_version": "1.0", + "source_step": str(source), + "source_package": str(package) if package is not None else None, + "volume_physical_name": "body.ap242_gmsh_bracket", + "interfaces": matched, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + return GmshMeshReport( + step_path=source, + mesh_path=destination, + mapping_path=mapping, + volume_count=len(volumes), + node_count=len(node_tags), + element_count=element_count, + interface_count=len(matched), + ) + + +def main(*, mesh_size: float = 2.0) -> None: + report = mesh_step_with_gmsh( + STEP_PATH, + MESH_PATH, + package_path=PACKAGE_PATH, + mapping_path=MAPPING_PATH, + mesh_size=mesh_size, + ) + print("gmsh_mesh", report.mesh_path) + print("gmsh_mapping", report.mapping_path) + print("gmsh_volumes", report.volume_count) + print("gmsh_interfaces", report.interface_count) + print("gmsh_nodes", report.node_count) + print("gmsh_3d_elements", report.element_count) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mesh-size", type=float, default=2.0) + args = parser.parse_args() + main(mesh_size=args.mesh_size) diff --git a/examples/12_ap242_gmsh_volume_mesh/export_obj.py b/examples/12_ap242_gmsh_volume_mesh/export_obj.py new file mode 100644 index 00000000..4b66797e --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/export_obj.py @@ -0,0 +1,33 @@ +"""Export the captured bracket directly from evaluated BREP as triangle OBJ.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +OBJ_PATH = OUT_DIR / "ap242_gmsh_bracket.obj" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + report = scad.exporter.export_product_package_to_obj( + data=PACKAGE_PATH, + output_path=OBJ_PATH, + linear_deflection=0.05, + angular_deflection_degrees=10.0, + ) + print("obj", report.output_path) + print("obj_vertices", report.vertex_count) + print("obj_triangles", report.triangle_count) + print("tessellation_backend", report.tessellation_backend) + print("linear_deflection", report.linear_deflection) + print("angular_deflection_degrees", report.angular_deflection_degrees) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/export_step.py b/examples/12_ap242_gmsh_volume_mesh/export_step.py new file mode 100644 index 00000000..7b278428 --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/export_step.py @@ -0,0 +1,27 @@ +"""Export the captured bracket product package as an AP242 STEP file.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +STEP_PATH = OUT_DIR / "ap242_gmsh_bracket.step" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + report = scad.exporter.export_product_package_to_step( + data=PACKAGE_PATH, + output_path=STEP_PATH, + ) + print("ap242_step", report.output_path) + print("ap242_metadata_items", report.metadata_item_count) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/export_stl.py b/examples/12_ap242_gmsh_volume_mesh/export_stl.py new file mode 100644 index 00000000..9163b2b4 --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/export_stl.py @@ -0,0 +1,33 @@ +"""Export the captured bracket directly from evaluated BREP as binary STL.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +STL_PATH = OUT_DIR / "ap242_gmsh_bracket.stl" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + report = scad.exporter.export_product_package_to_stl( + data=PACKAGE_PATH, + output_path=STL_PATH, + linear_deflection=0.05, + angular_deflection_degrees=10.0, + ) + print("stl", report.output_path) + print("stl_vertices", report.vertex_count) + print("stl_triangles", report.triangle_count) + print("tessellation_backend", report.tessellation_backend) + print("linear_deflection", report.linear_deflection) + print("angular_deflection_degrees", report.angular_deflection_degrees) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/model.py b/examples/12_ap242_gmsh_volume_mesh/model.py new file mode 100644 index 00000000..f41f94ce --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/model.py @@ -0,0 +1,181 @@ +"""Build a named single-solid L-bracket for STEP and Gmsh workflows.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +CACHE = scad.CachePolicy(root=OUT_DIR / ".cache") + +BRACKET_WIDTH = 40.0 +BRACKET_HEIGHT = 36.0 +BRACKET_DEPTH = 28.0 +PLATE_THICKNESS = 4.0 +MOUNT_HOLE_RADIUS = 2.5 +MOUNT_HOLE_SPACING = 22.0 +LOAD_HOLE_RADIUS = 3.0 +LOAD_HOLE_X = 12.0 +RIB_THICKNESS = 3.0 +RIB_HEIGHT = 18.0 +RIB_DEPTH = 18.0 + + +def _tag_closest_face( + body: scad.Solid, + *, + center: tuple[float, float, float], + normal: tuple[float, float, float] | None, + tag: str, +) -> scad.Solid: + """Tag one final face while preserving the active graph source binding.""" + + candidates: list[tuple[float, scad.Face]] = [] + for face in body.get_faces(): + actual_center = face.get_center() + if normal is not None: + actual_normal = face.get_normal_at() + alignment = ( + actual_normal.x * normal[0] + + actual_normal.y * normal[1] + + actual_normal.z * normal[2] + ) + if alignment < 0.8: + continue + distance_sq = ( + (actual_center.x - center[0]) ** 2 + + (actual_center.y - center[1]) ** 2 + + (actual_center.z - center[2]) ** 2 + ) + candidates.append((distance_sq, face)) + if not candidates: + raise ValueError(f"no final face matches {tag}") + distance_sq, selected = min(candidates, key=lambda item: item[0]) + if distance_sq > 100.0: + raise ValueError(f"final face match for {tag} is too distant: distance^2={distance_sq}") + return scad.apply_tag_rselection(scope=body, targets=[selected], tag=tag) + + +def _rib(*, y_center: float) -> scad.Solid: + profile = scad.make_polyline_rwire( + [ + (0.0, y_center - RIB_THICKNESS / 2.0, PLATE_THICKNESS), + (0.0, y_center - RIB_THICKNESS / 2.0, PLATE_THICKNESS + RIB_HEIGHT), + (RIB_DEPTH, y_center - RIB_THICKNESS / 2.0, PLATE_THICKNESS), + ], + closed=True, + ) + face = scad.make_face_from_wire_rface(profile, normal=(0.0, 1.0, 0.0)) + return scad.extrude_rsolid( + profile=face, + direction=(0.0, 1.0, 0.0), + distance=RIB_THICKNESS, + tag_prefix="bracket.rib", + ) + + +@scad.part( + id="ap242_gmsh_bracket", + revision="2.0.0", + inputs=(scad.file_input(path="examples/12_ap242_gmsh_volume_mesh/model.py"),), + cache=CACHE, +) +def build_bracket() -> scad.Part: + """Create one manifold L-bracket with named FEM boundary interfaces.""" + + wall = scad.make_box_rsolid( + width=PLATE_THICKNESS, + height=BRACKET_WIDTH, + depth=BRACKET_HEIGHT, + bottom_face_center=(0.0, 0.0, 0.0), + tag_prefix="bracket.wall", + ) + shelf = scad.make_box_rsolid( + width=BRACKET_DEPTH, + height=BRACKET_WIDTH, + depth=PLATE_THICKNESS, + bottom_face_center=(BRACKET_DEPTH / 2.0 - PLATE_THICKNESS / 2.0, 0.0, 0.0), + tag_prefix="bracket.shelf", + ) + body = scad.union_rsolid(wall, shelf, _rib(y_center=-11.0), _rib(y_center=11.0)) + + cutters = [] + for index, y in enumerate( + (-MOUNT_HOLE_SPACING / 2.0, MOUNT_HOLE_SPACING / 2.0), + start=1, + ): + cutters.append( + scad.make_cylinder_rsolid( + radius=MOUNT_HOLE_RADIUS, + height=PLATE_THICKNESS + 2.0, + bottom_face_center=(-PLATE_THICKNESS / 2.0 - 1.0, y, BRACKET_HEIGHT * 0.62), + axis=(1.0, 0.0, 0.0), + tag_prefix=f"bracket.mount_hole_{index}", + ) + ) + cutters.append( + scad.make_cylinder_rsolid( + radius=LOAD_HOLE_RADIUS, + height=PLATE_THICKNESS + 2.0, + bottom_face_center=(LOAD_HOLE_X, 0.0, -1.0), + axis=(0.0, 0.0, 1.0), + tag_prefix="bracket.load_hole", + ) + ) + body = scad.cut_rsolid(body, cutters, skip_non_intersecting=False) + body = scad.apply_tag(body, "role.structural_l_bracket") + + body = _tag_closest_face( + body, + center=(0.0, 0.0, BRACKET_HEIGHT / 2.0), + normal=(-1.0, 0.0, 0.0), + tag="interface.fixed_support", + ) + body = _tag_closest_face( + body, + center=((BRACKET_DEPTH + RIB_DEPTH - PLATE_THICKNESS) / 2.0, 0.0, PLATE_THICKNESS), + normal=(0.0, 0.0, 1.0), + tag="interface.load_surface", + ) + for index, y in enumerate((-MOUNT_HOLE_SPACING / 2.0, MOUNT_HOLE_SPACING / 2.0), start=1): + body = _tag_closest_face( + body, + center=(PLATE_THICKNESS / 2.0, y, BRACKET_HEIGHT * 0.62), + normal=None, + tag=f"interface.mount_hole_{index}", + ) + body = _tag_closest_face( + body, + center=(LOAD_HOLE_X, 0.0, PLATE_THICKNESS / 2.0), + normal=None, + tag="interface.load_hole", + ) + + part = scad.make_part_rpart( + part_id="ap242_gmsh_bracket", + body=body, + name="Named ribbed L-bracket", + ) + material = scad.make_material_rmaterial( + material_id="aluminum_6061_t6", + name="Aluminum 6061-T6", + density=2.70e-6, + density_unit="kg/mm^3", + color=(0.72, 0.74, 0.78), + ) + return scad.assign_material_rpart(part, material) + + +def main() -> None: + result = build_bracket() + scad.capture(result, PACKAGE_PATH) + print("product_package", PACKAGE_PATH) + print("faces", len(result.part.body.get_faces())) + print("volume", f"{result.part.body.get_volume():.3f}") + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/run_calculix.py b/examples/12_ap242_gmsh_volume_mesh/run_calculix.py new file mode 100644 index 00000000..4e15ca4f --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/run_calculix.py @@ -0,0 +1,544 @@ +"""Run a linear-static CalculiX analysis of the named Gmsh bracket mesh.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import importlib +import json +import math +import os +from pathlib import Path +import re +import shutil +import subprocess +from typing import Any, Callable, Sequence + +import numpy as np + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +MESH_PATH = OUT_DIR / "ap242_gmsh_bracket.msh" +INPUT_PATH = OUT_DIR / "ap242_gmsh_bracket_static.inp" +SUMMARY_PATH = OUT_DIR / "ap242_gmsh_bracket_static.calculix.json" + +FIXED_INTERFACE = "interface.fixed_support" +LOAD_INTERFACE = "interface.load_surface" +MATERIAL_NAME = "ALUMINUM_6061_T6" +YOUNGS_MODULUS_MPA = 68_900.0 +POISSON_RATIO = 0.33 +DEFAULT_LOAD_Z_N = -1_000.0 +LINEAR_SOLVERS = { + "SPOOLES", + "ITERATIVE CHOLESKY", + "ITERATIVE SCALING", +} + + +@dataclass(frozen=True, slots=True) +class CalculiXInputReport: + mesh_path: Path + input_path: Path + node_count: int + element_count: int + fixed_node_count: int + load_node_count: int + load_surface_area_mm2: float + applied_load_z_n: float + linear_solver: str = "SPOOLES" + + +@dataclass(frozen=True, slots=True) +class CalculiXRunReport: + executable: Path + input_path: Path + dat_path: Path + frd_path: Path + log_path: Path + summary_path: Path + max_displacement_mm: float + max_displacement_node: int + max_von_mises_mpa: float + max_von_mises_element: int + max_von_mises_integration_point: int + reaction_force_x_n: float + reaction_force_y_n: float + reaction_force_z_n: float + force_balance_z_n: float + + +@dataclass(frozen=True, slots=True) +class _MeshData: + nodes: tuple[tuple[int, float, float, float], ...] + tetrahedra: tuple[tuple[int, int, int, int, int], ...] + fixed_nodes: tuple[int, ...] + load_triangles: tuple[tuple[int, int, int], ...] + + +def _optional_gmsh(gmsh_module: Any | None) -> Any: + if gmsh_module is not None: + return gmsh_module + try: + return importlib.import_module("gmsh") + except ImportError as exc: + raise RuntimeError( + "CalculiX FEM support is optional; install Python dependencies with " + "`pip install simplecadapi[fem]`" + ) from exc + + +def _physical_group_tag(gmsh: Any, name: str, dimension: int) -> int: + matches = [ + int(tag) + for dim, tag in gmsh.model.getPhysicalGroups(dimension) + if int(dim) == dimension and gmsh.model.getPhysicalName(dim, tag) == name + ] + if len(matches) != 1: + raise ValueError( + f"mesh must contain exactly one {dimension}D physical group named {name!r}; " + f"found {len(matches)}" + ) + return matches[0] + + +def _read_gmsh_mesh(mesh_path: Path, gmsh: Any) -> _MeshData: + initialized = False + try: + gmsh.initialize() + initialized = True + gmsh.open(str(mesh_path)) + + node_tags, coordinates, _parameters = gmsh.model.mesh.getNodes() + node_ids = [int(tag) for tag in node_tags] + coordinate_values = np.asarray(coordinates, dtype=float).reshape((-1, 3)) + if not node_ids or len(node_ids) != len(coordinate_values): + raise ValueError("Gmsh mesh contains no valid three-dimensional nodes") + nodes = tuple( + (node_id, float(point[0]), float(point[1]), float(point[2])) + for node_id, point in zip(node_ids, coordinate_values) + ) + + tetrahedron_type = int(gmsh.model.mesh.getElementType("Tetrahedron", 1)) + volume_types = {int(value) for value in gmsh.model.mesh.getElementTypes(3)} + if volume_types != {tetrahedron_type}: + raise ValueError( + "CalculiX example requires only first-order tetrahedral volume elements; " + f"found Gmsh types {sorted(volume_types)}" + ) + element_tags, element_nodes = gmsh.model.mesh.getElementsByType(tetrahedron_type) + element_ids = [int(tag) for tag in element_tags] + connectivity = np.asarray(element_nodes, dtype=np.int64).reshape((-1, 4)) + if not element_ids or len(element_ids) != len(connectivity): + raise ValueError("Gmsh mesh contains no valid first-order tetrahedra") + tetrahedra = tuple( + (element_id, *(int(node) for node in element)) + for element_id, element in zip(element_ids, connectivity) + ) + + fixed_tag = _physical_group_tag(gmsh, FIXED_INTERFACE, 2) + fixed_node_tags, _fixed_coordinates = gmsh.model.mesh.getNodesForPhysicalGroup( + 2, fixed_tag + ) + fixed_nodes = tuple(sorted({int(tag) for tag in fixed_node_tags})) + if not fixed_nodes: + raise ValueError(f"physical group {FIXED_INTERFACE!r} contains no nodes") + + load_tag = _physical_group_tag(gmsh, LOAD_INTERFACE, 2) + load_entities = gmsh.model.getEntitiesForPhysicalGroup(2, load_tag) + triangle_type = int(gmsh.model.mesh.getElementType("Triangle", 1)) + triangles: list[tuple[int, int, int]] = [] + for entity_tag in load_entities: + _triangle_tags, triangle_nodes = gmsh.model.mesh.getElementsByType( + triangle_type, int(entity_tag) + ) + values = np.asarray(triangle_nodes, dtype=np.int64).reshape((-1, 3)) + triangles.extend(tuple(int(node) for node in triangle) for triangle in values) + if not triangles: + raise ValueError(f"physical group {LOAD_INTERFACE!r} contains no triangles") + load_triangles = tuple(triangles) + finally: + if initialized: + gmsh.finalize() + + return _MeshData( + nodes=nodes, + tetrahedra=tetrahedra, + fixed_nodes=fixed_nodes, + load_triangles=load_triangles, + ) + + +def _append_node_set(lines: list[str], name: str, ids: Sequence[int]) -> None: + lines.append(f"*NSET,NSET={name}") + for start in range(0, len(ids), 16): + lines.append(",".join(str(value) for value in ids[start : start + 16])) + + +def build_calculix_input( + mesh_path: str | Path, + input_path: str | Path, + *, + load_z_n: float = DEFAULT_LOAD_Z_N, + youngs_modulus_mpa: float = YOUNGS_MODULUS_MPA, + poisson_ratio: float = POISSON_RATIO, + linear_solver: str = "SPOOLES", + gmsh_module: Any | None = None, +) -> CalculiXInputReport: + """Convert the semantic Gmsh mesh into a CalculiX linear-static deck.""" + + if not math.isfinite(load_z_n) or load_z_n == 0.0: + raise ValueError("load_z_n must be finite and nonzero") + if not math.isfinite(youngs_modulus_mpa) or youngs_modulus_mpa <= 0.0: + raise ValueError("youngs_modulus_mpa must be positive") + if not math.isfinite(poisson_ratio) or not (-1.0 < poisson_ratio < 0.5): + raise ValueError("poisson_ratio must be between -1 and 0.5") + normalized_solver = linear_solver.strip().upper() + if normalized_solver not in LINEAR_SOLVERS: + raise ValueError( + f"linear_solver must be one of {sorted(LINEAR_SOLVERS)}" + ) + + source = Path(mesh_path).expanduser().resolve() + destination = Path(input_path).expanduser().resolve() + if not source.is_file(): + raise FileNotFoundError(f"Run export_fem_mesh.py first: {source}") + mesh = _read_gmsh_mesh(source, _optional_gmsh(gmsh_module)) + coordinates = { + node_id: np.asarray((x, y, z), dtype=float) + for node_id, x, y, z in mesh.nodes + } + + nodal_loads: dict[int, float] = {} + triangle_areas: list[float] = [] + for triangle in mesh.load_triangles: + first, second, third = (coordinates[node] for node in triangle) + area = 0.5 * float(np.linalg.norm(np.cross(second - first, third - first))) + if area <= 0.0: + raise ValueError("load surface contains a degenerate triangle") + triangle_areas.append(area) + total_area = math.fsum(triangle_areas) + for triangle, area in zip(mesh.load_triangles, triangle_areas): + share = load_z_n * area / (3.0 * total_area) + for node_id in triangle: + nodal_loads[node_id] = nodal_loads.get(node_id, 0.0) + share + + lines = [ + "*HEADING", + "SimpleCADAPI ribbed L-bracket linear static analysis", + "** Consistent units: mm, N, MPa", + "*NODE,NSET=NALL", + ] + lines.extend( + f"{node_id},{x:.12g},{y:.12g},{z:.12g}" + for node_id, x, y, z in mesh.nodes + ) + lines.append("*ELEMENT,TYPE=C3D4,ELSET=EALL") + lines.extend( + f"{element_id},{first},{second},{third},{fourth}" + for element_id, first, second, third, fourth in mesh.tetrahedra + ) + _append_node_set(lines, "FIXED_SUPPORT", mesh.fixed_nodes) + _append_node_set(lines, "LOAD_SURFACE", tuple(sorted(nodal_loads))) + lines.extend( + [ + f"*MATERIAL,NAME={MATERIAL_NAME}", + "*ELASTIC", + f"{youngs_modulus_mpa:.12g},{poisson_ratio:.12g}", + f"*SOLID SECTION,ELSET=EALL,MATERIAL={MATERIAL_NAME}", + "*BOUNDARY", + "FIXED_SUPPORT,1,3", + "*STEP", + f"*STATIC,SOLVER={normalized_solver}", + "*CLOAD", + ] + ) + lines.extend( + f"{node_id},3,{force:.12g}" + for node_id, force in sorted(nodal_loads.items()) + ) + lines.extend( + [ + "*NODE PRINT,NSET=NALL", + "U", + "*NODE PRINT,NSET=FIXED_SUPPORT,TOTALS=ONLY", + "RF", + "*EL PRINT,ELSET=EALL", + "S", + "*NODE FILE", + "U", + "*EL FILE", + "S", + "*END STEP", + ] + ) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text("\n".join(lines) + "\n", encoding="ascii") + return CalculiXInputReport( + mesh_path=source, + input_path=destination, + node_count=len(mesh.nodes), + element_count=len(mesh.tetrahedra), + fixed_node_count=len(mesh.fixed_nodes), + load_node_count=len(nodal_loads), + load_surface_area_mm2=total_area, + applied_load_z_n=math.fsum(nodal_loads.values()), + linear_solver=normalized_solver, + ) + + +_FLOAT_PATTERN = re.compile(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][-+]?\d+)?") + + +def _numeric_fields(line: str) -> list[float]: + return [float(value) for value in _FLOAT_PATTERN.findall(line)] + + +def _von_mises(stress: Sequence[float]) -> float: + sxx, syy, szz, sxy, sxz, syz = stress + return math.sqrt( + 0.5 * ((sxx - syy) ** 2 + (syy - szz) ** 2 + (szz - sxx) ** 2) + + 3.0 * (sxy**2 + sxz**2 + syz**2) + ) + + +def parse_calculix_dat(path: str | Path) -> dict[str, int | float]: + """Extract final-step displacement, stress, and support reaction facts.""" + + source = Path(path) + if not source.is_file(): + raise FileNotFoundError(f"CalculiX result file is missing: {source}") + displacements: list[tuple[float, int]] = [] + stresses: list[tuple[float, int, int]] = [] + reaction_force: tuple[float, float, float] | None = None + section: str | None = None + for line in source.read_text(encoding="utf-8", errors="replace").splitlines(): + lowered = line.lower() + if "displacements (vx,vy,vz)" in lowered: + section = "displacements" + displacements = [] + continue + if "total force (fx,fy,fz) for set fixed_support" in lowered: + section = "reaction" + reaction_force = None + continue + if "stresses (elem, integ.pnt." in lowered: + section = "stresses" + stresses = [] + continue + values = _numeric_fields(line) + if section == "displacements" and len(values) == 4: + node = int(values[0]) + magnitude = math.sqrt(math.fsum(value * value for value in values[1:4])) + displacements.append((magnitude, node)) + elif section == "stresses" and len(values) >= 8: + element = int(values[0]) + integration_point = int(values[1]) + stresses.append( + (_von_mises(values[2:8]), element, integration_point) + ) + elif section == "reaction" and len(values) == 3: + reaction_force = (values[0], values[1], values[2]) + if not displacements: + raise RuntimeError(f"no nodal displacements found in {source}") + if not stresses: + raise RuntimeError(f"no integration-point stresses found in {source}") + if reaction_force is None: + raise RuntimeError(f"no total support reaction found in {source}") + displacement, node = max(displacements) + stress, element, integration_point = max(stresses) + return { + "max_displacement_mm": displacement, + "max_displacement_node": node, + "max_von_mises_mpa": stress, + "max_von_mises_element": element, + "max_von_mises_integration_point": integration_point, + "reaction_force_x_n": reaction_force[0], + "reaction_force_y_n": reaction_force[1], + "reaction_force_z_n": reaction_force[2], + } + +def _ccx_version_key(path: Path) -> tuple[int, ...]: + values = tuple(int(value) for value in re.findall(r"\d+", path.name)) + return values or (0,) + + +def resolve_calculix_executable(explicit: str | Path | None = None) -> Path: + """Resolve --ccx, CALCULIX_BIN, unversioned ccx, then versioned ccx_* binaries.""" + + requested = str(explicit) if explicit is not None else os.environ.get("CALCULIX_BIN") + if requested: + candidate = Path(requested).expanduser() + resolved = Path(shutil.which(str(candidate)) or candidate).resolve() + if resolved.is_file() and os.access(resolved, os.X_OK): + return resolved + raise FileNotFoundError(f"CalculiX executable is not runnable: {requested}") + unversioned = shutil.which("ccx") + if unversioned: + return Path(unversioned).resolve() + versioned: list[Path] = [] + for directory in os.environ.get("PATH", "").split(os.pathsep): + if directory: + versioned.extend(Path(directory).glob("ccx_*")) + runnable = { + path.resolve() + for path in versioned + if path.is_file() and os.access(path, os.X_OK) + } + if runnable: + return max(runnable, key=_ccx_version_key) + raise FileNotFoundError( + "CalculiX solver not found. On macOS run " + "`brew install costerwi/homebrew-calculix/calculix-ccx`, then pass " + "`--ccx $(brew --prefix calculix-ccx)/bin/ccx_2.23` or set CALCULIX_BIN." + ) + + +def run_calculix_static( + input_report: CalculiXInputReport, + *, + ccx: str | Path | None = None, + summary_path: str | Path | None = None, + timeout_seconds: float = 300.0, + runner: Callable[..., Any] = subprocess.run, +) -> CalculiXRunReport: + """Execute ccx for one prepared deck and summarize its final static result.""" + + if not math.isfinite(timeout_seconds) or timeout_seconds <= 0.0: + raise ValueError("timeout_seconds must be positive") + executable = resolve_calculix_executable(ccx) + source = input_report.input_path.resolve() + destination = ( + Path(summary_path).expanduser().resolve() + if summary_path is not None + else source.with_suffix(".calculix.json") + ) + completed = runner( + [str(executable), source.stem], + cwd=source.parent, + capture_output=True, + text=True, + check=False, + timeout=timeout_seconds, + ) + log_path = source.with_suffix(".ccx.log") + log_path.write_text( + (completed.stdout or "") + + ("\n" if completed.stdout and completed.stderr else "") + + (completed.stderr or ""), + encoding="utf-8", + ) + if completed.returncode != 0: + raise RuntimeError( + f"CalculiX exited with status {completed.returncode}; see {log_path}" + ) + dat_path = source.with_suffix(".dat") + frd_path = source.with_suffix(".frd") + if not frd_path.is_file() or frd_path.stat().st_size <= 0: + raise RuntimeError(f"CalculiX did not create a non-empty FRD result: {frd_path}") + maxima = parse_calculix_dat(dat_path) + maxima["force_balance_z_n"] = ( + float(maxima["reaction_force_z_n"]) + input_report.applied_load_z_n + ) + payload = { + "schema_version": "1.0", + "analysis": "linear_static", + "units": {"length": "mm", "force": "N", "stress": "MPa"}, + "material": { + "name": MATERIAL_NAME, + "youngs_modulus_mpa": YOUNGS_MODULUS_MPA, + "poisson_ratio": POISSON_RATIO, + }, + "input": { + "mesh_path": str(input_report.mesh_path), + "input_path": str(input_report.input_path), + "node_count": input_report.node_count, + "element_count": input_report.element_count, + "fixed_node_count": input_report.fixed_node_count, + "load_node_count": input_report.load_node_count, + "load_surface_area_mm2": input_report.load_surface_area_mm2, + "applied_load_z_n": input_report.applied_load_z_n, + "linear_solver": input_report.linear_solver, + }, + "results": maxima, + "artifacts": { + "dat": str(dat_path), + "frd": str(frd_path), + "log": str(log_path), + }, + "solver": str(executable), + } + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + return CalculiXRunReport( + executable=executable, + input_path=source, + dat_path=dat_path, + frd_path=frd_path, + log_path=log_path, + summary_path=destination, + **maxima, + ) + + +def main( + *, + mesh_path: Path = MESH_PATH, + input_path: Path = INPUT_PATH, + summary_path: Path = SUMMARY_PATH, + load_z_n: float = DEFAULT_LOAD_Z_N, + ccx: str | None = None, + prepare_only: bool = False, + timeout_seconds: float = 300.0, + linear_solver: str = "SPOOLES", +) -> None: + input_report = build_calculix_input( + mesh_path, + input_path, + load_z_n=load_z_n, + linear_solver=linear_solver, + ) + print("calculix_input", input_report.input_path) + print("calculix_nodes", input_report.node_count) + print("calculix_elements", input_report.element_count) + print("calculix_fixed_nodes", input_report.fixed_node_count) + print("calculix_load_nodes", input_report.load_node_count) + print("calculix_load_z_n", f"{input_report.applied_load_z_n:.9g}") + print("calculix_linear_solver", input_report.linear_solver) + if prepare_only: + return + report = run_calculix_static( + input_report, + ccx=ccx, + summary_path=summary_path, + timeout_seconds=timeout_seconds, + ) + print("calculix_frd", report.frd_path) + print("calculix_summary", report.summary_path) + print("max_displacement_mm", f"{report.max_displacement_mm:.9g}") + print("max_von_mises_mpa", f"{report.max_von_mises_mpa:.9g}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mesh", type=Path, default=MESH_PATH) + parser.add_argument("--input", type=Path, default=INPUT_PATH) + parser.add_argument("--summary", type=Path, default=SUMMARY_PATH) + parser.add_argument("--load-z", type=float, default=DEFAULT_LOAD_Z_N) + parser.add_argument("--ccx") + parser.add_argument("--linear-solver", default="SPOOLES") + parser.add_argument("--prepare-only", action="store_true") + parser.add_argument("--timeout", type=float, default=300.0) + arguments = parser.parse_args() + main( + mesh_path=arguments.mesh, + input_path=arguments.input, + summary_path=arguments.summary, + load_z_n=arguments.load_z, + ccx=arguments.ccx, + linear_solver=arguments.linear_solver, + prepare_only=arguments.prepare_only, + timeout_seconds=arguments.timeout, + ) diff --git a/examples/12_ap242_gmsh_volume_mesh/study_mesh_convergence.py b/examples/12_ap242_gmsh_volume_mesh/study_mesh_convergence.py new file mode 100644 index 00000000..49af33a5 --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/study_mesh_convergence.py @@ -0,0 +1,383 @@ +"""Refine the Gmsh/CalculiX mesh until two adjacent response pairs form a platform.""" + +from __future__ import annotations + +import argparse +import csv +from dataclasses import asdict, dataclass +import json +import math +from pathlib import Path +import sys +import subprocess +from typing import Sequence + +EXAMPLE_DIR = Path(__file__).resolve().parent +if str(EXAMPLE_DIR) not in sys.path: + sys.path.insert(0, str(EXAMPLE_DIR)) + +from export_fem_mesh import PACKAGE_PATH, STEP_PATH, mesh_step_with_gmsh +from run_calculix import DEFAULT_LOAD_Z_N, build_calculix_input, run_calculix_static + + +OUT_DIR = EXAMPLE_DIR.parent / "out" / "ap242_gmsh_volume_mesh" +STUDY_DIR = OUT_DIR / "mesh_convergence" +REPORT_PATH = STUDY_DIR / "mesh_convergence.json" +CSV_PATH = STUDY_DIR / "mesh_convergence.csv" +DEFAULT_MESH_SIZES = (3.0, 2.0, 1.5, 1.0, 0.75, 0.5, 0.375, 0.3, 0.28, 0.27, 0.25) +DISPLACEMENT_TOLERANCE = 0.05 +STRESS_TOLERANCE = 0.10 +REQUIRED_PLATFORM_PAIRS = 3 + +@dataclass(frozen=True, slots=True) +class MeshConvergenceLevel: + mesh_size_mm: float + node_count: int + element_count: int + fixed_node_count: int + load_node_count: int + max_displacement_mm: float + max_von_mises_mpa: float + reaction_force_z_n: float + force_balance_z_n: float + displacement_change_from_previous: float | None + stress_change_from_previous: float | None + mesh_path: str + input_path: str + summary_path: str + linear_solver: str = "SPOOLES" + + +def _slug(mesh_size: float) -> str: + return f"h{mesh_size:g}".replace(".", "p") + + +def _relative_change(current: float, previous: float) -> float: + return abs(current - previous) / max(abs(current), 1.0e-30) + + +def _pair_is_converged( + level: MeshConvergenceLevel, + *, + displacement_tolerance: float, + stress_tolerance: float, +) -> bool: + return ( + level.displacement_change_from_previous is not None + and level.stress_change_from_previous is not None + and level.displacement_change_from_previous <= displacement_tolerance + and level.stress_change_from_previous <= stress_tolerance + ) + + +def assess_mesh_convergence( + levels: Sequence[MeshConvergenceLevel], + *, + displacement_tolerance: float = DISPLACEMENT_TOLERANCE, + stress_tolerance: float = STRESS_TOLERANCE, + required_platform_pairs: int = REQUIRED_PLATFORM_PAIRS, +) -> dict[str, object]: + """Recommend N-1 only after N confirms a sustained response platform.""" + + if len(levels) < 3: + raise ValueError("mesh convergence requires at least three refinement levels") + if required_platform_pairs < 1: + raise ValueError("required_platform_pairs must be positive") + converged_pairs = [ + _pair_is_converged( + level, + displacement_tolerance=displacement_tolerance, + stress_tolerance=stress_tolerance, + ) + for level in levels[1:] + ] + trailing_converged_pairs = 0 + for converged in reversed(converged_pairs): + if not converged: + break + trailing_converged_pairs += 1 + platform_reached = trailing_converged_pairs >= required_platform_pairs + finest = levels[-1] + recommended = levels[-2] if platform_reached else None + return { + "displacement_tolerance": displacement_tolerance, + "stress_tolerance": stress_tolerance, + "required_consecutive_converged_pairs": required_platform_pairs, + "trailing_converged_pairs": trailing_converged_pairs, + "platform_reached": platform_reached, + "mesh_independent": platform_reached, + "recommended_mesh_size_mm": ( + None if recommended is None else recommended.mesh_size_mm + ), + "production_level_n_minus_1": ( + None if recommended is None else len(levels) - 1 + ), + "verification_level_n": None if recommended is None else len(levels), + "finest_pair_displacement_within_tolerance": ( + finest.displacement_change_from_previous is not None + and finest.displacement_change_from_previous <= displacement_tolerance + ), + "finest_pair_stress_within_tolerance": ( + finest.stress_change_from_previous is not None + and finest.stress_change_from_previous <= stress_tolerance + ), + "stress_caution": ( + None + if platform_reached + else "No sustained platform was observed; peak stress may be mesh-sensitive or singular." + ), + } + + +def run_mesh_convergence_study( + *, + mesh_sizes: Sequence[float] = DEFAULT_MESH_SIZES, + ccx: str | Path | None = None, + load_z_n: float = DEFAULT_LOAD_Z_N, + study_dir: str | Path = STUDY_DIR, + displacement_tolerance: float = DISPLACEMENT_TOLERANCE, + stress_tolerance: float = STRESS_TOLERANCE, + required_platform_pairs: int = REQUIRED_PLATFORM_PAIRS, + solver_timeout_seconds: float = 300.0, + linear_solver: str = "SPOOLES", + resume_report: str | Path | None = None, +) -> dict[str, object]: + if len(mesh_sizes) < 3: + raise ValueError("provide at least three mesh sizes") + sizes = tuple(float(value) for value in mesh_sizes) + if any(not math.isfinite(value) or value <= 0.0 for value in sizes): + raise ValueError("mesh sizes must be finite and positive") + if any(first <= second for first, second in zip(sizes, sizes[1:])): + raise ValueError("mesh sizes must be strictly decreasing from coarse to fine") + if ( + not math.isfinite(displacement_tolerance) + or displacement_tolerance <= 0.0 + or not math.isfinite(stress_tolerance) + or stress_tolerance <= 0.0 + ): + raise ValueError("convergence tolerances must be finite and positive") + if required_platform_pairs < 1: + raise ValueError("required_platform_pairs must be positive") + if not math.isfinite(solver_timeout_seconds) or solver_timeout_seconds <= 0.0: + raise ValueError("solver_timeout_seconds must be finite and positive") + + destination = Path(study_dir).expanduser().resolve() + destination.mkdir(parents=True, exist_ok=True) + levels: list[MeshConvergenceLevel] = [] + failed_levels: list[dict[str, object]] = [] + if resume_report is not None: + resume_path = Path(resume_report).expanduser().resolve() + resume_payload = json.loads(resume_path.read_text(encoding="utf-8")) + levels = [ + MeshConvergenceLevel( + **({"linear_solver": "SPOOLES"} | item) + ) + for item in resume_payload["levels"] + ] + failed_levels = list(resume_payload.get("failed_levels", [])) + completed_sizes = tuple(level.mesh_size_mm for level in levels) + if completed_sizes != sizes[: len(completed_sizes)]: + raise ValueError("resume report levels must be a prefix of mesh_sizes") + if not math.isclose( + float(resume_payload["load_z_n"]), + load_z_n, + rel_tol=0.0, + abs_tol=1.0e-9, + ): + raise ValueError("resume report load_z_n does not match this study") + + previous_displacement = None if not levels else levels[-1].max_displacement_mm + previous_stress = None if not levels else levels[-1].max_von_mises_mpa + converged_pair_streak = 0 + for completed_level in reversed(levels[1:]): + if not _pair_is_converged( + completed_level, + displacement_tolerance=displacement_tolerance, + stress_tolerance=stress_tolerance, + ): + break + converged_pair_streak += 1 + + for mesh_size in sizes[len(levels) :]: + slug = _slug(mesh_size) + mesh_path = destination / f"bracket_{slug}.msh" + mapping_path = destination / f"bracket_{slug}.gmsh.json" + input_path = destination / f"bracket_{slug}.inp" + summary_path = destination / f"bracket_{slug}.calculix.json" + if mesh_path.is_file() and resume_report is not None: + print("mesh_reuse", mesh_path) + else: + mesh_step_with_gmsh( + STEP_PATH, + mesh_path, + package_path=PACKAGE_PATH, + mapping_path=mapping_path, + mesh_size=mesh_size, + ) + input_report = build_calculix_input( + mesh_path, + input_path, + load_z_n=load_z_n, + linear_solver=linear_solver, + ) + failed_levels = [ + failure + for failure in failed_levels + if float(failure["mesh_size_mm"]) != mesh_size + ] + try: + result = run_calculix_static( + input_report, + ccx=ccx, + summary_path=summary_path, + timeout_seconds=solver_timeout_seconds, + ) + except (OSError, RuntimeError, subprocess.TimeoutExpired) as exc: + failure = { + "mesh_size_mm": mesh_size, + "mesh_path": str(mesh_path), + "input_path": str(input_path), + "linear_solver": linear_solver, + "error_type": type(exc).__name__, + "error": str(exc), + } + failed_levels.append(failure) + print("mesh_level_failed", json.dumps(failure, sort_keys=True)) + break + displacement_change = ( + None + if previous_displacement is None + else _relative_change(result.max_displacement_mm, previous_displacement) + ) + stress_change = ( + None + if previous_stress is None + else _relative_change(result.max_von_mises_mpa, previous_stress) + ) + level = MeshConvergenceLevel( + mesh_size_mm=mesh_size, + node_count=input_report.node_count, + element_count=input_report.element_count, + fixed_node_count=input_report.fixed_node_count, + load_node_count=input_report.load_node_count, + max_displacement_mm=result.max_displacement_mm, + max_von_mises_mpa=result.max_von_mises_mpa, + reaction_force_z_n=result.reaction_force_z_n, + force_balance_z_n=result.force_balance_z_n, + linear_solver=input_report.linear_solver, + displacement_change_from_previous=displacement_change, + stress_change_from_previous=stress_change, + mesh_path=str(mesh_path), + input_path=str(input_path), + summary_path=str(summary_path), + ) + levels.append(level) + print( + "mesh_level", + f"h={mesh_size:g}", + f"nodes={level.node_count}", + f"elements={level.element_count}", + f"umax_mm={level.max_displacement_mm:.9g}", + f"smax_mpa={level.max_von_mises_mpa:.9g}", + ) + if _pair_is_converged( + level, + displacement_tolerance=displacement_tolerance, + stress_tolerance=stress_tolerance, + ): + converged_pair_streak += 1 + else: + converged_pair_streak = 0 + if converged_pair_streak >= required_platform_pairs: + print( + "mesh_platform", + f"production_h={levels[-2].mesh_size_mm:g}", + f"verification_h={mesh_size:g}", + ) + break + previous_displacement = result.max_displacement_mm + previous_stress = result.max_von_mises_mpa + + assessment = assess_mesh_convergence( + levels, + displacement_tolerance=displacement_tolerance, + stress_tolerance=stress_tolerance, + required_platform_pairs=required_platform_pairs, + ) + payload = { + "schema_version": "1.1", + "analysis": "linear_static_adaptive_mesh_convergence", + "units": {"mesh_size": "mm", "displacement": "mm", "stress": "MPa"}, + "load_z_n": load_z_n, + "requested_mesh_sizes_mm": list(sizes), + "linear_solver_for_new_levels": linear_solver, + "evaluated_level_count": len(levels), + "levels": [asdict(level) for level in levels], + "failed_levels": failed_levels, + "assessment": assessment, + } + report_path = destination / REPORT_PATH.name + csv_path = destination / CSV_PATH.name + payload["report_path"] = str(report_path) + payload["csv_path"] = str(csv_path) + report_path.write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + with csv_path.open("w", newline="", encoding="utf-8") as stream: + writer = csv.DictWriter(stream, fieldnames=list(asdict(levels[0]))) + writer.writeheader() + writer.writerows(asdict(level) for level in levels) + return payload + + +def main( + *, + ccx: str | None = None, + mesh_sizes: Sequence[float] = DEFAULT_MESH_SIZES, + solver_timeout_seconds: float = 300.0, + linear_solver: str = "SPOOLES", + required_platform_pairs: int = REQUIRED_PLATFORM_PAIRS, + resume_report: Path | None = None, +) -> None: + report = run_mesh_convergence_study( + ccx=ccx, + mesh_sizes=mesh_sizes, + solver_timeout_seconds=solver_timeout_seconds, + linear_solver=linear_solver, + required_platform_pairs=required_platform_pairs, + resume_report=resume_report, + ) + assessment = report["assessment"] + print("mesh_convergence_json", report["report_path"]) + print("mesh_convergence_csv", report["csv_path"]) + print("mesh_platform_reached", assessment["platform_reached"]) + print("recommended_mesh_size_mm", assessment["recommended_mesh_size_mm"]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ccx") + parser.add_argument("--solver-timeout", type=float, default=300.0) + parser.add_argument("--linear-solver", default="SPOOLES") + parser.add_argument( + "--required-platform-pairs", + type=int, + default=REQUIRED_PLATFORM_PAIRS, + ) + parser.add_argument("--resume", type=Path) + parser.add_argument( + "--mesh-sizes", + nargs="+", + type=float, + default=DEFAULT_MESH_SIZES, + metavar="MM", + ) + arguments = parser.parse_args() + main( + ccx=arguments.ccx, + mesh_sizes=arguments.mesh_sizes, + solver_timeout_seconds=arguments.solver_timeout, + linear_solver=arguments.linear_solver, + required_platform_pairs=arguments.required_platform_pairs, + resume_report=arguments.resume, + ) diff --git a/examples/12_ap242_gmsh_volume_mesh/translate_freecad_script.py b/examples/12_ap242_gmsh_volume_mesh/translate_freecad_script.py new file mode 100644 index 00000000..2df0a788 --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/translate_freecad_script.py @@ -0,0 +1,29 @@ +"""Translate the captured bracket into a standalone FreeCAD Python script.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +SCRIPT_PATH = OUT_DIR / "ap242_gmsh_bracket.freecad.py" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + script = ( + scad.translator.freecad_translator.translate_product_package_to_freecad_script( + data=PACKAGE_PATH, + document_name="AP242GmshBracket", + ) + ) + SCRIPT_PATH.write_text(script, encoding="utf-8") + print("freecad_script", SCRIPT_PATH) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/translate_fusion360_script.py b/examples/12_ap242_gmsh_volume_mesh/translate_fusion360_script.py new file mode 100644 index 00000000..a1502dab --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/translate_fusion360_script.py @@ -0,0 +1,27 @@ +"""Translate the captured bracket into a Fusion 360 Python script.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +SCRIPT_PATH = OUT_DIR / "ap242_gmsh_bracket.fusion360.py" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + script = scad.translator.fusion360_translator.translate_product_package_to_fusion360_script( + data=PACKAGE_PATH, + document_name="AP242GmshBracket", + ) + SCRIPT_PATH.write_text(script, encoding="utf-8") + print("fusion360_script", SCRIPT_PATH) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/translate_solidworks_script.py b/examples/12_ap242_gmsh_volume_mesh/translate_solidworks_script.py new file mode 100644 index 00000000..38f7423c --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/translate_solidworks_script.py @@ -0,0 +1,30 @@ +"""Translate the captured bracket into a SolidWorks automation script.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +PACKAGE_PATH = OUT_DIR / "ap242_gmsh_bracket.scadpkg" +SCRIPT_PATH = OUT_DIR / "ap242_gmsh_bracket.solidworks.py" +SOLIDWORKS_PATH = OUT_DIR / "ap242_gmsh_bracket.SLDPRT" + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run model.py first: {PACKAGE_PATH}") + script = scad.translator.solidworks_translator.translate_product_package_to_solidworks_script( + data=PACKAGE_PATH, + document_name="AP242GmshBracket", + output_path=str(SOLIDWORKS_PATH), + ) + SCRIPT_PATH.write_text(script, encoding="utf-8") + print("solidworks_script", SCRIPT_PATH) + print("solidworks_output_when_run", SOLIDWORKS_PATH) + + +if __name__ == "__main__": + main() diff --git a/examples/12_ap242_gmsh_volume_mesh/visualize_calculix.py b/examples/12_ap242_gmsh_volume_mesh/visualize_calculix.py new file mode 100644 index 00000000..dd341c8d --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh/visualize_calculix.py @@ -0,0 +1,469 @@ +"""Convert CalculiX FRD results to ParaView VTU and render a stress preview.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import importlib +from pathlib import Path +from typing import Any + + +OUT_DIR = Path(__file__).resolve().parents[1] / "out" / "ap242_gmsh_volume_mesh" +FRD_PATH = OUT_DIR / "ap242_gmsh_bracket_static.frd" +MESH_PATH = OUT_DIR / "ap242_gmsh_bracket.msh" +PNG_PATH = OUT_DIR / "ap242_gmsh_bracket_static_von_mises.png" +DEFAULT_DEFORMATION_SCALE = 120.0 +LOAD_INTERFACE = "interface.load_surface" +DEFAULT_LOAD_Z_N = -1_000.0 + + +@dataclass(frozen=True, slots=True) +class CalculiXVisualizationReport: + frd_path: Path + vtu_path: Path + png_path: Path + displacement_field: str + stress_field: str + deformation_scale: float + visualized_max_von_mises_mpa: float + load_surface_triangle_count: int + load_arrow_count: int + applied_load_z_n: float + + +def _optional_module(name: str, message: str) -> Any: + try: + return importlib.import_module(name) + except ImportError as exc: + raise RuntimeError(message) from exc + + +def _converted_vtu_path(frd_path: Path) -> Path: + direct = frd_path.with_suffix(".vtu") + if direct.is_file(): + return direct + candidates = sorted( + frd_path.parent.glob(f"{frd_path.stem}*.vtu"), + key=lambda path: path.stat().st_mtime_ns, + reverse=True, + ) + if not candidates: + raise RuntimeError(f"ccx2paraview created no VTU file for {frd_path}") + return candidates[0] + + +def convert_frd_to_vtu( + frd_path: str | Path, + *, + converter_class: Any | None = None, +) -> Path: + """Convert one ASCII CalculiX FRD result to modern ParaView VTU.""" + + source = Path(frd_path).expanduser().resolve() + if not source.is_file() or source.stat().st_size <= 0: + raise FileNotFoundError(f"Run run_calculix.py first: {source}") + if converter_class is None: + package = _optional_module( + "ccx2paraview", + "CalculiX visualization is optional; install it with " + "`pip install simplecadapi[fem]`", + ) + converter_class = package.Converter + converter_class(str(source), ["vtu"]).run() + destination = _converted_vtu_path(source) + if destination.stat().st_size <= 0: + raise RuntimeError(f"ccx2paraview created an empty VTU file: {destination}") + return destination + + +def _point_array_names(dataset: Any) -> list[str]: + point_data = dataset.GetPointData() + return [ + str(point_data.GetArrayName(index)) + for index in range(point_data.GetNumberOfArrays()) + ] + + +def _load_surface_mesh( + mesh_path: Path, + *, + gmsh_module: Any | None = None, +) -> tuple[dict[int, tuple[float, float, float]], list[tuple[int, int, int]]]: + gmsh = gmsh_module or _optional_module( + "gmsh", + "Load visualization requires Gmsh; install it with `pip install simplecadapi[fem]`", + ) + initialized = False + try: + gmsh.initialize() + initialized = True + gmsh.open(str(mesh_path)) + groups = [ + int(tag) + for dimension, tag in gmsh.model.getPhysicalGroups(2) + if gmsh.model.getPhysicalName(dimension, tag) == LOAD_INTERFACE + ] + if len(groups) != 1: + raise RuntimeError( + f"mesh must contain one physical group named {LOAD_INTERFACE!r}" + ) + node_tags, coordinates, _parameters = gmsh.model.mesh.getNodes() + values = list(float(value) for value in coordinates) + points = { + int(tag): (values[index], values[index + 1], values[index + 2]) + for tag, index in zip(node_tags, range(0, len(values), 3)) + } + triangle_type = int(gmsh.model.mesh.getElementType("Triangle", 1)) + triangles: list[tuple[int, int, int]] = [] + for entity in gmsh.model.getEntitiesForPhysicalGroup(2, groups[0]): + _element_tags, node_ids = gmsh.model.mesh.getElementsByType( + triangle_type, + int(entity), + ) + ids = [int(value) for value in node_ids] + triangles.extend( + (ids[index], ids[index + 1], ids[index + 2]) + for index in range(0, len(ids), 3) + ) + if not triangles: + raise RuntimeError(f"physical group {LOAD_INTERFACE!r} has no triangles") + return points, triangles + finally: + if initialized: + gmsh.finalize() + + +def _sample_centroids( + centroids: list[tuple[float, float, float]], + count: int, +) -> list[tuple[float, float, float]]: + if len(centroids) <= count: + return centroids + selected = [max(centroids, key=lambda point: point[0] + point[1])] + remaining = set(centroids) + remaining.remove(selected[0]) + while remaining and len(selected) < count: + next_point = max( + remaining, + key=lambda point: min( + sum((point[index] - chosen[index]) ** 2 for index in range(3)) + for chosen in selected + ), + ) + selected.append(next_point) + remaining.remove(next_point) + return selected + + +def _load_condition_actors( + vtk: Any, + dataset: Any, + mesh_path: Path, + displacement_field: str, + deformation_scale: float, + applied_load_z_n: float, +) -> tuple[Any, Any, Any, int, int]: + source_points, triangles = _load_surface_mesh(mesh_path) + locator = vtk.vtkPointLocator() + locator.SetDataSet(dataset) + locator.BuildLocator() + displacement = dataset.GetPointData().GetArray(displacement_field) + + used_nodes = sorted({node for triangle in triangles for node in triangle}) + local_index = {node: index for index, node in enumerate(used_nodes)} + warped_points: dict[int, tuple[float, float, float]] = {} + vtk_points = vtk.vtkPoints() + for node in used_nodes: + original = source_points[node] + point_index = locator.FindClosestPoint(original) + matched = dataset.GetPoint(point_index) + distance_sq = sum((matched[index] - original[index]) ** 2 for index in range(3)) + if distance_sq > 1.0e-8: + raise RuntimeError( + f"could not map load-surface node {node} into CalculiX VTU" + ) + vector = displacement.GetTuple3(point_index) + warped_point = tuple( + original[index] + deformation_scale * vector[index] + for index in range(3) + ) + warped_points[node] = warped_point + vtk_points.InsertNextPoint(warped_point) + + cells = vtk.vtkCellArray() + centroids: list[tuple[float, float, float]] = [] + for triangle in triangles: + cell = vtk.vtkTriangle() + for index, node in enumerate(triangle): + cell.GetPointIds().SetId(index, local_index[node]) + cells.InsertNextCell(cell) + centroids.append( + tuple( + sum(warped_points[node][axis] for node in triangle) / 3.0 + for axis in range(3) + ) + ) + load_surface = vtk.vtkPolyData() + load_surface.SetPoints(vtk_points) + load_surface.SetPolys(cells) + boundary = vtk.vtkFeatureEdges() + boundary.SetInputData(load_surface) + boundary.BoundaryEdgesOn() + boundary.FeatureEdgesOff() + boundary.ManifoldEdgesOff() + boundary.NonManifoldEdgesOff() + boundary.Update() + outline = vtk.vtkTubeFilter() + outline.SetInputConnection(boundary.GetOutputPort()) + outline.SetRadius(0.10) + outline.SetNumberOfSides(12) + outline.Update() + surface_mapper = vtk.vtkPolyDataMapper() + surface_mapper.SetInputConnection(outline.GetOutputPort()) + surface_mapper.ScalarVisibilityOff() + surface_actor = vtk.vtkActor() + surface_actor.SetMapper(surface_mapper) + surface_actor.GetProperty().SetColor(1.0, 0.78, 0.0) + surface_actor.GetProperty().LightingOff() + arrow_centroids = _sample_centroids(centroids, 12) + arrow_points = vtk.vtkPoints() + arrow_vectors = vtk.vtkFloatArray() + arrow_vectors.SetName("force_direction") + arrow_vectors.SetNumberOfComponents(3) + arrow_length = 6.0 + for centroid in arrow_centroids: + arrow_points.InsertNextPoint( + centroid[0], centroid[1], centroid[2] + arrow_length + ) + arrow_vectors.InsertNextTuple3(0.0, 0.0, -1.0) + arrow_polydata = vtk.vtkPolyData() + arrow_polydata.SetPoints(arrow_points) + arrow_polydata.GetPointData().SetVectors(arrow_vectors) + arrow_source = vtk.vtkArrowSource() + arrow_source.SetTipResolution(20) + arrow_source.SetShaftResolution(20) + glyph = vtk.vtkGlyph3D() + glyph.SetInputData(arrow_polydata) + glyph.SetSourceConnection(arrow_source.GetOutputPort()) + glyph.SetVectorModeToUseVector() + glyph.SetScaleModeToScaleByVector() + glyph.SetScaleFactor(arrow_length) + glyph.OrientOn() + glyph.Update() + arrow_mapper = vtk.vtkPolyDataMapper() + arrow_mapper.SetInputConnection(glyph.GetOutputPort()) + arrow_mapper.ScalarVisibilityOff() + arrow_actor = vtk.vtkActor() + arrow_actor.SetMapper(arrow_mapper) + arrow_actor.GetProperty().SetColor(0.88, 0.05, 0.12) + + legend = vtk.vtkTextActor() + legend.SetInput( + f"LOAD Fz: {applied_load_z_n:.0f} N\nBOUNDARY: yellow\nDIRECTION: -Z" + ) + legend.SetPosition(24, 24) + legend.GetTextProperty().SetFontSize(18) + legend.GetTextProperty().SetBold(True) + legend.GetTextProperty().SetColor(0.45, 0.02, 0.04) + return surface_actor, arrow_actor, legend, len(triangles), len(arrow_centroids) + +def render_von_mises_preview( + vtu_path: str | Path, + png_path: str | Path, + *, + mesh_path: str | Path = MESH_PATH, + deformation_scale: float = DEFAULT_DEFORMATION_SCALE, + applied_load_z_n: float = DEFAULT_LOAD_Z_N, + vtk_module: Any | None = None, +) -> CalculiXVisualizationReport: + """Render the displaced mesh, colored by nodal-extrapolated von Mises stress.""" + + if deformation_scale < 0.0: + raise ValueError("deformation_scale must be nonnegative") + source = Path(vtu_path).expanduser().resolve() + destination = Path(png_path).expanduser().resolve() + if not source.is_file() or source.stat().st_size <= 0: + raise FileNotFoundError(f"ParaView VTU result is missing: {source}") + vtk = vtk_module or _optional_module( + "vtk", + "VTK rendering is optional; install it with `pip install simplecadapi[fem]`", + ) + + reader = vtk.vtkXMLUnstructuredGridReader() + reader.SetFileName(str(source)) + reader.Update() + dataset = reader.GetOutput() + if dataset is None or dataset.GetNumberOfPoints() <= 0: + raise RuntimeError(f"VTK read no points from {source}") + arrays = _point_array_names(dataset) + displacement_field = "U" if "U" in arrays else "DISP" + stress_field = "S_Mises" if "S_Mises" in arrays else "S_Mises_Magnitude" + if displacement_field not in arrays: + raise RuntimeError(f"VTU has no displacement field; point arrays: {arrays}") + if stress_field not in arrays: + raise RuntimeError(f"VTU has no von Mises field; point arrays: {arrays}") + + warp = vtk.vtkWarpVector() + warp.SetInputData(dataset) + warp.SetInputArrayToProcess(0, 0, 0, 0, displacement_field) + warp.SetScaleFactor(float(deformation_scale)) + warp.Update() + warped = warp.GetOutput() + stress = warped.GetPointData().GetArray(stress_field) + stress_range = stress.GetRange() + + surface = vtk.vtkDataSetSurfaceFilter() + surface.SetInputData(warped) + surface.Update() + mapper = vtk.vtkPolyDataMapper() + mapper.SetInputConnection(surface.GetOutputPort()) + mapper.SetScalarModeToUsePointFieldData() + mapper.SelectColorArray(stress_field) + mapper.SetScalarRange(stress_range) + + lookup = vtk.vtkLookupTable() + lookup.SetNumberOfTableValues(256) + lookup.SetHueRange(0.667, 0.0) + lookup.Build() + mapper.SetLookupTable(lookup) + + actor = vtk.vtkActor() + actor.SetMapper(mapper) + actor.GetProperty().EdgeVisibilityOff() + + scalar_bar = vtk.vtkScalarBarActor() + scalar_bar.SetLookupTable(lookup) + scalar_bar.SetTitle("von Mises [MPa]") + scalar_bar.SetNumberOfLabels(5) + + load_surface_actor, arrow_actor, legend, load_triangle_count, arrow_count = ( + _load_condition_actors( + vtk, + dataset, + Path(mesh_path).expanduser().resolve(), + displacement_field, + float(deformation_scale), + float(applied_load_z_n), + ) + ) + renderer = vtk.vtkRenderer() + renderer.SetBackground(0.96, 0.97, 0.98) + renderer.AddActor(actor) + renderer.AddViewProp(scalar_bar) + renderer.AddActor(load_surface_actor) + renderer.AddActor(arrow_actor) + renderer.AddViewProp(legend) + renderer.ResetCamera() + camera = renderer.GetActiveCamera() + camera.Azimuth(35.0) + camera.Elevation(22.0) + camera.Zoom(1.2) + + window = vtk.vtkRenderWindow() + window.SetOffScreenRendering(1) + window.SetSize(1280, 900) + window.AddRenderer(renderer) + window.Render() + + capture = vtk.vtkWindowToImageFilter() + capture.SetInput(window) + capture.SetInputBufferTypeToRGBA() + capture.ReadFrontBufferOff() + capture.Update() + destination.parent.mkdir(parents=True, exist_ok=True) + writer = vtk.vtkPNGWriter() + writer.SetFileName(str(destination)) + writer.SetInputConnection(capture.GetOutputPort()) + writer.Write() + if not destination.is_file() or destination.stat().st_size <= 0: + raise RuntimeError(f"VTK did not create a non-empty preview at {destination}") + + return CalculiXVisualizationReport( + frd_path=source.with_suffix(".frd"), + vtu_path=source, + png_path=destination, + displacement_field=displacement_field, + stress_field=stress_field, + deformation_scale=float(deformation_scale), + visualized_max_von_mises_mpa=float(stress_range[1]), + load_surface_triangle_count=load_triangle_count, + load_arrow_count=arrow_count, + applied_load_z_n=float(applied_load_z_n), + ) + + +def visualize_calculix_result( + frd_path: str | Path, + png_path: str | Path, + *, + mesh_path: str | Path = MESH_PATH, + deformation_scale: float = DEFAULT_DEFORMATION_SCALE, + applied_load_z_n: float = DEFAULT_LOAD_Z_N, + converter_class: Any | None = None, + vtk_module: Any | None = None, +) -> CalculiXVisualizationReport: + vtu_path = convert_frd_to_vtu(frd_path, converter_class=converter_class) + report = render_von_mises_preview( + vtu_path, + png_path, + deformation_scale=deformation_scale, + mesh_path=mesh_path, + applied_load_z_n=applied_load_z_n, + vtk_module=vtk_module, + ) + return CalculiXVisualizationReport( + frd_path=Path(frd_path).expanduser().resolve(), + vtu_path=report.vtu_path, + png_path=report.png_path, + displacement_field=report.displacement_field, + stress_field=report.stress_field, + deformation_scale=report.deformation_scale, + visualized_max_von_mises_mpa=report.visualized_max_von_mises_mpa, + load_surface_triangle_count=report.load_surface_triangle_count, + load_arrow_count=report.load_arrow_count, + applied_load_z_n=report.applied_load_z_n, + ) + + +def main( + *, + frd_path: Path = FRD_PATH, + png_path: Path = PNG_PATH, + mesh_path: Path = MESH_PATH, + applied_load_z_n: float = DEFAULT_LOAD_Z_N, + deformation_scale: float = DEFAULT_DEFORMATION_SCALE, +) -> None: + report = visualize_calculix_result( + frd_path, + png_path, + deformation_scale=deformation_scale, + mesh_path=mesh_path, + applied_load_z_n=applied_load_z_n, + ) + print("paraview_vtu", report.vtu_path) + print("stress_preview", report.png_path) + print("displacement_field", report.displacement_field) + print("stress_field", report.stress_field) + print("deformation_scale", f"{report.deformation_scale:.9g}") + print("visualized_max_von_mises_mpa", f"{report.visualized_max_von_mises_mpa:.9g}") + print("load_surface_triangles", report.load_surface_triangle_count) + print("load_arrows", report.load_arrow_count) + print("applied_load_z_n", f"{report.applied_load_z_n:.9g}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--frd", type=Path, default=FRD_PATH) + parser.add_argument("--mesh", type=Path, default=MESH_PATH) + parser.add_argument("--load-z", type=float, default=DEFAULT_LOAD_Z_N) + parser.add_argument("--png", type=Path, default=PNG_PATH) + parser.add_argument("--deformation-scale", type=float, default=DEFAULT_DEFORMATION_SCALE) + arguments = parser.parse_args() + main( + frd_path=arguments.frd, + png_path=arguments.png, + mesh_path=arguments.mesh, + applied_load_z_n=arguments.load_z, + deformation_scale=arguments.deformation_scale, + ) diff --git a/examples/16_compact_two_stage_planetary_reducer/export_mjcf.py b/examples/16_compact_two_stage_planetary_reducer/export_mjcf.py new file mode 100644 index 00000000..4b1fdbd1 --- /dev/null +++ b/examples/16_compact_two_stage_planetary_reducer/export_mjcf.py @@ -0,0 +1,40 @@ +"""Export the compact reducer product package as MuJoCo MJCF.""" + +from __future__ import annotations + +from pathlib import Path + +import simplecadapi as scad + + +OUT_DIR = Path("examples/out/compact_two_stage_planetary_reducer") +PACKAGE_PATH = OUT_DIR / "compact_two_stage_planetary_reducer.scadpkg" +MJCF_PATH = OUT_DIR / "compact_two_stage_planetary_reducer.xml" +MAPPING_PATH = OUT_DIR / "compact_two_stage_planetary_reducer.mapping.json" +MESH_DIR = OUT_DIR / "compact_two_stage_planetary_reducer_meshes" +BEARING_STEEL_DENSITY_KG_M3 = 7850.0 + + +def main() -> None: + if not PACKAGE_PATH.is_file(): + raise FileNotFoundError(f"Run main.py first: {PACKAGE_PATH}") + report = scad.exporter.export_product_package_to_mjcf( + data=PACKAGE_PATH, + output_path=MJCF_PATH, + mapping_path=MAPPING_PATH, + mesh_directory=MESH_DIR, + linear_deflection=0.15, + default_density_kg_m3=BEARING_STEEL_DENSITY_KG_M3, + ) + print("mjcf", report.output_path) + print("mjcf_mapping", report.mapping_path) + print("mjcf_meshes", report.mesh_directory) + print("mjcf_bodies", report.body_count) + print("mjcf_joints", report.joint_count) + print("mjcf_equalities", report.equality_count) + print("mjcf_sites", report.site_count) + print("mjcf_default_density_parts", report.default_density_count) + + +if __name__ == "__main__": + main() diff --git a/examples/README.md b/examples/README.md index 7c81218e..b28aae64 100644 --- a/examples/README.md +++ b/examples/README.md @@ -3,7 +3,7 @@ Run examples from the repository root with `uv run python `. Generated artifacts are written to `examples/out/`, which is ignored by git. -Every formal example emits three synchronized artifacts under `examples/out/`: +Every formal single-script example emits three synchronized artifacts under `examples/out/`: the canonical self-contained `.scadpkg`, an AP242 `.step`, and an editable FreeCAD `.FCStd`. Single-solid products use `@scad.part`; assemblies use `@scad.assemble` with explicit immutable definitions for every physical part or @@ -12,9 +12,9 @@ package, so they retain the same definition closure, evaluated geometry, assembly instances, names, solved placements, materials, and available semantic metadata. -`tools/run_examples.py` requires every formal example to rewrite and validate -all three artifacts. Model/session JSON and the optional Gmsh `.msh` remain -secondary demonstration outputs. +`tools/run_examples.py` requires every formal single-script example to rewrite +and validate all three CAD artifacts. The split AP242/Gmsh workflow below is +run directly, one script per stage. ## Examples @@ -23,7 +23,39 @@ secondary demonstration outputs. - `09_naca0016_blade_freecad.py` — `out/naca0016_blade/naca0016_blade.scadpkg` - `10_part_assembly.py` — `out/hydraulic_rod_assembly/hydraulic_rod_assembly.scadpkg` - `11_external_reference_gear_train.py` — `out/external_reference_gear_train/nested_external_reference_gear_trains.scadpkg` -- `12_ap242_gmsh_volume_mesh.py` — `out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg` +- `12_ap242_gmsh_volume_mesh/model.py` — `out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg` - `7ep_caplcd_enclosure.py` — `out/7ep_caplcd_enclosure/caplcd_enclosure_7ep.scadpkg` - `16_compact_two_stage_planetary_reducer/` — `out/compact_two_stage_planetary_reducer/compact_two_stage_planetary_reducer.scadpkg` - `20_integrated_bldc_joint_actuator/` — `out/integrated_bldc_joint_actuator/integrated_bldc_joint_actuator.scadpkg` + +## Product Package Exporter And Translator Matrix + +Build the canonical package once: + +```bash +uv run python examples/12_ap242_gmsh_volume_mesh/model.py +``` + +Then run any downstream exporter or translator directly: + +```bash +uv run python examples/12_ap242_gmsh_volume_mesh/export_fcstd.py +uv run python examples/12_ap242_gmsh_volume_mesh/export_step.py +uv run --extra gmsh python examples/12_ap242_gmsh_volume_mesh/export_stl.py +uv run --extra gmsh python examples/12_ap242_gmsh_volume_mesh/export_obj.py +uv run python examples/12_ap242_gmsh_volume_mesh/translate_freecad_script.py +uv run python examples/12_ap242_gmsh_volume_mesh/translate_fusion360_script.py +uv run python examples/12_ap242_gmsh_volume_mesh/translate_solidworks_script.py +``` + +The outputs are editable FreeCAD `.FCStd`, AP242 `.step`, triangulated `.stl`, +quad-preserving `.obj`, and standalone Python scripts for FreeCAD, Fusion 360, +and SolidWorks. Every command above reads the same `.scadpkg` directly. + +FEM meshing consumes the STEP produced by `export_step.py`: + +```bash +uv run --extra gmsh python examples/12_ap242_gmsh_volume_mesh/export_fem_mesh.py +``` + +It imports AP242 through Gmsh's OpenCASCADE kernel and writes a 3D `.msh`. diff --git a/pyproject.toml b/pyproject.toml index 5880c006..1753eed5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,10 @@ inspect = [ gmsh = [ "gmsh>=4.15,<5", ] +fem = [ + "gmsh>=4.15,<5", + "ccx2paraview[VTK]>=3.2,<4", +] [project.urls] Homepage = "https://github.com/NiJingzhe/SimpleCADAPI" diff --git a/skills/simplecadapi/references/docs/api/ProductMJCFExportReport.md b/skills/simplecadapi/references/docs/api/ProductMJCFExportReport.md new file mode 100644 index 00000000..8b8ddc71 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/ProductMJCFExportReport.md @@ -0,0 +1,17 @@ +# ProductMJCFExportReport + +## Class Definition + +```python +class ProductMJCFExportReport(output_path: Path, mapping_path: Path, mesh_directory: Path, root_definition_id: str, mesh_count: int, body_count: int, joint_count: int, equality_count: int, grounded_group_count: int, site_count: int, default_density_count: int, limitations: tuple[str, ...]) +``` + +*Source: exporter/mjcf.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.mjcf.ProductMJCFExportReport(...)` + +## Description + +Observed facts and compiler decisions from one MJCF export. diff --git a/skills/simplecadapi/references/docs/api/ProductOBJExportReport.md b/skills/simplecadapi/references/docs/api/ProductOBJExportReport.md new file mode 100644 index 00000000..9e0ea7d5 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/ProductOBJExportReport.md @@ -0,0 +1,17 @@ +# ProductOBJExportReport + +## Class Definition + +```python +class ProductOBJExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, vertex_count: int, triangle_count: int, linear_deflection: float, angular_deflection_degrees: float, relative: bool, tessellation_backend: str = 'opencascade-brep-tessellation') +``` + +*Source: exporter/obj.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.obj.ProductOBJExportReport(...)` + +## Description + +Evidence from direct BREP tessellation and triangle OBJ export. diff --git a/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md b/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md index 66c0e89f..9ef3b9d7 100644 --- a/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md +++ b/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, quadrilateral_count: int, residual_triangle_count: int, stl_triangle_count: int, quad_fraction: float, mesh_size: float, remesh_backend: str = 'gmsh-quad-dominant') +class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, vertex_count: int, triangle_count: int, linear_deflection: float, angular_deflection_degrees: float, relative: bool, tessellation_backend: str = 'opencascade-brep-tessellation') ``` *Source: exporter/stl.py* @@ -14,4 +14,4 @@ class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_c ## Description -Evidence from quad-dominant product-surface remeshing and STL export. +Evidence from direct BREP tessellation and binary STL export. diff --git a/skills/simplecadapi/references/docs/api/README.md b/skills/simplecadapi/references/docs/api/README.md index 05088233..1a53ee0f 100644 --- a/skills/simplecadapi/references/docs/api/README.md +++ b/skills/simplecadapi/references/docs/api/README.md @@ -91,8 +91,12 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Export +- [ProductMJCFExportReport](ProductMJCFExportReport.md) *(from exporter/mjcf.py)* `exporter namespace` +- [ProductOBJExportReport](ProductOBJExportReport.md) *(from exporter/obj.py)* `exporter namespace` - [ProductSTEPExportReport](ProductSTEPExportReport.md) *(from exporter/step.py)* `exporter namespace` - [ProductSTLExportReport](ProductSTLExportReport.md) *(from exporter/stl.py)* `exporter namespace` +- [export_product_package_to_mjcf](export_product_package_to_mjcf.md) *(from exporter/mjcf.py)* `exporter namespace` +- [export_product_package_to_obj](export_product_package_to_obj.md) *(from exporter/obj.py)* `exporter namespace` - [export_product_package_to_step](export_product_package_to_step.md) *(from exporter/step.py)* `exporter namespace` - [export_product_package_to_stl](export_product_package_to_stl.md) *(from exporter/stl.py)* `exporter namespace` diff --git a/skills/simplecadapi/references/docs/api/export_product_package_to_mjcf.md b/skills/simplecadapi/references/docs/api/export_product_package_to_mjcf.md new file mode 100644 index 00000000..dc48db30 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/export_product_package_to_mjcf.md @@ -0,0 +1,23 @@ +# export_product_package_to_mjcf + +## API Definition + +```python +def export_product_package_to_mjcf(data: ProductPackageInput, output_path: str | Path, *, mesh_directory: str | Path | None = None, mapping_path: str | Path | None = None, linear_deflection: float = 0.15, default_density_kg_m3: float | None = None) -> ProductMJCFExportReport +``` + +*Source: exporter/mjcf.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.mjcf.export_product_package_to_mjcf(...)` + +## Description + +Compile a validated `.scadpkg` assembly into an MJCF model. + +Fixed constraints and attachments through forwarded nested-assembly +connectors create rigid groups. Revolute/prismatic edges form a +deterministic spanning tree. Gear, belt, and rack-pinion relations become +independent fixed-tendon equalities. Root assembly connectors and geometry +names in the ``interface.*`` namespace become MJCF sites. diff --git a/skills/simplecadapi/references/docs/api/export_product_package_to_obj.md b/skills/simplecadapi/references/docs/api/export_product_package_to_obj.md new file mode 100644 index 00000000..4e84a492 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/export_product_package_to_obj.md @@ -0,0 +1,21 @@ +# export_product_package_to_obj + +## API Definition + +```python +def export_product_package_to_obj(data: ProductPackageInput, output_path: str | Path, *, linear_deflection: float = 0.1, angular_deflection_degrees: float = 20.0, relative: bool = False) -> ProductOBJExportReport +``` + +*Source: exporter/obj.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.obj.export_product_package_to_obj(...)` + +## Description + +Export one `.scadpkg` directly from evaluated BREP as triangle OBJ. + +`linear_deflection` is the maximum chordal deviation in product units. +`angular_deflection_degrees` limits angular deviation on curved surfaces. +No remeshing or topology reconstruction is performed. diff --git a/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md b/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md index 922d7308..63c9f908 100644 --- a/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md +++ b/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md @@ -3,7 +3,7 @@ ## API Definition ```python -def export_product_package_to_stl(data: ProductPackageInput, output_path: str | Path, *, mesh_size: float = 1.0, recombination_angle_degrees: float = 45.0) -> ProductSTLExportReport +def export_product_package_to_stl(data: ProductPackageInput, output_path: str | Path, *, linear_deflection: float = 0.1, angular_deflection_degrees: float = 20.0, relative: bool = False) -> ProductSTLExportReport ``` *Source: exporter/stl.py* @@ -14,7 +14,8 @@ def export_product_package_to_stl(data: ProductPackageInput, output_path: str | ## Description -Export one validated `.scadpkg` as a quad-dominant remeshed STL. +Export one `.scadpkg` directly from evaluated BREP as binary STL. -Gmsh recombines each CAD surface into quadrilaterals before its STL writer -splits every quad into two triangles, as required by the STL file format. +`linear_deflection` is the maximum chordal deviation in product units. +`angular_deflection_degrees` limits angular deviation on curved surfaces. +No remeshing or topology reconstruction is performed. diff --git a/skills/simplecadapi/references/docs/guides/cache-build-workflow.md b/skills/simplecadapi/references/docs/guides/cache-build-workflow.md index 50023c37..7edc83f4 100644 --- a/skills/simplecadapi/references/docs/guides/cache-build-workflow.md +++ b/skills/simplecadapi/references/docs/guides/cache-build-workflow.md @@ -150,6 +150,8 @@ downstream target from the consumer contract: | `.scadpkg` | Rebuild, replay, cache, or further SimpleCAD editing is required | Complete durable definition closure, feature graphs, source snapshots, topology, connectors, constraints, and materials | SimpleCAD-specific archive | | `.FCStd` | A FreeCAD user needs an editable native document | Definition-owned, dependency-first native feature graphs; final body links; repeated instances; nested assemblies; names; solved placements; materials; connectors; constraints; grounding; revision; and content hashes | Requires FreeCADCmd/FreeCAD | | AP242 `.step` | Neutral CAD exchange or downstream OpenCASCADE tooling is required | Evaluated BREP, product hierarchy, shared definitions, occurrence names/placements, materials, colors, density, and named SimpleCAD property payloads | Canonical feature history is not reconstructed as AP242 features | +| Triangle `.obj` | Surface inspection or DCC exchange needs an indexed mesh | Direct OpenCASCADE tessellation of evaluated BREP with shared vertices and oriented triangles | Evaluated surface mesh only; no CAD hierarchy, feature semantics, quads, or materials | +| Binary `.stl` | Additive manufacturing or triangle-only consumers | The same direct OpenCASCADE BREP triangles | Facet soup only; no shared vertices, CAD hierarchy, feature semantics, or materials | ```python package_path = assembly_package.artifact_paths["product"] @@ -166,10 +168,21 @@ stl_report = scad.exporter.export_product_package_to_stl( package_path, "out/product.stl", ) +obj_report = scad.exporter.export_product_package_to_obj( + package_path, + "out/product.obj", +) print(step_report.definition_ids, step_report.occurrence_count) -print(stl_report.solid_count, stl_report.stl_triangle_count) +print(stl_report.solid_count, stl_report.triangle_count) +print(obj_report.vertex_count, obj_report.triangle_count) ``` +STL and OBJ use the same direct OpenCASCADE tessellation and parameters. Set +`linear_deflection` to the maximum chordal deviation in product units and +`angular_deflection_degrees` to the curved-surface angular limit. Both formats +contain oriented triangles; OBJ preserves shared vertex indices while binary STL +stores each facet independently. No remeshing or optional dependency is involved. + AP242 definition and occurrence metadata is stored in one standard `PROPERTY_DEFINITION_REPRESENTATION`. Its named `DESCRIPTIVE_REPRESENTATION_ITEM` records use @@ -180,9 +193,11 @@ connectors, constraints, grounding, name, and solved placement. `ProductSTEPExportReport` reports the schema, definition IDs, occurrence count, material IDs, metadata item count, and explicit limitations. -For tetrahedral meshing, install `simplecadapi[gmsh]` and run -`examples/12_ap242_gmsh_volume_mesh.py`. The example exports one `.scadpkg`, -converts it to AP242 STEP, imports it with Gmsh's OpenCASCADE kernel, rejects -imports with no 3D volumes, generates a dimension-3 mesh, writes `.msh`, and -always finalizes Gmsh. Gmsh remains optional and is never imported by the core -SDK or the product exporters. +For tetrahedral meshing, run the split example directly in dependency order: +`model.py` captures `.scadpkg`, `export_step.py` exports AP242 STEP, and +`export_fem_mesh.py` imports that STEP with Gmsh's OpenCASCADE kernel. The FEM +stage rejects imports with no 3D volumes, generates a dimension-3 mesh, writes +`.msh`, and always finalizes Gmsh. Install and invoke the optional dependency +with `uv run --extra gmsh python +examples/12_ap242_gmsh_volume_mesh/export_fem_mesh.py`; Gmsh is never imported +by the core SDK or product exporters. diff --git a/skills/simplecadapi/references/docs/updates/2.0.4b3.md b/skills/simplecadapi/references/docs/updates/2.0.4b3.md index bff8c48e..18ccb128 100644 --- a/skills/simplecadapi/references/docs/updates/2.0.4b3.md +++ b/skills/simplecadapi/references/docs/updates/2.0.4b3.md @@ -81,9 +81,18 @@ definition/occurrence properties. The property descriptions contain canonical sorted JSON for durable IDs and semantics. Feature history is not reconstructed as AP242 features; `.scadpkg` remains the canonical replayable artifact. -The optional `gmsh` extra and `examples/12_ap242_gmsh_volume_mesh.py` demonstrate -`.scadpkg -> AP242 STEP -> tetrahedral .msh` without adding Gmsh to the core -runtime dependency set. +Product mesh export now shares one direct OpenCASCADE tessellation of evaluated +BREP solids. OBJ and binary STL contain the same oriented triangles; OBJ keeps +shared vertex indices while STL stores independent facets. The public accuracy +controls are `linear_deflection`, `angular_deflection_degrees`, and `relative`. +No remeshing dependency or Python 3.11 version gate is involved, so mesh export +works across the package's complete supported Python range. + +The scripts in `examples/12_ap242_gmsh_volume_mesh/` build one `.scadpkg` and +demonstrate every package exporter and translator as independent downstream +commands: AP242 STEP, STL, OBJ, FCStd, FreeCAD, Fusion 360, and SolidWorks. +The optional Gmsh stage continues from AP242 STEP to a tetrahedral `.msh` +without adding Gmsh to the core runtime dependency set. ## 7. Native render crash isolation diff --git a/src/simplecadapi/auto_tools/auto_docs_gen.py b/src/simplecadapi/auto_tools/auto_docs_gen.py index 79e3ef3b..85c8cec4 100644 --- a/src/simplecadapi/auto_tools/auto_docs_gen.py +++ b/src/simplecadapi/auto_tools/auto_docs_gen.py @@ -48,7 +48,9 @@ DEFAULT_SOURCE_FILENAMES: tuple[str, ...] = ( "inspect/brep/render.py", "inspect/brep/slices.py", "exporter/step.py", + "exporter/obj.py", "exporter/stl.py", + "exporter/mjcf.py", ) DEFAULT_STDLIB_SOURCE_FILENAMES: tuple[str, ...] = ( @@ -90,7 +92,9 @@ EXPORTED_FUNCTION_MODULES = frozenset( "inspect/brep/render.py", "inspect/brep/slices.py", "exporter/step.py", + "exporter/obj.py", "exporter/stl.py", + "exporter/mjcf.py", } ) @@ -324,6 +328,8 @@ class APIDocumentGenerator: module_name: str, exported_names: set[str], ) -> bool: + if name.startswith("_"): + return False if module_name.startswith("exporter/"): return True if name.startswith("_"): diff --git a/src/simplecadapi/exporter/__init__.py b/src/simplecadapi/exporter/__init__.py index d41319ef..13ee26ef 100644 --- a/src/simplecadapi/exporter/__init__.py +++ b/src/simplecadapi/exporter/__init__.py @@ -1,11 +1,17 @@ -"""Product-package exporters for neutral CAD and mesh formats.""" +"""Product-package exporters for neutral CAD, mesh, and simulation formats.""" +from .mjcf import ProductMJCFExportReport, export_product_package_to_mjcf +from .obj import ProductOBJExportReport, export_product_package_to_obj from .step import ProductSTEPExportReport, export_product_package_to_step from .stl import ProductSTLExportReport, export_product_package_to_stl __all__ = [ + "ProductMJCFExportReport", + "ProductOBJExportReport", "ProductSTEPExportReport", "ProductSTLExportReport", + "export_product_package_to_mjcf", + "export_product_package_to_obj", "export_product_package_to_step", "export_product_package_to_stl", ] diff --git a/src/simplecadapi/exporter/_surface_mesh.py b/src/simplecadapi/exporter/_surface_mesh.py new file mode 100644 index 00000000..817c8eaf --- /dev/null +++ b/src/simplecadapi/exporter/_surface_mesh.py @@ -0,0 +1,205 @@ +"""Shared OpenCASCADE BREP tessellation for STL and OBJ exporters.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Any, Sequence + +import numpy as np +from OCP.BRep import BRep_Tool +from OCP.BRepMesh import BRepMesh_IncrementalMesh +from OCP.BRepTools import BRepTools +from OCP.TopAbs import TopAbs_FACE, TopAbs_REVERSED +from OCP.TopExp import TopExp_Explorer +from OCP.TopLoc import TopLoc_Location +from OCP.TopoDS import TopoDS + +from ..artifacts.assembly_io import materialize_definition +from ..kernel.ocp_booleans import solids_of +from ..operations import make_compound_from_assembly_rcompound +from ..product import Assembly, Part +from ..translator.package_units import ( + ProductPackageInput, + read_product_package_translation_units, +) + +_TESSELLATION_BACKEND = "opencascade-brep-tessellation" + + +@dataclass(frozen=True, slots=True) +class TessellatedSurfaceMesh: + """One triangle mesh produced directly from evaluated product BREP solids.""" + + vertices: np.ndarray + triangles: np.ndarray + root_definition_id: str + solid_count: int + definition_count: int + linear_deflection: float + angular_deflection_degrees: float + relative: bool + tessellation_backend: str = _TESSELLATION_BACKEND + + @property + def vertex_count(self) -> int: + return int(self.vertices.shape[0]) + + @property + def triangle_count(self) -> int: + return int(self.triangles.shape[0]) + + +def _product_solids(value: Part | Assembly) -> tuple[Any, ...]: + if isinstance(value, Part): + return (value.body.wrapped,) + projection = make_compound_from_assembly_rcompound(assembly=value) + solids = tuple(solids_of(projection.wrapped)) + if not solids: + raise ValueError("Product assembly produced no solids for mesh export") + return solids + + +def _vertex_key(point: Sequence[float], tolerance: float) -> tuple[int, int, int]: + return tuple(int(round(float(value) / tolerance)) for value in point) + + +def _is_collapsed_triangle( + vertices: Sequence[tuple[float, float, float]], + indices: tuple[int, int, int], +) -> bool: + points = np.asarray([vertices[index] for index in indices], dtype=np.float64) + first = points[1] - points[0] + second = points[2] - points[0] + third = points[2] - points[1] + max_edge_squared = max( + float(np.dot(first, first)), + float(np.dot(second, second)), + float(np.dot(third, third)), + ) + if max_edge_squared == 0.0: + return True + normal = np.cross(first, second) + area_squared = float(np.dot(normal, normal)) + relative_floor = np.finfo(np.float64).eps ** 2 * max_edge_squared**2 + return area_squared <= relative_floor + + +def _tessellate_solid( + solid: Any, + *, + linear_deflection: float, + angular_deflection_radians: float, + relative: bool, +) -> tuple[np.ndarray, np.ndarray]: + BRepTools.Clean_s(solid, False) + mesher = BRepMesh_IncrementalMesh( + solid, + linear_deflection, + relative, + angular_deflection_radians, + False, + ) + mesher.Perform() + if not mesher.IsDone(): + raise RuntimeError("OpenCASCADE failed to tessellate product geometry") + + weld_tolerance = max(min(linear_deflection * 1.0e-7, 1.0e-7), 1.0e-9) + vertices: list[tuple[float, float, float]] = [] + vertex_indices: dict[tuple[int, int, int], int] = {} + triangles: list[tuple[int, int, int]] = [] + explorer = TopExp_Explorer(solid, TopAbs_FACE) + while explorer.More(): + face = TopoDS.Face_s(explorer.Current()) + location = TopLoc_Location() + triangulation = BRep_Tool.Triangulation_s(face, location, 0) + if triangulation is None or triangulation.NbTriangles() == 0: + raise RuntimeError("OpenCASCADE produced an empty face triangulation") + transform = location.Transformation() + local_indices: dict[int, int] = {} + for node_index in range(1, triangulation.NbNodes() + 1): + point = triangulation.Node(node_index).Transformed(transform) + coordinates = (float(point.X()), float(point.Y()), float(point.Z())) + if not all(math.isfinite(value) for value in coordinates): + raise RuntimeError("OpenCASCADE produced a non-finite mesh vertex") + key = _vertex_key(coordinates, weld_tolerance) + global_index = vertex_indices.get(key) + if global_index is None: + global_index = len(vertices) + vertex_indices[key] = global_index + vertices.append(coordinates) + local_indices[node_index] = global_index + + reversed_face = face.Orientation() == TopAbs_REVERSED + for triangle_index in range(1, triangulation.NbTriangles() + 1): + a, b, c = triangulation.Triangle(triangle_index).Get() + indices = ( + (local_indices[a], local_indices[c], local_indices[b]) + if reversed_face + else (local_indices[a], local_indices[b], local_indices[c]) + ) + if len(set(indices)) == 3 and not _is_collapsed_triangle(vertices, indices): + triangles.append(indices) + explorer.Next() + + if not vertices or not triangles: + raise RuntimeError("OpenCASCADE produced no product surface triangles") + return ( + np.asarray(vertices, dtype=np.float64).reshape((-1, 3)), + np.asarray(triangles, dtype=np.int32).reshape((-1, 3)), + ) + + +def tessellate_product_surface( + data: ProductPackageInput, + *, + linear_deflection: float, + angular_deflection_degrees: float, + relative: bool, +) -> TessellatedSurfaceMesh: + """Tessellate every evaluated product solid directly with OpenCASCADE.""" + + linear = float(linear_deflection) + if not math.isfinite(linear) or linear <= 0.0: + raise ValueError("linear_deflection must be a positive finite value") + angular_degrees = float(angular_deflection_degrees) + if ( + not math.isfinite(angular_degrees) + or angular_degrees <= 0.0 + or angular_degrees > 180.0 + ): + raise ValueError("angular_deflection_degrees must be in (0, 180]") + if not isinstance(relative, bool): + raise TypeError("relative must be a bool") + + package, units = read_product_package_translation_units(data) + root = materialize_definition(package.root_definition) + solids = _product_solids(root) + vertex_blocks: list[np.ndarray] = [] + triangle_blocks: list[np.ndarray] = [] + vertex_offset = 0 + angular_radians = math.radians(angular_degrees) + for solid in solids: + vertices, triangles = _tessellate_solid( + solid, + linear_deflection=linear, + angular_deflection_radians=angular_radians, + relative=relative, + ) + vertex_blocks.append(vertices) + triangle_blocks.append(triangles + vertex_offset) + vertex_offset += len(vertices) + + return TessellatedSurfaceMesh( + vertices=np.concatenate(vertex_blocks, axis=0), + triangles=np.concatenate(triangle_blocks, axis=0), + root_definition_id=package.root_definition.definition_id, + solid_count=len(solids), + definition_count=len(units), + linear_deflection=linear, + angular_deflection_degrees=angular_degrees, + relative=relative, + ) + + +__all__ = ["TessellatedSurfaceMesh", "tessellate_product_surface"] diff --git a/src/simplecadapi/exporter/mjcf.py b/src/simplecadapi/exporter/mjcf.py new file mode 100644 index 00000000..1f508281 --- /dev/null +++ b/src/simplecadapi/exporter/mjcf.py @@ -0,0 +1,931 @@ +"""MuJoCo MJCF export for validated SimpleCAD product packages.""" + +from __future__ import annotations + +from collections import defaultdict, deque +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import re +from typing import Any, Mapping +import xml.etree.ElementTree as ET + +import numpy as np + +from ..artifacts.assembly_io import materialize_definition +from ..artifacts.canonical import parse_canonical_json +from ..artifacts.part_definition import PartDefinition +from ..product import Assembly, Part, Placement, relative_placement +from ..scene import read_scene_package +from ..translator.package_units import ( + ProductPackageInput, + read_product_package_translation_units, +) +from ._surface_mesh import _tessellate_solid + +@dataclass(frozen=True, slots=True) +class ProductMJCFExportReport: + """Observed facts and compiler decisions from one MJCF export.""" + + output_path: Path + mapping_path: Path + mesh_directory: Path + root_definition_id: str + mesh_count: int + body_count: int + joint_count: int + equality_count: int + grounded_group_count: int + site_count: int + default_density_count: int + limitations: tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return { + "output_path": str(self.output_path), + "mapping_path": str(self.mapping_path), + "mesh_directory": str(self.mesh_directory), + "root_definition_id": self.root_definition_id, + "mesh_count": self.mesh_count, + "body_count": self.body_count, + "joint_count": self.joint_count, + "equality_count": self.equality_count, + "grounded_group_count": self.grounded_group_count, + "site_count": self.site_count, + "default_density_count": self.default_density_count, + "limitations": list(self.limitations), + } + + +class _UnionFind: + def __init__(self, values: list[str]) -> None: + self.parent = {value: value for value in values} + self.rank = {value: 0 for value in values} + + def find(self, value: str) -> str: + parent = self.parent[value] + if parent != value: + self.parent[value] = self.find(parent) + return self.parent[value] + + def union(self, first: str, second: str) -> None: + left = self.find(first) + right = self.find(second) + if left == right: + return + if self.rank[left] < self.rank[right]: + left, right = right, left + self.parent[right] = left + if self.rank[left] == self.rank[right]: + self.rank[left] += 1 + + +def _safe_name(value: str, *, prefix: str = "item") -> str: + rendered = re.sub(r"[^A-Za-z0-9_]", "_", str(value)).strip("_") + if not rendered: + rendered = prefix + if not rendered[0].isalpha(): + rendered = f"{prefix}_{rendered}" + if len(rendered) > 96: + digest = hashlib.sha1(str(value).encode("utf-8")).hexdigest()[:12] + rendered = f"{rendered[:80]}_{digest}" + return rendered + + +def _fmt(value: float) -> str: + return f"{float(value):.12g}" + + +def _fmt_vec(values: tuple[float, float, float] | list[float]) -> str: + return " ".join(_fmt(float(value)) for value in values) + + +def _placement(payload: Mapping[str, Any]) -> Placement: + return Placement( + origin=tuple(float(value) for value in payload["origin"]), + x_axis=tuple(float(value) for value in payload["x_axis"]), + y_axis=tuple(float(value) for value in payload["y_axis"]), + z_axis=tuple(float(value) for value in payload["z_axis"]), + ) + + +def _inverse_vector( + frame: Placement, + vector: tuple[float, float, float], +) -> tuple[float, float, float]: + return ( + sum(vector[index] * frame.x_axis[index] for index in range(3)), + sum(vector[index] * frame.y_axis[index] for index in range(3)), + sum(vector[index] * frame.z_axis[index] for index in range(3)), + ) + + +def _add_scaled_terms( + target: dict[str, float], + source: Mapping[str, float], + scale: float, +) -> None: + for name, coefficient in source.items(): + target[name] = target.get(name, 0.0) + scale * coefficient + + +def _subtracted_terms( + first: Mapping[str, float], + second: Mapping[str, float], +) -> dict[str, float]: + result = dict(first) + _add_scaled_terms(result, second, -1.0) + return {name: value for name, value in result.items() if abs(value) > 1.0e-12} + + +def _matrix_to_quat(frame: Placement) -> tuple[float, float, float, float]: + """Convert the frame's orthonormal columns to MuJoCo wxyz.""" + + m00, m01, m02 = frame.x_axis[0], frame.y_axis[0], frame.z_axis[0] + m10, m11, m12 = frame.x_axis[1], frame.y_axis[1], frame.z_axis[1] + m20, m21, m22 = frame.x_axis[2], frame.y_axis[2], frame.z_axis[2] + trace = m00 + m11 + m22 + if trace > 0.0: + scale = 2.0 * (trace + 1.0) ** 0.5 + return ( + 0.25 * scale, + (m21 - m12) / scale, + (m02 - m20) / scale, + (m10 - m01) / scale, + ) + if m00 > m11 and m00 > m22: + scale = 2.0 * (1.0 + m00 - m11 - m22) ** 0.5 + return ( + (m21 - m12) / scale, + 0.25 * scale, + (m01 + m10) / scale, + (m02 + m20) / scale, + ) + if m11 > m22: + scale = 2.0 * (1.0 + m11 - m00 - m22) ** 0.5 + return ( + (m02 - m20) / scale, + (m01 + m10) / scale, + 0.25 * scale, + (m12 + m21) / scale, + ) + scale = 2.0 * (1.0 + m22 - m00 - m11) ** 0.5 + return ( + (m10 - m01) / scale, + (m02 + m20) / scale, + (m12 + m21) / scale, + 0.25 * scale, + ) + + +def _placement_attributes(value: Placement, *, scale_length: bool) -> dict[str, str]: + origin = tuple(component * 0.001 for component in value.origin) if scale_length else value.origin + return { + "pos": _fmt_vec(origin), + "quat": _fmt_vec(_matrix_to_quat(value)), + } + + +def _write_obj(path: Path, solid: Any, *, linear_deflection: float) -> tuple[int, int]: + vertices, triangles = _tessellate_solid( + solid.wrapped, + linear_deflection=linear_deflection, + angular_deflection_radians=0.35, + relative=False, + ) + with path.open("w", encoding="ascii", newline="\n") as stream: + stream.write("# SimpleCAD BREP tessellation for MuJoCo\n") + for x, y, z in vertices: + stream.write(f"v {_fmt(float(x))} {_fmt(float(y))} {_fmt(float(z))}\n") + for a, b, c in triangles: + stream.write(f"f {int(a) + 1} {int(b) + 1} {int(c) + 1}\n") + return int(len(vertices)), int(len(triangles)) + + +def _density_kg_m3( + material: Any, + *, + default_density_kg_m3: float | None, +) -> tuple[float, bool]: + density = getattr(material, "density", None) if material is not None else None + unit = str(getattr(material, "density_unit", None) or "") if material is not None else "" + if density is None: + if default_density_kg_m3 is None: + raise ValueError( + "MJCF export requires material density for every Part; pass " + "default_density_kg_m3 explicitly to opt into a fallback" + ) + return float(default_density_kg_m3), True + if unit == "kg/mm^3": + return float(density) * 1.0e9, False + if unit in {"kg/m^3", "kg/m3"}: + return float(density), False + raise ValueError(f"unsupported material density unit for MJCF: {unit!r}") + + +def _world_placements(scene: Mapping[str, Any]) -> dict[str, Placement]: + nodes = {str(item["node_id"]): item for item in scene["nodes"]} + result: dict[str, Placement] = {} + pending = set(nodes) + while pending: + progress = False + for node_id in sorted(pending): + node = nodes[node_id] + parent_id = node["parent_node_id"] + if parent_id is not None and parent_id not in result: + continue + local = _placement(node["transform"]) + result[node_id] = local if parent_id is None else result[parent_id].compose(local) + pending.remove(node_id) + progress = True + break + if not progress: + raise ValueError("Scene node hierarchy contains an unresolved parent cycle") + return result + + +def _runtime_ground_edges(value: Assembly, root_node_id: str) -> list[tuple[str, str]]: + edges: list[tuple[str, str]] = [] + + def visit(item: Part | Assembly, node_id: str) -> None: + if not isinstance(item, Assembly): + return + for component in item.components: + child_node_id = f"{node_id}/{component.component_id}" + if component.component_id in item.grounded_component_ids: + edges.append((node_id, child_node_id)) + visit(component.item, child_node_id) + + visit(value, root_node_id) + return edges + + +def _entity_documents( + scene_package: Any, +) -> dict[str, dict[str, Any]]: + result: dict[str, dict[str, Any]] = {} + for record in scene_package.manifest["entity_assets"]: + document = parse_canonical_json(scene_package.blobs[record["uri"]]) + result[str(document["definition_id"])] = document + return result + + +def _part_materials(units: tuple[Any, ...]) -> dict[str, tuple[Part, float, bool]]: + result: dict[str, tuple[Part, float, bool]] = {} + for unit in units: + if not isinstance(unit.definition, PartDefinition): + continue + runtime = materialize_definition(unit.definition) + if not isinstance(runtime, Part): + raise TypeError(f"definition {unit.definition_id!r} did not materialize as Part") + result[unit.definition_id] = (runtime, 0.0, False) + return result + + +def export_product_package_to_mjcf( + data: ProductPackageInput, + output_path: str | Path, + *, + mesh_directory: str | Path | None = None, + mapping_path: str | Path | None = None, + linear_deflection: float = 0.15, + default_density_kg_m3: float | None = None, +) -> ProductMJCFExportReport: + """Compile a validated `.scadpkg` assembly into an MJCF model. + + Fixed constraints and attachments through forwarded nested-assembly + connectors create rigid groups. Revolute/prismatic edges form a + deterministic spanning tree. Gear, belt, and rack-pinion relations become + independent fixed-tendon equalities. Root assembly connectors and geometry + names in the ``interface.*`` namespace become MJCF sites. + """ + + if linear_deflection <= 0.0: + raise ValueError("linear_deflection must be positive") + destination = Path(output_path).expanduser().resolve() + if destination.suffix.lower() != ".xml": + raise ValueError("output_path must end in .xml") + destination.parent.mkdir(parents=True, exist_ok=True) + mesh_root = ( + Path(mesh_directory).expanduser().resolve() + if mesh_directory is not None + else destination.parent / f"{destination.stem}_meshes" + ) + mesh_root.mkdir(parents=True, exist_ok=True) + decision_path = ( + Path(mapping_path).expanduser().resolve() + if mapping_path is not None + else destination.with_suffix(".mapping.json") + ) + decision_path.parent.mkdir(parents=True, exist_ok=True) + + package, units = read_product_package_translation_units(data) + if ( + not hasattr(package.root_definition, "definition_kind") + or package.root_definition.definition_kind != "assembly" + ): + raise ValueError("MJCF export requires an assembly-rooted .scadpkg") + root_runtime = materialize_definition(package.root_definition) + if not isinstance(root_runtime, Assembly): + raise TypeError("assembly package root did not materialize as Assembly") + scene_package = read_scene_package(package.scene_bytes) + scene = scene_package.manifest + world = _world_placements(scene) + nodes = {str(item["node_id"]): item for item in scene["nodes"]} + root_node_id = str(scene["roots"][0]) + connector_records = list(scene["connectors"]) + connector_by_snapshot = { + str(item["connector_snapshot_id"]): item for item in connector_records + } + connectors_by_node_and_id = { + (str(item["node_id"]), str(item["connector_id"])): item + for item in connector_records + } + + def leaf_connector(record: Mapping[str, Any]) -> Mapping[str, Any]: + current = record + seen: set[str] = set() + while current.get("forwarded_from") is not None: + snapshot_id = str(current["connector_snapshot_id"]) + if snapshot_id in seen: + raise ValueError(f"forwarded connector cycle at {snapshot_id!r}") + seen.add(snapshot_id) + source = current["forwarded_from"] + child_node_id = f"{current['node_id']}/{source['component_id']}" + key = (child_node_id, str(source["connector_id"])) + try: + current = connectors_by_node_and_id[key] + except KeyError as exc: + raise ValueError( + f"forwarded connector {snapshot_id!r} does not resolve to {key!r}" + ) from exc + return current + + uf = _UnionFind(sorted(nodes)) + rigid_edges: list[dict[str, str]] = [] + movable_edges: list[dict[str, Any]] = [] + equality_edges: list[dict[str, Any]] = [] + for first, second in _runtime_ground_edges(root_runtime, root_node_id): + uf.union(first, second) + rigid_edges.append({"kind": "ground", "a": first, "b": second}) + for joint in scene["joints"]: + first_original = connector_by_snapshot[ + str(joint["connector_a"]["connector_snapshot_id"]) + ] + second_original = connector_by_snapshot[ + str(joint["connector_b"]["connector_snapshot_id"]) + ] + first_connector = leaf_connector(first_original) + second_connector = leaf_connector(second_original) + first = str(first_connector["node_id"]) + second = str(second_connector["node_id"]) + kind = str(joint["joint_type"]) + forwarded_attachment = kind in {"revolute", "prismatic"} and ( + first_original.get("forwarded_from") is not None + or second_original.get("forwarded_from") is not None + ) + if kind == "fixed" or forwarded_attachment: + uf.union(first, second) + rigid_edges.append( + { + "kind": "forwarded_attachment" if forwarded_attachment else kind, + "a": first, + "b": second, + "joint_id": str(joint["joint_id"]), + } + ) + elif kind in {"revolute", "prismatic"}: + movable_edges.append( + { + "joint": joint, + "a": first, + "b": second, + "connector_a": first_connector, + "connector_b": second_connector, + } + ) + elif kind in {"gear", "belt", "rack_pinion"}: + equality_edges.append( + { + "joint": joint, + "a": first, + "b": second, + "connector_a": first_connector, + "connector_b": second_connector, + } + ) + else: + raise ValueError(f"MJCF exporter does not support joint type {kind!r}") + + groups: dict[str, list[str]] = defaultdict(list) + for node_id in sorted(nodes): + groups[uf.find(node_id)].append(node_id) + root_group = uf.find(root_node_id) + group_for_node = {node_id: uf.find(node_id) for node_id in nodes} + group_representative: dict[str, str] = {} + for group_id, members in groups.items(): + geometric = [ + node_id + for node_id in members + if nodes[node_id]["node_kind"] == "part" and nodes[node_id]["entity_asset_id"] is not None + ] + group_representative[group_id] = sorted(geometric or members)[0] + + movable_edges.sort( + key=lambda item: ( + str(item["joint"]["assembly_definition_id"]) + != str(package.root_definition.definition_id), + str(item["joint"]["joint_id"]), + ) + ) + adjacency: dict[str, list[dict[str, Any]]] = defaultdict(list) + for edge in movable_edges: + first_group = group_for_node[edge["a"]] + second_group = group_for_node[edge["b"]] + if first_group == second_group: + raise ValueError( + f"movable joint {edge['joint']['joint_id']!r} collapsed inside a rigid grounding group" + ) + edge["a_group"] = first_group + edge["b_group"] = second_group + adjacency[first_group].append(edge) + adjacency[second_group].append(edge) + + parent_group: dict[str, str | None] = {root_group: None} + parent_edge: dict[str, dict[str, Any]] = {} + queue: deque[str] = deque([root_group]) + while queue: + current = queue.popleft() + for edge in sorted( + adjacency[current], + key=lambda item: ( + str(item["joint"]["assembly_definition_id"]) + != str(package.root_definition.definition_id), + str(item["joint"]["joint_id"]), + ), + ): + target = edge["b_group"] if edge["a_group"] == current else edge["a_group"] + if target in parent_group: + continue + parent_group[target] = current + parent_edge[target] = edge + queue.append(target) + unreachable = sorted(set(groups) - set(parent_group)) + if unreachable: + raise ValueError( + "MJCF kinematic graph is disconnected from grounding; unreachable groups: " + + ", ".join(unreachable) + ) + + body_name_by_group: dict[str, str] = {} + for group_id, edge in parent_edge.items(): + joint = edge["joint"] + group_component_id = None + for side in ("a", "b"): + endpoint = joint[f"connector_{side}"] + endpoint_snapshot = connector_by_snapshot[ + str(endpoint["connector_snapshot_id"]) + ] + if group_for_node[str(leaf_connector(endpoint_snapshot)["node_id"])] == group_id: + group_component_id = str(endpoint["component_id"]) + break + if group_component_id is None: + raise ValueError(f"tree joint {joint['joint_id']!r} does not identify child group") + body_name_by_group[group_id] = _safe_name( + f"body_{group_component_id}", prefix="body" + ) + tree_joint_name_by_group: dict[str, str] = {} + for group_id, edge in parent_edge.items(): + tree_joint_name_by_group[group_id] = _safe_name( + "joint_" + str(edge["joint"]["joint_id"]), prefix="joint" + ) + + angle_terms_by_group: dict[str, dict[str, float]] = {root_group: {}} + for group_id in parent_group: + if group_id == root_group: + continue + parent = parent_group[group_id] + if parent is None or parent not in angle_terms_by_group: + raise ValueError(f"group {group_id!r} has no resolved parent angle expression") + terms = dict(angle_terms_by_group[parent]) + terms[tree_joint_name_by_group[group_id]] = 1.0 + angle_terms_by_group[group_id] = terms + + tree_edge_ids = {id(edge) for edge in parent_edge.values()} + non_tree_movable_edges = [edge for edge in movable_edges if id(edge) not in tree_edge_ids] + + def relative_angle_terms(edge: Mapping[str, Any]) -> dict[str, float]: + return _subtracted_terms( + angle_terms_by_group[str(edge["b_group"])], + angle_terms_by_group[str(edge["a_group"])], + ) + + def support_edge(connector_snapshot_id: str, group_id: str) -> dict[str, Any] | None: + candidates = [ + edge + for edge in movable_edges + if connector_snapshot_id + in { + str(edge["connector_a"]["connector_snapshot_id"]), + str(edge["connector_b"]["connector_snapshot_id"]), + } + ] + if not candidates: + return None if group_id == root_group else None + if len(candidates) != 1: + raise ValueError( + f"connector {connector_snapshot_id!r} has ambiguous movable supports: " + + ", ".join(str(edge["joint"]["joint_id"]) for edge in candidates) + ) + return candidates[0] + part_materials = _part_materials(units) + mesh_by_definition: dict[str, str] = {} + density_by_definition: dict[str, float] = {} + default_density_count = 0 + for definition_id, (part, _unused_density, _unused_default) in sorted(part_materials.items()): + density, used_default = _density_kg_m3( + part.material, + default_density_kg_m3=default_density_kg_m3, + ) + density_by_definition[definition_id] = density + default_density_count += int(used_default) + mesh_name = _safe_name("mesh_" + definition_id, prefix="mesh") + mesh_path = mesh_root / f"{mesh_name}.obj" + _write_obj(mesh_path, part.body, linear_deflection=linear_deflection) + mesh_by_definition[definition_id] = mesh_name + + entity_documents = _entity_documents(scene_package) + mesh_asset_elements: list[ET.Element] = [] + for definition_id, mesh_name in sorted(mesh_by_definition.items()): + mesh_asset_elements.append( + ET.Element( + "mesh", + { + "name": mesh_name, + "file": os.path.relpath( + mesh_root / f"{mesh_name}.obj", + start=destination.parent, + ), + "scale": "0.001 0.001 0.001", + }, + ) + ) + + root_xml = ET.Element("mujoco", {"model": str(package.root_definition.definition_id)}) + ET.SubElement(root_xml, "compiler", {"angle": "radian", "coordinate": "local"}) + ET.SubElement(root_xml, "option", {"gravity": "0 0 -9.81"}) + asset_xml = ET.SubElement(root_xml, "asset") + for element in mesh_asset_elements: + asset_xml.append(element) + world_xml = ET.SubElement(root_xml, "worldbody") + + group_children: dict[str, list[str]] = defaultdict(list) + for group_id, parent in parent_group.items(): + if parent is not None: + group_children[parent].append(group_id) + + group_body_frame: dict[str, Placement] = { + root_group: Placement((0.0, 0.0, 0.0)), + **{ + group_id: world[group_representative[group_id]] + for group_id in groups + if group_id != root_group + }, + } + body_nodes: dict[str, ET.Element] = {root_group: world_xml} + + def relative_to_group(group_id: str, node_id: str) -> Placement: + return relative_placement(group_body_frame[group_id], world[node_id]) + site_count = 0 + geom_count = 0 + site_records: list[dict[str, Any]] = [] + + def append_group_content(group_id: str, parent_xml: ET.Element) -> None: + nonlocal site_count, geom_count + body_frame = group_body_frame[group_id] + for node_id in sorted(groups[group_id]): + node = nodes[node_id] + definition_id = str(node["definition_id"]) + mesh_name = mesh_by_definition.get(definition_id) + if mesh_name is not None: + local = relative_to_group(group_id, node_id) + if node.get("parent_node_id") == root_node_id and node.get("component_id"): + semantic_id = str(node["component_id"]) + else: + semantic_id = f"geom_{node_id}" + geom_name = _safe_name(semantic_id, prefix="geom") + attrs = { + "name": geom_name, + "type": "mesh", + "mesh": mesh_name, + "density": _fmt(density_by_definition[definition_id]), + "contype": "1", + "conaffinity": "1", + **_placement_attributes(local, scale_length=True), + } + ET.SubElement(parent_xml, "geom", attrs) + geom_count += 1 + if node["entity_asset_id"] is None: + continue + document = entity_documents[definition_id] + for entity in document["entities"]: + tags = [ + str(tag) + for tag in entity.get("tags", []) + if str(tag).startswith("interface.") + ] + if not tags: + continue + props = entity.get("properties", {}) + frame_payload = props.get("connector_frame") + if frame_payload is None: + origin = tuple( + float(value) + for value in props.get("centroid", [0.0, 0.0, 0.0]) + ) + entity_frame = Placement(origin) + else: + entity_frame = _placement(frame_payload) + site_world = world[node_id].compose(entity_frame) + local = relative_placement(body_frame, site_world) + for tag in tags: + site_name = _safe_name(f"site_{node_id}_{tag}", prefix="site") + ET.SubElement( + parent_xml, + "site", + { + "name": site_name, + "size": "0.0008", + "type": "sphere", + **_placement_attributes(local, scale_length=True), + }, + ) + site_records.append( + { + "name": site_name, + "tag": tag, + "node_id": node_id, + "entity_id": entity["entity_id"], + "topo_id": entity["topo_id"], + } + ) + site_count += 1 + + def append_group_tree(group_id: str, parent_xml: ET.Element) -> None: + for child_group in sorted(group_children[group_id], key=lambda item: body_name_by_group[item]): + child_frame = group_body_frame[child_group] + parent_frame = group_body_frame[group_id] + local = relative_placement(parent_frame, child_frame) + body_xml = ET.SubElement( + parent_xml, + "body", + {"name": body_name_by_group[child_group], **_placement_attributes(local, scale_length=True)}, + ) + body_nodes[child_group] = body_xml + edge = parent_edge[child_group] + joint = edge["joint"] + connector = edge["connector_a"] + connector_frame = _placement(connector["local_frame"]) + joint_world = world[str(connector["node_id"])].compose(connector_frame) + joint_local = relative_placement(child_frame, joint_world) + joint_axis_world = world[str(connector["node_id"])].transform_vector( + connector_frame.z_axis + ) + axis = _inverse_vector(child_frame, joint_axis_world) + joint_attrs = { + "name": tree_joint_name_by_group[child_group], + "type": "hinge" if joint["joint_type"] == "revolute" else "slide", + "pos": _fmt_vec(tuple(value * 0.001 for value in joint_local.origin)), + "axis": _fmt_vec(axis), + } + limits = joint.get("limits") + if limits is not None: + limit_key = ( + "angle_limit" + if joint["joint_type"] == "revolute" + else "distance_limit" + ) + scalar_limit = limits.get(limit_key) or limits + lower = float(scalar_limit.get("lower_value", 0.0)) + upper = float(scalar_limit.get("upper_value", 0.0)) + if joint["joint_type"] == "revolute": + lower = lower * 3.141592653589793 / 180.0 + upper = upper * 3.141592653589793 / 180.0 + else: + lower, upper = lower * 0.001, upper * 0.001 + joint_attrs.update( + {"limited": "true", "range": f"{_fmt(lower)} {_fmt(upper)}"} + ) + ET.SubElement(body_xml, "joint", joint_attrs) + append_group_content(child_group, body_xml) + append_group_tree(child_group, body_xml) + + append_group_content(root_group, world_xml) + append_group_tree(root_group, world_xml) + + public_connectors = [ + connector + for connector in connector_records + if str(connector["node_id"]) == root_node_id + ] + for connector in public_connectors: + connector_id = str(connector["connector_id"]) + leaf = leaf_connector(connector) + leaf_node_id = str(leaf["node_id"]) + group_id = group_for_node[leaf_node_id] + frame_world = world[str(connector["node_id"])].compose( + _placement(connector["local_frame"]) + ) + local = relative_placement(group_body_frame[group_id], frame_world) + site_name = _safe_name(connector_id, prefix="site") + ET.SubElement( + body_nodes[group_id], + "site", + { + "name": site_name, + "size": "0.0012", + "type": "sphere", + **_placement_attributes(local, scale_length=True), + }, + ) + site_records.append( + { + "name": site_name, + "connector_id": connector_id, + "connector_snapshot_id": connector["connector_snapshot_id"], + "node_id": connector["node_id"], + "attached_group": group_id, + } + ) + site_count += 1 + + joint_names = sorted(tree_joint_name_by_group.values()) + joint_index = {name: index for index, name in enumerate(joint_names)} + candidate_equalities: list[dict[str, Any]] = [] + for edge in equality_edges: + joint = edge["joint"] + kind = str(joint["joint_type"]) + parameters = dict(joint.get("parameters") or {}) + endpoint_terms: list[dict[str, float]] = [] + for side in ("a", "b"): + connector = edge[f"connector_{side}"] + group_id = group_for_node[str(edge[side])] + support = support_edge(str(connector["connector_snapshot_id"]), group_id) + if support is None: + if group_id != root_group: + raise ValueError( + f"coupling {joint['joint_id']!r} endpoint {side} has no movable support" + ) + endpoint_terms.append({}) + else: + endpoint_terms.append(relative_angle_terms(support)) + first_terms, second_terms = endpoint_terms + coefficients: dict[str, float] = {} + if kind == "gear": + _add_scaled_terms(coefficients, first_terms, float(parameters["pitch_radius_a"])) + _add_scaled_terms(coefficients, second_terms, float(parameters["pitch_radius_b"])) + elif kind == "belt": + _add_scaled_terms(coefficients, first_terms, float(parameters["pulley_radius_a"])) + _add_scaled_terms(coefficients, second_terms, -float(parameters["pulley_radius_b"])) + else: + _add_scaled_terms(coefficients, first_terms, 1.0) + _add_scaled_terms( + coefficients, + second_terms, + float(parameters["pitch_radius"]) * 0.001, + ) + coefficients = { + name: value for name, value in coefficients.items() if abs(value) > 1.0e-12 + } + if not coefficients: + raise ValueError(f"coupling {joint['joint_id']!r} produced an empty equation") + row = np.zeros(len(joint_names), dtype=float) + for name, coefficient in coefficients.items(): + row[joint_index[name]] = coefficient + candidate_equalities.append( + { + "joint": joint, + "coefficients": coefficients, + "row": row, + "reference_phase": float(parameters.get("phase_offset", 0.0)), + } + ) + + independent_equalities: list[dict[str, Any]] = [] + current_rows = np.empty((0, len(joint_names)), dtype=float) + current_rank = 0 + equality_records: list[dict[str, Any]] = [] + for candidate in candidate_equalities: + trial = np.vstack((current_rows, candidate["row"])) + trial_rank = int(np.linalg.matrix_rank(trial, tol=1.0e-10)) + independent = trial_rank > current_rank + record = { + "equality_id": str(candidate["joint"]["joint_id"]), + "joint_type": str(candidate["joint"]["joint_type"]), + "coefficients": dict(sorted(candidate["coefficients"].items())), + "reference_phase_source_units": candidate["reference_phase"], + "independent": independent, + } + equality_records.append(record) + if independent: + independent_equalities.append({**candidate, "record": record}) + current_rows = trial + current_rank = trial_rank + + tendon_xml = ET.SubElement(root_xml, "tendon") + equality_xml = ET.SubElement(root_xml, "equality") + for candidate in independent_equalities: + joint = candidate["joint"] + tendon_name = _safe_name("coupling_" + str(joint["joint_id"]), prefix="coupling") + fixed_xml = ET.SubElement(tendon_xml, "fixed", {"name": tendon_name}) + for name, coefficient in sorted(candidate["coefficients"].items()): + ET.SubElement( + fixed_xml, + "joint", + {"joint": name, "coef": _fmt(coefficient)}, + ) + equality_name = _safe_name("equality_" + str(joint["joint_id"]), prefix="equality") + ET.SubElement( + equality_xml, + "tendon", + { + "name": equality_name, + "tendon1": tendon_name, + "polycoef": "0 0 0 0 0", + }, + ) + candidate["record"].update( + {"name": equality_name, "tendon": tendon_name} + ) + if not independent_equalities: + root_xml.remove(tendon_xml) + root_xml.remove(equality_xml) + + ET.indent(root_xml, space=" ") + tree = ET.ElementTree(root_xml) + tree.write(destination, encoding="utf-8", xml_declaration=True) + if destination.stat().st_size <= 0: + raise RuntimeError("MJCF writer produced an empty XML file") + + group_records = [ + { + "group_id": group_id, + "members": sorted(members), + "grounded": group_id == root_group, + "representative": group_representative[group_id], + "body_name": None if group_id == root_group else body_name_by_group[group_id], + "parent_group": parent_group[group_id], + "tree_joint": None if group_id == root_group else tree_joint_name_by_group[group_id], + } + for group_id, members in sorted(groups.items()) + ] + mapping = { + "schema_version": "1.0", + "root_definition_id": package.root_definition.definition_id, + "units": {"source": "mm", "mjcf_length": "m", "mjcf_angle": "radian"}, + "grounded_group_id": root_group, + "groups": group_records, + "rigid_edges": rigid_edges, + "tree_joints": [ + { + "joint_id": str(edge["joint"]["joint_id"]), + "group": group_id, + "parent_group": parent_group[group_id], + "joint_name": tree_joint_name_by_group[group_id], + } + for group_id, edge in sorted(parent_edge.items()) + ], + "redundant_movable_joints": [ + str(edge["joint"]["joint_id"]) for edge in non_tree_movable_edges + ], + "equalities": equality_records, + "sites": site_records, + "meshes": {definition_id: name for definition_id, name in sorted(mesh_by_definition.items())}, + "default_density_count": default_density_count, + } + decision_path.write_text(json.dumps(mapping, indent=2, sort_keys=True) + "\n", encoding="utf-8") + limitations = ( + "Mesh geoms are generated from BREP tessellation and scaled from mm to m.", + "MuJoCo mesh collision uses its supported mesh collision representation; no convex decomposition is attempted.", + "Revolute/prismatic attachments through forwarded nested-assembly connectors assign internal bearing geometry to the supported rigid group without adding another MJCF degree of freedom.", + "Gear, belt, and rack-pinion relations constrain reference-pose increments through independent fixed tendons.", + ) + return ProductMJCFExportReport( + output_path=destination, + mapping_path=decision_path, + mesh_directory=mesh_root, + root_definition_id=package.root_definition.definition_id, + mesh_count=len(mesh_by_definition), + body_count=len(body_name_by_group), + joint_count=len(tree_joint_name_by_group), + equality_count=len(independent_equalities), + grounded_group_count=1, + site_count=site_count, + default_density_count=default_density_count, + limitations=limitations, + ) + + +__all__ = ["ProductMJCFExportReport", "export_product_package_to_mjcf"] diff --git a/src/simplecadapi/exporter/obj.py b/src/simplecadapi/exporter/obj.py new file mode 100644 index 00000000..07f77fcc --- /dev/null +++ b/src/simplecadapi/exporter/obj.py @@ -0,0 +1,74 @@ +"""Direct OpenCASCADE BREP tessellation to triangle OBJ.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from ..translator.package_units import ProductPackageInput +from ._surface_mesh import tessellate_product_surface + + +@dataclass(frozen=True, slots=True) +class ProductOBJExportReport: + """Evidence from direct BREP tessellation and triangle OBJ export.""" + + output_path: Path + root_definition_id: str + solid_count: int + definition_count: int + vertex_count: int + triangle_count: int + linear_deflection: float + angular_deflection_degrees: float + relative: bool + tessellation_backend: str = "opencascade-brep-tessellation" + + +def export_product_package_to_obj( + data: ProductPackageInput, + output_path: str | Path, + *, + linear_deflection: float = 0.1, + angular_deflection_degrees: float = 20.0, + relative: bool = False, +) -> ProductOBJExportReport: + """Export one `.scadpkg` directly from evaluated BREP as triangle OBJ. + + `linear_deflection` is the maximum chordal deviation in product units. + `angular_deflection_degrees` limits angular deviation on curved surfaces. + No remeshing or topology reconstruction is performed. + """ + + destination = Path(output_path).expanduser().resolve() + if destination.suffix.lower() != ".obj": + raise ValueError("output_path must end in .obj") + destination.parent.mkdir(parents=True, exist_ok=True) + mesh = tessellate_product_surface( + data=data, + linear_deflection=linear_deflection, + angular_deflection_degrees=angular_deflection_degrees, + relative=relative, + ) + with destination.open("w", encoding="ascii", newline="\n") as stream: + stream.write("# SimpleCAD OpenCASCADE BREP tessellation\n") + for x, y, z in mesh.vertices: + stream.write(f"v {float(x):.17g} {float(y):.17g} {float(z):.17g}\n") + for a, b, c in mesh.triangles: + stream.write(f"f {int(a) + 1} {int(b) + 1} {int(c) + 1}\n") + if destination.stat().st_size <= 0: + raise RuntimeError("OBJ writer produced an empty file") + return ProductOBJExportReport( + output_path=destination, + root_definition_id=mesh.root_definition_id, + solid_count=mesh.solid_count, + definition_count=mesh.definition_count, + vertex_count=mesh.vertex_count, + triangle_count=mesh.triangle_count, + linear_deflection=mesh.linear_deflection, + angular_deflection_degrees=mesh.angular_deflection_degrees, + relative=mesh.relative, + ) + + +__all__ = ["ProductOBJExportReport", "export_product_package_to_obj"] diff --git a/src/simplecadapi/exporter/stl.py b/src/simplecadapi/exporter/stl.py index 80ad37a3..ae8fab83 100644 --- a/src/simplecadapi/exporter/stl.py +++ b/src/simplecadapi/exporter/stl.py @@ -1,166 +1,93 @@ -"""Quad-dominant STL export for validated product packages.""" +"""Direct OpenCASCADE BREP tessellation to binary STL.""" from __future__ import annotations from dataclasses import dataclass -import importlib from pathlib import Path -import tempfile -from typing import Any +import struct -from OCP.BRepTools import BRepTools +import numpy as np -from ..artifacts.assembly_io import materialize_definition -from ..operations import make_compound_from_assembly_rcompound -from ..product import Assembly, Part -from ..translator.package_units import ( - ProductPackageInput, - read_product_package_translation_units, -) +from ..translator.package_units import ProductPackageInput +from ._surface_mesh import TessellatedSurfaceMesh, tessellate_product_surface @dataclass(frozen=True, slots=True) class ProductSTLExportReport: - """Evidence from quad-dominant product-surface remeshing and STL export.""" + """Evidence from direct BREP tessellation and binary STL export.""" output_path: Path root_definition_id: str solid_count: int definition_count: int - quadrilateral_count: int - residual_triangle_count: int - stl_triangle_count: int - quad_fraction: float - mesh_size: float - remesh_backend: str = "gmsh-quad-dominant" + vertex_count: int + triangle_count: int + linear_deflection: float + angular_deflection_degrees: float + relative: bool + tessellation_backend: str = "opencascade-brep-tessellation" -def _load_gmsh() -> Any: - try: - return importlib.import_module("gmsh") - except ImportError as exc: - raise RuntimeError( - "Product STL export requires the 'gmsh' optional dependency; " - "install simplecadapi[gmsh]" - ) from exc - - -def _product_shape(value: Part | Assembly): - if isinstance(value, Part): - return value.body.wrapped, 1 - projection = make_compound_from_assembly_rcompound(assembly=value) - solid_count = int( - projection.get_metadata("assembly_projection", {}).get("solid_count", 0) - ) - if solid_count <= 0: - raise ValueError("Product assembly produced no solids for STL export") - return projection.wrapped, solid_count - - -def _surface_element_counts(gmsh: Any) -> tuple[int, int, int]: - quadrilaterals = 0 - triangles = 0 - stl_triangles = 0 - element_types, element_tags, _node_tags = gmsh.model.mesh.getElements(2) - for element_type, tags in zip(element_types, element_tags): - name, dimension, _order, node_count, _coords, primary_node_count = ( - gmsh.model.mesh.getElementProperties(element_type) - ) - if int(dimension) != 2: - continue - count = len(tags) - if int(primary_node_count) == 4 and "Quadrilateral" in str(name): - quadrilaterals += count - stl_triangles += 2 * count - elif int(primary_node_count) == 3 and "Triangle" in str(name): - triangles += count - stl_triangles += count - else: - raise RuntimeError( - f"Gmsh produced unsupported STL surface element {name!r} " - f"with {node_count} nodes" +def _write_binary_stl(path: Path, mesh: TessellatedSurfaceMesh) -> None: + header = b"SimpleCAD OpenCASCADE BREP tessellation".ljust(80, b"\0") + with path.open("wb") as stream: + stream.write(header) + stream.write(struct.pack(" ProductSTLExportReport: - """Export one validated `.scadpkg` as a quad-dominant remeshed STL. + """Export one `.scadpkg` directly from evaluated BREP as binary STL. - Gmsh recombines each CAD surface into quadrilaterals before its STL writer - splits every quad into two triangles, as required by the STL file format. + `linear_deflection` is the maximum chordal deviation in product units. + `angular_deflection_degrees` limits angular deviation on curved surfaces. + No remeshing or topology reconstruction is performed. """ - size = float(mesh_size) - if size <= 0.0: - raise ValueError("mesh_size must be greater than zero") - angle = float(recombination_angle_degrees) - if not 0.0 < angle <= 180.0: - raise ValueError("recombination_angle_degrees must be in (0, 180]") - - package, units = read_product_package_translation_units(data) - root = materialize_definition(package.root_definition) - shape, solid_count = _product_shape(root) destination = Path(output_path).expanduser().resolve() if destination.suffix.lower() != ".stl": raise ValueError("output_path must end in .stl") destination.parent.mkdir(parents=True, exist_ok=True) - - gmsh = _load_gmsh() - initialized = False - with tempfile.TemporaryDirectory(prefix="simplecad_product_stl_") as temp_dir: - brep_path = Path(temp_dir) / "product.brep" - if not BRepTools.Write_s(shape, str(brep_path)): - raise RuntimeError( - "OpenCASCADE failed to serialize product BREP for remeshing" - ) - try: - gmsh.initialize() - initialized = True - gmsh.option.setNumber("General.Terminal", 0) - gmsh.model.add("SimpleCADProductSTL") - imported = gmsh.model.occ.importShapes( - str(brep_path), highestDimOnly=True, format="brep" - ) - if not imported: - raise RuntimeError("Gmsh imported no product geometry") - gmsh.model.occ.synchronize() - surfaces = gmsh.model.getEntities(2) - if not surfaces: - raise RuntimeError("Gmsh product geometry has no meshable surfaces") - gmsh.option.setNumber("Mesh.Algorithm", 8) - gmsh.option.setNumber("Mesh.RecombinationAlgorithm", 1) - gmsh.option.setNumber("Mesh.MeshSizeMin", size) - gmsh.option.setNumber("Mesh.MeshSizeMax", size) - for _dimension, tag in surfaces: - gmsh.model.mesh.setRecombine(2, tag, angle) - gmsh.model.mesh.generate(2) - quadrilaterals, triangles, stl_triangles = _surface_element_counts(gmsh) - if quadrilaterals + triangles == 0: - raise RuntimeError("Gmsh produced no surface elements") - gmsh.write(str(destination)) - finally: - if initialized: - gmsh.finalize() - - if not destination.is_file() or destination.stat().st_size <= 0: - raise RuntimeError("Gmsh did not create a non-empty STL file") - surface_count = quadrilaterals + triangles + mesh = tessellate_product_surface( + data=data, + linear_deflection=linear_deflection, + angular_deflection_degrees=angular_deflection_degrees, + relative=relative, + ) + _write_binary_stl(destination, mesh) + if destination.stat().st_size != 84 + 50 * mesh.triangle_count: + raise RuntimeError("STL writer produced an invalid binary length") return ProductSTLExportReport( output_path=destination, - root_definition_id=package.root_definition.definition_id, - solid_count=solid_count, - definition_count=len(units), - quadrilateral_count=quadrilaterals, - residual_triangle_count=triangles, - stl_triangle_count=stl_triangles, - quad_fraction=quadrilaterals / surface_count, - mesh_size=size, + root_definition_id=mesh.root_definition_id, + solid_count=mesh.solid_count, + definition_count=mesh.definition_count, + vertex_count=mesh.vertex_count, + triangle_count=mesh.triangle_count, + linear_deflection=mesh.linear_deflection, + angular_deflection_degrees=mesh.angular_deflection_degrees, + relative=mesh.relative, ) diff --git a/test/test_ap242_gmsh_example.py b/test/test_ap242_gmsh_example.py index 35063a40..5b187326 100644 --- a/test/test_ap242_gmsh_example.py +++ b/test/test_ap242_gmsh_example.py @@ -4,16 +4,31 @@ from __future__ import annotations import importlib.util from pathlib import Path +import json import tempfile import unittest ROOT = Path(__file__).resolve().parents[1] -EXAMPLE = ROOT / "examples" / "12_ap242_gmsh_volume_mesh.py" +EXAMPLE_DIR = ROOT / "examples" / "12_ap242_gmsh_volume_mesh" +MODEL_EXAMPLE = EXAMPLE_DIR / "model.py" +DOWNSTREAM_EXAMPLES = { + "fcstd": EXAMPLE_DIR / "export_fcstd.py", + "step": EXAMPLE_DIR / "export_step.py", + "stl": EXAMPLE_DIR / "export_stl.py", + "obj": EXAMPLE_DIR / "export_obj.py", + "freecad_script": EXAMPLE_DIR / "translate_freecad_script.py", + "fusion360_script": EXAMPLE_DIR / "translate_fusion360_script.py", + "solidworks_script": EXAMPLE_DIR / "translate_solidworks_script.py", +} +MESH_EXAMPLE = EXAMPLE_DIR / "export_fem_mesh.py" +CALCULIX_EXAMPLE = EXAMPLE_DIR / "run_calculix.py" +VISUALIZATION_EXAMPLE = EXAMPLE_DIR / "visualize_calculix.py" +CONVERGENCE_EXAMPLE = EXAMPLE_DIR / "study_mesh_convergence.py" -def _load_example(): - spec = importlib.util.spec_from_file_location("ap242_gmsh_example", EXAMPLE) +def _load_example(path: Path, module_name: str): + spec = importlib.util.spec_from_file_location(module_name, path) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) import sys @@ -108,16 +123,149 @@ class _Gmsh: ) -class TestAP242GmshExample(unittest.TestCase): - def test_example_import_does_not_require_gmsh(self): - module = _load_example() +class _CalculiXMesh: + def getNodes(self): + return ( + [10, 20, 30, 40, 50], + [ + 0.0, 0.0, 0.0, + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0, + 1.0, 1.0, 0.0, + ], + [], + ) - self.assertTrue(callable(module.build_bracket)) - self.assertTrue(callable(module.mesh_step_with_gmsh)) - self.assertEqual(module.OUT_DIR.name, "ap242_gmsh_volume_mesh") + def getElementType(self, family, order): + self.last_element_request = (family, order) + return {"Tetrahedron": 4, "Triangle": 2}[family] + + def getElementTypes(self, dimension): + return [4] if dimension == 3 else [] + + def getElementsByType(self, element_type, tag=-1): + if element_type == 4: + return [100, 101], [10, 20, 30, 40, 20, 30, 40, 50] + if element_type == 2 and tag == 22: + return [200], [20, 30, 50] + return [], [] + + def getNodesForPhysicalGroup(self, dimension, tag): + self.last_node_group = (dimension, tag) + return [10, 30, 40], [0.0] * 9 + + +class _CalculiXModel: + def __init__(self): + self.mesh = _CalculiXMesh() + + def getPhysicalGroups(self, dimension): + return [(2, 2), (2, 4)] if dimension == 2 else [] + + def getPhysicalName(self, dimension, tag): + return { + (2, 2): "interface.fixed_support", + (2, 4): "interface.load_surface", + }[(dimension, tag)] + + def getEntitiesForPhysicalGroup(self, dimension, tag): + return [22] if (dimension, tag) == (2, 4) else [] + + +class _CalculiXGmsh: + def __init__(self): + self.model = _CalculiXModel() + self.initialized = 0 + self.finalized = 0 + self.opened = [] + + def initialize(self): + self.initialized += 1 + + def open(self, path): + self.opened.append(path) + + def finalize(self): + self.finalized += 1 + + +class TestAP242GmshExample(unittest.TestCase): + def test_split_example_modules_have_one_responsibility(self): + model = _load_example(MODEL_EXAMPLE, "ap242_model_example") + downstream = { + name: _load_example(path, f"ap242_{name}_example") + for name, path in DOWNSTREAM_EXAMPLES.items() + } + mesh = _load_example(MESH_EXAMPLE, "ap242_mesh_example") + calculix = _load_example(CALCULIX_EXAMPLE, "ap242_calculix_example") + visualization = _load_example( + VISUALIZATION_EXAMPLE, + "ap242_calculix_visualization_example", + ) + + self.assertTrue(callable(model.build_bracket)) + self.assertFalse(hasattr(model, "mesh_step_with_gmsh")) + self.assertTrue(all(callable(module.main) for module in downstream.values())) + self.assertTrue(callable(mesh.mesh_step_with_gmsh)) + self.assertTrue(callable(calculix.build_calculix_input)) + self.assertTrue(callable(calculix.run_calculix_static)) + self.assertTrue(callable(visualization.visualize_calculix_result)) + self.assertFalse(hasattr(mesh, "build_bracket")) + self.assertEqual( + { + model.OUT_DIR, + mesh.OUT_DIR, + *(module.OUT_DIR for module in downstream.values()), + }, + {ROOT / "examples" / "out" / "ap242_gmsh_volume_mesh"}, + ) + + def test_example_covers_every_package_exporter_and_translator(self): + import simplecadapi as scad + + self.assertEqual( + set(DOWNSTREAM_EXAMPLES), + { + "fcstd", + "step", + "stl", + "obj", + "freecad_script", + "fusion360_script", + "solidworks_script", + }, + ) + self.assertTrue(hasattr(scad.exporter, "export_product_package_to_step")) + self.assertTrue(hasattr(scad.exporter, "export_product_package_to_stl")) + self.assertTrue(hasattr(scad.exporter, "export_product_package_to_obj")) + self.assertTrue( + hasattr( + scad.translator.freecad_translator, + "translate_product_package_to_fcstd", + ) + ) + self.assertTrue( + hasattr( + scad.translator.freecad_translator, + "translate_product_package_to_freecad_script", + ) + ) + self.assertTrue( + hasattr( + scad.translator.fusion360_translator, + "translate_product_package_to_fusion360_script", + ) + ) + self.assertTrue( + hasattr( + scad.translator.solidworks_translator, + "translate_product_package_to_solidworks_script", + ) + ) def test_mesh_step_uses_occ_volume_mesh_and_reports_counts(self): - module = _load_example() + module = _load_example(MESH_EXAMPLE, "ap242_mesh_success_example") gmsh = _Gmsh() with tempfile.TemporaryDirectory() as tmp_dir: root = Path(tmp_dir) @@ -145,7 +293,7 @@ class TestAP242GmshExample(unittest.TestCase): self.assertEqual(report.element_count, 2) def test_gmsh_is_finalized_when_meshing_fails(self): - module = _load_example() + module = _load_example(MESH_EXAMPLE, "ap242_mesh_failure_example") gmsh = _Gmsh(fail=True) with tempfile.TemporaryDirectory() as tmp_dir: step = Path(tmp_dir) / "part.step" @@ -160,6 +308,246 @@ class TestAP242GmshExample(unittest.TestCase): self.assertEqual(gmsh.initialized, 1) self.assertEqual(gmsh.finalized, 1) + def test_calculix_input_preserves_node_ids_groups_and_total_load(self): + module = _load_example(CALCULIX_EXAMPLE, "ap242_calculix_input_example") + gmsh = _CalculiXGmsh() + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + mesh = root / "bracket.msh" + mesh.write_text("MSH", encoding="ascii") + input_path = root / "bracket.inp" + report = module.build_calculix_input( + mesh, + input_path, + load_z_n=-900.0, + gmsh_module=gmsh, + ) + deck = input_path.read_text(encoding="ascii") + + self.assertEqual(gmsh.initialized, 1) + self.assertEqual(gmsh.finalized, 1) + self.assertEqual(report.node_count, 5) + self.assertEqual(report.element_count, 2) + self.assertEqual(report.fixed_node_count, 3) + self.assertEqual(report.load_node_count, 3) + self.assertAlmostEqual(report.load_surface_area_mm2, 0.5) + self.assertAlmostEqual(report.applied_load_z_n, -900.0) + self.assertIn("10,0,0,0", deck) + self.assertIn("100,10,20,30,40", deck) + self.assertIn("FIXED_SUPPORT,1,3", deck) + self.assertIn("20,3,-300", deck) + self.assertIn("30,3,-300", deck) + self.assertIn("50,3,-300", deck) + self.assertIn("*NODE FILE\nU", deck) + self.assertIn("*NODE PRINT,NSET=FIXED_SUPPORT,TOTALS=ONLY\nRF", deck) + self.assertIn("*STATIC,SOLVER=SPOOLES", deck) + self.assertIn("*EL FILE\nS", deck) + + def test_calculix_input_accepts_iterative_cholesky_solver(self): + module = _load_example(CALCULIX_EXAMPLE, "ap242_calculix_solver_example") + gmsh = _CalculiXGmsh() + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + mesh = root / "bracket.msh" + mesh.write_text("MSH", encoding="ascii") + input_path = root / "bracket.inp" + report = module.build_calculix_input( + mesh, + input_path, + linear_solver="iterative cholesky", + gmsh_module=gmsh, + ) + deck = input_path.read_text(encoding="ascii") + + self.assertEqual(report.linear_solver, "ITERATIVE CHOLESKY") + self.assertIn("*STATIC,SOLVER=ITERATIVE CHOLESKY", deck) + + def test_calculix_dat_parser_reports_displacement_and_von_mises(self): + module = _load_example(CALCULIX_EXAMPLE, "ap242_calculix_parser_example") + with tempfile.TemporaryDirectory() as tmp_dir: + dat_path = Path(tmp_dir) / "result.dat" + dat_path.write_text( + " displacements (vx,vy,vz) for set NALL and time 1.0000000E+00\n" + " 10 3.0E-01 4.0E-01 0.0E+00\n" + " 20 0.0E+00 0.0E+00 -2.0E-01\n\n" + " total force (fx,fy,fz) for set FIXED_SUPPORT and time 1.0000000E+00\n" + " 0.0E+00 0.0E+00 9.0E+02\n\n" + " stresses (elem, integ.pnt.,sxx,syy,szz,sxy,sxz,syz) " + "for set EALL and time 1.0000000E+00\n" + " 100 1 1.0E+02 0.0E+00 0.0E+00 0.0E+00 0.0E+00 0.0E+00\n" + " 101 1 0.0E+00 0.0E+00 0.0E+00 5.0E+01 0.0E+00 0.0E+00\n", + encoding="ascii", + ) + result = module.parse_calculix_dat(dat_path) + + self.assertAlmostEqual(result["max_displacement_mm"], 0.5) + self.assertEqual(result["max_displacement_node"], 10) + self.assertAlmostEqual(result["max_von_mises_mpa"], 100.0) + self.assertEqual(result["max_von_mises_element"], 100) + self.assertAlmostEqual(result["reaction_force_z_n"], 900.0) + + def test_calculix_runner_executes_job_and_writes_summary(self): + module = _load_example(CALCULIX_EXAMPLE, "ap242_calculix_runner_example") + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + input_path = root / "job.inp" + input_path.write_text("*HEADING\n", encoding="ascii") + executable = root / "ccx_2.23" + executable.write_text("#!/bin/sh\n", encoding="ascii") + executable.chmod(0o755) + report = module.CalculiXInputReport( + mesh_path=root / "mesh.msh", + input_path=input_path, + node_count=5, + element_count=2, + fixed_node_count=3, + load_node_count=3, + load_surface_area_mm2=0.5, + applied_load_z_n=-900.0, + linear_solver="ITERATIVE CHOLESKY", + ) + + def runner(command, **kwargs): + self.assertEqual(command, [str(executable.resolve()), "job"]) + self.assertEqual(kwargs["cwd"], root.resolve()) + (root / "job.dat").write_text( + " displacements (vx,vy,vz) for set NALL and time 1\n" + " 10 0.0 0.0 -0.2\n" + " total force (fx,fy,fz) for set FIXED_SUPPORT and time 1\n" + " 0 0 900\n" + " stresses (elem, integ.pnt.,sxx,syy,szz,sxy,sxz,syz) " + "for set EALL and time 1\n" + " 100 1 100 0 0 0 0 0\n", + encoding="ascii", + ) + (root / "job.frd").write_text("FRD\n", encoding="ascii") + return type("Completed", (), {"returncode": 0, "stdout": "ok", "stderr": ""})() + + result = module.run_calculix_static( + report, + ccx=executable, + runner=runner, + ) + summary = json.loads(result.summary_path.read_text(encoding="utf-8")) + + self.assertAlmostEqual(result.max_displacement_mm, 0.2) + self.assertAlmostEqual(result.max_von_mises_mpa, 100.0) + self.assertEqual(summary["units"], {"force": "N", "length": "mm", "stress": "MPa"}) + self.assertEqual(summary["input"]["applied_load_z_n"], -900.0) + self.assertAlmostEqual(result.reaction_force_z_n, 900.0) + self.assertAlmostEqual(result.force_balance_z_n, 0.0) + self.assertAlmostEqual(summary["results"]["force_balance_z_n"], 0.0) + self.assertEqual(summary["input"]["applied_load_z_n"], -900.0) + self.assertEqual(summary["input"]["linear_solver"], "ITERATIVE CHOLESKY") + + def test_mesh_convergence_requires_a_sustained_platform(self): + module = _load_example( + CONVERGENCE_EXAMPLE, + "ap242_mesh_convergence_assessment_example", + ) + + def level(mesh_size, displacement_change, stress_change): + return module.MeshConvergenceLevel( + mesh_size_mm=mesh_size, + node_count=1, + element_count=1, + fixed_node_count=1, + load_node_count=1, + max_displacement_mm=1.0, + max_von_mises_mpa=1.0, + reaction_force_z_n=1.0, + force_balance_z_n=0.0, + displacement_change_from_previous=displacement_change, + stress_change_from_previous=stress_change, + mesh_path="mesh.msh", + input_path="job.inp", + summary_path="job.json", + ) + + transient = module.assess_mesh_convergence( + [ + level(3.0, None, None), + level(2.0, 0.04, 0.09), + level(1.5, 0.08, 0.05), + ] + ) + sustained = module.assess_mesh_convergence( + [ + level(3.0, None, None), + level(2.0, 0.20, 0.20), + level(1.5, 0.04, 0.09), + level(1.0, 0.03, 0.08), + ], + required_platform_pairs=2, + ) + + self.assertFalse(transient["platform_reached"]) + self.assertIsNone(transient["recommended_mesh_size_mm"]) + self.assertTrue(sustained["platform_reached"]) + self.assertEqual(sustained["production_level_n_minus_1"], 3) + self.assertEqual(sustained["verification_level_n"], 4) + self.assertEqual(sustained["recommended_mesh_size_mm"], 1.5) + + def test_mesh_convergence_reports_only_sustained_platform_as_independent(self): + module = _load_example( + CONVERGENCE_EXAMPLE, + "ap242_mesh_convergence_independence_example", + ) + + def level(mesh_size, displacement_change, stress_change): + return module.MeshConvergenceLevel( + mesh_size_mm=mesh_size, + node_count=1, + element_count=1, + fixed_node_count=1, + load_node_count=1, + max_displacement_mm=1.0, + max_von_mises_mpa=1.0, + reaction_force_z_n=1.0, + force_balance_z_n=0.0, + displacement_change_from_previous=displacement_change, + stress_change_from_previous=stress_change, + mesh_path="mesh.msh", + input_path="job.inp", + summary_path="job.json", + ) + + assessment = module.assess_mesh_convergence( + [ + level(0.75, None, None), + level(0.5, 0.03, 0.19), + level(0.375, 0.01, 0.03), + ] + ) + + self.assertFalse(assessment["mesh_independent"]) + self.assertTrue(assessment["finest_pair_displacement_within_tolerance"]) + self.assertTrue(assessment["finest_pair_stress_within_tolerance"]) + self.assertIsNone(assessment["recommended_mesh_size_mm"]) + + def test_calculix_visualizer_converts_frd_to_nonempty_vtu(self): + module = _load_example( + VISUALIZATION_EXAMPLE, + "ap242_calculix_vtu_example", + ) + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + frd = root / "job.frd" + frd.write_text("FRD\n", encoding="ascii") + + class Converter: + def __init__(self, source, formats): + self.source = Path(source) + self.formats = formats + + def run(self): + self.assert_formats = self.formats + self.source.with_suffix(".vtu").write_text("VTU\n", encoding="ascii") + + vtu = module.convert_frd_to_vtu(frd, converter_class=Converter) + + self.assertEqual(vtu.name, "job.vtu") + if __name__ == "__main__": unittest.main() diff --git a/test/test_auto_docs_gen.py b/test/test_auto_docs_gen.py index abbe3703..e3e119d8 100644 --- a/test/test_auto_docs_gen.py +++ b/test/test_auto_docs_gen.py @@ -129,6 +129,7 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): ) self.assertIn("inspect/brep/inspect.py", resolved_names) self.assertIn("inspect/brep/queries.py", resolved_names) + self.assertIn("exporter/mjcf.py", resolved_names) def test_default_source_files_include_cache_build_public_surface(self): with tempfile.TemporaryDirectory() as tmp_dir: @@ -168,6 +169,8 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): "CachePolicy", "CacheReport", "ContentAddressedStore", + "ProductMJCFExportReport", + "export_product_package_to_mjcf", ): self.assertIn(name, names) self.assertNotIn("snapshot_file_inputs", names) diff --git a/test/test_example_model_contract.py b/test/test_example_model_contract.py index 977b0fb6..19330fee 100644 --- a/test/test_example_model_contract.py +++ b/test/test_example_model_contract.py @@ -38,9 +38,6 @@ FORMAL_EXAMPLE_PACKAGES = { "examples/out/external_reference_gear_train/" "nested_external_reference_gear_trains.scadpkg" ), - "examples/12_ap242_gmsh_volume_mesh.py": ( - "examples/out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg" - ), "examples/7ep_caplcd_enclosure.py": ( "examples/out/7ep_caplcd_enclosure/caplcd_enclosure_7ep.scadpkg" ), diff --git a/test/test_product_exporter.py b/test/test_product_exporter.py index fbcde60b..14b588b3 100644 --- a/test/test_product_exporter.py +++ b/test/test_product_exporter.py @@ -1,10 +1,11 @@ -"""End-to-end tests for product-package STEP and STL exporters.""" +"""End-to-end tests for product-package CAD and mesh exporters.""" from __future__ import annotations import json from pathlib import Path import tempfile +import xml.etree.ElementTree as ET import unittest import numpy as np @@ -149,18 +150,42 @@ def _build_nested_package(root: Path): return scad.build_product_package(build_root()) +def _build_cylinder_package(root: Path): + cache = scad.CachePolicy(root=root / "cache") + + @scad.part( + id="cylinder", + cache=cache, + project_root=Path(__file__).parent, + ) + def build_cylinder() -> scad.Part: + body = scad.make_cylinder_rsolid(radius=4.0, height=8.0) + return scad.make_part_rpart("cylinder", body) + + return scad.build_product_package(build_cylinder()) + + class TestProductExporter(unittest.TestCase): def test_exporters_are_available_only_from_exporter_namespace(self): self.assertIs( scad.exporter.export_product_package_to_step, scad.exporter.step.export_product_package_to_step, ) + self.assertIs( + scad.exporter.export_product_package_to_obj, + scad.exporter.obj.export_product_package_to_obj, + ) self.assertIs( scad.exporter.export_product_package_to_stl, scad.exporter.stl.export_product_package_to_stl, ) + self.assertIs( + scad.exporter.export_product_package_to_mjcf, + scad.exporter.mjcf.export_product_package_to_mjcf, + ) self.assertFalse(hasattr(scad, "export_step")) self.assertFalse(hasattr(scad, "export_stl")) + self.assertFalse(hasattr(scad, "export_obj")) self.assertFalse(hasattr(scad.translator, "ap242_translator")) def test_nested_package_preserves_ap242_product_structure_and_placements(self): @@ -289,30 +314,210 @@ class TestProductExporter(unittest.TestCase): {(0.2, 0.4, 0.6)}, ) - def test_nested_package_exports_quad_dominant_stl(self): + def test_nested_package_exports_matching_direct_brep_meshes(self): with tempfile.TemporaryDirectory() as tmp_dir: root = Path(tmp_dir) package = _build_nested_package(root) stl_path = root / "nested.stl" - report = scad.exporter.export_product_package_to_stl( + obj_path = root / "nested.obj" + stl_report = scad.exporter.export_product_package_to_stl( package, stl_path, - mesh_size=0.75, + linear_deflection=0.05, + angular_deflection_degrees=10.0, ) - mesh = trimesh.load_mesh(stl_path, force="mesh", process=False) + obj_report = scad.exporter.export_product_package_to_obj( + package, + obj_path, + linear_deflection=0.05, + angular_deflection_degrees=10.0, + ) + stl_mesh = trimesh.load_mesh(stl_path, force="mesh", process=False) + obj_mesh = trimesh.load_mesh(obj_path, force="mesh", process=False) + stl_processed = trimesh.load_mesh(stl_path, force="mesh", process=True) + obj_lines = obj_path.read_text(encoding="ascii").splitlines() + stl_size = stl_path.stat().st_size - self.assertEqual(report.root_definition_id, "root") - self.assertEqual(report.definition_count, 3) - self.assertEqual(report.solid_count, 3) - self.assertGreater(report.quadrilateral_count, 0) - self.assertGreater(report.quad_fraction, 0.5) - self.assertEqual(len(mesh.faces), report.stl_triangle_count) - self.assertTrue( - np.allclose( - mesh.bounds, - [[-0.5, -1.35415439394285, -0.2077077845361233], [10.5, 6.0, 3.207707784536123]], - ) + source_bounds = np.asarray( + [ + [-0.5, -1.35415439394285, -0.2077077845361233], + [10.5, 6.0, 3.207707784536123], + ] ) + for report in (stl_report, obj_report): + self.assertEqual(report.root_definition_id, "root") + self.assertEqual(report.definition_count, 3) + self.assertEqual(report.solid_count, 3) + self.assertGreater(report.vertex_count, 0) + self.assertGreater(report.triangle_count, 0) + self.assertEqual(report.linear_deflection, 0.05) + self.assertEqual(report.angular_deflection_degrees, 10.0) + self.assertFalse(report.relative) + self.assertEqual( + report.tessellation_backend, + "opencascade-brep-tessellation", + ) + self.assertEqual(stl_report.vertex_count, obj_report.vertex_count) + self.assertEqual(stl_report.triangle_count, obj_report.triangle_count) + self.assertEqual(len(stl_mesh.faces), stl_report.triangle_count) + self.assertEqual(len(obj_mesh.faces), obj_report.triangle_count) + self.assertEqual( + sum(line.startswith("f ") for line in obj_lines), + obj_report.triangle_count, + ) + self.assertTrue( + all(len(line.split()) == 4 for line in obj_lines if line.startswith("f ")) + ) + self.assertTrue(np.allclose(stl_mesh.bounds, source_bounds, atol=1.0e-6)) + self.assertTrue(np.allclose(obj_mesh.bounds, source_bounds, atol=1.0e-6)) + self.assertTrue(stl_processed.is_watertight) + self.assertTrue(obj_mesh.is_watertight) + self.assertTrue(stl_processed.is_winding_consistent) + self.assertTrue(obj_mesh.is_winding_consistent) + self.assertEqual(stl_size, 84 + 50 * stl_report.triangle_count) + + def test_smaller_deflection_refines_curved_brep(self): + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + package = _build_cylinder_package(root) + coarse_path = root / "cylinder-coarse.obj" + fine_path = root / "cylinder-fine.obj" + coarse = scad.exporter.export_product_package_to_obj( + package, + coarse_path, + linear_deflection=0.5, + angular_deflection_degrees=30.0, + ) + fine = scad.exporter.export_product_package_to_obj( + package, + fine_path, + linear_deflection=0.01, + angular_deflection_degrees=5.0, + ) + mesh = trimesh.load_mesh(fine_path, force="mesh", process=False) + + self.assertEqual(coarse.solid_count, 1) + self.assertEqual(fine.solid_count, 1) + self.assertGreater(fine.vertex_count, coarse.vertex_count) + self.assertGreater(fine.triangle_count, coarse.triangle_count) + self.assertEqual(len(mesh.faces), fine.triangle_count) + self.assertTrue(mesh.is_watertight) + self.assertTrue(mesh.is_winding_consistent) + exact_bounds = np.asarray([[-4.0, -4.0, 0.0], [4.0, 4.0, 8.0]]) + self.assertTrue(np.all(mesh.bounds[0] >= exact_bounds[0] - 1.0e-9)) + self.assertTrue(np.all(mesh.bounds[1] <= exact_bounds[1] + 1.0e-9)) + self.assertLessEqual(float(np.max(np.abs(mesh.bounds - exact_bounds))), 0.01) + + def test_mjcf_exporter_builds_named_body_joint_site_and_mapping(self): + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + cache = scad.CachePolicy(root=root / "cache") + material = scad.make_material_rmaterial( + "test_aluminum", + density=2.7e-6, + density_unit="kg/mm^3", + ) + + def make_link(part_id: str) -> scad.Part: + body = scad.make_cylinder_rsolid(radius=2.0, height=4.0) + part = scad.make_part_rpart(part_id, body) + part = scad.assign_material_rpart(part, material) + return scad.add_connector_rpart( + part, + scad.make_placement_connector_rconnector( + "axis", + scad.identity_placement_rplacement(), + ), + ) + + @scad.part(id="mjcf_base", cache=cache, project_root=Path(__file__).parent) + def build_base() -> scad.Part: + return make_link("mjcf_base") + + @scad.part(id="mjcf_rotor", cache=cache, project_root=Path(__file__).parent) + def build_rotor() -> scad.Part: + return make_link("mjcf_rotor") + + base = build_base() + rotor = build_rotor() + + @scad.assemble( + id="mjcf_fixture", + definitions=(base, rotor), + cache=cache, + project_root=Path(__file__).parent, + ) + def build_fixture() -> scad.Assembly: + assembly = scad.make_assembly_rassembly("mjcf_fixture") + assembly = scad.add_component_rassembly( + assembly, + base.part, + component_id="base", + placement=scad.identity_placement_rplacement(), + ) + assembly = scad.add_component_rassembly( + assembly, + rotor.part, + component_id="rotor", + placement=scad.identity_placement_rplacement(), + ) + assembly = scad.ground_component_rassembly(assembly, "base") + assembly = scad.add_revolute_constraint_rassembly( + assembly, + "rotor_axis", + scad.make_connector_ref_rconnectorref("base", "axis"), + scad.make_connector_ref_rconnectorref("rotor", "axis"), + ) + return scad.forward_connector_rassembly( + assembly, + "tool_axis", + "rotor", + "axis", + ) + + package = scad.build_product_package(build_fixture()) + xml_path = root / "fixture.xml" + report = scad.exporter.export_product_package_to_mjcf( + package, + xml_path, + linear_deflection=0.1, + ) + xml_root = ET.parse(xml_path).getroot() + mapping = json.loads(report.mapping_path.read_text(encoding="utf-8")) + + self.assertEqual(report.body_count, 1) + self.assertEqual(report.joint_count, 1) + self.assertEqual(report.equality_count, 0) + self.assertEqual(report.site_count, 1) + self.assertIsNotNone(xml_root.find('.//body[@name="body_rotor"]')) + self.assertIsNotNone(xml_root.find('.//geom[@name="base"]')) + self.assertIsNotNone(xml_root.find('.//geom[@name="rotor"]')) + self.assertIsNotNone(xml_root.find('.//site[@name="tool_axis"]')) + self.assertEqual(len(mapping["tree_joints"]), 1) + self.assertEqual(mapping["sites"][0]["connector_id"], "tool_axis") + + def test_mesh_exporters_reject_invalid_tessellation_parameters(self): + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + package = _build_cylinder_package(root) + with self.assertRaisesRegex(ValueError, "linear_deflection"): + scad.exporter.export_product_package_to_stl( + package, + root / "invalid.stl", + linear_deflection=0.0, + ) + with self.assertRaisesRegex(ValueError, "angular_deflection_degrees"): + scad.exporter.export_product_package_to_obj( + package, + root / "invalid.obj", + angular_deflection_degrees=181.0, + ) + with self.assertRaisesRegex(TypeError, "relative"): + scad.exporter.export_product_package_to_obj( + package, + root / "invalid-relative.obj", + relative=1, + ) if __name__ == "__main__": diff --git a/test/test_rearchitecture_2_0_contract.py b/test/test_rearchitecture_2_0_contract.py index dae59155..a9a2c0c0 100644 --- a/test/test_rearchitecture_2_0_contract.py +++ b/test/test_rearchitecture_2_0_contract.py @@ -260,10 +260,12 @@ class TestRearchitecture20IoContracts(unittest.TestCase): self.assertGreaterEqual(payload["graph"].node_count, 1) self.assertGreaterEqual(payload["expression_graph"].node_count, 1) - def test_step_and_stl_exports_require_product_package_boundary(self): + def test_product_exports_require_exporter_namespace(self): self.assertFalse(hasattr(scad, "export_step")) self.assertFalse(hasattr(scad, "export_stl")) + self.assertFalse(hasattr(scad, "export_obj")) self.assertTrue(hasattr(scad.exporter, "export_product_package_to_step")) + self.assertTrue(hasattr(scad.exporter, "export_product_package_to_obj")) self.assertTrue(hasattr(scad.exporter, "export_product_package_to_stl")) def test_model_json_export_exists_as_canonical_seed(self): diff --git a/tools/run_examples.py b/tools/run_examples.py index 87f956cc..4971d080 100644 --- a/tools/run_examples.py +++ b/tools/run_examples.py @@ -70,11 +70,6 @@ CASES = ( "examples/out/external_reference_gear_train/" "nested_external_reference_gear_trains.scadpkg", ), - ExampleCase( - "examples/12_ap242_gmsh_volume_mesh.py", - "examples/out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg", - args=("--skip-mesh",), - ), ExampleCase( "examples/7ep_caplcd_enclosure.py", "examples/out/7ep_caplcd_enclosure/caplcd_enclosure_7ep.scadpkg", diff --git a/uv.lock b/uv.lock index f364e95a..5a5fa572 100644 --- a/uv.lock +++ b/uv.lock @@ -250,6 +250,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a6/84/566162a2fe2c6f5519bf6c9f8ca9535173cee42cc6d547d02c27b28c3402/cadquery_ocp_proxy-7.9.3.1-py3-none-any.whl", hash = "sha256:8259b53668784b682fe2e4a6c1fed8293886d52bf6c3b2ecc2aec986c49e92d7", size = 3263, upload-time = "2026-02-15T13:37:58.515Z" }, ] +[[package]] +name = "ccx2paraview" +version = "3.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/68/80/2d3f15215a6ef3029bc4a5a58365cd6979a8d9dd2ca7b97e7ef929381522/ccx2paraview-3.2.0.tar.gz", hash = "sha256:c9f0c8d0fadd7de9a30be1b38ff53ecede49a87659e32b67ba32230d9dafd600", size = 36243, upload-time = "2024-12-19T21:17:20.762Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/da/46b9c79188084d4c650144ce8341b78ecfe3a790bcdd585de9a3a5ae9798/ccx2paraview-3.2.0-py3-none-any.whl", hash = "sha256:814520a138c4ac345809b16f6242b43e2f16bb926215bec069398a0672e887a9", size = 29352, upload-time = "2024-12-19T21:17:18.532Z" }, +] + +[package.optional-dependencies] +vtk = [ + { name = "vtk" }, +] + [[package]] name = "certifi" version = "2025.6.15" @@ -2963,6 +2981,10 @@ dev = [ { name = "pytest" }, { name = "pytest-cov" }, ] +fem = [ + { name = "ccx2paraview", extra = ["vtk"] }, + { name = "gmsh" }, +] gmsh = [ { name = "gmsh" }, ] @@ -2986,6 +3008,8 @@ dev = [ requires-dist = [ { name = "black", marker = "extra == 'dev'", specifier = ">=23.0" }, { name = "cadquery-ocp", specifier = ">=7.9.3.1" }, + { name = "ccx2paraview", extras = ["vtk"], marker = "extra == 'fem'", specifier = ">=3.2,<4" }, + { name = "gmsh", marker = "extra == 'fem'", specifier = ">=4.15,<5" }, { name = "gmsh", marker = "extra == 'gmsh'", specifier = ">=4.15,<5" }, { name = "isort", marker = "extra == 'dev'", specifier = ">=5.0" }, { name = "jsonschema", specifier = ">=4.25.1,<5.0.0" }, @@ -3002,7 +3026,7 @@ requires-dist = [ { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0,<3" }, { name = "typing-extensions", specifier = ">=4.12,<5" }, ] -provides-extras = ["dev", "editor", "collision", "inspect", "gmsh"] +provides-extras = ["dev", "editor", "collision", "inspect", "gmsh", "fem"] [package.metadata.requires-dev] dev = [