beamme.four_c.model_importer

This module contains functions to load and parse existing 4C input files.

  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."""
 23
 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
 29
 30import beamme.core.conf as _conf
 31from beamme.core.boundary_condition import BoundaryCondition as _BoundaryCondition
 32from beamme.core.boundary_condition import (
 33    BoundaryConditionBase as _BoundaryConditionBase,
 34)
 35from beamme.core.conf import mpy as _mpy
 36from beamme.core.coupling import Coupling as _Coupling
 37from beamme.core.element_volume import VolumeHEX8 as _VolumeHEX8
 38from beamme.core.element_volume import VolumeHEX20 as _VolumeHEX20
 39from beamme.core.element_volume import VolumeHEX27 as _VolumeHEX27
 40from beamme.core.element_volume import VolumeTET4 as _VolumeTET4
 41from beamme.core.element_volume import VolumeTET10 as _VolumeTET10
 42from beamme.core.element_volume import VolumeWEDGE6 as _VolumeWEDGE6
 43from beamme.core.geometry_set import GeometrySetNodes as _GeometrySetNodes
 44from beamme.core.mesh import Mesh as _Mesh
 45from beamme.core.node import Node as _Node
 46from beamme.four_c.element_volume import SolidRigidSphere as _SolidRigidSphere
 47from beamme.four_c.input_file import InputFile as _InputFile
 48from beamme.four_c.input_file import (
 49    get_geometry_set_indices_from_section as _get_geometry_set_indices_from_section,
 50)
 51from beamme.four_c.input_file_mappings import (
 52    INPUT_FILE_MAPPINGS as _INPUT_FILE_MAPPINGS,
 53)
 54from beamme.utils.environment import cubitpy_is_available as _cubitpy_is_available
 55
 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    )
 60
 61
 62def import_cubitpy_model(
 63    cubit, convert_input_to_mesh: bool = False
 64) -> _Tuple[_InputFile, _Mesh]:
 65    """Convert a CubitPy instance to a BeamMe InputFile.
 66
 67    Args:
 68        cubit (CubitPy): An instance of a cubit model.
 69        convert_input_to_mesh: If this is false, the cubit model will be
 70            converted to plain FourCIPP input data. If this is true, an input
 71            file with all the parameters will be returned and a mesh which
 72            contains the mesh information from cubit converted to BeamMe
 73            objects.
 74
 75    Returns:
 76        A tuple with the input file and the mesh. If convert_input_to_mesh is
 77        False, the mesh will be empty. Note that the input sections which are
 78        converted to a BeamMe mesh are removed from the input file object.
 79    """
 80
 81    input_file = _InputFile(sections=_get_input_file_with_mesh(cubit).sections)
 82
 83    if convert_input_to_mesh:
 84        return _extract_mesh_sections(input_file)
 85    else:
 86        return input_file, _Mesh()
 87
 88
 89def import_four_c_model(
 90    input_file_path: _Path, convert_input_to_mesh: bool = False
 91) -> _Tuple[_InputFile, _Mesh]:
 92    """Import an existing 4C input file and optionally convert it into a BeamMe
 93    mesh.
 94
 95    Args:
 96        input_file_path: A file path to an existing 4C input file that will be
 97            imported.
 98        convert_input_to_mesh: If True, the input file will be converted to a
 99            BeamMe mesh.
