Skip to content

Commit 3d48324

Browse files
committed
Initial commit with hopefully working tests
1 parent a39375c commit 3d48324

File tree

10 files changed

+632
-1
lines changed

10 files changed

+632
-1
lines changed

.gitignore

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# UV
98+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99+
# This is especially recommended for binary packages to ensure reproducibility, and is more
100+
# commonly ignored for libraries.
101+
#uv.lock
102+
103+
# poetry
104+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105+
# This is especially recommended for binary packages to ensure reproducibility, and is more
106+
# commonly ignored for libraries.
107+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108+
#poetry.lock
109+
110+
# pdm
111+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112+
#pdm.lock
113+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114+
# in version control.
115+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116+
.pdm.toml
117+
.pdm-python
118+
.pdm-build/
119+
120+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121+
__pypackages__/
122+
123+
# Celery stuff
124+
celerybeat-schedule
125+
celerybeat.pid
126+
127+
# SageMath parsed files
128+
*.sage.py
129+
130+
# Environments
131+
.env
132+
.venv
133+
env/
134+
venv/
135+
ENV/
136+
env.bak/
137+
venv.bak/
138+
139+
# Spyder project settings
140+
.spyderproject
141+
.spyproject
142+
143+
# Rope project settings
144+
.ropeproject
145+
146+
# mkdocs documentation
147+
/site
148+
149+
# mypy
150+
.mypy_cache/
151+
.dmypy.json
152+
dmypy.json
153+
154+
# Pyre type checker
155+
.pyre/
156+
157+
# pytype static type analyzer
158+
.pytype/
159+
160+
# Cython debug symbols
161+
cython_debug/
162+
163+
# PyCharm
164+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166+
# and can be added to the global gitignore or merged into this file. For a more nuclear
167+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
168+
#.idea/
169+
170+
# PyPI configuration file
171+
.pypirc
172+
173+
# Project-specific exclusions
174+
*.msh
175+
old_code.py

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@
186186
same "printed page" as the copyright notice for easier
187187
identification within third-party archives.
188188

189-
Copyright [yyyy] [name of copyright owner]
189+
Copyright 2025 CadQuery Developers
190190

191191
Licensed under the Apache License, Version 2.0 (the "License");
192192
you may not use this file except in compliance with the License.

README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# cadquery-assembly-mesh-plugin
2+
3+
CadQuery plugin to create a mesh of an assembly with corresponding data.
4+
5+
This plugin makes use of CadQuery tags to collect surfaces into Gmsh physical groups. The
6+
tagged faces are matched to their corresponding surfaces in the mesh via their position in the CadQuery solid(s) vs the Gmsh surface ID. There are a few challenges with mapping tags to surfaces to be aware of.
7+
8+
1. Each tag can select multiple faces/surfaces at once, and this has to be accounted for when mapping tags to surfaces.
9+
2. Tags are present at the higher level of the Workplane class, but are do not propagate to lower-level classes like Face.
10+
3. OpenCASCADE does not provide a built-in mechanism for tagging low-level entities without the use of an external data structure or framework.
11+
12+
## Installation
13+
14+
You can do `pip install -e .` locally in the root of this repo to enable development. Alternatively, you can install via `pip install git+git@github.com:cadquery/cadquery-assembly-mesh-plugin.git` if you have access to the repo on Github.
15+
16+
## Usage
17+
18+
**PLEASE NOTE:** This plugin currently needs to be run in an Anaconda/Mamba environment because of a crash with the PyPI packages when passing OpenCASCADE objects to Gmesh in memory.
19+
20+
The plugin needs to be imported in order to monkey-patch its method into CadQuery:
21+
22+
```python
23+
import cadquery_assembly_mesh_plugin.plugin
24+
```
25+
26+
You can then tag faces in each of the assembly parts and create your asembly. To export the assembly to a mesh file, you do the following.
27+
28+
```python
29+
your_assembly.assemblyToGmsh(mesh_path="tagged_planar_coil.msh")
30+
```
31+
32+
Normal tag names lead to a physical group with the assembly part name prefixed. So a tag name of `inner-bottom` on an assembly part with the name `steel_plate` will be `steel_plate_inner-bottom`
33+
34+
By prefixing a tag with the `~` character, the part name is ignored, which allows for tagging of a multi-material
35+
physical group. For instance, tagging multiple faces with `~contact-with-casing` will produce a physical group with the name `contact-with-casing` that includes all those faces, even if they belong to different parts/solids.
36+
37+
## Tests
38+
39+
These tests are also run in Github Actions, and the meshes which are generated can be viewed as artifacts on the successful `tests` Actions there.
40+
41+
* [sample_coils.py](tests/sample_coils.py) contains generators for sample assemlies for use in testing the basic operation of this plugin. This file also contains the code to tag all faces of interest.
42+
* [smoke_test.py](tests/smoke_test.py) runs two tests currently. The first is for a simple cross-section of a coil (image below), which makes it easier to verify basic operation. The second is for a planar coil, which forces the use of more advanced selectors, but is not as complex as a coil with a non-planar sweep path. This planar-coil test is not complete yet.
43+
44+
![Coil Cross-Section Assembly](docs/images/logo.png)
45+
46+
Once the test has been run (using the pytest command), two mesh files (.msh extension) be created in the root of the repository.
47+
48+
* tagged_cross_section.msh
49+
* tagged_planar_coil.msh
50+
51+
These mesh files will have many physical groups since each surface gets its own physical group, but it should also contain physical groups corresponding to the tags that were created for the faces in the assembly parts.

