Debian Codegraph @

pyvista/core/utilities/_frd.py

raw
1 """CalculiX FRD file parser for PyVista."""
2
3 from __future__ import annotations
4
5 import contextlib
6 from dataclasses import dataclass
7 from dataclasses import field
8 from enum import Enum
9 from enum import IntEnum
10 import pathlib
11 import re
12 from typing import TYPE_CHECKING
13 from typing import Any
14
15 import numpy as np
16
17 import pyvista as pv
18 from pyvista.core.celltype import CellType
19
20 if TYPE_CHECKING:
21 from pyvista import UnstructuredGrid
22
23
24 class FRDBlock(Enum):
25 """CalculiX FRD block types."""
26
27 NODES = '2C'
28 ELEMENTS = '3C'
29 RESULTS = '100'
30
31
32 class CGXRecord(IntEnum):
33 """CGX Record Types.
34
35 Source https://www.dhondt.de/cgx_2.23.pdf (11 Result Format, page 144).
36 """
37
38 NODAL_VALUES = -1
39 ELEMENT_FACES = -2
40 END_OF_BLOCK = -3
41 ATTRIBUTE_HEADER = -4
42 COMPONENT_DEFINITION = -5
43
44
45 class FRDElementType(IntEnum):
46 """CalculiX FRD element types."""
47
48 HE8 = 1
49 PE6 = 2
50 TE4 = 3
51 HE20 = 4
52 PE15 = 5
53 TE10 = 6
54 TR3 = 7
55 TR6 = 8
56 QU4 = 9
57 QU8 = 10
58 BE2 = 11
59 BE3 = 12
60
61
62 # CalculiX element type -> VTK cell type
63 CCX_TO_VTK_TYPE: dict[FRDElementType, CellType] = {
64 FRDElementType.HE8: CellType.HEXAHEDRON,
65 FRDElementType.PE6: CellType.WEDGE,
66 FRDElementType.TE4: CellType.TETRA,
67 FRDElementType.HE20: CellType.QUADRATIC_HEXAHEDRON,
68 FRDElementType.PE15: CellType.QUADRATIC_WEDGE,
69 FRDElementType.TE10: CellType.QUADRATIC_TETRA,
70 FRDElementType.TR3: CellType.TRIANGLE,
71 FRDElementType.TR6: CellType.QUADRATIC_TRIANGLE,
72 FRDElementType.QU4: CellType.QUAD,
73 FRDElementType.QU8: CellType.QUADRATIC_QUAD,
74 FRDElementType.BE2: CellType.LINE,
75 FRDElementType.BE3: CellType.QUADRATIC_EDGE,
76 }
77
78 # Results hierarchy: step_time -> result_name -> node_id -> values
79 NodeResultData = dict[int, list[float]]
80 StepBucket = dict[str, NodeResultData]
81 ResultsByStep = dict[float, StepBucket]
82
83
84 class _LineTrackingStream:
85 """Wrap a file-like iterator to track line numbers automatically."""
86
87 def __init__(self, lines: Any) -> None:
88 self._lines = iter(lines)
89 self.line_number = 0
90
91 def __iter__(self) -> _LineTrackingStream:
92 return self
93
94 def __next__(self) -> str:
95 line = next(self._lines)
96 self.line_number += 1
97 return line
98
99
100 @dataclass
101 class _InvalidElement:
102 """Dataclass to store invalid elements detected when parsing."""
103
104 line_number: int
105 element_type: int
106 n_nodes_expected: int | None = None
107 n_nodes_actual: int | None = None
108
109 def __str__(self) -> str:
110 items_to_print: list[str] = [f'line {self.line_number}']
111 etype = self.element_type
112 content = (
113 f'{etype.value} ({etype.name})' if isinstance(etype, FRDElementType) else str(etype)
114 )
115 items_to_print.append(f'element type {content}')
116
117 actual = self.n_nodes_actual
118 expected = self.n_nodes_expected
119 if actual is not None and expected is not None:
120 items_to_print.append(f'num nodes {actual} (expected {expected})')
121 return ', '.join(items_to_print)
122
123
124 @dataclass
125 class _FRDData:
126 # Parsed data
127 nodes: dict[int, list[float]] = field(default_factory=dict)
128 elements: list[list[int]] = field(default_factory=list)
129 cell_types: list[int] = field(default_factory=list)
130 results_by_step: ResultsByStep = field(default_factory=dict)
131
132 # Diagnostic data
133 _has_too_many_points: list[_InvalidElement] = field(default_factory=list)
134 _has_too_few_points: list[_InvalidElement] = field(default_factory=list)
135 _has_unsupported_element: list[_InvalidElement] = field(default_factory=list)
136
137 # Format detection
138 _is_long_format: bool = False
139 _format_detected: bool = False
140
141
142 class _FRDParser:
143 """Parses a CalculiX FRD file into an FRDData object."""
144
145 # Compiled regex to fix scientific notation formatting issues
146 _SCIENTIFIC_RE = re.compile(r'(?<![EeDd])-')
147
148 def __init__(self, filename: str) -> None:
149 self._filename = filename
150
151 def parse(self) -> _FRDData:
152 frd_data = _FRDData()
153 with pathlib.Path(self._filename).open(errors='replace') as file_stream:
154 lines = _LineTrackingStream(file_stream)
155 for line in lines:
156 s = line.strip()
157 if s.startswith(FRDBlock.NODES.value):
158 self._parse_nodes(lines, frd_data)
159 elif s.startswith(FRDBlock.ELEMENTS.value):
160 self._parse_elements(lines, frd_data)
161 elif s.startswith(FRDBlock.RESULTS.value):
162 _step_id, step_time = self._parse_100cl_header(s)
163 frd_data.results_by_step.setdefault(step_time, {})
164 self._parse_results(lines, frd_data.results_by_step[step_time])
165 return frd_data
166
167 @staticmethod
168 def _fix_scientific(line: str) -> str:
169 return _FRDParser._SCIENTIFIC_RE.sub(' -', line)
170
171 @staticmethod
172 def _parse_100cl_header(line: str) -> tuple[int, float]:
173 parts = line.split()
174 try:
175 return int(parts[1]), float(parts[2])
176 except (IndexError, ValueError):
177 return -1, 0.0
178
179 @staticmethod
180 def _permute_nodes(node_ids: list[int], etype: FRDElementType) -> list[int]:
181 """Reorder node IDs from CalculiX to VTK conventions."""
182 if etype == FRDElementType.HE20:
183 return node_ids[:8] + node_ids[8:12] + node_ids[16:20] + node_ids[12:16]
184 if etype == FRDElementType.PE6 and pv.vtk_version_info < (9, 6, 99): # < (9, 7, 0)
185 return [node_ids[0], node_ids[2], node_ids[1], node_ids[3], node_ids[5], node_ids[4]]
186 if etype == FRDElementType.PE15:
187 return node_ids[:9] + node_ids[12:15] + node_ids[9:12]
188 return node_ids
189
190 @staticmethod
191 def _parse_nodes(file_stream: Any, frd_data: _FRDData) -> None:
192 end_block = str(CGXRecord.END_OF_BLOCK.value)
193 nodal_vals = str(CGXRecord.NODAL_VALUES.value)
194
195 for line in file_stream:
196 s = line.strip()
197 if s.startswith(end_block):
198 return
199 if not s.startswith(nodal_vals):
200 continue
201
202 idx = line.find(nodal_vals)
203
204 # _fix_scientific handles negative coordinates glued to ID (if any)
205 # split() is completely immune to varying space widths in both tests and real files
206 data_str = _FRDParser._fix_scientific(line[idx + len(nodal_vals) :].rstrip('\n\r'))
207 parts = data_str.split()
208
209 # A valid node definition contains at least 4 components: Node ID, X, Y, Z
210 if len(parts) >= 4:
211 try:
212 nid = int(parts[0])
213 frd_data.nodes[nid] = [float(parts[1]), float(parts[2]), float(parts[3])]
214 except ValueError:
215 # Ignore lines where coordinate parsing fails.
216 # This prevents crashes on formatting errors or unstructured
217 # text blocks mistakenly prefixed with the nodal value flag.
218 pass
219
220 @staticmethod
221 def _parse_elements(file_stream: Any, frd_data: _FRDData) -> None:
222 end_block = str(CGXRecord.END_OF_BLOCK.value)
223 elem_def = str(CGXRecord.NODAL_VALUES.value)
224 elem_faces = str(CGXRecord.ELEMENT_FACES.value)
225
226 needed = 0
227 node_ids: list[int] = []
228 etype = None
229 vtk_type = None
230 elem_line_number = -1
231
232 for line in file_stream:
233 s = line.strip()
234
235 # Prevent overlapping errors - if the line is not consecutive nodes
236 if etype is not None and not s.startswith(elem_faces):
237 invalid = _InvalidElement(
238 line_number=elem_line_number,
239 element_type=etype,
240 n_nodes_expected=needed,
241 n_nodes_actual=len(node_ids),
242 )
243 frd_data._has_too_few_points.append(invalid)
244 etype = None # Forces state refresh
245
246 if s.startswith(end_block):
247 return
248
249 if s.startswith(elem_def):
250 elem_line_number = file_stream.line_number
251
252 # Key: remove the prefix before split so that a glued ID does not break the parser
253 idx = line.find(elem_def)
254 data_str = line[idx + len(elem_def) :]
255 parts = data_str.split()
256
257 try:
258 # parts[0] = element ID, parts[1] = element type (e.g., 1 for HE8)
259 etype_val = int(parts[1])
260 except (ValueError, IndexError):
261 etype = None
262 continue
263
264 try:
265 etype = FRDElementType(etype_val)
266 except ValueError:
267 invalid = _InvalidElement(line_number=elem_line_number, element_type=etype_val)
268 frd_data._has_unsupported_element.append(invalid)
269 etype = None
270 continue
271
272 vtk_type = CCX_TO_VTK_TYPE[etype]
273 needed = vtk_type.n_points
274 node_ids = []
275
276 elif s.startswith(elem_faces) and etype is not None and vtk_type is not None:
277 idx = line.find(elem_faces)
278 data_str = line[idx + len(elem_faces) :].rstrip('\n\r')
279
280 if not frd_data._format_detected:
281 frd_data._is_long_format = len(data_str.rstrip()) > 50
282 frd_data._format_detected = True
283
284 width = 10 if frd_data._is_long_format else 5
285
286 # Use regular fixed-width indexing to parse nodes (CalculiX standard).
287 # This correctly splits glued identifiers (e.g., '1234567890' -> '12345', '67890')
288 # and strictly preserves whitespace constraints without relying on split().
289 try:
290 chunks = [data_str[i : i + width] for i in range(0, len(data_str), width)]
291 new_nodes = [int(c) for c in chunks if c.strip()]
292 node_ids.extend(new_nodes)
293 except ValueError:
294 # Fallback for malformed or edge-case real-world files
295 # where standard fixed-width indexing fails.
296 for p in data_str.split():
297 with contextlib.suppress(ValueError):
298 node_ids.append(int(p))
299
300 if (n_nodes := len(node_ids)) < needed:
301 # Element has too few points, and might be invalid, or maybe more points
302 # are defined on the next line
303 continue
304
305 if n_nodes > needed:
306 # Keep track of elements with too many points, but don't skip
307 invalid = _InvalidElement(
308 line_number=elem_line_number,
309 element_type=etype,
310 n_nodes_expected=needed,
311 n_nodes_actual=n_nodes,
312 )
313 frd_data._has_too_many_points.append(invalid)
314
315 final_nodes = _FRDParser._permute_nodes(node_ids, etype)
316 frd_data.elements.append(final_nodes[:needed])
317 frd_data.cell_types.append(vtk_type.value)
318
319 # Clean start for the next element
320 etype = None
321 node_ids = []
322
323 @staticmethod
324 def _parse_results(file_stream: Any, step_bucket: StepBucket) -> None:
325 name = 'Unknown'
326 attr_header = str(CGXRecord.ATTRIBUTE_HEADER.value)
327 comp_def = str(CGXRecord.COMPONENT_DEFINITION.value)
328 nodal_vals = str(CGXRecord.NODAL_VALUES.value)
329 end_block = str(CGXRecord.END_OF_BLOCK.value)
330
331 for line in file_stream:
332 s = line.strip()
333 if s.startswith(attr_header):
334 parts = s.split()
335 if len(parts) >= 2:
336 name = parts[1]
337 elif s.startswith(comp_def):
338 continue
339 elif s.startswith(nodal_vals):
340 _FRDParser._parse_result_data(line, file_stream, name, step_bucket)
341 return
342 elif s.startswith(end_block):
343 return
344
345 @staticmethod
346 def _parse_result_data( # noqa: PLR0917
347 first_line: str, file_stream: Any, name: str, step_bucket: StepBucket
348 ) -> None:
349 data: dict[int, list[float]] = {}
350 end_block = str(CGXRecord.END_OF_BLOCK.value)
351 nodal_vals = str(CGXRecord.NODAL_VALUES.value)
352
353 def parse_line(line_str: str) -> None:
354 s = line_str.strip()
355 if not s.startswith(nodal_vals):
356 return
357 idx = line_str.find(nodal_vals)
358
359 data_str = _FRDParser._fix_scientific(line_str[idx + len(nodal_vals) :].rstrip('\n\r'))
360 parts = data_str.split()
361
362 if len(parts) >= 2:
363 try:
364 nid = int(parts[0])
365 vals = [float(x) for x in parts[1:]]
366 if vals:
367 data[nid] = vals
368 except ValueError:
369 pass
370
371 parse_line(first_line)
372
373 for line in file_stream:
374 s = line.strip()
375 if s.startswith(end_block):
376 break
377 parse_line(line)
378
379 if data:
380 step_bucket[name] = data
381
382 @staticmethod
383 def _compute_derived_stress(
384 grid: UnstructuredGrid, base_name: str, tensor: np.ndarray
385 ) -> None:
386 xx, yy, zz = tensor[:, 0], tensor[:, 1], tensor[:, 2]
387 xy, yz, zx = tensor[:, 3], tensor[:, 4], tensor[:, 5]
388
389 vmises = np.sqrt(
390 0.5
391 * ((xx - yy) ** 2 + (yy - zz) ** 2 + (zz - xx) ** 2 + 6.0 * (xy**2 + yz**2 + zx**2))
392 )
393 trace = xx + yy + zz
394 grid.point_data[f'{base_name}_Mises'] = vmises
395 grid.point_data[f'{base_name}_sgMises'] = np.where(
396 trace != 0, np.sign(trace) * vmises, vmises
397 )
398 _FRDParser._compute_principals(grid, base_name, tensor)
399
400 @staticmethod
401 def _compute_derived_strain(
402 grid: UnstructuredGrid, base_name: str, tensor: np.ndarray
403 ) -> None:
404 xx, yy, zz = tensor[:, 0], tensor[:, 1], tensor[:, 2]
405 xy, yz, zx = tensor[:, 3], tensor[:, 4], tensor[:, 5]
406
407 k = np.sqrt(2.0) / 3.0
408 vmises_strain = k * np.sqrt(
409 (xx - yy) ** 2 + (yy - zz) ** 2 + (zz - xx) ** 2 + 6.0 * (xy**2 + yz**2 + zx**2)
410 )
411 volumetric = xx + yy + zz
412 grid.point_data[f'{base_name}_Mises'] = vmises_strain
413 grid.point_data[f'{base_name}_sgMises'] = np.where(
414 volumetric != 0, np.sign(volumetric) * vmises_strain, vmises_strain
415 )
416 _FRDParser._compute_principals(grid, base_name, tensor)
417
418 @staticmethod
419 def _compute_principals(grid: UnstructuredGrid, base_name: str, tensor: np.ndarray) -> None:
420 n = tensor.shape[0]
421 mat = np.zeros((n, 3, 3))
422 mat[:, 0, 0] = tensor[:, 0]
423 mat[:, 1, 1] = tensor[:, 1]
424 mat[:, 2, 2] = tensor[:, 2]
425 mat[:, 0, 1] = mat[:, 1, 0] = tensor[:, 3]
426 mat[:, 1, 2] = mat[:, 2, 1] = tensor[:, 4]
427 mat[:, 0, 2] = mat[:, 2, 0] = tensor[:, 5]
428
429 eigvals = np.linalg.eigvalsh(mat)
430 grid.point_data[f'{base_name}_PS3'] = eigvals[:, 0]
431 grid.point_data[f'{base_name}_PS2'] = eigvals[:, 1]
432 grid.point_data[f'{base_name}_PS1'] = eigvals[:, 2]
433
434 @staticmethod
435 def _build_grid(frd_data: _FRDData, step_data: StepBucket) -> UnstructuredGrid:
436
437 if not frd_data.nodes:
438 msg = 'No nodes found in FRD file -- cannot build grid.'
439 raise ValueError(msg)
440
441 sorted_ids = sorted(frd_data.nodes)
442 node_map = {nid: idx for idx, nid in enumerate(sorted_ids)}
443 points = np.array([frd_data.nodes[n] for n in sorted_ids], dtype=float)
444
445 cells: list[int] = []
446 types: list[int] = []
447 for conn, ctype in zip(frd_data.elements, frd_data.cell_types, strict=True):
448 try:
449 vtk_ids = [node_map[n] for n in conn]
450 except KeyError:
451 continue
452 cells.append(len(vtk_ids))
453 cells.extend(vtk_ids)
454 types.append(ctype)
455
456 grid = pv.UnstructuredGrid(
457 np.array(cells, dtype=np.int64),
458 np.array(types, dtype=np.uint8),
459 points,
460 )
461
462 grid.point_data['original_node_ids'] = np.array([str(nid) for nid in sorted_ids])
463
464 n_points = len(points)
465 for name, data in step_data.items():
466 if not data:
467 continue
468 n_components = len(next(iter(data.values())))
469
470 if n_components == 1:
471 arr = np.zeros(n_points)
472 for nid, vals in data.items():
473 if nid in node_map:
474 arr[node_map[nid]] = vals[0]
475 grid.point_data[name] = arr
476 else:
477 arr = np.zeros((n_points, n_components))
478 for nid, vals in data.items():
479 if nid in node_map:
480 arr[node_map[nid]] = vals
481 grid.point_data[name] = arr
482
483 upper = name.upper()
484 if 'STRESS' in upper and n_components == 6:
485 _FRDParser._compute_derived_stress(grid, name, arr)
486 elif 'STRAIN' in upper and n_components == 6:
487 _FRDParser._compute_derived_strain(grid, name, arr)
488
489 return grid