Beispiel #1
0
 def test_plot_gate_map(self, backend):
     """ tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)"""
     n = backend.configuration().n_qubits
     img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png")
     filename = "temp.png"
     fig = plot_gate_map(backend)
     fig.savefig(filename)
     self.assertImagesAreEqual(filename, img_ref, 0.2)
     os.remove(filename)
 def test_plot_gate_map(self, backend):
     """tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)"""
     n = backend.configuration().n_qubits
     img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png")
     fig = plot_gate_map(backend)
     with BytesIO() as img_buffer:
         fig.savefig(img_buffer, format="png")
         img_buffer.seek(0)
         self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
     plt.close(fig)
Beispiel #3
0
def backend_widget(backend):
    """Creates a backend widget.
    """
    config = backend.configuration().to_dict()
    props = backend.properties().to_dict()

    name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
                        layout=widgets.Layout())

    num_qubits = config['n_qubits']

    qv_val = '-'
    if 'quantum_volume' in config.keys():
        if config['quantum_volume']:
            qv_val = config['quantum_volume']

    qubit_count = widgets.HTML(
        value="<h5><b>{qubits}</b></h5>".format(qubits=num_qubits),
        layout=widgets.Layout(justify_content='center'))

    qv_value = widgets.HTML(value="<h5>{qubits}</h5>".format(qubits=qv_val),
                            layout=widgets.Layout(justify_content='center'))

    cmap = widgets.Output(layout=widgets.Layout(min_width='250px',
                                                max_width='250px',
                                                max_height='250px',
                                                min_height='250px',
                                                justify_content='center',
                                                align_items='center',
                                                margin='0px 0px 0px 0px'))

    with cmap:
        _cmap_fig = plot_gate_map(backend,
                                  plot_directed=False,
                                  label_qubits=False)
        if _cmap_fig is not None:
            display(_cmap_fig)
            # Prevents plot from showing up twice.
            plt.close(_cmap_fig)

    pending = generate_jobs_pending_widget()

    is_oper = widgets.HTML(value="<h5></h5>",
                           layout=widgets.Layout(justify_content='center'))

    least_busy = widgets.HTML(value="<h5></h5>",
                              layout=widgets.Layout(justify_content='center'))

    t1_units = props['qubits'][0][0]['unit']
    avg_t1 = round(
        sum([q[0]['value'] for q in props['qubits']]) / num_qubits, 1)
    avg_t2 = round(
        sum([q[1]['value'] for q in props['qubits']]) / num_qubits, 1)
    t12_widget = widgets.HTML(value="<h5>{t1} / {t2} {units}</h5>".format(
        t1=avg_t1, t2=avg_t2, units=t1_units),
                              layout=widgets.Layout())

    avg_cx_err = 'NA'
    if config['coupling_map']:
        sum_cx_err = 0
        num_cx = 0
        for gate in props['gates']:
            if gate['gate'] == 'cx':
                for param in gate['parameters']:
                    if param['name'] == 'gate_error':
                        # Value == 1.0 means gate effectively off
                        if param['value'] != 1.0:
                            sum_cx_err += param['value']
                            num_cx += 1
        avg_cx_err = round(sum_cx_err / (num_cx), 4)

    cx_widget = widgets.HTML(
        value="<h5>{cx_err}</h5>".format(cx_err=avg_cx_err),
        layout=widgets.Layout())

    avg_meas_err = 0
    for qub in props['qubits']:
        for item in qub:
            if item['name'] == 'readout_error':
                avg_meas_err += item['value']
    avg_meas_err = round(avg_meas_err / num_qubits, 4)
    meas_widget = widgets.HTML(
        value="<h5>{meas_err}</h5>".format(meas_err=avg_meas_err),
        layout=widgets.Layout())

    out = widgets.VBox([
        name, cmap, qubit_count, qv_value, pending, is_oper, least_busy,
        t12_widget, cx_widget, meas_widget
    ],
                       layout=widgets.Layout(display='inline-flex',
                                             flex_flow='column',
                                             align_items='center'))

    out._is_alive = True
    return out
