Note

This is the documentation for the current state of the development branch of Qiskit Experiments. The documentation or APIs here can change prior to being released.

IQPlotter

class IQPlotter(drawer)[source]

A plotter class to plot IQ data.

IQPlotter plots results from experiments which used measurement-level 1, i.e. IQ data. This class also supports plotting predictions from a discriminator (subclass of BaseDiscriminator), which is used to classify IQ results into labels. The discriminator labels are matched with the series names to generate an image of the predictions. Points that are misclassified by the discriminator are flagged in the figure (see the flag_misclassified option). A canonical application of IQPlotter is for classification of single-qubit readout for different prepared states.

Example

# Create plotter
plotter = IQPlotter(MplDrawer())

# Iterate over results, one per prepared state. Add points and centroid to
# plotter and set label for prepared states as |n> where n is the
# prepared-state number.
series_params = {}
for res in results:
    # Get IQ points from result memory.
    points = res.memory

    # Compute centroid as mean of all points.
    centroid = np.mean(points, axis=1)

    # Get ``prep``, which is part of the result metadata.
    prep = res.prep

    # Create label as a ket instead of just a state number (i.e., prep).
    series_params[prep] = {
        "label":f"|{prep}>",
    }

    plotter.set_series_data(prep, points=points, centroid=centroid)
plotter.set_figure_options(series_params=series_params)
...
# Optional: Add trained discriminator.
discrim = MyIQDiscriminator()
# Discriminator labels are the same as series names.
discrim.fit(train_data, train_labels)
plotter.set_supplementary_data(discriminator=discrim)
...
# Plot figure.
fig = plotter.figure()

Options

The following can be set using set_options().

Options
  • Defined in the class IQPlotter:

    • plot_discriminator (bool)

      Default value: True
      Whether to plot an image showing the predictions of the discriminator entry in supplementary_data. If True, the “discriminator” supplementary data entry must be set.
    • discriminator_multiplier (float)

      Default value: 1.1
      The multiplier to use when computing the extent of the discriminator plot. The range of the series data is taken as the base value and multiplied by discriminator_extent_multiplier to compute the extent of the discriminator predictions. Defaults to 1.1.
    • discriminator_aspect_ratio (float)

      Default value: 1.0
      The aspect ratio of the extent of the discriminator predictions, being width/height. Defaults to 1 for a square region.
    • discriminator_max_resolution (int)

      Default value: 1024
      The number of pixels to use for the largest edge of the discriminator extent, used when sampling the discriminator to create the prediction image. Defaults to 1024.
    • discriminator_alpha (float)

      Default value: 0.2
      The transparency of the discriminator prediction image. Defaults to 0.2 (i.e., 20%).
    • discriminator_extent (Optional[ExtentTuple])

      Default value: None
      An optional tuple defining the extent of the image created by sampling from the discriminator. If None, the extent tuple is computed using discriminator_multiplier, discriminator_aspect_ratio, and the series-data points and centroid. Defaults to None.
    • flag_misclassified (bool)

      Default value: True
      Whether to mark misclassified IQ values from all points series data, based on whether their series name is not the same as the prediction from the discriminator provided as supplementary data. If discriminator is not provided, flag_misclassified has no effect. Defaults to True.
    • misclassified_symbol (str)

      Default value: "x"
      Symbol for misclassified points, as a drawer-compatible string. Defaults to “x”.
    • misclassified_color (str | tuple)

      Default value: "r"
      Color for misclassified points, as a drawer-compatible string or RGB tuple. Defaults to “r”.
  • Defined in the class BasePlotter:

    • axis (Any)

      Default value: None
      Arbitrary object that can be used as a drawing canvas.
    • subplots (Tuple[int, int])

      Default value: (1, 1)
      Number of rows and columns when the experimental result is drawn in the multiple windows.
    • style (PlotStyle)

      Default value: {}
      The style definition to use when plotting. This overwrites figure option custom_style set in drawer. The default is an empty style object, and such the default drawer plotting style will be used.

Figure options

The following can be set using set_figure_options().

