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

82 statements  

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

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

2# 

3# This file is part of io4dolfinx 

4# 

5# SPDX-License-Identifier: MIT 

6 

7"""Run the HDF5 and ADIOS2 backends with h5py or ADIOS2 built without MPI. 

8 

9The serial backends (``h5py-serial``, ``vtkhdf-serial`` and ``adios2-serial``) write the 

10same files as the backends they wrap, without parallel IO: 

11 

12- To read, every process opens the file on its own and reads its part, as many processes 

13 may read a file at the same time. 

14- To write, the data is gathered on rank 0, which writes it with the backend it wraps on 

15 :data:`mpi4py.MPI.COMM_SELF`. Rank 0 then holds all the data being written. 

16 

17:func:`io4dolfinx.backends.get_backend` uses them in place of ``h5py`` and ``vtkhdf`` when 

18h5py is built without MPI, and in place of ``adios2`` when ADIOS2 is built without MPI. 

19""" 

20 

21from __future__ import annotations 

22 

23import contextlib 

24import contextvars 

25import dataclasses 

26import functools 

27from collections.abc import Callable, Generator 

28from typing import Any, TypeVar 

29 

30from mpi4py import MPI 

31 

32import numpy as np 

33import numpy.typing as npt 

34 

35from ..comm_helpers import run_on_root 

36from ..structures import ArrayData, FunctionData, MeshData, MeshTagsData 

37from .h5py.backend import force_serial_files 

38 

39__all__ = [ 

40 "serial_files", 

41 "serial", 

42 "gather_rows", 

43 "gather_mesh", 

44 "gather_function", 

45 "gather_meshtags", 

46 "gather_array", 

47 "write_on_root", 

48] 

49 

50F = TypeVar("F", bound=Callable[..., Any]) 

51T = TypeVar("T") 

52 

53 

54@contextlib.contextmanager 

55def serial_files( 

56 flag: contextvars.ContextVar[bool] = force_serial_files, 

57) -> Generator[None, None, None]: 

58 """Open files without MPI on every rank within the context. 

59 

60 Args: 

61 flag: The flag making a backend open files without MPI: HDF5 files by default, 

62 :data:`io4dolfinx.backends.adios2.helpers.force_serial_adios` for ADIOS2. 

63 """ 

64 token = flag.set(True) 

65 try: 

66 yield 

67 finally: 

68 flag.reset(token) 

69 

70 

71def serial(fn: F, flag: contextvars.ContextVar[bool] = force_serial_files) -> F: 

72 """The function, opening files without MPI on every rank. 

73 

74 Args: 

75 fn: The function to wrap. 

76 flag: The flag making a backend open files without MPI, see :func:`serial_files`. 

77 

78 Returns: 

79 The wrapped function. 

80 """ 

81 

82 @functools.wraps(fn) 

83 def wrapper(*args, **kwargs): 

84 with serial_files(flag): 

85 return fn(*args, **kwargs) 

86 

87 return wrapper # type: ignore[return-value] 

88 

89 

90def gather_rows( 

91 comm: MPI.Comm, start: int, rows: npt.NDArray, overlap: bool = False 

92) -> npt.NDArray | None: 

93 """The rows of all processes on rank 0, in global order. 

94 

95 Args: 

96 comm: The communicator the rows are divided over. 

97 start: The global position of this process's first row. 

98 rows: This process's rows. 

99 overlap: Whether the last row of each process is the first row of the next, as 

100 for offsets. It is then kept once. 

101 

102 Returns: 

103 All rows on rank 0, ``None`` on the other ranks. 

104 """ 

105 parts = comm.gather((start, rows), root=0) 

106 if parts is None: 

107 return None 

108 ordered = [part for _, part in sorted(parts, key=lambda part: part[0])] 

109 if overlap: 

110 ordered = [part[:-1] for part in ordered[:-1]] + ordered[-1:] 

111 return np.concatenate(ordered) 

112 

113 

114def gather_mesh(comm: MPI.Comm, mesh: MeshData) -> MeshData | None: 

115 """The mesh data of all processes on rank 0, ``None`` on the other ranks.""" 