Beispiel #4
0
def backend_widget(backend):
    """Creates a backend widget."""
    config = backend.configuration().to_dict()
    props = backend.properties().to_dict()

    name = widgets.HTML(value=f"<h4>{backend.name()}</h4>",
                        layout=widgets.Layout())

    num_qubits = config["n_qubits"]

    qv_val = "-"
    if "quantum_volume" in config.keys():
        if config["quantum_volume"]:
            qv_val = config["quantum_volume"]

    qubit_count = widgets.HTML(
        value=f"<h5><b>{num_qubits}</b></h5>",
        layout=widgets.Layout(justify_content="center"),
    )

    qv_value = widgets.HTML(
        value=f"<h5>{qv_val}</h5>",
        layout=widgets.Layout(justify_content="center"),
    )

    cmap = widgets.Output(layout=widgets.Layout(
        min_width="250px",
        max_width="250px",
        max_height="250px",
        min_height="250px",
        justify_content="center",
        align_items="center",
        margin="0px 0px 0px 0px",
    ))

    with cmap:
        _cmap_fig = plot_gate_map(backend,
                                  plot_directed=False,
                                  label_qubits=False)
        if _cmap_fig is not None:
            display(_cmap_fig)
            # Prevents plot from showing up twice.
            plt.close(_cmap_fig)

    pending = generate_jobs_pending_widget()

    is_oper = widgets.HTML(value="<h5></h5>",
                           layout=widgets.Layout(justify_content="center"))

    least_busy = widgets.HTML(value="<h5></h5>",
                              layout=widgets.Layout(justify_content="center"))

    t1_units = props["qubits"][0][0]["unit"]
    avg_t1 = round(sum(q[0]["value"] for q in props["qubits"]) / num_qubits, 1)
    avg_t2 = round(sum(q[1]["value"] for q in props["qubits"]) / num_qubits, 1)
    t12_widget = widgets.HTML(
        value=f"<h5>{avg_t1} / {avg_t2} {t1_units}</h5>",
        layout=widgets.Layout(),
    )

    avg_cx_err = "NA"
    if config["coupling_map"]:
        sum_cx_err = 0
        num_cx = 0
        for gate in props["gates"]:
            if gate["gate"] == "cx":
                for param in gate["parameters"]:
                    if param["name"] == "gate_error":
                        # Value == 1.0 means gate effectively off
                        if param["value"] != 1.0:
                            sum_cx_err += param["value"]
                            num_cx += 1
        if num_cx > 0:
            avg_cx_err = round(sum_cx_err / num_cx, 4)

    cx_widget = widgets.HTML(value=f"<h5>{avg_cx_err}</h5>",
                             layout=widgets.Layout())

    avg_meas_err = 0
    for qub in props["qubits"]:
        for item in qub:
            if item["name"] == "readout_error":
                avg_meas_err += item["value"]
    avg_meas_err = round(avg_meas_err / num_qubits, 4)
    meas_widget = widgets.HTML(value=f"<h5>{avg_meas_err}</h5>",
                               layout=widgets.Layout())

    out = widgets.VBox(
        [
            name,
            cmap,
            qubit_count,
            qv_value,
            pending,
            is_oper,
            least_busy,
            t12_widget,
            cx_widget,
            meas_widget,
        ],
        layout=widgets.Layout(display="inline-flex",
                              flex_flow="column",
                              align_items="center"),
    )

    out._is_alive = True
    return out
Beispiel #5
0
def config_tab(backend):
    """The backend configuration widget.

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        grid: A GridBox widget.
    """
    status = backend.status().to_dict()
    config = backend.configuration().to_dict()

    config_dict = {**status, **config}

    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')
    upper_str = "<table>"
    upper_str += """<style>
table {
    border-collapse: collapse;
    width: auto;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""

    footer = "</table>"

    # Upper HBox widget data

    upper_str += "<tr><th>Property</th><th>Value</th></tr>"
    for key in upper_list:
        upper_str += "<tr><td><font style='font-weight:bold'>%s</font></td><td>%s</td></tr>" % (
            key, config_dict[key])
    upper_str += footer

    upper_table = widgets.HTML(value=upper_str,
                               layout=widgets.Layout(width='100%',
                                                     grid_area='left'))

    image_widget = widgets.Output(
        layout=widgets.Layout(display='flex-inline',
                              grid_area='right',
                              padding='10px 10px 10px 10px',
                              width='auto',
                              max_height='300px',
                              align_items='center'))

    if not config['simulator']:
        with image_widget:
            gate_map = plot_gate_map(backend)
            display(gate_map)
        plt.close(gate_map)

    lower_str = "<table>"
    lower_str += """<style>