Options
  • Defined in the class BasePlotter:

    • xlabel (Union[str, List[str]])

      Default value: "In-Phase"
      X-axis label string of the output figure. If there are multiple columns in the canvas, this could be a list of labels.
    • ylabel (Union[str, List[str]])

      Default value: "Quadrature"
      Y-axis label string of the output figure. If there are multiple rows in the canvas, this could be a list of labels.
    • xlim (Union[Tuple[float, float], List[Tuple[float, float]])

      Default value: None
      Min and max value of the horizontal axis. If not provided, it is automatically scaled based on the input data points. If there are multiple columns in the canvas, this could be a list of xlims.
    • ylim (Union[Tuple[float, float], List[Tuple[float, float]])

      Default value: None
      Min and max value of the vertical axis. If not provided, it is automatically scaled based on the input data points. If there are multiple rows in the canvas, this could be a list of ylims.
    • xval_unit (Union[str, List[str]])

      Default value: "arb."
      Unit of x values. No scaling prefix is needed here as this is controlled by xval_unit_scale. If there are multiple columns in the canvas, this could be a list of xval_units.
    • yval_unit (Union[str, List[str]])

      Default value: "arb."
      Unit of y values. No scaling prefix is needed here as this is controlled by yval_unit_scale. If there are multiple rows in the canvas, this could be a list of yval_units.
    • xval_unit_scale (Union[bool, List[bool]])

      Default value: False
      Whether to add an SI unit prefix to xval_unit if needed. For example, when the x values represent time and xval_unit="s", xval_unit_scale=True adds an SI unit prefix to "s" based on X values of plotted data. In the output figure, the prefix is automatically selected based on the maximum value in this axis. If your x values are in [1e-3, 1e-4], they are displayed as [1 ms, 10 ms]. By default, this option is set to True. If False is provided, the axis numbers will be displayed in the scientific notation. If there are multiple columns in the canvas, this could be a list of xval_unit_scale.
    • yval_unit_scale (Union[bool, List[bool]])

      Default value: False
      Whether to add an SI unit prefix to yval_unit if needed. See xval_unit_scale for details. If there are multiple rows in the canvas, this could be a list of yval_unit_scale.
    • xscale (str)

      Default value: None
      The scaling of the x-axis, such as log or linear.
    • yscale (str)

      Default value: None
      The scaling of the y-axis, such as log or linear.
    • figure_title (str)

      Default value: None
      Title of the figure. Defaults to None, i.e. nothing is shown.
    • sharex (bool)

      Default value: True
      Set True to share x-axis ticks among sub-plots.
    • sharey (bool)

      Default value: True
      Set True to share y-axis ticks among sub-plots.
    • series_params (Dict[str, Dict[str, Any]])

      Default value: {}
      A dictionary of parameters for each series. This is keyed on the name for each series. Sub-dictionary is expected to have the following three configurations, “canvas”, “color”, “symbol” and “label”; “canvas” is the integer index of axis (when multi-canvas plot is set), “color” is the color of the drawn graphics, “symbol” is the series marker style for scatter plots, and “label” is a user provided series label that appears in the legend.

Initialization

Create a new plotter instance.

Parameters:

drawer (BaseDrawer) – The drawer to use when creating the figure.

Attributes

figure_options

Figure options for the plotter and its drawer.

Figure options differ from normal options (options) in that the plotter passes figure options on to the drawer when creating a figure (when figure() is called). This way drawer can draw an appropriate figure. An example of a figure option is the x-axis label.

options

Options for the plotter.

Options for a plotter modify how the class generates a figure. This includes an optional axis object, being the drawer canvas. Make sure verify whether the option you want to set is in options or figure_options.

series

Series names that have been added to this plotter.

series_data

Data for series being plotted.

Series data includes data such as scatter points, interpolated fit values, and standard deviations. Series data is grouped by series name (Union[str, int, float]) and then by a data key (str). Though series data can be accessed through series_data, it is recommended to access them with data_for() and data_exists_for() as they allow for easier access to nested values and can handle multiple data keys in one query.

Returns:

A dictionary containing series data.

supplementary_data

Additional data for the figure being plotted, that isn’t associated with a series.

Supplementary data includes text, fit reports, or other data that is associated with the figure but not an individual series. It is typically data additional to the direct results of an experiment.

Methods

clear_series_data(series_name=None)

Clear series data for this plotter.

Parameters:

series_name (str | int | float | None) – The series name identifying which data should be cleared. If None, all series data is cleared. Defaults to None.

clear_supplementary_data()

Clears supplementary data.

config()

Return the config dictionary for this drawing.

Return type:

Dict

data_exists_for(series_name, data_keys)

Returns whether the given data keys exist for the given series.

Parameters:
  • series_name (str | int | float) – The name of the given series.

  • data_keys (str | List[str]) – The data keys to be checked.

Returns:

True if all data keys have values assigned for the given series. False if at least one does not have a value assigned.

Return type:

bool

data_for(series_name, data_keys)

Returns data associated with the given series.

The returned tuple contains the data, associated with data_keys, in the same orders as they are provided. For example,

plotter.set_series_data("seriesA", x=data.x, y=data.y, yerr=data.yerr)

# The following calls are equivalent.
x, y, yerr = plotter.data_for("seriesA", ["x", "y", "yerr"])
x, y, yerr = data.x, data.y, data.yerr

# Retrieving a single data key returns a tuple. Note the comma after ``x``.
x, = plotter.data_for("seriesA", "x")

data_for() is intended to be used by sub-classes of BasePlotter when plotting in the _plot_figure() method.

Parameters:
  • series_name (str | int | float) – The series name for the given series.

  • data_keys (str | List[str]) – List of data keys for the data to be returned. If a single data key is given as a string, it is wrapped in a list.

Returns:

A tuple of data associated with the given series, identified by data_keys. If no data has been set for a data key, None is returned for the associated tuple entry.

Return type:

Tuple[Any | None]

data_keys_for(series_name)

Returns a list of data keys for the given series.

Parameters:

series_name (str | int | float) – The series name for which to return the data keys, i.e., the types of data for each series.

Returns:

The list of data keys for data in the plotter associated with the given series. If the series has not been added to the plotter, an empty list is returned.

Return type:

List[str]

classmethod expected_series_data_keys()[source]

Returns the expected series data keys supported by this plotter.

Data Keys:
  • points – Single-shot IQ data.

  • centroid – Averaged IQ data.

Return type:

List[str]

classmethod expected_supplementary_data_keys()[source]

Returns the expected figures data keys supported by this plotter.

Data Keys:
  • discriminator – A trained discriminator that classifies IQ points. If provided, the predictions of the discriminator will be sampled to generate a background image, indicating the regions for each predicted outcome. The predictions are assumed to be series names (Union[str, int, float]). The generated image allows viewers to see how well the discriminator classifies the provided series data. Must be a subclass of BaseDiscriminator. See options for ways to control the generation of the discriminator prediction image.

  • fidelity – A float representing the fidelity of the discrimination.

Return type:

List[str]

figure()

Generates and returns a figure for the already provided series and supplementary data.

figure() calls _plot_figure(), which is overridden by sub-classes. Before and after calling _plot_figure(); _configure_drawer(), initialize_canvas() and format_canvas() are called on the drawer respectively.

Returns:

A figure generated by drawer, of the same type as drawer.figure.

Return type:

Any

set_figure_options(**fields)

Set the figure options.

Parameters:

fields – The fields to update in figure options.

set_options(**fields)

Set the plotter options.

Parameters:

fields – The fields to update in options.

Raises:

AttributeError – If an unknown option is encountered.

set_series_data(series_name, **data_kwargs)

Sets data for the given series.

Note that if data has already been assigned for the given series and data key, it will be overwritten with the new values. set_series_data will warn if the data key is unexpected; i.e., not within those returned by expected_series_data_keys().

Parameters:
  • series_name (str | int | float) – The name of the given series.

  • data_kwargs – The data to be added, where the keyword is the data key.

set_supplementary_data(**data_kwargs)

Sets supplementary data for the plotter.

Supplementary data differs from series data in that it is not associate with a series name. Fit reports are examples of supplementary data as they contain fit results from an analysis class, such as the “goodness” of a curve fit.

Note that if data has already been assigned for the given data key, it will be overwritten with the new values. set_supplementary_data will warn if the data key is unexpected; i.e., not within those returned by expected_supplementary_data_keys().