Template code¶
Simulation¶
-
class
qsurface.codes._template.sim.
PerfectMeasurements
(size, **kwargs)¶ Simulation code class for perfect measurements.
The qubits of the code class are stored in a double dictionary, with the keys in the outer dictionary corresponding to the qubit layer. For perfect measurements, there is a single layer. For faulty measurements, there are multiple layers (and defaults to
self.size
). In the nested dictionaries each qubit is stored byqubit.loc
as key. A qubit can thus be accessed byself.qubits[layer][(x,y)]
.The qubit and edge classes from Code elements can be replaced with inherited classes to store decoder dependent attributes.
- Parameters
size (int or tuple) – Size of the surface code in single dimension or two dimensions
(x,y)
.
-
ancilla_qubits
¶ Nested dictionary of
AncillaQubit
objects.- Type
dict of dict
-
pseudo_qubits
¶ Nested dictionary of
PseudoQubit
objects.- Type
dict of dict
-
errors
¶ Dictionary of error modules with the module name as key. All error modules from Error types loaded in
self.errors
will be applied during a simulation byrandom_errors()
.- Type
-
logical_operators
¶ Dictionary with lists of
Edge
objects that from a trivial loop over the surface and correspond to a logical operator. The logical state of each operator can be obtained by the state of each Edge in the list.- Type
dict of list
-
logical_state
¶ Dictionary with the states corresponding to the logical operators in
self.logical_operators
.- Type
dict of bool
-
no_error
¶ Property for whether there is a logical error in the last iteration. The value for
self.no_error
is updated after a call toself.logical_state
.- Type
-
trivial_ancillas
¶ Property for whether all ancillas are trivial. Usefull for checking if decoding has been successfull.
- Type
-
instance
¶ Time stamp that is renewed every time
random_errors
is called. Helps with identifying a ‘round’ of simulation when using class attributes.- Type
-
initialize
(*args, **kwargs)¶ Initializes all data objects of the code.
Builds the surface with
init_surface
, adds the logical operators withinit_logical_operator
, and loads error modules withinit_errors
. All keyword arguments from these methods can be used forinitialize
.
-
abstract
init_surface
()¶ Initiates the surface code.
-
abstract
init_logical_operator
()¶ Initiates the logical operators.
-
init_errors
(*error_modules, error_rates={}, **kwargs)¶ Initializes error modules.
Any error module from Error types can loaded as either a string equivalent to the module file name or as the module itself. The default error rates for all loaded error modules can be supplied as a dictionary with keywords corresponding to the default error rates of the associated error modules.
- Parameters
error_modules (
Union
[str
,Sim
]) – The error modules to load. May be a string or an error module from Error types.error_rates (
dict
) – The default error rates for the loaded modules. Must be a dictionary with probabilities with keywords corresponding to the default or overriding error rates of the associated error modules.
Examples
Load Pauli error and Erasure error modules via string names. Set default bitflip rate to
0.1
and erasure to0.03
.>>> code.init_errors( ... "pauli", ... "erasure", ... error_rates={"p_bitflip": 0.1, "p_erasure": 0.03} ... )
Load Pauli error module via module. Set default phaseflip rate to
0.05
.>>> import .errors.pauli as pauli >>> code.init_errors(pauli, error_rates={"p_phaseflip": 0.05})
-
add_data_qubit
(loc, z=0, initial_states=None, None, **kwargs)¶ Initializes a
DataQubit
and saved toself.data_qubits[z][loc]
.
-
add_ancilla_qubit
(loc, z=0, state_type='x', **kwargs)¶ Initializes a
AncillaQubit
and saved toself.ancilla_qubits[z][loc]
.- Return type
-
add_pseudo_qubit
(loc, z=0, state_type='x', **kwargs)¶ Initializes a
PseudoQubit
and saved toself.pseudo_qubits[z][loc]
.- Return type
-
static
entangle_pair
(data_qubit, ancilla_qubit, key, edge=None, **kwargs)¶ Entangles one
DataQubit
to aAncillaQubit
for parity measurement.- Parameters
data_qubit (
DataQubit
) – Control qubit.ancilla_qubit (
AncillaQubit
) – Controlled qubit.key (
Any
) – The entanglement is saved by adding theDataQubit
toAncillaQubit
.parity_qubits[key]
edge (
Optional
[Edge
]) – The edge of the data-qubit to entangle to.
-
random_errors
(apply_order=None, measure=True, **kwargs)¶ Applies all errors loaded in
self.errors
attribute to layerz
.The random error is applied for each loaded error module by calling
random_error
. Ifapply_order
is specified, the error modules are applied in order of the error names in the list. If no order is specified, the errors are applied in a random order. Addionally, any error rate can set by supplying the rate as a keyword argument e.g.p_bitflip = 0.1
.
-
class
qsurface.codes._template.sim.
FaultyMeasurements
(size, *args, layers=None, p_bitflip_plaq=0, p_bitflip_star=0, **kwargs)¶ Simulation code class for faulty measurements.
A 3D graph is initiated with
layers
amount of 2D surfaces fromPerfectMeasurement
stacked on top of each other. The structure of theself.data_qubits
,self.ancilla_qubits
andself.pseudo_qubits
dictionary attributes allows for the storage for various time instances of the same qubits in the first nested layer. E.g.self.data_qubits[0][(0,0)]
andself.data_qubits[1][(0,0)]
store the data-qubit at (0,0) at time instances 0 and 1, respectively. Consecutive instances ofAncillaQubit
objects andPseudoQubit
objects are connected in the 3D graph byPseudoEdge
objects.- Parameters
-
simulate
(**kwargs)¶ Simulate an iteration or errors and measurement.
On all but the final layer, the default or overriding error rates (via keyworded arguments) are applied. On the final layer, perfect measurements are applied by setting
p_bitflip_plaq=0
andp_bitflip_star=0
.
-
init_surface
(**kwargs)¶ Initiates the surface code.
The 3D lattice is initialized by first building the ground layer. After that each consecutive layer is built and pseudo-edges are added to connect the ancilla qubits of each layer.
-
add_vertical_edge
(lower_ancilla, upper_ancilla, **kwargs)¶ Adds a
PseudoEdge
to connect two instances of an ancilla-qubit in time.A surface code with faulty measurements must be decoded in 3D. Instances of the same ancilla qubits in time must be connected with an edge. Here,
lower_ancilla
is an older instance of layer ‘z’, andupper_ancilla
is a newer instance of layer ‘z+1’.- Parameters
lower_ancilla (
AncillaQubit
) – Older instance of ancilla-qubit.upper_ancilla (
AncillaQubit
) – Newer instance of ancilla-qubit.
-
random_errors
(p_bitflip_plaq=None, p_bitflip_star=None, **kwargs)¶ Performs a round of parity measurements on layer
z
with faulty measurements.
-
random_errors_layer
(**kwargs)¶ Applies a layer of random errors loaded in
self.errors
.- Parameters
kwargs – Keyword arguments are passed on to
random_errors
.
-
add_ancilla_qubit
(loc, z=0, state_type='x', **kwargs)¶ Initializes a
AncillaQubit
and saved toself.ancilla_qubits[z][loc]
.- Return type
-
add_data_qubit
(loc, z=0, initial_states=None, None, **kwargs)¶ Initializes a
DataQubit
and saved toself.data_qubits[z][loc]
.
-
add_pseudo_qubit
(loc, z=0, state_type='x', **kwargs)¶ Initializes a
PseudoQubit
and saved toself.pseudo_qubits[z][loc]
.- Return type
-
static
entangle_pair
(data_qubit, ancilla_qubit, key, edge=None, **kwargs)¶ Entangles one
DataQubit
to aAncillaQubit
for parity measurement.- Parameters
data_qubit (
DataQubit
) – Control qubit.ancilla_qubit (
AncillaQubit
) – Controlled qubit.key (
Any
) – The entanglement is saved by adding theDataQubit
toAncillaQubit
.parity_qubits[key]
edge (
Optional
[Edge
]) – The edge of the data-qubit to entangle to.
-
init_errors
(*error_modules, error_rates={}, **kwargs)¶ Initializes error modules.
Any error module from Error types can loaded as either a string equivalent to the module file name or as the module itself. The default error rates for all loaded error modules can be supplied as a dictionary with keywords corresponding to the default error rates of the associated error modules.
- Parameters
error_modules (
Union
[str
,Sim
]) – The error modules to load. May be a string or an error module from Error types.error_rates (
dict
) – The default error rates for the loaded modules. Must be a dictionary with probabilities with keywords corresponding to the default or overriding error rates of the associated error modules.
Examples
Load Pauli error and Erasure error modules via string names. Set default bitflip rate to
0.1
and erasure to0.03
.>>> code.init_errors( ... "pauli", ... "erasure", ... error_rates={"p_bitflip": 0.1, "p_erasure": 0.03} ... )
Load Pauli error module via module. Set default phaseflip rate to
0.05
.>>> import .errors.pauli as pauli >>> code.init_errors(pauli, error_rates={"p_phaseflip": 0.05})
-
abstract
init_logical_operator
()¶ Initiates the logical operators.
-
initialize
(*args, **kwargs)¶ Initializes all data objects of the code.
Builds the surface with
init_surface
, adds the logical operators withinit_logical_operator
, and loads error modules withinit_errors
. All keyword arguments from these methods can be used forinitialize
.
-
random_measure_layer
(**kwargs)¶ Measures a layer of ancillas.
If the measured state of the current ancilla is not equal to the measured state of the previous instance, the current ancilla is a syndrome.
- Parameters
kwargs – Keyword arguments are passed on to
get_state
.
Plotting¶
-
class
qsurface.codes._template.plot.
PerfectMeasurements
(*args, **kwargs)¶ Plotting template code class for perfect measurements.
-
initialize
(*args, **kwargs)¶ Initializes the code with a figure. Also takes keyword arguments for
init_plot
.Since each error object delivers extra plot properties to the figure, which are dependent on the
self.params
values in the figure itself, we must initialize in the following sequence.First load figure to load
self.params
instance of thePlotParams
dataclass.Initialize lattice, error initialization must have figure properties
Draw figure with plot elements from errors
-
random_errors
(*args, **kwargs)¶ Applies all errors loaded in
self.errors
attribute to layerz
.The random error is applied for each loaded error module by calling
random_error
. Ifapply_order
is specified, the error modules are applied in order of the error names in the list. If no order is specified, the errors are applied in a random order. Addionally, any error rate can set by supplying the rate as a keyword argument e.g.p_bitflip = 0.1
.- Parameters
apply_order – The order in which the error modules are applied. Items in the list must equal keys in
self.errors
or the names of the loaded error modules.measure – Measure ancilla qubits after errors have been simulated.
-
show_corrected
(**kwargs)¶ Redraws the qubits and ancillas to show their states after decoding.
-
plot_data
(iter_name=None, **kwargs)¶ Update plots of all data-qubits. A plot iteration is added if a
iter_name
is supplied. Seedraw_figure
.
-
plot_ancilla
(iter_name=None, **kwargs)¶ Update plots of all ancilla-qubits. A plot iteration is added if a
iter_name
is supplied. Seedraw_figure
.
-
class
Figure
(code, *args, **kwargs)¶ Surface code plot for perfect measurements.
The inner figure class that plots the surface code based on the
Qubit.loc
andQubit.z
values on the set ofcode.data_qubits
,code.ancilla_qubits
andcode.pseudo_qubits
. This allows for a high amount of code inheritance.An additional
matplotlib.widgets.RadioButtons
object is added to the figure which allows for the user to choose one of the loaded errors and apply the error directly to a qubit via_pick_handler
.- Parameters
code (
PerfectMeasurements
) – Surface code instance.kwargs – Keyword arguments are passed on to
plot.Template2D
.
-
code_params
¶ Additional plotting parameters loaded to the
plot.PlotParams
instance atself.params
.
-
init_plot
(**kwargs)¶ Plots all elements of the surface code onto the figure. Also takes keyword arguments for
init_legend
.An additional
matplotlib.widgets.RadioButtons
object is added to the figure which allows for the user to choose one of the loaded errors and apply the error directly to a qubit via_pick_handler
. This object is added via theinit_plot
method to make sure that the errors are already loaded inself.code.errors
. The method for each loaded error is saved toself.error_methods
. Seeerrors._template.Plot
for more information.
-
init_legend
(legend_items=[], **kwargs)¶ Initializes the legend of the main axis of the figure. Also takes keyword arguments for
legend
.The legend of the main axis
self.main_ax
consists of a series ofLine2D
objects. The qubit, vertex and stars are always in the legend for a surface code plot. Any error from Error types loaded in the code atcode.errors
in de outer class will add an extra element to the legend for differentiation if an error occurs. TheLine2D
attributes are stored aterror.Plot.legend_params
of the error module (seeerrors._template.Plot
).- Parameters
legend_items (list of
Line2D
, optional) – Additional elements to the legend.
-
static
change_properties
(artist, prop_dict)¶ Changes the plot properties and draw the plot object or artist.
-
close
()¶ Closes the figure.
-
draw_figure
(new_iter_name=None, output=True, carriage_return=False, **kwargs)¶ Draws the canvas and blocks code execution.
Draws the queued plot changes onto the canvas and calls for
focus()
which blocks the code execution and catches user input for history navigation.If a new iteration is called by supplying a
new_iter_name
, we additionally check for future property changes in theself.future_dict
, and add these changes to the queue. Finally, all queued property changes for the next iteration are applied bychange_properties
.- Parameters
See also
-
focus
()¶ Enables the blocking object, catches input for history navigation.
The BlockingKeyInput object is called which blocks the execution of the code. During this block, the user input is received by the blocking object and return to the current method. From here, we can manipulate the plot or move through the plot history and call
focus()
again when all changes in the history have been drawn and blit.key
function
h
show help
i
show all iterations
d
redraw current iteration
enter or right
go to next iteration, enter iteration number
backspace or left
go to previous iteration
n
go to newest iteration
0-9
input iteration number
When the method is active, the focus is on the figure. This will be indicated by a green circle in the bottom right of the figure. When the focus is lost, the code execution is continued and the icon is red. The change is icon color is performed by
_set_figure_state()
, which also hides the interactive elements when the focus is lost.
-
property
history_at_newest
¶
-
load_interactive_backend
()¶ Configures the plotting backend.
If the Tkinter backend is enabled or can be enabled, the function returns True. For other backends False is returned.
- Return type
-
new_artist
(artist, axis=None)¶ Adds a new artist to the
axis
.Newly added artists must be hidden in the previous iteration. To make sure the history is properly logged, the visibility of the
artist
is set toFalse
, and a new property of shown visibility is added to the queue of the next iteration.
-
new_properties
(artist, properties, saved_properties={}, **kwargs)¶ Parses a dictionary of property changes of a matplotlib artist.
New properties are supplied via
properties
. If any of the new properties is different from its current value, this is seen as a property change. The old property value is stored inself.history_dict[self.history_iteration]
, and the new property value is stored atself.history_dict[self.history_iteration+1]
. These new properties are queued for the next interation. The queue is emptied by applying all changes whendraw_figure
is called. If the same property changes 2+ times within the same iteration, the previous property change is removed withnext_prop.pop(key, None)
.The
saved_properties
parameter is used when temporary property changes have been applied bytemporary_changes
, in which the original properties are saved toself.temporary_saved
as the saved properties. Before a new iteration is drawn, the temporary changes, which can be overwritten, are compared with the saved changes and the differences in properties are saved to[self.history_dict[self.history_iter-1]]
andself.history_dict[self.history_iteration]
.Some color values from different matplotlib objects are nested, some are list or tuple, and others may be a
numpy.ndarray
. The nested methodsget_nested()
andget_nested_property()
make sure that the return type is always a list.
-
temporary_properties
(artist, properties, **kwargs)¶ Applies temporary property changes to a matplotlib artist.
Only available on the newest iteration, as we cannot change what is already in the past. All values in
properties
are immediately applied toartist
. Since temporary changes can be overwritten within the same iteration, the first time a temporary property change is requested, the previous value is saved toself.temporary_saved
. When the iteration changes, the property differences of the previous and current iteration are recomputed and saved toself.history_dict
in_draw_from_history()
.
-
add_ancilla_qubit
(loc, z=0, state_type='x', **kwargs)¶ Initializes a
AncillaQubit
and saved toself.ancilla_qubits[z][loc]
.- Return type
-
add_data_qubit
(loc, z=0, initial_states=None, None, **kwargs)¶ Initializes a
DataQubit
and saved toself.data_qubits[z][loc]
.
-
add_pseudo_qubit
(loc, z=0, state_type='x', **kwargs)¶ Initializes a
PseudoQubit
and saved toself.pseudo_qubits[z][loc]
.- Return type
-
static
entangle_pair
(data_qubit, ancilla_qubit, key, edge=None, **kwargs)¶ Entangles one
DataQubit
to aAncillaQubit
for parity measurement.- Parameters
data_qubit (
DataQubit
) – Control qubit.ancilla_qubit (
AncillaQubit
) – Controlled qubit.key (
Any
) – The entanglement is saved by adding theDataQubit
toAncillaQubit
.parity_qubits[key]
edge (
Optional
[Edge
]) – The edge of the data-qubit to entangle to.
-
init_errors
(*error_modules, error_rates={}, **kwargs)¶ Initializes error modules.
Any error module from Error types can loaded as either a string equivalent to the module file name or as the module itself. The default error rates for all loaded error modules can be supplied as a dictionary with keywords corresponding to the default error rates of the associated error modules.
- Parameters
error_modules (
Union
[str
,Sim
]) – The error modules to load. May be a string or an error module from Error types.error_rates (
dict
) – The default error rates for the loaded modules. Must be a dictionary with probabilities with keywords corresponding to the default or overriding error rates of the associated error modules.
Examples
Load Pauli error and Erasure error modules via string names. Set default bitflip rate to
0.1
and erasure to0.03
.>>> code.init_errors( ... "pauli", ... "erasure", ... error_rates={"p_bitflip": 0.1, "p_erasure": 0.03} ... )
Load Pauli error module via module. Set default phaseflip rate to
0.05
.>>> import .errors.pauli as pauli >>> code.init_errors(pauli, error_rates={"p_phaseflip": 0.05})
-
abstract
init_logical_operator
()¶ Initiates the logical operators.
-
abstract
init_surface
()¶ Initiates the surface code.
-
-
class
qsurface.codes._template.plot.
FaultyMeasurements
(*args, figure3d=True, **kwargs)¶ Plotting template code class for faulty measurements.
Inherits from
codes._template.sim.FaultyMeasurements
andcodes._template.plot.PerfectMeasurements
. See documentation for these classes for more.Dependent on the
figure3d
argument, either a 3D figure object is created that inherits fromTemplate3D
andcodes._template.plot.PerfectMeasurements.Figure
, or the 2Dcodes._template.plot.PerfectMeasurements.Figure
is used.- Parameters
args – Positional arguments are passed on to
codes._template.sim.FaultyMeasurements
.figure3d (
bool
) – Enables plotting on a 3D lattice. Disable to plot layer-by-layer on a 2D lattice, which increases responsiveness.kwargs – Keyword arguments are passed on to
codes._template.sim.FaultyMeasurements
and the figure object.