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

88 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 11:58 +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"""Convert checkpoints of adios4dolfinx 0.7 and older, and mesh tags of legacy DOLFIN, to 

8the current format. 

9 

10:func:`convert` copies the stored data to a checkpoint of the current format, so no mesh or 

11function space is created. It reads two kinds of files: 

12 

13- Checkpoints of adios4dolfinx 0.7 and older (format 0, see :mod:`io4dolfinx.format`), 

14 written with ADIOS2. They store no function names or time stamps: each function is in a 

15 step of its own under the same variable names. Each function is given a name and written 

16 at time 0. 

17- HDF5 files of legacy DOLFIN (``HDF5File``), holding a mesh and mesh functions. The mesh 

18 and the named mesh functions are written as a mesh and mesh tags. Functions of these files 

19 are numbered by DOLFIN and need a function space: read them with 

20 :func:`io4dolfinx.read_function_from_legacy_h5` onto the mesh of the converted file, which 

21 has the node order of the DOLFIN file. 

22 

23The conversion is also available from the command line, under MPI if wanted:: 

24 

25 io4dolfinx-convert old.bp new.h5 --names u 

26 io4dolfinx-convert dolfin_mesh.h5 new.h5 --meshtags facet_tags 

27 

28or, equivalently, ``python3 -m io4dolfinx.converter``. 

29""" 

30 

31from __future__ import annotations 

32 

33import argparse 

34from collections.abc import Sequence 

35from pathlib import Path 

36from typing import Any 

37 

38from mpi4py import MPI 

39 

40import basix 

41import dolfinx 

42import h5py 

43 

44from .backends import FileMode, get_backend 

45from .format import stamp 

46from .structures import FunctionData, MeshData 

47from .utils import check_file_exists 

48from .writers import write_function, write_mesh 

49 

50__all__ = ["convert", "main"] 

51 

52# Backends that write checkpoints, by the suffix of their files 

53_backends_by_suffix = {".bp": "adios2", ".h5": "h5py"} 

54_checkpoint_backends = ("adios2", "adios2-serial", "h5py", "h5py-serial") 

55 

56 

57def _convert_dolfin( 

58 input_file: Path, 

59 output_file: Path, 

60 comm: MPI.Comm, 

61 meshtags: Sequence[str], 

62 mesh_group: str, 

63 backend: str, 

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

65): 

66 """Write the mesh and mesh functions of a legacy DOLFIN HDF5 file as a checkpoint.""" 

67 from .backends.h5py import backend as h5py_backend 

68 

69 assert isinstance(comm, MPI.Intracomm) 

70 topology, x, cell_type = h5py_backend.read_legacy_mesh(input_file, comm, mesh_group) 

71 if cell_type is None: 

72 raise ValueError(f"The mesh {mesh_group} in {input_file} has no cell type.") 

73 

74 def global_range(local_size: int) -> tuple[tuple[int, int], int]: 

75 # exscan is collective, and gives None on rank 0 

76 start = comm.exscan(local_size, op=MPI.SUM) 

77 start = start if comm.rank > 0 else 0 

78 return (start, start + local_size), comm.allreduce(local_size, op=MPI.SUM) 

79 

80 node_range, num_nodes = global_range(len(x)) 

81 cell_range, num_cells = global_range(len(topology)) 

82 mesh = MeshData( 

83 metadata=stamp(), 

84 local_geometry=x, 

85 local_geometry_pos=node_range, 

86 num_nodes_global=num_nodes, 

87 local_topology=topology, 

88 local_topology_pos=cell_range, 

89 num_cells_global=num_cells, 

90 cell_type=cell_type, 

91 degree=1, 

92 lagrange_variant=int(basix.LagrangeVariant.equispaced), 

93 store_partition=False, 

94 ) 

95 write_mesh(output_file, comm, mesh, 0.0, FileMode.write, backend_args, backend) 

96 

97 writer = get_backend(backend) 

