Visualization¶
Represents a planar embedding of a quantum device seen as a graph. 

Modifies a color by multiplying 

Plot a complex matrix with labeling. 

Very generic plotter that compares like estimates across a specified key keyword. 


Plotter that compares Pauli infidelities from CB, SC, and KNR. 
Very generic plotter that compares like estimates across subsystems of a multisystem register. 

Plots estimate fits from IRB. 

Plots KNR data as a heatmap. 

Very generic plotter that overlays exponential fits onto lightly processed data. 

A collection of 

Plots the timestamps of circuit results. 
Graph¶

class
trueq.visualization.
Graph
(locations, edges=None, show_labels=False, bounds=None)¶ Represents a planar embedding of a quantum device seen as a graph.
The nodes of the graph represent qubits and the edges are possible couplings. The purpose of this class is to draw this graph in figures.
import trueq as tq import matplotlib.pyplot as plt g = tq.visualization.Graph( {0: (0.1,0.9), 1: (0.5,0.9), 2: (0.9,0.9), 3: (0.5,0.5), 4: (0.5,0.1)}, [[0, 1], [1, 2], [1, 3], [3, 4]], ) plt.figure() ax = plt.subplot() cycles = [ tq.Cycle({(0, 1): tq.Gate.cx}), tq.Cycle({(1, 2): tq.Gate.cx}), tq.Cycle({(1, 3): tq.Gate.cx}), tq.Cycle({(3, 4): tq.Gate.cx}), tq.Cycle({(1, 2): tq.Gate.cx, (3, 4): tq.Gate.cx}), ] for idx, cycle in enumerate(cycles): g.add_graph(ax, (0.1 + 0.2 * idx, 1.03), width=0.15, cycle=cycle) # save_figure may not catch things outside of the axis without this plt.tight_layout()
Note
There are a number of class variable such as
NODE_SIZE
which can be altered on a given instance to change the properties of the displayed graph. Parameters
locations (
dict
) – A dictionary mapping qubit labels to locations. The locations should fall inside the unit square; they are scaled to the appropriate size whenadd_graph()
is called. The argumentbounds
can be modified if it is more convenient to specify them in another box.edges (
Iterable
) – A list of length2 tuples specifying the allowed edges.show_labels (
bool
) – Whether to display qubit label numbers on the qubit nodes. Their properties can be adjusted by modifying the class variablesLABEL_OFFSET
andLABEL_STYLE
.bounds (
tuple
) – A tuple(left, right, bottom, top)
indicating the drawing area extents of the coordinates inlocations
. By default, this is(0, 0, 1, 1)
.

static
ibmq_T
(show_labels=False)¶ Instantiates a new Graph with a Tshaped 5 qubit topology found on some IBMQ devices.
 Parameters
show_labels (
bool
) – Whether to display qubit label numbers on the qubit nodes.

static
ibmq_butterfly
(show_labels=False)¶ Instantiates a new Graph with a butterflyshaped 5 qubit topology found on some IBMQ devices.
 Parameters
show_labels (
bool
) – Whether to display qubit label numbers on the qubit nodes.

static
linear
(n, show_labels=False)¶ Instantiates a new Graph with a linear topology.
To condense the size of the displayed graph, nodes are placed on a circle.
 Parameters
n (
int
Iterable
) – The number of qubits or an iterable of qubit labels.show_labels (
bool
) – Whether to display qubit label numbers on the qubit nodes.

grid
(n_cols, show_labels=False)¶ Instantiates a new Graph with a grid topology.
Qubit labels start at 0 and are rastered lefttoright from the topleft of the grid.
 Parameters
n_rows (
int
) – The number rows in the grid.n_cols (
int
) – The number columns in the grid.show_labels (
bool
) – Whether to display qubit label numbers on the qubit nodes.

add_graph
(ax, xy, cycle=None, twirl=None, transform=None, width=None, height=None, xorigin='center', yorigin='bottom', aspect=None)¶ Embeds the graph into a matplotlib axis at a given position and size.
Certain edges of the graph can be highlighted by passing a cycle.
 Parameters
