Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/checkpointing.py: 97%

304 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 12:02 +0000

1# Copyright (C) 2023-2026 Jørgen Schartum Dokken 

2# 

3# This file is part of io4dolfinx 

4# 

5# SPDX-License-Identifier: MIT 

6 

7from __future__ import annotations 

8 

9import logging 

10import typing 

11import warnings 

12from pathlib import Path 

13from typing import Any, Callable 

14 

15from mpi4py import MPI 

16 

17import basix 

18import dolfinx 

19import fenicsx_compat 

20import numpy as np 

21import numpy.typing as npt 

22import ufl 

23 

24from .backends import FileMode, ReadMode, get_backend, get_mesh_name, with_mesh_name 

25from .comm_helpers import ( 

26 send_and_recv_cell_perm, 

27 send_dofmap_and_recv_values, 

28 send_dofs_and_recv_values, 

29 send_to_input_order, 

30) 

31from .format import check_appendable, check_readable, object_metadata, stamp 

32from .original_checkpoint import create_function_data_on_original_mesh, create_original_mesh_data 

33from .readers import create_geometry_function_space 

34from .structures import ArrayData, FunctionData, MeshTagsData, ReadMixedMeshData 

35from .utils import ( 

36 check_file_exists, 

37 compute_dofmap_pos, 

38 compute_local_range, 

39 coordinate_element, 

40 create_mixed_mesh, 

41 index_owner, 

42 input_cell_index, 

43 unroll_dofmap, 

44 unroll_insert_position, 

45) 

46from .writers import prepare_meshdata_for_storage 

47from .writers import write_function as _internal_function_writer 

48from .writers import write_mesh as _internal_mesh_writer 

49 

50__all__ = [ 

51 "read_mesh", 

52 "write_function", 

53 "read_function", 

54 "write_mesh", 

55 "read_meshtags", 

56 "write_meshtags", 

57 "read_attributes", 

58 "write_attributes", 

59] 

60 

61logger = logging.getLogger(__name__) 

62 

63 

64def write_attributes( 

65 filename: Path | str, 

66 comm: MPI.Comm, 

67 name: str, 

68 attributes: dict[str, np.ndarray], 

69 backend_args: dict[str, typing.Any] | None = None, 

70 backend: str | None = None, 

71): 

72 """Write attributes to file. 

73 

74 Args: 

75 filename: Path to file to write to 

76 comm: MPI communicator used in storage 

77 name: Name of the attributes 

78 attributes: Dictionary of attributes to write to file 

79 backend_args: Arguments for backend, for instance file type. 

80 backend: What backend to use for writing. 

81 """ 

82 logger.debug(f"Writing attributes to {filename} for attribute {name}") 

83 logger.debug(f"Using {backend} backend with arguments {backend_args} to write attributes") 

84 backend_cls = get_backend(backend) 

85 backend_args = backend_cls.get_default_backend_args(backend_args) 

86 backend_cls.write_attributes(filename, comm, name, attributes, backend_args) 

87 

88 

89def read_attributes( 

90 filename: Path | str, 

91 comm: MPI.Comm, 

92 name: str, 

93 backend_args: dict[str, typing.Any] | None = None, 

94 backend: str | None = None, 

95) -> dict[str, typing.Any]: 

96 """Read attributes from file. 

97 

98 Args: 

99 filename: Path to file to read from 

100 comm: MPI communicator used in storage 

101 name: Name of the attributes 

102 backend_args: Arguments for backend, for instance file type. 

103 backend: What backend to use for writing. 

104 Returns: 

105 The attributes 

106 """ 

107 logger.debug(f"Reading attributes from {filename} for attribute {name}") 

108 logger.debug(f"Using {backend} backend with arguments {backend_args} to read attributes") 

109 backend_cls = get_backend(backend) 

110 backend_args = backend_cls.get_default_backend_args(backend_args) 

111 return backend_cls.read_attributes(filename, comm, name, backend_args) 

112 

113 

114def read_timestamps( 

115 filename: Path | str, 

116 comm: MPI.Comm, 

117 function_name: str, 

118 backend_args: dict[str, typing.Any] | None = None, 

119 backend: str | None = None, 

120 mesh_name: str | None = None, 

121) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var] 

122 """ 

123 Read time-stamps from a checkpoint file. 

124 

125 Args: 

126 comm: MPI communicator 

127 filename: Path to file 

128 function_name: Name of the function to read time-stamps for 

129 backend_args: Arguments for backend, for instance file type. 

130 backend: What backend to use for writing. 

131 mesh_name: Name of the mesh in the file to act on. Defaults to the 

132 mesh written without an explicit name, so existing checkpoints and 

133 call sites are unaffected. 

134 Returns: 

135 The time-stamps 

136 

137 Raises: 

138 KeyError: With the adios2 and h5py backends, if the file does not hold the 

139 function on that mesh. The message names the functions it does hold. 

140 """ 

141 backend_args = with_mesh_name(backend_args, mesh_name) 

142 logger.debug(f"Reading time-stamps from {filename} for function {function_name}") 

143 logger.debug(f"Using {backend} backend with arguments {backend_args} to read time-stamps") 

144 check_file_exists(filename) 

145 backend_cls = get_backend(backend) 

146 backend_args = backend_cls.get_default_backend_args(backend_args) 

147 return backend_cls.read_timestamps(filename, comm, function_name, backend_args) 

148 

149 