98 writer_args = writer.get_default_backend_args(backend_args) 

99 for name in meshtags: 

100 tags = h5py_backend.read_meshtags_data(input_file, comm, name, {"legacy": True}) 

101 (tags.local_start, _), tags.num_entities_global = global_range(len(tags.values)) 

102 tags.num_dofs_per_entity = tags.indices.shape[1] 

103 tags.cell_type = dolfinx.mesh.to_string( 

104 dolfinx.cpp.mesh.cell_entity_type(dolfinx.mesh.to_type(cell_type), tags.dim, 0) 

105 ) 

106 tags.metadata = stamp() 

107 writer.write_meshtags(output_file, comm, tags, writer_args) 

108 

109 

110def convert( 

111 input_file: Path | str, 

112 output_file: Path | str, 

113 comm: MPI.Comm = MPI.COMM_WORLD, 

114 names: Sequence[str] | None = None, 

115 meshtags: Sequence[str] = (), 

116 mesh_group: str = "/mesh", 

117 backend: str | None = None, 

118 backend_args: dict[str, Any] | None = None, 

119 engine: str = "BP4", 

120 overwrite: bool = False, 

121): 

122 """Convert a checkpoint of adios4dolfinx 0.7 or older, or the mesh and mesh functions of 

123 a legacy DOLFIN HDF5 file, to the current format. 

124 

125 The data is copied as stored, so the result is read as any checkpoint, with 

126 :func:`io4dolfinx.read_mesh`, :func:`io4dolfinx.read_meshtags` and 

127 :func:`io4dolfinx.read_function`. A legacy DOLFIN file is recognised by the topology of 

128 its mesh, at `mesh_group`; any other file is read as an adios4dolfinx checkpoint. 

129 

130 Args: 

131 input_file: The file to convert. 

132 output_file: The checkpoint to write. 

133 comm: The communicator to read and write with. 

134 names: The name to give each function of an adios4dolfinx checkpoint, in the order 

135 they were written, as the file does not store names. Defaults to ``["u"]``. 

136 meshtags: The mesh functions of a legacy DOLFIN file to convert to mesh tags of the 

137 same names. 

138 mesh_group: The group of the mesh in a legacy DOLFIN file. 

139 backend: The backend to write with, ``"adios2"`` or ``"h5py"``. Chosen from the 

140 suffix of `output_file` if not given: ``.bp`` for ADIOS2, ``.h5`` for h5py. 

141 backend_args: Arguments of the backend that writes. 

142 engine: The ADIOS2 engine an adios4dolfinx checkpoint was written with. 

143 overwrite: Replace `output_file` if it exists. 

144 

145 Raises: 

146 FileExistsError: If `output_file` exists and `overwrite` is not set. 

147 ValueError: If `input_file` is neither kind of file, the number of names is not 

148 the number of functions in it, names are given for a legacy DOLFIN file or mesh 

149 tags for an adios4dolfinx checkpoint, or the backend is not given and cannot be 

150 chosen from the suffix of `output_file`. 

151 """ 

152 input_file = Path(input_file) 

153 output_file = Path(output_file) 

154 check_file_exists(input_file) 

155 if backend is None: 

156 if output_file.suffix not in _backends_by_suffix: 

157 raise ValueError( 

158 f"Cannot tell the backend from the suffix of {output_file}: give the backend, " 

159 f"one of {sorted(set(_backends_by_suffix.values()))}, or use one of the " 

160 f"suffixes {sorted(_backends_by_suffix)}." 

161 ) 

162 backend = _backends_by_suffix[output_file.suffix] 

163 if backend not in _checkpoint_backends: 

164 raise ValueError( 

165 f"Cannot write checkpoints with the {backend!r} backend, use one of " 

166 f"{list(_checkpoint_backends)}." 

167 ) 

168 if output_file.exists() and not overwrite: 

169 raise FileExistsError(f"{output_file} exists. Set overwrite to replace it.") 

