quantify_core.visualization#

The visualization module contains tools for real-time visualization as well as utilities to help in plotting.

Import alias

Maps to

quantify_core.visualization.InstrumentMonitor

InstrumentMonitor

quantify_core.visualization.PlotMonitor_pyqt

PlotMonitor_pyqt

instrument_monitor#

Module containing the pyqtgraph based plotting monitor.

class InstrumentMonitor(name, window_size=(600, 600), remote=True, update_interval=5)[source]#

Creates a pyqtgraph widget that displays the instrument monitor window.

Parameters:
  • name – name of the InstrumentMonitor object.

  • window_size (tuple (default: (600, 600))) – The size of the InstrumentMonitor window in px.

  • remote (bool (default: True)) – Switch to use a remote instance of the pyqtgraph class.

  • update_interval (int (default: 5)) – Interval in seconds between two updates

_update()[source]#

Updates the Qc widget with the current snapshot of the instruments.

Return type:

None

close()[source]#

(Modified from Instrument class)

Irreversibly stop this instrument and free its resources.

Subclasses should override this if they have other specific resources to close.

Return type:

None

create_widget(window_size=(1000, 600))[source]#

Saves an instance of the quantify_core.visualization.ins_mon_widget.qc_snapshot_widget.QcSnapshotWidget class during startup. Creates the snapshot tree to display within the remote widget window.

Parameters:

window_size (tuple (default: (1000, 600))) – The size of the InstrumentMonitor window in px.

setGeometry(x, y, w, h)[source]#

Set the geometry of the main widget window

Parameters:
  • x (int) – Horizontal position of the top-left corner of the window.

  • y (int) – Vertical position of the top-left corner of the window.

  • w (int) – Width of the window.

  • h (int) – Height of the window.

update_interval = Parameter( get_cmd=self._get_update_interval, set_cmd=self._set_update_interval, unit="s", initial_value=update_interval, vals=vals.Numbers(min_value=0.001), name="update_interval", instrument=self, )#

Only update the window if this amount of time has passed since the last update.

update_snapshot = ManualParameter( initial_value=False, vals=vals.Bool(), name="update_snapshot", instrument=self, )#

Set to True in order to query the instruments about each parameter before updating the window. Can be slow due to communication overhead.

class RepeatTimer(interval, function, args=None, kwargs=None)[source]#
cancel()[source]#

Stop the timer (and exit the loop/thread).

pause()[source]#

Pause the timer, i.e. do not execute the function, but stay in the loop/thread.

run()[source]#

Function called in separate thread after calling .start() on the instance.

unpause()[source]#

Unpause the timer, i.e. execute the function in the loop again.

pyqt_plotmon#

Module containing the pyqtgraph based plotting monitor.

class PlotMonitor_pyqt(name)[source]#

Pyqtgraph based plot monitor instrument.

A plot monitor is intended to provide a real-time visualization of a dataset.

The interaction with this virtual instrument are virtually instantaneous. All the heavier computations and plotting happens in a separate QtProcess.

__init__(name)[source]#

Creates an instance of the Measurement Control.

Parameters:

name (str) – Name of this instrument instance

close()[source]#

(Modified from Instrument class)

Irreversibly stop this instrument and free its resources.

Subclasses should override this if they have other specific resources to close.

Return type:

None

create_plot_monitor()[source]#

Creates the PyQtGraph plotting monitors. Can also be used to recreate these when plotting has crashed.

setGeometry_main(x, y, w, h)[source]#

Set the geometry of the main plotmon

Parameters:
  • x (int) – Horizontal position of the top-left corner of the window

  • y (int) – Vertical position of the top-left corner of the window

  • w (int) – Width of the window

  • h (int) – Height of the window

setGeometry_secondary(x, y, w, h)[source]#

Set the geometry of the secondary plotmon

Parameters:
  • x (int) – Horizontal position of the top-left corner of the window

  • y (int) – Vertical position of the top-left corner of the window

  • w (int) – Width of the window

  • h (int) – Height of the window

tuids_append(tuid=None)[source]#

Appends a tuid to tuids and also discards older datasets according to tuids_max_num.

The the corresponding data will be plotted in the main window with blue circles.

NB: do not call before the corresponding dataset file was created and filled with data

update(tuid=None)[source]#

Updates the curves/heatmaps of a specific dataset.

If the dataset is not specified the latest dataset in tuids is used.

If tuids is empty and tuid is provided then tuids_append(tuid) will be called. NB: this is intended mainly for MC to avoid issues when the file was not yet created or is empty.

main_QtPlot = QtPlotObjForJupyter(self._remote_plotmon, "main_QtPlot")#

