Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/vtkhdf/backend.py: 96%

565 statements  

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

1""" 

2Module that can read the VTKHDF format using h5py. 

3""" 

4 

5from pathlib import Path 

6from typing import Any 

7 

8from mpi4py import MPI 

9 

10import basix 

11import dolfinx 

12import fenicsx_compat 

13import h5py 

14import numpy as np 

15import numpy.typing as npt 

16 

17from io4dolfinx.structures import ArrayData, FunctionData, MeshData, MeshTagsData, ReadMeshData 

18from io4dolfinx.utils import ( 

19 check_file_exists, 

20 compute_local_range, 

21 pad_for_vtk, 

22 same_time, 

23 strip_vtk_padding, 

24) 

25 

26from .. import DEFAULT_MESH_NAME, FileMode, ReadMode 

27from ..h5py import storage as h5_storage 

28from ..h5py.backend import convert_file_mode, h5pyfile 

29from ..vtk_cell_types import _arbitrary_lagrange_vtk, _cell_degree, _first_order_vtk 

30 

31read_mode = ReadMode.parallel 

32 

33_vtk_hdf_version = np.array([2, 1], dtype=np.int32) 

34#: Top-level group for metadata io4dolfinx needs but VTKHDF has no slot for. 

35#: The specification reserves everything outside ``/VTKHDF`` for exactly this: 

36#: "Top-level groups outside of /VTKHDF do not contain any information related to 

37#: the VTK data model and are outside of the scope of this specification. They can 

38#: be useful to store meta-information that could be read and written by custom 

39#: VTKHDF implementation." 

40_metadata_group = "/io4dolfinx" 

41#: Basix Lagrange variant of a mesh's coordinate element, per mesh name. 

42_lagrange_variant_attr = "LagrangeVariant" 

43#: Steps at which a mesh's geometry or a point or cell array was written, in the mesh's 

44#: or array's metadata group. Every step needs data in VTKHDF, so the steps before the 

45#: first write share the data of the first write, and the offsets alone cannot tell at 

46#: which step that was. The writer needs it to fill in steps written out of order. 

47_written_steps = "Steps" 

48 

49 

50def _array_metadata_group(mesh_name: str, extension: str, name: str) -> str: 

51 """The io4dolfinx metadata group of a point or cell array. 

52 

53 Args: 

54 mesh_name: Name of the mesh the array is stored on 

55 extension: ``"Point"`` for point data, ``"Cell"`` for cell data 

56 name: Name of the array 

57 

58 Returns: 

59 Path of the group in the file 

60 """ 

61 return f"{_metadata_group}/{mesh_name}/{extension}Data/{name}" 

62 

63 

64#: Value shape of a point or cell array, attribute of the array's metadata group. VTK 

65#: stores vectors with 3 components and tensors with 9, so the value shape is needed to 

66#: read vectors and tensors of lower dimension back. 

67_value_shape_attr = "ValueShape" 

68 

69 

70def _read_value_shape( 

71 h5file: h5py.File, mesh_name: str, entity: str, name: str 

72) -> tuple[int, ...] | None: 

73 """The value shape of a point or cell array, as recorded by io4dolfinx. 

74 

75 Args: 

76 h5file: An open file 

77 mesh_name: Name of the mesh the array is stored on 

78 entity: ``"Point"`` for point data, ``"Cell"`` for cell data 

79 name: Name of the array 

80 

81 Returns: 

82 The value shape, or ``None`` for an array without one (written by another 

83 program or by an older version of io4dolfinx) 

84 """ 

85 group = _array_metadata_group(mesh_name, entity, name) 

86 if group not in h5file or _value_shape_attr not in h5file[group].attrs: 

87 return None 

88 return tuple(int(i) for i in h5file[group].attrs[_value_shape_attr]) 

89 

90 

91def read_value_shape( 

92 filename: Path | str, 

93 name: str, 

94 comm: MPI.Comm, 

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

96 entity: str, 

97) -> tuple[int, ...] | None: 

98 """Read the value shape of point or cell data. 

99 

100 Args: 

101 filename: Path to file 

102 name: Name of the array 

103 comm: MPI communicator used in storage 

104 backend_args: Arguments to backend 

105 entity: ``"Point"`` for point data, ``"Cell"`` for cell data 

106 

107 Returns: 

108 The value shape of an array written by io4dolfinx, ``None`` for other arrays 

109 """ 

110 backend_args = get_default_backend_args(backend_args) 

111 check_file_exists(filename) 

112 with h5pyfile(filename, "r", comm=comm) as h5file: 

113 return _read_value_shape(h5file, backend_args["name"], entity, name) 

114 

115 

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

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

118 

119 Args: 

120 arguments: Input backend arguments 

121 

122 Returns: 

123 Updated backend arguments 

124 """ 

125 # `arguments or {...}` would drop the default whenever the caller passed any 

126 # other argument, so set it on a copy instead. 

127 args = dict(arguments) if arguments else {} 

128 args.setdefault("name", DEFAULT_MESH_NAME) 

129 return args 

130 

131 

132def find_all_unique_cell_types(comm, cell_types, num_nodes): 

133 """ 

134 Given a set of cell types and number of nodes per cell, find all unique cell types 

135 across all ranks. 

136 

137 Args: 

138 comm: MPI communicator 

139 cell_types: Local cell types 

140 num_nodes: Number of nodes per cell 

141 

142 

143 Returns: 

144 A 2D array where each row corresponds to a cell type (vtk int) 

145 and the number of nodes. 

146 """ 

147 # Combine cell_types, num_nodes as tuple 

148 c_hash = np.zeros((2, len(cell_types)), dtype=np.int32) 

149 c_hash[0] = cell_types 

150 c_hash[1] = num_nodes 

151 indexes = np.unique(c_hash.T, axis=0, return_index=True)[1] 

152 local_unique_cells = c_hash.T[indexes] 

153 

154 all_cell_types = np.vstack(comm.allgather(local_unique_cells)) 

155 indexes = np.unique(all_cell_types, axis=0, return_index=True)[1] 

156 all_unique_cell_types = all_cell_types[indexes] 

157 return all_unique_cell_types 

158 

159 

160def _decode_bytes_if_needed(value: bytes | str) -> str: 

161 """Decode bytes to string if necessary (for h5py compatibility)""" 

162 if isinstance(value, bytes): 

163 return value.decode("utf-8") 

164 return value 

165 

166 

167def _get_vtk_group(h5file, name: str) -> h5py.Group: 

168 """ 

169 Navigates the VTKHDF group hierarchy to find the specific first 

170 UnstructuredGrid with a specific name. 

171 Handles both MultiBlockDataSet and direct UnstructuredGrid types. 

172 """ 

173 hdf = h5file["VTKHDF"] 

174 file_type = _decode_bytes_if_needed(hdf.attrs["Type"]) 

175 

176 if file_type == "MultiBlockDataSet": 

177 ass = hdf["Assembly"] 

178 

179 def visitor(path): 

180 mesh_group = path.rsplit("/", 1) 

181 mesh_name = mesh_group[0] if len(mesh_group) == 1 else mesh_group[1] 

182 if mesh_name == name: 

183 obj = ass.get(path) 

184 # Check attributes carefully 

185 if "Type" in obj.attrs.keys(): 

186 attr_type = obj.attrs["Type"] 

187 if isinstance(attr_type, bytes): 

188 attr_type = attr_type.decode("utf-8") 

189 if attr_type == "UnstructuredGrid": 

190 return path 

191 return None 

192 

193 mesh_node = ass.visit_links(visitor) 

194 if mesh_node is None: 

195 raise RuntimeError(f"Could not find unique mesh named '{name}' in Assembly.") 

196 

197 return ass[mesh_node] 

198 

199 elif file_type == "UnstructuredGrid": 

200 return hdf 

201 else: 

202 raise RuntimeError(f"Not supported file type {file_type}") 

203 

204 

205def _get_all_temporal_unstructured_grids(h5file: h5py.File) -> list[h5py.Group]: 

206 """The unstructured grids (meshes and mesh tags) with time steps in a file. 

207 

208 Args: 

209 h5file: An open MultiBlockDataSet file 

210 

211 Returns: 