table {
    border-collapse: collapse;
    width: auto;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""
    lower_str += "<tr><th></th><th></th></tr>"
    for key in lower_list:
        if key != 'name':
            lower_str += "<tr><td>%s</td><td>%s</td></tr>" % (key,
                                                              config_dict[key])
    lower_str += footer

    lower_table = widgets.HTML(value=lower_str,
                               layout=widgets.Layout(width='auto',
                                                     grid_area='bottom'))

    grid = widgets.GridBox(children=[upper_table, image_widget, lower_table],
                           layout=widgets.Layout(
                               grid_template_rows='auto auto',
                               grid_template_columns='25% 25% 25% 25%',
                               grid_template_areas='''
                               "left right right right"
                               "bottom bottom bottom bottom"
                               ''',
                               grid_gap='0px 0px'))

    return grid
Beispiel #6
0
def detailed_map(backend):
    """Widget for displaying detailed noise map.

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        GridBox: Widget holding noise map images.
    """
    props = backend.properties().to_dict()
    config = backend.configuration().to_dict()
    single_gate_errors = [
        q['parameters'][0]['value']
        for q in props['gates'][2:3 * config['n_qubits']:3]
    ]
    single_norm = matplotlib.colors.Normalize(vmin=min(single_gate_errors),
                                              vmax=max(single_gate_errors))
    q_colors = [cm.viridis(single_norm(err)) for err in single_gate_errors]

    cmap = config['coupling_map']

    cx_errors = []
    for line in cmap:
        for item in props['gates'][3 * config['n_qubits']:]:
            if item['qubits'] == line:
                cx_errors.append(item['parameters'][0]['value'])
                break
        else:
            continue

    cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors),
                                          vmax=max(cx_errors))
    line_colors = [cm.viridis(cx_norm(err)) for err in cx_errors]

    single_widget = widgets.Output(layout=widgets.Layout(
        display='flex-inline', grid_area='left', align_items='center'))

    cmap_widget = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                       grid_area='top',
                                                       width='auto',
                                                       height='auto',
                                                       align_items='center'))

    cx_widget = widgets.Output(layout=widgets.Layout(
        display='flex-inline', grid_area='right', align_items='center'))

    tick_locator = mpl.ticker.MaxNLocator(nbins=5)
    with cmap_widget:
        noise_map = plot_gate_map(backend,
                                  qubit_color=q_colors,
                                  line_color=line_colors,
                                  qubit_size=28,
                                  plot_directed=True)
        width, height = noise_map.get_size_inches()

        noise_map.set_size_inches(1.25 * width, 1.25 * height)

        display(noise_map)
        plt.close(noise_map)

    with single_widget:
        cbl_fig = plt.figure(figsize=(3, 1))
        ax1 = cbl_fig.add_axes([0.05, 0.80, 0.9, 0.15])
        single_cb = mpl.colorbar.ColorbarBase(ax1,
                                              cmap=cm.viridis,
                                              norm=single_norm,
                                              orientation='horizontal')
        single_cb.locator = tick_locator
        single_cb.update_ticks()
        ax1.set_title('Single-qubit U3 error rate')
        display(cbl_fig)
        plt.close(cbl_fig)

    with cx_widget:
        cx_fig = plt.figure(figsize=(3, 1))
        ax2 = cx_fig.add_axes([0.05, 0.80, 0.9, 0.15])
        cx_cb = mpl.colorbar.ColorbarBase(ax2,
                                          cmap=cm.viridis,
                                          norm=cx_norm,
                                          orientation='horizontal')
        cx_cb.locator = tick_locator
        cx_cb.update_ticks()
        ax2.set_title('CNOT error rate')
        display(cx_fig)
        plt.close(cx_fig)

    out_box = widgets.GridBox([single_widget, cmap_widget, cx_widget],
                              layout=widgets.Layout(
                                  grid_template_rows='auto auto',
                                  grid_template_columns='33% 33% 33%',
                                  grid_template_areas='''
                                                "top top top"
                                                "left . right"
                                                ''',
                                  grid_gap='0px 0px'))
    return out_box