Retrieves the image of the main window when used as the final statement in a cell of a Jupyter-like notebook.

secondary_QtPlot = QtPlotObjForJupyter( self._remote_plotmon, "secondary_QtPlot" )#

Retrieves the image of the secondary window when used as the final statement in a cell of a Jupyter-like notebook.

tuids = Parameter( initial_cache_value=[], vals=vals.Lists(elt_validator=vals.Strings()), get_cmd=self._get_tuids, set_cmd=self._set_tuids, name="tuids", instrument=self, )#

The tuids of the auto-accumulated previous datasets when specified through tuids_append. Can be set to a list ['tuid_one', 'tuid_two', ...]. Can be reset by setting to []. See also tuids_extra.

tuids_extra = Parameter( initial_cache_value=[], vals=vals.Lists(elt_validator=vals.Strings()), set_cmd=self._set_tuids_extra, get_cmd=self._get_tuids_extra, name="tuids_extra", instrument=self, )#

Extra tuids whose datasets are never affected by tuids_append or tuids_max_num. As opposed to the tuids, these ones never vanish. Can be reset by setting to []. Intended to perform realtime measurements and have a live comparison with previously measured datasets.

tuids_max_num = Parameter( vals=vals.Ints(min_value=1, max_value=100), set_cmd=self._set_tuids_max_num, get_cmd=self._get_tuids_max_num, initial_cache_value=3, name="tuids_max_num", instrument=self, )#

The maximum number of auto-accumulated datasets in tuids. Older dataset are discarded when tuids_append is called [directly or from update()].

class QtPlotObjForJupyter(remote_plotmon, attr_name)[source]#

A wrapper to be able to display a QtPlot window in Jupyter notebooks

color_utilities#

Module containing utilities for color manipulation

set_hlsa(color, h=None, l=None, s=None, a=None, to_hex=False)[source]#

Create an RGB(A) color specification from HLS(A) values.

Accepts a Matplotlib HLS(A) color specification (hue/lightness/saturation and optionally alpha value) and returns an RGB (red/green/blue) color with the specified HLS(A) values.

Parameters:
  • h (float | None (default: None)) – The value of the first hue.

  • l (float | None (default: None)) – The lightness value.

  • s (float | None (default: None)) – The saturation intensity.

  • a (float | None (default: None)) – Alpha bending value

  • to_hex (bool (default: False)) – If True, returns integers in 0..255 interval, otherwise floats in 0..1 range.

Return type:

tuple

Returns:

: Color RGB(A)

mpl_plotting#

Module containing matplotlib and xarray plotting utilities.

Naming convention: plotting functions that require Xarray object(s) as inputs are named plot_xr_....

flex_colormesh_plot_vs_xy(xvals, yvals, zvals, ax=None, normalize=False, log=False, cmap='viridis', vlim=(None, None), transpose=False)[source]#

Add a rectangular block to a color plot using pcolormesh().

Parameters:
  • xvals (np.ndarray) – Length N array corresponding to settable x0.

  • yvals (np.ndarray) – Length M array corresponding to settable x1.

  • zvals (np.ndarray) – M*N array corresponding to gettable yi.

  • ax (Axes | None (default: None)) – Axis to which to add the colormesh.

  • normalize (bool (default: False)) – If True, normalizes each row of data.

  • log (bool (default: False)) – if True, uses a logarithmic colorscale.

  • cmap (str (default: 'viridis')) – Colormap to use. See matplotlib docs for choosing an appropriate colormap.

  • vlim (tuple (default: (None, None))) – Limits of the z-axis.

  • transpose (bool (default: False)) – If True transposes the figure.

Return type:

QuadMesh

Returns:

: The created matplotlib QuadMesh.

Warning

The grid orientation for the zvals is the same as is used in pcolormesh(). Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. This can be counter.intuitive: zvals(y_idx, x_idx) and can be inconsistent with some arrays of zvals (such as a 2D histogram from numpy).

get_unit_from_attrs(data_array, str_format=' [{}]')[source]#

Extracts and formats the unit/units from an xarray.DataArray attribute.

Parameters:
  • data_array (DataArray) – Xarray array (coordinate or variable).

  • str_format (str (default: ' [{}]')) – String that will be formatted if a unit is found.

Return type:

str

Returns:

: str_format string formatted with the data_array.unit or data_array.units, with that order of precedence. Empty string is returned if none of these arguments are present.

plot_2d_grid(x, y, z, xlabel, xunit, ylabel, yunit, zlabel, zunit, ax, cax=None, add_cbar=True, title=None, normalize=False, log=False, cmap='viridis', vlim=(None, None), transpose=False)[source]#