212 The groups of the grids, empty if the file has no ``VTKHDF`` group 

213 """ 

214 if "VTKHDF" not in h5file: 

215 return [] 

216 return [ 

217 block 

218 for block in h5file["VTKHDF"].values() 

219 if isinstance(block, h5py.Group) 

220 and "Steps" in block 

221 and _decode_bytes_if_needed(block.attrs.get("Type", "")) == "UnstructuredGrid" 

222 ] 

223 

224 

225def _get_longest_time_sequence(h5file: h5py.File) -> np.ndarray: 

226 """The longest time sequence of the grids in a file. 

227 

228 VTK requires all grids to share their time steps, which older versions of io4dolfinx 

229 did not ensure. 

230 

231 Args: 

232 h5file: An open MultiBlockDataSet file 

233 

234 Returns: 

235 The time stamps, empty if no grid has time steps 

236 """ 

237 values = [block["Steps"]["Values"][:] for block in _get_all_temporal_unstructured_grids(h5file)] 

238 return max(values, key=len, default=np.empty(0, dtype=np.float64)) 

239 

240 

241def _find_time_step_index(stamps: np.ndarray, time: float, filename: str | Path) -> int | None: 

242 """Index of a time among the time steps of a file. 

243 

244 Args: 

245 stamps: Time stamps of the file, increasing 

246 time: The time to look for, see :func:`io4dolfinx.utils.same_time` 

247 filename: Name of the file, for error messages 

248 

249 Returns: 

250 The index of the time step, or ``None`` if ``time`` is a new time 

251 

252 Raises: 

253 ValueError: If ``time`` is new but earlier than the last time step. VTK requires 

254 increasing time steps. 

255 """ 

256 match = np.flatnonzero(same_time(stamps, time)) 

257 if len(match) > 1: 

258 raise ValueError(f"Time {time} matches several time steps in {filename}.") 

259 if len(match) == 1: 

260 return int(match[0]) 

261 if len(stamps) > 0 and time < stamps[-1]: 

262 raise ValueError( 

263 f"Cannot add time {time} to {filename}: a new time step must be later than " 

264 f"the last one, {stamps[-1]}." 

265 ) 

266 return None 

267 

268 

269def _extend_1d_dataset(dataset: h5py.Dataset, num_steps: int): 

270 """Extend a per-step dataset with entries that repeat its last entry. 

271 

272 Args: 

273 dataset: A dataset with one entry per time step 

274 num_steps: Number of entries after extension. A dataset with as many entries or 

275 more is left unchanged. 

276 """ 

277 num_old = dataset.shape[0] 

278 if 0 < num_old < num_steps: 

279 dataset.resize(num_steps, axis=0) 

280 dataset[num_old:] = dataset[num_old - 1] 

281 

282 

283def _set_time_steps(h5file: h5py.File, stamps: np.ndarray): 

284 """Give every grid in a file the same time steps. 

285 

286 The per-step datasets of a grid are extended to the new steps, where the grid keeps 

287 its data from its last step. 

288 

289 Args: 

290 h5file: An open MultiBlockDataSet file 

291 stamps: The time stamps, which extend the existing time steps of every grid 

292 """ 

293 num_steps = len(stamps) 

294 for block in _get_all_temporal_unstructured_grids(h5file): 

295 steps = block["Steps"] 

296 per_step = [ 

297 block[key] 

298 for key in ("NumberOfPoints", "NumberOfCells", "NumberOfConnectivityIds") 

299 if key in block 

300 ] 

301 per_step += [ 

302 steps[key] 

303 for key in ( 

304 "PartOffsets", 

305 "NumberOfParts", 

306 "PointOffsets", 

307 "CellOffsets", 

308 "ConnectivityIdOffsets", 

309 ) 

310 if key in steps 

311 ] 

312 for key in ("PointDataOffsets", "CellDataOffsets", "FieldDataOffsets"): 

313 if key in steps: 

314 per_step += list(steps[key].values()) 

315 # Datasets shared by a mesh and its tags are extended once 

316 for dataset in per_step: 

317 _extend_1d_dataset(dataset, num_steps) 

318 values = steps["Values"] 

319 if values.shape[0] != num_steps: 

320 values.resize(num_steps, axis=0) 

321 values[:] = stamps 

322 steps.attrs["NSteps"] = np.int64(num_steps) 

323 

324 

325def _link_steps_at_root(h5file: h5py.File): 

326 """Link ``/VTKHDF/Steps`` to the time steps of the first grid in a file. 

327 

328 Workaround for VTK 9.7, which reads the first time step of a MultiBlockDataSet for 

329 any time requested through the pipeline unless the root has a ``Steps`` group, see 

330 https://gitlab.kitware.com/vtk/vtk/-/issues/20246. The VTKHDF specification has no 

331 ``Steps`` group at the root of a MultiBlockDataSet, and earlier versions of VTK 

332 ignore it. All grids share their time steps, so those of any grid will do, and the 

333 hard link follows them as steps are added. To be removed once the issue is fixed. 

334 

335 Args: 

336 h5file: An open MultiBlockDataSet file 

337 """ 

338 hdf = h5file["VTKHDF"] 

339 grids = _get_all_temporal_unstructured_grids(h5file) 

340 if "Steps" not in hdf and len(grids) > 0: 

341 hdf["Steps"] = grids[0]["Steps"] 

342 

343 

344def _get_time_steps_and_data_offset( 

345 h5file: h5py.File, record: str, offsets_path: str 

346) -> tuple[np.ndarray, np.ndarray]: 

347 """Steps at which io4dolfinx wrote the geometry or an array, and the offset of the 

348 data written at each. 

349 

350 Files without the record (older versions of io4dolfinx) have a write at the first 

351 step and wherever the offset changes. 

352 

353 Args: 

354 h5file: An open file 

355 record: Path of the record of the written steps, see `_create_temporal_record` 

356 offsets_path: Path of the per-step offsets of the geometry or the array 

357 

358 Returns: 

359 The written steps and their offsets, both empty if the offsets do not exist 

360 """ 

361 if offsets_path not in h5file: 

362 return np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64) 

363 offsets = h5file[offsets_path][:] 

364 if record in h5file: 

365 steps = h5file[record][:] 

366 else: 

367 steps = np.flatnonzero(np.hstack([[True], offsets[1:] != offsets[:-1]])) 

368 return steps, offsets[steps] 

369 

370 

371def _fill_time_steps( 

372 num_steps: int, written_steps: np.ndarray, written_values: np.ndarray 

373) -> np.ndarray: 

374 """Values of a per-step dataset, such as data offsets, at every time step. 

375 

376 A step takes the value of the latest write at or before it. The steps before the 

377 first write take the value of the first write, as VTKHDF requires data at every step. 

378 

379 Args: 

380 num_steps: Number of time steps 

381 written_steps: Steps at which a value was written, in any order 

382 written_values: The value written at each of ``written_steps`` 

383 

384 Returns: 

385 The value at each of the ``num_steps`` time steps 

386 """ 

387 order = np.argsort(written_steps) 

388 previous_write = np.searchsorted(written_steps[order], np.arange(num_steps), side="right") - 1 

389 return written_values[order][np.maximum(previous_write, 0)] 

390 

391 

392def _create_temporal_record(h5file: h5py.File, record: str, written_steps: np.ndarray): 

393 """Create, or replace, the record of the steps at which the geometry or an array has 

394 been written. 

395 

396 Args: 

397 h5file: An open file 

398 record: Path of the record, in the io4dolfinx metadata group 

399 written_steps: The steps at which the geometry or the array has been written 

400 """ 

401 written_steps = np.sort(written_steps).astype(np.int64) 

402 if record in h5file: 

403 h5file[record].resize(written_steps.shape) 

404 h5file[record][:] = written_steps 

405 else: 

406 h5file.create_dataset(record, data=written_steps, chunks=True, maxshape=(None,)) 

407 

408 

409def _get_time_index(hdf: h5py.Group, time: float | str, filename: str | Path) -> int: 

410 """Finds the index of a specific time stamp.""" 

411 if "Steps" not in hdf.keys(): 

412 raise RuntimeError(f"No timestepping information found in {filename}.") 

413 stamps = hdf["Steps"]["Values"][:] 

414 pos = np.flatnonzero(same_time(stamps, float(time))) 

415 if len(pos) == 0: 

416 raise RuntimeError(f"Could not find mesh at t={time} in {filename}.") 

417 elif len(pos) > 1: 

418 raise RuntimeError(f"Multiple time steps for mesh at t={time} in {filename}") 

419 return pos[0] 

420 

421 

422def _read_lagrange_variant(h5file, name: str) -> int: 

423 """Lagrange variant of mesh ``name``, or the VTKHDF default. 

