def _format_plot(centers: List[complex],
                     ax: Optional["matplotlib.pyplot.AxesSubplot"] = None):
        """Format the readout_angle plot

        Args:
            centers: the two centers of the level 1 measurements for 0 and for 1.
            ax: matplotlib axis to add plot to.

        Returns:
            AxesSubPlot: the matplotlib axes containing the plot.
        """
        largest_extent = (np.max([
            np.max(np.abs(np.real(centers))),
            np.max(np.abs(np.imag(centers)))
        ]) * 1.1)

        ax = get_non_gui_ax()
        ax.plot(np.real(centers[0]), np.imag(centers[0]), "ro", markersize=24)
        ax.plot(np.real(centers[1]), np.imag(centers[1]), "bo", markersize=24)
        ax.set_xlim([-largest_extent, largest_extent])
        ax.set_ylim([-largest_extent, largest_extent])
        ax.set_xlabel("I [arb.]")
        ax.set_ylabel("Q [arb.]")
        ax.set_title("Centroid Positions")
        ax.legend(["0", "1"])
        return ax
예제 #2
0
    def _plot_calibration(self,
                          matrix,
                          labels,
                          ax=None) -> "matplotlib.figure.Figure":
        """
        Plot the calibration matrix (2D color grid plot).

        Args:
            matrix: calibration matrix to plot
            ax (matplotlib.axes): settings for the graph

        Returns:
            The generated plot of the calibration matrix

        Raises:
            QiskitError: if _cal_matrices was not set.

            ImportError: if matplotlib was not installed.

        """

        if ax is None:
            ax = get_non_gui_ax()
        figure = ax.get_figure()
        ax.matshow(matrix, cmap=plt.cm.binary, clim=[0, 1])
        ax.set_xlabel("Prepared State")
        ax.xaxis.set_label_position("top")
        ax.set_ylabel("Measured State")
        ax.set_xticks(np.arange(len(labels)))
        ax.set_yticks(np.arange(len(labels)))
        ax.set_xticklabels(labels)
        ax.set_yticklabels(labels)
        return figure
예제 #3
0
 def callback1(exp_data):
     """Callback function that call add_analysis_callback"""
     exp_data.add_analysis_callback(callback2)
     result = DbAnalysisResult("result_name", 0, [Qubit(0)], "experiment_id")
     exp_data.add_analysis_results(result)
     figure = get_non_gui_ax().get_figure()
     exp_data.add_figures(figure, "figure.svg")
     exp_data.add_data({"key": 1.2})
     exp_data.data()
예제 #4
0
def assignment_matrix_visualization(assignment_matrix, ax=None):
    """Displays a visualization of the assignment matrix compared to the identity"""
    if ax is None:
        ax = get_non_gui_ax()
    figure = ax.get_figure()
    n = len(assignment_matrix)
    diff = np.abs(assignment_matrix - np.eye(n))
    im2 = ax.matshow(diff, cmap=plt.cm.Reds, vmin=0, vmax=0.2)
    ax.set_yticks(np.arange(n))
    ax.set_xticks(np.arange(n))
    ax.set_yticklabels(n * [""])
    ax.set_xticklabels(n * [""])
    ax.set_xlabel(r"$|A - I|$", fontsize=16)
    figure.colorbar(im2, ax=ax)
    return figure
예제 #5
0
def plot_errorbar(
    xdata: np.ndarray,
    ydata: np.ndarray,
    sigma: Optional[np.ndarray] = None,
    ax=None,
    labelsize: int = 14,
    grid: bool = True,
    **kwargs,
):
    """Generate an errorbar plot of xy data.

    Wraps :func:`matplotlib.pyplot.errorbar`

    Args:
        xdata: xdata used for fitting
        ydata: ydata used for fitting
        sigma: Optional, standard deviation of ydata
        ax (matplotlib.axes.Axes): Optional, a matplotlib axes to add the plot to.
        labelsize: label size for plot
        grid: Show grid on plot.
        **kwargs: Additional options for :func:`matplotlib.pyplot.errorbar`

    Returns:
        matplotlib.axes.Axes: the matplotlib axes containing the plot.
    """
    if ax is None:
        ax = get_non_gui_ax()

    # Default plot options
    plot_opts = kwargs.copy()
    if "color" not in plot_opts:
        plot_opts["color"] = "red"
    if "marker" not in plot_opts:
        plot_opts["marker"] = "."
    if "markersize" not in plot_opts:
        plot_opts["markersize"] = 9
    if "linestyle" not in plot_opts:
        plot_opts["linestyle"] = "None"

    # Plot data
    ax.errorbar(xdata, ydata, yerr=sigma, **plot_opts)

    # Formatting
    ax.tick_params(labelsize=labelsize)
    ax.grid(grid)
    return ax
