def system_error_map(backend, figsize=(800, 500), show_title=True, remove_badcal_edges=True, background_color='white', as_widget=False): """Plot the error map of a device. Args: backend (IBMQBackend or FakeBackend or DeviceSimulator or Properties): Plot the error map for a backend. figsize (tuple, optional): Figure size in pixels. show_title (bool, optional): Whether to show figure title. remove_badcal_edges (bool, optional): Whether to remove bad CX gate calibration data. background_color (str, optional): Background color, either 'white' or 'black'. as_widget (bool, optional): ``True`` if the figure is to be returned as a ``PlotlyWidget``. Otherwise the figure is to be returned as a ``PlotlyFigure``. Returns: PlotlyFigure or PlotlyWidget: The error map figure. Raises: KaleidoscopeError: Invalid input type. Example: .. jupyter-execute:: from qiskit import * from kaleidoscope.qiskit.backends import system_error_map pro = IBMQ.load_account() backend = pro.backends.ibmq_vigo system_error_map(backend) """ if not isinstance( backend, (IBMQBackend, DeviceSimulator, FakeBackend, BackendProperties)): raise KaleidoscopeError( 'Input is not a valid backend or properties object.') if isinstance(backend, BackendProperties): backend = properties_to_pseudobackend(backend) meas_text_color = '#000000' if background_color == 'white': color_map = CMAP text_color = '#000000' plotly_cmap = BMY_PLOTLY elif background_color == 'black': color_map = CMAP text_color = '#FFFFFF' plotly_cmap = BMY_PLOTLY else: raise KaleidoscopeError( '"{}" is not a valid background_color selection.'.format( background_color)) if backend.configuration().simulator and not isinstance( backend, DeviceSimulator): raise KaleidoscopeError('Requires a device backend, not a simulator.') config = backend.configuration() n_qubits = config.n_qubits cmap = config.coupling_map if n_qubits in DEVICE_LAYOUTS.keys(): grid_data = DEVICE_LAYOUTS[n_qubits] else: fig = go.Figure() fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], margin=dict(t=60, l=0, r=0, b=0)) out = PlotlyWidget(fig) return out props = backend.properties().to_dict() t1s = [] t2s = [] for qubit_props in props['qubits']: count = 0 for item in qubit_props: if item['name'] == 'T1': t1s.append(item['value']) count += 1 elif item['name'] == 'T2': t2s.append(item['value']) count += 1 if count == 2: break # U2 error rates single_gate_errors = [0] * n_qubits for gate in props['gates']: if gate['gate'] == 'u2': _qubit = gate['qubits'][0] single_gate_errors[_qubit] = gate['parameters'][0]['value'] # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) max_1q_err = max(single_gate_errors) single_norm = mpl.colors.Normalize(vmin=min(single_gate_errors), vmax=max_1q_err) q_colors = [ mpl.colors.rgb2hex(color_map(single_norm(err))) for err in single_gate_errors ] if n_qubits > 1: line_colors = [] if cmap: cx_errors = [] for line in cmap: for item in props['gates']: if item['qubits'] == line: cx_errors.append(item['parameters'][0]['value']) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) # remove bad cx edges if remove_badcal_edges: cx_idx = np.where(cx_errors != 100.0)[0] else: cx_idx = np.arange(len(cx_errors)) avg_cx_err = np.mean(cx_errors[cx_idx]) cx_norm = mpl.colors.Normalize(vmin=min(cx_errors[cx_idx]), vmax=max(cx_errors[cx_idx])) for err in cx_errors: if err != 100.0 or not remove_badcal_edges: line_colors.append( mpl.colors.rgb2hex(color_map(cx_norm(err)))) else: line_colors.append("#ff0000") # Measurement errors read_err = [] for qubit in range(n_qubits): for item in props['qubits'][qubit]: if item['name'] == 'readout_error': read_err.append(item['value']) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) if n_qubits < 10: num_left = n_qubits num_right = 0 else: num_left = math.ceil(n_qubits / 2) num_right = n_qubits - num_left 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) qubit_size = 32 font_size = 14 offset = 0 if cmap: if y_max / max_dim < 0.33: qubit_size = 24 font_size = 10 offset = 1 if n_qubits > 5: right_meas_title = "Readout Error (%)" else: right_meas_title = None if cmap: cx_title = "CNOT Error Rate [Avg. {}%]".format(np.round(avg_cx_err, 3)) else: cx_title = None fig = make_subplots( rows=2, cols=11, row_heights=[0.95, 0.05], vertical_spacing=0.15, specs=[[{ "colspan": 2 }, None, { "colspan": 6 }, None, None, None, None, None, { "colspan": 2 }, None, None], [{ "colspan": 4 }, None, None, None, None, None, { "colspan": 4 }, None, None, None, None]], subplot_titles=("Readout Error (%)", None, right_meas_title, "Hadamard Error Rate [Avg. {}%]".format( np.round(avg_1q_err, 3)), cx_title)) # Add lines for couplings if cmap and n_qubits > 1: for ind, edge in enumerate(cmap): is_symmetric = False if edge[::-1] in cmap: is_symmetric = True y_start = grid_data[edge[0]][0] + offset x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] + offset x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start x_mid = x_end y_mid = y_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start x_mid = x_start y_mid = y_end else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start x_mid = x_end y_mid = y_end else: if y_start == y_end: x_mid = (x_end - x_start) / 2 + x_start y_mid = y_end elif x_start == x_end: x_mid = x_end y_mid = (y_end - y_start) / 2 + y_start else: x_mid = (x_end - x_start) / 2 + x_start y_mid = (y_end - y_start) / 2 + y_start fig.append_trace(go.Scatter( x=[x_start, x_mid, x_end], y=[-y_start, -y_mid, -y_end], mode="lines", line=dict(width=6, color=line_colors[ind]), hoverinfo='text', hovertext='CX<sub>err</sub>{B}_{A} = {err} %'.format( A=edge[0], B=edge[1], err=np.round(cx_errors[ind], 3))), row=1, col=3) # Add the qubits themselves qubit_text = [] qubit_str = "<b>Qubit {}</b><br>H<sub>err</sub> = {} %" qubit_str += "<br>T1 = {} \u03BCs<br>T2 = {} \u03BCs" for kk in range(n_qubits): qubit_text.append( qubit_str.format(kk, np.round(single_gate_errors[kk], 3), np.round(t1s[kk], 2), np.round(t2s[kk], 2))) if n_qubits > 20: qubit_size = 23 font_size = 11 if n_qubits > 50: qubit_size = 20 font_size = 9 qtext_color = [] for ii in range(n_qubits): if single_gate_errors[ii] > 0.8 * max_1q_err: qtext_color.append('black') else: qtext_color.append('white') fig.append_trace(go.Scatter(x=[d[1] for d in grid_data], y=[-d[0] - offset for d in grid_data], mode="markers+text", marker=go.scatter.Marker(size=qubit_size, color=q_colors, opacity=1), text=[str(ii) for ii in range(n_qubits)], textposition="middle center", textfont=dict(size=font_size, color=qtext_color), hoverinfo="text", hovertext=qubit_text), row=1, col=3) fig.update_xaxes(row=1, col=3, visible=False) _range = None if offset: _range = [-3.5, 0.5] fig.update_yaxes(row=1, col=3, visible=False, range=_range) # H error rate colorbar min_1q_err = min(single_gate_errors) max_1q_err = max(single_gate_errors) if n_qubits > 1: fig.append_trace(go.Heatmap(z=[ np.linspace(min_1q_err, max_1q_err, 100), np.linspace(min_1q_err, max_1q_err, 100) ], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=1) fig.update_yaxes(row=2, col=1, visible=False) fig.update_xaxes(row=2, col=1, tickvals=[0, 49, 99], ticktext=[ np.round(min_1q_err, 3), np.round( (max_1q_err - min_1q_err) / 2 + min_1q_err, 3), np.round(max_1q_err, 3) ]) # CX error rate colorbar if cmap and n_qubits > 1: min_cx_err = min(cx_errors) max_cx_err = max(cx_errors) fig.append_trace(go.Heatmap(z=[ np.linspace(min_cx_err, max_cx_err, 100), np.linspace(min_cx_err, max_cx_err, 100) ], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=7) fig.update_yaxes(row=2, col=7, visible=False) min_cx_idx_err = min(cx_errors[cx_idx]) max_cx_idx_err = max(cx_errors[cx_idx]) fig.update_xaxes(row=2, col=7, tickvals=[0, 49, 99], ticktext=[ np.round(min_cx_idx_err, 3), np.round((max_cx_idx_err - min_cx_idx_err) / 2 + min_cx_idx_err, 3), np.round(max_cx_idx_err, 3) ]) hover_text = "<b>Qubit {}</b><br>M<sub>err</sub> = {} %" # Add the left side meas errors for kk in range(num_left - 1, -1, -1): fig.append_trace(go.Bar( x=[read_err[kk]], y=[kk], orientation='h', marker=dict(color='#c7c7c5'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[hover_text.format(kk, np.round(read_err[kk], 3))]), row=1, col=1) fig.append_trace(go.Scatter(x=[avg_read_err, avg_read_err], y=[-0.25, num_left - 1 + 0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot')), row=1, col=1) fig.update_yaxes(row=1, col=1, tickvals=list(range(num_left)), autorange="reversed") fig.update_xaxes( row=1, col=1, range=[0, 1.1 * max_read_err], tickvals=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Add the right side meas errors, if any if num_right: for kk in range(n_qubits - 1, num_left - 1, -1): fig.append_trace(go.Bar( x=[-read_err[kk]], y=[kk], orientation='h', marker=dict(color='#c7c7c5'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[hover_text.format(kk, np.round(read_err[kk], 3))]), row=1, col=9) fig.append_trace(go.Scatter(x=[-avg_read_err, -avg_read_err], y=[num_left - 0.25, n_qubits - 1 + 0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot')), row=1, col=9) fig.update_yaxes( row=1, col=9, tickvals=list(range(n_qubits - 1, num_left - 1, -1)), side='right', autorange="reversed", ) fig.update_xaxes( row=1, col=9, range=[-1.1 * max_read_err, 0], tickvals=[ 0, -np.round(avg_read_err, 2), -np.round(max_read_err, 2) ], ticktext=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=13) title_text = "{} Error Map".format(backend.name()) if show_title else '' fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], title=dict(text=title_text, x=0.452), title_font_size=20, font=dict(color=text_color), margin=dict(t=60, l=0, r=40, b=0)) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
def system_gate_map(backend, figsize=(None, None), label_qubits=True, qubit_size=None, line_width=None, font_size=None, qubit_colors="#2f4b7c", qubit_labels=None, line_colors="#2f4b7c", font_color="white", background_color='white', as_widget=False): """Plots an interactive gate map of a device. Args: backend (IBMQBackend or FakeBackend or DeviceSimulator or Properties): Plot the error map for a backend. figsize (tuple): Output figure size (wxh) in pixels. label_qubits (bool): Labels for the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (float): Font size of qubit labels. qubit_colors (str or list): A list of colors for the qubits. If a single color is given, it's used for all qubits. qubit_labels (list): A list of qubit labels line_colors (str or list): A list of colors for each line from the coupling map. If a single color is given, it's used for all lines. font_color (str): The font color for the qubit labels. background_color (str): The background color, either 'white' or 'black'. as_widget (bool): Return the figure as a widget. Returns: PlotlyFigure or PlotlyWidget: Returned figure instance. Raises: KaleidoscopeError: Invalid input object. Example: .. jupyter-execute:: from qiskit import * from kaleidoscope.qiskit.backends import system_gate_map pro = IBMQ.load_account() backend = pro.backends.ibmq_vigo system_gate_map(backend) """ if not isinstance( backend, (IBMQBackend, DeviceSimulator, FakeBackend, BackendProperties)): raise KaleidoscopeError( 'Input is not a valid backend or properties object.') if isinstance(backend, BackendProperties): backend = properties_to_pseudobackend(backend) config = backend.configuration() n_qubits = config.n_qubits cmap = config.coupling_map # set coloring if isinstance(qubit_colors, str): qubit_colors = [qubit_colors] * n_qubits if isinstance(line_colors, str): line_colors = [line_colors] * len(cmap) if cmap else [] if str(n_qubits) in LAYOUTS['layouts'].keys(): kind = 'generic' if backend.name() in LAYOUTS['special_names']: if LAYOUTS['special_names'][backend.name()] in LAYOUTS['layouts'][ str(n_qubits)]: kind = LAYOUTS['special_names'][backend.name()] grid_data = LAYOUTS['layouts'][str(n_qubits)][kind] else: fig = go.Figure() fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], margin=dict(t=30, l=0, r=0, b=0)) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig) offset = 0 if cmap: if n_qubits in [14, 15, 16]: offset = 1 if qubit_size is None: qubit_size = 24 if font_size is None: font_size = 10 if line_width is None: line_width = 4 if figsize == (None, None): figsize = (400, 200) elif n_qubits == 27: if qubit_size is None: qubit_size = 24 if font_size is None: font_size = 10 if line_width is None: line_width = 4 if figsize == (None, None): figsize = (400, 300) else: if qubit_size is None: qubit_size = 32 if font_size is None: font_size = 14 if line_width is None: line_width = 6 if figsize == (None, None): figsize = (300, 300) else: if figsize == (None, None): figsize = (300, 300) if qubit_size is None: qubit_size = 30 fig = go.Figure() # Add lines for couplings if cmap: for ind, edge in enumerate(cmap): is_symmetric = False if edge[::-1] in cmap: is_symmetric = True y_start = grid_data[edge[0]][0] + offset x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] + offset x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start x_mid = x_end y_mid = y_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start x_mid = x_start y_mid = y_end else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start x_mid = x_end y_mid = y_end else: if y_start == y_end: x_mid = (x_end - x_start) / 2 + x_start y_mid = y_end elif x_start == x_end: x_mid = x_end y_mid = (y_end - y_start) / 2 + y_start else: x_mid = (x_end - x_start) / 2 + x_start y_mid = (y_end - y_start) / 2 + y_start fig.add_trace( go.Scatter(x=[x_start, x_mid, x_end], y=[-y_start, -y_mid, -y_end], mode="lines", hoverinfo='none', line=dict(width=line_width, color=line_colors[ind]))) # Add the qubits themselves qubit_text = [] qubit_str = "<b>Qubit {}" for num in range(n_qubits): qubit_text.append( qubit_str.format(qubit_labels[num] if qubit_labels else num)) if qubit_labels is None: qubit_labels = [str(ii) for ii in range(n_qubits)] if n_qubits > 50: if qubit_size is None: qubit_size = 20 if font_size is None: font_size = 9 fig.add_trace( go.Scatter(x=[d[1] for d in grid_data], y=[-d[0] - offset for d in grid_data], mode="markers+text", marker=go.scatter.Marker(size=qubit_size, color=qubit_colors, opacity=1), text=qubit_labels if label_qubits else '', textposition="middle center", textfont=dict(size=font_size, color=font_color), hoverinfo="text" if label_qubits else 'none', hovertext=qubit_text)) fig.update_xaxes(visible=False) _range = None if offset: _range = [-3.5, 0.5] fig.update_yaxes(visible=False, range=_range) fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], margin=dict(t=30, l=0, r=0, b=0)) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
def bloch_sphere(vectors=None, vectors_color=None, vectors_alpha=None, vectors_annotation=False, points=None, points_color=None, points_alpha=None, figsize=(350, 350), label_fontsize=16, annotation_fontsize=10, as_widget=False): """Generates a Bloch sphere from a given collection of vector and/or points data expressed in cartesian coordinates, [x, y, z]. Parameters: vectors (list, ndarray): Collection of one or more vectors to display. vectors_color (str or list): List of colors to use when plotting vectors. vectors_alpha (float or list): List of alphas to use when plotting vectors. vectors_annotation (bool or list): Boolean values to determine if a annotation should be displayed. points (list, ndarray): Collection of one or more points to display. points_color (str or list): List of colors to use when plotting points. points_alpha (float or list): List of alphas to use when plotting points. figsize (tuple): Figure size in pixels. label_fontsize (int): Font size for axes labels. annotation_fontsize (int): Font size for annotations. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure or PlotlyWidget: A Plotly figure or widget instance Raises: ValueError: Input lengths do not match. KaleidoscopeError: Invalid vector input. Example: .. jupyter-execute:: import numpy as np from matplotlib.colors import LinearSegmentedColormap, rgb2hex from kaleidoscope.interactive import bloch_sphere cm = LinearSegmentedColormap.from_list('graypurple', ["#999999", "#AA00FF"]) pointsx = [[0, -np.sin(th), np.cos(th)] for th in np.linspace(0, np.pi/2, 20)] pointsz = [[np.sin(th), -np.cos(th), 0] for th in np.linspace(0, 3*np.pi/4, 30)] points = pointsx + pointsz points_alpha = [np.linspace(0.8, 1, len(points))] points_color = [[rgb2hex(cm(kk)) for kk in np.linspace(-1,1,len(points))]] vectors_color = ["#777777", "#AA00FF"] bloch_sphere(points=points, vectors=[[0, 0, 1], [1/np.sqrt(2), 1/np.sqrt(2), 0]], vectors_color=vectors_color, points_alpha=points_alpha, points_color=points_color) """ # Output figure instance fig = go.Figure() # List for vector annotations, if any fig_annotations = [] idx = 0 if points is not None: nest_depth = nest_level(points) # Take care of single point passed if nest_depth == 1: points = [[points]] # A single list of points passes elif nest_depth == 2: points = [points] # nest_depth = 3 means multiple lists passed if points_color is None: # passed a single point if nest_depth == 1: points_color = [DARK2[0]] elif nest_depth == 2: points_color = [[ DARK2[kk % 8] for kk in range(len(points[0])) ]] elif nest_depth == 3: points_color = [] for kk, pnts in enumerate(points): points_color.append(DARK2[kk % 8] * len(pnts)) if nest_depth == 2 and nest_level(points_color) == 1: points_color = [points_color] if isinstance(points_color, str): points_color = [points_color] if points_alpha is None: points_alpha = [[1.0] * len(p) for p in points] if nest_depth == 2 and nest_level(points_alpha) == 1: points_alpha = [points_alpha] if isinstance(points_alpha, (int, float)): points_alpha = [[points_alpha]] for idx, point_collection in enumerate(points): x_pnts = [] y_pnts = [] z_pnts = [] if isinstance(points_color[idx], str): _colors = [points_color[idx]] * len(point_collection) else: _colors = points_color[idx] if len(points_alpha[idx]) != len(point_collection): err_str = 'number of alpha values ({}) does not equal number of points ({})' raise ValueError( err_str.format(len(points_alpha[idx]), len(x_pnts))) mcolors = [] for kk, point in enumerate(point_collection): x_pnts.append(point[0]) y_pnts.append(point[1]) z_pnts.append(point[2]) mcolors.append("rgba({},{},{},{})".format( *hex_to_rgb(_colors[kk]), points_alpha[idx][kk])) fig.add_trace( go.Scatter3d( x=x_pnts, y=y_pnts, z=z_pnts, mode='markers', marker=dict(size=7, color=mcolors), )) idx += 1 if vectors is not None: if vectors.__class__.__name__ in ['Statevector'] \ and 'qiskit' in vectors.__class__.__module__: vectors = bloch_components(vectors.data) elif not isinstance(vectors[0], (list, np.ndarray)): if vectors[0].__class__.__name__ not in ['Statevector']: vectors = [[vectors[0], vectors[1], vectors[2]]] new_vecs = [] for vec in vectors: if vec.__class__.__name__ in [ 'Statevector' ] and 'qiskit' in vec.__class__.__module__: # pylint: disable=no-member new_vecs.append(bloch_components(vec.data)[0]) else: nst_lvl = nest_level(vec) if nst_lvl == 1: new_vecs.append(vec) elif nst_lvl == 2: new_vecs.append(vec[0]) else: raise KaleidoscopeError("Invalid vector input.") if vectors_color is None: vectors_color = [ DARK2[kk + idx % 8] for kk in range(len(new_vecs)) ] if isinstance(vectors_color, str): vectors_color = [vectors_color] if vectors_alpha is None: vectors_alpha = [1.0] * len(new_vecs) if isinstance(vectors_alpha, (int, float)): vectors_alpha = [vectors_alpha] if vectors_annotation is True: vectors_annotation = [True] * len(new_vecs) elif not vectors_annotation: vectors_annotation = [False] * len(new_vecs) eps = 1e-12 for idx, vec in enumerate(new_vecs): vec = np.asarray(vec) if np.linalg.norm(vec) > 1.0 + eps: raise ValueError('Vector norm must be <= 1.') # So that line does not go out of arrow head vec_line = vec / 1.05 color_str = "rgba({},{},{},{})".format( *hex_to_rgb(vectors_color[idx]), vectors_alpha[idx]) fig.add_trace( go.Scatter3d(x=[0, vec_line[0]], y=[0, vec_line[1]], z=[0, vec_line[2]], mode="lines", hoverinfo=None, line=dict(color=color_str, width=10))) fig.add_trace( go.Cone(x=[vec[0]], y=[vec[1]], z=[vec[2]], u=[vec[0]], v=[vec[1]], w=[vec[2]], sizemode="absolute", showscale=False, opacity=vectors_alpha[idx], colorscale=[vectors_color[idx], vectors_color[idx]], sizeref=0.25, anchor="tip")) if vectors_annotation[idx]: fig_annotations.append( dict( showarrow=False, x=vec[0] * 1.05, y=vec[1] * 1.05, z=vec[2] * 1.05, text="[{},<br> {},<br> {}]".format( round(vec[0], 3), round(vec[1], 3), round(vec[2], 3)), align='left', borderpad=3, xanchor='right' if vec[1] <= 0 else "left", xshift=10, bgcolor="#53565F", font=dict( size=annotation_fontsize, color="#ffffff", family="Courier New, monospace", ), )) # Start construction of sphere # Sphere fig.add_trace(BSPHERE()) # latitudes for kk in LATS: fig.add_trace(kk) # longitudes for kk in LONGS: fig.add_trace(kk) # z-axis fig.add_trace(ZAXIS) # x-axis fig.add_trace(XAXIS) # y-axis fig.add_trace(YAXIS) # zaxis label fig.add_trace(Z0LABEL(fontsize=label_fontsize)) fig.add_trace(Z1LABEL(fontsize=label_fontsize)) # xaxis label fig.add_trace(XLABEL(fontsize=label_fontsize)) # yaxis label fig.add_trace(YLABEL(fontsize=label_fontsize)) fig.update_layout(width=figsize[0], height=figsize[1], autosize=False, hoverdistance=50, showlegend=False, scene_aspectmode='cube', margin=dict(r=0, b=0, l=0, t=0), scene=dict(annotations=fig_annotations, xaxis=dict(showbackground=False, range=[-1.2, 1.2], showspikes=False, visible=False), yaxis=dict(showbackground=False, range=[-1.2, 1.2], showspikes=False, visible=False), zaxis=dict(showbackground=False, range=[-1.2, 1.2], showspikes=False, visible=False)), scene_camera=dict(eye=dict(x=1.5, y=0.4, z=0.4))) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig, modebar=True)
def bloch_disc(rho, figsize=None, title=None, as_widget=False): """Plot a Bloch disc for a single qubit. Parameters: rho (list or ndarray or Statevector or DensityMatrix): Input statevector, density matrix, or Bloch components. figsize (tuple): Figure size in pixels, default=(200,275). title (str): Plot title. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure: A Plotly figure instance PlotlyWidget : A Plotly widget if `as_widget=True`. Example: .. jupyter-execute:: import numpy as np from qiskit import * from qiskit.quantum_info import Statevector from kaleidoscope.interactive import bloch_disc qc = QuantumCircuit(1) qc.ry(np.pi*np.random.random(), 0) qc.rz(np.pi*np.random.random(), 0) state = Statevector.from_instruction(qc) bloch_disc(state) """ # A hack so I do not have to import the actual instances from Qiskit. if rho.__class__.__name__ in ['Statevector', 'DensityMatrix'] \ and 'qiskit' in rho.__class__.__module__: rho = rho.data if len(rho) != 3: rho = np.asarray(rho, dtype=complex) comp = bloch_components(rho) else: comp = [rho] if title: title = [title] + ["\u2329Z\u232A"] else: title = [""] + ["\u2329Z\u232A"] if figsize is None: figsize = (200, 275) fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'domain'}]+[{'type': 'xy'}]], subplot_titles=title, column_widths=[0.93]+[0.07]) fig.add_trace(bloch_sunburst(comp[0]), row=1, col=1) zval = comp[0][2] zrange = [k*np.ones(1) for k in np.linspace(-1, 1, 100)] idx = (np.abs(np.linspace(-1, 1, 100) - zval)).argmin() tickvals = np.array([0, 49, 99, idx]) idx_sort = np.argsort(tickvals) tickvals = tickvals[idx_sort] ticktext = [-1, 0, 1, "\u25C0"+str(np.round(zval, 3))] if zval <= -0.95: ticktext[0] = '' elif abs(zval) <= 0.05: ticktext[1] = '' elif zval >= 0.95: ticktext[2] = '' ticktext = [ticktext[kk] for kk in idx_sort] fig.append_trace(go.Heatmap(z=zrange, colorscale=BMY_PLOTLY, showscale=False, hoverinfo='none', ), row=1, col=2 ) fig.update_yaxes(row=1, col=2, tickvals=tickvals, ticktext=ticktext) fig.update_yaxes(row=1, col=2, side="right") fig.update_xaxes(row=1, col=2, visible=False) fig.update_layout(margin=dict(t=30, l=10, r=0, b=0), height=figsize[0], width=figsize[1], hoverlabel=dict(font_size=16, font_family="courier,monospace", align='left' ) ) for ann in fig['layout']['annotations']: ann['font'] = dict(size=14) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
def bloch_multi_disc(rho, figsize=None, titles=True, as_widget=False): """Plot Bloch discs for a multi-qubit state. Parameters: rho (list or ndarray or Statevector or DensityMatrix): Input statevector, density matrix. figsize (tuple): Figure size in pixels, default=(125*num_qubits, 150). titles (bool): Display titles. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure: A Plotly figure instance PlotlyWidget : A Plotly widget if `as_widget=True`. Example: .. jupyter-execute:: import numpy as np from qiskit import * from qiskit.quantum_info import Statevector from kaleidoscope.interactive import bloch_multi_disc N = 4 qc = QuantumCircuit(N) qc.h(range(N)) for kk in range(N): qc.ry(2*np.pi*np.random.random(), kk) for kk in range(N-1): qc.cx(kk,kk+1) for kk in range(N): qc.rz(2*np.pi*np.random.random(), kk) state = Statevector.from_instruction(qc) bloch_multi_disc(state) """ # A hack so I do not have to import the actual instances from Qiskit. if rho.__class__.__name__ in ['Statevector', 'DensityMatrix'] \ and 'qiskit' in rho.__class__.__module__: rho = rho.data rho = np.asarray(rho, dtype=complex) comp = bloch_components(rho) num = int(np.log2(rho.shape[0])) nrows = 1 ncols = num if figsize is None: figsize = (ncols*125, 150) if titles: titles = ["Qubit {}".format(k) for k in range(num)] + ["\u2329Z\u232A"] else: titles = ["" for k in range(num)] + ["\u2329Z\u232A"] fig = make_subplots(rows=nrows, cols=ncols+1, specs=[[{'type': 'domain'}]*ncols+[{'type': 'xy'}]], subplot_titles=titles, column_widths=[0.95/num]*num+[0.05]) for jj in range(num): fig.add_trace(bloch_sunburst(comp[jj]), row=1, col=jj+1) zrange = [k*np.ones(1) for k in np.linspace(-1, 1, 100)] fig.append_trace(go.Heatmap(z=zrange, colorscale=BMY_PLOTLY, showscale=False, hoverinfo='none', ), row=1, col=num+1) fig.update_yaxes(row=1, col=num+1, tickvals=[0, 49, 99], ticktext=[-1, 0, 1]) fig.update_yaxes(row=1, col=num+1, side="right") fig.update_xaxes(row=1, col=num+1, visible=False) fig.update_layout(margin=dict(t=50, l=0, r=15, b=30), width=figsize[0], height=figsize[1], hoverlabel=dict(font_size=14, font_family="monospace", align='left' ) ) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=16) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
def system_error_map(backend, figsize=(None, None), colormap=None, background_color='white', show_title=True, remove_badcal_edges=True, as_widget=False): """Plot the error map of a device. Args: backend (IBMQBackend or FakeBackend or DeviceSimulator or Properties): Plot the error map for a backend. figsize (tuple, optional): Figure size in pixels. colormap (Colormap): A matplotlib colormap. background_color (str, optional): Background color, either 'white' or 'black'. show_title (bool, optional): Whether to show figure title. remove_badcal_edges (bool, optional): Whether to remove bad CX gate calibration data. as_widget (bool, optional): ``True`` if the figure is to be returned as a ``PlotlyWidget``. Otherwise the figure is to be returned as a ``PlotlyFigure``. Returns: PlotlyFigure or PlotlyWidget: The error map figure. Raises: KaleidoscopeError: Invalid input type. Example: .. jupyter-execute:: from qiskit import * from kaleidoscope.qiskit.backends import system_error_map pro = IBMQ.load_account() backend = pro.backends.ibmq_vigo system_error_map(backend) """ if not isinstance( backend, (IBMQBackend, DeviceSimulator, FakeBackend, BackendProperties)): raise KaleidoscopeError( 'Input is not a valid backend or properties object.') if isinstance(backend, BackendProperties): backend = properties_to_pseudobackend(backend) CMAP = BMW PLOTLY_CMAP = cmap_to_plotly(CMAP) if colormap is not None: CMAP = colormap PLOTLY_CMAP = cmap_to_plotly(CMAP) meas_text_color = '#000000' if background_color == 'white': color_map = CMAP text_color = '#000000' plotly_cmap = PLOTLY_CMAP elif background_color == 'black': color_map = CMAP text_color = '#FFFFFF' plotly_cmap = PLOTLY_CMAP else: raise KaleidoscopeError( '"{}" is not a valid background_color selection.'.format( background_color)) if backend.configuration().simulator and not isinstance( backend, DeviceSimulator): raise KaleidoscopeError('Requires a device backend, not a simulator.') config = backend.configuration() n_qubits = config.n_qubits cmap = config.coupling_map if str(n_qubits) in LAYOUTS['layouts'].keys(): kind = 'generic' if backend.name() in LAYOUTS['special_names']: if LAYOUTS['special_names'][backend.name()] in LAYOUTS['layouts'][ str(n_qubits)]: kind = LAYOUTS['special_names'][backend.name()] grid_data = LAYOUTS['layouts'][str(n_qubits)][kind] else: fig = go.Figure() fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], margin=dict(t=60, l=0, r=0, b=0)) out = PlotlyWidget(fig) return out props = backend.properties() freqs = [0] * n_qubits t1s = [0] * n_qubits t2s = [0] * n_qubits alphas = [0] * n_qubits for idx, qubit_props in enumerate(props.qubits): for item in qubit_props: if item.name == 'frequency': freqs[idx] = item.value elif item.name == 'T1': t1s[idx] = item.value elif item.name == 'T2': t2s[idx] = item.value elif item.name == 'anharmonicity': alphas[idx] = item.value # U2 error rates single_gate_errors = [0] * n_qubits single_gate_times = [0] * n_qubits for gate in props.gates: if gate.gate in ['u2', 'sx']: _qubit = gate.qubits[0] for gpar in gate.parameters: if gpar.name == 'gate_error': single_gate_errors[_qubit] = gpar.value elif gpar.name == 'gate_length': single_gate_times[_qubit] = gpar.value # Convert to log10 single_gate_errors = np.log10(np.asarray(single_gate_errors)) avg_1q_err = np.mean(single_gate_errors) max_1q_err = _round_log10_exp(np.max(single_gate_errors), rnd='up', decimals=1) min_1q_err = _round_log10_exp(np.min(single_gate_errors), rnd='down', decimals=1) single_norm = mpl.colors.Normalize(vmin=min_1q_err, vmax=max_1q_err) q_colors = [ mpl.colors.rgb2hex(color_map(single_norm(err))) for err in single_gate_errors ] if n_qubits > 1: line_colors = [] if cmap: cx_errors = [] cx_times = [] for line in cmap: for gate in props.gates: if gate.qubits == line: for gpar in gate.parameters: if gpar.name == 'gate_error': cx_errors.append(gpar.value) elif gpar.name == 'gate_length': cx_times.append(gpar.value) # Convert to array cx_errors = np.log10(np.asarray(cx_errors)) # remove bad cx edges if remove_badcal_edges: cx_idx = np.where(cx_errors != 0.0)[0] else: cx_idx = np.arange(len(cx_errors)) avg_cx_err = np.mean(cx_errors[cx_idx]) min_cx_err = _round_log10_exp(np.min(cx_errors[cx_idx]), rnd='down', decimals=1) max_cx_err = _round_log10_exp(np.max(cx_errors[cx_idx]), rnd='up', decimals=1) cx_norm = mpl.colors.Normalize(vmin=min_cx_err, vmax=max_cx_err) for err in cx_errors: if err != 0.0 or not remove_badcal_edges: line_colors.append( mpl.colors.rgb2hex(color_map(cx_norm(err)))) else: line_colors.append("#ff0000") # Measurement errors read_err = [0] * n_qubits p01_err = [0] * n_qubits p10_err = [0] * n_qubits for qubit in range(n_qubits): for item in props.qubits[qubit]: if item.name == 'readout_error': read_err[qubit] = item.value elif item.name == 'prob_meas0_prep1': p01_err[qubit] = item.value elif item.name == 'prob_meas1_prep0': p10_err[qubit] = item.value read_err = np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) p01_err = np.asarray(p01_err) p10_err = np.asarray(p10_err) if n_qubits < 10: num_left = n_qubits num_right = 0 else: num_left = math.ceil(n_qubits / 2) num_right = n_qubits - num_left 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) qubit_size = 32 font_size = 14 offset = 0 if cmap: if y_max / max_dim < 0.33: qubit_size = 24 font_size = 10 offset = 1 if n_qubits > 5: right_meas_title = "Readout error" else: right_meas_title = None if cmap: cx_title = "CNOT error rate [Avg. {}]".format( '{:.2}\u22C510<sup>{}</sup>'.format(*_pow10_coeffs(avg_cx_err))) else: cx_title = None fig = make_subplots( rows=2, cols=11, row_heights=[0.95, 0.05], vertical_spacing=0.15, specs=[[{ "colspan": 2 }, None, { "colspan": 6 }, None, None, None, None, None, { "colspan": 2 }, None, None], [{ "colspan": 4 }, None, None, None, None, None, { "colspan": 4 }, None, None, None, None]], subplot_titles=("Readout error", None, right_meas_title, "SX error rate [Avg. {}]".format( '{:.2}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(avg_1q_err))), cx_title)) # Add lines for couplings if cmap and n_qubits > 1: for ind, edge in enumerate(cmap): is_symmetric = False if edge[::-1] in cmap: is_symmetric = True y_start = grid_data[edge[0]][0] + offset x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] + offset x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start x_mid = x_end y_mid = y_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start x_mid = x_start y_mid = y_end else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start x_mid = x_end y_mid = y_end else: if y_start == y_end: x_mid = (x_end - x_start) / 2 + x_start y_mid = y_end elif x_start == x_end: x_mid = x_end y_mid = (y_end - y_start) / 2 + y_start else: x_mid = (x_end - x_start) / 2 + x_start y_mid = (y_end - y_start) / 2 + y_start cx_str = 'cnot<sub>err</sub> = {err}' cx_str += '<br>𝜏<sub>cx</sub> = {tau} ns' fig.append_trace(go.Scatter( x=[x_start, x_mid, x_end], y=[-y_start, -y_mid, -y_end], mode="lines", line=dict(width=6, color=line_colors[ind]), hoverinfo='text', hovertext=cx_str.format( err='{:.3}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(cx_errors[ind])), tau=np.round(cx_times[ind], 2))), row=1, col=3) # Add the qubits themselves qubit_text = [] qubit_str = "<b>Qubit {idx}</b>" qubit_str += "<br>freq = {freq} GHz" qubit_str += "<br>T<sub>1</sub> = {t1} \u03BCs" qubit_str += "<br>T<sub>2</sub> = {t2} \u03BCs" qubit_str += "<br>α = {anh} GHz" qubit_str += "<br>sx<sub>err</sub> = {err}" qubit_str += "<br>𝜏<sub>sx</sub> = {tau} ns" for kk in range(n_qubits): qubit_text.append( qubit_str.format( idx=kk, freq=np.round(freqs[kk], 5), t1=np.round(t1s[kk], 2), t2=np.round(t2s[kk], 2), anh=np.round(alphas[kk], 3) if alphas[kk] else 'NA', err='{:.3}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(single_gate_errors[kk])), tau=np.round(single_gate_times[kk], 2))) if n_qubits > 20: qubit_size = 23 font_size = 11 if n_qubits > 50: qubit_size = 20 font_size = 9 qtext_color = [] for ii in range(n_qubits): qtext_color.append(find_text_color(q_colors[ii])) fig.append_trace(go.Scatter(x=[d[1] for d in grid_data], y=[-d[0] - offset for d in grid_data], mode="markers+text", marker=go.scatter.Marker(size=qubit_size, color=q_colors, opacity=1), text=[str(ii) for ii in range(n_qubits)], textposition="middle center", textfont=dict(size=font_size, color=qtext_color), hoverinfo="text", hovertext=qubit_text), row=1, col=3) fig.update_xaxes(row=1, col=3, visible=False) _range = None if offset: _range = [-3.5, 0.5] fig.update_yaxes(row=1, col=3, visible=False, range=_range) # H error rate colorbar if n_qubits > 1: fig.append_trace(go.Heatmap(z=[ np.linspace(min_1q_err, max_1q_err, 100), np.linspace(min_1q_err, max_1q_err, 100) ], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=1) fig.update_yaxes(row=2, col=1, visible=False) mid_1q_err = _round_log10_exp( (max_1q_err - min_1q_err) / 2 + min_1q_err, rnd='up', decimals=1) fig.update_xaxes(row=2, col=1, tickfont=dict(size=13), tickvals=[0, 49, 99], ticktext=[ '{:.2}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(min_1q_err)), '{:.2}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(mid_1q_err)), '{:.2}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(max_1q_err)), ]) # CX error rate colorbar if cmap and n_qubits > 1: fig.append_trace(go.Heatmap(z=[ np.linspace(min_cx_err, max_cx_err, 100), np.linspace(min_cx_err, max_cx_err, 100) ], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=7) fig.update_yaxes(row=2, col=7, visible=False) mid_cx_err = (max_cx_err - min_cx_err) / 2 + min_cx_err fig.update_xaxes( row=2, col=7, tickfont=dict(size=13), tickvals=[0, 49, 99], ticktext=[ '{:.2}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(min_cx_err)), '{:.2}\u22C510<sup>{}</sup>'.format( *_pow10_coeffs(mid_cx_err)), '{:.2}\u22C510<sup>{}</sup>'.format(*_pow10_coeffs(max_cx_err)) ]) hover_text = "<b>Qubit {idx}</b>" hover_text += "<br>M<sub>err</sub> = {err}" hover_text += "<br>P<sub>0|1</sub> = {p01}" hover_text += "<br>P<sub>1|0</sub> = {p10}" # Add the left side meas errors for kk in range(num_left - 1, -1, -1): fig.append_trace(go.Bar( x=[read_err[kk]], y=[kk], orientation='h', marker=dict(color='#c7c7c5'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[ hover_text.format(idx=kk, err=np.round(read_err[kk], 4), p01=np.round(p01_err[kk], 4), p10=np.round(p10_err[kk], 4)) ]), row=1, col=1) fig.append_trace(go.Scatter(x=[avg_read_err, avg_read_err], y=[-0.25, num_left - 1 + 0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot')), row=1, col=1) fig.update_yaxes(row=1, col=1, tickvals=list(range(num_left)), autorange="reversed") fig.update_xaxes( row=1, col=1, range=[0, 1.1 * max_read_err], tickvals=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Add the right side meas errors, if any if num_right: for kk in range(n_qubits - 1, num_left - 1, -1): fig.append_trace(go.Bar( x=[-read_err[kk]], y=[kk], orientation='h', marker=dict(color='#c7c7c5'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[ hover_text.format(idx=kk, err=np.round(read_err[kk], 4), p01=np.round(p01_err[kk], 4), p10=np.round(p10_err[kk], 4)) ]), row=1, col=9) fig.append_trace(go.Scatter(x=[-avg_read_err, -avg_read_err], y=[num_left - 0.25, n_qubits - 1 + 0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot')), row=1, col=9) fig.update_yaxes( row=1, col=9, tickvals=list(range(n_qubits - 1, num_left - 1, -1)), side='right', autorange="reversed", ) fig.update_xaxes( row=1, col=9, range=[-1.1 * max_read_err, 0], tickvals=[ 0, -np.round(avg_read_err, 2), -np.round(max_read_err, 2) ], ticktext=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=13) title_text = "{} error map".format(backend.name()) if show_title else '' fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], title=dict(text=title_text, x=0.452), title_font_size=20, font=dict(color=text_color), margin=dict(t=60, l=0, r=0, b=0), hoverlabel=dict(font_size=14, font_family="courier,monospace", align='left')) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)