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

39 statements  

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

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

2# 

3# This file is part of io4dolfinx 

4# 

5# SPDX-License-Identifier: MIT 

6 

7"""Version of the layout of io4dolfinx checkpoints. 

8 

9Every mesh, function and set of mesh tags in a checkpoint written by the ``h5py`` or 

10``adios2`` backend is stamped with the version of the checkpoint format it was written in, 

11when it is first written. The stamp is never changed, so a file appended to by several 

12versions of io4dolfinx records the format of each object. 

13 

14- The major version changes when the layout changes so that older versions of io4dolfinx can 

15 no longer read it. A checkpoint with a newer major version than :data:`FORMAT_VERSION` 

16 is not read. 

17- The minor version changes when something optional is added. Readers ignore what they do 

18 not know, and treat what is missing as its default, so a checkpoint with a newer minor 

19 version is read, and an object with an older minor version can be appended to. 

20 

21Objects without a stamp were written before checkpoints were stamped, and are read as 

22format 1.0. The layout of each format is described in :doc:`checkpoint_format`. 

23""" 

24 

25from __future__ import annotations 

26 

27from importlib.metadata import version 

28from pathlib import Path 

29from typing import Any 

30 

31from mpi4py import MPI 

32 

33import dolfinx 

34import numpy as np 

35 

36__all__ = [ 

37 "FORMAT_VERSION", 

38 "stamp", 

39 "format_version", 

40 "object_metadata", 

41 "check_readable", 

42 "check_appendable", 

43] 

44 

45#: ``(major, minor)`` version of the checkpoint format written by this version of io4dolfinx 

46FORMAT_VERSION: tuple[int, int] = (1, 0) 

47 

48#: Names of the metadata stored with each object 

49FORMAT_KEY = "io4dolfinx_format" 

50VERSION_KEY = "io4dolfinx_version" 

51DOLFINX_VERSION_KEY = "dolfinx_version" 

52METADATA_KEYS = (FORMAT_KEY, VERSION_KEY, DOLFINX_VERSION_KEY) 

53 

54 

55def stamp() -> dict[str, Any]: 

56 """The metadata stored with an object when it is first written. 

57 

58 Returns: 

59 The checkpoint format version, as an ``int32`` array ``[major, minor]``, and the 

60 versions of io4dolfinx and DOLFINx that wrote the object, as strings 

61 """ 

62 return { 

63 FORMAT_KEY: np.array(FORMAT_VERSION, dtype=np.int32), 

64 VERSION_KEY: version("io4dolfinx"), 

65 DOLFINX_VERSION_KEY: dolfinx.__version__, 

66 } 

67 

68 

69def format_version(metadata: dict[str, Any]) -> tuple[int, int] | None: 

70 """The checkpoint format version in the metadata of an object. 

71 

72 Returns: 

73 ``(major, minor)``, or ``None`` if the object has no stamp 

74 """ 

75 if FORMAT_KEY not in metadata: 

76 return None 

77 major, minor = (int(v) for v in np.asarray(metadata[FORMAT_KEY]).reshape(-1)[:2]) 

78 return major, minor 

79 

80 

81def object_metadata( 

82 backend: Any, 

83 filename: Path | str, 

84 comm: MPI.Comm, 

85 kind: str, 

86 name: str | None = None, 

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

88) -> dict[str, Any]: 

89 """The metadata of an object in a file, if the backend stores metadata. 

90 

91 Only the checkpoint backends (``h5py`` and ``adios2``) do; for any other backend, and 

92 for an object that does not exist, the metadata is empty. 

93 

94 Args: 

95 backend: The backend module 

96 filename: Path to file 

97 comm: MPI communicator 

98 kind: ``"mesh"``, ``"function"`` or ``"meshtags"`` 

99 name: Name of the function or mesh tags, unused for a mesh 

100 backend_args: Arguments to backend 

101 """ 

102 reader = getattr(backend, "read_metadata", None) 

103 return {} if reader is None else reader(filename, comm, kind, name, backend_args) 

104 

105 

106def _describe(metadata: dict[str, Any], what: str) -> str: 

107 major, minor = format_version(metadata) # type: ignore[misc] 

108 written_by = metadata.get(VERSION_KEY) 

109 by = f" by io4dolfinx {written_by}" if written_by else "" 

110 return f"{what} was written{by} in checkpoint format {major}.{minor}" 

111 

112 

113def check_readable(metadata: dict[str, Any], what: str) -> tuple[int, int]: 

114 """Check that an object can be read by this version of io4dolfinx. 

115 

116 Args: 

117 metadata: The metadata of the object, as read by the backend 

118 what: Description of the object for the error message, e.g. ``"Function 'u' in 

119 file.bp"`` 

120 

121 Returns: 

122 The checkpoint format version of the object, ``(1, 0)`` if it has no stamp 

123 

124 Raises: 

125 ValueError: If the object has a newer major version than this io4dolfinx reads. 

126 """ 

127 found = format_version(metadata) 

128 if found is None: 

129 return (1, 0) 

130 if found[0] > FORMAT_VERSION[0]: 

131 raise ValueError( 

132 f"{_describe(metadata, what)}, but this version of io4dolfinx " 

133 f"({version('io4dolfinx')}) reads checkpoint format {FORMAT_VERSION[0]}.x. " 

134 "Upgrade io4dolfinx to read it." 

135 ) 

136 return found 

137 

138 

139def check_appendable(metadata: dict[str, Any], what: str): 

140 """Check that this version of io4dolfinx can append to an existing object. 

141 

142 Appending keeps the stamp of the object, so it is allowed if the object has the same 

143 major version, whatever its minor version. 

144 

145 Args: 

146 metadata: The metadata of the object, empty if it does not exist yet 

147 what: Description of the object for the error message 

148 

149 Raises: 

150 ValueError: If the object has another major version. 

151 """ 

152 found = format_version(metadata) 

153 if found is not None and found[0] != FORMAT_VERSION[0]: 

154 raise ValueError( 

155 f"{_describe(metadata, what)}, and this version of io4dolfinx " 

156 f"({version('io4dolfinx')}) writes checkpoint format " 

157 f"{FORMAT_VERSION[0]}.{FORMAT_VERSION[1]}, so it cannot append to it. " 

158 "Write to a new file." 

159 )