Skip to content

Add assy imprint method - #2128

Merged
adam-urbanczyk merged 30 commits into
masterfrom
adam-assy-imprint-method
Nov 27, 2026
Merged

adam-urbanczyk merged 30 commits into
masterfrom
adam-assy-imprint-method

Conversation

@adam-urbanczyk

@adam-urbanczyk adam-urbanczyk commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Fixes #2075

  • cq.Assembly.imprint() method with subshape handling
  • tests
  • docs
  • check bool op for errors (this includes imprint)

I added (as it turns out without need) undoMove and undoMoved to Shape. Additionally reworked slightly how op history is handling default values. Nice to see that this feature can be used to develop new CQ features.

NB: this PR changes how __iter__ behaves. They keys can match now convetions used by __getitem__ and .objects.

@adam-urbanczyk
adam-urbanczyk marked this pull request as draft November 6, 2026 17:46
@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.94595% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.23%. Comparing base (082b8de) to head (3882162).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
cadquery/occ_impl/shapes.py 92.30% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2128      +/-   ##
==========================================
+ Coverage   95.85%   96.23%   +0.38%     
==========================================
  Files          30       30              
  Lines        9651    11455    +1804     
  Branches     1460     1930     +470     
==========================================
+ Hits         9251    11024    +1773     
- Misses        246      277      +31     
  Partials      154      154              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

shimwell added a commit to fusion-energy/paramak that referenced this pull request Nov 6, 2026
paramak's remove() matched parts with endswith('/<name>') on the names
yielded by iterating the assembly. CadQuery/cadquery#2128 changes those
names so direct children of the root no longer carry the root prefix,
which would make remove() silently return the full assembly.

