cad-to-dagmc 0.9.2__py3-none-any.whl → 0.9.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
_version.py CHANGED
@@ -1,7 +1,14 @@
1
1
  # file generated by setuptools-scm
2
2
  # don't change, don't track in version control
3
3
 
4
- __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
5
12
 
6
13
  TYPE_CHECKING = False
7
14
  if TYPE_CHECKING:
@@ -9,13 +16,19 @@ if TYPE_CHECKING:
9
16
  from typing import Union
10
17
 
11
18
  VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
12
20
  else:
13
21
  VERSION_TUPLE = object
22
+ COMMIT_ID = object
14
23
 
15
24
  version: str
16
25
  __version__: str
17
26
  __version_tuple__: VERSION_TUPLE
18
27
  version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
19
30
 
20
- __version__ = version = '0.9.2'
21
- __version_tuple__ = version_tuple = (0, 9, 2)
31
+ __version__ = version = '0.9.4'
32
+ __version_tuple__ = version_tuple = (0, 9, 4)
33
+
34
+ __commit_id__ = commit_id = None
cad_to_dagmc/__init__.py CHANGED
@@ -13,4 +13,5 @@ except PackageNotFoundError:
13
13
 
14
14
  __all__ = ["__version__"]
15
15
 
16
+ from .direct_mesh_plugin import *
16
17
  from .core import *
cad_to_dagmc/core.py CHANGED
@@ -9,6 +9,7 @@ import tempfile
9
9
  import warnings
10
10
  from typing import Iterable
11
11
  from cad_to_dagmc import __version__
12
+ from .direct_mesh_plugin import to_mesh
12
13
 
13
14
 
14
15
  def define_moab_core_and_tags() -> tuple[core.Core, dict]:
@@ -811,53 +812,112 @@ class CadToDagmc:
811
812
  def export_dagmc_h5m_file(
812
813
  self,
813
814
  filename: str = "dagmc.h5m",
814
- min_mesh_size: float | None = None,
815
- max_mesh_size: float | None = None,
816
- mesh_algorithm: int = 1,
815
+ meshing_backend: str = "cadquery",
817
816
  implicit_complement_material_tag: str | None = None,
818
- method: str = "file",
819
817
  scale_factor: float = 1.0,
820
818
  imprint: bool = True,
821
- set_size: dict[int, float] | None = None,
822
- unstructured_volumes: Iterable[int] | None = None,
823
- umesh_filename: str = "umesh.vtk",
819
+ **kwargs,
824
820
  ) -> str:
825
821
  """Saves a DAGMC h5m file of the geometry
826
822
 
827
823
  Args:
828
- filename (str, optional): the filename to use for the saved DAGMC file. Defaults to "dagmc.h5m".
829
- min_mesh_size (float, optional): the minimum size of mesh elements to use. Defaults to 1.
830
- max_mesh_size (float, optional): the maximum size of mesh elements to use. Defaults to 5.
831
- mesh_algorithm (int, optional): the GMSH mesh algorithm to use.. Defaults to 1.
832
- implicit_complement_material_tag (str | None, optional):
833
- the name of the material tag to use for the implicit complement
834
- (void space). Defaults to None which is a vacuum. Defaults to None.
835
- method: the method to use to import the geometry into gmsh. Options
836
- are 'file' or 'in memory'. 'file' is the default and will write
837
- the geometry to a temporary file before importing it into gmsh.
838
- 'in memory' will import the geometry directly into gmsh but
839
- requires the version of OpenCASCADE used to build gmsh to be
840
- the same as the version used by CadQuery. This is possible to
841
- ensure when installing the package with Conda but harder when
842
- installing from PyPI.
843
- scale_factor: a scaling factor to apply to the geometry that can be
844
- used to enlarge or shrink the geometry. Useful when converting
845
- Useful when converting the geometry to cm for use in neutronics
846
- imprint: whether to imprint the geometry or not. Defaults to True as this is
847
- normally needed to ensure the geometry is meshed correctly. However if
848
- you know your geometry does not need imprinting you can set this to False
849
- and this can save time.
850
- set_size: a dictionary of volume ids (int) and target mesh sizes
851
- (floats) to set for each volume, passed to gmsh.model.mesh.setSize.
852
- unstructured_volumes: a list of volume ids to be saved in as an
853
- unstructured mesh file.
854
- umesh_filename: the filename to use for the optional unstructured
855
- mesh file. Only used if unstructured_volumes is not empty.
824
+ filename: the filename to use for the saved DAGMC file.
825
+ meshing_backend: determines whether gmsh or cadquery's direct mesh method
826
+ is used for meshing. Options are 'gmsh' or 'cadquery'.
827
+ implicit_complement_material_tag: the name of the material tag to use
828
+ for the implicit complement (void space).
829
+ scale_factor: a scaling factor to apply to the geometry.
830
+ imprint: whether to imprint the geometry or not.
831
+
832
+ **kwargs: Backend-specific parameters:
833
+
834
+ For GMSH backend:
835
+ - min_mesh_size (float): minimum mesh element size
836
+ - max_mesh_size (float): maximum mesh element size
837
+ - mesh_algorithm (int): GMSH mesh algorithm (default: 1)
838
+ - method (str): import method 'file' or 'in memory' (default: 'file')
839
+ - set_size (dict[int, float]): volume ids and target mesh sizes
840
+ - unstructured_volumes (Iterable[int]): volume ids for unstructured mesh
841
+ - umesh_filename (str): filename for unstructured mesh (default: 'umesh.vtk')
842
+
843
+ For CadQuery backend:
844
+ - tolerance (float): meshing tolerance (default: 0.1)
845
+ - angular_tolerance (float): angular tolerance (default: 0.1)
856
846
 
857
847
  Returns:
858
- str: the filenames(s) for the files created.
848
+ str: the filename(s) for the files created.
849
+
850
+ Raises:
851
+ ValueError: If invalid parameter combinations are used.
859
852
  """
