Beispiel #1
0
    def qiskit_backend_monitor(self, line='', cell=None):  # pylint: disable=W0613
        """A Jupyter magic function to monitor backends.
        """
        backend = self.shell.user_ns[line]
        if not isinstance(backend, IBMQBackend):
            raise QISKitError('Input variable is not of type IBMQBackend.')
        title_style = "style='color:#ffffff;background-color:#000000;padding-top: 1%;"
        title_style += "padding-bottom: 1%;padding-left: 1%; margin-top: 0px'"
        title_html = "<h1 {style}>{name}</h1>".format(
            style=title_style, name=backend.name())

        details = [config_tab(backend)]

        tab_contents = ['Configuration']

        if not backend.configuration().simulator:
            tab_contents.extend(['Qubit Properties', 'Multi-Qubit Gates',
                                 'Error Map', 'Job History'])
            details.extend([qubits_tab(backend), gates_tab(backend),
                            detailed_map(backend), job_history(backend)])

        tabs = widgets.Tab(layout=widgets.Layout(overflow_y='scroll'))
        tabs.children = details
        for i in range(len(details)):
            tabs.set_title(i, tab_contents[i])

        title_widget = widgets.HTML(value=title_html,
                                    layout=widgets.Layout(margin='0px 0px 0px 0px'))

        backend_monitor = widgets.VBox([title_widget, tabs],
                                       layout=widgets.Layout(border='4px solid #000000',
                                                             max_height='650px', min_height='650px',
                                                             overflow_y='hidden'))

        display(backend_monitor)
def get_unique_backends():
    """Gets the unique backends that are available.

    Returns:
        list: Unique available backends.

    Raises:
        QISKitError: No backends available.
    """
    backends = IBMQ.backends()
    unique_hardware_backends = []
    unique_names = []
    for back in backends:
        if back.name(
        ) not in unique_names and not back.configuration().simulator:
            unique_hardware_backends.append(back)
            unique_names.append(back.name())
    if not unique_hardware_backends:
        raise QISKitError('No backends available.')
    return unique_hardware_backends
def backend_monitor(backend):
    """Monitor a single IBMQ backend.

    Args:
        backend (IBMQBackend): Backend to monitor.
    Raises:
        QISKitError: Input is not a IBMQ backend.
    """
    if not isinstance(backend, IBMQBackend):
        raise QISKitError('Input variable is not of type IBMQBackend.')
    config = backend.configuration().to_dict()
    status = backend.status().to_dict()
    config_dict = {**status, **config}
    if not config['simulator']:
        props = backend.properties().to_dict()

    print(backend.name())
    print('=' * len(backend.name()))
    print('Configuration')
    print('-' * 13)
    offset = '    '

    upper_list = [
        'n_qubits', 'operational', 'status_msg', 'pending_jobs', 'basis_gates',
        'local', 'simulator'
    ]

    lower_list = list(set(config_dict.keys()).difference(upper_list))
    # Remove gates because they are in a different tab
    lower_list.remove('gates')
    for item in upper_list + lower_list:
        print(offset + item + ':', config_dict[item])

    # Stop here if simulator
    if config['simulator']:
        return

    print()
    qubit_header = 'Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]'
    print(qubit_header)
    print('-' * len(qubit_header))

    sep = ' / '
    for qub in range(len(props['qubits'])):
        name = 'Q%s' % qub
        qubit_data = props['qubits'][qub]
        gate_data = props['gates'][3 * qub:3 * qub + 3]
        t1_info = qubit_data[0]
        t2_info = qubit_data[1]
        freq_info = qubit_data[2]
        readout_info = qubit_data[3]

        freq = str(round(freq_info['value'], 5)) + ' ' + freq_info['unit']
        T1 = str(round(
            t1_info['value'],  # pylint: disable=invalid-name
            5)) + ' ' + t1_info['unit']
        T2 = str(round(
            t2_info['value'],  # pylint: disable=invalid-name
            5)) + ' ' + t2_info['unit']
        # pylint: disable=invalid-name
        U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))

        readout_error = str(round(readout_info['value'], 5))

        qstr = sep.join([name, freq, T1, T2, U1, U2, U3, readout_error])
        print(offset + qstr)

    print()
    multi_qubit_gates = props['gates'][3 * config['n_qubits']:]
    multi_header = 'Multi-Qubit Gates [Name / Type / Gate Error]'
    print(multi_header)
    print('-' * len(multi_header))

    for gate in multi_qubit_gates:
        name = gate['name']
        ttype = gate['gate']
        error = str(round(gate['parameters'][0]['value'], 5))
        mstr = sep.join([name, ttype, error])
        print(offset + mstr)
