Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/__init__.py: 95%

114 statements  

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

1import warnings 

2from collections.abc import Iterable 

3from enum import Enum 

4from importlib import import_module 

5from pathlib import Path 

6from typing import Any, Protocol 

7 

8from mpi4py import MPI 

9 

10import dolfinx 

11import numpy as np 

12import numpy.typing as npt 

13 

14from ..structures import ( 

15 ArrayData, 

16 FunctionData, 

17 MeshData, 

18 MeshTagsData, 

19 ReadMeshData, 

20 ReadMixedMeshData, 

21) 

22 

23__all__ = [ 

24 "DEFAULT_MESH_NAME", 

25 "FileMode", 

26 "IOBackend", 

27 "function_not_found", 

28 "get_backend", 

29 "get_mesh_name", 

30 "set_default_backend", 

31 "with_mesh_name", 

32] 

33 

34_DEFAULT_BACKEND = "h5py" 

35 

36#: Name used for a mesh when the caller does not supply one. A file written 

37#: before named meshes existed holds exactly this mesh, so backends must store 

38#: it exactly as they did before (see :func:`get_mesh_name`). 

39DEFAULT_MESH_NAME = "mesh" 

40 

41 

42def get_mesh_name(backend_args: dict[str, Any] | None) -> str: 

43 """Get the name of the mesh a backend call refers to. 

44 

45 A checkpoint may hold several meshes -- for instance a mesh and a submesh of 

46 it -- distinguished by name. Backends take the name from 

47 ``backend_args["name"]``. 

48 

49 Args: 

50 backend_args: Arguments to backend, or None 

51 

52 Returns: 

53 The mesh name, :data:`DEFAULT_MESH_NAME` if none was given. 

54 """ 

55 if backend_args is None: 

56 return DEFAULT_MESH_NAME 

57 name = backend_args.get("name", DEFAULT_MESH_NAME) 

58 return DEFAULT_MESH_NAME if name is None else str(name) 

59 

60 

61def with_mesh_name( 

62 backend_args: dict[str, Any] | None, mesh_name: str | None 

63) -> dict[str, Any] | None: 

64 """Backend arguments selecting the mesh ``mesh_name``, as backends expect them. 

65 

66 Public functions take the mesh as ``mesh_name``, while backends read it from 

67 ``backend_args["name"]`` (see :func:`get_mesh_name`). Passing the mesh name in 

68 ``backend_args`` to a public function is deprecated. 

69 

70 Args: 

71 backend_args: Backend arguments of the caller, not modified. 

72 mesh_name: Name of the mesh, or ``None`` for the default mesh. 

73 

74 Returns: 

75 ``backend_args`` with ``"name"`` set to ``mesh_name``. 

76 

77 Raises: 

78 ValueError: If ``backend_args["name"]`` and ``mesh_name`` name different meshes. 

79 """ 

80 if backend_args is not None and "name" in backend_args: 

81 if mesh_name is not None and backend_args["name"] != mesh_name: 

82 raise ValueError( 

83 f"backend_args['name']={backend_args['name']!r} and mesh_name={mesh_name!r} " 

84 "name different meshes; pass mesh_name only." 

85 ) 

86 warnings.warn( 

87 "Passing the mesh name as backend_args['name'] is deprecated; use mesh_name.", 

88 DeprecationWarning, 

89 stacklevel=3, 

90 ) 

91 return backend_args 

92 if mesh_name is None: 

93 return backend_args 

94 return {**(backend_args or {}), "name": mesh_name} 

95 

96 

97def function_not_found( 

98 filename: Path | str, function_name: str, mesh_name: str, function_names: Iterable[str] 

99) -> KeyError: 

100 """The error for a function a checkpoint does not hold, naming the ones it does. 

101 

102 The names tell a misspelt name, or one written on another mesh, from a function that 

103 was never written. 

104 

105 Args: 

106 filename: Path to the file 

107 function_name: Name of the function asked for 

108 mesh_name: Name of the mesh it was asked for on 

109 function_names: Names of the functions the file holds on that mesh 

110 

111 Returns: 

112 The error to raise 

113 """ 

114 names = sorted(set(function_names)) 

