Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/adios2/helpers.py: 94%

125 statements  

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

1""" 

2Helpers reading/writing data with ADIOS2 

3""" 

4 

5from __future__ import annotations 

6 

7import contextvars 

8import shutil 

9from contextlib import contextmanager 

10from pathlib import Path 

11from typing import NamedTuple 

12 

13from mpi4py import MPI 

14 

15import adios2 

16import dolfinx.graph 

17import fenicsx_compat 

18import numpy as np 

19import numpy.typing as npt 

20 

21from ...utils import compute_local_range, valid_function_types 

22 

23# ADIOS2 without MPI is supported through the adios2-serial backend 

24adios2 = fenicsx_compat.resolve_adios_scope(adios2, require_mpi=False) 

25 

26 

27__all__ = [ 

28 "force_serial_adios", 

29 "create_adios", 

30 "AdiosFile", 

31 "ADIOSFile", 

32 "check_variable_exists", 

33 "read_array", 

34 "read_adjacency_list", 

35 "read_local_rows", 

36 "adios_to_numpy_dtype", 

37] 

38 

39adios_to_numpy_dtype = { 

40 "float": np.float32, 

41 "double": np.float64, 

42 "float complex": np.complex64, 

43 "double complex": np.complex128, 

44 "uint32_t": np.uint32, 

45 "int32_t": np.int32, 

46 "int64_t": np.int64, 

47 "uint64_t": np.uint64, 

48} 

49 

50 

51#: Create ADIOS objects without MPI on every rank, even with ADIOS2 built with MPI. Set by the 

52#: adios2-serial backend, see :mod:`io4dolfinx.backends.serial`. 

53force_serial_adios = contextvars.ContextVar("force_serial_adios", default=False) 

54 

55 

56def create_adios(comm: MPI.Comm) -> adios2.ADIOS: 

57 """Create an ADIOS object. 

58 

59 Args: 

60 comm: The communicator of the processes opening files with it. 

61 

62 Returns: 

63 An ADIOS object on ``comm``, or one without MPI that opens files on this process 

64 only, if ADIOS2 is built without MPI or :data:`force_serial_adios` is set. 

65 """ 

66 if adios2.is_built_with_mpi and not force_serial_adios.get(): 

67 return adios2.ADIOS(comm) 

68 return adios2.ADIOS() 

69 

70 

71class AdiosFile(NamedTuple): 

72 io: adios2.IO 

73 file: adios2.Engine 

74 

75 

76@contextmanager 

77def ADIOSFile( 

78 adios: adios2.ADIOS, 

79 filename: Path | str, 

80 engine: str, 

81 mode: adios2.Mode, 

82 io_name: str, 

83 comm: MPI.Comm | None = None, 

84): 

85 io = adios.DeclareIO(io_name) 

86 io.SetEngine(engine) 

87 # ADIOS2 sometimes struggles with existing files/folders it should overwrite 

88 if mode == adios2.Mode.Write: 

89 filename = Path(filename) 

90 if filename.exists() and comm is not None and comm.rank == 0: 

91 if filename.is_dir(): 

92 shutil.rmtree(filename) 

93 else: 

94 filename.unlink() 

95 if comm is not None: 

96 comm.Barrier() 

97 

98 file = io.Open(str(filename), mode) 

99 try: 

100 yield AdiosFile(io=io, file=file) 

101 finally: 

102 file.Close() 

103 adios.RemoveIO(io_name) 

104 

105 

106def read_local_rows( 

107 adios_file: AdiosFile, 

108 comm: MPI.Comm, 

109 name: str, 

110 overlap: int = 0, 

111 mode: adios2.Mode = adios2.Mode.Sync, 

112) -> tuple[npt.NDArray, tuple[int, int], int]: 

113 """Read this process's rows of a variable in the current step, the rows being divided 

114 over the processes by :func:`io4dolfinx.utils.compute_local_range`. 

115 

116 Args: 

117 adios_file: The open file. 

118 comm: The communicator the rows are divided over. 

119 name: Name of the variable. 

120 overlap: Number of rows after this process's rows to read as well, e.g. 1 for 

121 offsets. 

122 mode: ``adios2.Mode.Deferred`` to fill the array at the next ``PerformGets``. 

123 

124 Returns: 

125 The rows read, their range (without the overlap) and the global number of rows 

126 (without the overlap). 

127 """ 