예제 #6
0
def plot_scatter(
    xdata: np.ndarray,
    ydata: np.ndarray,
    ax=None,
    labelsize: int = 14,
    grid: bool = True,
    **kwargs,
):
    """Generate a scatter plot of xy data.

    Wraps :func:`matplotlib.pyplot.scatter`.

    Args:
        xdata: xdata used for fitting
        ydata: ydata used for fitting
        ax (matplotlib.axes.Axes): Optional, a matplotlib axes to add the plot to.
        labelsize: label size for plot
        grid: Show grid on plot.
        **kwargs: Additional options for :func:`matplotlib.pyplot.scatter`

    Returns:
        matplotlib.axes.Axes: the matplotlib axes containing the plot.
    """
    if ax is None:
        ax = get_non_gui_ax()

    # Default plot options
    plot_opts = kwargs.copy()
    if "c" not in plot_opts:
        plot_opts["c"] = "grey"
    if "marker" not in plot_opts:
        plot_opts["marker"] = "x"
    if "alpha" not in plot_opts:
        plot_opts["alpha"] = 0.8

    # Plot data
    ax.scatter(xdata, ydata, **plot_opts)

    # Formatting
    ax.tick_params(labelsize=labelsize)
    ax.grid(grid)
    return ax
    def _run_analysis(
        self, experiment_data: ExperimentData
    ) -> Tuple[List[AnalysisResultData], List["pyplot.Figure"]]:
        """Wrap the analysis to optionally plot the IQ data."""
        analysis_results, figures = super()._run_analysis(experiment_data)

        if self.options.plot_iq_data:
            axis = get_non_gui_ax()
            figure = axis.get_figure()
            figure.set_size_inches(*self.options.style.figsize)

            iqs = []

            for datum in experiment_data.data():
                if "memory" in datum:
                    mem = np.array(datum["memory"])

                    # Average single-shot data.
                    if len(mem.shape) == 3:
                        for idx in range(mem.shape[1]):
                            iqs.append(np.average(mem[:, idx, :], axis=0))
                    else:
                        iqs.append(mem)

            if len(iqs) > 0:
                iqs = np.vstack(iqs)
                axis.scatter(iqs[:, 0], iqs[:, 1], color="b")
                axis.set_xlabel("In phase [arb. units]",
                                fontsize=self.options.style.axis_label_size)
                axis.set_ylabel("Quadrature [arb. units]",
                                fontsize=self.options.style.axis_label_size)
                axis.tick_params(labelsize=self.options.style.tick_label_size)
                axis.grid(True)

                figures.append(figure)

        return analysis_results, figures
