Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/h5py/storage.py: 99%

111 statements  

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

1"""HDF5 dataset storage options for the h5py-based backends. 

2 

3Used by the h5py and VTKHDF backends. 

4 

5Validates filter and chunk settings passed through ``backend_args``, agrees on them 

6across ranks, and writes local slices, collectively for files opened with MPI-IO. 

7Filter options are passed to :meth:`h5py.Group.create_dataset` under their h5py names, 

8see https://docs.h5py.org/en/stable/high/dataset.html#dataset-compression. Only gzip 

9compression is accepted, as ParaView's bundled HDF5 can read it without filter plugins. 

10 

11SPDX License identifier: MIT 

12""" 

13 

14import numbers 

15from contextlib import closing 

16from typing import Any 

17 

18from mpi4py import MPI 

19 

20import h5py 

21import numpy as np 

22import numpy.typing as npt 

23 

24__all__ = [ 

25 "DEFAULT_STORAGE_OPTIONS", 

26 "check_storage_options", 

27 "chunk_shape", 

28 "create_dataset", 

29 "filter_options", 

30 "storage_options", 

31 "write_dataset", 

32] 

33 

34 

35#: Recognised storage options and their defaults for new datasets. Validated options 

36#: are never filled in with these: an omitted option keeps the setting of an existing 

37#: dataset on append. Scale-offset is a built-in HDF5 filter, so it is available in 

38#: every HDF5 build, and it is lossless on the integer datasets it is applied to. 

39DEFAULT_STORAGE_OPTIONS: dict[str, Any] = { 

40 "compression": None, # "gzip" or None 

41 "compression_opts": None, # gzip level 0-9; h5py uses 4 if omitted 

42 "shuffle": False, 

43 "fletcher32": False, 

44 "scaleoffset": True, # Integer datasets only; off by default with fletcher32 

45 "chunk_bytes": 2**20, # Target size of a chunk of whole rows, see `chunk_shape` 

46} 

47#: HDF5 limits the size of a chunk to less than 4 GiB. 

48_MAX_CHUNK_BYTES = 2**32 - 1 

49#: Options that set up a new dataset only and are not checked against existing ones. 

50_CREATION_OPTIONS = ("chunk_bytes",) 

51_BOOLEAN_OPTIONS = tuple( 

52 key for key, value in DEFAULT_STORAGE_OPTIONS.items() if isinstance(value, bool) 

53) 

54_FILTERS = { 

55 "shuffle": h5py.h5z.FILTER_SHUFFLE, 

56 "fletcher32": h5py.h5z.FILTER_FLETCHER32, 

57 "scaleoffset": h5py.h5z.FILTER_SCALEOFFSET, 

58} 

59 

60 

61def _resolve(options: dict[str, Any]) -> dict[str, Any]: 

62 """All storage settings: explicit options, completed with the defaults. 

63 

64 h5py cannot combine fletcher32 and scale-offset, so an explicit 

65 ``fletcher32=True`` turns off scale-offset unless that is also given explicitly. 

66 """ 

67 settings = DEFAULT_STORAGE_OPTIONS | options 

68 if "scaleoffset" not in options and settings["fletcher32"] is True: 

69 settings["scaleoffset"] = False 

70 return settings 

71 

72 

73def _is_integer(value: Any) -> bool: 

74 """Whether a value is a Python or numpy integer, excluding booleans.""" 

75 return isinstance(value, numbers.Integral) and not isinstance(value, bool | np.bool_) 

76 

77 

78def _get_and_validate_storage_options(arguments: dict[str, Any]) -> dict[str, Any]: 

79 """Extract the storage options from backend arguments and validate them locally. 

80 

81 Args: 

82 arguments: Backend arguments. Keys other than those in 

83 :data:`DEFAULT_STORAGE_OPTIONS` are ignored, except ``chunks``, which is 

84 rejected in favour of ``chunk_bytes``. 

85 

86 Returns: 

87 The storage options present in ``arguments``, with numpy integers and booleans 

88 converted to Python ``int`` and ``bool``. Omitted options are not added. 

89 

90 Raises: 

91 ValueError: If an option has an invalid value, the options are incompatible, 

92 or this rank's HDF5 cannot write the requested filters. 

93 """ 

94 options = {key: arguments[key] for key in DEFAULT_STORAGE_OPTIONS if key in arguments} 

95 for key in _BOOLEAN_OPTIONS: 

96 if key in options: 

97 if not isinstance(options[key], bool | np.bool_): 

98 raise ValueError(f"{key} must be a boolean") 

99 options[key] = bool(options[key]) 

100 compression = options.get("compression") 

101 if compression is not None and compression != "gzip": 

102 raise ValueError("HDF5 compression must be 'gzip' or None") 

103 if "compression_opts" in options: 

104 level = options["compression_opts"] 

