Skip to content

Commit

Permalink
Initial commit with hopefully working tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jmwright committed Jan 28, 2025
1 parent a39375c commit 3d48324
Show file tree
Hide file tree
Showing 10 changed files with 632 additions and 1 deletion.
175 changes: 175 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# PyPI configuration file
.pypirc

# Project-specific exclusions
*.msh
old_code.py
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]
Copyright 2025 CadQuery Developers

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# cadquery-assembly-mesh-plugin

CadQuery plugin to create a mesh of an assembly with corresponding data.

This plugin makes use of CadQuery tags to collect surfaces into Gmsh physical groups. The
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.

1. Each tag can select multiple faces/surfaces at once, and this has to be accounted for when mapping tags to surfaces.
2. Tags are present at the higher level of the Workplane class, but are do not propagate to lower-level classes like Face.
3. OpenCASCADE does not provide a built-in mechanism for tagging low-level entities without the use of an external data structure or framework.

## Installation

You can do `pip install -e .` locally in the root of this repo to enable development. Alternatively, you can install via `pip install [email protected]:cadquery/cadquery-assembly-mesh-plugin.git` if you have access to the repo on Github.

## Usage

**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.

The plugin needs to be imported in order to monkey-patch its method into CadQuery:

```python
import cadquery_assembly_mesh_plugin.plugin
```

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.

```python
your_assembly.assemblyToGmsh(mesh_path="tagged_planar_coil.msh")
```

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`

By prefixing a tag with the `~` character, the part name is ignored, which allows for tagging of a multi-material
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.

## Tests

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.

* [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.
* [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.

![Coil Cross-Section Assembly](docs/images/logo.png)

Once the test has been run (using the pytest command), two mesh files (.msh extension) be created in the root of the repository.

* tagged_cross_section.msh
* tagged_planar_coil.msh

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.
Empty file.
124 changes: 124 additions & 0 deletions assembly_mesh_plugin/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from OCP.TopoDS import TopoDS_Shape
import cadquery as cq
import gmsh


def assembly_to_gmsh(self, mesh_path="tagged_mesh.msh"):
"""
Pack the assembly into a gmsh object, respecting assembly part names and face tags when creating
the physical groups.
"""

gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 0)
gmsh.model.add("coil_assembly")

# The mesh volume and surface ids should line up with the order of solids and faces in the assembly
vol_id = 1
surface_id = 1

# Tracks multi-surface physical groups
multi_material_groups = {}
surface_groups = {}

# Holds the collection of individual faces that are tagged
tagged_faces = {}

for obj, name, loc, _ in self:
# CadQuery assembly code prepends a UUID to names sometimes that we do not need
short_name = name.split("/")[-1]

# Separate tagged faces by solid since they might be duplicates
tagged_faces[short_name] = {}

# Extract the tagged faces and make sure they are in the appropriate relative locations
# in the assembly. Tags can hold multiple faces, so we have to extract all of them.
for tag, wp in self.objects[short_name].obj.ctx.tags.items():
for face in wp.faces().all():
# Check to see if we have found this tag before (multi-material tag)
if tag in tagged_faces[short_name]:
tagged_faces[short_name][tag].append(face.val())
else:
tagged_faces[short_name][tag] = [face.val()]

# All the solids in the current part should be added to the mesh
for s in obj.moved(loc).Solids():
# Add the current solid to the mesh
gmsh.model.occ.importShapesNativePointer(s.wrapped._address())
gmsh.model.occ.synchronize()

# All the faces in the current part should be added to the mesh
for face in s.Faces():
# Face name can be based on a tag, or just be a generic name
found_tag = False

#
# Handle tagged faces
# Step through the faces in the solid and check them against all the tagged faces
#
for tag, tag_faces in tagged_faces[short_name].items():
for tag_face in tag_faces:
# Move the face to the correct location in the assembly
tag_face = tag_face.moved(loc)

# If OpenCASCADE says the faces are the same, we have a match for the tag
if TopoDS_Shape.IsEqual(face.wrapped, tag_face.wrapped):
# Make sure a generic surface is not added for this face
found_tag = True

# Find out if this is a multi-material tag
if tag.startswith("~"):
# Set the surface name to be the name of the tag without the ~
group_name = tag.replace("~", "").split("-")[0]

# Add this face to the multi-material group
if group_name in multi_material_groups:
multi_material_groups[group_name].append(surface_id)
else:
multi_material_groups[group_name] = [surface_id]
else:
# We want to track all surfaces that might be in a tag group
cur_tag_name = f"{short_name}_{tag}"
if cur_tag_name in surface_groups:
print(
"Append: ", cur_tag_name, short_name, surface_id
)
surface_groups[cur_tag_name].append(surface_id)
else:
print("New: ", cur_tag_name, short_name, surface_id)
surface_groups[cur_tag_name] = [surface_id]

# If no tag was found, set a physical group generic name
if not found_tag:
face_name = f"{short_name}_surface_{surface_id}"
ps = gmsh.model.addPhysicalGroup(2, [surface_id])
gmsh.model.setPhysicalName(2, ps, f"{face_name}")

# Move to the next surface id
surface_id += 1

# Move to the next volume id
vol_id += 1

# Handle tagged surface groups
for t_name, surf_group in surface_groups.items():
ps = gmsh.model.addPhysicalGroup(2, surf_group)
gmsh.model.setPhysicalName(2, ps, t_name)

# Handle multi-material tags
for group_name, mm_group in multi_material_groups.items():
ps = gmsh.model.addPhysicalGroup(2, mm_group)
gmsh.model.setPhysicalName(2, ps, f"{group_name}")

gmsh.model.occ.synchronize()

gmsh.model.mesh.field.setAsBackgroundMesh(2)

gmsh.model.mesh.generate(3)
gmsh.write(mesh_path)

gmsh.finalize()


# Patch the new assembly functions into CadQuery's importers package
cq.Assembly.assemblyToGmsh = assembly_to_gmsh
Loading

0 comments on commit 3d48324

Please sign in to comment.