Coverage for src / beamme / four_c / model_importer.py: 93%
76 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-06 06:24 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-06 06:24 +0000
1# The MIT License (MIT)
2#
3# Copyright (c) 2018-2025 BeamMe 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 collections import defaultdict as _defaultdict
25from pathlib import Path as _Path
26from typing import Tuple as _Tuple
28from beamme.core.boundary_condition import BoundaryCondition as _BoundaryCondition
29from beamme.core.boundary_condition import (
30 BoundaryConditionBase as _BoundaryConditionBase,
31)
32from beamme.core.conf import bme as _bme
33from beamme.core.coupling import Coupling as _Coupling
34from beamme.core.geometry_set import GeometrySetNodes as _GeometrySetNodes
35from beamme.core.mesh import Mesh as _Mesh
36from beamme.core.node import Node as _Node
37from beamme.four_c.input_file import InputFile as _InputFile
38from beamme.four_c.input_file_mappings import (
39 INPUT_FILE_MAPPINGS as _INPUT_FILE_MAPPINGS,
40)
41from beamme.four_c.material import MaterialSolid as _MaterialSolid
42from beamme.utils.environment import cubitpy_is_available as _cubitpy_is_available
44if _cubitpy_is_available():
45 from cubitpy.cubit_to_fourc_input import (
46 get_input_file_with_mesh as _get_input_file_with_mesh,
47 )
50def import_cubitpy_model(
51 cubit, convert_input_to_mesh: bool = False
52) -> _Tuple[_InputFile, _Mesh]:
53 """Convert a CubitPy instance to a BeamMe InputFile.
55 Args:
56 cubit (CubitPy): An instance of a cubit model.
57 convert_input_to_mesh: If this is false, the cubit model will be
58 converted to plain FourCIPP input data. If this is true, an input
59 file with all the parameters will be returned and a mesh which
60 contains the mesh information from cubit converted to BeamMe
61 objects.
63 Returns:
64 A tuple with the input file and the mesh. If convert_input_to_mesh is
65 False, the mesh will be empty. Note that the input sections which are
66 converted to a BeamMe mesh are removed from the input file object.
67 """
69 input_file = _InputFile()
70 input_file.add(_get_input_file_with_mesh(cubit).sections)
72 if convert_input_to_mesh:
73 return _extract_mesh_sections(input_file)
74 else:
75 return input_file, _Mesh()
78def import_four_c_model(
79 input_file_path: _Path, convert_input_to_mesh: bool = False
80) -> _Tuple[_InputFile, _Mesh]:
81 """Import an existing 4C input file and optionally convert it into a BeamMe
82 mesh.
84 Args:
85 input_file_path: A file path to an existing 4C input file that will be
86 imported.
87 convert_input_to_mesh: If True, the input file will be converted to a
88 BeamMe mesh.
90 Returns:
91 A tuple with the input file and the mesh. If convert_input_to_mesh is
92 False, the mesh will be empty. Note that the input sections which are
93 converted to a BeamMe mesh are removed from the input file object.
94 """
96 input_file = _InputFile().from_4C_yaml(input_file_path=input_file_path)
98 if convert_input_to_mesh:
99 return _extract_mesh_sections(input_file)
100 else:
101 return input_file, _Mesh()
104def _extract_mesh_sections(input_file: _InputFile) -> _Tuple[_InputFile, _Mesh]:
105 """Convert an InputFile into a native mesh by translating sections like
106 materials, nodes, elements, geometry sets, and boundary conditions.
108 Args:
109 input_file: The input file containing 4C sections.
110 Returns:
111 A tuple (input_file, mesh). The input_file is modified in place to remove
112 sections converted into BeamMe objects.
113 """
115 # function to pop sections from the input file
116 _pop_section = lambda name: input_file.pop(name, [])
118 # convert all sections to native objects and add to a new mesh
119 mesh = _Mesh()
121 # extract materials
122 material_id_map = {}
124 for mat in _pop_section("MATERIALS"):
125 mat_id = mat.pop("MAT")
126 if len(mat) != 1:
127 raise ValueError(
128 f"Could not convert the material data `{mat}` to a BeamMe material!"
129 )
130 mat_name, mat_data = list(mat.items())[0]
131 material = _MaterialSolid(material_string=mat_name, data=mat_data)
132 mesh.add(material)
133 material_id_map[mat_id] = material
135 # extract nodes
136 mesh.nodes = [_Node(node["COORD"]) for node in _pop_section("NODE COORDS")]
138 # extract elements
139 for input_element in _pop_section("STRUCTURE ELEMENTS"):
140 if (
141 input_element["cell"]["type"]
142 not in _INPUT_FILE_MAPPINGS["element_four_c_string_to_type"]
143 ):
144 raise TypeError(
145 f"Could not create a BeamMe element for `{input_element['data']['type']}` `{input_element['cell']['type']}`!"
146 )
147 nodes = [mesh.nodes[i - 1] for i in input_element["cell"]["connectivity"]]
148 element_class = _INPUT_FILE_MAPPINGS["element_four_c_string_to_type"][
149 input_element["cell"]["type"]
150 ]
151 element = element_class(nodes=nodes, data=input_element["data"])
152 if "MAT" in element.data:
153 element.data["MAT"] = material_id_map[element.data["MAT"]]
154 mesh.elements.append(element)
156 # extract geometry sets
157 geometry_sets_in_sections: dict[str, dict[int, _GeometrySetNodes]] = _defaultdict(
158 dict
159 )
161 for section_name in input_file.sections:
162 if not section_name.endswith("TOPOLOGY"):
163 continue
165 items = _pop_section(section_name)
166 if not items:
167 continue
169 # Find geometry type for this section
170 try:
171 geometry_type = _INPUT_FILE_MAPPINGS[
172 "geometry_sets_condition_to_geometry_name"
173 ][section_name]
174 except ValueError as e:
175 raise ValueError(f"Unknown geometry section: {section_name}") from e
177 # Extract geometry set indices
178 geom_dict: dict[int, list[int]] = _defaultdict(list)
179 for entry in items:
180 geom_dict[entry["d_id"]].append(entry["node_id"] - 1)
182 geometry_sets_in_sections[geometry_type] = {
183 gid: _GeometrySetNodes(geometry_type, nodes=[mesh.nodes[i] for i in ids])
184 for gid, ids in geom_dict.items()
185 }
187 mesh.geometry_sets[geometry_type] = list(
188 geometry_sets_in_sections[geometry_type].values()
189 )
191 # extract boundary conditions
192 _standard_bc_types = (
193 _bme.bc.dirichlet,
194 _bme.bc.neumann,
195 _bme.bc.locsys,
196 _bme.bc.beam_to_solid_surface_meshtying,
197 _bme.bc.beam_to_solid_surface_contact,
198 _bme.bc.beam_to_solid_volume_meshtying,
199 )
201 for (bc_key, geometry_type), section_name in _INPUT_FILE_MAPPINGS[
202 "boundary_conditions"
203 ].items():
204 for bc_data in _pop_section(section_name):
205 geometry_set = geometry_sets_in_sections[geometry_type][bc_data.pop("E")]
207 bc_obj: _BoundaryConditionBase
209 if bc_key in _standard_bc_types or isinstance(bc_key, str):
210 bc_obj = _BoundaryCondition(geometry_set, bc_data, bc_type=bc_key)
211 elif bc_key is _bme.bc.point_coupling:
212 bc_obj = _Coupling(
213 geometry_set, bc_key, bc_data, check_overlapping_nodes=False
214 )
215 else:
216 raise ValueError(f"Unexpected boundary condition: {bc_key}")
218 mesh.boundary_conditions.append((bc_key, geometry_type), bc_obj)
220 return input_file, mesh