예제 #8
0
    def draw(
        cls,
        series_defs: List[SeriesDef],
        raw_samples: List[CurveData],
        fit_samples: List[CurveData],
        tick_labels: Dict[str, str],
        fit_data: FitData,
        result_entries: List[AnalysisResultData],
        style: Optional[PlotterStyle] = None,
        axis: Optional["matplotlib.axes.Axes"] = None,
    ) -> "pyplot.Figure":
        """Create a fit result of all curves in the single canvas.

        Args:
            series_defs: List of definition for each curve.
            raw_samples: List of raw sample data for each curve.
            fit_samples: List of formatted sample data for each curve.
            tick_labels: Dictionary of axis label information. Axis units and label for x and y
                value should be explained.
            fit_data: fit data generated by the analysis.
            result_entries: List of analysis result data entries.
            style: Optional. A configuration object to modify the appearance of the figure.
            axis: Optional. A matplotlib Axis object.

        Returns:
            A matplotlib figure of the curve fit result.
        """
        if axis is None:
            axis = get_non_gui_ax()

            # update image size to experiment default
            figure = axis.get_figure()
            figure.set_size_inches(*style.figsize)
        else:
            figure = axis.get_figure()

        # draw all curves on the same canvas
        for series_def, raw_samp, fit_samp in zip(series_defs, raw_samples,
                                                  fit_samples):
            draw_single_curve_mpl(
                axis=axis,
                series_def=series_def,
                raw_sample=raw_samp,
                fit_sample=fit_samp,
                fit_data=fit_data,
                style=style,
            )

        # add legend
        if len(series_defs) > 1:
            axis.legend(loc=style.legend_loc)

        # get axis scaling factor
        for this_axis in ("x", "y"):
            sub_axis = getattr(axis, this_axis + "axis")
            unit = tick_labels[this_axis + "val_unit"]
            label = tick_labels[this_axis + "label"]
            if unit:
                maxv = np.max(np.abs(sub_axis.get_data_interval()))
                scaled_maxv, prefix = detach_prefix(maxv, decimal=3)
                prefactor = scaled_maxv / maxv
                # pylint: disable=cell-var-from-loop
                sub_axis.set_major_formatter(
                    FuncFormatter(lambda x, p: f"{x * prefactor: .3g}"))
                sub_axis.set_label_text(f"{label} [{prefix}{unit}]",
                                        fontsize=style.axis_label_size)
            else:
                sub_axis.set_label_text(label, fontsize=style.axis_label_size)
                axis.ticklabel_format(axis=this_axis,
                                      style="sci",
                                      scilimits=(-3, 3))

        if tick_labels["xlim"]:
            axis.set_xlim(tick_labels["xlim"])

        if tick_labels["ylim"]:
            axis.set_ylim(tick_labels["ylim"])

        # write analysis report
        if fit_data:
            report_str = write_fit_report(result_entries)
            report_str += r"Fit $\chi^2$ = " + f"{fit_data.reduced_chisq: .4g}"

            report_handler = axis.text(
                *style.fit_report_rpos,
                report_str,
                ha="center",
                va="top",
                size=style.fit_report_text_size,
                transform=axis.transAxes,
            )

            bbox_props = dict(boxstyle="square, pad=0.3",
                              fc="white",
                              ec="black",
                              lw=1,
                              alpha=0.8)
            report_handler.set_bbox(bbox_props)

        axis.tick_params(labelsize=style.tick_label_size)
        axis.grid(True)

        return figure
