Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/changes/newsfragments/8781.new
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Added the config option ``qcodes.config.dataset.export_netcdf_snapshot_in_group``. When enabled, the snapshot of datasets
exported to NetCDF is stored as a variable in the ``qcodes_metadata`` group, compressed with the same
``qcodes.config.dataset.export_netcdf_compression_level`` as the data, rather than as the
``snapshot`` attribute. The snapshot is then only read when needed, which reduces the time it takes to open
files with large snapshots, and their size when compression is enabled.
The ``snapshot`` attribute then contains a pointer to that location. ``load_from_netcdf`` supports both layouts, and
the new function ``qcodes.dataset.snapshot_from_netcdf`` can be used to read the snapshot from either layout
without a QCoDeS database. The option is disabled by default since tools that read the ``snapshot`` attribute directly
must be updated to support the new layout.
50 changes: 49 additions & 1 deletion docs/dataset/dataset_design.rst
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,55 @@ database fail; ``get_metadata("snapshot")`` returns the raw bytes; and runs
without a results table, such as those written by ``DataSetInMem``, cannot be
loaded at all. Direct SQL consumers must handle BLOBs explicitly rather than
passing them to SQLite JSON functions. Exporting to NetCDF with QCoDeS 0.64.0 or
later retains the snapshot as JSON for interchange with earlier versions.
later retains the snapshot as JSON for interchange with earlier versions,
unless the snapshot is stored in a separate group as described below.

.. _sec:design_netcdf_snapshot_storage:

Snapshot storage in NetCDF exports
----------------------------------

By default the snapshot of a dataset exported to NetCDF is stored as the JSON
string attribute ``snapshot`` of the root group. HDF5 attributes cannot be
compressed and are read in full whenever a file is opened, which is costly for
large snapshots. The layout is controlled by::

qcodes.config.dataset.export_netcdf_snapshot_in_group = True

When enabled (the default is ``False``), the exported file is laid out as
follows:

- The variable ``/qcodes_metadata/snapshot`` holds the JSON snapshot encoded as
UTF-8 in a one-dimensional ``uint8`` array along the dimension
``snapshot_bytes``. It is compressed with deflate (gzip) at
``qcodes.config.dataset.export_netcdf_compression_level``, the same level as
the data, and is stored uncompressed if that level is ``0``.
- The root ``snapshot`` attribute contains a pointer to that variable, the JSON
object ``{"__qcodes_snapshot_location__": "qcodes_metadata/snapshot"}``.
- Datasets without a snapshot keep the attribute ``"null"`` and get no group.
- If the dataset has a variable or dimension named ``qcodes_metadata``, the
snapshot is stored as the attribute instead and a warning is logged.
- If writing the group fails, the export is discarded and an existing file at
the destination is left unchanged, since a grouped export is written to a
temporary file next to the destination and only moved into place once
complete. The replacement keeps the permission bits of the existing file, and
a symlinked destination has its target replaced. When
reading a file whose pointer refers to a missing variable, a warning is
logged and the dataset is treated as having no snapshot, so its data can
still be loaded.

The group is standard netCDF4, readable by netCDF-C and h5py, and is not part
of ``xarray.open_dataset(path)``, so the snapshot is only read when needed.
``load_from_netcdf`` follows the pointer, so loaded datasets and their
``to_xarray_dataset()`` output contain the snapshot as JSON as before. To read
the snapshot from either layout without a QCoDeS database, use
``qcodes.dataset.snapshot_from_netcdf(path)``. Tools that read the ``snapshot``
attribute directly see only the pointer and must be updated; older QCoDeS
versions still load the data of such files, but their snapshot contains only the
pointer. Exporting an xarray dataset opened directly from such a file raises an
error rather than writing a pointer without its group; load it with
``load_from_netcdf`` or replace the attribute with
``json.dumps(snapshot_from_netcdf(path))`` first.