100
101    Returns:
102        A tuple with the input file and the mesh. If convert_input_to_mesh is
103        False, the mesh will be empty. Note that the input sections which are
104        converted to a BeamMe mesh are removed from the input file object.
105    """
106
107    input_file = _InputFile().from_4C_yaml(input_file_path=input_file_path)
108
109    if convert_input_to_mesh:
110        return _extract_mesh_sections(input_file)
111    else:
112        return input_file, _Mesh()
113
114
115def _element_from_dict(nodes: _List[_Node], element: dict):
116    """Create a solid element from a dictionary from a 4C input file.
117
118    Args:
119        nodes: A list of nodes that are part of the element.
120        element: A dictionary with the element data.
121    Returns:
122        A solid element object.
123    """
124
125    # Depending on the number of nodes chose which solid element to return.
126    # TODO reuse element_type_to_four_c_string from beamme.core.element_volume
127    element_type = {
128        "HEX8": _VolumeHEX8,
129        "HEX20": _VolumeHEX20,
130        "HEX27": _VolumeHEX27,
131        "TET4": _VolumeTET4,
132        "TET10": _VolumeTET10,
133        "WEDGE6": _VolumeWEDGE6,
134        "POINT1": _SolidRigidSphere,
135    }
136
137    if element["cell"]["type"] not in element_type:
138        raise TypeError(
139            f"Could not create a BeamMe element for {element['data']['type']} {element['cell']['type']}!"
140        )
141
142    return element_type[element["cell"]["type"]](nodes=nodes, data=element["data"])
143
144
145def _boundary_condition_from_dict(
146    geometry_set: _GeometrySetNodes,
147    bc_key: _Union[_conf.BoundaryCondition, str],
148    data: _Dict,
149) -> _BoundaryConditionBase:
150    """This function acts as a factory and creates the correct boundary
151    condition object from a dictionary parsed from an input file."""
152
153    del data["E"]
154
155    if bc_key in (
156        _mpy.bc.dirichlet,
157        _mpy.bc.neumann,
158        _mpy.bc.locsys,
159        _mpy.bc.beam_to_solid_surface_meshtying,
160        _mpy.bc.beam_to_solid_surface_contact,
161        _mpy.bc.beam_to_solid_volume_meshtying,
162    ) or isinstance(bc_key, str):
163        return _BoundaryCondition(geometry_set, data, bc_type=bc_key)
164    elif bc_key is _mpy.bc.point_coupling:
165        return _Coupling(geometry_set, bc_key, data, check_overlapping_nodes=False)
166    else:
167        raise ValueError("Got unexpected boundary condition!")
168
169
170def _get_yaml_geometry_sets(
171    nodes: _List[_Node], geometry_key: _conf.Geometry, section_list: _List
172) -> _Dict[int, _GeometrySetNodes]:
173    """Add sets of points, lines, surfaces or volumes to the object."""
174
175    # Create the individual geometry sets
176    geometry_set_dict = _get_geometry_set_indices_from_section(section_list)
177    geometry_sets_in_this_section = {}
178    for geometry_set_id, node_ids in geometry_set_dict.items():
179        geometry_sets_in_this_section[geometry_set_id] = _GeometrySetNodes(
180            geometry_key, nodes=[nodes[node_id] for node_id in node_ids]
181        )
182    return geometry_sets_in_this_section
183
184
185def _extract_mesh_sections(input_file: _InputFile) -> _Tuple[_InputFile, _Mesh]:
186    """Convert an existing input file to a BeamMe mesh with mesh items, e.g.,
187    nodes, elements, element sets, node sets, boundary conditions, materials.
188
189    Args:
190        input_file: The input file object that contains the sections to be
191            converted to a BeamMe mesh.
192    Returns:
193        A tuple with the input file and the mesh. The input file will be
194            modified to remove the sections that have been converted to a
195            BeamMe mesh.
196    """
197
198    def _get_section_items(section_name):
199        """Return the items in a given section.
200
201        Since we will add the created BeamMe objects to the mesh, we
202        delete them from the plain data storage to avoid having
203        duplicate entries.
204        """
205
206        if section_name in input_file:
207            return input_file.pop(section_name)
208        else:
209            return []
210
211    # Go through all sections that have to be converted to full BeamMe objects
212    mesh = _Mesh()
213
214    # Add nodes
215    if "NODE COORDS" in input_file:
216        mesh.nodes = [_Node(node["COORD"]) for node in input_file.pop("NODE COORDS")]
217
218    # Add elements
219    if "STRUCTURE ELEMENTS" in input_file:
220        for element in input_file.pop("STRUCTURE ELEMENTS"):
221            nodes = [
222                mesh.nodes[node_id - 1] for node_id in element["cell"]["connectivity"]
223            ]
224            mesh.elements.append(_element_from_dict(nodes=nodes, element=element))
225
226    # Add geometry sets
227    geometry_sets_in_sections: dict[str, dict[int, _GeometrySetNodes]] = {
228        key: {} for key in _mpy.geo
229    }
230    for section_name in input_file.sections.keys():
231        if section_name.endswith("TOPOLOGY"):
232            section_items = _get_section_items(section_name)
233            if len(section_items) > 0:
234                # Get the geometry key for this set
235                for key, value in _INPUT_FILE_MAPPINGS["geometry_sets"].items():
236                    if value == section_name:
237                        geometry_key = key
238                        break
239                else:
240                    raise ValueError(f"Could not find the set {section_name}")
241                geometry_sets_in_section = _get_yaml_geometry_sets(
242                    mesh.nodes, geometry_key, section_items
243                )
244                geometry_sets_in_sections[geometry_key] = geometry_sets_in_section
245                mesh.geometry_sets[geometry_key] = list(
246                    geometry_sets_in_section.values()
247                )
248
249    # Add boundary conditions
250    for (
251        bc_key,
252        geometry_key,
253    ), section_name in _INPUT_FILE_MAPPINGS["boundary_conditions"].items():
254        for item in _get_section_items(section_name):
255            geometry_set_id = item["E"]
256            geometry_set = geometry_sets_in_sections[geometry_key][geometry_set_id]
257            mesh.boundary_conditions.append(
258                (bc_key, geometry_key),
259                _boundary_condition_from_dict(geometry_set, bc_key, item),
260            )
261
262    return input_file, mesh
def import_cubitpy_model( cubit, convert_input_to_mesh: bool = False) -> Tuple[beamme.four_c.input_file.InputFile, beamme.core.mesh.Mesh]:
63def import_cubitpy_model(
64    cubit, convert_input_to_mesh: bool = False
65) -> _Tuple[_InputFile, _Mesh]:
66    """Convert a CubitPy instance to a BeamMe InputFile.
67
68    Args:
69        cubit (CubitPy): An instance of a cubit model.
70        convert_input_to_mesh: If this is false, the cubit model will be
71            converted to plain FourCIPP input data. If this is true, an input
72            file with all the parameters will be returned and a mesh which
73            contains the mesh information from cubit converted to BeamMe
74            objects.
75
76    Returns:
77        A tuple with the input file and the mesh. If convert_input_to_mesh is
78        False, the mesh will be empty. Note that the input sections which are
79        converted to a BeamMe mesh are removed from the input file object.
80    """
81
82    input_file = _InputFile(sections=_get_input_file_with_mesh(cubit).sections)
83
84    if convert_input_to_mesh:
85        return _extract_mesh_sections(input_file)
86    else:
87        return input_file, _Mesh()

Convert a CubitPy instance to a BeamMe InputFile.

Arguments:
  • cubit (CubitPy): An instance of a cubit model.
  • convert_input_to_mesh: If this is false, the cubit model will be converted to plain FourCIPP input data. If this is true, an input file with all the parameters will be returned and a mesh which contains the mesh information from cubit converted to BeamMe objects.
Returns:

A tuple with the input file and the mesh. If convert_input_to_mesh is False, the mesh will be empty. Note that the input sections which are converted to a BeamMe mesh are removed from the input file object.

def import_four_c_model( input_file_path: pathlib.Path, convert_input_to_mesh: bool = False) -> Tuple[beamme.four_c.input_file.InputFile, beamme.core.mesh.Mesh]:
 90def import_four_c_model(
 91    input_file_path: _Path, convert_input_to_mesh: bool = False
 92) -> _Tuple[_InputFile, _Mesh]:
 93    """Import an existing 4C input file and optionally convert it into a BeamMe
 94    mesh.
 95
 96    Args:
 97        input_file_path: A file path to an existing 4C input file that will be
 98            imported.
 99        convert_input_to_mesh: If True, the input file will be converted to a
100            BeamMe mesh.
101
102    Returns:
103        A tuple with the input file and the mesh. If convert_input_to_mesh is
104        False, the mesh will be empty. Note that the input sections which are
105        converted to a BeamMe mesh are removed from the input file object.
106    """
107
108    input_file = _InputFile().from_4C_yaml(input_file_path=input_file_path)
109
110    if convert_input_to_mesh:
111        return _extract_mesh_sections(input_file)
112    else:
113        return input_file, _Mesh()

Import an existing 4C input file and optionally convert it into a BeamMe mesh.

Arguments:
  • input_file_path: A file path to an existing 4C input file that will be imported.
  • convert_input_to_mesh: If True, the input file will be converted to a BeamMe mesh.
Returns:

A tuple with the input file and the mesh. If convert_input_to_mesh is False, the mesh will be empty. Note that the input sections which are converted to a BeamMe mesh are removed from the input file object.