cadquery has had Assembly.remove since 2.6.0 (paramak's floor). It
removes the part in place by its key, keeps nested structure and raises
ValueError for an unknown name. Drop the override and test cadquery's
method on plain assemblies, nested sub-assemblies and a full reactor.
@shimwell

shimwell commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

this looks useful for a few workflows in cad-to-dagmc where i have functions that take assemblies and imprint them.

It might be useful to allow the assembly to know if it has been imprinted or know so that if imprinted assemblies are passed around the receiver does not accidentally imprint them again

I was looking into how this improves my upstream codes and got a few keyerrors that might be worth considering

@shimwell

shimwell commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

KeyError when a part (or a named sub-shape) is not changed by the imprint

import cadquery as cq

a = cq.Assembly()
a.add(cq.Workplane().box(10, 10, 10).val(), name="p0")
a.add(cq.Workplane().transformed(offset=(50, 0, 0)).box(10, 10, 10).val(), name="p1")
a.imprint()  # KeyError

@shimwell

shimwell commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Parts with a loc are moved twice and lose their shared faces

a = cq.Assembly()
a.add(cq.Workplane().box(10, 10, 10).val(), name="a")
a.add(cq.Workplane().box(10, 10, 10).val(), name="b", loc=cq.Location((10, 0, 0)))
a.imprint()
# "b" now spans x 15..25 (should be 5..15), and the compound has 12 faces instead of 11

@adam-urbanczyk

Copy link
Copy Markdown
Member Author

Thanks @shimwell , this is still a draft. I would not yet recommend testing.

@shimwell

shimwell commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the update. I tested 44d4900a with cad_to_dagmc (fusion-energy/cad_to_dagmc#247, which switches our imprinting over to Assembly.imprint). it got further than first time i tried

One case still fails

a Workplane or Compound part that the imprint leaves untouched still raises KeyError.

import cadquery as cq

a = cq.Assembly()
a.add(cq.Workplane().box(10, 10, 10), name="a")
a.add(cq.Workplane().box(10, 10, 10).translate((50, 0, 0)), name="b")
a.imprint()  # KeyError

The same thing happens with cq.Compound.makeCompound([box]) parts. The same two parts as Solids imprint fine.

I did a local fix in which appears to help

val = d[el] if default is None else d.get(el, el)

shimwell added a commit to fusion-energy/cad_to_dagmc that referenced this pull request Nov 20, 2026
Brings in main up to #255. The conflicts were the tag length check that
main added beside the material tag count check, which now counts parts
since the remapping helpers are gone, and main's rewrite of the imprinting
docs.

The overlaps docs said the Gmsh backend writes overlapping solids without
an error. Its imprint now refuses the same overlaps as the mesher's, as
each one splits a part into several solids.

CadQuery 2.8.0, the current release, has no Assembly.imprint, so
imprint_assembly falls back to the functional imprint when it is missing.
The fallback puts the imprinted solids back in part order and raises the
same overlapping solids error, so the gmsh paths behave the same either
way. On the legacy imprint, "full" and None glue raise RuntimeError again,
as they did before this branch. The requirement goes back to
cadquery>=2.8.0, CI tests stable, master and the CadQuery/cadquery#2128
branch, and the imprint_assembly tests run against both implementations.
TODOs mark the fallback for removal once a CadQuery release includes
Assembly.imprint.
@shimwell

Copy link
Copy Markdown
Contributor

This now works for my use cases. Many thanks

@jmwright jmwright left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @adam-urbanczyk there are just a few comments.

Comment thread cadquery/assembly.py Resolved
Comment thread cadquery/assembly.py Resolved
Comment thread doc/assy.rst Resolved
Comment thread cadquery/assembly.py Resolved

@lorenzncode lorenzncode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from cadquery import Assembly, Location
from cadquery.func import box

box_bottom = box(2, 2, 1)
box_top = box(1, 1, 1)

assy = Assembly()
assy.add(box_bottom, name="box_bottom")
assy.add(box_top, name="box_top", loc=Location(z=1))

assy["box_bottom"].addSubshape(box_bottom.face(">Z"), name="face_at_z1")
assy.imprint()
assy.export("split_face.step")  # AssertionError: Invalid subshape

Here STEP export fails after imprint splits a named face.

@lorenzncode lorenzncode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from cadquery import Assembly, Location
from cadquery.func import box, compound

box_bottom = box(1, 1, 1)
box_top = box(1, 1, 1)

assy = Assembly()
assy.add(compound(compound(box_bottom)), name="box_bottom")
assy.add(box_top, name="box_top", loc=Location(z=1))
assy.imprint()

# The boxes touch at z=1, so should count as one unique face.
result = assy.toCompound()
assert len(result.Solids()) == 2
face_count = len(result.Faces())
assert face_count == 11, f"Expected 11 unique faces, got {face_count}"

The resulting number of faces is unexpected with a nested compound.

@adam-urbanczyk

Copy link
Copy Markdown
Member Author

Good stuff @lorenzncode , thanks! I reworked somewhat how history handles compounds (and added the Shape.unpack(recursive: bool = True) -> list[Shape] method). Looks like it is fixed now.

Comment thread cadquery/occ_impl/shapes.py Resolved

@lorenzncode lorenzncode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find the root name is dropped from the path when iterating over the assembly.

from cadquery import Assembly
from cadquery.func import * 

assy1 = Assembly(name="assy1")
assy1.add(sphere(1), name="part1")

assy2 = Assembly(name="assy2")
assy2.add(sphere(2), name="part1")

# example: name collision when creating a dict of parts
parts = {}
for assy in (assy1, assy2):
    for shape, name, loc, color in assy:
        parts[name] = shape

print(list(parts)) # ['part1']  on master: ['assy1/part1', 'assy2/part1']
assert len(parts) == 2

@adam-urbanczyk

adam-urbanczyk commented Nov 27, 2026 •

Copy link
Copy Markdown
Member Author

That is correct. Names returned by __iter__ match __getitem__ and .objects keys now. AFAICT __iter__ was introduced when implementing occ_impl.assembly.imprint and so the names returned by this function can also be now used directly to backreference the original assembly leafs via __getitem__. It might of course impact some downstream code. @shimwell do you have any strong feelings about this detail? Likely you are the main user of occ_impl.assembly.imprint.

Comment thread cadquery/assembly.py Resolved
Co-authored-by: Jonathan Shimwell <mail@jshimwell.com>
@shimwell

Copy link
Copy Markdown
Contributor

I have just been testing this branch today so perfect timing

don't worry about me and cad-to-dagmc, we can adapt to whatever is best for cadquery.

I had a look anyway and it doesn't actually affect us. We only use these names to match parts up with the origins that get reutrned from occ_impl.assembly.imprint, and both of those come from the same iterator. so losing the root name on both sides is fine.

I ran the cad-to-dagmc tests pass against this branch and they all passed ✔️

Being able to pass the names straight into assembly[name] is nice.

Would AssemblyProtocol.iter need the new depth arg too?

Seems like an additional default arg on the implementation side does not break the contract, but still adding it for completeness.
@adam-urbanczyk

Copy link
Copy Markdown
Member Author

Good point regarding AssemblyProtocol.__iter__, updated.

Comment thread doc/assy.rst Resolved
Co-authored-by: Jonathan Shimwell <mail@jshimwell.com>

@lorenzncode lorenzncode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Last one. Please check - is this usage unexpected? imprint can fail in the following case:

from cadquery import Assembly, Location
from cadquery.func import box

box_bottom = box(1, 1, 1)
box_top = box(1, 1, 1)

assy = Assembly(name="assy")
assy.add(box_bottom, name="box_bottom")
assy_box_top = Assembly(name="assy_box_top").add(
    box_top, name="box_top", loc=Location(z=1)
)
assy.add(assy_box_top)
outer = Assembly().add(assy)

outer["assy"].imprint()  # KeyError: 'assy_box_top/box_top'
# outer.imprint()  # no error 

@adam-urbanczyk

Copy link
Copy Markdown
Member Author

Thanks, this definitely should work.

@adam-urbanczyk

Copy link
Copy Markdown
Member Author

@lorenzncode very good catch! It was a bug in _copy() that resulted in wrong keys in the .objects field of the subassy. looks like it is solved (tm).

@lorenzncode lorenzncode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @adam-urbanczyk !

@adam-urbanczyk
adam-urbanczyk merged commit d10fbbb into master Nov 27, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement cq.Assembly.imprint

4 participants