150def write_meshtags( 

151 filename: Path | str, 

152 mesh: dolfinx.mesh.Mesh, 

153 meshtags: dolfinx.mesh.MeshTags, 

154 meshtag_name: typing.Optional[str] = None, 

155 backend_args: dict[str, Any] | None = None, 

156 backend: str | None = None, 

157 on_input_mesh: bool = False, 

158 mesh_name: str | None = None, 

159): 

160 """ 

161 Write meshtags associated with input mesh to file. 

162 

163 .. note:: 

164 For this checkpoint to work, the mesh must be written to file 

165 using :func:`write_mesh` before calling this function. 

166 

167 Args: 

168 filename: Path to save meshtags (with file-extension) 

169 mesh: The mesh associated with the meshtags 

170 meshtags: The meshtags to write to file 

171 meshtag_name: Name of the meshtag. If None, the meshtag name is used. 

172 backend_args: Backend-specific options. For VTKHDF compression, 

173 see :ref:`vtkhdfbackend`. 

174 backend: IO backend 

175 on_input_mesh: If True, the meshtags are written with the node ordering 

176 of the input mesh. Use the same value for every write to a file; 

177 see :ref:`input-ordering`. 

178 mesh_name: Name of the mesh in the file to act on. Defaults to the 

179 mesh written without an explicit name, so existing checkpoints and 

180 call sites are unaffected. 

181 """ 

182 backend_args = with_mesh_name(backend_args, mesh_name) 

183 logger.debug(f"Writing meshtags to {filename} for meshtag {meshtag_name or meshtags.name}") 

184 logger.debug(f"Using {backend} backend with arguments {backend_args} to write meshtags") 

185 

186 # Extract data from meshtags (convert to global geometry node indices for each entity) 

187 tag_entities = meshtags.indices 

188 dim = meshtags.dim 

189 num_tag_entities_local = mesh.topology.index_map(dim).size_local 

190 local_tag_entities = tag_entities[tag_entities < num_tag_entities_local] 

191 local_values = meshtags.values[: len(local_tag_entities)] 

192 

193 num_saved_tag_entities = len(local_tag_entities) 

194 assert isinstance(mesh.comm, MPI.Intracomm) 

195 local_start = mesh.comm.exscan(num_saved_tag_entities, op=MPI.SUM) 

196 local_start = local_start if mesh.comm.rank != 0 else 0 

197 global_num_tag_entities = mesh.comm.allreduce(num_saved_tag_entities, op=MPI.SUM) 

198 

199 dof_layout = fenicsx_compat.cmap(mesh).create_dof_layout() 

200 num_dofs_per_entity = len(dof_layout.entity_closure_dofs(dim, 0)) 

201 mesh.topology.create_connectivity(dim, mesh.topology.dim) 

202 mesh.topology.create_connectivity(0, mesh.topology.dim) 

203 entities_to_geometry = dolfinx.cpp.mesh.entities_to_geometry( 

204 mesh._cpp_object, dim, local_tag_entities, False 

205 ) 

206 

207 if on_input_mesh: 

208 indices = mesh.geometry.input_global_indices[entities_to_geometry] 

209 else: 

210 indices = ( 

211 mesh.geometry.index_map() 

212 .local_to_global(entities_to_geometry.reshape(-1)) 

213 .reshape(entities_to_geometry.shape) 

214 ) 

215 name = meshtag_name or meshtags.name 

216 

217 tag_ct = dolfinx.cpp.mesh.cell_entity_type(mesh.topology.cell_type, dim, 0).name 

218 tag_data = MeshTagsData( 

219 metadata=stamp(), 

220 values=local_values, 

221 num_entities_global=global_num_tag_entities, 

222 num_dofs_per_entity=num_dofs_per_entity, 

223 indices=indices, 

224 name=name, 

225 local_start=local_start, 

226 dim=meshtags.dim, 

227 cell_type=tag_ct, 

228 ) 

229 

230 # Get backend and default arguments 

231 backend_cls = get_backend(backend) 

232 backend_args = backend_cls.get_default_backend_args(backend_args) 

233 check_appendable( 

234 object_metadata(backend_cls, filename, mesh.comm, "mesh", None, backend_args), 

235 f"The mesh '{get_mesh_name(backend_args)}' in {filename}", 

236 ) 

237 return backend_cls.write_meshtags(filename, mesh.comm, tag_data, backend_args=backend_args) 

238 

239 

240def read_meshtags( 

241 filename: Path | str, 

242 mesh: dolfinx.mesh.Mesh, 

243 meshtag_name: str, 

244 backend_args: dict[str, Any] | None = None, 

245 backend: str | None = None, 

246 mesh_name: str | None = None, 

247) -> dolfinx.mesh.MeshTags: 

248 """ 

249 Read meshtags from file and return a :class:`dolfinx.mesh.MeshTags` object. 

250 

251 Args: 

252 filename: Path to meshtags file (with file-extension) 

253 mesh: The mesh associated with the meshtags. Its numbering must match the 

254 one the meshtags were written in; see :ref:`input-ordering`. 

255 meshtag_name: The name of the meshtag to read 

256 engine: Adios2 Engine 

257 mesh_name: Name of the mesh in the file to act on. Defaults to the 

258 mesh written without an explicit name, so existing checkpoints and 

259 call sites are unaffected. 

260 Returns: 

261 The meshtags 

262 """ 

263 backend_args = with_mesh_name(backend_args, mesh_name) 

264 logger.debug(f"Reading meshtags from {filename} for meshtag {meshtag_name}") 

265 logger.debug(f"Using {backend} backend with arguments {backend_args} to read meshtags") 