860
853
 
854
+ # Validate meshing backend
855
+ if meshing_backend not in ["gmsh", "cadquery"]:
856
+ raise ValueError(
857
+ f'meshing_backend "{meshing_backend}" not supported. '
858
+ 'Available options are "gmsh" or "cadquery"'
859
+ )
860
+
861
+ # Initialize variables to avoid unbound errors
862
+ tolerance = 0.1
863
+ angular_tolerance = 0.1
864
+ min_mesh_size = None
865
+ max_mesh_size = None
866
+ mesh_algorithm = 1
867
+ method = "file"
868
+ set_size = None
869
+ unstructured_volumes = None
870
+ umesh_filename = "umesh.vtk"
871
+
872
+ # Extract backend-specific parameters with defaults
873
+ if meshing_backend == "cadquery":
874
+ # CadQuery parameters
875
+ tolerance = kwargs.get("tolerance", 0.1)
876
+ angular_tolerance = kwargs.get("angular_tolerance", 0.1)
877
+
878
+ # Check for invalid parameters
879
+ unstructured_volumes = kwargs.get("unstructured_volumes")
880
+ if unstructured_volumes is not None:
881
+ raise ValueError(
882
+ "CadQuery backend cannot be used for volume meshing. "
883
+ "unstructured_volumes must be None when using 'cadquery' backend."
884
+ )
885
+
886
+ # Warn about unused GMSH parameters
887
+ gmsh_params = [
888
+ "min_mesh_size",
889
+ "max_mesh_size",
890
+ "mesh_algorithm",
891
+ "set_size",
892
+ "umesh_filename",
893
+ "method",
894
+ ]
895
+ unused_params = [param for param in gmsh_params if param in kwargs]
896
+ if unused_params:
897
+ warnings.warn(
898
+ f"The following parameters are ignored when using CadQuery backend: "
899
+ f"{', '.join(unused_params)}"
900
+ )
901
+
902
+ elif meshing_backend == "gmsh":
903
+ # GMSH parameters
904
+ min_mesh_size = kwargs.get("min_mesh_size")
905
+ max_mesh_size = kwargs.get("max_mesh_size")
906
+ mesh_algorithm = kwargs.get("mesh_algorithm", 1)
907
+ method = kwargs.get("method", "file")
908
+ set_size = kwargs.get("set_size")
909
+ unstructured_volumes = kwargs.get("unstructured_volumes")
910
+ umesh_filename = kwargs.get("umesh_filename", "umesh.vtk")
911
+
912
+ # Warn about unused CadQuery parameters
913
+ cq_params = ["tolerance", "angular_tolerance"]
914
+ unused_params = [param for param in cq_params if param in kwargs]
915
+ if unused_params:
916
+ warnings.warn(
917
+ f"The following parameters are ignored when using GMSH backend: "
918
+ f"{', '.join(unused_params)}"
919
+ )
920
+
861
921
  assembly = cq.Assembly()
862
922
  for part in self.parts:
863
923
  assembly.add(part)
@@ -870,41 +930,80 @@ class CadToDagmc:
870
930
  msg = f"Number of volumes {len(original_ids)} is not equal to number of material tags {len(self.material_tags)}"
871
931
  raise ValueError(msg)
872
932
 