예제 #9
0
    def draw(
        cls,
        series_defs: List[SeriesDef],
        raw_samples: List[CurveData],
        fit_samples: List[CurveData],
        tick_labels: Dict[str, str],
        fit_data: FitData,
        result_entries: List[AnalysisResultData],
        style: Optional[PlotterStyle] = None,
        axis: Optional["matplotlib.axes.Axes"] = None,
    ) -> "pyplot.Figure":
        """Create a fit result of all curves in the single canvas.

        Args:
            series_defs: List of definition for each curve.
            raw_samples: List of raw sample data for each curve.
            fit_samples: List of formatted sample data for each curve.
            tick_labels: Dictionary of axis label information. Axis units and label for x and y
                value should be explained.
            fit_data: fit data generated by the analysis.
            result_entries: List of analysis result data entries.
            style: Optional. A configuration object to modify the appearance of the figure.
            axis: Optional. A matplotlib Axis object.

        Returns:
            A matplotlib figure of the curve fit result.
        """
        if axis is None:
            axis = get_non_gui_ax()

            # update image size to experiment default
            figure = axis.get_figure()
            figure.set_size_inches(*style.figsize)
        else:
            figure = axis.get_figure()

        # get canvas number
        n_subplots = max(series_def.canvas for series_def in series_defs) + 1

        # use inset axis. this allows us to draw multiple canvases on a given single axis object
        inset_ax_h = (1 - (0.05 * (n_subplots - 1))) / n_subplots
        inset_axes = [
            axis.inset_axes(
                [
                    0, 1 -
                    (inset_ax_h + 0.05) * n_axis - inset_ax_h, 1, inset_ax_h
                ],
                transform=axis.transAxes,
                zorder=1,
            ) for n_axis in range(n_subplots)
        ]

        # show x label only in the bottom canvas
        for inset_axis in inset_axes[:-1]:
            inset_axis.set_xticklabels([])
        inset_axes[-1].get_shared_x_axes().join(*inset_axes)

        # remove original axis frames
        axis.spines.right.set_visible(False)
        axis.spines.left.set_visible(False)
        axis.spines.top.set_visible(False)
        axis.spines.bottom.set_visible(False)
        axis.set_xticks([])
        axis.set_yticks([])

        # collect data source per canvas
        plot_map = defaultdict(list)
        for curve_ind, series_def in enumerate(series_defs):
            plot_map[series_def.canvas].append(curve_ind)

        y_labels = tick_labels["ylabel"].split(",")
        if len(y_labels) == 1:
            y_labels = y_labels * n_subplots

        for ax_ind, curve_inds in plot_map.items():
            inset_axis = inset_axes[ax_ind]

            for curve_ind in curve_inds:
                draw_single_curve_mpl(
                    axis=inset_axis,
                    series_def=series_defs[curve_ind],
                    raw_sample=raw_samples[curve_ind],
                    fit_sample=fit_samples[curve_ind],
                    fit_data=fit_data,
                    style=style,
                )

            # add legend to each inset axis
            if len(curve_inds) > 1:
                inset_axis.legend(loc=style.legend_loc)

            # format y axis tick value of each inset axis
            yaxis = getattr(inset_axis, "yaxis")
            unit = tick_labels["yval_unit"]
            label = y_labels[ax_ind]
            if unit:
                maxv = np.max(np.abs(yaxis.get_data_interval()))
                scaled_maxv, prefix = detach_prefix(maxv, decimal=3)
                prefactor = scaled_maxv / maxv
                # pylint: disable=cell-var-from-loop
                yaxis.set_major_formatter(
                    FuncFormatter(lambda x, p: f"{x * prefactor: .3g}"))
                yaxis.set_label_text(f"{label} [{prefix}{unit}]",
                                     fontsize=style.axis_label_size)
            else:
                inset_axis.ticklabel_format(axis="y",
                                            style="sci",
                                            scilimits=(-3, 3))
                yaxis.set_label_text(label, fontsize=style.axis_label_size)

            if tick_labels["ylim"]:
                inset_axis.set_ylim(tick_labels["ylim"])

        # format x axis
        xaxis = getattr(inset_axes[-1], "xaxis")
        unit = tick_labels["xval_unit"]
        label = tick_labels["xlabel"]
        if unit:
            maxv = np.max(np.abs(xaxis.get_data_interval()))
            scaled_maxv, prefix = detach_prefix(maxv, decimal=3)
            prefactor = scaled_maxv / maxv
            # pylint: disable=cell-var-from-loop
            xaxis.set_major_formatter(
                FuncFormatter(lambda x, p: f"{x * prefactor: .3g}"))
            xaxis.set_label_text(f"{label} [{prefix}{unit}]",
                                 fontsize=style.axis_label_size)
        else:
            axis.ticklabel_format(axis="x", style="sci", scilimits=(-3, 3))
            xaxis.set_label_text(label, fontsize=style.axis_label_size)

        if tick_labels["xlim"]:
            inset_axes[-1].set_xlim(tick_labels["xlim"])

        # write analysis report
        if fit_data:
            report_str = write_fit_report(result_entries)
            report_str += r"Fit $\chi^2$ = " + f"{fit_data.reduced_chisq: .4g}"

            report_handler = axis.text(
                *style.fit_report_rpos,
                report_str,
                ha="center",
                va="top",
                size=style.fit_report_text_size,
                transform=axis.transAxes,
            )

            bbox_props = dict(boxstyle="square, pad=0.3",
                              fc="white",
                              ec="black",
                              lw=1,
                              alpha=0.8)
            report_handler.set_bbox(bbox_props)

        axis.tick_params(labelsize=style.tick_label_size)
        axis.grid(True)

        return figure