assembly_mesh_plugin/__init__.py

Whitespace-only changes.

assembly_mesh_plugin/plugin.py

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
from OCP.TopoDS import TopoDS_Shape
2+
import cadquery as cq
3+
import gmsh
4+
5+
6+
def assembly_to_gmsh(self, mesh_path="tagged_mesh.msh"):
7+
"""
8+
Pack the assembly into a gmsh object, respecting assembly part names and face tags when creating
9+
the physical groups.
10+
"""
11+
12+
gmsh.initialize()
13+
gmsh.option.setNumber("General.Terminal", 0)
14+
gmsh.model.add("coil_assembly")
15+
16+
# The mesh volume and surface ids should line up with the order of solids and faces in the assembly
17+
vol_id = 1
18+
surface_id = 1
19+
20+
# Tracks multi-surface physical groups
21+
multi_material_groups = {}
22+
surface_groups = {}
23+
24+
# Holds the collection of individual faces that are tagged
25+
tagged_faces = {}
26+
27+
for obj, name, loc, _ in self:
28+
# CadQuery assembly code prepends a UUID to names sometimes that we do not need
29+
short_name = name.split("/")[-1]
30+
31+
# Separate tagged faces by solid since they might be duplicates
32+
tagged_faces[short_name] = {}
33+
34+
# Extract the tagged faces and make sure they are in the appropriate relative locations
35+
# in the assembly. Tags can hold multiple faces, so we have to extract all of them.
36+
for tag, wp in self.objects[short_name].obj.ctx.tags.items():
37+
for face in wp.faces().all():
38+
# Check to see if we have found this tag before (multi-material tag)
39+
if tag in tagged_faces[short_name]:
40+
tagged_faces[short_name][tag].append(face.val())
41+
else:
42+
tagged_faces[short_name][tag] = [face.val()]
43+
44+
# All the solids in the current part should be added to the mesh
45+
for s in obj.moved(loc).Solids():
46+
# Add the current solid to the mesh
47+
gmsh.model.occ.importShapesNativePointer(s.wrapped._address())
48+
gmsh.model.occ.synchronize()
49+
50+
# All the faces in the current part should be added to the mesh
51+
for face in s.Faces():
52+
# Face name can be based on a tag, or just be a generic name
53+
found_tag = False
54+
55+
#
56+
# Handle tagged faces
57+
# Step through the faces in the solid and check them against all the tagged faces
58+
#
59+
for tag, tag_faces in tagged_faces[short_name].items():
60+
for tag_face in tag_faces:
61+
# Move the face to the correct location in the assembly
62+
tag_face = tag_face.moved(loc)
63+
64+
# If OpenCASCADE says the faces are the same, we have a match for the tag
65+
if TopoDS_Shape.IsEqual(face.wrapped, tag_face.wrapped):
66+
# Make sure a generic surface is not added for this face
67+
found_tag = True
68+
69+
# Find out if this is a multi-material tag
70+
if tag.startswith("~"):
71+
# Set the surface name to be the name of the tag without the ~
72+
group_name = tag.replace("~", "").split("-")[0]
73+
74+
# Add this face to the multi-material group
75+
if group_name in multi_material_groups:
76+
multi_material_groups[group_name].append(surface_id)
77+
else:
78+
multi_material_groups[group_name] = [surface_id]
79+
else:
80+
# We want to track all surfaces that might be in a tag group
81+
cur_tag_name = f"{short_name}_{tag}"
82+
if cur_tag_name in surface_groups:
83+
print(
84+
"Append: ", cur_tag_name, short_name, surface_id
85+
)
86+
surface_groups[cur_tag_name].append(surface_id)
87+
else:
88+
print("New: ", cur_tag_name, short_name, surface_id)
89+
surface_groups[cur_tag_name] = [surface_id]
90+
91+
# If no tag was found, set a physical group generic name
92+
if not found_tag:
93+
face_name = f"{short_name}_surface_{surface_id}"
94+
ps = gmsh.model.addPhysicalGroup(2, [surface_id])
95+
gmsh.model.setPhysicalName(2, ps, f"{face_name}")
96+
97+
# Move to the next surface id
98+
surface_id += 1
99+
100+
# Move to the next volume id
101+
vol_id += 1
102+
103+
# Handle tagged surface groups
104+
for t_name, surf_group in surface_groups.items():
105+
ps = gmsh.model.addPhysicalGroup(2, surf_group)
106+
gmsh.model.setPhysicalName(2, ps, t_name)
107+
108+
# Handle multi-material tags
109+
for group_name, mm_group in multi_material_groups.items():
110+
ps = gmsh.model.addPhysicalGroup(2, mm_group)
111+
gmsh.model.setPhysicalName(2, ps, f"{group_name}")
112+
113+
gmsh.model.occ.synchronize()
114+
115+
gmsh.model.mesh.field.setAsBackgroundMesh(2)
116+
117+
gmsh.model.mesh.generate(3)
118+
gmsh.write(mesh_path)
119+
120+
gmsh.finalize()
121+
122+
123+
# Patch the new assembly functions into CadQuery's importers package
124+
cq.Assembly.assemblyToGmsh = assembly_to_gmsh

0 commit comments

Comments
 (0)