Skip to content

Read data

extract_h5_data(path, keys=None, get_metadata=False)

Extract data at the given keys from an HDF5 file. If no keys are given (None) returns the data field of the object.

Parameters:

Name Type Description Default
path str

path to the HDF5 file or a folder in which is contained a data.ddh5 file

required
keys None or List

list of keys to extract from file['data'], by default None

None
get_metadata bool

whether or not to extract also metadata, like database schema and qubit IDs, by default None.

False

Returns:

Type Description
Dict or Tuple[ndarray, ...]

The full data dictionary if keys = None. The tuple with the requested keys otherwise.

Example
Extract the data object from the dataset:
>>> data = extract_h5_data(path)
Extracting only 'amp' and 'phase' from the dataset:
>>> amp, phase = extract_h5_data(path, ['amp', 'phase'])
Extracting only 'phase':
>>> phase, = extract_h5_data(path, ['phase'])
Source code in sqil_core/utils/_read.py
def extract_h5_data(
    path: str, keys: list[str] | None = None, get_metadata=False
) -> dict | tuple[np.ndarray, ...]:
    """Extract data at the given keys from an HDF5 file. If no keys are
    given (None) returns the data field of the object.

    Parameters
    ----------
    path : str
        path to the HDF5 file or a folder in which is contained a data.ddh5 file
    keys : None or List, optional
        list of keys to extract from file['data'], by default None
    get_metadata : bool, optional
        whether or not to extract also metadata, like database schema and qubit IDs,
        by default None.

    Returns
    -------
    Dict or Tuple[np.ndarray, ...]
        The full data dictionary if keys = None.
        The tuple with the requested keys otherwise.

    Example
    -------
        Extract the data object from the dataset:
        >>> data = extract_h5_data(path)
        Extracting only 'amp' and 'phase' from the dataset:
        >>> amp, phase = extract_h5_data(path, ['amp', 'phase'])
        Extracting only 'phase':
        >>> phase, = extract_h5_data(path, ['phase'])
    """
    # If the path is to a folder open /data.ddh5
    if os.path.isdir(path):
        path = os.path.join(path, "data.ddh5")

    with h5py.File(path, "r") as h5file:
        data = h5file["data"]
        data_keys = data.keys()

        metadata = {}
        if get_metadata:
            metadata["schema"] = json.loads(data.attrs.get("__schema__", "null"))
            metadata["qu_ids"] = json.loads(data.attrs.get("__qu_ids__", "null"))
            metadata["params"] = json.loads(data.attrs.get("__params__", "null"))

        # Extract only the requested keys
        if bool(keys) and (len(keys) > 0):
            res = []
            for key in keys:
                key = str(key)
                if (not bool(key)) | (key not in data_keys):
                    res.append([])
                    continue
                res.append(np.array(data[key][:]))
            if not get_metadata and len(res) == 1:
                return res[0]
            return tuple(res) if not get_metadata else (*tuple(res), metadata)
        # Extract the whole data dictionary
        h5_dict = _h5_to_dict(data)
        return h5_dict if not get_metadata else {**h5_dict, "metadata": metadata}

read_json(path)

Reads a json file and returns the data as a dictionary.

Source code in sqil_core/utils/_read.py
def read_json(path: str) -> dict:
    """Reads a json file and returns the data as a dictionary."""
    with open(path) as f:
        dictionary = json.load(f)
    return dictionary

read_qpu(dir_path, filename)

Reads QPU file stored in dir_path/filename using laboneq serializers.

Source code in sqil_core/utils/_read.py
def read_qpu(dir_path: str, filename: str) -> QPU:
    """Reads QPU file stored in dir_path/filename using laboneq serializers."""
    qpu = serializers.load(os.path.join(dir_path, filename))
    return qpu