116 geometry = gather_rows(comm, mesh.local_geometry_pos[0], mesh.local_geometry) 

117 topology = gather_rows(comm, mesh.local_topology_pos[0], mesh.local_topology) 

118 ownership_array = ownership_offset = None 

119 partition_range = None 

120 if mesh.store_partition: 

121 assert mesh.partition_range is not None and mesh.ownership_offset is not None 

122 assert mesh.ownership_array is not None and mesh.partition_global is not None 

123 partition_range = (0, mesh.partition_global) 

124 ownership_array = gather_rows(comm, mesh.partition_range[0], mesh.ownership_array) 

125 ownership_offset = gather_rows( 

126 comm, mesh.local_topology_pos[0], mesh.ownership_offset, overlap=True 

127 ) 

128 if comm.rank != 0: 

129 return None 

130 assert geometry is not None and topology is not None 

131 return dataclasses.replace( 

132 mesh, 

133 local_geometry=geometry, 

134 local_geometry_pos=(0, mesh.num_nodes_global), 

135 local_topology=topology, 

136 local_topology_pos=(0, mesh.num_cells_global), 

137 ownership_array=ownership_array, 

138 ownership_offset=ownership_offset, 

139 partition_range=partition_range, 

140 ) 

141 

142 

143def gather_function(comm: MPI.Comm, u: FunctionData) -> FunctionData | None: 

144 """The function data of all processes on rank 0, ``None`` on the other ranks.""" 

145 cell_start = u.local_cell_range[0] 

146 cell_permutations = gather_rows(comm, cell_start, u.cell_permutations) 

147 dofmap = gather_rows(comm, u.dofmap_range[0], u.dofmap_array) 

148 offsets = gather_rows(comm, cell_start, u.dofmap_offsets, overlap=True) 

149 values = gather_rows(comm, u.dof_range[0], u.values) 

150 if comm.rank != 0: 

151 return None 

152 assert cell_permutations is not None and dofmap is not None 

153 assert offsets is not None and values is not None 

154 return dataclasses.replace( 

155 u, 

156 cell_permutations=cell_permutations, 

157 local_cell_range=(0, u.num_cells_global), 

158 dofmap_array=dofmap, 

159 dofmap_offsets=offsets, 

160 dofmap_range=(0, u.global_dofs_in_dofmap), 

161 values=values, 

162 dof_range=(0, u.num_dofs_global), 

163 ) 

164 

165 

166def gather_meshtags(comm: MPI.Comm, tags: MeshTagsData) -> MeshTagsData | None: 

167 """The mesh tags of all processes on rank 0, ``None`` on the other ranks.""" 

168 start = 0 if tags.local_start is None else tags.local_start 

169 indices = gather_rows(comm, start, tags.indices) 

170 values = gather_rows(comm, start, tags.values) 

171 if comm.rank != 0: 

172 return None 

173 assert indices is not None and values is not None 

174 return dataclasses.replace(tags, indices=indices, values=values, local_start=0) 

175 

176 

177def gather_array(comm: MPI.Comm, data: ArrayData) -> ArrayData | None: 

178 """The array data of all processes on rank 0, ``None`` on the other ranks.""" 

179 values = gather_rows(comm, data.local_range[0], data.values) 

180 if comm.rank != 0: 

181 return None 

182 assert values is not None 

183 return dataclasses.replace(data, values=values, local_range=(0, data.global_shape[0])) 

184 

185 

186def write_on_root( 

187 comm: MPI.Comm, 

188 data: T | None, 

189 write: Callable[[T], None], 

190 flag: contextvars.ContextVar[bool] = force_serial_files, 

191): 

192 """Write data on rank 0, with files opened without MPI, and raise any error it raises on 

193 all ranks. 

194 

195 Args: 

196 comm: The communicator of the processes writing. 

197 data: The data to write on rank 0, as from the gather functions. Not used on the 

198 other ranks. 

199 write: Function writing the data. 

200 flag: The flag making a backend open files without MPI, see :func:`serial_files`. 

201 """ 

202 

203 def run(): 

204 assert data is not None 

205 with serial_files(flag): 

206 write(data) 

207 

208 run_on_root(comm, run)