128 variable = adios_file.io.InquireVariable(name) 

129 shape = variable.Shape() 

130 num_rows = shape[0] - overlap 

131 start, stop = compute_local_range(comm, num_rows) 

132 count = [stop - start + overlap, *shape[1:]] 

133 variable.SetSelection([[start] + [0] * (len(shape) - 1), count]) 

134 data = np.empty(count, dtype=adios_to_numpy_dtype[variable.Type()]) 

135 adios_file.file.Get(variable, data, mode) 

136 return data, (start, stop), num_rows 

137 

138 

139def check_variable_exists( 

140 adios: adios2.ADIOS, 

141 filename: Path | str, 

142 variable: str, 

143 engine: str, 

144) -> bool: 

145 io_name = f"{variable}_reader" 

146 

147 if not Path(filename).exists(): 

148 return False 

149 

150 variable_found = False 

151 with ADIOSFile( 

152 adios=adios, 

153 engine=engine, 

154 filename=filename, 

155 mode=adios2.Mode.Read, 

156 io_name=io_name, 

157 ) as adios_file: 

158 # Find step that has cell permutation 

159 for _ in range(adios_file.file.Steps()): 

160 adios_file.file.BeginStep() 

161 if variable in adios_file.io.AvailableVariables().keys(): 

162 variable_found = True 

163 break 

164 adios_file.file.EndStep() 

165 

166 # Not sure if this is needed, but just in case 

167 if variable in adios_file.io.AvailableVariables().keys(): 

168 variable_found = True 

169 return variable_found 

170 

171 

172def read_adjacency_list( 

173 adios: adios2.ADIOS, 

174 comm: MPI.Comm, 

175 filename: Path | str, 

176 data_name: str, 

177 offsets_name: str, 

178 engine: str, 

179) -> dolfinx.graph.AdjacencyList: 

180 """ 

181 Read an adjacency-list from an ADIOS file with given communicator. 

182 The adjancency list is split in to a flat array (data) and its corresponding offset. 

183 

184 Args: 

185 adios: The ADIOS instance 

186 comm: The MPI communicator used to read the data 

187 filename: Path to input file 

188 data_name: Name of variable containing the indices of the adjacencylist 

189 dofmap_offsets: Name of variable containing offsets of the adjacencylist 

190 engine: Type of ADIOS engine to use for reading data 

191 

192 Returns: 

193 The local part of dofmap from input dofs 

194 

195 .. note:: 

196 No MPI communication is done during this call 

197 """ 

198 

199 # Open ADIOS engine 

200 io_name = f"{data_name=}_reader" 

201 

202 with ADIOSFile( 

203 adios=adios, 

204 engine=engine, 

205 filename=filename, 

206 mode=adios2.Mode.Read, 

207 io_name=io_name, 

208 ) as adios_file: 

209 # First find step with dofmap offsets, to be able to read 

210 # in a full row of the dofmap 

211 for _ in range(adios_file.file.Steps()): 

212 adios_file.file.BeginStep() 

213 if offsets_name in adios_file.io.AvailableVariables().keys(): 

214 break 

215 adios_file.file.EndStep() 

216 if offsets_name not in adios_file.io.AvailableVariables().keys(): 

217 raise KeyError(f"Dof offsets not found at '{offsets_name}' in {filename}") 

218 

219 # The offsets are one longer than the number of nodes, so read one row more 

220 in_offsets, _, _ = read_local_rows(adios_file, comm, offsets_name, overlap=1) 

221 shape = adios_file.io.InquireVariable(offsets_name).Shape() 

222 in_offsets = in_offsets.squeeze() 

223 

224 # Assuming dofmap is saved in stame step 

225 # Get the relevant part of the dofmap 

226 if data_name not in adios_file.io.AvailableVariables().keys(): 

227 raise KeyError(f"Dofs not found at {data_name} in {filename}") 

228 cell_dofs = adios_file.io.InquireVariable(data_name) 