예제 #10
0
def plot_curve_fit(
    func: Callable,
    result: FitData,
    fit_uncertainty: bool = False,
    ax=None,
    num_fit_points: int = 100,
    labelsize: int = 14,
    grid: bool = True,
    **kwargs,
):
    """Generate plot of a curve fit analysis result.

    Wraps :func:`matplotlib.pyplot.plot`.

    Args:
        func: the fit function for curve_fit.
        result: a fitting data set.
        fit_uncertainty: if True plot the fit uncertainty from popt_err.
        ax (matplotlib.axes.Axes): Optional, a matplotlib axes to add the plot to.
        num_fit_points: the number of points to plot for xrange.
        labelsize: label size for plot
        grid: Show grid on plot.
        **kwargs: Additional options for matplotlib.pyplot.plot

    Returns:
        matplotlib.axes.Axes: the matplotlib axes containing the plot.

    Raises:
        ImportError: if matplotlib is not installed.
    """
    if ax is None:
        ax = get_non_gui_ax()

    # Default plot options
    plot_opts = kwargs.copy()
    if "color" not in plot_opts:
        plot_opts["color"] = "blue"
    if "linestyle" not in plot_opts:
        plot_opts["linestyle"] = "-"
    if "linewidth" not in plot_opts:
        plot_opts["linewidth"] = 2

    # Result data
    fit_params = result.popt
    param_keys = result.popt_keys
    fit_errors = result.popt_err
    xmin, xmax = result.x_range

    # Plot fit data
    xs = np.linspace(xmin, xmax, num_fit_points)
    if param_keys:
        ys_fit = func(xs, **dict(zip(param_keys, fit_params)))
    else:
        ys_fit = func(xs, *fit_params)
    ax.plot(xs, ys_fit, **plot_opts)

    # Plot standard error interval
    if fit_uncertainty and fit_errors is not None:
        if param_keys:
            params_upper = {}
            params_lower = {}
            for key, param, error in zip(param_keys, fit_params, fit_errors):
                params_upper[key] = param + error
                params_lower[key] = param - error
            ys_upper = func(xs, **params_upper)
            ys_lower = func(xs, **params_lower)
        else:
            params_upper = [
                param + error for param, error in zip(fit_params, fit_errors)
            ]
            params_lower = [
                param - error for param, error in zip(fit_params, fit_errors)
            ]
            ys_upper = func(xs, *params_upper)
            ys_lower = func(xs, *params_lower)
        ax.fill_between(xs,
                        ys_lower,
                        ys_upper,
                        alpha=0.1,
                        color=plot_opts["color"])

    # Formatting
    ax.tick_params(labelsize=labelsize)
    ax.grid(grid)
    return ax
