Coverage for src/meshpy/four_c/model_importer.py: 91%
85 statements
« prev ^ index » next coverage.py v7.9.0, created at 2025-06-13 04:26 +0000
« prev ^ index » next coverage.py v7.9.0, created at 2025-06-13 04:26 +0000
1# The MIT License (MIT)
2#
3# Copyright (c) 2018-2025 MeshPy Authors
4#
5# Permission is hereby granted, free of charge, to any person obtaining a copy
6# of this software and associated documentation files (the "Software"), to deal
7# in the Software without restriction, including without limitation the rights
8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9# copies of the Software, and to permit persons to whom the Software is
10# furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice shall be included in
13# all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21# THE SOFTWARE.
22"""This module contains functions to load and parse existing 4C input files."""
24from pathlib import Path as _Path
25from typing import Dict as _Dict
26from typing import List as _List
27from typing import Tuple as _Tuple
28from typing import Union as _Union
30import meshpy.core.conf as _conf
31from meshpy.core.boundary_condition import BoundaryCondition as _BoundaryCondition
32from meshpy.core.boundary_condition import (
33 BoundaryConditionBase as _BoundaryConditionBase,
34)
35from meshpy.core.conf import mpy as _mpy
36from meshpy.core.coupling import Coupling as _Coupling
37from meshpy.core.element_volume import VolumeHEX8 as _VolumeHEX8
38from meshpy.core.element_volume import VolumeHEX20 as _VolumeHEX20
39from meshpy.core.element_volume import VolumeHEX27 as _VolumeHEX27
40from meshpy.core.element_volume import VolumeTET4 as _VolumeTET4
41from meshpy.core.element_volume import VolumeTET10 as _VolumeTET10
42from meshpy.core.element_volume import VolumeWEDGE6 as _VolumeWEDGE6
43from meshpy.core.geometry_set import GeometrySetNodes as _GeometrySetNodes
44from meshpy.core.mesh import Mesh as _Mesh
45from meshpy.core.node import Node as _Node
46from meshpy.four_c.element_volume import SolidRigidSphere as _SolidRigidSphere
47from meshpy.four_c.input_file import InputFile as _InputFile
48from meshpy.four_c.input_file import (
49 get_geometry_set_indices_from_section as _get_geometry_set_indices_from_section,
50)
51from meshpy.four_c.input_file_mappings import (
52 INPUT_FILE_MAPPINGS as _INPUT_FILE_MAPPINGS,
53)
54from meshpy.utils.environment import cubitpy_is_available as _cubitpy_is_available
56if _cubitpy_is_available():
57 from cubitpy.cubit_to_fourc_input import (
58 get_input_file_with_mesh as _get_input_file_with_mesh,
59 )
62def import_cubitpy_model(cubit, convert_input_to_mesh: bool = False):
63 """Convert a CubitPy instance to a MeshPy InputFile.
65 Args:
66 cubit (CubitPy): An instance of a cubit model.
67 convert_input_to_mesh: If this is false, the cubit model will be
68 converted to plain FourCIPP input data. If this is true, an input
69 file with all the parameters will be returned and a mesh which
70 contains the mesh information from cubit converted to MeshPy
71 objects.
73 Returns:
74 A tuple with the input file and the mesh. If convert_input_to_mesh is
75 False, the mesh will be empty. Note that the input sections which are
76 converted to a MeshPy mesh are removed from the input file object.
77 """
79 input_file = _InputFile(sections=_get_input_file_with_mesh(cubit).sections)
81 if convert_input_to_mesh:
82 return _extract_mesh_sections(input_file)
83 else:
84 return input_file, _Mesh()
87def import_four_c_model(
88 input_file_path: _Path, convert_input_to_mesh: bool = False
89) -> _Tuple[_InputFile, _Mesh]:
90 """Import an existing 4C input file and optionally convert it into a MeshPy
91 mesh.
93 Args:
94 input_file_path: A file path to an existing 4C input file that will be
95 imported.
96 convert_input_to_mesh: If True, the input file will be converted to a
97 MeshPy mesh.
99 Returns:
100 A tuple with the input file and the mesh. If convert_input_to_mesh is
101 False, the mesh will be empty. Note that the input sections which are
102 converted to a MeshPy mesh are removed from the input file object.
103 """
105 input_file = _InputFile().from_4C_yaml(input_file_path=input_file_path)
107 if convert_input_to_mesh:
108 return _extract_mesh_sections(input_file)
109 else:
110 return input_file, _Mesh()
113def _element_from_dict(nodes: _List[_Node], element: dict):
114 """Create a solid element from a dictionary from a 4C input file.
116 Args:
117 nodes: A list of nodes that are part of the element.
118 element: A dictionary with the element data.
119 Returns:
120 A solid element object.
121 """
123 # Depending on the number of nodes chose which solid element to return.
124 # TODO reuse element_type_to_four_c_string from meshpy.core.element_volume
125 element_type = {
126 "HEX8": _VolumeHEX8,
127 "HEX20": _VolumeHEX20,
128 "HEX27": _VolumeHEX27,
129 "TET4": _VolumeTET4,
130 "TET10": _VolumeTET10,
131 "WEDGE6": _VolumeWEDGE6,
132 "POINT1": _SolidRigidSphere,
133 }
135 if element["cell"]["type"] not in element_type:
136 raise TypeError(
137 f"Could not create a MeshPy element for {element['data']['type']} {element['cell']['type']}!"
138 )
140 return element_type[element["cell"]["type"]](nodes=nodes, data=element["data"])
143def _boundary_condition_from_dict(
144 geometry_set: _GeometrySetNodes,
145 bc_key: _Union[_conf.BoundaryCondition, str],
146 data: _Dict,
147) -> _BoundaryConditionBase:
148 """This function acts as a factory and creates the correct boundary
149 condition object from a dictionary parsed from an input file."""
151 del data["E"]
153 if bc_key in (
154 _mpy.bc.dirichlet,
155 _mpy.bc.neumann,
156 _mpy.bc.locsys,
157 _mpy.bc.beam_to_solid_surface_meshtying,
158 _mpy.bc.beam_to_solid_surface_contact,
159 _mpy.bc.beam_to_solid_volume_meshtying,
160 ) or isinstance(bc_key, str):
161 return _BoundaryCondition(geometry_set, data, bc_type=bc_key)
162 elif bc_key is _mpy.bc.point_coupling:
163 return _Coupling(geometry_set, bc_key, data, check_overlapping_nodes=False)
164 else:
165 raise ValueError("Got unexpected boundary condition!")
168def _get_yaml_geometry_sets(
169 nodes: _List[_Node], geometry_key: _conf.Geometry, section_list: _List
170) -> _Dict[int, _GeometrySetNodes]:
171 """Add sets of points, lines, surfaces or volumes to the object."""
173 # Create the individual geometry sets
174 geometry_set_dict = _get_geometry_set_indices_from_section(section_list)
175 geometry_sets_in_this_section = {}
176 for geometry_set_id, node_ids in geometry_set_dict.items():
177 geometry_sets_in_this_section[geometry_set_id] = _GeometrySetNodes(
178 geometry_key, nodes=[nodes[node_id] for node_id in node_ids]
179 )
180 return geometry_sets_in_this_section
183def _extract_mesh_sections(input_file: _InputFile) -> _Tuple[_InputFile, _Mesh]:
184 """Convert an existing input file to a MeshPy mesh with mesh items, e.g.,
185 nodes, elements, element sets, node sets, boundary conditions, materials.
187 Args:
188 input_file: The input file object that contains the sections to be
189 converted to a MeshPy mesh.
190 Returns:
191 A tuple with the input file and the mesh. The input file will be
192 modified to remove the sections that have been converted to a
193 MeshPy mesh.
194 """
196 def _get_section_items(section_name):
197 """Return the items in a given section.
199 Since we will add the created MeshPy objects to the mesh, we
200 delete them from the plain data storage to avoid having
201 duplicate entries.
202 """
204 if section_name in input_file:
205 return input_file.pop(section_name)
206 else:
207 return []
209 # Go through all sections that have to be converted to full MeshPy objects
210 mesh = _Mesh()
212 # Add nodes
213 if "NODE COORDS" in input_file:
214 mesh.nodes = [_Node(node["COORD"]) for node in input_file.pop("NODE COORDS")]
216 # Add elements
217 if "STRUCTURE ELEMENTS" in input_file:
218 for element in input_file.pop("STRUCTURE ELEMENTS"):
219 nodes = [
220 mesh.nodes[node_id - 1] for node_id in element["cell"]["connectivity"]
221 ]
222 mesh.elements.append(_element_from_dict(nodes=nodes, element=element))
224 # Add geometry sets
225 geometry_sets_in_sections: dict[str, dict[int, _GeometrySetNodes]] = {
226 key: {} for key in _mpy.geo
227 }
228 for section_name in input_file.sections.keys():
229 if section_name.endswith("TOPOLOGY"):
230 section_items = _get_section_items(section_name)
231 if len(section_items) > 0:
232 # Get the geometry key for this set
233 for key, value in _INPUT_FILE_MAPPINGS["geometry_sets"].items():
234 if value == section_name:
235 geometry_key = key
236 break
237 else:
238 raise ValueError(f"Could not find the set {section_name}")
239 geometry_sets_in_section = _get_yaml_geometry_sets(
240 mesh.nodes, geometry_key, section_items
241 )
242 geometry_sets_in_sections[geometry_key] = geometry_sets_in_section
243 mesh.geometry_sets[geometry_key] = list(
244 geometry_sets_in_section.values()
245 )
247 # Add boundary conditions
248 for (
249 bc_key,
250 geometry_key,
251 ), section_name in _INPUT_FILE_MAPPINGS["boundary_conditions"].items():
252 for item in _get_section_items(section_name):
253 geometry_set_id = item["E"]
254 geometry_set = geometry_sets_in_sections[geometry_key][geometry_set_id]
255 mesh.boundary_conditions.append(
256 (bc_key, geometry_key),
257 _boundary_condition_from_dict(geometry_set, bc_key, item),
258 )
260 return input_file, mesh