115 holds = ( 

116 f"Functions on that mesh: {', '.join(map(repr, names))}." 

117 if names 

118 else "There are no functions on that mesh." 

119 ) 

120 return KeyError( 

121 f"Function {function_name!r} not found on mesh {mesh_name!r} in {filename}. {holds}" 

122 ) 

123 

124 

125def set_default_backend(backend: str): 

126 """Set the global default backend for io4dolfinx.""" 

127 global _DEFAULT_BACKEND 

128 if backend not in BUILTIN_BACKENDS: 

129 try: 

130 get_backend(backend) 

131 except ImportError as e: 

132 raise ImportError(f"Backend {backend} not found.") from e 

133 _DEFAULT_BACKEND = backend 

134 

135 

136def get_default_backend(): 

137 """Get the global default backend for io4dolfinx.""" 

138 return _DEFAULT_BACKEND 

139 

140 

141class ReadMode(Enum): 

142 serial = 10 # This means that all data is read in on root rank 

143 

144 # Total number of data P, num processes = i + 1. 

145 # All processes reads at least `P // (i+1)` items 

146 # The first j=P%(i+1) processes reads `P // (i+1) + 1` items 

147 # ```python 

148 # def compute_partitioning(P, J): 

149 # min_num = P // J 

150 # num_per_proc = np.full(J, min_num) 

151 # rem = P % J 

152 # num_per_proc[:int(rem)] += 1 

153 # assert(sum(num_per_proc)) == P 

154 # return num_per_proc 

155 # ``` 

156 parallel = 20 

157 

158 

159class FileMode(Enum): 

160 """Filen mode used for opening files.""" 

161 

162 append = 10 #: Append data to file 

163 write = 20 #: Write data to file 

164 read = 30 #: Read data from file 

165 

166 

167# See https://peps.python.org/pep-0544/#modules-as-implementations-of-protocols 

168class IOBackend(Protocol): 

169 """Interface a storage backend must provide. 

170 

171 .. note:: 

172 A checkpoint may hold more than one mesh, each with its own topology, 

173 geometry, meshtags, cell permutations and functions. Every method that 

174 touches mesh-associated data takes the mesh it refers to from 

175 ``backend_args["name"]``; use :func:`get_mesh_name` to read it, so that 

176 omitting it selects :data:`DEFAULT_MESH_NAME` consistently. A backend 

177 must store that default mesh exactly as it did before named meshes 

178 existed, so that older checkpoints stay readable. 

179 """ 

180 

181 read_mode: ReadMode 

182 

183 def get_default_backend_args(self, arguments: dict[str, Any] | None) -> dict[str, Any]: 

184 """Get default backend arguments given a set of input arguments. 

185 

186 Args: 

187 arguments: Input backend arguments 

188 

189 Returns: 

190 Updated backend arguments 

191 """ 

192 

193 def write_attributes( 

194 self, 

195 filename: Path | str, 

196 comm: MPI.Comm, 

197 name: str, 

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

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

200 ): 

201 """Write attributes to file. 

202 

203 Args: 

204 filename: Path to file to write to 

205 comm: MPI communicator used in storage 

206 name: Name of the attribute group 

207 attributes: Dictionary of attributes to write 

208 backend_args: Arguments to backend 

209 """ 

210 

211 def read_attributes( 

212 self, 

213 filename: Path | str, 

214 comm: MPI.Comm, 

215 name: str, 

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

217 ) -> dict[str, Any]: 

218 """Read attributes from file. 

219 

220 Args: 

221 filename: Path to file to read from 

222 comm: MPI communicator used in storage 

223 name: Name of the attribute group 

224 backend_args: Arguments to backend 

225 

226 Returns: 

227 Dictionary of attributes read from file 

228 """ 

229 

