Debian Codegraph @

nixio/cmd/upgrade.py

raw symbols SCIP
1 """
2 Upgrade NIX files to newest file format version.
3 """
4 import h5py
5 import nixio as nix
6
7
8 def get_file_version(fname):
9 with h5py.File(fname, mode="r") as hfile:
10 return tuple(hfile.attrs["version"])
11
12
13 def has_valid_file_id(fname):
14 with h5py.File(fname, mode="r") as hfile:
15 fileid = hfile.attrs.get("id")
16 if fileid and nix.util.is_uuid(fileid):
17 return True
18 return False
19
20
21 def add_file_id(fname):
22 """
23 Returns a closure that binds the filename if a file ID is required. When
24 the return value is called, it adds a UUID to the file header.
25 """
26 if has_valid_file_id(fname):
27 return None
28
29 def add_id():
30 "Add a UUID to the file header"
31 with h5py.File(fname, mode="a") as hfile:
32 if has_valid_file_id(fname):
33 return
34 hfile.attrs["id"] = nix.util.create_id()
35 return add_id
36
37
38 def update_property_values(fname):
39 """
40 Returns a closure that binds the filename if at least one Property update
41 is required. When the return value is called, it rewrites all the metadata
42 Property objects to the new format.
43 """
44 props = list()
45
46 with h5py.File(fname, mode="r") as hfile:
47 sections = hfile["metadata"]
48
49 def find_props(_, group):
50 if isinstance(group, h5py.Dataset) and len(group.dtype):
51 # structured/compound dtypes have non-zero length
52 props.append(group.name)
53
54 sections.visititems(find_props)
55
56 if not props:
57 return None
58
59 def update_props():
60 for propname in props:
61 with h5py.File(fname, mode="a") as hfile:
62 prop = hfile[propname]
63 if not (isinstance(prop, h5py.Dataset) and len(prop.dtype)):
64 # File was possibly changed since the tasks were
65 # collected. File may have been submitted twice or
66 # multiple instances of the script could be running.
67 # skip this prop
68 continue
69
70 # pull out the old extra attributes
71 uncertainty = prop["uncertainty"]
72 reference = prop["reference"]
73 filename = prop["filename"]
74 encoder = prop["encoder"]
75 checksum = prop["checksum"]
76
77 # replace base prop
78 values = prop["value"]
79 definition = prop.attrs.get("definition")
80 unit = prop.attrs.get("unit")
81 dt = values.dtype
82 del hfile[propname]
83 newprop = create_property(hfile, propname,
84 dtype=dt, data=values,
85 definition=definition,
86 unit=unit)
87
88 # Create properties for any extra attrs that are set
89 if len(set(uncertainty)) > 1:
90 # multiple values, make new prop
91 create_property(hfile, propname + ".uncertainty",
92 dtype=float, data=uncertainty)
93 elif any(uncertainty):
94 # single, unique, non-zero value; add to main prop attr
95 newprop.attrs["uncertainty"] = uncertainty[0]
96
97 if any(reference):
98 create_property(hfile, propname + ".reference",
99 dtype=nix.util.vlen_str_dtype,
100 data=reference)
101
102 if any(filename):
103 create_property(hfile, propname + ".filename",
104 dtype=nix.util.vlen_str_dtype,
105 data=filename)
106
107 if any(encoder):
108 create_property(hfile, propname + ".encoder",
109 dtype=nix.util.vlen_str_dtype,
110 data=encoder)
111
112 if any(checksum):
113 create_property(hfile, propname + ".checksum",
114 dtype=nix.util.vlen_str_dtype,
115 data=checksum)
116
117 psuffix = "ies" if len(props) > 1 else "y"
118 update_props.__doc__ = "Update {} propert{}".format(len(props), psuffix)
119 return update_props
120
121
122 def create_h5group(parent, name):
123 """
124 Creates an h5group with the given name under the given parent using the
125 same flags and properties used in NIX (creation order tracking and
126 indexing).
127 """
128 gcpl = h5py.h5p.create(h5py.h5p.GROUP_CREATE)
129 flags = h5py.h5p.CRT_ORDER_TRACKED | h5py.h5p.CRT_ORDER_INDEXED
130 gcpl.set_link_creation_order(flags)
131 name = name.encode("utf-8")
132 gid = h5py.h5g.create(parent.id, name, gcpl=gcpl)
133 return h5py.Group(gid)
134
135
136 def update_alias_range_dimension(fname):
137 """
138 Returns a closure that binds the filename if at least one
139 AliasRangeDimension is found. When the return value is called, it converts
140 all AliasRangeDimensions to a RangeDimension with a DimensionLink to the
141 DataArray.
142 """
143 dims = list()
144 with h5py.File(fname, mode="r") as hfile:
145 for block in hfile["data"].values():
146 if "data_arrays" not in block:
147 continue
148
149 for data_array in block["data_arrays"].values():
150 if "dimensions" not in data_array:
151 continue
152 for dimension in data_array["dimensions"].values():
153 daid = data_array.attrs["entity_id"]
154 if ("ticks" not in dimension and "link" not in dimension
155 and daid in dimension):
156 # found alias range dimension
157 dims.append(dimension.name)
158
159 if not dims:
160 return None
161
162 def update_alias_dims():
163 for dimname in dims:
164 with h5py.File(fname, mode="a") as hfile:
165 dim = hfile[dimname]
166 parentda = dim.parent.parent
167 daid = parentda.attrs["entity_id"]
168 if ("ticks" in dim or "link" in dim and daid not in dim):
169 # File was possibly changed since the tasks were
170 # collected. File may have been submitted twice or
171 # multiple instances of the script could be running.
172 # skip this prop
173 continue
174
175 # create link object
176 link = create_h5group(dim, "link")
177 link.attrs["entity_id"] = nix.util.create_id()
178 link.attrs["data_object_type"] = "DataArray"
179 link[daid] = parentda # creates link
180 link.attrs["index"] = [-1]
181 now = nix.util.time_to_str(nix.util.now_int())
182 link.attrs["created_at"] = now
183 link.attrs["updated_at"] = now
184
185 # delete old alias link
186 del dim[daid]
187
188 plural = "s" if len(dims) > 1 else ""
189 update_alias_dims.__doc__ = ("Convert {} alias range dimension{s} "
190 "to link{s}").format(len(dims), s=plural)
191 return update_alias_dims
192
193
194 def create_property(hfile, name, dtype, data, definition=None, unit=None):
195 prop = hfile.create_dataset(name, dtype=dtype, data=data, chunks=True)
196 prop.attrs["name"] = name.split("/")[-1]
197 prop.attrs["entity_id"] = nix.util.create_id()
198 prop.attrs["created_at"] = nix.util.time_to_str(nix.util.now_int())
199 prop.attrs["updated_at"] = nix.util.time_to_str(nix.util.now_int())
200 if definition:
201 prop.attrs["definition"] = definition
202 if unit:
203 prop.attrs["unit"] = unit
204 return prop
205
206
207 def update_format_version(fname):
208 """
209 Returns a closure that binds the filename. When the return value is
210 called, it updates the version in the header to the version in the library.
211 """
212 def update_ver():
213 with h5py.File(fname, mode="a") as hfile:
214 hfile.attrs["version"] = nix.file.HDF_FF_VERSION
215 lib_verstr = ".".join(str(v) for v in nix.file.HDF_FF_VERSION)
216 update_ver.__doc__ = f"Update the file format version to {lib_verstr}"
217 return update_ver
218
219
220 def collect_tasks(fname):
221 tasks = list()
222 file_ver = get_file_version(fname)
223 file_verstr = ".".join(str(v) for v in file_ver)
224 lib_verstr = ".".join(str(v) for v in nix.file.HDF_FF_VERSION)
225 if file_ver >= nix.file.HDF_FF_VERSION:
226 return tasks, file_verstr, lib_verstr
227
228 # even if the version string indicates the file is old, check format
229 # details before scheduling tasks
230 id_task = add_file_id(fname)
231 if id_task:
232 tasks.append(id_task)
233
234 props_task = update_property_values(fname)
235 if props_task:
236 tasks.append(props_task)
237
238 alias_task = update_alias_range_dimension(fname)
239 if alias_task:
240 tasks.append(alias_task)
241
242 # always update the format last
243 tasks.append(update_format_version(fname))
244
245 return tasks, file_verstr, lib_verstr
246
247
248 def create_subcmd_parser(parser):
249 parser.add_argument("-f", "--force", action="store_true",
250 help="overwrite existing files without prompting")
251 parser.add_argument("file", type=str, nargs="+",
252 help="path to file to upgrade (at least one)")
253 return parser
254
255
256 def print_tasks(fname, tasklist, fileversion, libversion):
257 if len(tasklist) == 0:
258 print(f"File {fname} is up to date ({fileversion})")
259 return
260 print(f"{fname}: {fileversion} -> {libversion}")
261 print(" - " + "\n - ".join(t.__doc__ for t in tasklist) + "\n")
262
263
264 def process_tasks(fname, tasklist, quiet=True):
265 if not quiet:
266 print(f"Processing {fname} ", end="", flush=True)
267 for task in tasklist:
268 task()
269 if not quiet:
270 print("done")
271
272
273 def file_upgrade(fname, quiet=True):
274 """
275 Upgrades a file from an old format version to the current version.
276
277 :param fname: The fully qualified filename.
278 :type fname: str
279 :param quiet: Whether or not the upgrade tool should give feedback on the command line. Defaults to True, no output.
280 :type quiet: bool
281
282 :returns: True if the conversion succeeded, False otherwise, it the file does not need upgrading True is returned.
283 :rtype : bool
284 """
285 try:
286 tasklist, fileversion, libversion = collect_tasks(fname)
287 if not quiet:
288 print_tasks(fname, tasklist, fileversion, libversion)
289
290 process_tasks(fname, tasklist, quiet=quiet)
291 except Exception as e:
292 print(f"An Exception occurred while upgrading file {fname}. Error is {e}")
293 return False
294 return True
295
296
297 def main(args):
298 filenames = args.file
299
300 tasks = dict()
301 for fname in filenames:
302 tasklist, fileversion, libversion = collect_tasks(fname)
303 print_tasks(fname, tasklist, fileversion, libversion)
304 if not tasklist:
305 continue
306
307 tasks[fname] = tasklist
308
309 if not tasks:
310 return
311
312 force = args.force
313 if not force:
314 print("""
315 PLEASE READ CAREFULLY
316
317 If you choose to continue, the changes listed above will be applied to the
318 respective files. This will make the files unreadable by older NIX library
319 versions. Although this procedure is generally fast and safe, interrupting it
320 may leave files in a corrupted state.
321
322 MAKE SURE YOUR FILES AND DATA ARE BACKED UP BEFORE CONTINUING.
323 """)
324 conf = None
325
326 while conf not in ("y", "n", "yes", "no"):
327 conf = input("Continue with changes? [yes/no] ")
328 conf = conf.lower()
329 else:
330 conf = "yes"
331
332 if conf in ("y", "yes"):
333 for fname, tasklist in tasks.items():
334 process_tasks(fname, tasklist, quiet=False)