Beispiel #4
0
def plot_gate_map(backend,
                  figsize=None,
                  plot_directed=False,
                  label_qubits=True,
                  qubit_size=24,
                  line_width=4,
                  font_size=12,
                  qubit_color=None,
                  line_color=None,
                  font_color='w'):
    """Plots the gate map of a device.

    Args:
        backend (BaseBackend): A backend instance,
        figsize (tuple): Output figure size (wxh) in inches.
        plot_directed (bool): Plot directed coupling map.
        label_qubits (bool): Label the qubits.
        qubit_size (float): Size of qubit marker.
        line_width (float): Width of lines.
        font_size (int): Font size of qubit labels.
        qubit_color (list): A list of colors for the qubits
        line_color (list): A list of colors for each line from coupling_map.
        font_color (str): The font color for the qubit labels.

    Returns:
        Figure: A Matplotlib figure instance.

    Raises:
        QISKitError: Tried to pass a simulator.
    """
    if backend.configuration().simulator:
        raise QISKitError('Requires a device backend, not simulator.')

    mpl_data = {}

    mpl_data['ibmq_20_tokyo'] = [[0, 0], [0, 1], [0, 2], [0, 3], [0,
                                                                  4], [1, 0],
                                 [1, 1], [1, 2], [1, 3], [1, 4], [2,
                                                                  0], [2, 1],
                                 [2, 2], [2, 3], [2, 4], [3, 0], [3, 1],
                                 [3, 2], [3, 3], [3, 4]]

    mpl_data['ibmq_poughkeepsie'] = mpl_data['ibmq_20_tokyo']

    mpl_data['ibmq_16_melbourne'] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],
                                     [0, 5], [0, 6], [1, 7], [1, 6], [1, 5],
                                     [1, 4], [1, 3], [1, 2], [1, 1]]

    mpl_data['ibmq_16_rueschlikon'] = [[1, 0], [0, 0], [0, 1], [0, 2], [0, 3],
                                       [0, 4], [0, 5], [0, 6], [0, 7], [1, 7],
                                       [1, 6], [1, 5], [1, 4], [1, 3], [1, 2],
                                       [1, 1]]

    mpl_data['ibmq_5_tenerife'] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]

    mpl_data['ibmq_5_yorktown'] = mpl_data['ibmq_5_tenerife']

    config = backend.configuration()
    name = config.backend_name
    cmap = config.coupling_map

    dep_names = {
        'ibmqx5': 'ibmq_16_rueschlikon',
        'ibmqx4': 'ibmq_5_tenerife',
        'ibmqx2': 'ibmq_5_yorktown'
    }

    if name in dep_names.keys():
        name = dep_names[name]

    if name in mpl_data.keys():
        grid_data = mpl_data[name]
    else:
        fig, ax = plt.subplots(figsize=(5, 5))  # pylint: disable=invalid-name
        ax.axis('off')
        return fig

    x_max = max([d[1] for d in grid_data])
    y_max = max([d[0] for d in grid_data])
    max_dim = max(x_max, y_max)

    if figsize is None:
        if x_max / max_dim > 0.33 and y_max / max_dim > 0.33:
            figsize = (5, 5)
        else:
            figsize = (9, 3)

    fig, ax = plt.subplots(figsize=figsize)  # pylint: disable=invalid-name
    ax.axis('off')
    fig.tight_layout()

    # set coloring
    if qubit_color is None:
        qubit_color = ['#648fff'] * config.n_qubits
    if line_color is None:
        line_color = ['#648fff'] * len(cmap)

    # Add lines for couplings
    for ind, edge in enumerate(cmap):
        is_symmetric = False
        if edge[::-1] in cmap:
            is_symmetric = True
        y_start = grid_data[edge[0]][0]
        x_start = grid_data[edge[0]][1]
        y_end = grid_data[edge[1]][0]
        x_end = grid_data[edge[1]][1]

        if is_symmetric:
            if y_start == y_end:
                x_end = (x_end - x_start) / 2 + x_start

            elif x_start == x_end:
                y_end = (y_end - y_start) / 2 + y_start

            else:
                x_end = (x_end - x_start) / 2 + x_start
                y_end = (y_end - y_start) / 2 + y_start
        ax.add_artist(
            plt.Line2D([x_start, x_end], [-y_start, -y_end],
                       color=line_color[ind],
                       linewidth=line_width,
                       zorder=0))
        if plot_directed:
            dx = x_end - x_start  # pylint: disable=invalid-name
            dy = y_end - y_start  # pylint: disable=invalid-name
            if is_symmetric:
                x_arrow = x_start + dx * 0.95
                y_arrow = -y_start - dy * 0.95
                dx_arrow = dx * 0.01
                dy_arrow = -dy * 0.01
                head_width = 0.15
            else:
                x_arrow = x_start + dx * 0.5
                y_arrow = -y_start - dy * 0.5
                dx_arrow = dx * 0.2
                dy_arrow = -dy * 0.2
                head_width = 0.2
            ax.add_patch(
                mpatches.FancyArrow(x_arrow,
                                    y_arrow,
                                    dx_arrow,
                                    dy_arrow,
                                    head_width=head_width,
                                    length_includes_head=True,
                                    edgecolor=None,
                                    linewidth=0,
                                    facecolor=line_color[ind],
                                    zorder=1))

    # Add circles for qubits
    for var, idx in enumerate(grid_data):
        _idx = [idx[1], -idx[0]]
        width = _GraphDist(qubit_size, ax, True)
        height = _GraphDist(qubit_size, ax, False)
        ax.add_artist(
            mpatches.Ellipse(_idx,
                             width,
                             height,
                             color=qubit_color[var],
                             zorder=1))
        if label_qubits:
            ax.text(*_idx,
                    s=str(var),
                    horizontalalignment='center',
                    verticalalignment='center',
                    color=font_color,
                    size=font_size,
                    weight='bold')
    ax.set_xlim([-1, x_max + 1])
    ax.set_ylim([-(y_max + 1), 1])
    plt.close(fig)
    return fig