Coverage for src/beamme/four_c/input_file_dump_item.py: 91%
92 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-29 11:30 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-29 11:30 +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.core.nurbs_patch import NURBSSurface as _NURBSSurface
36from beamme.core.nurbs_patch import NURBSVolume as _NURBSVolume
37from beamme.four_c.four_c_types import BeamType as _BeamType
38from beamme.four_c.input_file_mappings import (
39 INPUT_FILE_MAPPINGS as _INPUT_FILE_MAPPINGS,
40)
43def dump_node(node):
44 """Return the representation of a node in the 4C input file."""
46 if isinstance(node, _ControlPoint):
47 return {
48 "id": node.i_global + 1,
49 "COORD": node.coordinates,
50 "data": {"type": "CP", "weight": node.weight},
51 }
52 elif isinstance(node, _Node):
53 return {
54 "id": node.i_global + 1,
55 "COORD": node.coordinates,
56 "data": {"type": "NODE"},
57 }
58 else:
59 raise TypeError(f"Got unexpected item of type {type(node)}")
62def dump_solid_element(solid_element):
63 """Return a dict with the items representing the given solid element."""
65 return {
66 "id": solid_element.i_global + 1,
67 "cell": {
68 "type": _INPUT_FILE_MAPPINGS["element_type_to_four_c_string"][
69 type(solid_element)
70 ],
71 "connectivity": solid_element.nodes,
72 },
73 "data": solid_element.data,
74 }
77def dump_coupling(coupling):
78 """Return the input file representation of the coupling condition."""
80 if isinstance(coupling.data, dict):
81 data = coupling.data
82 else:
83 # In this case we have to check which beams are connected to the node.
84 # TODO: Coupling also makes sense for different beam types, this can
85 # be implemented at some point.
86 nodes = coupling.geometry_set.get_points()
87 connected_elements = [
88 element for node in nodes for element in node.element_link
89 ]
90 element_types = {type(element) for element in connected_elements}
91 if len(element_types) > 1:
92 raise TypeError(
93 f"Expected a single connected type of beam elements, got {element_types}"
94 )
95 element_type = element_types.pop()
96 if element_type.four_c_beam_type is _BeamType.kirchhoff:
97 rotvec = {
98 type(element).four_c_element_data["ROTVEC"]
99 for element in connected_elements
100 }
101 if len(rotvec) > 1 or not rotvec.pop():
102 raise TypeError(
103 "Couplings for Kirchhoff beams and rotvec==False not yet implemented."
104 )
106 data = element_type.get_coupling_dict(coupling.data)
108 return {"E": coupling.geometry_set.i_global + 1, **data}
111def dump_geometry_set(geometry_set):
112 """Return a list with the data describing this set."""
114 # Sort nodes based on their global index
115 nodes = sorted(geometry_set.get_all_nodes(), key=lambda n: n.i_global)
117 if not nodes:
118 raise ValueError("Writing empty geometry sets is not supported")
120 return [
121 {
122 "type": "NODE",
123 "node_id": node.i_global + 1,
124 "d_type": _INPUT_FILE_MAPPINGS["geometry_sets_geometry_to_entry_name"][
125 geometry_set.geometry_type
126 ],
127 "d_id": geometry_set.i_global + 1,
128 }
129 for node in nodes
130 ]
133def dump_nurbs_patch_knotvectors(input_file, nurbs_patch) -> None:
134 """Set the knot vectors of the NURBS patch in the input file."""
136 patch_data: dict[str, _Any] = {
137 "KNOT_VECTORS": [],
138 }
140 for dir_manifold in range(nurbs_patch.get_nurbs_dimension()):
141 knotvector = nurbs_patch.knot_vectors[dir_manifold]
142 num_knots = len(knotvector)
144 # Check the type of knot vector, in case that the multiplicity of the first and last
145 # knot vectors is not p + 1, then it is a closed (periodic) knot vector, otherwise it
146 # is an open (interpolated) knot vector.
147 knotvector_type = "Interpolated"
149 for i in range(nurbs_patch.polynomial_orders[dir_manifold] - 1):
150 if (abs(knotvector[i] - knotvector[i + 1]) > _bme.eps_knot_vector) or (
151 abs(knotvector[num_knots - 2 - i] - knotvector[num_knots - 1 - i])
152 > _bme.eps_knot_vector
153 ):
154 knotvector_type = "Periodic"
155 break
157 patch_data["KNOT_VECTORS"].append(
158 {
159 "DEGREE": nurbs_patch.polynomial_orders[dir_manifold],
160 "TYPE": knotvector_type,
161 "KNOTS": [
162 knot_vector_val
163 for knot_vector_val in nurbs_patch.knot_vectors[dir_manifold]
164 ],
165 }
166 )
168 if "STRUCTURE KNOTVECTORS" in input_file:
169 # Get all existing patches in the input file - they will be added to the
170 # input file again at the end of this function. By doing it this way, the
171 # FourCIPP type converter will be applied to the current patch.
172 # This also means that we apply the type converter again already existing
173 # patches. But, with the usual number of patches and data size, this
174 # should not lead to a measurable performance impact.
175 patches = input_file.pop("STRUCTURE KNOTVECTORS")["PATCHES"]
176 else:
177 patches = []
179 patch_data["ID"] = nurbs_patch.i_nurbs_patch + 1
180 patches.append(patch_data)
181 input_file.add({"STRUCTURE KNOTVECTORS": {"PATCHES": patches}})
184def dump_nurbs_patch_elements(nurbs_patch):
185 """Return a list with all the element definitions contained in this
186 patch."""
188 nurbs_type_to_default_four_c_type = {
189 _NURBSSurface: "WALLNURBS",
190 _NURBSVolume: "SOLID",
191 }
193 # Check the material
194 nurbs_patch._check_material()
196 patch_elements = []
197 j = 0
199 for knot_span in nurbs_patch._get_knot_span_iterator(): # TODO better name for this
200 element_cps_ids = nurbs_patch._get_ids_ctrlpts(*knot_span)
201 connectivity = [nurbs_patch.nodes[i] for i in element_cps_ids]
202 num_cp = len(connectivity)
204 patch_elements.append(
205 {
206 "id": nurbs_patch.i_global + j + 1,
207 "cell": {
208 "type": f"NURBS{num_cp}",
209 "connectivity": connectivity,
210 },
211 "data": {
212 "type": nurbs_type_to_default_four_c_type[type(nurbs_patch)],
213 "MAT": nurbs_patch.material,
214 **(nurbs_patch.data if nurbs_patch.data else {}),
215 },
216 }
217 )
218 j += 1
220 return patch_elements
223def dump_item_to_list(dumped_list, item) -> None:
224 """General function to dump items to a 4C input file."""
225 if hasattr(item, "dump_to_list"):
226 dumped_list.append(item.dump_to_list())
227 elif isinstance(item, _Node):
228 dumped_list.append(dump_node(item))
229 elif isinstance(item, _VolumeElement):
230 dumped_list.append(dump_solid_element(item))
231 elif isinstance(item, _GeometrySet) or isinstance(item, _GeometrySetNodes):
232 dumped_list.extend(dump_geometry_set(item))
233 elif isinstance(item, _NURBSPatch):
234 dumped_list.extend(dump_nurbs_patch_elements(item))
235 elif isinstance(item, _BoundaryCondition):
236 if item.geometry_set.i_global is None:
237 raise ValueError("i_global is not set")
238 dumped_list.append(
239 {
240 "E": item.geometry_set.i_global + 1,
241 **item.data,
242 }
243 )
244 elif isinstance(item, _Coupling):
245 dumped_list.append(dump_coupling(item))
246 else:
247 raise TypeError(f"Could not dump {item}")
250def dump_item_to_section(input_file, item) -> None:
251 """This function dumps information of mesh items to general input file
252 sections, e.g., knotvectors for NURBS."""
253 if isinstance(item, _NURBSPatch):
254 dump_nurbs_patch_knotvectors(input_file, item)