230 def read_timestamps( 

231 self, 

232 filename: Path | str, 

233 comm: MPI.Comm, 

234 function_name: str, 

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

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

237 """Read timestamps from file. 

238 

239 Args: 

240 filename: Path to file to read from 

241 comm: MPI communicator used in storage 

242 function_name: Name of the function to read timestamps for 

243 backend_args: Arguments to backend 

244 

245 Returns: 

246 Numpy array of timestamps read from file 

247 

248 Raises: 

249 KeyError: In the adios2 and h5py backends, if the file does not hold the 

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

251 (:func:`function_not_found`). 

252 """ 

253 

254 def write_mesh( 

255 self, 

256 filename: Path | str, 

257 comm: MPI.Comm, 

258 mesh: MeshData, 

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

260 mode: FileMode, 

261 time: float, 

262 ): 

263 """ 

264 Write a mesh to file. 

265 

266 Args: 

267 comm: MPI communicator used in storage 

268 mesh: Internal data structure for the mesh data to save to file 

269 filename: Path to file to write to 

270 backend_args: Arguments to backend 

271 mode: File-mode to store the mesh 

272 time: Time stamp associated with the mesh 

273 """ 

274 

275 def write_meshtags( 

276 self, 

277 filename: str | Path, 

278 comm: MPI.Comm, 

279 data: MeshTagsData, 

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

281 ): 

282 """Write mesh tags to file. 

283 

284 Args: 

285 filename: Path to file to write to 

286 comm: MPI communicator used in storage 

287 data: Internal data structure for the mesh tags to save to file 

288 backend_args: Arguments to backend 

289 """ 

290 

291 def read_mesh_data( 

292 self, 

293 filename: Path | str, 

294 comm: MPI.Comm, 

295 time: str | float | None, 

296 read_from_partition: bool, 

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

298 ) -> ReadMeshData | ReadMixedMeshData: 

299 """Read mesh data from file. 

300 

301 Args: 

302 filename: Path to file to read from 

303 comm: MPI communicator used in storage 

304 time: Time stamp associated with the mesh to read 

305 read_from_partition: Whether to read partition information 

306 backend_args: Arguments to backend 

307 

308 Returns: 

309 Internal data structure for the mesh data read from file, 

310 :class:`~io4dolfinx.structures.ReadMixedMeshData` for a mesh with several 

311 cell types 

312 """ 

313 

314 def read_meshtags_data( 

315 self, 

316 filename: str | Path, 

317 comm: MPI.Comm, 

318 name: str, 

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

320 ) -> MeshTagsData: 

321 """Read mesh tags from file. 

322 

323 Args: 

324 filename: Path to file to read from 

325 comm: MPI communicator used in storage 

326 name: Name of the mesh tags to read 

327 backend_args: Arguments to backend 

328 

329 Returns: 

330 Internal data structure for the mesh tags read from file 

331 """ 

332 

333 def read_dofmap( 

334 self, 

335 filename: str | Path, 

336 comm: MPI.Comm, 

337 name: str, 

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

339 ) -> dolfinx.graph.AdjacencyList: 

340 """Read the dofmap of a function with a given name. 

341 

342 Args: 

343 filename: Path to file to read from 

344 comm: MPI communicator used in storage 

345 name: Name of the function to read the dofmap for 

346 backend_args: Arguments to backend 

347 

348 Returns: 

349 Dofmap as an :class:`dolfinx.graph.AdjacencyList` 

350 """ 

351 

352 def read_dofs( 

353 self, 

354 filename: str | Path, 

355 comm: MPI.Comm, 

356 name: str, 

357 time: float, 

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

359 ) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]: 

360 """Read the dofs (values) of a function with a given name from a given timestep. 

361 

362 Args: 

363 filename: Path to file to read from 

364 comm: MPI communicator used in storage 

365 name: Name of the function to read the dofs for 

366 time: Time stamp associated with the function to read 

367 backend_args: Arguments to backend 

368 

369 Returns: 

370 Contiguous sequence of degrees of freedom (with respect to input data) 

371 and the global starting point on the process. 

372 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc. 

373 """ 

374 

375 def read_cell_perms( 

376 self, comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None 

377 ) -> npt.NDArray[np.uint32]: 

378 """ 

379 Read cell permutation from file with given communicator, 

380 Split in continuous chunks based on number of cells in the input data. 

381 

382 Cell permutations belong to a mesh, not to a function, so which mesh is 

383 meant is taken from ``backend_args["name"]``. 

384 

385 Args: 

386 comm: MPI communicator used in storage 

387 filename: Path to file to read from 

388 backend_args: Arguments to backend 

389 

390 Returns: 

391 Contiguous sequence of permutations (with respect to input data) 

392 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc. 

393 """ 