.. _sec:design_split_storage:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"QCoDeD will attempt to call any [EntryPoint](https://setuptools.pypa.io/en/latest/userguide/entry_point.html#entry-points-for-plugins) registered for the group \"qcodes.dataset.on_export\". This will allow a user to setup a function that can trigger post processing such as backup to cloud, external drive, plotting or post process analysis. Functions registered for this entry point group are expected to take a Path to the file as input and return None. Please consult the [Setuptools docs](https://setuptools.pypa.io/en/latest/userguide/entry_point.html#entry-points-for-plugins) for more information on the use of EntryPoints. The entry point function must take the path to the exported file as a positional argument and take ``**kwargs`` for future compatibility. At the moment a single keyword argument ``automatic_export`` is passed to the function which indicates if the dataset was automatically or manually exported."
"QCoDeS will attempt to call any [EntryPoint](https://setuptools.pypa.io/en/latest/userguide/entry_point.html#entry-points-for-plugins) registered for the group \"qcodes.dataset.on_export\". This will allow a user to setup a function that can trigger post processing such as backup to cloud, external drive, plotting or post process analysis. Functions registered for this entry point group are expected to take a Path to the file as input and return None. Please consult the [Setuptools docs](https://setuptools.pypa.io/en/latest/userguide/entry_point.html#entry-points-for-plugins) for more information on the use of EntryPoints. The entry point function must take the path to the exported file as a positional argument and take ``**kwargs`` for future compatibility. At the moment a single keyword argument ``automatic_export`` is passed to the function which indicates if the dataset was automatically or manually exported."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Storing large snapshots in a separate group\n",
"\n",
"By default the snapshot is stored as the `snapshot` attribute of the exported NetCDF file. Attributes cannot be compressed and are always read when a file is opened, which is costly for large snapshots. Setting `qcodes.config.dataset.export_netcdf_snapshot_in_group = True` stores the snapshot as a variable in the `qcodes_metadata` group of the file instead, compressed with the same `export_netcdf_compression_level` as the data, and the `snapshot` attribute then contains a pointer to that location. The snapshot is then only read when needed, and it is only compressed when `export_netcdf_compression_level` is above 0. `load_from_netcdf` supports both layouts. To read the snapshot of an exported file without a QCoDeS database, use `qcodes.dataset.snapshot_from_netcdf(path)` rather than reading the `snapshot` attribute directly."
]
},
{
Expand Down
1 change: 1 addition & 0 deletions src/qcodes/configuration/qcodesrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"export_chunked_export_of_large_files_enabled": false,
"export_chunked_threshold": 1000,
"export_netcdf_compression_level": 0,
"export_netcdf_snapshot_in_group": false,
"in_memory_cache": true,
"load_from_exported_file": false,
"raw_data_backend": "sqlite_main_db",
Expand Down
5 changes: 5 additions & 0 deletions src/qcodes/configuration/qcodesrc_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,11 @@
"default": 0,
"description": "Deflate (gzip) compression level used when exporting datasets to netcdf. The default of 0 writes uncompressed files. A level of 4 is recommended when enabling compression since higher levels are slower with almost no additional size reduction."
},
"export_netcdf_snapshot_in_group": {
"type": "boolean",
"default": false,
"description": "Store the snapshot of datasets exported to netcdf as a variable in the 'qcodes_metadata' group, compressed with export_netcdf_compression_level, rather than as the 'snapshot' attribute. The 'snapshot' attribute then contains a pointer to that location. The snapshot is then only read when needed, which reduces the time to open files with large snapshots, and the file size when export_netcdf_compression_level is above 0. Tools that read the 'snapshot' attribute directly must be updated, e.g. to use qcodes.dataset.snapshot_from_netcdf. Files written with this enabled can be loaded with load_from_netcdf by older versions of QCoDeS, but the snapshot of the loaded dataset will only contain the pointer."
},
"load_from_exported_file": {
"description": "Flag to load metadata and raw data from exported file of type specified in export_type. If set to true, qcodes will try to import from file first, if it exists.",
"type": "boolean",
Expand Down
2 changes: 2 additions & 0 deletions src/qcodes/dataset/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
)
from .experiment_settings import get_default_experiment_id, reset_default_experiment_id
from .export_config import get_data_export_path
from .exporters.netcdf_snapshot import snapshot_from_netcdf
from .guid_helpers import guids_from_dbs, guids_from_dir, guids_from_list_str
from .legacy_import import import_dat_file
from .measurement_extensions import (
Expand Down Expand Up @@ -134,5 +135,6 @@
"purge_orphaned_datasets",
"reset_default_experiment_id",
"rundescriber_from_json",
"snapshot_from_netcdf",
"update_raw_data_paths",
]
12 changes: 10 additions & 2 deletions src/qcodes/dataset/data_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -1770,15 +1770,20 @@ def _export_as_netcdf(self, path: Path, file_name: str) -> Path:
num_digits = len(str(num_files))
file_name_template = f"ds_{{:0{num_digits}d}}.nc"
for i in trange(num_files, desc="Writing individual files"):
row_dataset = self.to_xarray_dataset(start=i + 1, end=i + 1)
# the snapshot is added once to the combined file below
# rather than written to every temporary file
row_dataset.attrs["snapshot"] = "null"
xarray_to_h5netcdf_with_complex_numbers(
self.to_xarray_dataset(start=i + 1, end=i + 1),
row_dataset,
temp_path / file_name_template.format(i),
# these files are temporary and immediately recombined
# into the final file so compressing them only costs time
compression_level=0,
)
files = tuple(temp_path.glob("*.nc"))
data = xr.open_mfdataset(files)
data.attrs["snapshot"] = self._snapshot_raw or "null"
try:
log.info(
"Combining temp files into one file.",
Expand All @@ -1791,7 +1796,10 @@ def _export_as_netcdf(self, path: Path, file_name: str) -> Path:
},
)
xarray_to_h5netcdf_with_complex_numbers(
data, file_path, compute=False
data,
file_path,
compute=False,
snapshot_in_group=qcodes.config.dataset.export_netcdf_snapshot_in_group,
)
finally:
data.close()
Expand Down
10 changes: 8 additions & 2 deletions src/qcodes/dataset/data_set_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
load_to_xarray_dataset,
load_to_xarray_dataset_dict,
)
from .exporters.netcdf_snapshot import _resolve_netcdf_snapshot_raw

