Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/utils.py: 95%
137 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 12:02 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 12:02 +0000
1# Copyright (C) 2023 Jørgen Schartum Dokken
2#
3# This file is part of io4dolfinx
4#
5# SPDX-License-Identifier: MIT
7"""
8Vectorized numpy operations used internally in io4dolfinx
9"""
11from __future__ import annotations
13from collections.abc import Sequence
14from pathlib import Path
16from mpi4py import MPI
18import basix
19import dolfinx
20import fenicsx_compat
21import numpy as np
22import numpy.typing as npt
24__all__ = [
25 "check_file_exists",
26 "compute_local_range",
27 "index_owner",
28 "compute_dofmap_pos",
29 "unroll_dofmap",
30 "compute_insert_position",
31 "unroll_insert_position",
32 "codim_names",
33 "match_rows",
34 "same_time",
35 "vtk_components",
36 "pad_for_vtk",
37 "strip_vtk_padding",
38 "strip_suffix",
39 "input_cell_index",
40 "create_mixed_mesh",
41 "as_rows",
42 "serendipity_num_nodes",
43 "coordinate_element",
44]
46#: Codimension of the entities named ``"cell"``, ``"facet"``, ``"ridge"`` and ``"peak"``,
47#: as in :func:`dolfinx.io.gmsh.model_to_mesh`
48codim_names = {"cell": 0, "facet": 1, "ridge": 2, "peak": 3}
50#: Number of nodes of the cells read with DOLFINx's nodal degree-2 serendipity
51#: coordinate element, with nodes at the vertices and edge midpoints
52serendipity_num_nodes = {"quadrilateral": 8, "hexahedron": 20}
55def coordinate_element(
56 cell_type: str, degree: int, lvar: int, serendipity: bool, dtype: npt.DTypeLike
57) -> basix.ufl._ElementBase:
58 """Create a scalar coordinate element, Lagrange or nodal serendipity.
60 Args:
61 cell_type: DOLFINx cell type
62 degree: Degree of the Lagrange element
63 lvar: Lagrange variant
64 serendipity: Use DOLFINx's nodal degree-2 serendipity element instead of Lagrange
65 dtype: Floating point type of the coordinates
67 Returns:
68 The element, without the block size of the geometric dimension
69 """
70 if serendipity:
71 try:
72 from dolfinx.io.utils import _serendipity_coordinate_element
73 except ImportError as e:
74 raise NotImplementedError(
75 "Meshes with serendipity geometry (8-node quadrilaterals, 20-node "
76 "hexahedra) require the main branch of DOLFINx."
77 ) from e
78 return _serendipity_coordinate_element(dolfinx.mesh.to_type(cell_type), dtype)
79 return basix.ufl.element(
80 basix.ElementFamily.P, cell_type, degree, basix.LagrangeVariant(int(lvar)), dtype=dtype
81 )
84def check_file_exists(filename: Path | str):
85 """Check if file exists."""
86 if not Path(filename).exists():
87 raise FileNotFoundError(f"{filename} not found")
90valid_function_types = np.float32 | np.float64 | np.complex64 | np.complex128
91valid_real_types = np.float32 | np.float64
94def element_signature(V):
95 return V.element.signature
98def compute_insert_position(
99 data_owner: npt.NDArray[np.int32],
100 destination_ranks: npt.NDArray[np.int32],
101 out_size: npt.NDArray[np.int32],
102) -> npt.NDArray[np.int32]:
103 """
104 Giving a list of ranks, compute the local insert position for each rank in a list
105 sorted by destination ranks. This function is used for packing data from a
106 given process to its destination processes.
108 Example:
110 .. highlight:: python
111 .. code-block:: python
113 data_owner = [0, 1, 1, 0, 2, 3]
114 destination_ranks = [2,0,3,1]
115 out_size = [1, 2, 1, 2]
116 insert_position = compute_insert_position(data_owner, destination_ranks, out_size)
118 Insert position is then ``[1, 4, 5, 2, 0, 3]``
119 """
120 process_pos_indicator = data_owner.reshape(-1, 1) == destination_ranks
122 # Compute offsets for insertion based on input size
123 send_offsets = np.zeros(len(out_size) + 1, dtype=np.intc)
124 send_offsets[1:] = np.cumsum(out_size)
125 assert send_offsets[-1] == len(data_owner)
127 # Compute local insert index on each process
128 proc_row, proc_col = np.nonzero(process_pos_indicator)
129 cum_pos = np.cumsum(process_pos_indicator, axis=0)
130 insert_position = cum_pos[proc_row, proc_col] - 1
132 # Add process offset for each local index
133 insert_position += send_offsets[proc_col]
134 return insert_position
137def unroll_insert_position(
138 insert_position: npt.NDArray[np.int32], block_size: int
139) -> npt.NDArray[np.int32]:
140 """
141 Unroll insert position by a block size
143 Example:
146 .. highlight:: python
147 .. code-block:: python
149 insert_position = [1, 4, 5, 2, 0, 3]
150 unrolled_ip = unroll_insert_position(insert_position, 3)
152 where ``unrolled_ip = [3, 4 ,5, 12, 13, 14, 15, 16, 17, 6, 7, 8, 0, 1, 2, 9, 10, 11]``
153 """
154 unrolled_ip = np.repeat(insert_position, block_size) * block_size
155 unrolled_ip += np.tile(np.arange(block_size), len(insert_position))
156 return unrolled_ip
159def compute_local_range(comm: MPI.Comm, N: int | np.int64):
160 """
161 Divide a set of `N` objects into `M` partitions, where `M` is
162 the size of the MPI communicator `comm`.
164 NOTE: If N is not divisible by the number of ranks, the first `r`
165 processes gets an extra value
167 Returns the local range of values
168 """
169 rank = comm.rank
170 size = comm.size
171 n = N // size
172 r = N % size
173 # First r processes has one extra value
174 if rank < r:
175 return [rank * (n + 1), (rank + 1) * (n + 1)]
176 else:
177 return [rank * n + r, (rank + 1) * n + r]
180def index_owner(
181 comm: MPI.Comm, indices: npt.NDArray[np.int64], N: int | np.int64
182) -> npt.NDArray[np.int32]:
183 """
184 Find which rank (local to comm) which owns an `index`, given that
185 data of size `N` has been split equally among the ranks.
187 NOTE: If `N` is not divisible by the number of ranks, the first `r`
188 processes gets an extra value.
189 """
190 size = comm.size
191 assert (indices < N).all()
192 n = N // size
193 r = N % size
195 owner = np.empty_like(indices, dtype=np.int32)
196 inc_remainder = indices < (n + 1) * r
197 owner[inc_remainder] = indices[inc_remainder] // (n + 1)
198 owner[~inc_remainder] = r + (indices[~inc_remainder] - r * (n + 1)) // n
199 return owner
202def unroll_dofmap(dofs: npt.NDArray[np.int32], bs: int) -> npt.NDArray[np.int32]:
203 """
204 Given a two-dimensional dofmap of size `(num_cells, num_dofs_per_cell)`
205 Expand the dofmap by its block size such that the resulting array
206 is of size `(num_cells, bs*num_dofs_per_cell)`
207 """
208 num_cells, num_dofs_per_cell = dofs.shape
209 unrolled_dofmap = np.repeat(dofs, bs).reshape(num_cells, num_dofs_per_cell * bs) * bs
210 unrolled_dofmap += np.tile(np.arange(bs), num_dofs_per_cell)
211 return unrolled_dofmap
214def compute_dofmap_pos(
215 V: dolfinx.fem.FunctionSpace,
216) -> tuple[npt.NDArray[np.int32], npt.NDArray[np.int32]]:
217 """
218 Compute a map from each owned dof in the dofmap to a single cell owned by the
219 process, and the relative position of the dof.
221 .. note::
222 Every owned dof must be reachable from a cell owned by the process. This
223 holds for a mesh created by :func:`dolfinx.mesh.create_mesh`, but not
224 necessarily for one created by :func:`dolfinx.mesh.create_submesh`, which
225 builds its vertex map allowing owner changes: a rank may own a vertex --
226 and therefore a dof -- that is only incident to cells it ghosts. Such
227 dofs cannot be assigned a position and raise rather than silently
228 yielding an arbitrary one.
230 :param V: The function space
231 :returns: The tuple (`cells`, `dof_pos`) where each array is the size of the
232 number of owned dofs (unrolled for block size)
233 :raises RuntimeError: If an owned dof is not contained in any owned cell.
234 """
235 dofs = V.dofmap.list
236 mesh = V.mesh
237 num_owned_cells = mesh.topology.index_map(mesh.topology.dim).size_local
238 dofmap_bs = V.dofmap.bs
239 num_owned_dofs = V.dofmap.index_map.size_local * V.dofmap.index_map_bs
241 # Initialize to -1 rather than leaving uninitialized, so that a dof that is
242 # never visited below is detectable instead of holding arbitrary memory.
243 local_cell = np.full(
244 num_owned_dofs, -1, dtype=np.int32
245 ) # Local cell index for each dof owned by process
246 dof_pos = np.full(num_owned_dofs, -1, dtype=np.int32) # Position in dofmap for said dof
248 unrolled_dofmap = unroll_dofmap(dofs[:num_owned_cells, :], dofmap_bs)
249 markers = unrolled_dofmap < num_owned_dofs
250 local_indices = np.broadcast_to(np.arange(markers.shape[1]), markers.shape)
251 cell_indicator = np.broadcast_to(
252 np.arange(num_owned_cells, dtype=np.int32).reshape(-1, 1),
253 (num_owned_cells, markers.shape[1]),
254 )
255 indicator = unrolled_dofmap[markers].reshape(-1)
256 local_cell[indicator] = cell_indicator[markers].reshape(-1)
257 dof_pos[indicator] = local_indices[markers].reshape(-1)
259 num_unreachable = int(np.count_nonzero(local_cell < 0))
260 if num_unreachable > 0:
261 raise RuntimeError(
262 f"{num_unreachable} of {num_owned_dofs} owned dofs are not contained in any"
263 " cell owned by this process, so their position in the dofmap is undefined."
264 " This happens on meshes created with `dolfinx.mesh.create_submesh`, which"
265 " may move vertex ownership to a process that does not own an incident cell."
266 " Read the function on a standalone mesh (see `io4dolfinx.read_submesh`)"
267 " rather than on a mesh derived with `create_submesh`."
268 )
269 return local_cell, dof_pos
272def match_rows(reference: npt.NDArray[np.int64], query: npt.NDArray[np.int64]) -> npt.NDArray:
273 """Find the rows of ``reference`` holding the same nodes as each row of ``query``.
275 Returns:
276 Index into ``reference`` of each query row, ``-1`` if it has no match. If
277 several rows match, the first one is used.
278 """
279 if len(query) == 0:
280 return np.zeros(0, dtype=np.int64)
281 rows = np.vstack([np.sort(reference, axis=1), np.sort(query, axis=1)])
282 _, inverse = np.unique(rows, axis=0, return_inverse=True)
283 inverse = inverse.reshape(-1)
284 lookup = np.full(inverse.max() + 1, -1, dtype=np.int64)
285 matched, first = np.unique(inverse[: len(reference)], return_index=True)
286 lookup[matched] = first
287 return lookup[inverse[len(reference) :]]
290def same_time(stamps: npt.ArrayLike, time: float) -> npt.NDArray[np.bool_]:
291 """Which time stamps are the same as ``time``, up to the precision of their dtype.
293 The relative tolerance is the square root of the machine epsilon of the stamps
294 (float64 if they are not floating point), so that round-off in computing a time does
295 not make it a different time. The absolute tolerance is the machine epsilon, so that
296 small but distinct times near zero stay apart.
298 Args:
299 stamps: Time stamps
300 time: The time to look for
302 Returns:
303 A boolean array, true where a stamp is the same as ``time``
304 """
305 stamps = np.asarray(stamps)
306 dtype = stamps.dtype if np.issubdtype(stamps.dtype, np.floating) else np.dtype(np.float64)
307 eps = np.finfo(dtype).eps
308 return np.isclose(stamps, time, rtol=np.sqrt(eps), atol=eps)
311def vtk_components(value_shape: tuple[int, ...]) -> tuple[int, npt.NDArray[np.int64]]:
312 """The layout VTK expects for values of a given shape.
314 VTK reads arrays with 3 components as vectors and arrays with 9 components as
315 tensors. Vectors with fewer than 3 components are therefore padded to 3, and tensors
316 of at most 3 x 3 are embedded in a 3 x 3 tensor, row by row. Other shapes are stored
317 as they are.
319 Args:
320 value_shape: Value shape of the data, for instance ``(2,)`` or ``(2, 2)``
322 Returns:
323 The number of components VTK stores, and the component holding each value (in
324 row-major order)
325 """
326 if len(value_shape) == 1 and value_shape[0] < 3:
327 return 3, np.arange(value_shape[0], dtype=np.int64)
328 if len(value_shape) == 2 and max(value_shape) <= 3:
329 rows, cols = np.indices(value_shape).reshape(2, -1)
330 return 9, (3 * rows + cols).astype(np.int64)
331 size = int(np.prod(value_shape))
332 return size, np.arange(size, dtype=np.int64)
335def pad_for_vtk(values: np.ndarray, value_shape: tuple[int, ...]) -> np.ndarray:
336 """Lay out values as VTK expects them, see :func:`vtk_components`.
338 Args:
339 values: Values with one row per point or cell and one column per component
340 value_shape: Value shape of the data
342 Returns:
343 The values, with zeros in the components added for VTK
344 """
345 num_components, columns = vtk_components(value_shape)
346 padded = np.zeros((values.shape[0], num_components), dtype=values.dtype)
347 padded[:, columns] = values
348 return padded
351def strip_vtk_padding(data: np.ndarray, value_shape: tuple[int, ...] | None) -> np.ndarray:
352 """Remove the components added by :func:`pad_for_vtk`.
354 Args:
355 data: Data read from a VTK file, 1D for single-component arrays
356 value_shape: Value shape of the data, ``None`` if unknown
358 Returns:
359 The data with one column per component: those of the value shape, or every
360 stored column if it is unknown
361 """
362 if data.ndim == 1:
363 data = data.reshape(-1, 1)
364 if value_shape is None:
365 return data
366 return data[:, vtk_components(value_shape)[1]]
369def strip_suffix(filename: Path | str, suffixes: Sequence[str]) -> Path:
370 """Remove the suffix of a filename if it is one of ``suffixes``.
372 For formats that store a dataset as several files sharing a base name.
374 Args:
375 filename: Base name, or the path of one of its files
376 suffixes: Suffixes of the files of the format, e.g. ``(".pts", ".elem")``
378 Returns:
379 The base name
380 """
381 path = Path(filename)
382 return path.with_suffix("") if path.suffix in suffixes else path
385def input_cell_index(mesh: dolfinx.mesh.Mesh) -> npt.NDArray[np.int64]:
386 """The index of each local cell in the input mesh, for writing data in the input ordering.
388 Raises:
389 ValueError: If the mesh has no input cell indices, as for a submesh. DOLFINx raises a
390 ``RuntimeError`` or a ``ValueError``, depending on its version.
391 """
392 try:
393 return mesh.topology.original_cell_index
394 except (RuntimeError, ValueError) as e:
395 raise ValueError(
396 "The mesh has no input cell indices, so the data cannot be written in the input "
397 "ordering. This is the case for a submesh."
398 ) from e
401def create_mixed_mesh(
402 comm: MPI.Comm,
403 cells: Sequence[npt.NDArray[np.int64]],
404 cell_types: Sequence[str],
405 x: npt.NDArray[np.floating],
406 degree: int,
407 lvar: int,
408 ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.shared_facet,
409 max_facet_to_cell_links: int = 2,
410) -> dolfinx.mesh.Mesh:
411 """Create a mesh with several cell types (mixed topology).
413 DOLFINx has no public Python interface for this, so the C++ constructor is called as
414 in :func:`dolfinx.io.gmsh.model_to_mesh`: ``_create_mixed_mesh`` after DOLFINx 0.11,
415 and the overload of ``create_mesh`` taking a list of cell arrays in 0.11.
417 Args:
418 comm: MPI communicator to distribute the mesh over
419 cells: Global cell->node connectivity of each cell type, in DOLFINx node ordering,
420 each of shape ``(num_cells, num_nodes_per_cell)``
421 cell_types: Cell type of each entry in ``cells``
422 x: Mesh coordinates, of shape ``(num_nodes, gdim)``
423 degree: Degree of the Lagrange coordinate elements
424 lvar: Lagrange variant of the coordinate elements
425 ghost_mode: Ghost mode of the mesh
426 max_facet_to_cell_links: Maximum number of cells a facet can be connected to
428 Returns:
429 The distributed mesh. It has no UFL domain, as UFL does not support mixed meshes.
431 Raises:
432 NotImplementedError: If DOLFINx is older than 0.11.
433 """
434 if fenicsx_compat.before("0.11.0.dev0"):
435 raise NotImplementedError(
436 f"Reading a mesh with several cell types {list(cell_types)} requires DOLFINx "
437 f"0.11 or later, found {dolfinx.__version__}."
438 )
439 x = np.ascontiguousarray(x)
440 cmaps = [
441 dolfinx.fem.coordinate_element(
442 dolfinx.mesh.to_type(cell_type),
443 degree,
444 basix.LagrangeVariant(lvar),
445 dtype=x.dtype,
446 )._cpp_object
447 for cell_type in cell_types
448 ]
449 flat_cells = [np.ascontiguousarray(c, dtype=np.int64).reshape(-1) for c in cells]
450 if hasattr(dolfinx.cpp.mesh, "_create_mixed_mesh"):
451 cpp_mesh = dolfinx.cpp.mesh._create_mixed_mesh(
452 comm,
453 flat_cells,
454 cmaps, # type: ignore[arg-type]
455 x,
456 dolfinx.cpp.graph.partitioner() if comm.size > 1 else None,
457 ghost_mode,
458 max_facet_to_cell_links,
459 1,
460 cell_weights=None,
461 reorder_fn=None,
462 )
463 else:
464 partitioner = (
465 fenicsx_compat.create_cell_partitioner(ghost_mode, max_facet_to_cell_links)
466 if comm.size > 1
467 else None
468 )
469 cpp_mesh = dolfinx.cpp.mesh.create_mesh( # type: ignore[call-overload]
470 comm, flat_cells, cmaps, x, partitioner, max_facet_to_cell_links
471 )
472 return dolfinx.mesh.Mesh(cpp_mesh, None)
475def as_rows(values: npt.ArrayLike) -> np.ndarray:
476 """Data with one row per entity, such as a VTK data array.
478 Args:
479 values: Scalar values of shape ``(num_values,)``, or values of shape
480 ``(num_values, ...)``
482 Returns:
483 The values, of shape ``(num_values, num_components)``
484 """
485 values = np.asarray(values)
486 return values.reshape(len(values), -1)