394 

395 def write_function( 

396 self, 

397 filename: Path, 

398 comm: MPI.Comm, 

399 u: FunctionData, 

400 time: float, 

401 mode: FileMode, 

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

403 ): 

404 """Write a function to file. 

405 

406 Args: 

407 comm: MPI communicator used in storage 

408 u: Internal data structure for the function data to save to file 

409 filename: Path to file to write to 

410 time: Time stamp associated with function 

411 mode: File-mode to store the function 

412 backend_args: Arguments to backend 

413 """ 

414 

415 def read_legacy_mesh( 

416 self, filename: Path | str, comm: MPI.Comm, group: str 

417 ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]: 

418 """Read in the mesh topology, geometry and (optionally) cell type from a 

419 legacy DOLFIN HDF5-file. 

420 

421 Args: 

422 filename: Path to file to read from 

423 comm: MPI communicator used in storage 

424 group: Group in HDF5 file where mesh is stored 

425 

426 Returns: 

427 Tuple containing: 

428 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices 

429 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates 

430 - Cell type as a string (e.g. "tetrahedron") or None if not found 

431 """ 

432 

433 def snapshot_checkpoint( 

434 self, 

435 filename: Path | str, 

436 mode: FileMode, 

437 u: dolfinx.fem.Function, 

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

439 ): 

440 """Create a snapshot checkpoint of a dolfinx function. 

441 

442 Args: 

443 filename: Path to file to read from 

444 mode: File-mode to store the function 

445 u: dolfinx function to create a snapshot checkpoint for 

446 backend_args: Arguments to backend 

447 """ 

448 

449 def read_hdf5_array( 

450 self, 

451 comm: MPI.Comm, 

452 filename: Path | str, 

453 group: str, 

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

455 ) -> tuple[np.ndarray, int]: 

456 """Read an array from an HDF5 file. 

457 

458 Args: 

459 comm: MPI communicator used in storage 

460 filename: Path to file to read from 

461 group: Group in HDF5 file where array is stored 

462 backend_args: Arguments to backend 

463 

464 Returns: 

465 Tuple containing: 

466 - Numpy array read from file 

467 - Global starting point on the process. 

468 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc. 

469 """ 

470 

471 def read_point_data( 

472 self, 

473 filename: Path | str, 

474 name: str, 

475 comm: MPI.Comm, 

476 time: str | float | None, 

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

478 ) -> tuple[np.ndarray, int]: 

479 """Read data from the nodes of a mesh. 

480 

481 Args: 

482 filename: Path to file 

483 name: Name of point data 

484 comm: Communicator to launch IO on. 

485 time: The time stamp 

486 backend_args: The backend arguments 

487 Returns: 

488 Data local to process (contiguous, no mpi comm) and local start range 

489 """ 

490 ... 

491 

492 def read_function_names( 

493 self, filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None 

494 ) -> list[str]: 

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

496 

497 Args: 

498 filename: Path to file 

499 comm: MPI communicator to launch IO on. 

500 backend_args: Arguments to backend 

501 

502 Returns: 

503 A list of function names. 

504 """ 

505 ... 

506 

507 def read_cell_data( 

508 self, 

509 filename: Path | str, 

510 name: str, 

511 comm: MPI.Comm, 

512 time: str | float | None, 

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

514 ) -> tuple[npt.NDArray[np.int64], np.ndarray]: 

515 """Read data from the cells of a mesh. 

516 

517 Args: 

518 filename: Path to file 

519 name: Name of point data 

520 comm: Communicator to launch IO on. 

521 time: The time stamp 

522 backend_args: The backend arguments 

523 Returns: 

524 A tuple (topology, dofs) where topology contains the 

525 vertex indices of the cells, dofs the degrees of 

526 freedom within that cell. 

527 """ 

528 ... 

529 

530 def write_data( 

531 self, 

532 filename: Path | str, 

533 array_data: ArrayData, 

534 comm: MPI.Comm, 

535 time: str | float | None, 

536 mode: FileMode, 

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

538 ): 

539 """Write a 2D-array to file. 

540 

541 

542 Args: 

543 filename: Path to file 

544 array_data: Data to write to file. 

545 comm: The MPI communicator to open the writer with. 