def backend_widget(backend):
    """Creates a backend widget.
    """
    config = backend.configuration().to_dict()
    props = backend.properties().to_dict()

    name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
                        layout=widgets.Layout())

    n_qubits = config['n_qubits']

    qubit_count = widgets.HTML(
        value="<h5><b>{qubits}</b></h5>".format(qubits=n_qubits),
        layout=widgets.Layout(justify_content='center'))

    cmap = widgets.Output(layout=widgets.Layout(min_width='250px',
                                                max_width='250px',
                                                max_height='250px',
                                                min_height='250px',
                                                justify_content='center',
                                                align_items='center',
                                                margin='0px 0px 0px 0px'))

    with cmap:
        _cmap_fig = plot_gate_map(backend,
                                  plot_directed=False,
                                  label_qubits=False)
        if _cmap_fig is not None:
            display(_cmap_fig)
            # Prevents plot from showing up twice.
            plt.close(_cmap_fig)

    pending = generate_jobs_pending_widget()

    is_oper = widgets.HTML(value="<h5></h5>",
                           layout=widgets.Layout(justify_content='center'))

    least_busy = widgets.HTML(value="<h5></h5>",
                              layout=widgets.Layout(justify_content='center'))

    t1_units = props['qubits'][0][0]['unit']
    avg_t1 = round(sum([q[0]['value'] for q in props['qubits']]) / n_qubits, 1)
    t1_widget = widgets.HTML(value="<h5>{t1} {units}</h5>".format(
        t1=avg_t1, units=t1_units),
                             layout=widgets.Layout())

    t2_units = props['qubits'][0][1]['unit']
    avg_t2 = round(sum([q[1]['value'] for q in props['qubits']]) / n_qubits, 1)
    t2_widget = widgets.HTML(value="<h5>{t2} {units}</h5>".format(
        t2=avg_t2, units=t2_units),
                             layout=widgets.Layout())

    out = widgets.VBox([
        name, cmap, qubit_count, pending, least_busy, is_oper, t1_widget,
        t2_widget
    ],
                       layout=widgets.Layout(display='inline-flex',
                                             flex_flow='column',
                                             align_items='center'))

    out._is_alive = True
    return out
Beispiel #8
0
def config_tab(backend):
    """The backend configuration widget.

    Args:
        backend (IBMQBackend | FakeBackend): The backend.

    Returns:
        grid: A GridBox widget.
    """
    status = backend.status().to_dict()
    config = backend.configuration().to_dict()

    config_dict = {**status, **config}

    upper_list = ["n_qubits"]

    if "quantum_volume" in config.keys():
        if config["quantum_volume"]:
            upper_list.append("quantum_volume")

    upper_list.extend([
        "operational",
        "status_msg",
        "pending_jobs",
        "backend_version",
        "basis_gates",
        "max_shots",
        "max_experiments",
    ])

    lower_list = list(set(config_dict.keys()).difference(upper_list))
    # Remove gates because they are in a different tab
    lower_list.remove("gates")
    # Look for hamiltonian
    if "hamiltonian" in lower_list:
        htex = config_dict["hamiltonian"]["h_latex"]
        config_dict["hamiltonian"] = "$$%s$$" % htex

    upper_str = "<table>"
    upper_str += """<style>
table {
    border-collapse: collapse;
    width: auto;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""

    footer = "</table>"

    # Upper HBox widget data

    upper_str += "<tr><th>Property</th><th>Value</th></tr>"
    for key in upper_list:
        upper_str += "<tr><td><font style='font-weight:bold'>{}</font></td><td>{}</td></tr>".format(
            key,
            config_dict[key],
        )
    upper_str += footer

    upper_table = widgets.HTMLMath(value=upper_str,
                                   layout=widgets.Layout(width="100%",
                                                         grid_area="left"))

    image_widget = widgets.Output(layout=widgets.Layout(
        display="flex-inline",
        grid_area="right",
        padding="10px 10px 10px 10px",
        width="auto",
        max_height="325px",
        align_items="center",
    ))

    if not config["simulator"]:
        with image_widget:
            qubit_size = 24
            if config["n_qubits"] > 20:
                qubit_size = 34
            gate_map = plot_gate_map(backend, qubit_size=qubit_size)
            display(gate_map)
        plt.close(gate_map)

    lower_str = "<table>"
    lower_str += """<style>
table {
    border-collapse: collapse;
    width: auto;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""
    lower_str += "<tr><th></th><th></th></tr>"
    for key in lower_list:
        if key != "name":
            lower_str += f"<tr><td>{key}</td><td>{config_dict[key]}</td></tr>"
    lower_str += footer

    lower_table = widgets.HTMLMath(value=lower_str,
                                   layout=widgets.Layout(width="auto",
                                                         grid_area="bottom"))

    grid = widgets.GridBox(
        children=[upper_table, image_widget, lower_table],
        layout=widgets.Layout(
            grid_template_rows="auto auto",
            grid_template_columns="31% 23% 23% 23%",
            grid_template_areas="""
                               "left right right right"
                               "bottom bottom bottom bottom"
                               """,
            grid_gap="0px 0px",
        ),
    )

    return grid