Creates a heatmap of x,y,z data that was acquired on a grid expects three “columns” of data of equal length.

Parameters:
  • x – Length N array corresponding to x values.

  • y – Length N array corresponding to y values.

  • z – Length N array corresponding to gettable z values.

  • xlabel (str) – x label to add to the heatmap.

  • ylabel (str) – y label to add to the heatmap.

  • xunit (str) – x unit used in unit aware axis labels.

  • yunit (str) – y unit used in unit aware axis labels.

  • zlabel (str) – Label used for the colorbar.

  • ax (Axes) – Axis to which to add the colormesh.

  • cax (Axes | None (default: None)) – Axis on which to add the colorbar, if set to None, will create a new axis.

  • add_cbar (bool (default: True)) – if True, adds a colorbar.

  • title (str | None (default: None)) – Text to add as title to the axis.

  • normalize (bool (default: False)) – if True, normalizes each row of data.

  • log (bool (default: False)) – if True, uses a logarithmic colorscale

  • cmap (str (default: 'viridis')) –

    The colormap to use. See matplotlib docs for choosing an appropriate colormap.

  • vlim (tuple (default: (None, None))) – limits of the z-axis.

  • transpose (bool (default: False)) – if True transposes the figure.

Return type:

tuple[QuadMesh, Colorbar | None]

Returns:

: The new matplotlib QuadMesh and Colorbar.

plot_complex_points(points, colors=None, labels=None, markers=None, legend=True, ax=None, **kwargs)[source]#

Plots complex points with (by default) different colors and markers on the imaginary plane using matplotlib.axes.Axes.plot().

Intended for a small number of points.

Example

from quantify_core.utilities.examples_support import plot_centroids

_ = plot_centroids([1 + 1j, -1.5 - 2j])

Parameters:
  • ax (Axes | None (default: None)) – A matplotlib axis to plot on.

  • points (list | NDArray) – Array of complex numbers.

  • colors (list | None (default: None)) – Colors to use for each point.

  • labels (list | None (default: None)) – Labels to use for each point. Defaults to f"|{i}>"

  • markers (list | None (default: None)) – Markers to use for each point.

  • legend (bool (default: True)) – Calls legend() if True.

  • **kwargs – Keyword arguments passed to the plot().

Return type:

tuple[Figure, Axes]

plot_fit(ax, fit_res, plot_init=True, plot_numpoints=1000, range_casting='real', fit_kwargs=None, init_kwargs=None)[source]#

Plot a fit of an lmfit model with a real domain.

Parameters:
  • ax – axis on which to plot the fit.

  • fit_res – an lmfit fit results object.

  • plot_init (bool (default: True)) – if True, plot the initial guess of the fit.

  • plot_numpoints (int (default: 1000)) – the number of points used on which to evaluate the fit.

  • range_casting (Literal[‘abs’, ‘angle’, ‘real’, ‘imag’] (default: 'real')) – how to plot fit functions that have a complex range. Casting of values happens using absolute, angle, real and imag. Angle is in degrees.

  • fit_kwargs (dict | None (default: None)) – Matplotlib pyplot formatting and label keyword arguments for the fit plot. default value is {“color”: “C3”, “label”: “Fit”}

  • optional – Matplotlib pyplot formatting and label keyword arguments for the fit plot. default value is {“color”: “C3”, “label”: “Fit”}

  • init_kwargs (dict | None (default: None)) – Matplotlib pyplot formatting and label keyword arguments for the init plot. default value is {“color”: “grey”, “linestyle”: “–”, “label”: “Guess”}

  • optional – Matplotlib pyplot formatting and label keyword arguments for the init plot. default value is {“color”: “grey”, “linestyle”: “–”, “label”: “Guess”}

Return type:

list[plt.Line2D]

Returns:

: list of matplotlib pyplot Line2D objects

plot_fit_complex_plane(ax, fit_res, plot_init=True, plot_numpoints=1000)[source]#

Plot a fit of an lmfit model with a real domain in the complex plane.

Return type:

None

plot_textbox(ax, text, **kw)[source]#

Plot a textbox with sensible defaults using text.

Parameters:
  • ax (Axes) – The Axes on which to plot.

  • text (str) – The text of the textbox.

Return type:

Text

Returns:

: the new text object

plot_xr_complex(var, marker_scatter='o', label_real='Real', label_imag='Imag', cmap='viridis', c=None, kwargs_line=None, kwargs_scatter=None, title='{} [{}]; shape = {}', legend=True, ax=None)[source]#

