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 collections import defaultdict as _defaultdict
 25from pathlib import Path as _Path
 26from typing import Tuple as _Tuple
 27
 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
 43
 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    )
 48
 49
 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.
 54
 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.
 62
 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    """
 68
 69    input_file = _InputFile()
 70    input_file.add(_get_input_file_with_mesh(cubit).sections)
 71
 72    if convert_input_to_mesh:
 73        return _extract_mesh_sections(input_file)
 74    else:
 75        return input_file, _Mesh()
 76
 77
 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.
 83
 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.
 89
 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    """
 95
 96    input_file = _InputFile().from_4C_yaml(input_file_path=input_file_path)
 97
 98    if convert_input_to_mesh:
 99        return _extract_mesh_sections(input_file)
100    else:
101        return input_file, _Mesh()
102
103
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.
107
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    """
114
115    # function to pop sections from the input file
116    _pop_section = lambda name: input_file.pop(name, [])
117
118    # convert all sections to native objects and add to a new mesh
119    mesh = _Mesh()
120
121    # extract materials
122    material_id_map_all = {}
123
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        material_id_map_all[mat_id] = material
133
134    nested_materials = set()
135    for material in material_id_map_all.values():
136        # Loop over each material and link nested materials. Also, mark nested materials
137        # as they will not be added to the mesh.
138        material_ids = material.data.get("MATIDS", [])
139        for i_sub_material, material_id in enumerate(material_ids):
140            try:
141                material_ids[i_sub_material] = material_id_map_all[material_id]
142            except KeyError as key_exception:
143                raise KeyError(
144                    f"Material ID {material_id} not in material_id_map_all (available "
145                    f"IDs: {list(material_id_map_all.keys())})."
146                ) from key_exception
147            nested_materials.add(material_id)
148
149    # Get a map of all non-nested materials. We assume that only those are used as
150    # materials for elements. Also, add the non-nested materials to the mesh.
151    material_id_map = {
152        key: val
153        for key, val in material_id_map_all.items()
154        if key not in nested_materials
155    }
156    mesh.materials.extend(material_id_map.values())
157
158    # extract nodes
159    mesh.nodes = [_Node(node["COORD"]) for node in _pop_section("NODE COORDS")]
160
161    # extract elements
162    for input_element in _pop_section("STRUCTURE ELEMENTS"):
163        if (
164            input_element["cell"]["type"]
165            not in _INPUT_FILE_MAPPINGS["element_four_c_string_to_type"]
166        ):
167            raise TypeError(
168                f"Could not create a BeamMe element for `{input_element['data']['type']}` `{input_element['cell']['type']}`!"
169            )
170        nodes = [mesh.nodes[i - 1] for i in input_element["cell"]["connectivity"]]
171        element_class = _INPUT_FILE_MAPPINGS["element_four_c_string_to_type"][
172            input_element["cell"]["type"]
173        ]
174        element = element_class(nodes=nodes, data=input_element["data"])
175        if "MAT" in element.data:
176            element.data["MAT"] = material_id_map[element.data["MAT"]]
177        mesh.elements.append(element)
178
179    # extract geometry sets
180    geometry_sets_in_sections: dict[str, dict[int, _GeometrySetNodes]] = _defaultdict(
181        dict
182    )
183
184    for section_name in input_file.sections:
185        if not section_name.endswith("TOPOLOGY"):
186            continue
187
188        items = _pop_section(section_name)
189        if not items:
190            continue
191
192        # Find geometry type for this section
193        try:
194            geometry_type = _INPUT_FILE_MAPPINGS[
195                "geometry_sets_condition_to_geometry_name"
196            ][section_name]
197        except ValueError as e:
198            raise ValueError(f"Unknown geometry section: {section_name}") from e
199
200        # Extract geometry set indices
201        geom_dict: dict[int, list[int]] = _defaultdict(list)
202        for entry in items:
203            geom_dict[entry["d_id"]].append(entry["node_id"] - 1)
204
205        geometry_sets_in_sections[geometry_type] = {
206            gid: _GeometrySetNodes(geometry_type, nodes=[mesh.nodes[i] for i in ids])
207            for gid, ids in geom_dict.items()
208        }
209
210        mesh.geometry_sets[geometry_type] = list(
211            geometry_sets_in_sections[geometry_type].values()
212        )
213
214    # extract boundary conditions
215    _standard_bc_types = (
216        _bme.bc.dirichlet,
217        _bme.bc.neumann,
218        _bme.bc.locsys,
219        _bme.bc.beam_to_solid_surface_meshtying,
220        _bme.bc.beam_to_solid_surface_contact,
221        _bme.bc.beam_to_solid_volume_meshtying,
222    )
223
224    for (bc_key, geometry_type), section_name in _INPUT_FILE_MAPPINGS[
225        "boundary_conditions"
226    ].items():
227        for bc_data in _pop_section(section_name):
228            geometry_set = geometry_sets_in_sections[geometry_type][bc_data.pop("E")]
229
230            bc_obj: _BoundaryConditionBase
231
232            if bc_key in _standard_bc_types or isinstance(bc_key, str):
233                bc_obj = _BoundaryCondition(geometry_set, bc_data, bc_type=bc_key)
234            elif bc_key is _bme.bc.point_coupling:
235                bc_obj = _Coupling(
236                    geometry_set, bc_key, bc_data, check_overlapping_nodes=False
237                )
238            else:
239                raise ValueError(f"Unexpected boundary condition: {bc_key}")
240
241            mesh.boundary_conditions.append((bc_key, geometry_type), bc_obj)
242
243    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]:
51def import_cubitpy_model(
52    cubit, convert_input_to_mesh: bool = False
53) -> _Tuple[_InputFile, _Mesh]:
54    """Convert a CubitPy instance to a BeamMe InputFile.
55
56    Args:
57        cubit (CubitPy): An instance of a cubit model.
58        convert_input_to_mesh: If this is false, the cubit model will be
59            converted to plain FourCIPP input data. If this is true, an input
60            file with all the parameters will be returned and a mesh which
61            contains the mesh information from cubit converted to BeamMe
62            objects.
63
64    Returns:
65        A tuple with the input file and the mesh. If convert_input_to_mesh is
66        False, the mesh will be empty. Note that the input sections which are
67        converted to a BeamMe mesh are removed from the input file object.
68    """
69
70    input_file = _InputFile()
71    input_file.add(_get_input_file_with_mesh(cubit).sections)
72
73    if convert_input_to_mesh:
74        return _extract_mesh_sections(input_file)
75    else:
76        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]:
 79def import_four_c_model(
 80    input_file_path: _Path, convert_input_to_mesh: bool = False
 81) -> _Tuple[_InputFile, _Mesh]:
 82    """Import an existing 4C input file and optionally convert it into a BeamMe
 83    mesh.
 84
 85    Args:
 86        input_file_path: A file path to an existing 4C input file that will be
 87            imported.
 88        convert_input_to_mesh: If True, the input file will be converted to a
 89            BeamMe mesh.
 90
 91    Returns:
 92        A tuple with the input file and the mesh. If convert_input_to_mesh is
 93        False, the mesh will be empty. Note that the input sections which are
 94        converted to a BeamMe mesh are removed from the input file object.
 95    """
 96
 97    input_file = _InputFile().from_4C_yaml(input_file_path=input_file_path)
 98
 99    if convert_input_to_mesh:
100        return _extract_mesh_sections(input_file)
101    else:
102        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.