Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/nastran/backend.py: 95%
97 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
1"""
2Nastran interface to io4dolfinx.
4Reads the mesh and mesh tags of Nastran bulk data files (``.bdf``, ``.nas``) through the
5`Gmsh <https://gmsh.info>`_ Python API, reusing :mod:`dolfinx.io.gmsh` for the geometry,
6the topology and the node ordering. All file access happens on rank 0.
8- The cells are the elements of the highest topological dimension. Meshes with several
9 cell types, such as hexahedra, pyramids and tetrahedra, are read as mixed meshes.
10- Mesh tags are the property IDs (PID) of the elements, see :func:`read_meshtags_data`.
11- Node ``i`` is the node with the ``i``-th smallest GRID ID. The GRID IDs can be read as
12 point data and as vertex tags, both called ``"GRID"``, on meshes with one cell type.
14SPDX License identifier: MIT
15"""
17from pathlib import Path
18from typing import Any
20from mpi4py import MPI
22import basix
23import dolfinx
24import numpy as np
25import numpy.typing as npt
26from dolfinx.io.gmsh import extract_geometry
28try:
29 import gmsh
30except ImportError:
31 raise ModuleNotFoundError("The nastran-backend requires gmsh")
33from ...structures import (
34 ArrayData,
35 FunctionData,
36 MeshData,
37 MeshTagsData,
38 ReadMeshData,
39 ReadMixedMeshData,
40)
41from ...utils import check_file_exists
42from .. import FileMode, ReadMode
43from ..gmsh.backend import _run_on_root
44from . import helpers
46read_mode = ReadMode.serial
49def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]:
50 """Get default backend arguments given a set of input arguments.
52 Args:
53 arguments: Input backend arguments
55 Returns:
56 The arguments, with defaults for:
57 - ``"dtype"``: Floating point type of the mesh coordinates, ``np.float64``
58 """
59 args: dict[str, Any] = {"dtype": np.float64}
60 args.update(arguments or {})
61 return args
64def read_mesh_data(
65 filename: Path | str,
66 comm: MPI.Comm,
67 time: str | float | None = None,
68 read_from_partition: bool = False,
69 backend_args: dict[str, Any] | None = None,
70) -> ReadMeshData | ReadMixedMeshData:
71 """Read mesh data from a Nastran file.
73 The cells are the elements of the highest topological dimension. If they are of
74 several types, e.g. hexahedra, pyramids and tetrahedra, the mesh is read as a mixed
75 mesh. All data is read on rank 0.
77 Args:
78 filename: Path to file to read from
79 comm: MPI communicator used in storage
80 time: Time stamp associated with the mesh to read
81 read_from_partition: Whether to read partition information
82 backend_args: Arguments to backend, see :func:`get_default_backend_args`
84 Returns:
85 Internal data structure for the mesh data read from file
86 """
87 if read_from_partition:
88 raise NotImplementedError("The nastran backend cannot read partitioning data.")
89 check_file_exists(filename)
90 backend_args = get_default_backend_args(backend_args)
92 def read(
93 preexisting_views: list[int],
94 ) -> tuple[
95 tuple[npt.NDArray[np.float64], list[npt.NDArray[np.int64]]],
96 tuple[list[str], int, list[int]],
97 ]:
98 elements, _ = helpers.read_elements(filename)
99 blocks = elements[max(elements)]
100 degrees = {block.degree for block in blocks}
101 if len(degrees) > 1:
102 raise NotImplementedError(f"Cells of several degrees {degrees} in {filename}.")
103 x = extract_geometry(gmsh.model)
104 cells = [block.nodes for block in blocks]
105 cell_types = [block.cell_type for block in blocks]
106 return (x, cells), (cell_types, degrees.pop(), [c.shape[1] for c in cells])
108 local, (cell_types, degree, num_nodes) = _run_on_root(comm, read)
109 if local is None:
110 x = np.zeros((0, 3), dtype=np.float64)
111 cells = [np.zeros((0, n), dtype=np.int64) for n in num_nodes]
112 else:
113 x, cells = local
114 x = x.astype(backend_args["dtype"], copy=False)
115 lvar = int(basix.LagrangeVariant.equispaced)
116 if len(cell_types) == 1:
117 return ReadMeshData(cells=cells[0], cell_type=cell_types[0], x=x, lvar=lvar, degree=degree)
118 return ReadMixedMeshData(cells=cells, cell_types=cell_types, x=x, lvar=lvar, degree=degree)
121def read_point_data(
122 filename: Path | str,
123 name: str,
124 comm: MPI.Comm,
125 time: float | str | None,
126 backend_args: dict[str, Any] | None,
127) -> tuple[np.ndarray, int]:
128 """Read the GRID IDs of the nodes of a mesh with one cell type.
130 Note:
131 The function holding the GRID IDs has the precision of the mesh. In single
132 precision, IDs above :math:`2^{24}` are not exact; read them as vertex tags with
133 :func:`read_meshtags_data` instead.
135 Args:
136 filename: Path to file
137 name: Name of point data, ``"GRID"``
138 comm: Communicator to launch IO on.
139 time: Ignored, as a Nastran file holds no time series
140 backend_args: The backend arguments
142 Returns:
143 Tuple containing:
144 - The GRID ID of each node, of shape ``(num_nodes, 1)``, on rank 0
145 - The global start of the data on this process, ``0``
147 Raises:
148 KeyError: If ``name`` is not ``"GRID"``.
149 NotImplementedError: If the mesh has several cell types.
150 """
151 check_file_exists(filename)
152 if name != helpers.GRID:
153 raise KeyError(f"No point data '{name}' in {filename}. Available: ['{helpers.GRID}']")
155 def read(preexisting_views: list[int]) -> tuple[npt.NDArray[np.int64], None]:
156 elements, grid_ids = helpers.read_elements(filename)
157 helpers.get_single_cell_type(elements, "Reading GRID IDs as point data", filename)
158 return grid_ids, None
160 grid_ids, _ = _run_on_root(comm, read)
161 if grid_ids is None:
162 grid_ids = np.zeros(0, dtype=np.int64)
163 return grid_ids.reshape(-1, 1).astype(np.float64), 0
166def read_cell_data(
167 filename: Path | str,
168 name: str,
169 comm: MPI.Comm,
170 time: str | float | None,
171 backend_args: dict[str, Any] | None,
172) -> tuple[npt.NDArray[np.int64], np.ndarray]:
173 """Read data from the cells of a mesh.
175 Args:
176 filename: Path to file
177 name: Name of point data
178 comm: Communicator to launch IO on.
179 time: The time stamp
180 backend_args: The backend arguments
181 Returns:
182 A tuple (topology, dofs) where topology contains the
183 vertex indices of the cells, dofs the degrees of
184 freedom within that cell.
185 """
186 raise NotImplementedError("The nastran backend does not support reading cell data.")
189def write_attributes(
190 filename: Path | str,
191 comm: MPI.Comm,
192 name: str,
193 attributes: dict[str, np.ndarray],
194 backend_args: dict[str, Any] | None,
195):
196 """Write attributes to file.
198 Args:
199 filename: Path to file to write to
200 comm: MPI communicator used in storage
201 name: Name of the attribute group
202 attributes: Dictionary of attributes to write
203 backend_args: Arguments to backend
204 """
205 raise NotImplementedError("The nastran backend cannot write attributes.")
208def read_attributes(
209 filename: Path | str,
210 comm: MPI.Comm,
211 name: str,
212 backend_args: dict[str, Any] | None,
213) -> dict[str, Any]:
214 """Read attributes from file.
216 Args:
217 filename: Path to file to read from
218 comm: MPI communicator used in storage
219 name: Name of the attribute group
220 backend_args: Arguments to backend
222 Returns:
223 Dictionary of attributes read from file
224 """
225 raise NotImplementedError("The nastran backend cannot read attributes.")
228def read_timestamps(
229 filename: Path | str,
230 comm: MPI.Comm,
231 function_name: str,
232 backend_args: dict[str, Any] | None,
233) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var]
234 """Read timestamps from file.
236 Args:
237 filename: Path to file to read from
238 comm: MPI communicator used in storage
239 function_name: Name of the function to read timestamps for
240 backend_args: Arguments to backend
242 Returns:
243 Numpy array of timestamps read from file
244 """
245 raise NotImplementedError("The nastran backend cannot read timestamps.")
248def read_function_names(
249 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None
250) -> list[str]:
251 """Read all function names from a file.
253 Args:
254 filename: Path to file
255 comm: MPI communicator to launch IO on.
256 backend_args: Arguments to backend
258 Returns:
259 A list of function names.
260 """
262 return [helpers.GRID]
265def write_mesh(
266 filename: Path | str,
267 comm: MPI.Comm,
268 mesh: MeshData,
269 backend_args: dict[str, Any] | None,
270 mode: FileMode,
271 time: float,
272):
273 """
274 Write a mesh to file.
276 Args:
277 comm: MPI communicator used in storage
278 mesh: Internal data structure for the mesh data to save to file
279 filename: Path to file to write to
280 backend_args: Arguments to backend
281 mode: File-mode to store the mesh
282 time: Time stamp associated with the mesh
283 """
284 raise NotImplementedError("The nastran backend cannot write meshes.")
287def write_meshtags(
288 filename: str | Path,
289 comm: MPI.Comm,
290 data: MeshTagsData,
291 backend_args: dict[str, Any] | None,
292):
293 """Write mesh tags to file.
295 Args:
296 filename: Path to file to write to
297 comm: MPI communicator used in storage
298 data: Internal data structure for the mesh tags to save to file
299 backend_args: Arguments to backend
300 """
301 raise NotImplementedError("The nastran backend cannot write meshtags.")
304def read_meshtags_data(
305 filename: Path | str,
306 comm: MPI.Comm,
307 name: str,
308 backend_args: dict[str, Any] | None = None,
309) -> MeshTagsData:
310 """Read mesh tags from a Nastran file.
312 Args:
313 filename: Path to the Nastran file
314 comm: MPI communicator
315 name: One of:
317 - ``"PSOLID"``: the 3D solid elements, tagged with their property ID (PID)
318 - ``"PSHELL"``: the 2D shell elements (often used for boundary conditions),
319 tagged with their PID
320 - ``"GRID"``: the vertices, tagged with their GRID ID. Only supported on
321 meshes with one cell type.
323 backend_args: Arguments to backend, unused
325 Returns:
326 Internal data structure for the mesh tags read from file, on rank 0
328 Raises:
329 NotImplementedError: If the tagged entities are of several types, or for ``"GRID"``
330 on a mesh with several cell types.
331 """
332 check_file_exists(filename)
333 if name != helpers.GRID and name not in helpers.PROPERTY_TO_DIM:
334 names = [*sorted(helpers.PROPERTY_TO_DIM), helpers.GRID]
335 raise ValueError(f"Unsupported meshtag name {name!r}. Expected one of: {names}.")
336 dim = 0 if name == helpers.GRID else helpers.PROPERTY_TO_DIM[name]
338 def read(
339 preexisting_views: list[int],
340 ) -> tuple[tuple[npt.NDArray[np.int64], npt.NDArray[np.int32]], int]:
341 elements, grid_ids = helpers.read_elements(filename)
342 if name == helpers.GRID:
343 # Tag each vertex with its GRID ID, e.g. for point measures (ufl.dP). Only
344 # vertex nodes are tagged: the edge, face and interior nodes of higher-order
345 # cells are not mesh vertices. Each vertex is given by its node index (one
346 # node per entity), which read_meshtags maps to the mesh vertex. Node i has
347 # the i-th smallest GRID ID, so grid_ids[i] is its tag value, which must fit
348 # in the int32 values of a MeshTags.
349 cells = helpers.get_single_cell_type(
350 elements, "Reading GRID IDs as vertex tags", filename
351 )
352 vertices = helpers.get_vertex_nodes(cells)
353 if len(grid_ids) > 0 and grid_ids[-1] > np.iinfo(np.int32).max:
354 raise ValueError(f"GRID IDs in {filename} do not fit in mesh tag values (int32).")
355 return (vertices.reshape(-1, 1), grid_ids[vertices].astype(np.int32)), 1
357 # Check that the file has elements of the dimension of the property card, all of
358 # one type, as a DOLFINx MeshTags holds entities of a single type
359 blocks = elements.get(dim, [])
360 if len(blocks) == 0:
361 raise ValueError(f"No {name} elements (dimension {dim}) found in {filename}.")
362 if len(blocks) > 1:
363 types = [block.cell_type for block in blocks]
364 raise NotImplementedError(
365 f"{name} elements of several types {types} in {filename}; mesh tags of "
366 "several entity types are not supported."
367 )
368 return (blocks[0].nodes, blocks[0].pids), blocks[0].nodes.shape[1]
370 local, num_nodes = _run_on_root(comm, read)
371 if local is None:
372 local = (np.zeros((0, num_nodes), dtype=np.int64), np.zeros(0, dtype=np.int32))
373 return MeshTagsData(name=name, values=local[1], indices=local[0], dim=dim)
376def read_dofmap(
377 filename: str | Path,
378 comm: MPI.Comm,
379 name: str,
380 backend_args: dict[str, Any] | None,
381) -> dolfinx.graph.AdjacencyList:
382 """Read the dofmap of a function with a given name.
384 Args:
385 filename: Path to file to read from
386 comm: MPI communicator used in storage
387 name: Name of the function to read the dofmap for
388 backend_args: Arguments to backend
390 Returns:
391 Dofmap as an AdjacencyList
392 """
393 raise NotImplementedError("The nastran backend cannot make checkpoints.")
396def read_dofs(
397 filename: str | Path,
398 comm: MPI.Comm,
399 name: str,
400 time: float,
401 backend_args: dict[str, Any] | None,
402) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]:
403 """Read the dofs (values) of a function with a given name from a given timestep.
405 Args:
406 filename: Path to file to read from
407 comm: MPI communicator used in storage
408 name: Name of the function to read the dofs for
409 time: Time stamp associated with the function to read
410 backend_args: Arguments to backend
412 Returns:
413 Contiguous sequence of degrees of freedom (with respect to input data)
414 and the global starting point on the process.
415 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
416 """
417 raise NotImplementedError("The nastran backend cannot make checkpoints.")
420def read_cell_perms(
421 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None
422) -> npt.NDArray[np.uint32]:
423 """
424 Read cell permutation from file with given communicator,
425 Split in continuous chunks based on number of cells in the input data.
427 Args:
428 comm: MPI communicator used in storage
429 filename: Path to file to read from
430 backend_args: Arguments to backend
432 Returns:
433 Contiguous sequence of permutations (with respect to input data)
434 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
435 """
436 raise NotImplementedError("The nastran backend cannot make checkpoints.")
439def write_function(
440 filename: Path,
441 comm: MPI.Comm,
442 u: FunctionData,
443 time: float,
444 mode: FileMode,
445 backend_args: dict[str, Any] | None,
446):
447 """
448 Write a function to file.
450 Args:
451 comm: MPI communicator used in storage
452 u: Internal data structure for the function data to save to file
453 filename: Path to file to write to
454 time: Time stamp associated with function
455 mode: File-mode to store the function
456 backend_args: Arguments to backend
457 """
458 raise NotImplementedError("The nastran backend cannot make checkpoints.")
461def read_legacy_mesh(
462 filename: Path | str, comm: MPI.Comm, group: str
463) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]:
464 """Read in the mesh topology, geometry and (optionally) cell type from a
465 legacy DOLFIN HDF5-file.
467 Args:
468 filename: Path to file to read from
469 comm: MPI communicator used in storage
470 group: Group in HDF5 file where mesh is stored
472 Returns:
473 Tuple containing:
474 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices
475 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates
476 - Cell type as a string (e.g. "tetrahedron") or None if not found
477 """
478 raise NotImplementedError("The nastran backend cannot read legacy DOLFIN meshes.")
481def snapshot_checkpoint(
482 filename: Path | str,
483 mode: FileMode,
484 u: dolfinx.fem.Function,
485 backend_args: dict[str, Any] | None,
486):
487 """Create a snapshot checkpoint of a dolfinx function.
489 Args:
490 filename: Path to file to read from
491 mode: File-mode to store the function
492 u: dolfinx function to create a snapshot checkpoint for
493 backend_args: Arguments to backend
494 """
495 raise NotImplementedError("The nastran backend cannot make checkpoints.")
498def read_hdf5_array(
499 comm: MPI.Comm,
500 filename: Path | str,
501 group: str,
502 backend_args: dict[str, Any] | None,
503) -> tuple[np.ndarray, int]:
504 """Read an array from an HDF5 file.
506 Args:
507 comm: MPI communicator used in storage
508 filename: Path to file to read from
509 group: Group in HDF5 file where array is stored
510 backend_args: Arguments to backend
512 Returns:
513 Tuple containing:
514 - Numpy array read from file
515 - Global starting point on the process.
516 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
517 """
518 raise NotImplementedError("The nastran backend cannot read HDF5 arrays")
521def write_data(
522 filename: Path | str,
523 array_data: ArrayData,
524 comm: MPI.Comm,
525 time: str | float | None,
526 mode: FileMode,
527 backend_args: dict[str, Any] | None,
528):
529 """Write a 2D-array to file (distributed across proceses with MPI).
531 Args:
532 filename: Path to file
533 array_data: Data to write to file
534 comm: MPI communicator to open the file with
535 time: Time stamp
536 mode: Append or write
537 backend_args: The backend arguments
538 """
539 raise NotImplementedError("The nastran backend does not support writing point data")