Plots the real and imaginary parts of complex data. Points are colored by default according to their order in the array.

Parameters:
  • var (xr.DataArray) – 1D array of complex data.

  • marker_scatter (str (default: 'o')) – Marker used for the scatter plot.

  • label_real (str (default: 'Real')) – Label for legend.

  • label_imag (str (default: 'Imag')) – Label for legend.

  • cmap (str (default: 'viridis')) – The colormap to use for coloring the points.

  • c (np.ndarray | None (default: None)) – Color of the points. Defaults to an array of integers.

  • kwargs_line (dict | None (default: None)) – Keyword arguments passed to matplotlib.axes.Axes.plot().

  • kwargs_scatter (dict | None (default: None)) – Keyword arguments passed to matplotlib.axes.Axes.scatter().

  • title (str (default: '{} [{}]; shape = {}')) – Axes title. By default gets formatted with var.long_name, var.name and var.shape``.

  • legend (bool (default: True)) – Calls legend() if True.

  • ax (object (default: None)) – The matplotlib axes. If None a new axes (and figure) is created.

Return type:

tuple[Figure, Axes]

plot_xr_complex_on_plane(var, marker='o', label='Data on imaginary plane', cmap='viridis', c=None, xlabel='Real{}{}{}', ylabel='Imag{}{}{}', legend=True, ax=None, **kwargs)[source]#

Plots complex data on the imaginary plane. Points are colored by default according to their order in the array.

Parameters:
  • var (xr.DataArray) – 1D array of complex data.

  • marker (str (default: 'o')) – Marker used for the scatter plot.

  • label (str (default: 'Data on imaginary plane')) – Data label for the legend.

  • cmap (str (default: 'viridis')) – The colormap to use for coloring the points.

  • c (np.ndarray | None (default: None)) – Color of the points. Defaults to an array of integers.

  • xlabel (str (default: 'Real{}{}{}')) – Label o x axes.

  • ylabel (str (default: 'Imag{}{}{}')) – Label o y axes.

  • legend (bool (default: True)) – Calls legend() if True.

  • ax (object (default: None)) – The matplotlib axes. If None a new axes (and figure) is created.

Return type:

tuple[Figure, Axes]

set_cyclic_colormap(image_or_collection, shifted=False, unit='deg', clim=None)[source]#

Sets a cyclic colormap on a matplolib 2D color plot if cyclic units are detected.

Parameters:
  • image_or_collection (AxesImage | QuadMesh | Collection) – A matplotlib object returned by either one of pcolor(), pcolormesh(), imshow() or matshow().

  • shifted (bool (default: False)) – Chooses between "twilight_shifted"/"twilight" colormap and the colormap range.

  • unit (Literal[‘deg’, ‘rad’] (default: 'deg')) – Used to fix the colormap range.

  • clim (tuple | None (default: None)) – The colormap limit.

Return type:

None

set_suptitle_from_dataset(fig, dataset, prefix='')[source]#

Sets the suptitle of a matplotlib figure based on

  • (optional) prefix;

  • dataset.name;

  • dataset.tuid,

Intended for tagging figures with unique ID of the original dataset.

Parameters:
  • prefix (str (default: '')) – Optional string to pre-pend, e.g., x0-y0.

  • fig (Figure) – The matplotlib figure.

  • dataset (Dataset) – A dataset expected to have a .name and a .tuid" attributes.

Return type:

None

plot_interpolation#

Plot interpolations.

interpolate_heatmap(x, y, z, n=None, interp_method='linear')[source]#

The output of this method can directly be used for plt.imshow(z_grid, extent=extent, aspect=’auto’) where the extent is determined by the min and max of the x_grid and y_grid.

The output can also be used as input for ax.pcolormesh(x, y, Z,**kw)

Parameters:
  • x (numpy.ndarray) – x data points

  • y (numpy.ndarray) – y data points

  • z (numpy.ndarray) – z data points

  • n (Optional[int] (default: None)) – number of points for each dimension on the interpolated grid if set to None will auto determine amount of points needed

  • interp_method (Literal['linear', 'nearest', 'deg'] (default: 'linear')) – determines what interpolation method is used.

Returns:

x_gridnumpy.ndarray

N*1 array of x-values of the interpolated grid

y_gridnumpy.ndarray

N*1 array of x-values of the interpolated grid

z_gridnumpy.ndarray

N*N array of z-values that form a grid.

SI_utilities#

Utilities for managing SI units with plotting systems.

class SafeFormatter(missing='~~', bad_fmt='!!')[source]#