266 check_file_exists(filename) 

267 backend_cls = get_backend(backend) 

268 backend_args = backend_cls.get_default_backend_args(backend_args) 

269 if backend_args.get("legacy", False): 

270 warnings.warn( 

271 "Reading mesh tags of legacy DOLFIN files with legacy=True is deprecated. Convert " 

272 "the file once with io4dolfinx.convert or the io4dolfinx-convert command, with " 

273 f"--meshtags {meshtag_name}.", 

274 DeprecationWarning, 

275 stacklevel=2, 

276 ) 

277 check_readable( 

278 object_metadata(backend_cls, filename, mesh.comm, "meshtags", meshtag_name, backend_args), 

279 f"Mesh tags '{meshtag_name}' in {filename}", 

280 ) 

281 data = backend_cls.read_meshtags_data(filename, mesh.comm, meshtag_name, backend_args) 

282 

283 indices = data.indices 

284 if indices.shape[0] == 0: 

285 # A backend without entities may not know the number of geometry nodes per entity 

286 layout = fenicsx_compat.cmap(mesh).create_dof_layout() 

287 num_nodes = len(layout.entity_closure_dofs(int(data.dim), 0)) 

288 indices = np.zeros((0, num_nodes), dtype=np.int64) 

289 local_entities, local_values = dolfinx.io.distribute_entity_data( 

290 mesh, int(data.dim), indices, data.values 

291 ) 

292 mesh.topology.create_connectivity(data.dim, 0) 

293 mesh.topology.create_connectivity(data.dim, mesh.topology.dim) 

294 

295 adj = dolfinx.graph.adjacencylist(local_entities) 

296 

297 local_values = np.array(local_values, dtype=np.int32) 

298 

299 mt = dolfinx.mesh.meshtags_from_entities(mesh, int(data.dim), adj, local_values) 

300 mt.name = meshtag_name 

301 return mt 

302 

303 

304def read_function( 

305 filename: Path | str, 

306 u: dolfinx.fem.Function, 

307 time: float = 0.0, 

308 name: str | None = None, 

309 backend_args: dict[str, Any] | None = None, 

310 backend: str | None = None, 

311 mesh_name: str | None = None, 

312): 

313 """ 

314 Read checkpoint from file and fill it into `u`. 

315 

316 Args: 

317 filename: Path to checkpoint 

318 u: Function to fill. Its mesh's numbering must match the one the function 

319 was written in; see :ref:`input-ordering`. 

320 time: Time-stamp associated with checkpoint 

321 name: If not provided, `u.name` is used to search through the input file for the function 

322 mesh_name: Name of the mesh in the file to act on. Defaults to the 

323 mesh written without an explicit name, so existing checkpoints and 

324 call sites are unaffected. 

325 """ 

326 backend_args = with_mesh_name(backend_args, mesh_name) 

327 logger.debug( 

328 f"Reading function checkpoint from {filename} for function {name or u.name} at time {time}" 

329 ) 

330 logger.debug( 

331 f"Using {backend} backend with arguments {backend_args} to read function checkpoint" 

332 ) 

333 check_file_exists(filename) 

334 

335 mesh = u.function_space.mesh 

336 comm = mesh.comm 

337 if name is None: 

338 name = u.name 

339 

340 check_file_exists(filename) 

341 backend_cls = get_backend(backend) 

342 backend_args = backend_cls.get_default_backend_args(backend_args) 

343 check_readable( 

344 object_metadata(backend_cls, filename, comm, "function", name, backend_args), 

345 f"Function '{name}' in {filename}", 

346 ) 

347 

348 # Compute index of input cells and get cell permutation 

349 num_owned_cells = mesh.topology.index_map(mesh.topology.dim).size_local 

350 input_cells = mesh.topology.original_cell_index[:num_owned_cells] 

351 cell_perm = fenicsx_compat.cell_permutation_info(mesh.topology)[:num_owned_cells] 

352 

353 # Compute mesh->input communicator 

354 # 1.1 Compute mesh->input communicator 

355 owners: npt.NDArray[np.int32] 

356 if backend_cls.read_mode == ReadMode.serial: 

357 owners = np.zeros(input_cells, dtype=np.int32) 

358 elif backend_cls.read_mode == ReadMode.parallel: 

359 num_cells_global = mesh.topology.index_map(mesh.topology.dim).size_global 

360 owners = index_owner(mesh.comm, input_cells, num_cells_global) 

361 else: 

362 raise NotImplementedError(f"{backend_cls.read_mode} not implemented") 

363 # -------------------Step 2------------------------------------ 

364 # Send and receive global cell index and cell perm 

365 inc_cells, inc_perms = send_and_recv_cell_perm(input_cells, cell_perm, owners, mesh.comm) 

366 

367 input_dofmap = backend_cls.read_dofmap(filename, comm, name, backend_args) 

368 

369 # Compute owner of dofs in dofmap 

370 dof_owner: npt.NDArray[np.int32] 

371 if backend_cls.read_mode == ReadMode.serial: 

372 dof_owner = np.zeros(len(input_dofmap.array), dtype=np.int32) 

373 elif backend_cls.read_mode == ReadMode.parallel: 

374 num_dofs_global = ( 

375 u.function_space.dofmap.index_map.size_global * u.function_space.dofmap.index_map_bs 

376 ) 

377 dof_owner = index_owner(comm, input_dofmap.array.astype(np.int64), num_dofs_global) 

378 else: 

379 raise NotImplementedError(f"{backend_cls.read_mode} not implemented") 