105 if compression != "gzip" or not _is_integer(level) or not 0 <= int(level) <= 9: 

106 raise ValueError("compression_opts requires gzip and an integer level from 0 to 9") 

107 options["compression_opts"] = int(level) 

108 settings = _resolve(options) 

109 if settings["fletcher32"] and settings["scaleoffset"]: 

110 # h5py forbids the combination, as scale-offset is lossy for floats. 

111 raise ValueError("fletcher32 cannot be combined with scaleoffset") 

112 if "chunk_bytes" in options: 

113 size = options["chunk_bytes"] 

114 if not _is_integer(size) or not 1 <= int(size) <= _MAX_CHUNK_BYTES: 

115 raise ValueError( 

116 f"chunk_bytes must be an integer from 1 to {_MAX_CHUNK_BYTES} (HDF5's limit)" 

117 ) 

118 options["chunk_bytes"] = int(size) 

119 if "chunks" in arguments: 

120 raise ValueError( 

121 "Chunks are whole rows of the dataset; set their size with chunk_bytes instead " 

122 "of chunks" 

123 ) 

124 filters = [h5py.h5z.FILTER_DEFLATE] if compression else [] 

125 filters += [filter_id for key, filter_id in _FILTERS.items() if settings[key]] 

126 for filter_id in filters: 

127 if not h5py.h5z.filter_avail(filter_id) or not ( 

128 h5py.h5z.get_filter_info(filter_id) & h5py.h5z.FILTER_CONFIG_ENCODE_ENABLED 

129 ): 

130 raise ValueError(f"HDF5 filter {filter_id} is unavailable for writing") 

131 return options 

132 

133 

134def storage_options(comm: MPI.Comm, arguments: dict[str, Any]) -> dict[str, Any]: 

135 """Validate the storage options in backend arguments on all ranks. 

136 

137 Collective: call on every rank before opening the file, so that an error on one 

138 rank is raised on all of them. 

139 

140 Args: 

141 comm: Communicator the file is written with. 

142 arguments: Backend arguments, see :func:`_get_and_validate_storage_options`. 

143 

144 Returns: 

145 The storage options present in ``arguments``, identical on all ranks. 

146 Omitted options are not added, so that they keep the settings of existing 

147 datasets on append; :func:`filter_options` applies the defaults to new ones. 

148 

149 Raises: 

150 ValueError: On every rank, if validation fails on any rank or the options 

151 differ between ranks. 

152 """ 

153 options: dict[str, Any] = {} 

154 error = None 

155 try: 

156 options = _get_and_validate_storage_options(arguments) 

157 except (TypeError, ValueError) as exc: 

158 error = str(exc) 

159 

160 # One exchange handles both errors and settings; a single rank needs no exchange. 

161 settings = comm.allgather((error, options)) if comm.size > 1 else [(error, options)] 

162 for rank_error, _ in settings: 

163 if rank_error is not None: 

164 raise ValueError(rank_error) 

165 if any(rank_options != options for _, rank_options in settings): 

166 raise ValueError("HDF5 storage options must be identical on every MPI rank") 

167 return options 

168 

169 

170def filter_options(options: dict[str, Any], dtype: npt.DTypeLike) -> dict[str, Any]: 

171 """h5py filter arguments for a new bulk dataset of the given type. 

172 

173 Omitted options take their defaults. Scale-offset is applied to integer datasets 

174 only, where h5py's automatic bit width makes it lossless; it is lossy for 

175 floating-point data. 

176 

177 Args: 

178 options: Storage options returned by :func:`storage_options`. 

179 dtype: Data type of the dataset. 

180 

181 Returns: 

182 Keyword arguments for :meth:`h5py.Group.create_dataset`. 

183 """ 

184 settings = _resolve(options) 

185 filters: dict[str, Any] = { 

186 key: options[key] for key in ("compression", "compression_opts") if key in options 

187 } 

188 filters |= {key: True for key in ("shuffle", "fletcher32") if settings[key]} 

189 if settings["scaleoffset"] and np.issubdtype(dtype, np.integer): 

190 filters["scaleoffset"] = True 

191 return filters 

192 

193 

194def chunk_shape( 

195 options: dict[str, Any], shape: tuple[int, ...], dtype: npt.DTypeLike 

196) -> tuple[int, ...]: 

197 """Chunk shape of a new bulk dataset: whole rows, about ``chunk_bytes`` per chunk. 

198 

199 At least one row, and at most the rows of the dataset at creation. 

200 

201 Args: 

202 options: Storage options returned by :func:`storage_options`. 

203 shape: Shape of the new dataset; rows are along the first axis. 

204 dtype: Data type of the dataset. 

205 

206 Returns: 

207 The ``chunks`` argument for :meth:`h5py.Group.create_dataset`. 

208 """ 

209 row_bytes = np.dtype(dtype).itemsize * int(np.prod(shape[1:], dtype=np.int64)) 