229 if len(shape) == 1: 

230 cell_dofs.SetSelection([[in_offsets[0]], [in_offsets[-1] - in_offsets[0]]]) 

231 in_dofmap = np.empty(in_offsets[-1] - in_offsets[0], dtype=cell_dofs.Type().strip("_t")) 

232 else: 

233 cell_dofs.SetSelection([[in_offsets[0], 0], [in_offsets[-1] - in_offsets[0], shape[1]]]) 

234 in_dofmap = np.empty( 

235 (in_offsets[-1] - in_offsets[0], shape[1]), 

236 dtype=cell_dofs.Type().strip("_t"), 

237 ) 

238 assert shape[1] == 1 

239 

240 in_dofmap = np.empty(in_offsets[-1] - in_offsets[0], dtype=cell_dofs.Type().strip("_t")) 

241 adios_file.file.Get(cell_dofs, in_dofmap, adios2.Mode.Sync) 

242 in_offsets -= in_offsets[0] 

243 adios_file.file.EndStep() 

244 

245 # Return local dofmap 

246 return dolfinx.graph.adjacencylist(in_dofmap, in_offsets.astype(np.int32)) 

247 

248 

249def read_array( 

250 adios: adios2.ADIOS, 

251 filename: Path | str, 

252 array_name: str, 

253 engine: str, 

254 comm: MPI.Comm, 

255 time: float = 0.0, 

256 time_name: str = "", 

257 legacy: bool = False, 

258) -> tuple[npt.NDArray[valid_function_types], int]: 

259 """ 

260 Read an array from file, return the global starting position of the local array 

261 

262 Args: 

263 adios: The ADIOS instance 

264 filename: Path to file to read array from 

265 array_name: Name of array in file 

266 engine: Name of engine to use to read file 

267 comm: MPI communicator used for reading the data 

268 time_name: Name of time variable for modern checkpoints 

269 legacy: If True ignore time_name and read the first available step 

270 Returns: 

271 Local part of array and its global starting position 

272 """ 

273 

274 with ADIOSFile( 

275 adios=adios, 

276 engine=engine, 

277 filename=filename, 

278 mode=adios2.Mode.Read, 

279 io_name="ArrayReader", 

280 ) as adios_file: 

281 # Get time-stamp from first available step 

282 if legacy: 

283 for i in range(adios_file.file.Steps()): 

284 adios_file.file.BeginStep() 

285 if array_name in adios_file.io.AvailableVariables().keys(): 

286 break 

287 adios_file.file.EndStep() 

288 if array_name not in adios_file.io.AvailableVariables().keys(): 

289 raise KeyError(f"No array found at {array_name}") 

290 else: 

291 for i in range(adios_file.file.Steps()): 

292 adios_file.file.BeginStep() 

293 if time_name in adios_file.io.AvailableVariables().keys(): 

294 arr = adios_file.io.InquireVariable(time_name) 

295 time_shape = arr.Shape() 

296 arr.SetSelection([[0], [time_shape[0]]]) 

297 times = np.empty(time_shape[0], dtype=adios_to_numpy_dtype[arr.Type()]) 

298 adios_file.file.Get(arr, times, adios2.Mode.Sync) 

299 if times[0] == time: 

300 break 

301 if i == adios_file.file.Steps() - 1: 

302 raise KeyError( 

303 f"No data associated with {time_name}={time} found in {filename}" 

304 ) 

305 

306 adios_file.file.EndStep() 

307 

308 if time_name not in adios_file.io.AvailableVariables().keys(): 

309 raise KeyError(f"No data associated with {time_name}={time} found in {filename}") 

310 

311 if array_name not in adios_file.io.AvailableVariables().keys(): 

312 raise KeyError(f"No array found at {time=} for {array_name}") 

313 

314 arr_shape = adios_file.io.InquireVariable(array_name).Shape() 

315 assert len(arr_shape) == 1 or arr_shape[1] == 1 

316 vals, arr_range, _ = read_local_rows(adios_file, comm, array_name) 

317 adios_file.file.EndStep() 

318 

319 return vals.reshape(-1), arr_range[0]