예제 #11
0
def plot_curve_fit(
    func: Callable,
    result: FitData,
    ax=None,
    num_fit_points: int = 100,
    labelsize: int = 14,
    grid: bool = True,
    fit_uncertainty: List[Tuple[float, float]] = None,
    **kwargs,
):
    """Generate plot of a curve fit analysis result.

    Wraps :func:`matplotlib.pyplot.plot`.

    Args:
        func: the fit function for curve_fit.
        result: a fitting data set.
        ax (matplotlib.axes.Axes): Optional, a matplotlib axes to add the plot to.
        num_fit_points: the number of points to plot for xrange.
        labelsize: label size for plot
        grid: Show grid on plot.
        fit_uncertainty: a list of sigma values to plot confidence interval of fit line.
        **kwargs: Additional options for matplotlib.pyplot.plot

    Returns:
        matplotlib.axes.Axes: the matplotlib axes containing the plot.

    Raises:
        ImportError: if matplotlib is not installed.
    """
    if ax is None:
        ax = get_non_gui_ax()

    if fit_uncertainty is None:
        fit_uncertainty = list()
    elif isinstance(fit_uncertainty, tuple):
        fit_uncertainty = [fit_uncertainty]

    # Default plot options
    plot_opts = kwargs.copy()
    if "color" not in plot_opts:
        plot_opts["color"] = "blue"
    if "linestyle" not in plot_opts:
        plot_opts["linestyle"] = "-"
    if "linewidth" not in plot_opts:
        plot_opts["linewidth"] = 2

    xmin, xmax = result.x_range

    # Plot fit data
    xs = np.linspace(xmin, xmax, num_fit_points)
    ys_fit_with_error = func(xs, **dict(zip(result.popt_keys, result.popt)))

    # Line
    ax.plot(xs, unp.nominal_values(ys_fit_with_error), **plot_opts)

    # Confidence interval of N sigma values
    stdev_arr = unp.std_devs(ys_fit_with_error)
    if np.isfinite(stdev_arr).all():
        for sigma, alpha in fit_uncertainty:
            ax.fill_between(
                xs,
                y1=unp.nominal_values(ys_fit_with_error) - sigma * stdev_arr,
                y2=unp.nominal_values(ys_fit_with_error) + sigma * stdev_arr,
                alpha=alpha,
                color=plot_opts["color"],
            )

    # Formatting
    ax.tick_params(labelsize=labelsize)
    ax.grid(grid)
    return ax
예제 #12
0
    def initialize_canvas(self):
        # Create axis if empty
        if not self.options.axis:
            axis = get_non_gui_ax()
            figure = axis.get_figure()
            figure.set_size_inches(*self.options.figsize)
        else:
            axis = self.options.axis

        n_rows, n_cols = self.options.subplots
        n_subplots = n_cols * n_rows
        if n_subplots > 1:
            # Add inset axis. User may provide a single axis object via the analysis option,
            # while this analysis tries to draw its result in multiple canvases,
            # especially when the analysis consists of multiple curves.
            # Inset axis is experimental implementation of matplotlib 3.0 so maybe unstable API.
            # This draws inset axes with shared x and y axis.
            inset_ax_h = 1 / n_rows
            inset_ax_w = 1 / n_cols
            for i in range(n_rows):
                for j in range(n_cols):
                    # x0, y0, width, height
                    bounds = [
                        inset_ax_w * j,
                        1 - inset_ax_h * (i + 1),
                        inset_ax_w,
                        inset_ax_h,
                    ]
                    sub_ax = axis.inset_axes(bounds,
                                             transform=axis.transAxes,
                                             zorder=1)
                    if j != 0:
                        # remove y axis except for most-left plot
                        sub_ax.set_yticklabels([])
                    else:
                        # this axis locates at left, write y-label
                        if self.options.ylabel:
                            label = self.options.ylabel
                            if isinstance(label, list):
                                # Y label can be given as a list for each sub axis
                                label = label[i]
                            sub_ax.set_ylabel(
                                label, fontsize=self.options.axis_label_size)
                    if i != n_rows - 1:
                        # remove x axis except for most-bottom plot
                        sub_ax.set_xticklabels([])
                    else:
                        # this axis locates at bottom, write x-label
                        if self.options.xlabel:
                            label = self.options.xlabel
                            if isinstance(label, list):
                                # X label can be given as a list for each sub axis
                                label = label[j]
                            sub_ax.set_xlabel(
                                label, fontsize=self.options.axis_label_size)
                    if j == 0 or i == n_rows - 1:
                        # Set label size for outer axes where labels are drawn
                        sub_ax.tick_params(
                            labelsize=self.options.tick_label_size)
                    sub_ax.grid()

            # Remove original axis frames
            axis.axis("off")
        else:
            axis.set_xlabel(self.options.xlabel,
                            fontsize=self.options.axis_label_size)
            axis.set_ylabel(self.options.ylabel,
                            fontsize=self.options.axis_label_size)
            axis.tick_params(labelsize=self.options.tick_label_size)
            axis.grid()

        self._axis = axis