ax (
matplotlib.artist.Artist
) – The axis (or any other type of artist) to add the graph to.xy (
tuple
) – The x and y position at which to add the graph, in coordinates specified bytransform
.cycle (
trueq.Cycle
) – Coupled edges and active nodes in this cycle will be highlighted in the graph.twirl (
tuple
) – Twirled edges and nodes in the twirl will be highlighted in the graph.transform (
matplotlib.transforms.Transform
) – Specifies the units ofx
,y
, width andheight
. By default, takes the value blended_transform_factory(ax.transData, ax.transAxes) so that horizontal units are data units, and vertical units are axis units.width (
float
) – The width graph, in coordinates specified bytransform
. This is optional, seeaspect
for details.height (
float
) – The width graph, in coordinates specified bytransform
. This is optional, seeaspect
for details.xorigin (
str
float
) – One of"left"
,"center"
, “right”, or any value between 0 and 1. Specifies which point of the graph’s bounding box should be located at position x.yorigin (
str
float
) – One of “bottom”, “middle”, “top”, or any value between 0 and 1. Specifies which point of the graph’s bounding box should be located at position `y.aspect (
float
) – Force a display aspect ratio of the graph’s bounding box. This is done by computing the largest rectangle of the given aspect ratio that fits in the rectangle of size(width, height)
. By default, if bothwidth
andheight
are provided, then these numbers (after being converted to display units) define the aspect ratio. However, if only one ofwidth
orheight
are given, then a default aspect ratio is defined as the aspect ratio of thebounds
set at initialization (default is 1).

plot
(cycle=None, twirl=None)¶ Plots the graph in its own figure.
 Parameters
cycle (
trueq.Cycle
) – Coupled edges and active nodes in this cycle will be highlighted in the graph.twirl (
tuple
) – Twirled edges and nodes in the twirl will be highlighted in the graph.
Multipy Lightness¶

trueq.visualization.
multiply_lightness
(color, amount=0.5)¶ Modifies a color by multiplying
(1  lightness)
in HSL space by the given amount.Numbers less than 1 result in a lighter color, and numbers greater than 1 result in a darker color.
from trueq.visualization.general import multiply_lightness import matplotlib.pyplot as plt plt.axvline(1, lw=3, color="g") plt.axvline(2, lw=3, color=multiply_lightness("g", 0.3)) plt.axvline(4, lw=3, color="#F034A3") plt.axvline(5, lw=3, color=multiply_lightness("#F034A3", 0.6)) plt.axvline(7, lw=3, color=(0.3, 0.55, 0.1)) plt.axvline(8, lw=3, color=multiply_lightness((0.3, 0.55, 0.1), 1.2))
<matplotlib.lines.Line2D at 0x7f58fe0996d8>
 Parameters
color (
str
tuple
) – A matplotlib color string, hex string, or RGB tuple.amount (
float
) – The amount to multiply(1  lightness)
of the input color by.
 Returns
An RGB tuple.
 Return type
tuple
Plot Mat¶

trueq.visualization.
plot_mat
(mat, xlabels=2, ylabels=2, show_values=True, abs_max=None, ax=None)¶ Plot a complex matrix with labeling.
The plot will have the following properties:
Color is dictated by the complex angle of each cell.
Transparency (alpha) is decided by the magnitude of each cell.
Size of plot scales based on shape of
mat
.
import trueq as tq import numpy as np phase = [np.exp(1j * t *np.pi) for t in np.linspace(0, 1, 8)] tq.visualization.plot_mat(np.outer(phase, phase))
 Parameters
mat (
numpy.ndarray
like) – A real or complex matrix.xlabels (
int
Iterable
None
) – EitherNone
, an iterable of labels for the xaxis, or the dimension of the subsystems where the x axis labels are the computational basis states as inferred from the size of mat. IfNone
, the axis will be labelled by the numbers that index the columns.ylabels (
int
Iterable
None
) – EitherNone
, an iterable of labels for the yaxis, or the dimension of the subsystems where the x axis labels are the computational basis states as inferred from the size of mat. IfNone
, the axis will be labelled by the numbers that index the rows.show_values (
bool
) – Whether to show the numeric values of the matrix in each cell.abs_max (
None
float
) – The value to scale absolute values of the matrix by; the value at which plotted colors become fully opaque. By default, this is the largest absolute magnitude of the input matrix.ax (
matplotlib.Axis
) – An existing axis to plot on. If not given, a new figure will be created.
Compare¶

class
trueq.visualization.plotters.comparisons.
compare
¶ Very generic plotter that compares like estimates across a specified key keyword.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit, names, keyword, label_rotation=0, axes=None, filename=None)¶ Plots a comparison of the value of one or more estimates specified by
names
versus the value ofkeyword
found in each estimate’skey
. Within each subplot, all other keywords and values are constant.import trueq as tq all_circuits = tq.CircuitCollection() for p in [0.01, 0.02, 0.03, 0.04]: circuits = tq.make_srb(0, [4, 20, 40]) tq.Simulator().add_depolarizing(p).run(circuits) all_circuits.append(circuits.update_keys(p_depolarizing=p)) all_circuits.plot.compare("p", "p_depolarizing")
 Parameters
fit (
EstimateCollection
CircuitCollection
) – A collection of circuits or their fit.names (
Iterable
str
) – A name or a list of names specifying which estimate parameters should be included in the plot as yvalues.keyword (
str
) – A keyword found in the the estimates’key
s whose values the given parameters will be compared against.axes (
Iterable
) – An iterable of existing axes. If none are provided, new axes are created. Note that axis instances can be repeated in this list if you want to force the combination of subfigures that would normally be distinct, seeaxes()
for an example.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.

static
Compare Pauli Infidelities¶

class
trueq.visualization.plotters.comparisons.
compare_pauli_infidelities
¶ Plotter that compares Pauli infidelities from CB, SC, and KNR.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit, graph=None, axis_size=8, 3.5, axes=None, filename=None)¶ Plots a comparison of all Pauli infidelities measured by CB, KNR, or SCexperiments. In the case of SC, the process infidelity of the entire cycle, which is the average of all Pauli infidelities, is overlaid. Every unique experiment and sublabel combination is shown on a separate subplot.
import trueq as tq circuits = tq.make_cb({0: tq.Gate.x, 1: tq.Gate.x}, [2, 8]) sim = tq.Simulator().add_stochastic_pauli(pz=0.04).add_overrotation(0.04) sim.run(circuits) circuits.plot.compare_pauli_infidelities()
 Parameters
fit (
EstimateCollection
CircuitCollection
) – A collection of circuits or their fit.graph (
Graph
) – Optionally,Graph
object to display device topologies to the right of each subplot.axis_size (
tuple
) – The width and height of each subplot axis in inches.axes (
Iterable
) – An iterable of existing axes. If none are provided, new axes are created. Note that axis instances can be repeated in this list if you want to force the combination of subfigures that would normally be distinct, seeaxes()
for an example.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.

static
Compare RB¶

class
trueq.visualization.plotters.comparisons.
compare_rb
¶ Compares SRB and XRB infidelities vs twirling groups.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit, axes=None, filename=None)¶ Plots a comparison of process infidelity
e_F
measured by SRB and/or stochastic fidelitye_S
measured by XRB. The comparison is made across twirling groups and is the natural plotting function formake_crosstalk_diagnostics()
.import trueq as tq circuits = tq.make_crosstalk_diagnostics([0, 1, 2], [1, 6]) tq.Simulator().add_depolarizing(0.05).run(circuits) circuits.plot.compare_rb()
 Parameters
fit (
EstimateCollection
CircuitCollection
) – A collection of circuits or their fit.axes (
Iterable
) – An iterable of existing axes. If none are provided, new axes are created. Note that axis instances can be repeated in this list if you want to force the combination of subfigures that would normally be distinct, seeaxes()
for an example.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.

static
Compare Twirl¶

class
trueq.visualization.plotters.comparisons.
compare_twirl
¶ Very generic plotter that compares like estimates across subsystems of a multisystem register.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit, names, axes=None, filename=None)¶ Plots a comparison of the value of one or more estimates specified by
names
. The comparison is made across twirling groups. For example, if some protocol like SRB is performed on qubits in isolation as well as simultaneously, then this function can be used to compare these situations for any of the reported estimates.import trueq as tq circuits = tq.make_crosstalk_diagnostics([0, 1, 2], [1, 6]) tq.Simulator().add_depolarizing(0.05).run(circuits) circuits.plot.compare_twirl("p")
 Parameters
fit (
EstimateCollection
CircuitCollection
) – A collection of circuits or their fit.names (
Iterable
str
) – A name or list of names specifying which estimate parameters should be included in the plot.axes (
Iterable
) – An iterable of existing axes. If none are provided, new axes are created. Note that axis instances can be repeated in this list if you want to force the combination of subfigures that would normally be distinct, seeaxes()
for an example.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.

static
IRB Summary¶

class
trueq.visualization.plotters.irb.
irb_summary
¶ Plots estimate fits from IRB.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit, axes=None, filename=None)¶ Plots data from an IRB experiment. Relevant information from associated SRB and XRB experiments is also shown, see the IRB guide for details.
 Parameters
fit (
EstimateCollection
CircuitCollection
) – A collection of circuits or their fit.axes (
Iterable
) – An iterable of existing axes. If none are provided, new axes are created. Note that axis instances can be repeated in this list if you want to force the combination of subfigures that would normally be distinct, seeaxes()
for an example.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.

static
KNR Heatmap¶

class
trueq.visualization.plotters.nr.
knr_heatmap
¶ Plots KNR data as a heatmap.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit_or_circuits, graph=None, width=None, cutoff=0.2, cutoff_relative_to_max=True, cutoff_ci=0.95, common_ylim=True, single_colorbar=True)¶ Plots all KNR data given in a single figure divided by whitespace into rows and columns of subplots. Each column of subplots corresponds to a unique cycle that was diagnosed with KNR, and each row of subplots corresponds to a different weight of error modes. Yaxis labels indicade which error occurred, and xaxis labels indicate which part of the cycle the error occurred on.
All reported errors are marginal errors. For example, if for a cycle
{0: tq.Gate.id, 1: tq.Gate.id, (2,3): tq.Gate.cnot}
it is reported that \(Z\) error occurs on1: I
with probability 0.1, then this is the sum of the probabilities of all length4 Pauli errors with a \(Z\) on qubit 1. This particular error could in fact be part of a \(Z\otimes Z\) error on qubits 0 and 1 in the context of this cycle; you should look for this term in the heatmap to check.Some Pauli errors cannot be distinguished from each other using the KNR protocol depending on the symmetries of a particular gate. Such indistinguishable errors are grouped together with commas in the ylabels. For example, \(IZ\) cannot be distinguished from \(ZZ\) in a CNOT gate.
 Parameters
fit_or_circuits (
CircuitCollection
EstimateCollection
) – A circuit collection with KNR data, or an estimate collection with KNR fits.graph (
Graph
) – AGraph
object to display device topologies at the top of columns.width (
float
None
) – The width of the figure in inches, orNone
for automatic.cutoff (
float
) – A value below which data will not be displayed; a row of the plot will be hidden if every probability in the row is below the cutoff. This cutoff may be given in relative or absolute units, seecutoff_relative_to_max
.cutoff_relative_to_max (
bool
) – Whethercutoff
is a fraction of the maximum error probability in the entire dataset, or whether it is absolute.cutoff_ci (
float
) – A value of0.95
here indicates that a probability value is considered below cutoff if its estimator is below the cutoff with 95% confidence.common_ylim (
float
bool
) – A common maximum value for every color scale, orTrue
to pick the maximum over all subplots, orFalse
to have a different color scale for every subplot row.single_colorbar (
bool
) – Ifcommon_ylim
is notFalse
, whether to draw a single color bar, or one identical colorbar for each subplot.

static
Raw¶

class
trueq.visualization.plotters.raw.
raw
¶ Very generic plotter that overlays exponential fits onto lightly processed data.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(fit, labels=None, n_columns=3, axes=None, filename=None)¶ Plots a summary of raw data for each applicable circuit collection. Also fits all applicable data to exponential curves and displays this too.
These plots are diagnostic tools which can quickly tell you if your sequence lengths are way off, or if there has been some systematic error in data entry or circuit conversion to your format.
import trueq as tq circuits = tq.make_srb([0, 1], range(5, 50, 5), 20) tq.Simulator().add_overrotation(0.08).add_depolarizing(0.02).run(circuits) # show the exponential decays circuits.plot.raw()
 Parameters
fit (
EstimateCollection
CircuitCollection
) – A collection of circuits or their fit.labels (
Iterable
) – A list of labels (or list of lists of labels) specifying which qubit subset (or list of qubit subsets) to marginalize over.axes (
Iterable
) – An iterable of existing axes. If none are provided, new axes are created. Note that axis instances can be repeated in this list if you want to force the combination of subfigures that would normally be distinct, seeaxes()
for an example.n_columns (
int
) – If new axes are made, how many columns in the grid to use.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.

static
PlottingSuite¶

class
trueq.visualization.plotters.
PlottingSuite
(parent=None)¶ A collection of
Plotter
s, which are accessible as methods of instances of this class. Which plotters are present in the namespace is dependent on the parent object passed in at initialization. For example, a plotting function to do with XRB will only be present if the given parent has data for XRB. Parameters
parent (
EstimateCollection
CircuitCollection
) – A circuit collection or estimate collection to store plotters for.
Timestamps¶

class
trueq.visualization.plotters.timestamps.
timestamps
¶ Plots the timestamps of circuit results.
Note
This class typically should not be invoked directly by users; the main plotting method is exposed dynamically by the attributes
trueq.CircuitCollection.plot
andtrueq.estimate.EstimateCollection.plot
if relevant.
static
plot
(circuits, timezone=None, axis=None, filename=None, **filter)¶ Plots the timestamp of each result in the given circuit collection, sorted by protocol type. These timestamps are taken from the
Results.last_modified
attribute of each circuit with existing results—it is assumed that these values are parsable bydateutil.parser.parse
.The yaxis is meaningless; values are chosen randomly to distinguish circuits with nearly equal timestamps.
import trueq as tq # make 30 circuits circuits = tq.make_srb(0, 5, 30) # this simulator updates the results attribute of each circuit in turn, and # new Results objects get timestamps on instantiation tq.Simulator().run(circuits) circuits.plot.timestamps()
The timezone displayed on the xaxis is set to your local timezone by default, but can be changed to any timezone by providing the
timezone
argument. The displayed timezone is completely independent of any timezone information present in the result timestamps—the relevant conversions takes place automatically. If these timestamps do not contain any timezone information, then it is assumed that they represent UTC times.import trueq as tq # make 30 circuits and populate their results circuits = tq.make_srb(0, 5, 30) tq.Simulator().run(circuits) circuits.plot.timestamps(timezone="Australia/Sydney") # The pytz package is a bit more comprehensive and not OSdependent # You can get timezones from there, too. import pytz # list of all timezones print(pytz.all_timezones[:5] + ["..."]) circuits.plot.timestamps(timezone=pytz.timezone("GMT+0"))
['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', '...']
 Parameters
circuits – A circuit collection.
timezone (
str
datetime.tzinfo
) – The timezone to use on the xaxis.axis (
matplotlib.Axis
) – An existing axis to plot on.filename (
str
) – An optional filename to save the file as. The extension determines the filetype; common choices are “.png”, “.pdf”, and “.svg”. If no extension is given, PNG is chosen.filter – A filter to apply to the datastructure, for example,
circuits.plot.timestamps(protocol="SRB")
.

static