Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/submesh.py: 97%
138 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# Copyright (C) 2026 Jørgen Schartum Dokken
2#
3# This file is part of io4dolfinx
4#
5# SPDX-License-Identifier: MIT
7"""Checkpointing of submeshes.
9A :func:`dolfinx.mesh.create_submesh` submesh cannot be checkpointed the way an
10ordinary mesh is. Two properties of the DOLFINx construction get in the way:
121. For a submesh of co-dimension greater than zero, a cell of the submesh is an
13 *entity* of the parent, and the vertices of an entity are ordered by their
14 current global vertex index. Re-partitioning the parent renumbers the
15 vertices, so the same submesh cell comes back with its vertices in a
16 different order and the degrees of freedom inside it land in different
17 positions.
182. :func:`dolfinx.mesh.create_submesh` builds its vertex map allowing owner
19 changes, so a process can own a vertex -- and a dof -- that is only incident
20 to cells it ghosts. Such a dof has no position in any owned cell, which is
21 what :func:`io4dolfinx.utils.compute_dofmap_pos` needs.
23So a function is never read onto a re-derived submesh. Instead the submesh is
24stored as an ordinary, independent mesh (whose cells keep the stored node order
25and whose ownership is the ordinary one), read back as such, and the data is
26then transferred to a mesh re-derived from the parent when the caller needs the
27entity maps that make mixed-dimensional assembly possible.
28"""
30from __future__ import annotations
32import logging
33from dataclasses import dataclass
34from pathlib import Path
35from typing import Any
37from mpi4py import MPI
39import dolfinx
40import numpy as np
41import numpy.typing as npt
42from dolfinx import cpp as _cpp
44from .backends import FileMode, get_backend, with_mesh_name
45from .checkpointing import write_mesh
46from .comm_helpers import exchange_to_owners, numpy_to_mpi
47from .format import stamp
48from .structures import MeshTagsData
49from .utils import check_file_exists, compute_local_range, index_owner
51__all__ = [
52 "SubmeshCheckpoint",
53 "read_submesh",
54 "transfer_submesh_function",
55 "write_submesh",
56]
58logger = logging.getLogger(__name__)
61def _post_code_name(mesh_name: str) -> str:
62 """Name of the meshtag holding the post codes of the submesh ``mesh_name``.
64 The post codes tag the *parent* mesh, so they are stored in the parent's
65 namespace and must not collide with a tag a user wrote.
66 """
67 return f"__submesh_post_code_{mesh_name}"
70def _parent_entities(
71 submesh: dolfinx.mesh.Mesh, cell_map: dolfinx.mesh.EntityMap
72) -> npt.NDArray[np.int32]:
73 """Parent entity of every cell of ``submesh``, owned and ghost."""
74 imap = submesh.topology.index_map(submesh.topology.dim)
75 cells = np.arange(imap.size_local + imap.num_ghosts, dtype=np.int32)
76 return cell_map.sub_topology_to_topology(cells, False)
79@dataclass
80class SubmeshCheckpoint:
81 """A submesh re-derived from a parent mesh that was read from a checkpoint."""
83 #: The submesh, derived from the parent with :func:`dolfinx.mesh.create_submesh`
84 submesh: dolfinx.mesh.Mesh
85 #: Map from cells of :attr:`submesh` to entities of the parent
86 cell_map: dolfinx.mesh.EntityMap
87 #: Map from vertices of :attr:`submesh` to vertices of the parent
88 vertex_map: dolfinx.mesh.EntityMap
89 #: Map from geometry nodes of :attr:`submesh` to nodes of the parent
90 node_map: npt.NDArray[np.int32]
92 #: Index the cell had in the stored submesh, per local cell (owned and ghost).
93 #: This is the key both submeshes agree on: :func:`transfer_submesh_function`
94 #: derives from it the post office holding each cell, and so routes the data
95 #: from the stored submesh to this one.
96 post_code: npt.NDArray[np.int64]
98 @property
99 def parent_entities(self) -> npt.NDArray[np.int32]:
100 """Parent entities of the submesh cells, aligned with :attr:`post_code`."""
101 return _parent_entities(self.submesh, self.cell_map)
104def write_submesh(
105 filename: Path | str,
106 submesh: dolfinx.mesh.Mesh,
107 parent: dolfinx.mesh.Mesh,
108 cell_map: Any,
109 mesh_name: str,
110 parent_mesh_name: str | None = None,
111 parent_filename: Path | str | None = None,
112 time: float = 0.0,
113 mode: FileMode = FileMode.append,
114 backend_args: dict[str, Any] | None = None,
115 backend: str | None = None,
116):
117 """Write a submesh, and the post codes that tie it back to its parent.
119 The submesh is stored as an ordinary independent mesh under ``mesh_name``, so
120 :func:`io4dolfinx.read_mesh` and :func:`io4dolfinx.read_function` read it
121 back with no special handling. Alongside it goes a tag of *post codes*: every
122 parent entity that became a submesh cell is given the index that cell has in
123 the stored submesh. The entities are addressed by their parent geometry
124 nodes, which is what lets :func:`read_submesh` find them again in a
125 re-partitioned parent; the values come back as
126 :attr:`SubmeshCheckpoint.post_code`.
128 The post codes tag entities of the *parent*, so they are stored in the parent's
129 namespace, in ``parent_filename``. Leave that unset to keep everything in one
130 checkpoint, or point it at the parent's own file to keep the two apart; the
131 submesh always goes to ``filename``. Either way the parent must already have
132 been written there with :func:`io4dolfinx.write_mesh`.
134 Args:
135 filename: Path to write the submesh to
136 submesh: The submesh, as returned by :func:`dolfinx.mesh.create_submesh`
137 parent: The mesh the submesh was derived from
138 cell_map: Map from submesh cells to parent entities, as returned by
139 :func:`dolfinx.mesh.create_submesh`
140 mesh_name: Name to store the submesh under
141 parent_mesh_name: Name the parent mesh is stored under
142 parent_filename: File holding the parent mesh, if not ``filename``
143 time: Time stamp associated with the submesh geometry
144 mode: Whether to create the file or append to it
145 backend_args: Arguments for the backend
146 backend: Which backend to use
147 """
148 logger.debug(f"Writing submesh '{mesh_name}' to {filename}")
149 dim = submesh.topology.dim
151 # 1. The submesh itself, as a perfectly ordinary mesh.
152 write_mesh(
153 Path(filename),
154 submesh,
155 mode=mode,
156 time=time,
157 backend_args=backend_args,
158 backend=backend,
159 mesh_name=mesh_name,
160 )
162 # 2. The post codes. Structurally this is a meshtag on the parent: the
163 # tagged entities are the parent entities that became submesh cells, and
164 # each value is that cell's post code, its index in the stored submesh.
165 cell_imap = submesh.topology.index_map(dim)
166 num_owned = cell_imap.size_local
167 parent_entities = cell_map.sub_topology_to_topology(np.arange(num_owned, dtype=np.int32), False)
168 post_code = np.arange(*cell_imap.local_range, dtype=np.int64)
170 parent.topology.create_connectivity(dim, parent.topology.dim)
171 parent.topology.create_connectivity(0, parent.topology.dim)
172 entities_to_geometry = dolfinx.cpp.mesh.entities_to_geometry(
173 parent._cpp_object, dim, parent_entities, False
174 )
175 indices = (
176 parent.geometry.index_map()
177 .local_to_global(entities_to_geometry.reshape(-1))
178 .reshape(entities_to_geometry.shape)
179 )
181 tag_data = MeshTagsData(
182 metadata=stamp(),
183 values=post_code,
184 num_entities_global=cell_imap.size_global,
185 num_dofs_per_entity=entities_to_geometry.shape[1],
186 indices=indices,
187 name=_post_code_name(mesh_name),
188 local_start=cell_imap.local_range[0],
189 dim=dim,
190 cell_type=submesh.topology.cell_name(),
191 )
192 backend_cls = get_backend(backend)
193 parent_args = backend_cls.get_default_backend_args(
194 with_mesh_name(backend_args, parent_mesh_name)
195 )
196 post_code_file = filename if parent_filename is None else parent_filename
197 backend_cls.write_meshtags(post_code_file, parent.comm, tag_data, backend_args=parent_args)
200def read_submesh(
201 filename: Path | str,
202 parent: dolfinx.mesh.Mesh,
203 mesh_name: str,
204 parent_mesh_name: str | None = None,
205 backend_args: dict[str, Any] | None = None,
206 backend: str | None = None,
207) -> SubmeshCheckpoint:
208 """Re-derive a stored submesh from a parent mesh that has been read back.
210 The result is a genuine :func:`dolfinx.mesh.create_submesh` submesh, so its
211 entity maps are accepted by :func:`dolfinx.fem.form` for mixed-dimensional
212 assembly against ``parent``.
214 It does **not** carry the checkpointed data. Read that onto the standalone
215 submesh with :func:`io4dolfinx.read_mesh` and :func:`io4dolfinx.read_function`,
216 then move it across with :func:`transfer_submesh_function`.
218 Args:
219 filename: File holding the parent mesh and the post codes, i.e. whatever
220 was passed as ``parent_filename`` to :func:`write_submesh`
221 parent: The parent mesh, as read back from the checkpoint
222 mesh_name: Name the submesh was stored under
223 parent_mesh_name: Name the parent mesh is stored under
224 backend_args: Arguments for the backend
225 backend: Which backend to use
227 Returns:
228 The re-derived submesh and the maps relating it to ``parent``.
229 """
230 logger.debug(f"Reading submesh '{mesh_name}' from {filename}")
231 check_file_exists(filename)
232 backend_cls = get_backend(backend)
233 parent_args = backend_cls.get_default_backend_args(
234 with_mesh_name(backend_args, parent_mesh_name)
235 )
236 # Post codes are global cell indices, so they must survive as int64.
237 parent_args["values_dtype"] = np.int64
238 data = backend_cls.read_meshtags_data(
239 filename, parent.comm, _post_code_name(mesh_name), parent_args
240 )
241 dim = int(data.dim)
243 local_entities, local_values = dolfinx.io.distribute_entity_data(
244 parent, dim, data.indices, data.values.astype(np.int64)
245 )
246 parent.topology.create_connectivity(dim, 0)
247 parent.topology.create_connectivity(dim, parent.topology.dim)
248 adj = dolfinx.graph.adjacencylist(local_entities)
249 tags = dolfinx.mesh.meshtags_from_entities(
250 parent, dim, adj, np.asarray(local_values, dtype=np.int64)
251 )
253 # `distribute_entity_data` only reports entities to processes that hold them;
254 # a process ghosting an entity may not be among them. Scattering through an
255 # index map gives every process the owner's value for its ghosts, so the
256 # submesh is built from a consistent set of entities everywhere.
257 entity_map = parent.topology.index_map(dim)
258 marker = dolfinx.la.vector(entity_map, dtype=np.int64)
259 marker.array[:] = -1
260 marker.array[tags.indices] = tags.values
261 marker.scatter_forward()
262 entities = np.flatnonzero(marker.array >= 0).astype(np.int32)
264 submesh, cell_map, vertex_map, node_map = dolfinx.mesh.create_submesh(parent, dim, entities)
265 post_code = marker.array[_parent_entities(submesh, cell_map)].astype(np.int64)
266 return SubmeshCheckpoint(
267 submesh=submesh,
268 cell_map=cell_map,
269 vertex_map=vertex_map,
270 node_map=node_map,
271 post_code=post_code,
272 )
275def _point_ownership_data(
276 comm: MPI.Intracomm,
277 src_owner: npt.NDArray[np.int32],
278 points: npt.NDArray[np.floating],
279 source_cells: npt.NDArray[np.int32],
280) -> Any:
281 """Build a :class:`dolfinx.geometry.PointOwnershipData` from a known routing.
283 :func:`dolfinx.fem.create_interpolation_data` would derive the same object by
284 searching a bounding-box tree for each point, with a padding tolerance and an
285 extrapolation fallback. Here the owning rank and cell of every point are
286 already known exactly, so the routing is done directly.
288 The layout required of the returned
289 :class:`dolfinx.geometry.PointOwnershipData` is dictated by
290 ``fem::interpolate`` and ``impl::scatter_values``:
292 * ``src_owner`` is per interpolation point of the receiving function, in the
293 order :func:`dolfinx.cpp.fem.interpolation_coords` produced them.
294 * ``dest_owners`` must be in **contiguous runs by rank**; ``scatter_values``
295 reduces it with a non-sorting ``unique``, so interleaved ranks would
296 silently build the wrong neighbourhood. :func:`exchange_to_owners` groups
297 by ascending source rank, which satisfies this.
298 * ``dest_points`` is flat row-major ``(n_recv, 3)`` and ``dest_cells`` indexes
299 cells of the *sending* function's mesh on the receiving process.
301 Args:
302 comm: The MPI communicator both meshes live on
303 src_owner: Rank holding the source cell of each point
304 points: The points, shape ``(num_points, 3)``
305 source_cells: Source-mesh local cell of each point, on ``src_owner``
307 Returns:
308 Interpolation data for :meth:`dolfinx.fem.Function.interpolate_nonmatching`.
309 """
310 (recv_points, recv_cells), sources, _, recv_counts, _ = exchange_to_owners(
311 comm, src_owner, [points, source_cells]
312 )
314 # One entry per received point, naming the rank it came from. `sources` is
315 # ascending and `exchange_to_owners` receives in that order, so the runs are
316 # contiguous by construction -- which `scatter_values` requires.
317 dest_owners = np.repeat(sources, recv_counts).astype(np.int32)
319 dtype = np.dtype(points.dtype)
320 cls = getattr(_cpp.geometry, f"PointOwnershipData_float{8 * dtype.itemsize}")
321 return dolfinx.geometry.PointOwnershipData(
322 cls(
323 np.ascontiguousarray(src_owner, dtype=np.int32),
324 dest_owners,
325 np.ascontiguousarray(recv_points, dtype=dtype).reshape(-1),
326 np.ascontiguousarray(recv_cells, dtype=np.int32),
327 )
328 )
331def transfer_submesh_function(
332 u_source: dolfinx.fem.Function,
333 u_dest: dolfinx.fem.Function,
334 post_code: npt.NDArray[np.int64],
335):
336 """Move data from a standalone submesh onto one re-derived from a parent.
338 ``u_source`` lives on the submesh as it was stored -- read with
339 :func:`io4dolfinx.read_mesh` and :func:`io4dolfinx.read_function` -- and
340 ``u_dest`` on the submesh :func:`read_submesh` derived from the parent. The
341 two meshes cover the same cells but number their vertices differently and are
342 partitioned independently, so the transfer cannot be a copy.
344 Every cell of ``u_dest``'s mesh has a known counterpart in ``u_source``'s, so
345 each interpolation point is routed straight to the process and cell that can
346 evaluate it, with no geometric point location. This is an evaluation followed
347 by a scatter and a local interpolation: it assembles no form and needs no
348 entity map between the two meshes, which would have no meaning as neither is
349 derived from the other.
351 Args:
352 u_source: Function on the submesh as stored
353 u_dest: Function to fill, on the submesh re-derived from the parent
354 post_code: For each cell of ``u_dest``'s mesh (owned and ghost), the
355 index that cell had in the stored submesh, which is what the cell is
356 routed by. From :attr:`SubmeshCheckpoint.post_code`.
358 Raises:
359 NotImplementedError: For H(div)/H(curl) spaces on a manifold submesh
360 with a DOLFINx lacking ``FiniteElement.physical_base_value_size``,
361 whose interpolation would return wrong values without reporting an
362 error.
363 """
364 V_dest = u_dest.function_space
365 dest_mesh = V_dest.mesh
366 source_mesh = u_source.function_space.mesh
367 comm = dest_mesh.comm
368 assert isinstance(comm, MPI.Intracomm)
370 tdim = dest_mesh.topology.dim
371 supports_manifold_transform = hasattr(dolfinx.fem.FiniteElement, "physical_base_value_size")
372 manifold_transformations = (
373 tdim < dest_mesh.geometry.dim and V_dest.element.needs_dof_transformations
374 )
376 if manifold_transformations and not supports_manifold_transform:
377 raise NotImplementedError(
378 "Transferring an H(div)/H(curl) function onto a submesh with"
379 f" tdim ({tdim}) < gdim ({dest_mesh.geometry.dim}) is not supported."
380 " This DOLFINx cannot reconcile the reference and physical value sizes"
381 " of these families on a manifold (FEniCS/dolfinx#3619,"
382 " https://github.com/FEniCS/dolfinx/issues/3619, fixed on the main"
383 " branch by FEniCS/dolfinx#4511), and the interpolation"
384 " this transfer relies on does not report that: it returns silently"
385 " with values that are wrong (measured: the L2 norm of an N1curl field"
386 " on a facet submesh fell from 9.096 to 4.904). Writing and reading the"
387 " standalone submesh is exact for these spaces -- use `read_mesh` and"
388 " `read_function` with the submesh's `mesh_name` and stop there. Only"
389 " re-deriving from the parent is unavailable."
390 )
392 sub_imap = dest_mesh.topology.index_map(tdim)
393 num_cells = sub_imap.size_local + sub_imap.num_ghosts
394 # Both checks below are collective. What follows them is a neighbourhood
395 # exchange, so a process that raised on its own would leave the others
396 # waiting at it: every process has to reach the same verdict, even one whose
397 # own data is fine.
398 if comm.allreduce(len(post_code) != num_cells, MPI.LOR):
399 raise ValueError(
400 "Expected one stored cell index per cell of the destination mesh;"
401 " the counts disagree on at least one process."
402 f" Here: {num_cells} cells, {len(post_code)} indices."
403 )
404 post_code = np.asarray(post_code, dtype=np.int64)
405 cells = np.arange(num_cells, dtype=np.int32)
407 # Interpolation points of the destination, grouped per cell.
408 points = _cpp.fem.interpolation_coords(
409 V_dest.element._cpp_object, # type: ignore[arg-type]
410 dest_mesh.geometry._cpp_object, # type: ignore[arg-type]
411 cells,
412 )
413 points = np.ascontiguousarray(points.T) # (num_points, 3)
414 points_per_cell = 0 if num_cells == 0 else points.shape[0] // num_cells
416 # Which process holds each stored cell in the source mesh, and where.
417 source_tdim = source_mesh.topology.dim
418 source_imap = source_mesh.topology.index_map(source_tdim)
419 # `index_owner` asserts that its indices are in range, and that assert is
420 # local: a process tripping it would abort while every other process waited
421 # for it in the exchange below. So the range is checked collectively first.
422 num_stored = source_imap.size_global
423 out_of_range = post_code[(post_code < 0) | (post_code >= num_stored)]
424 if comm.allreduce(len(out_of_range), MPI.SUM) > 0:
425 raise ValueError(
426 f"Post codes must index cells of the stored submesh, which has"
427 f" {num_stored} of them. Out of range here: {out_of_range[:5]}."
428 )
430 owner_rank, owner_cell = _lookup_post_code(
431 comm,
432 np.asarray(source_mesh.topology.original_cell_index[: source_imap.size_local]),
433 post_code,
434 num_stored,
435 )
436 # Counting owned cells only makes this an exact global tally: a ghost carries
437 # the same post code as its owner and so resolves the same way, and would
438 # otherwise be counted once per process holding it.
439 missing = np.flatnonzero(owner_rank[: sub_imap.size_local] < 0)
440 num_missing = comm.allreduce(len(missing), MPI.SUM)
441 if num_missing > 0:
442 raise RuntimeError(
443 f"{num_missing} cells of the destination submesh have no counterpart"
444 " in the stored submesh. The two must describe the same submesh of the"
445 f" same parent. Post codes missing here: {post_code[missing][:5]}."
446 )
448 interpolation_data = _point_ownership_data(
449 comm,
450 np.repeat(owner_rank, points_per_cell),
451 points,
452 np.repeat(owner_cell, points_per_cell),
453 )
454 u_dest.interpolate_nonmatching(u_source, cells, interpolation_data=interpolation_data)
455 u_dest.x.scatter_forward()
458def _lookup_post_code(
459 comm: MPI.Intracomm,
460 owned_post_code: npt.NDArray[np.int64],
461 queried_post_code: npt.NDArray[np.int64],
462 num_cells_global: int,
463) -> tuple[npt.NDArray[np.int32], npt.NDArray[np.int32]]:
464 """Locate each post code in the *stored* submesh: which process, which cell.
466 Which side is which follows from what each submesh is. The stored submesh is
467 the standalone one, independent of the parent, and it is where the data
468 lives, so it is the side that publishes: it says where each of its cells is
469 held. The submesh re-derived from the parent is the side that needs that
470 information, so it is the side that queries.
472 The two are partitioned independently, so neither knows where the other put a
473 given cell. Both talk to a third: the process that :func:`index_owner`
474 assigns the post code in the equal-split layout acts as a directory. Owners
475 publish into it, queriers read out of it, each in one neighbourhood exchange,
476 so no process ever holds a global table.
478 Every process is on both sides, it holds part of each submesh, so it
479 publishes for the stored cells it owns and queries for the re-derived cells
480 it holds, which is why the two arrays below come from different meshes.
482 Args:
483 comm: The MPI communicator both submeshes live on
484 owned_post_code: Post code of each cell this process owns in the
485 **stored** submesh, which for a mesh read back from a checkpoint is
486 its ordinary ``topology.original_cell_index``. The position in the
487 array is that cell's local index in the stored submesh, and that
488 index is what gets published.
489 queried_post_code: Post codes this process wants to locate, one per cell
490 of the **re-derived** submesh, owned and ghost
491 num_cells_global: Number of cells in the stored submesh, globally
493 Returns:
494 ``(rank, local_cell)`` aligned with ``queried_post_code``: the process
495 that owns that cell in the **stored** submesh, and the cell's local index
496 in *that* process's stored submesh -- not in the re-derived one. Both are
497 ``-1`` where the post code was never published.
498 """
499 directory_range = compute_local_range(comm, num_cells_global)
500 directory_size = int(directory_range[1] - directory_range[0])
501 directory_rank = np.full(directory_size, -1, dtype=np.int32)
502 directory_cell = np.full(directory_size, -1, dtype=np.int32)
504 # Publish: each owner tells the directory where it keeps the cell.
505 owned_post_code = np.asarray(owned_post_code, dtype=np.int64)
506 local_cells = np.arange(len(owned_post_code), dtype=np.int32)
507 publish_to = index_owner(comm, owned_post_code, num_cells_global)
508 (pub_keys, pub_cells), pub_sources, _, pub_counts, _ = exchange_to_owners(
509 comm, publish_to, [owned_post_code, local_cells]
510 )
511 slots = (pub_keys - directory_range[0]).astype(np.int64)
512 directory_rank[slots] = np.repeat(pub_sources, pub_counts)
513 directory_cell[slots] = pub_cells
515 # Query: ask the directory, and unpack the reply into the order asked.
516 queried_post_code = np.asarray(queried_post_code, dtype=np.int64)
517 query_to = index_owner(comm, queried_post_code, num_cells_global)
518 (inc_keys,), q_sources, q_send_counts, q_recv_counts, q_insert = exchange_to_owners(
519 comm, query_to, [queried_post_code]
520 )
521 inc_slots = (inc_keys - directory_range[0]).astype(np.int64)
522 reply_rank = directory_rank[inc_slots]
523 reply_cell = directory_cell[inc_slots]
525 # Send the answers back along the reverse of the query graph.
526 q_destinations = np.unique(query_to)
527 reverse = comm.Create_dist_graph_adjacent(
528 q_destinations.tolist(), q_sources.tolist(), reorder=False
529 )
530 packed_rank = np.zeros(len(queried_post_code), dtype=np.int32)
531 packed_cell = np.zeros(len(queried_post_code), dtype=np.int32)
532 reverse.Neighbor_alltoallv(
533 [reply_rank, q_recv_counts, numpy_to_mpi[np.int32]],
534 [packed_rank, q_send_counts, numpy_to_mpi[np.int32]],
535 )
536 reverse.Neighbor_alltoallv(
537 [reply_cell, q_recv_counts, numpy_to_mpi[np.int32]],
538 [packed_cell, q_send_counts, numpy_to_mpi[np.int32]],
539 )
540 reverse.Free()
542 # `q_insert[i]` is where local entry `i` was packed into the outgoing buffer,
543 # and the reply comes back in that same packed order, so read the answers
544 # back out by gathering -- scattering here would apply the inverse
545 # permutation and silently mix up which cell each answer belongs to.
546 return packed_rank[q_insert], packed_cell[q_insert]