qblox_scheduler.quantify_utils#

Local copy of quantify_core utility functions to reduce dependency on quantify_core.

Attributes#

Exceptions#

DatasetLoadingError

Exception group used when failing to load a dataset with several NetCDF engines.

Classes#

TUID

Time-based unique identifier (TUID) class.

Functions#

_find_stack_level(→ int)

Find the first place in the stack that is not inside qblox-scheduler.

deprecated(→ collections.abc.Callable)

A decorator for deprecating classes and methods.

without(→ dict)

Return a copy of a dictionary with the specified keys removed.

load_json_schema(→ dict)

Load a JSON schema from a file relative to a module location.

gen_tuid(→ str)

Generate a time-based unique identifier (TUID).

_is_uniformly_spaced_array(→ bool)

Check if an array is uniformly spaced.

_cast_numpy_bool_attrs(→ None)

Cast any np.bool_ attributes to Python bool (in-place) to avoid h5netcdf errors.

write_dataset(→ None)

Write an xarray Dataset to disk.

snapshot(→ dict)

Create a snapshot of the current state.

save_json(→ None)

Save a dictionary to a JSON file.

to_gridded_dataset(→ xarray.Dataset)

Convert a flattened dataset (as generated by initialize_dataset) to a gridded

set_xlabel(→ matplotlib.axes.Axes)

Add a unit aware x-label to an axis object.

set_ylabel(→ matplotlib.axes.Axes | None)

Add a unit aware y-label to an axis object.