A formatter that replaces “missing” values and “bad_fmt” to prevent unexpected Exceptions being raised.

Parameters:
  • missing (str (default: '~~')) – Replaces missing values with specified string.

  • bad_fmt (str (default: '!!')) – Replaces values that cannot be formatted with specified string.

Notes

Based on https://stackoverflow.com/questions/20248355/how-to-get-python-to-gracefully-format-none-and-non-existing-fields

SI_prefix_and_scale_factor(val, unit=None)[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 (float) – the value

  • unit (str | None (default: None)) – the unit of the value

Return type:

tuple[float, str]

Returns:

scale_factor

scale_factor needed to convert value

scaled_unit

unit including the prefix

SI_val_to_msg_str(val, unit=None, return_type=<class 'str'>)[source]#

Takes in a value with optional unit and returns a string tuple consisting of (value_str, unit) where the value and unit are rescaled according to SI prefixes, IF the unit is an SI unit (according to the comprehensive list of SI units in this file ;).

the value_str is of the type specified in return_type (str) by default.

_get_scale_factor_and_offset_and_prefix(ticks, unit=None, precision=4)[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 (list[float]) – A list of axis tick values.

  • unit (str | None (default: None)) – The unit of the tick values.

  • precision (int (default: 4)) – The maximum amount of digits to display as tick labels.

Return type:

tuple[float, float, str]

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')
_set_offset_string(formatter, offset, unit)[source]#

Set the offset string of the Formatter to a conveniently scaled offset.

This function scales the given offset and unit using SI_prefix_and_scale_factor(), and sets the offset string of the Formatter to the scaled offset value.

Parameters:
  • formatter (Formatter) – The matplotlib Formatter.

  • offset (float) – The value to scale and display.

  • unit (str) – The unit of the value.

Return type:

None

adjust_axeslabels_SI(ax)[source]#

Auto adjust the labels of a plot generated by xarray to SI-unit aware labels.

Return type:

None

format_value_string(par_name, parameter, end_char='', unit=None)[source]#

Format an lmfit parameter or uncertainties ufloat to a string of value with uncertainty.

If there is no stderr, use 5 significant figures. If there is a standard error use a precision one order of magnitude more precise than the size of the error and display the stderr itself to two significant figures in standard index notation in the same units as the value.

Parameters:
  • par_name (str) – A name of the parameter to use in the string

  • parameter (lmfit.parameter.Parameter,) – uncertainties.core.Variable or float. A Parameter object or an object e.g., returned by uncertainties.ufloat(). The value and stderr of this parameter will be used. If a float is given, the stderr is taken to be None.

  • end_char (default: '') – A character that will be put at the end of the line.

  • unit (default: None) – A unit. If this is an SI unit it will be used in automatically determining a prefix for the unit and rescaling accordingly.

Return type:

str

Returns:

: The parameter and its error formatted as a string

set_cbarlabel(cbar, label, unit=None, **kw)[source]#

Add a unit aware z-label to a colorbar object.

Parameters:
  • cbar (matplotlib.colorbar.Colorbar) – colorbar object to set label on

  • label (str) – the desired label

  • unit (str | None (default: None)) – the unit

  • **kw – keyword argument to be passed to cbar.set_label

set_xlabel(label, unit=None, axis=None, auto_scale=True, **kw)[source]#

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

Parameters:
  • label (str | plt.Axes) – the desired label

  • unit (str | None (default: None)) – the unit

  • auto_scale (bool (default: True)) – If True, then automatically scale the units

  • axis (plt.Axes | None (default: None)) – matplotlib axis object to set label on

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

Return type:

plt.Axes

set_ylabel(label, unit=None, axis=None, auto_scale=True, **kw)[source]#

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

Parameters:
  • label (str | plt.Axes) – the desired label

  • unit (str | None (default: None)) – the unit

  • axis (plt.Axes | None (default: None)) – matplotlib axis object to set label on

  • auto_scale (bool (default: True)) – If True, then automatically scale the units

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

Return type:

plt.Axes | None

value_precision(val, stderr=None)[source]#

Calculate the precision to which a parameter is to be specified, according to its standard error. Returns the appropriate format specifier string.

If there is no stderr, use 5 significant figures. If there is a standard error use a precision one order of magnitude more precise than the size of the error and display the stderr itself to two significant figures in standard index notation in the same units as the value.

Parameters:
  • val (float) – the nominal value of the parameter

  • stderr (default: None) – the standard error on the parameter

Return type:

tuple[str, str]

Returns:

val_format_specifierstr

python format specifier which sets the precision of the parameter value

err_format_specifierstr

python format specifier which set the precision of the error