380 

381 # --------------------Step 4----------------------------------- 

382 # Read array from file and communicate them to input dofmap process 

383 input_array, starting_pos = backend_cls.read_dofs(filename, comm, name, time, backend_args) 

384 

385 recv_array = send_dofs_and_recv_values( 

386 input_dofmap.array.astype(np.int64), dof_owner, comm, input_array, starting_pos 

387 ) 

388 

389 # -------------------Step 5-------------------------------------- 

390 # Invert permutation of input data based on input perm 

391 # Then apply current permutation to the local data 

392 element = u.function_space.element 

393 if element.needs_dof_transformations: 

394 bs = u.function_space.dofmap.bs 

395 

396 # Read input cell permutations on dofmap process 

397 local_input_range = compute_local_range(comm, num_cells_global) 

398 input_local_cell_index = inc_cells - local_input_range[0] 

399 input_perms = backend_cls.read_cell_perms(comm, filename, backend_args) 

400 

401 # Start by sorting data array by cell permutation 

402 num_dofs_per_cell = input_dofmap.offsets[1:] - input_dofmap.offsets[:-1] 

403 assert np.allclose(num_dofs_per_cell, num_dofs_per_cell[0]) 

404 

405 # Sort dofmap by input local cell index 

406 input_perms_sorted = input_perms[input_local_cell_index] 

407 unrolled_dofmap_position = unroll_insert_position( 

408 input_local_cell_index, num_dofs_per_cell[0] 

409 ) 

410 dofmap_sorted_by_input = recv_array[unrolled_dofmap_position] 

411 

412 # First invert input data to reference element then transform to current mesh 

413 element.Tt_apply(dofmap_sorted_by_input, input_perms_sorted, bs) 

414 element.Tt_inv_apply(dofmap_sorted_by_input, inc_perms, bs) 

415 # Compute invert permutation 

416 inverted_perm = np.empty_like(unrolled_dofmap_position) 

417 inverted_perm[unrolled_dofmap_position] = np.arange( 

418 len(unrolled_dofmap_position), dtype=inverted_perm.dtype 

419 ) 

420 recv_array = dofmap_sorted_by_input[inverted_perm] 

421 

422 # ------------------Step 6---------------------------------------- 

423 # For each dof owned by a process, find the local position in the dofmap. 

424 V = u.function_space 

425 local_cells, dof_pos = compute_dofmap_pos(V) 

426 input_cells = V.mesh.topology.original_cell_index[local_cells] 

427 num_cells_global = V.mesh.topology.index_map(V.mesh.topology.dim).size_global 

428 

429 if backend_cls.read_mode == ReadMode.serial: 

430 owners = np.zeros(len(input_cells), dtype=np.int32) 

431 elif backend_cls.read_mode == ReadMode.parallel: 

432 owners = index_owner(V.mesh.comm, input_cells, num_cells_global) 

433 else: 

434 raise NotImplementedError(f"{backend_cls.read_mode} not implemented") 

435 

436 unique_owners, owner_count = np.unique(owners, return_counts=True) 

437 # FIXME: In C++ use NBX to find neighbourhood 

438 assert isinstance(V.mesh.comm, MPI.Intracomm) 

439 sub_comm = V.mesh.comm.Create_dist_graph( 

440 [V.mesh.comm.rank], [len(unique_owners)], unique_owners.tolist(), reorder=False 

441 ) 

442 source, dest, _ = sub_comm.Get_dist_neighbors() 

443 sub_comm.Free() 

444 

445 owned_values = send_dofmap_and_recv_values( 

446 comm, 

447 np.asarray(source, dtype=np.int32), 

448 np.asarray(dest, dtype=np.int32), 

449 owners, 

450 owner_count.astype(np.int32), 

451 input_cells, 

452 dof_pos, 

453 num_cells_global, 

454 recv_array, 

455 input_dofmap.offsets, 

456 ) 

457 u.x.array[: len(owned_values)] = owned_values 

458 u.x.scatter_forward() 

459 

460 

461def read_mesh( 

462 filename: Path | str, 

463 comm: MPI.Comm, 

464 ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.shared_facet, 

465 time: float | str | None = 0.0, 

466 read_from_partition: bool = False, 

467 backend_args: dict[str, Any] | None = None, 

468 backend: str | None = None, 

469 max_facet_to_cell_links: int = 2, 

470 mesh_name: str | None = None, 

471) -> dolfinx.mesh.Mesh: 

472 """ 

473 Read an ADIOS2 mesh into DOLFINx. 

474 

475 Args: 

476 filename: Path to input file 

477 comm: The MPI communciator to distribute the mesh over 

478 ghost_mode: Ghost mode to use for mesh. If `read_from_partition` 

479 is set to `True` this option is ignored. 

480 time: Time stamp associated with mesh 

481 read_from_partition: Read mesh with partition from file 

482 backend_args: List of arguments to reader backend 

483 max_facet_to_cell_links: Maximum number of cells a facet 

484 can be connected to. 

485 mesh_name: Name of the mesh in the file to act on. Defaults to the 

486 mesh written without an explicit name, so existing checkpoints and 

487 call sites are unaffected. 

488 Returns: 

489 The distributed mesh. A mesh with several cell types, which only some backends 

490 read, has no UFL domain and requires DOLFINx 0.11 or later. 

491 """ 

492 backend_args = with_mesh_name(backend_args, mesh_name) 

493 logger.debug(f"Reading mesh from {filename}") 

494 logger.debug(f"Using {backend} backend with arguments {backend_args}") 