_get_scale_factor_and_offset_and_prefix(→ tuple[float, ...)

Return a convenient scale factor, offset and SI prefix based on the tick values.

SI_prefix_and_scale_factor(→ tuple[float, str])

Takes in a value and unit, returns a scale factor and scaled unit.

get_tuids_containing(→ list[TUID])

Returns a list of tuids containing a specific label.

locate_experiment_container(→ str)

Returns the path to the experiment container of the specified tuid.

_locate_experiment_file(→ str)

load_dataset(→ xarray.Dataset)

Loads a dataset specified by a tuid.

load_dataset_from_path(→ xarray.Dataset)

Loads a Dataset with a specific engine preference.

_reshape_data(→ list[numpy.typing.NDArray])

Convert an array of complex numbers into two arrays of real numbers.

_process_acquired_data(...)

Reshapes the data as returned from the gettable into the form

Module Contents#

SI_PREFIXES[source]#
SI_UNITS = ['SI_PREFIX_ONLY', 'm', 's', 'g', 'W', 'J', 'V', 'A', 'F', 'T', 'Hz', 'Ohm', 'S', 'N', 'C',...[source]#
_SI_PREFIX_TO_FACTOR_MAPPING[source]#
_prefix_regexp = '()'[source]#
_si_regex = '()'[source]#
_prefixed_si_regex[source]#
_find_stack_level() int[source]#

Find the first place in the stack that is not inside qblox-scheduler.

Returns:

: The stack level

deprecated(drop_version: str, message_or_alias: str | collections.abc.Callable) collections.abc.Callable[source]#

A decorator for deprecating classes and methods.

Parameters:
  • drop_version – A version of the package when the deprecated function or class will be dropped.

  • message_or_alias – Either an instruction about the usage of deprecated calls (string), or the new drop-in replacement to the deprecated class or function (callable).

Returns:

: The decorated function or class

without(d: dict, keys: list) dict[source]#

Return a copy of a dictionary with the specified keys removed.

Parameters:
  • d – The dictionary to copy

  • keys – List of keys to remove

Returns:

: A new dictionary without the specified keys

load_json_schema(file_location: str, filename: str) dict[source]#

Load a JSON schema from a file relative to a module location.

Parameters:
  • file_location – The location of the file (typically __file__)

  • filename – The name of the schema file

Returns:

: The loaded JSON schema as a dictionary

DATASET_NAME = 'dataset.hdf5'[source]#
PROCESSED_DATASET_NAME = 'dataset_processed.hdf5'[source]#
QUANTITIES_OF_INTEREST_NAME = 'quantities_of_interest.json'[source]#
gen_tuid() str[source]#

Generate a time-based unique identifier (TUID).

Returns:

: A TUID string of the form “YYYYmmDD-HHMMSS-sss-**

_is_uniformly_spaced_array(arr: numpy.ndarray, rtol: float = 1e-10, atol: float = 1e-10) bool[source]#

Check if an array is uniformly spaced.

Parameters:
  • arr – The array to check

  • rtol – Relative tolerance for comparison

  • atol – Absolute tolerance for comparison

Returns:

: True if the array is uniformly spaced, False otherwise

class TUID[source]#

Bases: str

Time-based unique identifier (TUID) class.

A TUID is a string of the form “YYYYmmDD-HHMMSS-sss-**

_TUID_LENGTH = 26[source]#
classmethod is_valid(tuid: str) bool[source]#

Check if a string is a valid TUID.

Parameters:

tuid – The string to check

Returns:

: True if the string is a valid TUID, False otherwise

classmethod datetime_seconds(tuid: str) datetime.datetime[source]#

Get the datetime for a TUID.

Parameters:

tuid – The TUID string

Returns:

: Datetime object

_cast_numpy_bool_attrs(dataset: xarray.Dataset) None[source]#

Cast any np.bool_ attributes to Python bool (in-place) to avoid h5netcdf errors.

write_dataset(path: str | pathlib.Path, dataset: xarray.Dataset) None[source]#

Write an xarray Dataset to disk.

Parameters:
  • path – The path to write to

  • dataset – The dataset to write

snapshot() dict[source]#

Create a snapshot of the current state.

Returns:

: A dictionary containing the snapshot

save_json(directory: str | pathlib.Path | None, filename: str, data: dict, compression: str | None = None) None[source]#

Save a dictionary to a JSON file.

Parameters:
  • directory – The directory to save to

  • filename – The filename

  • data – The data to save

  • compression – The compression type (“bz2”, “gzip”, “lzma”, or None)

to_gridded_dataset(dataset: xarray.Dataset, dimension: str = 'dim_0', coords_names: list[str] | None = None) xarray.Dataset[source]#

Convert a flattened dataset (as generated by initialize_dataset) to a gridded dataset in which the measured values are mapped onto a grid.

Parameters:
  • dataset – The input dataset in flattened format.

  • dimension – The flattened xarray Dimension.

  • coords_names – Optionally specify which Variables correspond to orthogonal coordinates. Defaults to all variables starting with “x”.

Returns:

: A gridded dataset.

set_xlabel(label: str, unit: str | None = None, axis: matplotlib.axes.Axes | None = None, auto_scale: bool = True, **kw) matplotlib.axes.Axes[source]#

Add a unit aware x-label to an axis object.

Parameters:
  • label – the desired label

  • unit – the unit

  • auto_scale – If True, then automatically scale the units

  • axis – matplotlib axis object to set label on

  • **kw – keyword argument to be passed to matplotlib.set_xlabel

set_ylabel(label: str, unit: str | None = None, axis: matplotlib.axes.Axes | None = None, auto_scale: bool = True, **kw) matplotlib.axes.Axes | None[source]#

Add a unit aware y-label to an axis object.

Parameters:
  • label – the desired label

  • unit – the unit

  • axis – matplotlib axis object to set label on

  • auto_scale – If True, then automatically scale the units

  • **kw – keyword argument to be passed to matplotlib.set_ylabel

_get_scale_factor_and_offset_and_prefix(ticks: collections.abc.Sequence[float] | numpy.ndarray, unit: str | None = None, precision: int = 4) tuple[float, float, str][source]#

Return a convenient scale factor, offset and SI prefix based on the tick values.

This function uses the SI_prefix_and_scale_factor() function to determine a scale factor such that the distance between ticks is in the range [0.1, 100.0), plus the corresponding scaled SI unit (e.g. ‘mT’, ‘kV’), deduced from the input unit, to represent the tick values in those scaled units. In addition, an offset is calculated such that the maximum absolute tick value is less than 10^precision.

Parameters:
  • ticks – A list of axis tick values.

  • unit – The unit of the tick values.

  • precision – The maximum amount of digits to display as tick labels.

Returns:

scale_factor

The scale factor to multiply the tick values with.

offset

The offset to subtract from the tick values.

unit

The unit including the SI prefix.

Examples

>>> _get_scale_factor_and_offset_and_prefix(
...     ticks=[2100000, 2100100, 2100200],
...     unit="Hz",
...     precision=4,
... )
(1.0, 2100000, 'Hz')
SI_prefix_and_scale_factor(val: float, unit: str | None = None) tuple[float, str][source]#

Takes in a value and unit, returns a scale factor and scaled unit. It returns a scale factor to convert the input value to a value in the range [1.0, 1000.0), plus the corresponding scaled SI unit (e.g. ‘mT’, ‘kV’), deduced from the input unit, to represent the input value in those scaled units.

The scaling is only applied if the unit is an unscaled or scaled unit present in the variable :data::SI_UNITS.

If the unit is None, no scaling is done. If the unit is “SI_PREFIX_ONLY”, the value is scaled and an SI prefix is applied without a base unit.

Parameters:
  • val – the value

  • unit – the unit of the value

Returns:

scale_factor

scale_factor needed to convert value

scaled_unit

unit including the prefix

get_tuids_containing(contains: str = '', t_start: datetime.datetime | str | None = None, t_stop: datetime.datetime | str | None = None, max_results: int = sys.maxsize, reverse: bool = False) list[TUID][source]#

Returns a list of tuids containing a specific label.

Tip

If one is only interested in the most recent TUID, get_latest_tuid() is preferred for performance reasons.

Parameters:
  • contains – A string contained in the experiment name.

  • t_start – datetime to search from, inclusive. If a string is specified, it will be converted to a datetime object using parse. If no value is specified, will use the year 1 as a reference t_start.

  • t_stop – datetime to search until, exclusive. If a string is specified, it will be converted to a datetime object using parse. If no value is specified, will use the current time as a reference t_stop.

  • max_results – Maximum number of results to return. Defaults to unlimited.

  • reverse – If False, sorts tuids chronologically, if True sorts by most recent.

Returns:

list A list of TUID: objects.

Raises:

FileNotFoundError – No data found.

locate_experiment_container(tuid: TUID, datadir: pathlib.Path | str | None = None) str[source]#

Returns the path to the experiment container of the specified tuid.

Parameters:
  • tuid – A TUID string. It is also possible to specify only the first part of a tuid.

  • datadir – Path of the data directory. If None, uses get_datadir() to determine the data directory.

Returns:

: The path to the experiment container

Raises:

FileNotFoundError – Experiment container not found.

_locate_experiment_file(tuid: TUID, datadir: pathlib.Path | str | None = None, name: str = DATASET_NAME) str[source]#
load_dataset(tuid: TUID, datadir: pathlib.Path | str | None = None, name: str = DATASET_NAME) xarray.Dataset[source]#

Loads a dataset specified by a tuid.

Tip

This method also works when specifying only the first part of a TUID.

Note

This method uses load_dataset() to ensure the file is closed after loading as datasets are intended to be immutable after performing the initial experiment.

Parameters:
  • tuid – A TUID string. It is also possible to specify only the first part of a tuid.

  • datadir – Path of the data directory. If None, uses get_datadir() to determine the data directory.

  • name – Name of the dataset.

Returns:

: The dataset.

Raises:

FileNotFoundError – No data found for specified date.

exception DatasetLoadingError(errors: list[Exception])[source]#

Bases: Exception

Exception group used when failing to load a dataset with several NetCDF engines.

errors[source]#
load_dataset_from_path(path: pathlib.Path | str) xarray.Dataset[source]#

Loads a Dataset with a specific engine preference.

Before returning the dataset AdapterH5NetCDF.recover() is applied.

This function tries to load the dataset until success with the following engine preference:

Parameters:

path – Path to the dataset.

Returns:

: The loaded dataset.

_reshape_data(acq_protocol: str, vals: numpy.typing.NDArray[numpy.complexfloating], real_imag: bool) list[numpy.typing.NDArray][source]#

Convert an array of complex numbers into two arrays of real numbers.

_process_acquired_data(acquired_data: xarray.Dataset, batched: bool, real_imag: bool) tuple[numpy.typing.NDArray[numpy.float64], ...][source]#

Reshapes the data as returned from the gettable into the form accepted by the measurement control.

Parameters:
  • acquired_data – Data that is returned by gettable.

  • batched – Parameter to distinct iterative and batched experiment.

  • real_imag – If true, the gettable returns I, Q values. Otherwise, magnitude and phase

  • returned. ((degrees) are)

Returns:

: A tuple of data, casted to a historical conventions on data format.