Coverage for src / beamme / four_c / input_file_dump_item.py: 90%
92 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-21 12:57 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-21 12:57 +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 file defines functions to dump mesh items for 4C."""
24from typing import Any as _Any
26from beamme.core.boundary_condition import BoundaryCondition as _BoundaryCondition
27from beamme.core.conf import bme as _bme
28from beamme.core.coupling import Coupling as _Coupling
29from beamme.core.element_volume import VolumeElement as _VolumeElement
30from beamme.core.geometry_set import GeometrySet as _GeometrySet
31from beamme.core.geometry_set import GeometrySetNodes as _GeometrySetNodes
32from beamme.core.node import ControlPoint as _ControlPoint
33from beamme.core.node import Node as _Node
34from beamme.core.nurbs_patch import NURBSPatch as _NURBSPatch
35from beamme.four_c.four_c_types import (
36 BeamKirchhoffParametrizationType as _BeamKirchhoffParametrizationType,
37)
38from beamme.four_c.four_c_types import BeamType as _BeamType
39from beamme.four_c.input_file_mappings import (
40 INPUT_FILE_MAPPINGS as _INPUT_FILE_MAPPINGS,
41)
44def dump_node(node):
45 """Return the representation of a node in the 4C input file."""
47 if isinstance(node, _ControlPoint):
48 return {
49 "id": node.i_global + 1,
50 "COORD": node.coordinates,
51 "data": {"type": "CP", "weight": node.weight},
52 }
53 elif isinstance(node, _Node):
54 return {
55 "id": node.i_global + 1,
56 "COORD": node.coordinates,
57 "data": {"type": "NODE"},
58 }
59 else:
60 raise TypeError(f"Got unexpected item of type {type(node)}")
63def dump_solid_element(solid_element):
64 """Return a dict with the items representing the given solid element."""
66 return {
67 "id": solid_element.i_global + 1,
68 "cell": {
69 "type": _INPUT_FILE_MAPPINGS["element_type_to_four_c_string"][
70 type(solid_element)
71 ],
72 "connectivity": solid_element.nodes,
73 },
74 "data": solid_element.data,
75 }
78def dump_coupling(coupling):
79 """Return the input file representation of the coupling condition."""
81 if isinstance(coupling.data, dict):
82 data = coupling.data
83 else:
84 # In this case we have to check which beams are connected to the node.
85 # TODO: Coupling also makes sense for different beam types, this can
86 # be implemented at some point.
87 nodes = coupling.geometry_set.get_points()
88 connected_elements = [
89 element for node in nodes for element in node.element_link
90 ]
91 element_types = {type(element) for element in connected_elements}
92 if len(element_types) > 1:
93 raise TypeError(
94 f"Expected a single connected type of beam elements, got {element_types}"
95 )
96 element_type = element_types.pop()
97 if element_type.four_c_beam_type is _BeamType.kirchhoff:
98 unique_parametrization_flags = {
99 _BeamKirchhoffParametrizationType[
100 type(element).four_c_element_data["PARAMETRIZATION"]
101 ]
102 for element in connected_elements
103 }
104 if (
105 len(unique_parametrization_flags) > 1
106 or not unique_parametrization_flags.pop()
107 == _BeamKirchhoffParametrizationType.rot
108 ):
109 raise TypeError(
110 "Couplings for Kirchhoff beams and tangent "
111 "based parametrization not yet implemented."
112 )
114 data = element_type.get_coupling_dict(coupling.data)
116 return {"E": coupling.geometry_set.i_global + 1, **data}
119def dump_geometry_set(geometry_set):
120 """Return a list with the data describing this set."""
122 # Sort nodes based on their global index
123 nodes = sorted(geometry_set.get_all_nodes(), key=lambda n: n.i_global)
125 if not nodes:
126 raise ValueError("Writing empty geometry sets is not supported")
128 return [
129 {
130 "type": "NODE",
131 "node_id": node.i_global + 1,
132 "d_type": _INPUT_FILE_MAPPINGS["geometry_sets_geometry_to_entry_name"][
133 geometry_set.geometry_type
134 ],
135 "d_id": geometry_set.i_global + 1,
136 }
137 for node in nodes
138 ]
141def dump_nurbs_patch_knotvectors(input_file, nurbs_patch) -> None:
142 """Set the knot vectors of the NURBS patch in the input file."""
144 patch_data: dict[str, _Any] = {
145 "KNOT_VECTORS": [],
146 }
148 for dir_manifold in range(nurbs_patch.get_nurbs_dimension()):
149 knotvector = nurbs_patch.knot_vectors[dir_manifold]
150 num_knots = len(knotvector)
152 # Check the type of knot vector, in case that the multiplicity of the first and last
153 # knot vectors is not p + 1, then it is a closed (periodic) knot vector, otherwise it
154 # is an open (interpolated) knot vector.
155 knotvector_type = "Interpolated"
157 for i in range(nurbs_patch.polynomial_orders[dir_manifold] - 1):
158 if (abs(knotvector[i] - knotvector[i + 1]) > _bme.eps_knot_vector) or (
159 abs(knotvector[num_knots - 2 - i] - knotvector[num_knots - 1 - i])
160 > _bme.eps_knot_vector
161 ):
162 knotvector_type = "Periodic"
163 break
165 patch_data["KNOT_VECTORS"].append(
166 {
167 "DEGREE": nurbs_patch.polynomial_orders[dir_manifold],
168 "TYPE": knotvector_type,
169 "KNOTS": [
170 knot_vector_val
171 for knot_vector_val in nurbs_patch.knot_vectors[dir_manifold]
172 ],
173 }
174 )
176 if "STRUCTURE KNOTVECTORS" in input_file:
177 # Get all existing patches in the input file - they will be added to the
178 # input file again at the end of this function. By doing it this way, the
179 # FourCIPP type converter will be applied to the current patch.
180 # This also means that we apply the type converter again already existing
181 # patches. But, with the usual number of patches and data size, this
182 # should not lead to a measurable performance impact.
183 patches = input_file.pop("STRUCTURE KNOTVECTORS")["PATCHES"]
184 else:
185 patches = []
187 patch_data["ID"] = nurbs_patch.i_nurbs_patch + 1
188 patches.append(patch_data)
189 input_file.add({"STRUCTURE KNOTVECTORS": {"PATCHES": patches}})
192def dump_nurbs_patch_elements(nurbs_patch: _NURBSPatch) -> list[dict[str, _Any]]:
193 """Return a list with all the element definitions contained in this
194 patch."""
196 if nurbs_patch.i_global is None:
197 raise ValueError(
198 "i_global is not set, make sure that the NURBS patch is added to the mesh"
199 )
201 # Check the material
202 nurbs_patch._check_material()
204 patch_elements = []
205 j = 0
207 for knot_span in nurbs_patch.get_knot_span_iterator():
208 element_cps_ids = nurbs_patch.get_ids_ctrlpts(*knot_span)
209 connectivity = [nurbs_patch.nodes[i] for i in element_cps_ids]
210 num_cp = len(connectivity)
212 patch_elements.append(
213 {
214 "id": nurbs_patch.i_global + j + 1,
215 "cell": {
216 "type": f"NURBS{num_cp}",
217 "connectivity": connectivity,
218 },
219 "data": {
220 "type": _INPUT_FILE_MAPPINGS["nurbs_type_to_default_four_c_type"][
221 type(nurbs_patch)
222 ],
223 "MAT": nurbs_patch.material,
224 **(nurbs_patch.data if nurbs_patch.data else {}),
225 },
226 }
227 )
228 j += 1
230 return patch_elements
233def dump_item_to_list(dumped_list, item) -> None:
234 """General function to dump items to a 4C input file."""
235 if hasattr(item, "dump_to_list"):
236 dumped_list.append(item.dump_to_list())
237 elif isinstance(item, _Node):
238 dumped_list.append(dump_node(item))
239 elif isinstance(item, _VolumeElement):
240 dumped_list.append(dump_solid_element(item))
241 elif isinstance(item, _GeometrySet) or isinstance(item, _GeometrySetNodes):
242 dumped_list.extend(dump_geometry_set(item))
243 elif isinstance(item, _NURBSPatch):
244 dumped_list.extend(dump_nurbs_patch_elements(item))
245 elif isinstance(item, _BoundaryCondition):
246 if item.geometry_set.i_global is None:
247 raise ValueError("i_global is not set")
248 dumped_list.append(
249 {
250 "E": item.geometry_set.i_global + 1,
251 **item.data,
252 }
253 )
254 elif isinstance(item, _Coupling):
255 dumped_list.append(dump_coupling(item))
256 else:
257 raise TypeError(f"Could not dump {item}")
260def dump_item_to_section(input_file, item) -> None:
261 """This function dumps information of mesh items to general input file
262 sections, e.g., knotvectors for NURBS."""
263 if isinstance(item, _NURBSPatch):
264 dump_nurbs_patch_knotvectors(input_file, item)