495 logger.debug(f"Time {time} and read_from_partition {read_from_partition}") 

496 # Read in data in a distributed fashin 

497 check_file_exists(filename) 

498 backend_cls = get_backend(backend) 

499 backend_args = backend_cls.get_default_backend_args(backend_args) 

500 check_readable( 

501 object_metadata(backend_cls, filename, comm, "mesh", None, backend_args), 

502 f"The mesh '{get_mesh_name(backend_args)}' in {filename}", 

503 ) 

504 

505 # Let each backend handle what should be default behavior when reading mesh 

506 # with or without time stamp. 

507 dist_in_data = backend_cls.read_mesh_data( 

508 filename, 

509 comm, 

510 time=time, 

511 read_from_partition=read_from_partition, 

512 backend_args=backend_args, 

513 ) 

514 

515 if isinstance(dist_in_data, ReadMixedMeshData): 

516 return create_mixed_mesh( 

517 comm, 

518 dist_in_data.cells, 

519 dist_in_data.cell_types, 

520 dist_in_data.x, 

521 dist_in_data.degree, 

522 dist_in_data.lvar, 

523 ghost_mode=ghost_mode, 

524 max_facet_to_cell_links=max_facet_to_cell_links, 

525 ) 

526 

527 # Create DOLFINx mesh 

528 element = basix.ufl.blocked_element( 

529 coordinate_element( 

530 dist_in_data.cell_type, 

531 dist_in_data.degree, 

532 dist_in_data.lvar, 

533 dist_in_data.serendipity, 

534 dist_in_data.x.dtype, 

535 ), 

536 shape=(dist_in_data.x.shape[1],), 

537 ) 

538 domain = ufl.Mesh(element) 

539 # `dolfinx.mesh.PartitioningFunc` is not available in all supported 

540 # versions of DOLFINx, and the accepted callback signature varies (see 

541 # below), so type the callback permissively. 

542 partitioner: Callable[..., dolfinx.cpp.graph.AdjacencyList_int32] | None = None 

543 if (partition_graph := dist_in_data.partition_graph) is not None: 

544 # The arguments DOLFINx passes to a partitioner callback have changed 

545 # over time: 0.11 calls it with 

546 # ``(comm, nparts, cell_types, local_graph)``, while newer versions call 

547 # it with ``(comm, nparts, dual_graph, cell_weights, edge_weights, 

548 # ghosting)`` (see https://github.com/FEniCS/dolfinx/pull/4403). 

549 # We read the partitioning from file, so the returned graph does not 

550 # depend on any of these arguments. Accept them all and stay agnostic to 

551 # the calling convention rather than branching on `dolfinx.__version__`, 

552 # which does not distinguish pre-releases and post-releases reliably. 

553 def _custom_partitioner(*args: Any, **kwargs: Any) -> dolfinx.cpp.graph.AdjacencyList_int32: 

554 if hasattr(partition_graph, "_cpp_object"): 

555 cpp_obj = partition_graph._cpp_object 

556 assert isinstance(cpp_obj, dolfinx.cpp.graph.AdjacencyList_int32) 

557 return cpp_obj 

558 else: 

559 assert isinstance(partition_graph, dolfinx.cpp.graph.AdjacencyList_int32) 

560 return partition_graph 

561 

562 partitioner = _custom_partitioner 

563 

564 return fenicsx_compat.create_mesh( 

565 comm, 

566 dist_in_data.cells, 

567 domain, 

568 dist_in_data.x, 

569 partitioner=partitioner, 

570 ghost_mode=ghost_mode, 

571 max_facet_to_cell_links=max_facet_to_cell_links, 

572 ) 

573 

574 

575def write_mesh( 

576 filename: Path, 

577 mesh: dolfinx.mesh.Mesh, 

578 mode: FileMode = FileMode.write, 

579 time: float = 0.0, 

580 store_partition_info: bool = False, 

581 backend_args: dict[str, Any] | None = None, 

582 backend: str | None = None, 

583 mesh_name: str | None = None, 

584 on_input_mesh: bool = False, 

585): 

586 """ 

587 Write a mesh to file. 

588 

589 Args: 

590 filename: Path to save mesh (without file-extension) 

591 mesh: The mesh to write to file 

592 

593 store_partition_info: Store mesh partitioning (including ghosting) to file 

594 backend_args: Backend-specific options. For VTKHDF compression, 

595 see :ref:`vtkhdfbackend`. 

596 mesh_name: Name of the mesh in the file to act on. Defaults to the 

597 mesh written without an explicit name, so existing checkpoints and 

598 call sites are unaffected. 

599 on_input_mesh: If True, the mesh is written with the node and cell ordering of 

600 the input mesh, so the file does not depend on the number of processes. 

601 Cannot be combined with ``store_partition_info``. Use the same value for 

602 every write to a file; see :ref:`input-ordering`. 

603 """ 

604 backend_args = with_mesh_name(backend_args, mesh_name) 

605 logger.debug(f"Writing mesh to {filename}") 

606 if on_input_mesh: 

607 if store_partition_info: 

608 raise ValueError( 

609 "Cannot store partition info for a mesh written in the input ordering." 

610 ) 

611 logger.debug("Preparing mesh data in the input ordering") 

612 mesh_data = create_original_mesh_data(mesh) 

613 else: 

614 logger.debug( 

615 f"Preparing mesh data for storage storing partition info: {store_partition_info}" 

616 ) 