170 if output_file.resolve() == input_file.resolve(): 

171 raise ValueError("The converted checkpoint cannot replace the one it is read from.") 

172 

173 dolfin_file = False 

174 if h5py.is_hdf5(input_file): 

175 with h5py.File(input_file, "r") as h5file: 

176 dolfin_file = f"{mesh_group}/topology" in h5file 

177 if dolfin_file: 

178 if names is not None: 

179 raise ValueError( 

180 "Functions of legacy DOLFIN files are numbered by DOLFIN and need a function " 

181 "space: read them with io4dolfinx.read_function_from_legacy_h5 onto the mesh " 

182 "of the converted file." 

183 ) 

184 _convert_dolfin(input_file, output_file, comm, meshtags, mesh_group, backend, backend_args) 

185 return 

186 if len(meshtags) > 0: 

187 raise ValueError(f"{input_file} is an adios4dolfinx checkpoint, which has no mesh tags.") 

188 

189 from .backends.adios2.backend import read_format0_checkpoint 

190 

191 names = ["u"] if names is None else names 

192 mesh, functions = read_format0_checkpoint(input_file, comm, engine) 

193 if len(names) != len(functions): 

194 raise ValueError( 

195 f"{input_file} holds {len(functions)} functions, so it needs {len(functions)} " 

196 f"names, got {list(names)}." 

197 ) 

198 if len(set(names)) != len(names): 

199 raise ValueError(f"The names of the functions must differ, got {list(names)}.") 

200 

201 write_mesh(output_file, comm, mesh, 0.0, FileMode.write, backend_args, backend) 

202 for name, function in zip(names, functions): 

203 data = FunctionData(metadata=stamp(), name=name, **function) 

204 write_function(output_file, comm, data, 0.0, FileMode.append, backend_args, backend) 

205 

206 

207def main(argv: Sequence[str] | None = None): 

208 """Run :func:`convert` from the command line.""" 

209 parser = argparse.ArgumentParser( 

210 description="Convert a checkpoint of adios4dolfinx 0.7 or older, or the mesh and mesh " 

211 "functions of a legacy DOLFIN HDF5 file, to the current io4dolfinx format.", 

212 formatter_class=argparse.ArgumentDefaultsHelpFormatter, 

213 ) 

214 parser.add_argument("input", type=Path, help="The checkpoint to convert") 

215 parser.add_argument("output", type=Path, help="The checkpoint to write") 

216 parser.add_argument( 

217 "--names", 

218 nargs="+", 

219 default=None, 

220 help="The name of each function of an adios4dolfinx checkpoint, in the order they " 

221 "were written (default: u)", 

222 ) 

223 parser.add_argument( 

224 "--meshtags", 

225 nargs="+", 

226 default=(), 

227 help="The mesh functions of a legacy DOLFIN file to convert to mesh tags", 

228 ) 

229 parser.add_argument( 

230 "--mesh-group", default="/mesh", help="The group of the mesh in a legacy DOLFIN file" 

231 ) 

232 parser.add_argument( 

233 "--backend", 

234 choices=_checkpoint_backends, 

235 default=None, 

236 help="The backend to write with. Chosen from the suffix of the output if not given: " 

237 ".bp for adios2, .h5 for h5py", 

238 ) 

239 parser.add_argument( 

240 "--engine", default="BP4", help="The ADIOS2 engine the input was written with" 

241 ) 

242 parser.add_argument("--overwrite", action="store_true", help="Replace the output if it exists") 

243 args = parser.parse_args(argv) 

244 convert( 

245 args.input, 

246 args.output, 

247 names=args.names, 

248 meshtags=args.meshtags, 

249 mesh_group=args.mesh_group, 

250 backend=args.backend, 

251 engine=args.engine, 

252 overwrite=args.overwrite, 

253 ) 

254 

255 

256if __name__ == "__main__": 

257 main()