if TYPE_CHECKING:
from collections.abc import Mapping
Expand Down Expand Up @@ -495,17 +496,22 @@ def __init__(self, dataset: DataSetInMem, loaded_data: Path | str):

def load_data_from_db(self) -> None:
if self._data == {}:
loaded_data = self._load_xr_dataset()
# the raw data does not include the snapshot so skip reading it
loaded_data = self._load_xr_dataset(resolve_snapshot=False)
self._data = self._dataset._from_xarray_dataset_to_qcodes_raw_data(
loaded_data
)

def _load_xr_dataset(self) -> xr.Dataset:
def _load_xr_dataset(self, *, resolve_snapshot: bool = True) -> xr.Dataset:
import cf_xarray as cf_xr
import xarray as xr

loaded_data = xr.load_dataset(self._xr_dataset_path, engine="h5netcdf")
loaded_data = cf_xr.coding.decode_compress_to_multi_index(loaded_data)
if resolve_snapshot and "snapshot" in loaded_data.attrs:
loaded_data.attrs["snapshot"] = _resolve_netcdf_snapshot_raw(
self._xr_dataset_path, loaded_data.attrs["snapshot"]
)
export_info = ExportInfo.from_str(loaded_data.attrs.get("export_info", ""))
export_info.export_paths["nc"] = str(self._xr_dataset_path)
loaded_data.attrs["export_info"] = export_info.to_str()
Expand Down
8 changes: 4 additions & 4 deletions src/qcodes/dataset/data_set_in_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from .descriptions.versioning import serialization as serial
from .experiment_settings import get_default_experiment_id
from .exporters.export_info import ExportInfo
from .exporters.netcdf_snapshot import _resolve_netcdf_snapshot_raw
from .linked_datasets.links import str_to_links

if TYPE_CHECKING:
Expand Down Expand Up @@ -240,6 +241,8 @@ def _load_from_netcdf(
# reading them back results in a numpy array of one element
import xarray as xr

# h5netcdf, used to read a grouped snapshot, does not expand ``~``
path = os.path.abspath(os.path.expanduser(path))
with xr.open_dataset(path, engine="h5netcdf") as loaded_data:
parent_dataset_links = str_to_links(
loaded_data.attrs.get("parent_dataset_links", "[]")
Expand All @@ -260,9 +263,6 @@ def _load_from_netcdf(
run_id = int(loaded_data.captured_run_id)
counter = int(loaded_data.captured_counter)

path = str(path)
path = os.path.abspath(path)

export_info = ExportInfo.from_str(loaded_data.attrs.get("export_info", ""))
export_info.export_paths["nc"] = path
non_metadata = {
Expand Down Expand Up @@ -318,7 +318,7 @@ def _load_from_netcdf(
rundescriber=serial.from_json_to_current(loaded_data.run_description),
parent_dataset_links=parent_dataset_links,
export_info=export_info,
snapshot=loaded_data.snapshot,
snapshot=_resolve_netcdf_snapshot_raw(path, loaded_data.snapshot),
Comment thread
Copilot marked this conversation as resolved.
Resolved
)
ds._cache = DataSetCacheDeferred(ds, path)

Expand Down
7 changes: 6 additions & 1 deletion src/qcodes/dataset/data_set_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import numpy as np
import numpy.typing as npt

import qcodes
from qcodes.dataset.descriptions.dependencies import InterDependencies_
from qcodes.dataset.descriptions.param_spec import ParamSpec
from qcodes.dataset.export_config import (
Expand Down Expand Up @@ -432,7 +433,11 @@ def _export_as_netcdf(self, path: Path, file_name: str) -> Path:
"""Export data as netcdf to a given path with file prefix"""
file_path = path / file_name
xarr_dataset = self.to_xarray_dataset()
xarray_to_h5netcdf_with_complex_numbers(xarr_dataset, file_path)
xarray_to_h5netcdf_with_complex_numbers(
xarr_dataset,
file_path,
snapshot_in_group=qcodes.config.dataset.export_netcdf_snapshot_in_group,
)
return file_path

def _export_as_csv(self, path: Path, file_name: str) -> Path:
Expand Down
Loading
Loading