546 time: The time stamp 

547 mode: Append or write 

548 backend_args: The backend arguments 

549 """ 

550 ... 

551 

552 

553def get_backend(backend: str | None = None) -> IOBackend: 

554 """Get backend class from backend name. 

555 

556 Args: 

557 backend: Name of the backend to get 

558 

559 Returns: 

560 Backend class 

561 """ 

562 if backend is None: 

563 backend = _DEFAULT_BACKEND 

564 

565 if backend in ("h5py", "vtkhdf"): 

566 import h5py 

567 

568 if not h5py.get_config().mpi: 

569 warnings.warn( 

570 f"h5py is built without MPI, so the {backend} backend runs as " 

571 f"{backend}-serial, which writes all data through rank 0. Install h5py " 

572 "with MPI for parallel IO, see the io4dolfinx installation guide.", 

573 stacklevel=2, 

574 ) 

575 backend = f"{backend}-serial" 

576 elif backend == "adios2": 

577 import adios2 

578 

579 if not adios2.is_built_with_mpi: 

580 warnings.warn( 

581 "ADIOS2 is built without MPI, so the adios2 backend runs as adios2-serial, " 

582 "which writes all data through rank 0. Install ADIOS2 with MPI for parallel IO, " 

583 "see the io4dolfinx installation guide.", 

584 stacklevel=2, 

585 ) 

586 backend = "adios2-serial" 

587 

588 if backend == "h5py": 

589 from .h5py import backend as H5PYInterface 

590 

591 return H5PYInterface 

592 elif backend == "h5py-serial": 

593 from .h5py_serial import backend as H5PYSerialInterface 

594 

595 return H5PYSerialInterface 

596 elif backend == "vtkhdf-serial": 

597 from .vtkhdf_serial import backend as VTKHDFSerialInterface 

598 

599 return VTKHDFSerialInterface 

600 elif backend == "adios2": 

601 from .adios2 import backend as ADIOS2Interface 

602 

603 return ADIOS2Interface 

604 elif backend == "adios2-serial": 

605 from .adios2_serial import backend as ADIOS2SerialInterface 

606 

607 return ADIOS2SerialInterface 

608 elif backend == "pyvista": 

609 from .pyvista import backend as PYVISTAInterface 

610 

611 return PYVISTAInterface 

612 elif backend == "xdmf": 

613 from .xdmf import backend as XDMFInterface 

614 

615 return XDMFInterface 

616 elif backend == "vtkhdf": 

617 from .vtkhdf import backend as VTKDHFInterface 

618 

619 return VTKDHFInterface 

620 elif backend == "exodus": 

621 from .exodus import backend as EXODUSInterface 

622 

623 return EXODUSInterface 

624 elif backend == "med": 

625 from .med import backend as MEDInterface 

626 

627 return MEDInterface 

628 elif backend == "gmsh": 

629 from .gmsh import backend as GMSHInterface 

630 

631 return GMSHInterface 

632 elif backend == "opencarp": 

633 from .opencarp import backend as OpenCARPInterface 

634 

635 return OpenCARPInterface 

636 elif backend == "nastran": 

637 from .nastran import backend as NASTRANInterface 

638 

639 return NASTRANInterface 

640 elif backend == "openfoam": 

641 from .openfoam import backend as OpenFOAMInterface 

642 

643 return OpenFOAMInterface 

644 else: 

645 return import_module(backend) 

646 

647 

648BUILTIN_BACKENDS = ( 

649 "h5py", 

650 "h5py-serial", 

651 "vtkhdf-serial", 

652 "adios2", 

653 "adios2-serial", 

654 "pyvista", 

655 "xdmf", 

656 "vtkhdf", 

657 "exodus", 

658 "med", 

659 "gmsh", 

660 "opencarp", 

661 "nastran", 

662 "openfoam", 

663) 

664 

665 

666def list_builtin_backends() -> list[str]: 

667 """List available builtin backends. 

668 

669 Returns: 

670 List of available backends 

671 """ 

672 lst = [] 

673 for backend in BUILTIN_BACKENDS: 

674 try: 

675 get_backend(backend) 

676 except ImportError: 

677 continue 

678 lst.append(backend) 

679 return lst