617 mesh_data = prepare_meshdata_for_storage( 

618 mesh=mesh, store_partition_info=store_partition_info 

619 ) 

620 logger.debug(f"Write mesh using {backend} backend, with arguments {backend_args}") 

621 logger.debug(f"Mode {mode} and time {time}") 

622 if mode == FileMode.append: 

623 check_appendable( 

624 object_metadata(get_backend(backend), filename, mesh.comm, "mesh", None, backend_args), 

625 f"The mesh '{get_mesh_name(backend_args)}' in {filename}", 

626 ) 

627 _internal_mesh_writer( 

628 filename, 

629 mesh.comm, 

630 mesh_data=mesh_data, 

631 time=time, 

632 backend_args=backend_args, 

633 backend=backend, 

634 mode=mode, 

635 ) 

636 

637 

638def _check_function_appendable( 

639 filename: Path, 

640 comm: MPI.Comm, 

641 name: str, 

642 backend: str | None, 

643 backend_args: dict[str, Any] | None, 

644): 

645 """Check that the mesh and the function ``name`` in a file can be appended to.""" 

646 backend_cls = get_backend(backend) 

647 check_appendable( 

648 object_metadata(backend_cls, filename, comm, "mesh", None, backend_args), 

649 f"The mesh '{get_mesh_name(backend_args)}' in {filename}", 

650 ) 

651 check_appendable( 

652 object_metadata(backend_cls, filename, comm, "function", name, backend_args), 

653 f"Function '{name}' in {filename}", 

654 ) 

655 

656 

657def write_function( 

658 filename: Path | str, 

659 u: dolfinx.fem.Function, 

660 time: float = 0.0, 

661 mode: FileMode = FileMode.append, 

662 name: str | None = None, 

663 backend_args: dict[str, Any] | None = None, 

664 backend: str | None = None, 

665 mesh_name: str | None = None, 

666 on_input_mesh: bool = False, 

667): 

668 """ 

669 Write function checkpoint to file. 

670 

671 Args: 

672 u: Function to write to file 

673 time: Time-stamp for simulation 

674 filename: Path to write to 

675 mode: Write or append. 

676 name: Name of function to write. If None, the name of the function is used. 

677 backend_args: Arguments to the IO backend. 

678 backend: The backend to use 

679 mesh_name: Name of the mesh in the file to act on. Defaults to the 

680 mesh written without an explicit name, so existing checkpoints and 

681 call sites are unaffected. 

682 on_input_mesh: If True, the function is written against the input mesh, to be 

683 read with a mesh written with ``on_input_mesh=True`` (or read from the 

684 input mesh file). Use the same value for every write to a file; 

685 see :ref:`input-ordering`. 

686 """ 

687 backend_args = with_mesh_name(backend_args, mesh_name) 

688 n = u.name if name is None else name 

689 logger.debug(f"Writing function checkpoint to {filename} for function {n} at time {time}") 

690 logger.debug(f"Using {backend} backend with arguments {backend_args}") 

691 if on_input_mesh: 

692 fname = Path(filename) 

693 comm = u.function_space.mesh.comm 

694 function_data = create_function_data_on_original_mesh(u, name) 

695 if mode == FileMode.append: 

696 _check_function_appendable(fname, comm, function_data.name, backend, backend_args) 

697 _internal_function_writer( 

698 fname, comm, function_data, time, backend_args=backend_args, backend=backend, mode=mode 

699 ) 

700 return 

701 dofmap = u.function_space.dofmap 

702 values = u.x.array 

703 mesh = u.function_space.mesh 

704 comm = mesh.comm 

705 cell_perm = fenicsx_compat.cell_permutation_info(mesh.topology) 

706 num_cells_local = mesh.topology.index_map(mesh.topology.dim).size_local 

707 local_cell_range = mesh.topology.index_map(mesh.topology.dim).local_range 

708 num_cells_global = mesh.topology.index_map(mesh.topology.dim).size_global 

709 

710 # Convert local dofmap into global_dofmap 

711 dmap = dofmap.list 

712 num_dofs_per_cell = dmap.shape[1] 

713 dofmap_bs = dofmap.bs 

714 num_dofs_local_dmap = num_cells_local * num_dofs_per_cell * dofmap_bs 

715 index_map_bs = dofmap.index_map_bs 

716 

717 # Unroll dofmap for block size 

718 unrolled_dofmap = unroll_dofmap(dofmap.list[:num_cells_local, :], dofmap_bs) 