424 

425 A file written by anything other than io4dolfinx -- or by io4dolfinx before 

426 this metadata existed -- holds VTKHDF's equispaced higher-order cells. 

427 

428 Args: 

429 h5file: The open HDF5 file 

430 name: Name of the mesh 

431 

432 Returns: 

433 The basix Lagrange variant as an integer. 

434 """ 

435 equispaced = int(basix.LagrangeVariant.equispaced) 

436 metadata = h5file.get(_metadata_group) 

437 if metadata is None or name not in metadata: 

438 return equispaced 

439 return int(metadata[name].attrs.get(_lagrange_variant_attr, equispaced)) 

440 

441 

442def read_mesh_data( 

443 filename: Path | str, 

444 comm: MPI.Comm, 

445 time: str | float | None, 

446 read_from_partition: bool, 

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

448) -> ReadMeshData: 

449 """Read mesh data from file. 

450 

451 Args: 

452 filename: Path to file to read from 

453 comm: MPI communicator used in storage 

454 time: Time stamp associated with the mesh to read 

455 read_from_partition: Whether to read partition information 

456 backend_args: Arguments to backend 

457 

458 Returns: 

459 Internal data structure for the mesh data read from file 

460 """ 

461 backend_args = get_default_backend_args(backend_args) 

462 check_file_exists(filename) 

463 if read_from_partition: 

464 raise RuntimeError("Cannot read partition data with VTKHDF") 

465 with h5pyfile(filename, "r", comm=comm) as h5file: 

466 hdf = _get_vtk_group(h5file, backend_args["name"]) 

467 lagrange_variant = _read_lagrange_variant(h5file, backend_args["name"]) 

468 if time is None: 

469 num_cells_global = hdf["Types"].size 

470 local_cell_range = compute_local_range(comm, num_cells_global) 

471 cell_types_local = hdf["Types"][slice(*local_cell_range)] 

472 

473 num_points_global = hdf["NumberOfPoints"][0] 

474 local_point_range = compute_local_range(comm, num_points_global) 

475 points_local = hdf["Points"][slice(*local_point_range)] 

476 

477 # Connectivity read 

478 offsets = hdf["Offsets"] 

479 local_connectivity_offset = offsets[local_cell_range[0] : local_cell_range[1] + 1] 

480 topology = hdf["Connectivity"][ 

481 local_connectivity_offset[0] : local_connectivity_offset[-1] 

482 ] 

483 offset = local_connectivity_offset - local_connectivity_offset[0] 

484 else: 

485 time_index = _get_time_index(hdf, time, filename) 

486 

487 stamps = hdf["Steps"]["Values"][:] 

488 # Get number of points 

489 point_node = hdf["Points"] 

490 step_start = hdf["Steps"]["PointOffsets"][time_index] 

491 

492 # NOTE: currently, it doesn't seem like we follow: 

493 # https://docs.vtk.org/en/latest/vtk_file_formats/vtkhdf_file_format/vtkhdf_specifications.html#temporal-unstructuredgrid-and-polydata 

494 # As only one num_points is stored irregardless of time steps added. 

495 if hdf["NumberOfPoints"].shape[0] != len(stamps): 

496 num_pts = hdf["NumberOfPoints"][0] 

497 else: 

498 num_pts = hdf["NumberOfPoints"][time_index] 

499 lr = compute_local_range(comm, num_pts) 

500 points_local = point_node[step_start + lr[0] : step_start + lr[1]] 

501 

502 # Get cell-types in step 

503 cell_start = hdf["Steps"]["CellOffsets"][time_index] 

504 if hdf["NumberOfCells"].shape[0] != len(stamps): 

505 num_cells = hdf["NumberOfCells"][0] 

506 else: 

507 num_cells = hdf["NumberOfCells"][time_index] 

508 local_cell_range = compute_local_range(comm, num_cells) 

509 cell_types_local = hdf["Types"][ 

510 cell_start + local_cell_range[0] : cell_start + local_cell_range[1] 

511 ] 

512 

513 # Get connectivity in step 

514 connectivity_start = hdf["Steps"]["ConnectivityIdOffsets"][time_index] 

515 # Connectivity read 

516 offsets = hdf["Offsets"] 

517 local_connectivity_offset = offsets[ 

518 connectivity_start + local_cell_range[0] : connectivity_start 

519 + local_cell_range[1] 

520 + 1 

521 ] 

522 topology = hdf["Connectivity"][ 

523 local_connectivity_offset[0] : local_connectivity_offset[-1] 

524 ] 

525 offset = local_connectivity_offset - local_connectivity_offset[0] 

526 

527 # NOTE: Currently we limit ourselfs to a single celltype, as it makes life easier, 

528 # other things have to change in `MeshReadData` to support this. 

529 num_nodes_per_cell = offset[1:] - offset[:-1] 

530 unique_cells = find_all_unique_cell_types(comm, cell_types_local, num_nodes_per_cell) 

531 if unique_cells.shape[0] > 1: 

532 raise NotImplementedError("io4dolfinx does not support mixed celltype grids") 

533 if unique_cells.shape[0] == 0: 

534 name = backend_args["name"] 

535 raise ValueError(f"Grid '{name}' in {filename} has no cells on any process.") 

536 # Take the width from the globally agreed cell type rather than from this 

537 # process's own cells: a mesh with fewer cells than processes leaves some of 

538 # them with nothing local to measure. 

539 cell_type, number_of_nodes = unique_cells[0] 

540 topology = topology.reshape(-1, number_of_nodes) 

541 gtype = backend_args.get("dtype", points_local.dtype) 

542 if cell_type in _first_order_vtk.keys(): 

543 ct = _first_order_vtk[cell_type] 

544 degree = 1 

545 elif cell_type in _arbitrary_lagrange_vtk.keys(): 

546 ct = _arbitrary_lagrange_vtk[cell_type] 

547 degree = _cell_degree(ct, num_nodes=number_of_nodes) 

548 else: 

549 raise ValueError(f"Unknown VTK cell type {cell_type} in {filename}") 

550 perm = dolfinx.cpp.io.perm_vtk(dolfinx.mesh.to_type(ct), number_of_nodes) 

551 topology = topology[:, perm] 

552 # Equispaced is the VTKHDF default; a file io4dolfinx wrote says which 

553 # variant its nodes were actually placed with. 

554 lvar = int(lagrange_variant) 

555 return ReadMeshData( 

556 cells=topology, cell_type=ct, x=points_local.astype(gtype), lvar=lvar, degree=degree 

557 ) 

558 

559 

560def read_point_data( 

561 filename: Path | str, 

562 name: str, 

563 comm: MPI.Comm, 

564 time: float | str | None, 

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

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

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

568 

569 Args: 

570 filename: Path to file 

571 name: Name of point data 

572 comm: Communicator to launch IO on. 

573 time: The time stamp 

574 backend_args: The backend arguments 

575 

576 Returns: 

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

578 """ 

579 backend_args = get_default_backend_args(backend_args) 

580 check_file_exists(filename) 

581 with h5pyfile(filename, "r", comm=comm) as h5file: 

582 hdf = _get_vtk_group(h5file, backend_args["name"]) 

583 point_data = hdf["PointData"] 

584 assert point_data is not None 

585 if name not in point_data.keys(): 

586 raise ValueError(f"No point data named {name} in {filename}.") 

587 func_node = point_data[name] 

588 value_shape = _read_value_shape(h5file, backend_args["name"], "Point", name) 

589 

590 if time is None: 

591 data_shape = func_node.shape[0] 

592 lr = compute_local_range(comm, data_shape) 

593 data = func_node[slice(*lr)] 