210 rows = max(1, _resolve(options)["chunk_bytes"] // max(row_bytes, 1)) 

211 return (min(rows, max(shape[0], 1)), *shape[1:]) 

212 

213 

214def check_storage_options(dataset: h5py.Dataset, options: dict[str, Any]) -> None: 

215 """Reject explicit changes to the immutable filters of an existing dataset. 

216 

217 Chunk sizes only apply to new datasets, so an existing dataset keeps its chunks. 

218 """ 

219 for key, requested in options.items(): 

220 if key in _CREATION_OPTIONS: 

221 continue 

222 if key == "scaleoffset" and not np.issubdtype(dataset.dtype, np.integer): 

223 continue 

224 actual = getattr(dataset, key) 

225 if key == "scaleoffset": 

226 actual = actual is not None 

227 if actual != requested: 

228 raise ValueError( 

229 f"Dataset {dataset.name} already has {key}={actual!r}; " 

230 f"cannot append with {key}={requested!r}" 

231 ) 

232 

233 

234def create_dataset( 

235 group: h5py.Group, 

236 name: str, 

237 shape: tuple[int, ...] | list[int], 

238 dtype: npt.DTypeLike, 

239 options: dict[str, Any], 

240 previous: h5py.Dataset | None = None, 

241) -> h5py.Dataset: 

242 """Create a bulk dataset, chunked and filtered as set by the storage options. 

243 

244 Args: 

245 group: Group to create the dataset in. 

246 name: Name of the dataset. 

247 shape: Shape of the dataset. 

248 dtype: Data type of the dataset. 

249 options: Storage options returned by :func:`storage_options`. 

250 previous: Dataset of an earlier time step, whose chunks and filters the new 

251 dataset keeps. ``options`` must not conflict with them. 

252 

253 Returns: 

254 The new dataset. 

255 """ 

256 shape = tuple(shape) 

257 if previous is None: 

258 layout = {"chunks": chunk_shape(options, shape, dtype), **filter_options(options, dtype)} 

259 else: 

260 check_storage_options(previous, options) 

261 layout = { 

262 key: getattr(previous, key) 

263 for key in ("compression", "compression_opts", "shuffle", "fletcher32", "scaleoffset") 

264 } 

265 layout["chunks"] = previous.chunks 

266 # A zero-length dataset still needs a positive chunk size 

267 if any(size == 0 for size in shape): 

268 layout["maxshape"] = tuple(None if size == 0 else size for size in shape) 

269 return group.create_dataset(name, shape=shape, dtype=dtype, **layout) 

270 

271 

272def write_dataset( 

273 dataset: h5py.Dataset, 

274 selection: slice | tuple[slice, ...], 

275 values: np.ndarray, 

276) -> None: 

277 """Write this rank's slice of a dataset, collectively for MPI-IO files. 

278 

279 In a collective write all ranks write together, so that the MPI library can 

280 combine their slices into fewer and larger file operations (collective 

281 buffering). This is much faster than independent writes, where each rank writes 

282 on its own, and parallel HDF5 requires it for filtered datasets. 

283 

284 Note: 

285 For a file opened with the ``mpio`` driver, every rank of the file's 

286 communicator must call this function, also ranks without data. 

287 

288 Args: 

289 dataset: Dataset to write to. 

290 selection: This rank's part of the dataset. 

291 values: Data for ``selection``; may be empty. 

292 """ 

293 # Parallel filtered writes cannot ask HDF5 to convert the memory datatype. 

294 values = np.asarray(values, dtype=dataset.dtype, order="C") 

295 if dataset.file.driver != "mpio": 

296 dataset[selection] = values 

297 elif values.size > 0: 

298 with dataset.collective: 

299 dataset[selection] = values 

300 else: 

301 _join_collective_write(dataset, values) 

302 

303 

304def _join_collective_write(dataset: h5py.Dataset, values: np.ndarray) -> None: 

305 """Take part in a collective write without writing data. 

306 

307 Every rank must call ``H5Dwrite`` in a collective write, or the other ranks wait 

308 forever. h5py's ``dataset[selection] = values`` makes no ``H5Dwrite`` call for an 

309 empty selection, so ranks without data call it directly, selecting nothing in 

310 both the file and the memory buffer. 

311 """ 

312 with ( 

313 closing(dataset.id.get_space()) as file_space, 

314 closing(h5py.h5s.create_simple(values.shape)) as memory_space, 

315 closing(h5py.h5p.create(h5py.h5p.DATASET_XFER)) as transfer, 

316 ): 

317 file_space.select_none() 

318 memory_space.select_none() 

319 transfer.set_dxpl_mpio(h5py.h5fd.MPIO_COLLECTIVE) 

320 dataset.id.write(memory_space, file_space, values, dxpl=transfer)