719 dmap_loc = (unrolled_dofmap // index_map_bs).reshape(-1) 

720 dmap_rem = (unrolled_dofmap % index_map_bs).reshape(-1) 

721 

722 # Convert imap index to global index 

723 imap_global = dofmap.index_map.local_to_global(dmap_loc) 

724 dofmap_global = imap_global * index_map_bs + dmap_rem 

725 dofmap_imap = fenicsx_compat.create_index_map( 

726 mesh.comm, 

727 num_dofs_local_dmap, 

728 np.empty(0, dtype=np.int64), 

729 np.empty(0, dtype=np.int32), 

730 ) 

731 

732 # Compute dofmap offsets 

733 local_dofmap_offsets = np.arange(num_cells_local + 1, dtype=np.int64) 

734 local_dofmap_offsets[:] *= num_dofs_per_cell * dofmap_bs 

735 local_dofmap_offsets += dofmap_imap.local_range[0] 

736 

737 num_dofs_global = dofmap.index_map.size_global * dofmap.index_map_bs 

738 local_dof_range = np.asarray(dofmap.index_map.local_range) * dofmap.index_map_bs 

739 num_dofs_local = local_dof_range[1] - local_dof_range[0] 

740 

741 # Create internal data structure for function data to write to file 

742 function_data = FunctionData( 

743 metadata=stamp(), 

744 cell_permutations=cell_perm[:num_cells_local].copy(), 

745 local_cell_range=local_cell_range, 

746 num_cells_global=num_cells_global, 

747 dofmap_array=dofmap_global, 

748 dofmap_offsets=local_dofmap_offsets, 

749 dofmap_range=dofmap_imap.local_range, 

750 global_dofs_in_dofmap=dofmap_imap.size_global, 

751 values=values[:num_dofs_local].copy(), 

752 dof_range=(local_dof_range[0], local_dof_range[1]), 

753 num_dofs_global=num_dofs_global, 

754 name=name or u.name, 

755 ) 

756 # Write to file 

757 fname = Path(filename) 

758 if mode == FileMode.append: 

759 _check_function_appendable(fname, comm, function_data.name, backend, backend_args) 

760 _internal_function_writer( 

761 fname, comm, function_data, time, backend_args=backend_args, backend=backend, mode=mode 

762 ) 

763 

764 

765def write_function_on_input_mesh( 

766 filename: Path | str, 

767 u: dolfinx.fem.Function, 

768 time: float = 0.0, 

769 name: str | None = None, 

770 mode: FileMode = FileMode.append, 

771 backend_args: dict[str, Any] | None = None, 

772 backend: str | None = None, 

773): 

774 """ 

775 Write function checkpoint (to be read with the input mesh). 

776 

777 Deprecated: use :func:`write_function` with ``on_input_mesh=True``. 

778 

779 Note: 

780 Requires backend to implement :meth:`io4dolfinx.backends.IOBackend.write_function`. 

781 

782 Args: 

783 filename: The filename to write to 

784 u: The function to checkpoint 

785 time: Time-stamp associated with function at current write step 

786 mode: The mode to use (write or append) 

787 name: Name of function. If None, the name of the function is used. 

788 backend_args: Arguments to backend 

789 backend: Choice of backend module 

790 """ 

791 warnings.warn( 

792 "write_function_on_input_mesh is deprecated and will be removed in a future release. " 

793 + "Use write_function with on_input_mesh=True instead.", 

794 category=DeprecationWarning, 

795 stacklevel=2, 

796 ) 

797 write_function( 

798 filename, 

799 u, 

800 time=time, 

801 mode=mode, 

802 name=name, 

803 backend_args=backend_args, 

804 backend=backend, 

805 on_input_mesh=True, 

806 ) 

807 

808 

809def write_mesh_input_order( 

810 filename: Path | str, 

811 mesh: dolfinx.mesh.Mesh, 

812 time: float = 0.0, 

813 mode: FileMode = FileMode.write, 

814 backend: str | None = None, 

815 backend_args: dict[str, Any] | None = None, 

816): 

817 """ 

818 Write mesh to checkpoint file in original input ordering. 

819 

820 Deprecated: use :func:`write_mesh` with ``on_input_mesh=True``. 

821 

822 Note: 

823 Requires backend to implement :meth:`io4dolfinx.backends.IOBackend.write_mesh`. 

824 

825 Args: 

826 filename: The filename to write to 

827 mesh: Mesh to checkpoint 

828 time: Time-stamp associated with function at current write step 

829 mode: The mode to use (write or append) 

830 backend_args: Arguments to backend 

831 backend: Choice of backend module 

832 """ 

833 warnings.warn( 

834 "write_mesh_input_order is deprecated and will be removed in a future release. " 

835 + "Use write_mesh with on_input_mesh=True instead.", 

836 category=DeprecationWarning, 

837 stacklevel=2, 

838 ) 

839 write_mesh( 

840 Path(filename), 

841 mesh, 

842 mode=mode, 

843 time=time, 

844 backend_args=backend_args, 

845 backend=backend, 

846 on_input_mesh=True, 

847 ) 

848 

849 

850def read_function_names( 

851 filename: Path | str, 

852 comm: MPI.Comm, 

853 backend_args: dict[str, Any] | None = None, 

854 backend: str = "h5py", 

855 mesh_name: str | None = None, 

856) -> list[str]: 

857 """Read all function names from a file. 

858 

859 Args: 

860 filename: Path to file 

861 comm: MPI communicator to launch IO on. 

862 backend_args: Arguments to backend 

863 mesh_name: Name of the mesh in the file to act on. Defaults to the 

864 mesh written without an explicit name, so existing checkpoints and 

865 call sites are unaffected. 

866 

867 Returns: 

868 A list of function names. 

869 """ 

870 backend_args = with_mesh_name(backend_args, mesh_name) 

871 logger.debug(f"Reading function names from {filename}") 

872 logger.debug(f"Using {backend} backend with arguments {backend_args} to read function names") 

873 check_file_exists(filename) 

874 backend_cls = get_backend(backend) 

875 return backend_cls.read_function_names(filename, comm, backend_args=backend_args) 

876 

877 

878def write_point_data( 

879 filename: Path | str, 

880 u: dolfinx.fem.Function, 

881 time: str | float | None, 

882 mode: FileMode, 

883 backend_args: dict[str, Any] | None, 

884 backend: str = "vtkhdf", 

885 mesh_name: str | None = None, 

886 on_input_mesh: bool = False, 

887): 

888 """Write function to file by interpolating into geometry nodes. 

889 

890 

891 Args: 

892 filename: Path to file 

893 u: The function to store 

894 time: Time stamp 

895 mode: Append or write 

896 backend_args: Backend-specific options. For VTKHDF compression, 

897 see :ref:`vtkhdfbackend`. 

898 backend: Which backend to use. 

899 mesh_name: Name of the mesh in the file to write the data against. 

900 Defaults to the mesh written without an explicit name. 

901 on_input_mesh: If True, the node values are written in the node ordering of the 

902 input mesh, matching a mesh written with :func:`write_mesh_input_order`. 

903 """ 

904 backend_args = with_mesh_name(backend_args, mesh_name) 

905 logger.debug(f"Writing point data to {filename} for function {u.name} at time {time}") 

906 V = create_geometry_function_space( 

907 u.function_space.mesh, int(np.prod(u.ufl_shape)), value_shape=u.ufl_shape 

908 ) 

909 v_out = dolfinx.fem.Function(V, name=u.name, dtype=u.x.array.dtype) 

910 v_out.interpolate(u) 

911 comm = v_out.function_space.mesh.comm 

912 data_shape = (V.dofmap.index_map.size_global, V.dofmap.index_map_bs) 

913 local_range = V.dofmap.index_map.local_range 

914 num_dofs_local = V.dofmap.index_map.size_local 

915 data = v_out.x.array.reshape(-1, V.dofmap.index_map_bs)[:num_dofs_local] 

916 

917 if on_input_mesh: 

918 # The dofs of the geometry space are the geometry nodes 

919 input_nodes = V.mesh.geometry.input_global_indices[:num_dofs_local] 

920 assert isinstance(comm, MPI.Intracomm) 

921 (data,), local_range = send_to_input_order(comm, input_nodes, [data], data_shape[0]) 

922 

923 ad = ArrayData( 

924 name=v_out.name, 

925 values=data, 

926 global_shape=data_shape, 

927 local_range=local_range, 

928 type="Point", 

929 value_shape=tuple(u.ufl_shape), 

930 ) 

931 logger.debug( 

932 f"Using {backend} backend with arguments {backend_args} and mode {mode} to write point data" 

933 ) 

934 backend_cls = get_backend(backend) 

935 return backend_cls.write_data( 

936 filename, comm=comm, mode=mode, time=time, array_data=ad, backend_args=backend_args 

937 ) 

938 

939 

940def write_cell_data( 

941 filename: Path | str, 

942 u: dolfinx.fem.Function, 

943 time: str | float | None, 

944 mode: FileMode, 

945 backend_args: dict[str, Any] | None, 

946 backend: str = "vtkhdf", 

947 mesh_name: str | None = None, 

948 on_input_mesh: bool = False, 

949): 

950 """Write function to file by interpolating into cell midpoints. 

951 

952 

953 Args: 

954 filename: Path to file 

955 point_data: Data to write to file 

956 time: Time stamp 

957 mode: Append or write 

958 backend_args: Backend-specific options. For VTKHDF compression, 

959 see :ref:`vtkhdfbackend`. 

960 mesh_name: Name of the mesh in the file to write the data against. 

961 Defaults to the mesh written without an explicit name. 

962 on_input_mesh: If True, the cell values are written in the cell ordering of the 

963 input mesh, matching a mesh written with :func:`write_mesh_input_order`. 

964 """ 

965 backend_args = with_mesh_name(backend_args, mesh_name) 

966 logger.debug(f"Writing cell data to {filename} for function {u.name} at time {time}") 

967 if u.function_space.ufl_element().family_name == "quadrature": 

968 raise ValueError( 

969 f"Cannot write {u.name!r} as cell data, as a function in a quadrature space cannot " 

970 "be interpolated into DG-0." 

971 ) 

972 V = dolfinx.fem.functionspace(u.function_space.mesh, ("DG", 0, u.ufl_shape)) 

973 v_out = dolfinx.fem.Function(V, name=u.name, dtype=u.x.array.dtype) 

974 v_out.interpolate(u) 

975 comm = v_out.function_space.mesh.comm 

976 data_shape = (V.dofmap.index_map.size_global, V.dofmap.index_map_bs) 

977 values = v_out.x.array.reshape(-1, V.dofmap.index_map_bs) 

978 

979 if on_input_mesh: 

980 # DG-0 dofs of owned cells are owned, so send the value of each owned cell 

981 mesh = V.mesh 

982 tdim = mesh.topology.dim 

983 num_owned_cells = mesh.topology.index_map(tdim).size_local 

984 input_cells = input_cell_index(mesh)[:num_owned_cells] 

985 cell_values = values[V.dofmap.list[:num_owned_cells, 0]] 

986 assert isinstance(comm, MPI.Intracomm) 

987 (data,), local_range = send_to_input_order(comm, input_cells, [cell_values], data_shape[0]) 

988 else: 

989 local_range = V.dofmap.index_map.local_range 

990 data = values[: V.dofmap.index_map.size_local] 

991 

992 ad = ArrayData( 

993 name=v_out.name, 

994 values=data, 

995 global_shape=data_shape, 

996 local_range=local_range, 

997 type="Cell", 

998 value_shape=tuple(u.ufl_shape), 

999 ) 

1000 logger.debug( 

1001 f"Using {backend} backend with arguments {backend_args} and mode {mode} to write cell data" 

1002 ) 

1003 backend_cls = get_backend(backend) 

1004 

1005 return backend_cls.write_data( 

1006 filename, comm=comm, mode=mode, time=time, array_data=ad, backend_args=backend_args 

1007 )