594 return strip_vtk_padding(data, value_shape), lr[0] 

595 else: 

596 time_index = _get_time_index(hdf, time, filename) 

597 stamps = hdf["Steps"]["Values"][:] 

598 step_start = hdf["Steps"]["PointDataOffsets"][name][time_index] 

599 # NOTE: currently, it doesn't seem like we follow: 

600 # https://docs.vtk.org/en/latest/vtk_file_formats/vtkhdf_file_format/vtkhdf_specifications.html#temporal-unstructuredgrid-and-polydata 

601 # As only one num_points is stored irregardless of time steps added. 

602 if hdf["NumberOfPoints"].shape[0] != len(stamps): 

603 num_pts = hdf["NumberOfPoints"][0] 

604 else: 

605 num_pts = hdf["NumberOfPoints"][time_index] 

606 lr = compute_local_range(comm, num_pts) 

607 data = func_node[step_start + lr[0] : step_start + lr[1]] 

608 return strip_vtk_padding(data, value_shape), lr[0] 

609 

610 

611def read_cell_data( 

612 filename: Path | str, 

613 name: str, 

614 comm: MPI.Comm, 

615 time: str | float | None, 

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

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

618 backend_args = get_default_backend_args(backend_args) 

619 check_file_exists(filename) 

620 with h5pyfile(filename, "r", comm=comm) as h5file: 

621 hdf = _get_vtk_group(h5file, backend_args["name"]) 

622 

623 if "CellData" not in hdf.keys(): 

624 raise RuntimeError(f"No cell data found in {filename}.") 

625 cell_data = hdf["CellData"] 

626 assert cell_data is not None 

627 if name not in cell_data.keys(): 

628 raise ValueError(f"No cell data with name {name} in {filename}") 

629 cell_data_node = cell_data[name] 

630 assert cell_data_node is not None 

631 value_shape = _read_value_shape(h5file, backend_args["name"], "Cell", name) 

632 if time is None: 

633 cell_data_shape = cell_data_node.shape 

634 num_cells_global = hdf["Types"].size 

635 assert num_cells_global == cell_data_shape[0] 

636 local_cell_range = compute_local_range(comm, num_cells_global) 

637 data = cell_data_node[slice(*local_cell_range)] 

638 else: 

639 time_index = _get_time_index(hdf, time, filename) 

640 stamps = hdf["Steps"]["Values"][:] 

641 cd_start = hdf["Steps"]["CellDataOffsets"][name][time_index] 

642 

643 # NOTE: currently, it doesn't seem like we follow: 

644 # https://docs.vtk.org/en/latest/vtk_file_formats/vtkhdf_file_format/vtkhdf_specifications.html#temporal-unstructuredgrid-and-polydata 

645 # As only one num_points is stored irregardless of time steps added. 

646 if hdf["NumberOfCells"].shape[0] != len(stamps): 

647 number_of_cells = hdf["NumberOfCells"][0] 

648 else: 

649 number_of_cells = hdf["NumberOfCells"][time_index] 

650 lr = compute_local_range(comm, number_of_cells) 

651 data = cell_data_node[cd_start + lr[0] : cd_start + lr[1]] 

652 

653 # NOTE: THis could be optimized by hand-coding some communication in 

654 # `read_cell_data` on the frontend side 

655 md = read_mesh_data( 

656 filename, comm, time=time, read_from_partition=False, backend_args=backend_args 

657 ) 

658 return md.cells, strip_vtk_padding(data, value_shape) 

659 

660 

661def write_attributes( 

662 filename: Path | str, 

663 comm: MPI.Comm, 

664 name: str, 

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

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

667): 

668 """Write attributes to file. 

669 

670 Args: 

671 filename: Path to file to write to 

672 comm: MPI communicator used in storage 

673 name: Name of the attribute group 

674 attributes: Dictionary of attributes to write 

675 backend_args: Arguments to backend 

676 """ 

677 raise NotImplementedError("The VTKHDF backend cannot write attributes.") 

678 

679 

680def read_attributes( 

681 filename: Path | str, 

682 comm: MPI.Comm, 

683 name: str, 

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

685) -> dict[str, Any]: 

686 """Read attributes from file. 

687 

688 Args: 

689 filename: Path to file to read from 

690 comm: MPI communicator used in storage 

691 name: Name of the attribute group 

692 backend_args: Arguments to backend 

693 

694 Returns: 

695 Dictionary of attributes read from file 

696 """ 

697 raise NotImplementedError("The VTKHDF backend cannot read attributes.") 

698 

699 

700def read_timestamps( 

701 filename: Path | str, 

702 comm: MPI.Comm, 

703 function_name: str, 

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

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

706 """Read timestamps from file. 

707 

708 Args: 

709 filename: Path to file to read from 

710 comm: MPI communicator used in storage 

711 function_name: Name of the function to read timestamps for 

712 backend_args: Arguments to backend 

713 

714 Returns: 

715 The time steps of the mesh the function is stored on. A VTKHDF array has 

716 data at every time step of its mesh. 

717 """ 

718 backend_args = get_default_backend_args(backend_args) 

719 check_file_exists(filename) 

720 mesh_name = backend_args["name"] 

721 # Temporal data storage as described in 

722 # https://docs.vtk.org/en/latest/vtk_file_formats/vtkhdf_file_format/vtkhdf_specifications.html#temporal-data 

723 with h5pyfile(filename, "r", comm=comm) as h5file: 

724 block = _get_vtk_group(h5file, mesh_name) 

725 if "Steps" not in block.keys(): 

726 raise RuntimeError(f"{filename} does not contain time-stepping information.") 

727 for data in ("CellData", "PointData"): 

728 if data in block.keys() and function_name in block[data].keys(): 

729 return block["Steps"]["Values"][:] 

730 raise RuntimeError(f"Function {function_name} is not associated with a time-stamp.") 

731 

732 

733def read_function_names( 

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

735) -> list[str]: 

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

737 

738 Args: 

739 filename: Path to file 

740 comm: MPI communicator to launch IO on. 

741 backend_args: Arguments to backend 

742 

743 Returns: 

744 A list of function names. 

745 """ 

746 backend_args = get_default_backend_args(backend_args) 

747 check_file_exists(filename) 

748 with h5pyfile(filename, "r", comm=comm) as h5file: 

749 hdf = _get_vtk_group(h5file, backend_args["name"]) 

750 function_names = set() 

751 if "CellData" in hdf.keys(): 

752 for item in hdf["CellData"].keys(): 

753 function_names.add(item) 

754 if "PointData" in hdf.keys(): 

755 for item in hdf["PointData"].keys(): 

756 function_names.add(item) 

757 return list(function_names) 

758 

759 

760def _create_dataset( 

761 root: h5py.File | h5py.Group, 

762 name: str, 

763 shape: tuple[int, ...], 

764 dtype: npt.DTypeLike, 

765 maxshape: tuple[int | None, ...], 

766 mode: str, 

767 resize: bool = True, 

768 storage: dict[str, Any] | None = None, 

769) -> h5py.Dataset: 

770 """Create a dataset, or open (and resize) an existing one in append mode. 

771 

772 Args: 

773 storage: Storage options of a bulk dataset, from 

774 :func:`io4dolfinx.backends.h5py.storage.storage_options`. A new bulk dataset 

775 is chunked by rows and filtered as these options say. Omitted for small 

776 bookkeeping datasets, which every rank writes independently and which must 

777 therefore stay unfiltered; they use h5py's automatic chunking. 

778 """ 

779 if name not in root.keys(): 

780 mode = "w" 

781 if mode == "w": 

782 if storage is None: 

783 layout: dict[str, Any] = {"chunks": True} 

784 else: 

785 layout = { 

786 "chunks": h5_storage.chunk_shape(storage, shape, dtype), 

787 **h5_storage.filter_options(storage, dtype), 

788 } 

789 dataset = root.create_dataset(name, shape=shape, dtype=dtype, maxshape=maxshape, **layout) 

790 elif mode == "a": 

791 dataset = root[name] 

792 old_shape = dataset.shape 

793 # Only resize for dimension 

794 if resize: 

795 if len(old_shape) == 1: 

796 new_shape = (old_shape[0] + shape[0],) 

797 else: 

798 new_shape = (old_shape[0] + shape[0], *old_shape[1:]) 

799 dataset.resize(new_shape) 

800 else: 

801 raise ValueError(f"Unknown file mode '{mode}' when creating dataset {name} in {root}") 

802 return dataset 

803 

804 

805def _create_group(root: h5py.File | h5py.Group, name: str, mode: str) -> h5py.Group: 

806 if name not in root.keys(): 

807 mode = "w" 

808 if mode == "w": 

809 # Track order has to be on to make multiblock work: 

810 # https://docs.vtk.org/en/latest/vtk_file_formats/vtkhdf_file_format/vtkhdf_specifications.html#partitioneddatasetcollection-and-multiblockdataset 

811 group = root.create_group(name, track_order=True) 

812 elif mode == "a": 

813 group = root[name] 

814 else: 

815 raise ValueError("Unknown file mode '{h5_mode}'") 

816 return group 

817 

818 

819def _compute_append_slice( 

820 dataset: h5py.Dataset, input_size: int, original_slice: tuple[int, int] | np.ndarray, mode: str 

821) -> slice: 

822 append_offset = dataset.shape[0] - input_size if mode == "a" else 0 

823 return slice(*(np.asarray(original_slice) + append_offset).astype(np.int64)) 

824 

825 

826def write_mesh( 

827 filename: Path | str, 

828 comm: MPI.Comm, 

829 mesh: MeshData, 

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

831 mode: FileMode, 

832 time: float, 

833): 

834 """ 

835 Write a mesh to file. 

836 

837 Args: 

838 comm: MPI communicator used in storage 

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

840 filename: Path to file to write to 

841 backend_args: Arguments to backend 

842 mode: File-mode to store the mesh 

843 time: Time stamp associated with the mesh 

844 """ 

845 h5_mode = convert_file_mode(mode) 

846 backend_args = get_default_backend_args(backend_args) 

847 name = backend_args["name"] 

848 storage_options = h5_storage.storage_options(comm, backend_args) 

849 

850 with h5pyfile(filename, h5_mode, comm=comm) as h5file: 

851 # Check all existing bulk arrays before changing attributes or resizing anything. 

852 if storage_options and h5_mode == "a" and f"/VTKHDF/{name}" in h5file: 

853 block = h5file[f"/VTKHDF/{name}"] 

854 for key in ("Points", "Offsets", "Connectivity", "Types"): 

855 if key in block: 

856 h5_storage.check_storage_options(block[key], storage_options) 

857 

858 # Check the mesh and the time before writing anything. Only the geometry of a mesh 

859 # can change between time steps, as its topology is stored once. 

860 block_path = f"/VTKHDF/{name}" 

861 if block_path in h5file and "NumberOfCells" in h5file[block_path]: 

862 num_dofs_per_cell = mesh.local_topology.shape[1] 

863 for key, value in ( 

864 ("NumberOfPoints", mesh.num_nodes_global), 

865 ("NumberOfCells", mesh.num_cells_global), 

866 ("NumberOfConnectivityIds", mesh.num_cells_global * num_dofs_per_cell), 

867 ): 

868 stored = int(h5file[block_path][key][0]) 

869 if stored != value: 

870 raise ValueError( 

871 f"Mesh '{name}' in {filename} has {key} {stored}, not {value}. Only " 

872 "the geometry of a mesh can change between time steps." 

873 ) 

874 stamps = _get_longest_time_sequence(h5file) 

875 step = _find_time_step_index(stamps, time, filename) 

876 record = f"{_metadata_group}/{name}/{_written_steps}" 

877 written_steps, written_offsets = _get_time_steps_and_data_offset( 

878 h5file, record, f"/VTKHDF/{name}/Steps/PointOffsets" 

879 ) 

880 if same_time(stamps[written_steps], time).any(): 

881 raise ValueError( 

882 f"Mesh '{name}' has already been written at time {time} in {filename}." 

883 ) 

884 if step is None: 

885 stamps = np.append(stamps, time) 

886 step = len(stamps) - 1 

887 _set_time_steps(h5file, stamps) 

888 num_steps = len(stamps) 

889 

890 hdf = _create_group(h5file, "/VTKHDF", h5_mode) 

891 hdf.attrs.create("Type", "MultiBlockDataSet") 

892 hdf.attrs["Version"] = _vtk_hdf_version 

893 

894 mesh_group = _create_group(hdf, name, h5_mode) 

895 mesh_group.attrs.create("Type", "UnstructuredGrid") 

896 mesh_group.attrs["Version"] = _vtk_hdf_version 

897 

898 assembly = _create_group(hdf, "Assembly", h5_mode) 

899 

900 mesh_assembly = _create_group(assembly, name, h5_mode) 

901 if name not in mesh_assembly.keys(): 

902 mesh_assembly[name] = h5py.SoftLink(f"/VTKHDF/{name}") 

903 

904 # VTKHDF defines its higher-order cells as equispaced and has nowhere to 

905 # record a Lagrange variant, so it goes in our own top-level group, which 

906 # the specification reserves for exactly this. Without it a degree>1 mesh 

907 # reads back with its coordinates intact but its cells curving 

908 # differently between them. 

909 metadata = _create_group(h5file, _metadata_group, h5_mode) 

910 mesh_metadata = _create_group(metadata, name, h5_mode) 

911 mesh_metadata.attrs[_lagrange_variant_attr] = np.int32(mesh.lagrange_variant) 

912 

913 # Number of points per time step, set with the point offsets below 

914 number_of_points = _create_dataset( 

915 mesh_group, 

916 "NumberOfPoints", 

917 shape=(num_steps,), 

918 dtype=np.int64, 

919 maxshape=(None,), 

920 mode=h5_mode, 

921 resize=False, 

922 ) 

923 

924 # Store nodes 

925 points = _create_dataset( 

926 mesh_group, 

927 "Points", 

928 shape=(mesh.num_nodes_global, 3), 

929 dtype=mesh.local_geometry.dtype, 

930 maxshape=(None, 3), 

931 mode=h5_mode, 

932 storage=storage_options, 

933 ) 

934 insert_slice = _compute_append_slice( 

935 points, mesh.num_nodes_global, mesh.local_geometry_pos, h5_mode 

936 ) 

937 h5_storage.write_dataset( 

938 points, 

939 (insert_slice, slice(0, mesh.local_geometry.shape[1])), 

940 mesh.local_geometry, 

941 ) 

942 

943 # DOLFINx meshes only move their geometry, so the topology is stored once and a 

944 # later write of the mesh rewrites it in place. Every time step reads it as part 

945 # 0 (zero PartOffsets, CellOffsets and ConnectivityIdOffsets), the VTKHDF layout 

946 # for static data. 

947 time_indep_datasets = {} 

948 for key in ["NumberOfCells", "NumberOfConnectivityIds"]: 

949 time_indep_datasets[key] = _create_dataset( 

950 mesh_group, 

951 key, 

952 shape=(num_steps,), 

953 dtype=np.int64, 

954 maxshape=(None,), 

955 mode=h5_mode, 

956 resize=False, # Static, stored once 

957 ) 

958 

959 num_dofs_per_cell = mesh.local_topology.shape[1] 

960 time_indep_datasets["NumberOfCells"][:] = mesh.num_cells_global 

961 time_indep_datasets["NumberOfConnectivityIds"][:] = ( 

962 mesh.num_cells_global * num_dofs_per_cell 

963 ) 

964 

965 # Store topology offsets (single celltype assumption) 

966 offsets = _create_dataset( 

967 mesh_group, 

968 "Offsets", 

969 shape=(mesh.num_cells_global + 1,), 

970 dtype=np.int64, 

971 mode=h5_mode, 

972 maxshape=(None,), 

973 resize=False, # Static, stored once 

974 storage=storage_options, 

975 ) 

976 # Each offset has one writer. Only the last nonempty rank writes the final offset. 

977 first, last = mesh.local_topology_pos 

978 include_end = last == mesh.num_cells_global and last > first 

979 offset_data = np.arange(last - first + int(include_end), dtype=np.int64) 

980 offset_data *= num_dofs_per_cell 

981 offset_data += num_dofs_per_cell * mesh.local_topology_pos[0] 

982 insert_slice = _compute_append_slice( 

983 offsets, 

984 mesh.num_cells_global + 1, 

985 (first, last + int(include_end)), 

986 mode=h5_mode, 

987 ) 

988 h5_storage.write_dataset(offsets, insert_slice, offset_data) 

989 del offset_data 

990 

991 # Permute and store topology data 

992 dx_ct = dolfinx.mesh.to_type(mesh.cell_type) 

993 top_perm = np.argsort(dolfinx.cpp.io.perm_vtk(dx_ct, num_dofs_per_cell)) 

994 topology_data = mesh.local_topology[:, top_perm].flatten() 

995 topology = _create_dataset( 

996 mesh_group, 

997 "Connectivity", 

998 shape=(mesh.num_cells_global * num_dofs_per_cell,), 

999 dtype=np.int64, 

1000 maxshape=(None,), 

1001 mode=h5_mode, 

1002 resize=False, # Static, stored once 

1003 storage=storage_options, 

1004 ) 

1005 insert_slice = _compute_append_slice( 

1006 topology, 

1007 mesh.num_cells_global * num_dofs_per_cell, 

1008 np.array(mesh.local_topology_pos) * num_dofs_per_cell, 

1009 mode=h5_mode, 

1010 ) 

1011 h5_storage.write_dataset(topology, insert_slice, topology_data) 

1012 del topology_data 

1013 

1014 # Store celltypes 

1015 cell_types = np.full( 

1016 mesh.local_topology.shape[0], 

1017 fenicsx_compat.vtk_cell_type(dx_ct, num_dofs_per_cell), 

1018 dtype=np.uint8, 

1019 ) 

1020 types = _create_dataset( 

1021 mesh_group, 

1022 "Types", 

1023 shape=(mesh.num_cells_global,), 

1024 dtype=np.uint8, 

1025 maxshape=(None,), 

1026 mode=h5_mode, 

1027 resize=False, # Static, stored once 

1028 storage=storage_options, 

1029 ) 

1030 insert_slice = _compute_append_slice( 

1031 types, mesh.num_cells_global, mesh.local_topology_pos, h5_mode 

1032 ) 

1033 h5_storage.write_dataset(types, insert_slice, cell_types) 

1034 del cell_types 

1035 

1036 # The file's time steps, with static topology. The geometry at each step is 

1037 # that of the latest write at or before it, see `_fill_time_steps`. 

1038 steps = _create_group(mesh_group, "Steps", mode=h5_mode) 

1039 steps.attrs["NSteps"] = np.int64(num_steps) 

1040 for key, dtype in ( 

1041 ("Values", np.float64), 

1042 ("NumberOfParts", np.int64), 

1043 ("PartOffsets", np.int64), 

1044 ("PointOffsets", np.int64), 

1045 ("CellOffsets", np.int64), 

1046 ("ConnectivityIdOffsets", np.int64), 

1047 ): 

1048 _create_dataset( 

1049 steps, 

1050 key, 

1051 shape=(num_steps,), 

1052 dtype=dtype, 

1053 maxshape=(None,), 

1054 mode=h5_mode, 

1055 resize=False, 

1056 ) 

1057 steps["Values"][:] = stamps 

1058 steps["NumberOfParts"][:] = 1 

1059 steps["PartOffsets"][:] = 0 

1060 steps["CellOffsets"][:] = types.shape[0] - mesh.num_cells_global 

1061 steps["ConnectivityIdOffsets"][:] = ( 

1062 topology.shape[0] - mesh.num_cells_global * num_dofs_per_cell 

1063 ) 

1064 for key in ("CellDataOffsets", "PointDataOffsets"): 

1065 _create_group(steps, key, mode=h5_mode) 

1066 

1067 written_points = np.append(number_of_points[:][written_steps], mesh.num_nodes_global) 

1068 written_offsets = np.append(written_offsets, points.shape[0] - mesh.num_nodes_global) 

1069 written_steps = np.append(written_steps, step) 

1070 steps["PointOffsets"][:] = _fill_time_steps(num_steps, written_steps, written_offsets) 

1071 number_of_points[:] = _fill_time_steps(num_steps, written_steps, written_points) 

1072 _create_temporal_record(h5file, record, written_steps) 

1073 _link_steps_at_root(h5file) 

1074 

1075 

1076def write_meshtags( 

1077 filename: str | Path, 

1078 comm: MPI.Comm, 

1079 data: MeshTagsData, 

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

1081): 

1082 """Write mesh tags to file. 

1083 

1084 Args: 

1085 filename: Path to file to write to 

1086 comm: MPI communicator used in storage 

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

1088 backend_args: Arguments to backend 

1089 """ 

1090 backend_args = get_default_backend_args(backend_args) 

1091 name = backend_args["name"] 

1092 h5_mode = "a" 

1093 storage_options = h5_storage.storage_options(comm, backend_args) 

1094 with h5pyfile(filename, h5_mode, comm=comm) as h5file: 

1095 hdf = h5file["VTKHDF"] 

1096 file_type = _decode_bytes_if_needed(hdf.attrs["Type"]) 

1097 # Check for type of VTKHDF file 

1098 if file_type != "MultiBlockDataSet": 

1099 raise ValueError(f"Cannot write meshtags to {filename} with VTK type {file_type}") 

1100 

1101 # We place the mesh-tags in the same subgroup of assembly as the mesh 

1102 parent_mesh_group = _get_vtk_group(h5file, name) 

1103 block = parent_mesh_group.parent 

1104 

1105 tag_path = f"/VTKHDF/{name}_{data.name}" 

1106 # Check all existing bulk arrays before changing anything. 

1107 if tag_path in h5file: 

1108 tag_group = h5file[tag_path] 

1109 for key in (f"CellData/{data.name}", "Offsets", "Connectivity", "Types"): 

1110 if key in tag_group: 

1111 h5_storage.check_storage_options(tag_group[key], storage_options) 

1112 if data.name not in block.keys(): 

1113 block[data.name] = h5py.SoftLink(tag_path) 

1114 

1115 mesh_group = _create_group(hdf, tag_path, mode=h5_mode) 

1116 mesh_group.attrs.create("Type", "UnstructuredGrid") 

1117 mesh_group.attrs["Version"] = _vtk_hdf_version 

1118 

1119 cell_data = _create_group(mesh_group, "CellData", mode=h5_mode) 

1120 assert data.num_entities_global is not None 

1121 dataset = _create_dataset( 

1122 cell_data, 

1123 data.name, 

1124 shape=(data.num_entities_global,), 

1125 dtype=data.values.dtype, 

1126 maxshape=(None,), 

1127 mode=h5_mode, 

1128 storage=storage_options, 

1129 ) 

1130 assert data.local_start is not None 

1131 insert_slice = _compute_append_slice( 

1132 dataset, 

1133 data.num_entities_global, 

1134 np.array([data.local_start, data.local_start + data.indices.shape[0]]), 

1135 mode=h5_mode, 

1136 ) 

1137 h5_storage.write_dataset(dataset, insert_slice, data.values) 

1138 

1139 # NOTE: The following is more or less a copy from write_mesh, 

1140 # except that we pull out the point storage and use a softlink 

1141 num_cells = _create_dataset( 

1142 mesh_group, 

1143 "NumberOfCells", 

1144 shape=(1,), 

1145 dtype=np.int64, 

1146 maxshape=(None,), 

1147 mode=h5_mode, 

1148 resize=False, # Static, stored once 

1149 ) 

1150 num_cells[-1] = data.num_entities_global 

1151 

1152 # Hardlink data should also follow hardlink for numbering 

1153 for key in ["Points", "NumberOfPoints"]: 

1154 if key not in mesh_group.keys(): 

1155 mesh_group[key] = parent_mesh_group[key] 

1156 

1157 # Single celltype assumption 

1158 num_dofs_per_cell = data.num_dofs_per_entity 

1159 number_of_connectivities = _create_dataset( 

1160 mesh_group, 

1161 "NumberOfConnectivityIds", 

1162 shape=(1,), 

1163 dtype=np.int64, 

1164 maxshape=(None,), 

1165 mode=h5_mode, 

1166 resize=False, # Static, stored once 

1167 ) 

1168 assert data.num_entities_global is not None and num_dofs_per_cell is not None 

1169 number_of_connectivities[-1] = data.num_entities_global * num_dofs_per_cell 

1170 

1171 # Store topology offsets (single celltype assumption) 

1172 offsets = _create_dataset( 

1173 mesh_group, 

1174 "Offsets", 

1175 shape=(data.num_entities_global + 1,), 

1176 dtype=np.int64, 

1177 mode=h5_mode, 

1178 maxshape=(None,), 

1179 resize=False, # Static, stored once 

1180 storage=storage_options, 

1181 ) 

1182 # Each offset has one writer. Only the last nonempty rank writes the final offset. 

1183 assert data.local_start is not None 

1184 first, last = data.local_start, data.local_start + data.indices.shape[0] 

1185 include_end = last == data.num_entities_global and last > first 

1186 offset_data = np.arange(first, last + int(include_end), dtype=np.int64) 

1187 offset_data *= num_dofs_per_cell 

1188 insert_slice = _compute_append_slice( 

1189 offsets, 

1190 data.num_entities_global + 1, 

1191 (first, last + int(include_end)), 

1192 mode=h5_mode, 

1193 ) 

1194 h5_storage.write_dataset(offsets, insert_slice, offset_data) 

1195 del offset_data 

1196 

1197 # Permute and store topology data 

1198 if data.cell_type is None: 

1199 raise ValueError("Cannot write meshtags without cell-type information") 

1200 dx_ct = dolfinx.mesh.to_type(data.cell_type) 

1201 top_perm = np.argsort(dolfinx.cpp.io.perm_vtk(dx_ct, num_dofs_per_cell)) 

1202 topology_data = data.indices[:, top_perm].flatten() 

1203 topology = _create_dataset( 

1204 mesh_group, 

1205 "Connectivity", 

1206 shape=(data.num_entities_global * num_dofs_per_cell,), 

1207 dtype=np.int64, 

1208 maxshape=(None,), 

1209 mode=h5_mode, 

1210 resize=False, # Static, stored once 

1211 storage=storage_options, 

1212 ) 

1213 insert_slice = _compute_append_slice( 

1214 topology, 

1215 data.num_entities_global * num_dofs_per_cell, 

1216 np.array([data.local_start, data.local_start + data.indices.shape[0]]) 

1217 * num_dofs_per_cell, 

1218 mode=h5_mode, 

1219 ) 

1220 h5_storage.write_dataset(topology, insert_slice, topology_data) 

1221 del topology_data 

1222 

1223 # Store celltypes 

1224 cell_types = np.full( 

1225 data.indices.shape[0], 

1226 fenicsx_compat.vtk_cell_type(dx_ct, num_dofs_per_cell), 

1227 dtype=np.uint8, 

1228 ) 

1229 types = _create_dataset( 

1230 mesh_group, 

1231 "Types", 

1232 shape=(data.num_entities_global,), 

1233 dtype=np.uint8, 

1234 maxshape=(None,), 

1235 mode=h5_mode, 

1236 resize=False, # Static, stored once 

1237 storage=storage_options, 

1238 ) 

1239 insert_slice = _compute_append_slice( 

1240 types, 

1241 data.num_entities_global, 

1242 (data.local_start, data.local_start + data.indices.shape[0]), 

1243 h5_mode, 

1244 ) 

1245 h5_storage.write_dataset(types, insert_slice, cell_types) 

1246 del cell_types 

1247 

1248 steps = _create_group(mesh_group, "Steps", mode=h5_mode) 

1249 

1250 # Copy n-step counter 

1251 steps.attrs.create("NSteps", parent_mesh_group["Steps"].attrs["NSteps"]) 

1252 

1253 # Hardlink data that we know is the same across meshes 

1254 hardlink_keys = ["NumberOfParts", "PartOffsets", "Values", "PointOffsets"] 

1255 for key in hardlink_keys: 

1256 steps[key] = parent_mesh_group["Steps"][key] 

1257 

1258 # Write offset data for current time-step 

1259 all_parts = {} 

1260 for key in ["CellOffsets", "ConnectivityIdOffsets"]: 

1261 all_parts[key] = _create_dataset( 

1262 steps, 

1263 key, 

1264 shape=(1,), 

1265 dtype=np.int64, 

1266 maxshape=(None,), 

1267 mode=h5_mode, 

1268 ) 

1269 

1270 all_parts["CellOffsets"][-1] = types.shape[0] - data.num_entities_global 

1271 all_parts["ConnectivityIdOffsets"][-1] = offsets.shape[0] - (data.num_entities_global + 1) 

1272 # CellData requires an offset 

1273 cd_off = _create_group(steps, "CellDataOffsets", mode=h5_mode) 

1274 cd_data = _create_dataset( 

1275 cd_off, 

1276 data.name, 

1277 shape=parent_mesh_group["Steps"]["CellOffsets"].shape, 

1278 dtype=np.int64, 

1279 maxshape=(None,), 

1280 mode=h5_mode, 

1281 ) 

1282 cd_data[-1] = types.shape[0] - data.num_entities_global 

1283 

1284 # Static tags: every time step of the mesh holds the same cells 

1285 num_steps = int(steps.attrs["NSteps"]) 

1286 for dataset in ( 

1287 num_cells, 

1288 number_of_connectivities, 

1289 all_parts["CellOffsets"], 

1290 all_parts["ConnectivityIdOffsets"], 

1291 cd_data, 

1292 ): 

1293 _extend_1d_dataset(dataset, num_steps) 

1294 

1295 

1296def read_meshtags_data( 

1297 filename: str | Path, 

1298 comm: MPI.Comm, 

1299 name: str, 

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

1301) -> MeshTagsData: 

1302 """Read mesh tags from file. 

1303 

1304 Args: 

1305 filename: Path to file to read from 

1306 comm: MPI communicator used in storage 

1307 name: Name of the mesh tags to read 

1308 backend_args: Arguments to backend 

1309 

1310 Returns: 

1311 Internal data structure for the mesh tags read from file 

1312 """ 

1313 backend_args = get_default_backend_args(backend_args) 

1314 backend_args.update({"name": name}) 

1315 # Reuse reading cell-data 

1316 indices, values = read_cell_data(filename, name, comm, None, backend_args=backend_args) 

1317 # Read cell-type of grid to get topological dimension 

1318 with h5pyfile(filename, "r", comm=comm) as h5file: 

1319 hdf = _get_vtk_group(h5file, backend_args["name"]) 

1320 num_cells_global = hdf["Types"].size 

1321 local_cell_range = compute_local_range(comm, num_cells_global) 

1322 cell_types_local = hdf["Types"][slice(*local_cell_range)] 

1323 unique_cells = find_all_unique_cell_types(comm, cell_types_local, indices.shape[1]) 

1324 if unique_cells.shape[0] > 1: 

1325 raise NotImplementedError("io4dolfinx does not support mixed celltype grids") 

1326 vtk_cell_type = unique_cells[0][0] 

1327 if vtk_cell_type in _first_order_vtk.keys(): 

1328 ct = _first_order_vtk[vtk_cell_type] 

1329 elif vtk_cell_type in _arbitrary_lagrange_vtk.keys(): 

1330 ct = _arbitrary_lagrange_vtk[vtk_cell_type] 

1331 dim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(ct)) 

1332 return MeshTagsData(name=name, values=values.flatten(), indices=indices, dim=dim) 

1333 

1334 

1335def read_dofmap( 

1336 filename: str | Path, 

1337 comm: MPI.Comm, 

1338 name: str, 

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

1340) -> dolfinx.graph.AdjacencyList: 

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

1342 

1343 Args: 

1344 filename: Path to file to read from 

1345 comm: MPI communicator used in storage 

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

1347 backend_args: Arguments to backend 

1348 

1349 Returns: 

1350 Dofmap as an AdjacencyList 

1351 """ 

1352 raise NotImplementedError("The VTKHDF backend cannot make checkpoints.") 

1353 

1354 

1355def read_dofs( 

1356 filename: str | Path, 

1357 comm: MPI.Comm, 

1358 name: str, 

1359 time: float, 

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

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

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

1363 

1364 Args: 

1365 filename: Path to file to read from 

1366 comm: MPI communicator used in storage 

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

1368 time: Time stamp associated with the function to read 

1369 backend_args: Arguments to backend 

1370 

1371 Returns: 

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

1373 and the global starting point on the process. 

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

1375 """ 

1376 raise NotImplementedError("The VTKHDF backend cannot make checkpoints.") 

1377 

1378 

1379def read_cell_perms( 

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

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

1382 """ 

1383 Read cell permutation from file with given communicator, 

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

1385 

1386 Args: 

1387 comm: MPI communicator used in storage 

1388 filename: Path to file to read from 

1389 backend_args: Arguments to backend 

1390 

1391 Returns: 

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

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

1394 """ 

1395 raise NotImplementedError("The VTKHDF backend cannot make checkpoints.") 

1396 

1397 

1398def write_function( 

1399 filename: Path, 

1400 comm: MPI.Comm, 

1401 u: FunctionData, 

1402 time: float, 

1403 mode: FileMode, 

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

1405): 

1406 """ 

1407 Write a function to file. 

1408 

1409 Args: 

1410 comm: MPI communicator used in storage 

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

1412 filename: Path to file to write to 

1413 time: Time stamp associated with function 

1414 mode: File-mode to store the function 

1415 backend_args: Arguments to backend 

1416 """ 

1417 raise NotImplementedError("The VTKHDF backend cannot make checkpoints.") 

1418 

1419 

1420def read_legacy_mesh( 

1421 filename: Path | str, comm: MPI.Comm, group: str 

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

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

1424 legacy DOLFIN HDF5-file. 

1425 

1426 Args: 

1427 filename: Path to file to read from 

1428 comm: MPI communicator used in storage 

1429 group: Group in HDF5 file where mesh is stored 

1430 

1431 Returns: 

1432 Tuple containing: 

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

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

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

1436 """ 

1437 raise NotImplementedError("The VTKHDF backend cannot read legacy DOLFIN meshes.") 

1438 

1439 

1440def snapshot_checkpoint( 

1441 filename: Path | str, 

1442 mode: FileMode, 

1443 u: dolfinx.fem.Function, 

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

1445): 

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

1447 

1448 Args: 

1449 filename: Path to file to read from 

1450 mode: File-mode to store the function 

1451 u: dolfinx function to create a snapshot checkpoint for 

1452 backend_args: Arguments to backend 

1453 """ 

1454 raise NotImplementedError("The VTKHDF backend cannot make checkpoints.") 

1455 

1456 

1457def read_hdf5_array( 

1458 comm: MPI.Comm, 

1459 filename: Path | str, 

1460 group: str, 

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

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

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

1464 

1465 Args: 

1466 comm: MPI communicator used in storage 

1467 filename: Path to file to read from 

1468 group: Group in HDF5 file where array is stored 

1469 backend_args: Arguments to backend 

1470 

1471 Returns: 

1472 Tuple containing: 

1473 - Numpy array read from file 

1474 - Global starting point on the process. 

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

1476 """ 

1477 raise NotImplementedError("The VTKHDF backend cannot read HDF5 arrays") 

1478 

1479 

1480def write_data( 

1481 filename: Path | str, 

1482 array_data: ArrayData, 

1483 comm: MPI.Comm, 

1484 time: str | float | None, 

1485 mode: FileMode, 

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

1487): 

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

1489 

1490 

1491 Args: 

1492 filename: Path to file 

1493 array_data: Data to write to file 

1494 time: Time stamp 

1495 mode: Append or write 

1496 backend_args: The backend arguments 

1497 """ 

1498 h5_mode = convert_file_mode(mode) 

1499 assert h5_mode == "a" 

1500 backend_args = get_default_backend_args(backend_args) 

1501 mesh_name = backend_args["name"] 

1502 extension = array_data.type 

1503 storage_options = h5_storage.storage_options(comm, backend_args) 

1504 with h5pyfile(filename, h5_mode, comm=comm) as h5file: 

1505 hdf = h5file["VTKHDF"] 

1506 file_type = _decode_bytes_if_needed(hdf.attrs["Type"]) 

1507 # Check for type of VTKHDF file 

1508 if file_type != "MultiBlockDataSet": 

1509 raise ValueError(f"Cannot write meshtags to {filename} with VTK type {file_type}") 

1510 

1511 # Find mesh block to add data to 

1512 block = _get_vtk_group(h5file, mesh_name) 

1513 

1514 # Lay out vectors and tensors as VTK expects them 

1515 values = array_data.values 

1516 global_shape = array_data.global_shape 

1517 if array_data.value_shape is not None: 

1518 stored_shape = _read_value_shape(h5file, mesh_name, extension, array_data.name) 

1519 if stored_shape is not None and stored_shape != array_data.value_shape: 

1520 raise ValueError( 

1521 f"{extension} data {array_data.name} in {filename} has value shape " 

1522 f"{stored_shape}, not {array_data.value_shape}." 

1523 ) 

1524 values = pad_for_vtk(values, array_data.value_shape) 

1525 global_shape = (global_shape[0], values.shape[1]) 

1526 

1527 data_path = f"{extension}Data/{array_data.name}" 

1528 if storage_options and data_path in block: 

1529 h5_storage.check_storage_options(block[data_path], storage_options) 

1530 

1531 # Check the time before writing anything 

1532 assert isinstance(time, float) 

1533 stamps = _get_longest_time_sequence(h5file) 

1534 step = _find_time_step_index(stamps, time, filename) 

1535 record = f"{_array_metadata_group(mesh_name, extension, array_data.name)}/{_written_steps}" 

1536 written_steps, written_offsets = _get_time_steps_and_data_offset( 

1537 h5file, record, f"{block.name}/Steps/{extension}DataOffsets/{array_data.name}" 

1538 ) 

1539 if same_time(stamps[written_steps], time).any(): 

1540 raise ValueError( 

1541 f"{extension} data '{array_data.name}' has already been written at time " 

1542 f"{time} in {filename}." 

1543 ) 

1544 if step is None: 

1545 stamps = np.append(stamps, time) 

1546 step = len(stamps) - 1 

1547 _set_time_steps(h5file, stamps) 

1548 num_steps = len(stamps) 

1549 

1550 data_group = _create_group(block, f"{extension}Data", mode=h5_mode) 

1551 dataset = _create_dataset( 

1552 data_group, 

1553 array_data.name, 

1554 shape=global_shape, 

1555 dtype=values.dtype, 

1556 maxshape=(None, values.shape[1]), 

1557 mode=h5_mode, 

1558 storage=storage_options, 

1559 ) 

1560 insert_slice = _compute_append_slice( 

1561 dataset, 

1562 global_shape[0], 

1563 np.array( 

1564 [ 

1565 array_data.local_range[0], 

1566 array_data.local_range[0] + values.shape[0], 

1567 ] 

1568 ), 

1569 mode=h5_mode, 

1570 ) 

1571 h5_storage.write_dataset( 

1572 dataset, 

1573 insert_slice, 

1574 values, 

1575 ) 

1576 

1577 # The data at each step is that of the latest write at or before it, see 

1578 # `_fill_time_steps`. 

1579 data_offsets = _create_group(block["Steps"], f"{extension}DataOffsets", mode=h5_mode) 

1580 offsets = _create_dataset( 

1581 data_offsets, 

1582 array_data.name, 

1583 shape=(num_steps,), 

1584 dtype=np.int64, 

1585 maxshape=(None,), 

1586 mode=h5_mode, 

1587 resize=False, 

1588 ) 

1589 written_offsets = np.append(written_offsets, dataset.shape[0] - global_shape[0]) 

1590 written_steps = np.append(written_steps, step) 

1591 offsets[:] = _fill_time_steps(num_steps, written_steps, written_offsets) 

1592 _create_temporal_record(h5file, record, written_steps) 

1593 if array_data.value_shape is not None: 

1594 metadata = h5file[_array_metadata_group(mesh_name, extension, array_data.name)] 

1595 metadata.attrs[_value_shape_attr] = np.array(array_data.value_shape, dtype=np.int64) 

1596 _link_steps_at_root(h5file)