qblox_scheduler.quantify_utils#
Local copy of quantify_core utility functions to reduce dependency on quantify_core.
Attributes#
Exceptions#
Exception group used when failing to load a dataset with several NetCDF engines. |
Classes#
Time-based unique identifier (TUID) class. |
Functions#
|
Find the first place in the stack that is not inside qblox-scheduler. |
|
A decorator for deprecating classes and methods. |
|
Return a copy of a dictionary with the specified keys removed. |
|
Load a JSON schema from a file relative to a module location. |
|
Generate a time-based unique identifier (TUID). |
|
Check if an array is uniformly spaced. |
|
Cast any np.bool_ attributes to Python bool (in-place) to avoid h5netcdf errors. |
|
Write an xarray Dataset to disk. |
|
Create a snapshot of the current state. |
|
Save a dictionary to a JSON file. |
|
Convert a flattened dataset (as generated by initialize_dataset) to a gridded |
|
Add a unit aware x-label to an axis object. |
|
Add a unit aware y-label to an axis object. |
|
Return a convenient scale factor, offset and SI prefix based on the tick values. |
|
Takes in a value and unit, returns a scale factor and scaled unit. |
|
Returns a list of tuids containing a specific label. |
|
Returns the path to the experiment container of the specified tuid. |
|
|
|
Loads a dataset specified by a tuid. |
|
Loads a |
|
Convert an array of complex numbers into two arrays of real numbers. |
Reshapes the data as returned from the gettable into the form |
Module Contents#
- SI_UNITS = ['SI_PREFIX_ONLY', 'm', 's', 'g', 'W', 'J', 'V', 'A', 'F', 'T', 'Hz', 'Ohm', 'S', 'N', 'C',...[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
- 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:
strTime-based unique identifier (TUID) class.
A TUID is a string of the form “YYYYmmDD-HHMMSS-sss-**
- 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
TUIDstring. It is also possible to specify only the first part of a tuid.datadir – Path of the data directory. If
None, usesget_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
TUIDstring. It is also possible to specify only the first part of a tuid.datadir – Path of the data directory. If
None, usesget_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:
ExceptionException group used when failing to load a dataset with several NetCDF engines.
- load_dataset_from_path(path: pathlib.Path | str) xarray.Dataset[source]#
Loads a
Datasetwith 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:
"h5netcdf""netcdf4"No engine specified (
load_dataset()default)
- 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.