873
- if imprint:
874
- imprinted_assembly, imprinted_solids_with_org_id = cq.occ_impl.assembly.imprint(
875
- assembly
933
+ # Use the CadQuery direct mesh plugin
934
+ if meshing_backend == "cadquery":
935
+
936
+ # Mesh the assembly using CadQuery's direct-mesh plugin
937
+ cq_mesh = to_mesh(
938
+ assembly,
939
+ imprint=imprint,
940
+ tolerance=tolerance,
941
+ angular_tolerance=angular_tolerance,
942
+ scale_factor=scale_factor,
876
943
  )
877
944
 
878
- scrambled_ids = get_ids_from_imprinted_assembly(imprinted_solids_with_org_id)
945
+ # Fix the material tag order for imprinted assemblies
946
+ if cq_mesh["imprinted_assembly"] is not None:
947
+ imprinted_solids_with_org_id = cq_mesh["imprinted_solids_with_orginal_ids"]
879
948
 
880
- material_tags_in_brep_order = order_material_ids_by_brep_order(
881
- original_ids, scrambled_ids, self.material_tags
882
- )
883
- else:
884
- material_tags_in_brep_order = self.material_tags
885
- imprinted_assembly = assembly
949
+ scrambled_ids = get_ids_from_imprinted_assembly(imprinted_solids_with_org_id)
886
950
 
887
- check_material_tags(material_tags_in_brep_order, self.parts)
951
+ material_tags_in_brep_order = order_material_ids_by_brep_order(
952
+ original_ids, scrambled_ids, self.material_tags
953
+ )
954
+ else:
955
+ material_tags_in_brep_order = self.material_tags
956
+
957
+ check_material_tags(material_tags_in_brep_order, self.parts)
958
+
959
+ # Extract the mesh information to allow export to h5m from the direct-mesh result
960
+ vertices = cq_mesh["vertices"]
961
+ triangles_by_solid_by_face = cq_mesh["solid_face_triangle_vertex_map"]
962
+ # Use gmsh
963
+ elif meshing_backend == "gmsh":
964
+ # If assembly is not to be imprinted, pass through the assembly as-is
965
+ if imprint:
966
+ imprinted_assembly, imprinted_solids_with_org_id = cq.occ_impl.assembly.imprint(
967
+ assembly
968
+ )
888
969
 
889
- gmsh = init_gmsh()
970
+ scrambled_ids = get_ids_from_imprinted_assembly(imprinted_solids_with_org_id)
890
971
 
891
- gmsh, volumes = get_volumes(
892
- gmsh, imprinted_assembly, method=method, scale_factor=scale_factor
893
- )
972
+ material_tags_in_brep_order = order_material_ids_by_brep_order(
973
+ original_ids, scrambled_ids, self.material_tags
974
+ )
894
975
 
895
- gmsh = set_sizes_for_mesh(
896
- gmsh=gmsh,
897
- min_mesh_size=min_mesh_size,
898
- max_mesh_size=max_mesh_size,
899
- mesh_algorithm=mesh_algorithm,
900
- set_size=set_size,
901
- )
976
+ else:
977
+ material_tags_in_brep_order = self.material_tags
978
+ imprinted_assembly = assembly
902
979
 
903
- gmsh.model.mesh.generate(2)
980
+ check_material_tags(material_tags_in_brep_order, self.parts)
904
981
 
905
- vertices, triangles_by_solid_by_face = mesh_to_vertices_and_triangles(
906
- dims_and_vol_ids=volumes
907
- )
982
+ # Start generating the mesh
983
+ gmsh = init_gmsh()
984
+
985
+ gmsh, volumes = get_volumes(
986
+ gmsh, imprinted_assembly, method=method, scale_factor=scale_factor
987
+ )
988
+
989
+ gmsh = set_sizes_for_mesh(
990
+ gmsh=gmsh,
991
+ min_mesh_size=min_mesh_size,
992
+ max_mesh_size=max_mesh_size,
993
+ mesh_algorithm=mesh_algorithm,
994
+ set_size=set_size,
995
+ )
996
+
997
+ gmsh.model.mesh.generate(2)
998
+
999
+ vertices, triangles_by_solid_by_face = mesh_to_vertices_and_triangles(
1000
+ dims_and_vol_ids=volumes
1001
+ )
1002
+
1003
+ else:
1004
+ raise ValueError(
1005
+ f'meshing_backend {meshing_backend} not supported. Available options are "cadquery" or "gmsh"'
1006
+ )
908
1007
 
909
1008
  dagmc_filename = vertices_to_h5m(
910
1009
  vertices=vertices,
@@ -0,0 +1,508 @@
1
+ # This is a temporary solution until we have to_mesh like functionality in a
2
+ # PYPI distributed version of CadQuery.
3
+ # This code is adapted from the cadquery-direct-mesh-plugin repository:
4
+ # https://github.com/jmwright/cadquery-direct-mesh-plugin
5
+
6
+ # Apache License
7
+ # Version 2.0, January 2004
8
+ # http://www.apache.org/licenses/
9
+
10
+ # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
+
12
+ # 1. Definitions.
13
+
14
+ # "License" shall mean the terms and conditions for use, reproduction,
15
+ # and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ # "Licensor" shall mean the copyright owner or entity authorized by
18
+ # the copyright owner that is granting the License.
19
+
20
+ # "Legal Entity" shall mean the union of the acting entity and all
21
+ # other entities that control, are controlled by, or are under common
22
+ # control with that entity. For the purposes of this definition,
23
+ # "control" means (i) the power, direct or indirect, to cause the
24
+ # direction or management of such entity, whether by contract or
25
+ # otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ # outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+ # "You" (or "Your") shall mean an individual or Legal Entity
29
+ # exercising permissions granted by this License.
30
+
31
+ # "Source" form shall mean the preferred form for making modifications,
32
+ # including but not limited to software source code, documentation
33
+ # source, and configuration files.
34
+
35
+ # "Object" form shall mean any form resulting from mechanical
36
+ # transformation or translation of a Source form, including but
37
+ # not limited to compiled object code, generated documentation,
38
+ # and conversions to other media types.
39
+
40
+ # "Work" shall mean the work of authorship, whether in Source or
41
+ # Object form, made available under the License, as indicated by a
42
+ # copyright notice that is included in or attached to the work
43
+ # (an example is provided in the Appendix below).
44
+
45
+ # "Derivative Works" shall mean any work, whether in Source or Object
46
+ # form, that is based on (or derived from) the Work and for which the
47
+ # editorial revisions, annotations, elaborations, or other modifications
48
+ # represent, as a whole, an original work of authorship. For the purposes
49
+ # of this License, Derivative Works shall not include works that remain
50
+ # separable from, or merely link (or bind by name) to the interfaces of,
51
+ # the Work and Derivative Works thereof.
52
+
53
+ # "Contribution" shall mean any work of authorship, including
54
+ # the original version of the Work and any modifications or additions
55
+ # to that Work or Derivative Works thereof, that is intentionally
56
+ # submitted to Licensor for inclusion in the Work by the copyright owner
57
+ # or by an individual or Legal Entity authorized to submit on behalf of
58
+ # the copyright owner. For the purposes of this definition, "submitted"
59
+ # means any form of electronic, verbal, or written communication sent
60
+ # to the Licensor or its representatives, including but not limited to
61
+ # communication on electronic mailing lists, source code control systems,
62
+ # and issue tracking systems that are managed by, or on behalf of, the
63
+ # Licensor for the purpose of discussing and improving the Work, but
64
+ # excluding communication that is conspicuously marked or otherwise
65
+ # designated in writing by the copyright owner as "Not a Contribution."
66
+
67
+ # "Contributor" shall mean Licensor and any individual or Legal Entity
68
+ # on behalf of whom a Contribution has been received by Licensor and
69
+ # subsequently incorporated within the Work.
70
+
71
+ # 2. Grant of Copyright License. Subject to the terms and conditions of
72
+ # this License, each Contributor hereby grants to You a perpetual,
73
+ # worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
+ # copyright license to reproduce, prepare Derivative Works of,
75
+ # publicly display, publicly perform, sublicense, and distribute the
76
+ # Work and such Derivative Works in Source or Object form.
77
+
78
+ # 3. Grant of Patent License. Subject to the terms and conditions of
79
+ # this License, each Contributor hereby grants to You a perpetual,
80
+ # worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
+ # (except as stated in this section) patent license to make, have made,
82
+ # use, offer to sell, sell, import, and otherwise transfer the Work,
83
+ # where such license applies only to those patent claims licensable
84
+ # by such Contributor that are necessarily infringed by their
85
+ # Contribution(s) alone or by combination of their Contribution(s)
86
+ # with the Work to which such Contribution(s) was submitted. If You
87
+ # institute patent litigation against any entity (including a
88
+ # cross-claim or counterclaim in a lawsuit) alleging that the Work
89
+ # or a Contribution incorporated within the Work constitutes direct
90
+ # or contributory patent infringement, then any patent licenses
91
+ # granted to You under this License for that Work shall terminate
92
+ # as of the date such litigation is filed.
93
+
94
+ # 4. Redistribution. You may reproduce and distribute copies of the
95
+ # Work or Derivative Works thereof in any medium, with or without
96
+ # modifications, and in Source or Object form, provided that You
97
+ # meet the following conditions:
98
+
99
+ # (a) You must give any other recipients of the Work or
100
+ # Derivative Works a copy of this License; and
101
+
102
+ # (b) You must cause any modified files to carry prominent notices
103
+ # stating that You changed the files; and
104
+
105
+ # (c) You must retain, in the Source form of any Derivative Works
106
+ # that You distribute, all copyright, patent, trademark, and
107
+ # attribution notices from the Source form of the Work,
108
+ # excluding those notices that do not pertain to any part of
109
+ # the Derivative Works; and
110
+
111
+ # (d) If the Work includes a "NOTICE" text file as part of its
112
+ # distribution, then any Derivative Works that You distribute must
113
+ # include a readable copy of the attribution notices contained
114
+ # within such NOTICE file, excluding those notices that do not
115
+ # pertain to any part of the Derivative Works, in at least one
116
+ # of the following places: within a NOTICE text file distributed
117
+ # as part of the Derivative Works; within the Source form or
118
+ # documentation, if provided along with the Derivative Works; or,
119
+ # within a display generated by the Derivative Works, if and
120
+ # wherever such third-party notices normally appear. The contents
121
+ # of the NOTICE file are for informational purposes only and
122
+ # do not modify the License. You may add Your own attribution
123
+ # notices within Derivative Works that You distribute, alongside
124
+ # or as an addendum to the NOTICE text from the Work, provided
125
+ # that such additional attribution notices cannot be construed
126
+ # as modifying the License.
127
+
128
+ # You may add Your own copyright statement to Your modifications and
129
+ # may provide additional or different license terms and conditions
130
+ # for use, reproduction, or distribution of Your modifications, or
131
+ # for any such Derivative Works as a whole, provided Your use,
132
+ # reproduction, and distribution of the Work otherwise complies with
133
+ # the conditions stated in this License.
134
+
135
+ # 5. Submission of Contributions. Unless You explicitly state otherwise,
136
+ # any Contribution intentionally submitted for inclusion in the Work
137
+ # by You to the Licensor shall be under the terms and conditions of
138
+ # this License, without any additional terms or conditions.
139
+ # Notwithstanding the above, nothing herein shall supersede or modify
140
+ # the terms of any separate license agreement you may have executed
141
+ # with Licensor regarding such Contributions.
142
+
143
+ # 6. Trademarks. This License does not grant permission to use the trade
144
+ # names, trademarks, service marks, or product names of the Licensor,
145
+ # except as required for reasonable and customary use in describing the
146
+ # origin of the Work and reproducing the content of the NOTICE file.
147
+
148
+ # 7. Disclaimer of Warranty. Unless required by applicable law or
149
+ # agreed to in writing, Licensor provides the Work (and each
150
+ # Contributor provides its Contributions) on an "AS IS" BASIS,
151
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
+ # implied, including, without limitation, any warranties or conditions
153
+ # of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
+ # PARTICULAR PURPOSE. You are solely responsible for determining the
155
+ # appropriateness of using or redistributing the Work and assume any
156
+ # risks associated with Your exercise of permissions under this License.
157
+
158
+ # 8. Limitation of Liability. In no event and under no legal theory,
159
+ # whether in tort (including negligence), contract, or otherwise,
160
+ # unless required by applicable law (such as deliberate and grossly
161
+ # negligent acts) or agreed to in writing, shall any Contributor be
162
+ # liable to You for damages, including any direct, indirect, special,
163
+ # incidental, or consequential damages of any character arising as a
164
+ # result of this License or out of the use or inability to use the
165
+ # Work (including but not limited to damages for loss of goodwill,
166
+ # work stoppage, computer failure or malfunction, or any and all
167
+ # other commercial damages or losses), even if such Contributor
168
+ # has been advised of the possibility of such damages.
169
+
170
+ # 9. Accepting Warranty or Additional Liability. While redistributing
171
+ # the Work or Derivative Works thereof, You may choose to offer,
172
+ # and charge a fee for, acceptance of support, warranty, indemnity,
173
+ # or other liability obligations and/or rights consistent with this
174
+ # License. However, in accepting such obligations, You may act only
175
+ # on Your own behalf and on Your sole responsibility, not on behalf
176
+ # of any other Contributor, and only if You agree to indemnify,
177
+ # defend, and hold each Contributor harmless for any liability
178
+ # incurred by, or claims asserted against, such Contributor by reason
179
+ # of your accepting any such warranty or additional liability.
180
+
181
+ # END OF TERMS AND CONDITIONS
182
+
183
+ # APPENDIX: How to apply the Apache License to your work.
184
+
185
+ # To apply the Apache License to your work, attach the following
186
+ # boilerplate notice, with the fields enclosed by brackets "[]"
187
+ # replaced with your own identifying information. (Don't include
188
+ # the brackets!) The text should be enclosed in the appropriate
189
+ # comment syntax for the file format. We also recommend that a
190
+ # file or class name and description of purpose be included on the
191
+ # same "printed page" as the copyright notice for easier
192
+ # identification within third-party archives.
193
+
194
+ # Copyright [yyyy] [name of copyright owner]
195
+
196
+ # Licensed under the Apache License, Version 2.0 (the "License");
197
+ # you may not use this file except in compliance with the License.
198
+ # You may obtain a copy of the License at
199
+
200
+ # http://www.apache.org/licenses/LICENSE-2.0
201
+
202
+ # Unless required by applicable law or agreed to in writing, software
203
+ # distributed under the License is distributed on an "AS IS" BASIS,
204
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205
+ # See the License for the specific language governing permissions and
206
+ # limitations under the License.
207
+
208
+
209
+ from OCP.TopLoc import TopLoc_Location
210
+ from OCP.BRep import BRep_Tool
211
+ from OCP.BRepMesh import BRepMesh_IncrementalMesh
212
+ from OCP import GCPnts, BRepAdaptor
213
+ from OCP.TopAbs import TopAbs_REVERSED, TopAbs_IN
214
+ from OCP.gp import gp_Pnt, gp_Vec
215
+ import cadquery as cq
216
+
217
+
218
+ def _is_interior_face(face, solid, tolerance=0.01):
219
+ """
220
+ Determine if a face is interior to a solid (like a cavity wall).
221
+
222
+ This is more robust than just checking face orientation, as it considers
223
+ the geometric relationship between the face and the solid.
224
+ """
225
+ # Get geometric surface and parameter bounds
226
+ surf = BRep_Tool.Surface_s(face.wrapped)
227
+ u_min, u_max, v_min, v_max = face._uvBounds()
228
+
229
+ # # Take center point in UV space on the face
230
+ u = (u_min + u_max) * 0.5
231
+ v = (v_min + v_max) * 0.5
232
+ face_pnt = surf.Value(u, v)
233
+
234
+ # Determine if the face is most likely inside the solid
235
+ is_inside = solid.isInside((face_pnt.X(), face_pnt.Y(), face_pnt.Z()))
236
+
237
+ # Determine if the normal of the face points generally towards to the center of the solid
238
+ is_pointing_inward = False
239
+ face_normal = face.normalAt((face_pnt.X(), face_pnt.Y(), face_pnt.Z()))
240
+ solid_center = solid.Center()
241
+
242
+ to_center = gp_Vec(face_pnt, gp_Pnt(solid_center.x, solid_center.y, solid_center.z))
243
+
244
+ # Dot product: negative = toward, positive = away
245
+ dot = face_normal.dot(cq.Vector(to_center.Normalized()))
246
+
247
+ if dot < 0:
248
+ is_pointing_inward = False
249
+ else:
250
+ is_pointing_inward = True
251
+
252
+ # If the face seems to be inside the solid and its normal points inwards, it should be an internal face
253
+ is_internal_face = False
254
+ if is_inside and is_pointing_inward:
255
+ is_internal_face = True
256
+
257
+ return is_internal_face
258
+
259
+
260
+ def to_mesh(
261
+ assembly,
262
+ imprint=True,
263
+ tolerance=0.1,
264
+ angular_tolerance=0.1,
265
+ scale_factor=1.0,
266
+ include_brep_edges=False,
267
+ include_brep_vertices=False,
268
+ ):
269
+ """
270
+ Converts an assembly to a custom mesh format defined by the CadQuery team.
271
+
272
+ :param imprint: Whether or not the assembly should be imprinted
273
+ :param tolerance: Tessellation tolerance for mesh generation
274
+ :param angular_tolerance: Angular tolerance for tessellation
275
+ :param include_brep_edges: Whether to include BRep edge segments
276
+ :param include_brep_vertices: Whether to include BRep vertices
277
+ """
278
+
279
+ # To keep track of the vertices and triangles in the mesh
280
+ vertices = []
281
+ vertex_map = {}
282
+ solids = []
283
+ solid_face_triangle = {}
284
+ imprinted_assembly = None
285
+ imprinted_solids_with_orginal_ids = None
286
+ solid_colors = []
287
+ solid_locs = []
288
+ solid_brep_edge_segments = []
289
+ solid_brep_vertices = []
290
+
291
+ # Imprinted assemblies end up being compounds, whereas you have to step through each of the
292
+ # parts in an assembly and extract the solids.
293
+ if imprint:
294
+ # Imprint the assembly and process it as a compound
295
+ (
296
+ imprinted_assembly,
297
+ imprinted_solids_with_orginal_ids,
298
+ ) = cq.occ_impl.assembly.imprint(assembly)
299
+
300
+ # Extract the solids from the imprinted assembly because we should not mesh the compound
301
+ for solid in imprinted_assembly.Solids():
302
+ solids.append(solid)
303
+
304
+ # Keep track of the colors and location of each of the solids
305
+ solid_colors.append((0.5, 0.5, 0.5, 1.0))
306
+ solid_locs.append(cq.Location())
307
+ else:
308
+ # Step through every child in the assembly and save their solids
309
+ for child in assembly.children:
310
+ # Make sure we end up with a base shape
311
+ obj = child.obj
312
+ if type(child.obj).__name__ == "Workplane":
313
+ solids.append(obj.val())
314
+ else:
315
+ solids.append(obj)
316
+
317
+ # Use the color set for the assembly component, or use a default color
318
+ if child.color:
319
+ solid_colors.append(child.color.toTuple())
320
+ else:
321
+ solid_colors.append((0.5, 0.5, 0.5, 1.0))
322
+
323
+ # Keep track of the location of each of the solids
324
+ solid_locs.append(child.loc)
325
+
326
+ # Solid and face IDs need to be unique unless they are a shared face
327
+ solid_idx = 1 # We start at 1 to mimic gmsh
328
+ face_idx = 1 # We start at id of 1 to mimic gmsh
329
+
330
+ # Step through all of the collected solids and their respective faces to get the vertices
331
+ for solid in solids:
332
+ # Reset this each time so that we get the correct number of faces per solid
333
+ face_triangles = {}
334
+
335
+ # Order the faces in order of area, largest first
336
+ sorted_faces = []
337
+ face_areas = []
338
+ for face in solid.Faces():
339
+ area = face.Area()
340
+ sorted_faces.append((face, area))
341
+ face_areas.append(area)
342
+
343
+ # Sort by area (largest first)
344
+ sorted_faces.sort(key=lambda x: x[1], reverse=False)
345
+
346
+ # Extract just the sorted faces if you need them separately
347
+ sorted_face_list = [face_info[0] for face_info in sorted_faces]
348
+
349
+ # Walk through all the faces
350
+ for face in sorted_face_list:
351
+ # Figure out if the face has a reversed orientation so we can handle the triangles accordingly
352
+ is_reversed = False
353
+ if face.wrapped.Orientation() == TopAbs_REVERSED:
354
+ is_reversed = True
355
+
356
+ # Location information of the face to place the vertices and edges correctly
357
+ loc = TopLoc_Location()
358
+
359
+ # Perform the tessellation
360
+ BRepMesh_IncrementalMesh(face.wrapped, tolerance, False, angular_tolerance)
361
+ face_mesh = BRep_Tool.Triangulation_s(face.wrapped, loc)
362
+
363
+ # If this is not an imprinted assembly, override the location of the triangulation
364
+ if not imprint:
365
+ loc = solid_locs[solid_idx - 1].wrapped
366
+
367
+ # Save the transformation so that we can place vertices in the correct locations later
368
+ Trsf = loc.Transformation()
369
+
370
+ # Pre-process all vertices from the face mesh for better performance
371
+ face_vertices = {} # Map from face mesh node index to global vertex index
372
+ for node_idx in range(1, face_mesh.NbNodes() + 1):
373
+ node = face_mesh.Node(node_idx)
374
+ v_trsf = node.Transformed(Trsf)
375
+ vertex_coords = (
376
+ v_trsf.X() * scale_factor,
377
+ v_trsf.Y() * scale_factor,
378
+ v_trsf.Z() * scale_factor,
379
+ )
380
+
381
+ # Use dictionary for O(1) lookup instead of O(n) list operations
382
+ if vertex_coords in vertex_map:
383
+ face_vertices[node_idx] = vertex_map[vertex_coords]
384
+ else:
385
+ global_vertex_idx = len(vertices)
386
+ vertices.append(vertex_coords)
387
+ vertex_map[vertex_coords] = global_vertex_idx
388
+ face_vertices[node_idx] = global_vertex_idx
389
+
390
+ # Step through the triangles of the face
391
+ cur_triangles = []
392
+ for i in range(1, face_mesh.NbTriangles() + 1):
393
+ # Get the current triangle and its index vertices
394
+ cur_tri = face_mesh.Triangle(i)
395
+ idx_1, idx_2, idx_3 = cur_tri.Get()
396
+
397
+ # Look up pre-processed vertex indices - O(1) operation
398
+ if is_reversed:
399
+ triangle_vertex_indices = [
400
+ face_vertices[idx_1],
401
+ face_vertices[idx_3],
402
+ face_vertices[idx_2],
403
+ ]
404
+ else:
405
+ triangle_vertex_indices = [
406
+ face_vertices[idx_1],
407
+ face_vertices[idx_2],
408
+ face_vertices[idx_3],
409
+ ]
410
+
411
+ cur_triangles.append(triangle_vertex_indices)
412
+
413
+ # Save this triangle for the current face
414
+ face_triangles[face_idx] = cur_triangles
415
+
416
+ # Move to the next face
417
+ face_idx += 1
418
+
419
+ solid_face_triangle[solid_idx] = face_triangles
420
+
421
+ # If the caller wants to track edges, include them
422
+ if include_brep_edges:
423
+ # If this is not an imprinted assembly, override the location of the edges
424
+ loc = TopLoc_Location()
425
+ if not imprint:
426
+ loc = solid_locs[solid_idx - 1].wrapped
427
+
428
+ # Save the transformation so that we can place vertices in the correct locations later
429
+ Trsf = loc.Transformation()
430
+
431
+ # Add CadQuery-reported edges
432
+ current_segments = []
433
+ for edge in solid.edges():
434
+ # We need to handle different kinds of edges differently
435
+ gt = edge.geomType()
436
+
437
+ # Line edges are just point to point
438
+ if gt == "LINE":
439
+ start = edge.startPoint().toPnt()
440
+ end = edge.endPoint().toPnt()
441
+
442
+ # Apply the assembly location transformation to each vertex
443
+ start_trsf = start.Transformed(Trsf)
444
+ located_start = (start_trsf.X(), start_trsf.Y(), start_trsf.Z())
445
+ end_trsf = end.Transformed(Trsf)
446
+ located_end = (end_trsf.X(), end_trsf.Y(), end_trsf.Z())
447
+
448
+ # Save the start and end points for the edge
449
+ current_segments.append([located_start, located_end])
450
+ # If dealing with some sort of arc, discretize it into individual lines
451
+ elif gt in ("CIRCLE", "ARC", "SPLINE", "BSPLINE", "ELLIPSE"):
452
+ # Discretize the curve
453
+ disc = GCPnts.GCPnts_TangentialDeflection(
454
+ BRepAdaptor.BRepAdaptor_Curve(edge.wrapped),
455
+ tolerance,
456
+ angular_tolerance,
457
+ )
458
+
459
+ # Add each of the discretized sections to the edge list
460
+ if disc.NbPoints() > 1:
461
+ for i in range(2, disc.NbPoints() + 1):
462
+ p_0 = disc.Value(i - 1)
463
+ p_1 = disc.Value(i)
464
+
465
+ # Apply the assembly location transformation to each vertex
466
+ p_0_trsf = p_0.Transformed(Trsf)
467
+ located_p_0 = (p_0_trsf.X(), p_0_trsf.Y(), p_0_trsf.Z())
468
+ p_1_trsf = p_1.Transformed(Trsf)
469
+ located_p_1 = (p_1_trsf.X(), p_1_trsf.Y(), p_1_trsf.Z())
470
+
471
+ # Save the start and end points for the edge
472
+ current_segments.append([located_p_0, located_p_1])
473
+
474
+ solid_brep_edge_segments.append(current_segments)
475
+
476
+ # Add CadQuery-reported vertices, if requested
477
+ if include_brep_vertices:
478
+ # If this is not an imprinted assembly, override the location of the edges
479
+ loc = TopLoc_Location()
480
+ if not imprint:
481
+ loc = solid_locs[solid_idx - 1].wrapped
482
+
483
+ # Save the transformation so that we can place vertices in the correct locations later
484
+ Trsf = loc.Transformation()
485
+
486
+ current_vertices = []
487
+ for vertex in solid.vertices():
488
+ p = BRep_Tool.Pnt_s(vertex.wrapped)
489
+
490
+ # Apply the assembly location transformation to each vertex
491
+ p_trsf = p.Transformed(Trsf)
492
+ located_p = (p_trsf.X(), p_trsf.Y(), p_trsf.Z())
493
+ current_vertices.append(located_p)
494
+
495
+ solid_brep_vertices.append(current_vertices)
496
+
497
+ # Move to the next solid
498
+ solid_idx += 1
499
+
500
+ return {
501
+ "vertices": vertices,
502
+ "solid_face_triangle_vertex_map": solid_face_triangle,
503
+ "solid_colors": solid_colors,
504
+ "solid_brep_edge_segments": solid_brep_edge_segments,
505
+ "solid_brep_vertices": solid_brep_vertices,
506
+ "imprinted_assembly": imprinted_assembly,
507
+ "imprinted_solids_with_orginal_ids": imprinted_solids_with_orginal_ids,
508
+ }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cad_to_dagmc
3
- Version: 0.9.2
3
+ Version: 0.9.4
4
4
  Summary: Converts CAD files to a DAGMC h5m file
5
5
  Author-email: Jonathan Shimwell <mail@jshimwell.com>
6
6
  Project-URL: Homepage, https://github.com/fusion-energy/cad_to_dagmc
@@ -49,11 +49,9 @@ cad-to-dagmc can convert the following in to DAGMC compatible meshes:
49
49
  - Gmsh meshes (optionally use physical groups as material tags)
50
50
 
51
51
  Cad-to-dagmc offers a wide range of features including.
52
- - Compatibly with [assembly-mesh-plugin](https://github.com/CadQuery/assembly-mesh-plugin) (see examples)
53
- - Access to the Gmsh mesh to allow user to define full set of mesh parameters
54
- - Option to use Gmsh physical groups as material tags
55
52
  - Geometry scaling with ```scale_factor``` argument
56
- - Model wide mesh size parameters with ```min_mesh_size``` and ```max_mesh_size``` arguments
53
+ - Ddirect surface meshing of CadQuery geometry with ```tolerance``` and ```angular_tolerance``` arguments (avoids using Gmsh)
54
+ - Model wide mesh Gmsh size parameters with ```min_mesh_size``` and ```max_mesh_size``` arguments
57
55
  - Volume specific mesh sizing parameters with the ```set_size``` argument
58
56
  - Unstructured mesh that share the same coordinates as the surface mesh.
59
57
  - Volume mesh allows selecting individual volumes in the geometry.
@@ -65,6 +63,9 @@ Cad-to-dagmc offers a wide range of features including.
65
63
  - Pass CadQuery objects in memory for fast transfer of geometry using the ```method``` argument
66
64
  - Easy to install with [pip](https://pypi.org/project/cad-to-dagmc/) and [Conda/Mamba](https://anaconda.org/conda-forge/cad_to_dagmc)
67
65
  - Well tested both with [CI unit tests](https://github.com/fusion-energy/cad_to_dagmc/tree/main/tests), integration tests and the CSG [Model Benchmark Zoo](https://github.com/fusion-energy/model_benchmark_zoo).
66
+ - Access to the Gmsh mesh to allow user to define full set of mesh parameters
67
+ - Option to use Gmsh physical groups as material tags
68
+ - Compatibly with [assembly-mesh-plugin](https://github.com/CadQuery/assembly-mesh-plugin) (see examples)
68
69
  - Compatible with [Paramak](https://github.com/fusion-energy/paramak) geometry for fusion simulations.
69
70
 
70
71
 
@@ -0,0 +1,9 @@
1
+ _version.py,sha256=neCU47g_h2UhyiDH9FD_S8jzk8iEdw9LEgRY7JImMPs,704
2
+ cad_to_dagmc/__init__.py,sha256=oCr1P0QnBsf6AH0RZujX7T7tdrb75NazdF70HtqXSfc,528
3
+ cad_to_dagmc/core.py,sha256=xYDP7OQ8D-FtPhjfcbZ2Gs5oX4pZisd72zyk3lSkpJg,40352
4
+ cad_to_dagmc/direct_mesh_plugin.py,sha256=5jG5ILafjbDacaAvBRWD_ilMZLepcM6H1Tjze85vAxE,24013
5
+ cad_to_dagmc-0.9.4.dist-info/licenses/LICENSE,sha256=B8kznH_777JVNZ3HOKDc4Tj24F7wJ68ledaNYeL9sCw,1070
6
+ cad_to_dagmc-0.9.4.dist-info/METADATA,sha256=7EeDiEXc-NKoTwMSiTPs2bo2uLPKSQqB2n1cgGyudFM,9121
7
+ cad_to_dagmc-0.9.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ cad_to_dagmc-0.9.4.dist-info/top_level.txt,sha256=zTi8C64SEBsE5WOtPovnxhOzt-E6Oc5nC3RW6M_5aEA,22
9
+ cad_to_dagmc-0.9.4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.3.1)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,8 +0,0 @@
1
- _version.py,sha256=eeYYTSIkrgfRwSQ7LKo_py3xs3DvzgfWiAtK4K1JM4A,511
2
- cad_to_dagmc/__init__.py,sha256=fskHUTyCunSpnpJUvBfAYjx4uwDKXHTTiMP6GqnFRf0,494
3
- cad_to_dagmc/core.py,sha256=dGj5LRRzboQ8CL8VS5dkvIkGLyj5MJWcbkTPtrFk0QQ,36947
4
- cad_to_dagmc-0.9.2.dist-info/licenses/LICENSE,sha256=B8kznH_777JVNZ3HOKDc4Tj24F7wJ68ledaNYeL9sCw,1070
5
- cad_to_dagmc-0.9.2.dist-info/METADATA,sha256=8vLnV93ycmV216LiNj38YI4z445pWtdpBKpcESFLLH0,8990
6
- cad_to_dagmc-0.9.2.dist-info/WHEEL,sha256=0CuiUZ_p9E4cD6NyLD6UG80LBXYyiSYZOKDm5lp32xk,91
7
- cad_to_dagmc-0.9.2.dist-info/top_level.txt,sha256=zTi8C64SEBsE5WOtPovnxhOzt-E6Oc5nC3RW6M_5aEA,22
8
- cad_to_dagmc-0.9.2.dist-info/RECORD,,