pygsti.circuits
¶
A subpackage holding circuitrelated objects
Subpackages¶
Submodules¶
Package Contents¶
Classes¶
A quantum circuit. 

A unmutable list (a tuple) of 

Encapsulates a single "plaquette" or "submatrix" within a circuit plot. 

A plaquette whose rows and columns correspond to measurement and preparation fiducial circuits. 

A plaquette whose rows and columns correspond to fiducial pairs and whose base is a germpower. 

Encapsulates a set of circuits, along with an associated structure. 

A label used to identify a gate, circuit layer, or (sub)circuit. 

A quantum circuit. 

A plaquette whose rows and columns correspond to measurement and preparation fiducial circuits. 

A plaquette whose rows and columns correspond to fiducial pairs and whose base is a germpower. 

Encapsulates a set of circuits, along with an associated structure. 

Class responsible for logging things to stdout or a file. 
Functions¶



Create a list of circuits using a nested loop. 

Repeat x num_times times. 

The maximum number of times x can be repeated such that its length is <= max_length. 

Repeat the x an integer number of times such that the result has length <= max_length. 

Repeat and truncate x to yield a sequence with exactly length n. 

Returns the portion truncated by :function:`repeat_and_truncate`. 

Simplify a string representation of a circuit. 

List all the circuits in a given length range. 

Iterative version of :function:`list_all_circuits` 

List all the circuits of a given length. 

Iterative version of :function:`list_all_circuits_onelen` 

List all distinct aperiodic circuits up to a maximum length. 

Create a list of random circuits of a given length. 

List the partial subcircuits of circuit. 

List the circuits required for running LGST. 

Compute the circuits that LGST is able to estimate from dataset and sets of fiducials. 

Converts a list of operation label tuples or strings to a list of 

Translates circuit according to the aliases in alias_dict. 

Applies :function:`translate_circuit` to each element of circuits. 

Composes two alias dicts. 

Manipulates a Circuit object according to rules. 

Applies :function:`manipulate_circuit` to each element of circuits. 

Applies :function:`filter_circuit` to each element of circuits. 

Filters circuit by keeping only a subset of its "lines" (i.e. state space labels, often qubits). 

Applies :function:`manipulate_circuit` to each element of circuits. 

Decorator for deprecating a function. 

Create a set of circuit lists for LSGST based on germs and maxlengths. 

Deprecated function. 

Create a set of longsequence GST circuit lists (including structure). 

List all the circuits (i.e. experiments) required for longsequence GST (LSGST). 

Create a set of circuit lists for eLGST based on germs and maxlengths 

List of all the circuits (i.e. experiments) required for extended LGST (eLGST). 

 class pygsti.circuits.Circuit(layer_labels=(), line_labels='auto', num_lines=None, editable=False, stringrep=None, name='', check=True, expand_subcircuits='default', occurrence=None, compilable_layer_indices=None)¶
Bases:
object
A quantum circuit.
A Circuit represents a quantum circuit, consisting of state preparation, gates, and measurement operations. It is composed of some number of “lines”, typically one per qubit, and stores the operations on these lines as a sequence of
Label
objects, one per circuit layer, whose .sslbls members indicate which line(s) the label belongs on. When a circuit is created with ‘editable=True’, a rich set of operations may be used to construct the circuit in place, after which done_editing() should be called so that the Circuit can be properly hashed as needed. Parameters
layer_labels (iterable of Labels or str) –
This argument provides a list of the layer labels specifying the state preparations, gates, and measurements for the circuit. This argument can also be a
Circuit
or a string, in which case it is parsed as a textformatted circuit. Internally this will eventually be converted to a list of Label objects, one per layer, but it may be specified using anything that can be readily converted to a Label objects. For example, any of the following are allowed:[‘Gx’,’Gx’] : X gate on each of 2 layers
`[Label(‘Gx’),Label(‘Gx’)] : same as above
[(‘Gx’,0),(‘Gy’,0)] : X then Y on qubit 0 (2 layers)
[[(‘Gx’,0),(‘Gx’,1)],[(‘Gy’,0),(‘Gy’,1)]] : parallel X then Y on qubits 0 & 1
line_labels (iterable, optional) – The (string valued) label for each circuit line. If ‘auto’, then line_labels is taken to be the list of all statespace labels present within layer_labels. If there are no such labels (e.g. if layer_labels contains just gate names like (‘Gx’,’Gy’)), then the special value ‘*’ is used as a single line label.
num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines1.
editable (bool, optional) – Whether the created Circuit is created in able to be modified. If True, then you should call done_editing() once the circuit is completely assembled, as this makes the circuit readonly and allows it to be hashed.
stringrep (string, optional) – A string representation for the circuit. If None (the default), then this will be generated automatically when needed. One reason you’d want to specify this is if you know of a nice compact string representation that you’d rather use, e.g. “Gx^4” instead of the automatically generated “GxGxGxGx”. If you want to initialize a Circuit entirely from a string representation you can either specify the string in as layer_labels or set layer_labels to None and stringrep to any valid (oneline) circuit string.
name (str, optional) – A name for this circuit (useful if/when used as a block within larger circuits).
check (bool, optional) – Whether stringrep should be checked against layer_labels to ensure they are consistent, and whether the labels in layer_labels are a subset of line_labels. The only reason you’d want to set this to False is if you’re absolutely sure stringrep and line_labels are consistent and want to save computation time.
expand_subcircuits (bool or "default") – If “default”, then the value of Circuit.default_expand_subcircuits is used. If True, then any subcircuits (e.g. anything exponentiated like “(GxGy)^4”) will be expanded when it is stored within the created Circuit. If False, then such subcircuits will be left asis. It’s typically more robust to expand subcircuits as this facilitates comparison (e.g. so “GxGx” == “Gx^2”), but in cases when you have massive exponents (e.g. “Gx^8192”) it may improve performance to set expand_subcircuits=False.
occurrence (hashable, optional) – A value to set as the “occurrence id” for this circuit. This value doesn’t affect the circuit an any way except by affecting it’s hashing and equivalence testing. Circuits with different occurrence ids are not equivalent. Occurrence values effectively allow multiple copies of the same ciruit to be stored in a dictionary or
DataSet
.compilable_layer_indices (tuple, optional) – The circuitlayer indices that may be internally altered (but retaining the same target operation) and/or combined with the following circuit layer by a hardware compiler.when executing this circuit. Layers that are not “compilable” are effectively followed by a barrier which prevents the hardward compiler from restructuring the circuit across the layer boundary.
 default_expand_subcircuits¶
By default, expand subcircuit labels.
 Type
bool
 line_labels¶
The line labels (often qubit labels) of this circuit.
 Type
tuple
 layertup¶
This Circuit’s layers as a standard Python tuple of layer Labels.
 Type
tuple
 tup¶
This Circuit as a standard Python tuple of layer Labels and line labels.
 Type
tuple
 str¶
The Python string representation of this Circuit.
 Type
str
 default_expand_subcircuits = True¶
 classmethod cast(cls, obj)¶
Convert obj into a
Circuit
. Parameters
obj (object) – Object to convert
 Returns
Circuit
 classmethod from_tuple(cls, tup)¶
Creates a
Circuit
from a tuple Parameters
tup (tuple) – The tuple to convert.
 Returns
Circuit
 classmethod _fastinit(cls, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)¶
 _bare_init(self, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)¶
 to_label(self, nreps=1)¶
Construct and return this entire circuit as a
CircuitLabel
.Note: occurrenceid information is not stored in a circuit label, so circuits that differ only in their occurence_id will return circuit labels that are equal.
 Parameters
nreps (int, optional) – The number of times this circuit will be repeated (CircuitLabels support exponentiation and you can specify this here).
 Returns
CircuitLabel
 property line_labels(self)¶
The line labels (often qubit labels) of this circuit.
 property name(self)¶
The name of this circuit.
Note: the name is not a part of the hashed value. The name is used to name the
CircuitLabel
returned from :method:`to_label`.
 property occurrence(self)¶
The occurrence id of this circuit.
 property layertup(self)¶
This Circuit’s layers as a standard Python tuple of layer Labels.
 Returns
tuple
 property tup(self)¶
This Circuit as a standard Python tuple of layer Labels and line labels.
 Returns
tuple
 property compilable_layer_indices(self)¶
Tuple of the layer indices corresponding to “compilable” layers.
 property compilable_by_layer(self)¶
Boolean array indicating whether each layer is “compilable” or not.
 property str(self)¶
The Python string representation of this Circuit.
 Returns
str
 property layerstr(self)¶
Just the string representation of the circuit layers (no ‘@<line_labels>’ suffix)
 property linesstr(self)¶
Just the string representation of the circuit’s line labels (the ‘@<line_labels>’ suffix)
 _labels_lines_str(self)¶
Split the string representation up into layerlabels & linelabels parts
 __hash__(self)¶
Return hash(self).
 __len__(self)¶
 __iter__(self)¶
 __contains__(self, x)¶
Note: this is not covered by __iter__ for case of contained CircuitLabels
 __radd__(self, x)¶
 __add__(self, x)¶
 repeat(self, ntimes, expand='default')¶
Repeat this circuit ntimes times.
 Parameters
ntimes (int) – Number of repetitions.
expand (bool or "default", optional) – When False, the returned circuit will contain a
CircuitLabel
encapsulating the repetitions without explicitly storing them. When True, the returned circuit will be expanded into the ntimes repetitions. “default” means to use the value in the class variable Circuit.default_expand_subcircuits.
 __mul__(self, x)¶
 __pow__(self, x)¶
 __eq__(self, x)¶
Return self==value.
 __lt__(self, x)¶
Return self<value.
 __gt__(self, x)¶
Return self>value.
 property num_lines(self)¶
The number of lines in this circuit.
 Returns
int
 copy(self, editable='auto')¶
Returns a copy of the circuit.
 Parameters
editable ({True,False,"auto"}) – Whether returned copy is editable. If “auto” is given, then the copy is editable if and only if this Circuit is.
 Returns
Circuit
 clear(self)¶
Removes all the gates in a circuit (preserving the number of lines).
 Returns
None
 _proc_layers_arg(self, layers)¶
Preprocess the layers argument used by many methods
 _proc_lines_arg(self, lines)¶
Preprocess the lines argument used by many methods
 _proc_key_arg(self, key)¶
Preprocess the key argument used by many methods
 _layer_components(self, ilayer)¶
Get the components of the ilayerth layer as a list/tuple.
 _remove_layer_component(self, ilayer, indx)¶
Removes the indxth component from the ilayerth layer
 _append_layer_component(self, ilayer, val)¶
Add val to the ilayerth layer
 _replace_layer_component(self, ilayer, indx, val)¶
 extract_labels(self, layers=None, lines=None, strict=True)¶
Get a subregion  a “rectangle”  of this Circuit.
This can be used to select multiple layers and/or lines of this Circuit. The strict argument controls whether gates need to be entirely within the given rectangle or can be intersecting it. If layers is a single integer then a
Label
is returned (representing a layer or a part of a layer), otherwise aCircuit
is returned. Parameters
layers (int, slice, or list/tuple of ints) – Which layers to select (the horizontal dimension of the selection rectangle). Layers are always selected by index, and this argument can be a single (integer) index  in which case a Label is returned  or multiple indices as given by a slice or list  in which case a Circuit is returned. Note that, even though we speak of a “rectangle”, layer indices do not need to be contiguous. The special value None selects all layers.
lines (str/int, slice, or list/tuple of strs/ints) – Which lines to select (the vertical dimension of the selection rectangle). Lines are selected by their linelabels (elements of the circuit’s .line_labels property), which can be strings and/or integers. A single or multiple linelabels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to select multiple of them. Note that linelabels do not need to be contiguous. The special value None selects all lines.
strict (bool, optional) – When True, only gates lying completely within the selected region are included in the return value. If a gate straddles the region boundary (e.g. if we select just line 1 and the circuit contains “Gcnot:1:2”) then it is silently notincluded in the returned label or circuit. If False, then gates which straddle the region boundary are included. Note that this may result in a Label or Circuit containing more line labels than where requested in the call to extract_labels(…)..
 Returns
Label or Circuit – The requested portion of this circuit, given as a Label if layers is a single integer and as a Circuit otherwise. Note: if you want a Circuit when only selecting one layer, set layers to a slice or tuple containing just a single index.
 set_labels(self, lbls, layers=None, lines=None)¶
Write lbls to the block defined by the layers and lines arguments.
Note that lbls can be anything interpretable as a
Label
or list of labels. Parameters
lbls (Label, list/tuple of Labels, or Circuit) – When layers is a single integer, lbls should be a single “layer label” of type Label. Otherwise, lbls should be a list or tuple of Label objects with length equal to the number of layers being set. A Circuit may also be used in this case.
layers (int, slice, or list/tuple of ints) – Which layers to set (the horizontal dimension of the destination rectangle). Layers are always selected by index, and this argument can be a single (integer) index or multiple indices as given by a slice or list. Note that these indices do not need to be contiguous. The special value None stands for all layers.
lines (str/int, slice, or list/tuple of strs/ints) – Which lines to set (the vertical dimension of the destination rectangle). Lines are selected by their linelabels, which can be strings and/or integers. A single or multiple linelabels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to specify multiple of them. The linelabels do not need to be contiguous. The special value None stands for all lines, and in this case new lines will be created if there are new statespace labels in lbls (when lines is not None an error is raised instead).
 Returns
None
 insert_idling_layers(self, insert_before, num_to_insert, lines=None)¶
Inserts into this circuit one or more idling (blank) layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
num_to_insert (int) – The number of new layers to insert.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple linelabels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.
 Returns
Circuit
 insert_idling_layers_inplace(self, insert_before, num_to_insert, lines=None)¶
Inserts into this circuit one or more idling (blank) layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
num_to_insert (int) – The number of new layers to insert.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple linelabels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.
 Returns
None
 _append_idling_layers_inplace(self, num_to_insert, lines=None)¶
Adds one or more idling (blank) layers to the end of this circuit.
By default, complete layer(s) are appended. The lines argument allows you to add partial layers (on only a subset of the lines).
 Parameters
num_to_insert (int) – The number of new layers to append.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple linelabels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.
 Returns
None
 insert_labels_into_layers(self, lbls, layer_to_insert_before, lines=None)¶
Inserts into this circuit the contents of lbls into new full or partial layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.
 Returns
Circuit
 insert_labels_into_layers_inplace(self, lbls, layer_to_insert_before, lines=None)¶
Inserts into this circuit the contents of lbls into new full or partial layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.
 Returns
None
 insert_idling_lines(self, insert_before, line_labels)¶
Insert one or more idling (blank) lines into this circuit.
 Parameters
insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.
line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).
 Returns
Circuit
 insert_idling_lines_inplace(self, insert_before, line_labels)¶
Insert one or more idling (blank) lines into this circuit.
 Parameters
insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.
line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).
 Returns
None
 _append_idling_lines(self, line_labels)¶
Add one or more idling (blank) lines onto the bottom of this circuit.
 Parameters
line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).
 Returns
None
 insert_labels_as_lines_inplace(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')¶
Inserts into this circuit the contents of lbls into new lines.
By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.
 Parameters
lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The statespace (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.
line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.
line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.
 Returns
None
 insert_labels_as_lines(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')¶
Inserts into this circuit the contents of lbls into new lines.
By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.
 Parameters
lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The statespace (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.
line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.
line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.
 Returns
None
 _append_labels_as_lines(self, lbls, layer_to_insert_before=None, line_labels='auto')¶
Adds the contents of lbls as new lines at the bottom of this circuit.
By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.
 Parameters
lbls (list/tuple of Labels, or Circuit) – A list of layer labels to append as new lines. The statespace (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.
line_labels (list, tuple, or "auto") – The labels of the new lines being added. If “auto”, then these are inferred from lbls.
 Returns
None
 _clear_labels(self, layers, lines, clear_straddlers=False)¶
remove all labels in a block given by layers and lines Note: layers & lines must be lists/tuples of values; they can’t be slices or single vals
 clear_labels(self, layers=None, lines=None, clear_straddlers=False)¶
Removes all the gates within the given circuit region. Does not reduce the number of layers or lines.
 Parameters
layers (int, slice, or list/tuple of ints) – Defines the horizontal dimension of the region to clear. See :method:`extract_labels` for details.
lines (str/int, slice, or list/tuple of strs/ints) – Defines the vertical dimension of the region to clear. See :method:`extract_labels` for details.
clear_straddlers (bool, optional) – Whether or not gates which straddle cleared and noncleared lines should be cleared. If False and straddling gates exist, an error will be raised.
 Returns
None
 delete_layers(self, layers=None)¶
Deletes one or more layers from the circuit.
 Parameters
layers (int, slice, or list/tuple of ints) – The layer index or indices to delete. See :method:`extract_labels` for details.
 Returns
None
 delete_lines(self, lines, delete_straddlers=False)¶
Deletes one or more lines from the circuit.
 Parameters
lines (str/int, slice, or list/tuple of strs/ints) – The line label(s) to delete. See :method:`extract_labels` for details.
delete_straddlers (bool, optional) – Whether or not gates which straddle deleted and nondeleted lines should be removed. If False and straddling gates exist, an error will be raised.
 Returns
None
 __getitem__(self, key)¶
 __setitem__(self, key, val)¶
 __delitem__(self, key)¶
 to_pythonstr(self, op_labels)¶
Convert this circuit to an “encoded” python string.
In the returned string each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This can be useful for processing operation sequences using python’s string tools (regex in particular).
 Parameters
op_labels (tuple) – An iterable containing at least all the layerLabels that appear in this Circuit, and which will be mapped to alphabet characters, beginning with ‘A’.
 Returns
string – The converted operation sequence.
Examples
(‘Gx’,’Gx’,’Gy’,’Gx’) => “AABA”
 classmethod from_pythonstr(cls, python_string, op_labels)¶
Decode an “encoded string” into a
Circuit
.Create a Circuit from a python string where each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This performs the inverse of :method:`to_pythonstr`.
 Parameters
python_string (string) – string whose individual characters correspond to the operation labels of a operation sequence.
op_labels (tuple) – tuple containing all the operation labels that will be mapped from alphabet characters, beginning with ‘A’.
 Returns
Circuit
Examples
“AABA” => (‘Gx’,’Gx’,’Gy’,’Gx’)
 serialize(self)¶
Serialize the parallel gate operations of this Circuit.
Construct a new Circuit whereby all layers containing multiple gates are converted to separate singlegate layers, effectively putting each elementary gate operation into its own layer. Ordering is dictated by the ordering of the compound layer labels.
 Returns
Circuit
 parallelize(self, can_break_labels=True, adjacent_only=False)¶
Compress a circuit’s gates by performing them in parallel.
Construct a circuit with the same underlying labels as this one, but with as many gates performed in parallel as possible (with some restrictions  see the Parameters section below). Generally, gates are moved as far left (toward the start) of the circuit as possible.
 Parameters
can_break_labels (bool, optional) – Whether compound (parallelgate) labels in this Circuit can be separated during the parallelization process. For example, if can_break_labels=True then “Gx:0[Gy:0Gy:1]” => “[Gx:0Gy:1]Gy:0” whereas if can_break_labels=False the result would remain “Gx:0[Gy:0Gy:1]” because [Gy:0Gy:1] cannot be separated.
adjacent_only (bool, optional) – It True, then operation labels are only allowed to move into an adjacent label, that is, they cannot move “through” other operation labels. For example, if adjacent_only=True then “Gx:0Gy:0Gy:1” => “Gx:0[Gy:0Gy:1]” whereas if adjacent_only=False the result would be “[Gx:0Gy:1]Gy:0. Setting this to True is sometimes useful if you want to parallelize a serial string in such a way that subsequently calling .serialize() will give you back the original string.
 Returns
Circuit
 expand_subcircuits_inplace(self)¶
Expands all
CircuitLabel
labels within this circuit.This operation is done in place and so can only be performed on an editable
Circuit
. Returns
None
 expand_subcircuits(self)¶
Returns a new circuit with
CircuitLabel
labels expanded. Returns
Circuit
 factorize_repetitions_inplace(self)¶
Attempt to replace repeated subcircuits with
CircuitLabel
objects.More or less the reverse of :method:`expand_subcircuits`, this method attempts to collapse repetitions of the same labels into single
CircuitLabel
labels within this circuit.This operation is done in place and so can only be performed on an editable
Circuit
. Returns
None
 insert_layer(self, circuit_layer, j)¶
Inserts a single layer into a circuit.
The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.
 Parameters
circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.
j (int) – The layer index (depth) at which to insert the circuit_layer.
 Returns
Circuit
 insert_layer_inplace(self, circuit_layer, j)¶
Inserts a single layer into a circuit.
The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.
 Parameters
circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.
j (int) – The layer index (depth) at which to insert the circuit_layer.
 Returns
None
 insert_circuit(self, circuit, j)¶
Inserts a circuit into this circuit.
The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all nonidling qubits must be a subset of the labels of this circuit.
 Parameters
circuit (Circuit) – The circuit to be inserted.
j (int) – The layer index (depth) at which to insert the circuit.
 Returns
Circuit
 insert_circuit_inplace(self, circuit, j)¶
Inserts a circuit into this circuit.
The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all nonidling qubits must be a subset of the labels of this circuit.
 Parameters
circuit (Circuit) – The circuit to be inserted.
j (int) – The layer index (depth) at which to insert the circuit.
 Returns
None
 append_circuit(self, circuit)¶
Append a circuit to the end of this circuit.
This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be appended.
 Returns
Circuit
 append_circuit_inplace(self, circuit)¶
Append a circuit to the end of this circuit.
This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be appended.
 Returns
None
 prefix_circuit(self, circuit)¶
Prefix a circuit to the beginning of this circuit.
This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be prefixed.
 Returns
Circuit
 prefix_circuit_inplace(self, circuit)¶
Prefix a circuit to the beginning of this circuit.
This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be prefixed.
 Returns
None
 tensor_circuit_inplace(self, circuit, line_order=None)¶
The tensor product of this circuit and circuit.
That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.
 Parameters
circuit (A Circuit object) – The circuit to be tensored.
line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.
 Returns
None
 tensor_circuit(self, circuit, line_order=None)¶
The tensor product of this circuit and circuit.
That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.
 Parameters
circuit (A Circuit object) – The circuit to be tensored.
line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.
 Returns
Circuit
 replace_layer_with_circuit_inplace(self, circuit, j)¶
Replaces the jth layer of this circuit with circuit.
 Parameters
circuit (Circuit) – The circuit to insert
j (int) – The layer index to replace.
 Returns
None
 replace_layer_with_circuit(self, circuit, j)¶
Replaces the jth layer of this circuit with circuit.
 Parameters
circuit (Circuit) – The circuit to insert
j (int) – The layer index to replace.
 Returns
Circuit
 replace_gatename_inplace(self, old_gatename, new_gatename)¶
Changes the name of a gate throughout this Circuit.
Note that the name is only a part of the label identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.
 Parameters
old_gatename (str) – The gate name to replace.
new_gatename (str) – The name to replace old_gatename with.
 Returns
None
 replace_gatename(self, old_gatename, new_gatename)¶
Returns a copy of this Circuit except that old_gatename is changed to new_gatename.
Note that the “name” is only a part of the “label” identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.
 Parameters
old_gatename (str) – The gate name to replace.
new_gatename (str) – The name to replace old_gatename with.
 Returns
Circuit
 replace_gatename_with_idle_inplace(self, gatename)¶
Treats a given gatename as an idle gate throughout this Circuit.
This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.
 Parameters
gatename (str) – The gate name to replace.
 Returns
None
 replace_gatename_with_idle(self, gatename)¶
Returns a copy of this Circuit with a given gatename treated as an idle gate.
This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.
 Parameters
gatename (str) – The gate name to replace.
 Returns
Circuit
 replace_layer(self, old_layer, new_layer)¶
Returns a copy of this Circuit except that old_layer is changed to new_layer.
 replace_layers_with_aliases(self, alias_dict)¶
Performs a find and replace using layer aliases.
Returns a copy of this Circuit except that it’s layers that match keys of alias_dict are replaced with the corresponding values.
 Parameters
alias_dict (dict) – A dictionary whose keys are layer Labels (or equivalent tuples or strings), and whose values are Circuits.
 Returns
Circuit
 change_gate_library(self, compilation, allowed_filter=None, allow_unchanged_gates=False, depth_compression=True, one_q_gate_relations=None)¶
Reexpress a circuit over a different model.
 Parameters
compilation (dict or CompilationLibrary.) –
If a dictionary, the keys are some or all of the gates that appear in the circuit, and the values are replacement circuits that are normally compilations for each of these gates (if they are not, the action of the circuit will be changed). The circuits need not be on all of the qubits, and need only satisfy the requirements of the insert_circuit method. There must be a key for every gate except the self.identity gate, unless allow_unchanged_gates is False. In that case, gate that aren’t a key in this dictionary are left unchanged.
If a CompilationLibrary, this will be queried via the retrieve_compilation_of() method to find compilations for all of the gates in the circuit. So this CompilationLibrary must contain or be able to autogenerate compilations for the requested gates, except when allow_unchanged_gates is True. In that case, gates that a compilation is not returned for are left unchanged.
allowed_filter (dict or set, optional) – Specifies which gates are allowed to be used when generating compilations from compilation. Can only be not None if compilation is a CompilationLibrary. If a dict, keys must be gate names (like “Gcnot”) and values
QubitGraph
objects indicating where that gate (if it’s present in the library) may be used. If a set, then it specifies a set of qubits and any gate in the current library that is confined within that set is allowed. If None, then all gates within the library are allowed.allow_unchanged_gates (bool, optional) – Whether to allow some gates to remain unchanged, and therefore to be absent from compilation. When True such gates are left alone; when False an error is raised if any such gates are encountered.
depth_compression (bool, optional) – Whether to perform depth compression after changing the gate library. If one_q_gate_relations is None this will only remove idle layers and compress the circuit by moving everything as far forward as is possible without knowledge of the action of any gates other than self.identity. See the depth_compression method for more details. Under most circumstances this should be true; if it is False changing gate library will often result in a massive increase in circuit depth.
one_q_gate_relations (dict, optional) – Gate relations for the onequbit gates in the new gate library, that are used in the depth compression, to cancel / combine gates. E.g., one keyvalue pair might be (‘Gh’,’Gh’) : ‘I’, to signify that two Hadamards c ompose to the idle gate ‘Gi’. See the depth_compression() method for more details.
 Returns
None
 map_names_inplace(self, mapper)¶
The names of all of the simple labels are updated inplace according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing gate name values and whose values are the new names (strings) or a function which takes a single (existing name) argument and returns a new name.
 Returns
None
 map_state_space_labels_inplace(self, mapper)¶
The labels of all of the lines (wires/qubits) are updated according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing linelabel) argument and returns a new linelabel.
 Returns
None
 map_state_space_labels(self, mapper)¶
Creates a new Circuit whose line labels are updated according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing linelabel) argument and returns a new linelabel.
 Returns
Circuit
 reorder_lines_inplace(self, order)¶
Reorders the lines (wires/qubits) of the circuit.
Note that the ordering of the lines is unimportant for most purposes.
 Parameters
order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.
 Returns
None
 reorder_lines(self, order)¶
Reorders the lines (wires/qubits) of the circuit.
Note that the ordering of the lines is unimportant for most purposes.
 Parameters
order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.
 Returns
Circuit
 _is_line_idling(self, line_label, idle_layer_labels=None)¶
Whether the line in question is idling in every circuit layer.
 Parameters
line_label (str or int) – The label of the line (i.e., “wire” or qubit).
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
bool – True if the line is idling. False otherwise.
 idling_lines(self, idle_layer_labels=None)¶
Returns the line labels corresponding to idling lines.
 Parameters
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
tuple
 delete_idling_lines_inplace(self, idle_layer_labels=None)¶
Removes from this circuit all lines that are idling at every layer.
 Parameters
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
None
 delete_idling_lines(self, idle_layer_labels=None)¶
Removes from this circuit all lines that are idling at every layer.
 Parameters
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
Circuit
 replace_with_idling_line_inplace(self, line_label, clear_straddlers=True)¶
Converts the specified line to an idling line, by removing all its gates.
If there are any multiqubit gates acting on this line, this function will raise an error when clear_straddlers=False.
 Parameters
line_label (str or int) – The label of the line to convert to an idling line.
clear_straddlers (bool, optional) – Whether or not gates which straddle the line_label should also be cleared. If False and straddling gates exist, an error will be raised.
 Returns
None
 reverse_inplace(self)¶
Reverses the order of the circuit.
 Returns
None
 _combine_one_q_gates_inplace(self, one_q_gate_relations)¶
Compresses sequences of 1qubit gates in the circuit, using the provided gate relations.
One of the steps of the depth_compression() method, and in most cases that method will be more useful.
 Parameters
one_q_gate_relations (dict) –
Keys that are pairs of strings, corresponding to 1qubit gate names, with values that are a single string, also corresponding to a 1qubit gate name. Whenever a 1qubit gate with name name1 is followed in the circuit by a 1qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 > name3 and name2 > self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) > name12, (name12,name3) > name123 etc then the entire sequence of 1qubit gates will be compressed into a single possibly nonidle 1qubit gate followed by idle gates in place of the previous 1qubit gates. Note that None can be used as name3 to signify that the result is the identity (no gate labels).
If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and autogenerated) one_q_gate_relations.
Note that this function will not compress sequences of 1qubit gates that cannot be compressed by independently inspecting sequential nonidle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) > Gypi, even though the sequence is the identity).
 Returns
bool – False if the circuit is unchanged, and True otherwise.
 _shift_gates_forward_inplace(self)¶
Shift all gates forward (left) as far as is possible.
This operation is performed without any knowledge of what any of the gates are. One of the steps of :method:`depth_compression()`.
 Returns
bool – False if the circuit is unchanged, and True otherwise.
 delete_idle_layers_inplace(self)¶
Deletes all layers in this circuit that contain no gate operations.
One of the steps of the depth_compression() method.
 Returns
bool – False if the circuit is unchanged, and True otherwise.
 compress_depth_inplace(self, one_q_gate_relations=None, verbosity=0)¶
Compresses the depth of this circuit using very simple rewrite rules.
If one_q_gate_relations is provided, all sequences of 1qubit gates in the circuit are compressed as far as is possible using only the pairwise combination rules provided by this dict (see below).
All gates are shifted forwarded as far as is possible without any knowledge of what any of the gates are.
All idleonly layers are deleted.
 Parameters
one_q_gate_relations (dict) –
Keys that are pairs of strings, corresponding to 1qubit gate names, with values that are a single string, also corresponding to a 1qubit gate name. Whenever a 1qubit gate with name name1 is followed in the circuit by a 1qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 > name3 and name2 > self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) > name12, (name12,name3) > name123 etc then the entire sequence of 1qubit gates will be compressed into a single possibly nonidle 1qubit gate followed by idle gates in place of the previous 1qubit gates.
If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and autogenerated) one_q_gate_relations.
Note that this function will not compress sequences of 1qubit gates that cannot be compressed by independently inspecting sequential nonidle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) > Gypi, even though the sequence is the identity).
verbosity (int, optional) – If > 0, information about the depth compression is printed to screen.
 Returns
None
 layer(self, j)¶
Returns a tuple of the components, i.e. the (nonidentity) gates, in the layer at depth j.
These are the .components of the
Label
returned by indexing this Circuit (using square brackets) with j, i.e. this returns this_circuit[j].components. Parameters
j (int) – The index (depth) of the layer to be returned
 Returns
tuple
 layer_label(self, j)¶
Returns the layer, as a
Label
, at depth j.This label contains as components all the (nonidentity) gates in the layer..
 Parameters
j (int) – The index (depth) of the layer to be returned
 Returns
Label
 layer_with_idles(self, j, idle_gate_name='I')¶
Returns a tuple of the components of the layer at depth j, with idle_gate_name at empty circuit locations.
This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.
 Parameters
j (int) – The index (depth) of the layer to be returned
idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a
Label
.
 Returns
tuple
 layer_label_with_idles(self, j, idle_gate_name='I')¶
Returns the layer, as a
Label
, at depth j, with idle_gate_name at empty circuit locations.This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.
 Parameters
j (int) – The index (depth) of the layer to be returned
idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a
Label
.
 Returns
Label
 property num_layers(self)¶
The number of circuit layers.
In simple circuits, this is the same as the depth (given by :method:`depth`). For circuits containing subcircuit blocks, this gives the number of toplevel layers in this circuit.
 Returns
int
 property depth(self)¶
The circuit depth.
This is the number of layers in simple circuits. For circuits containing subcircuit blocks, this includes the full depth of these blocks. If you just want the number of toplevel layers, use :method:`num_layers`.
 Returns
int
 property width(self)¶
The circuit width.
This is the number of qubits on which the circuit acts. This includes qubits that only idle, but are included as part of the circuit according to self.line_labels.
 Returns
int
 property size(self)¶
Returns the circuit size.
This is the sum of the sizes of all the gates in the circuit. A gate that acts on nqubits has a size of n, with the exception of the idle which has a size of 0. Hence, the circuit is given by: size = depth * num_lines  num_1Q_idles.
 Returns
int
 property duration(self)¶
 two_q_gate_count(self)¶
The number of twoqubit gates in the circuit.
(Note that this cannot distinguish between “true” 2qubit gates and gate that have been defined to act on two qubits but that represent some tensorproduct gate.)
 Returns
int
 num_nq_gates(self, nq)¶
The number of nqqubit gates in the circuit.
(Note that this cannot distinguish between “true” nqqubit gates and gate that have been defined to act on nq qubits but that represent some tensorproduct gate.)
 Parameters
nq (int) – The qubitcount of the gates to count. For example, if nq == 3, this function returns the number of 3qubit gates.
 Returns
int
 property num_multiq_gates(self)¶
The number of multiqubit (2+ qubits) gates in the circuit.
(Note that this cannot distinguish between “true” multiqubit gates and gate that have been defined to act on more than one qubit but that represent some tensorproduct gate.)
 Returns
int
 _togrid(self, identity_name)¶
return a listoflists rep?
 __str__(self)¶
A text rendering of the circuit.
 __repr__(self)¶
Return repr(self).
 format_display_str(self, width=80)¶
Formats a string for displaying this circuit suject to a maximum width.
 Parameters
width (int, optional) – The maximum width in characters. If the circuit is longer than this width it is wrapped using multiple lines (like a musical score).
 Returns
str
 _print_labelinfo(self)¶
A useful debug routine for printing the internal label structure of a circuit
 abstract _write_q_circuit_tex(self, filename)¶
Writes a LaTeX file for rendering this circuit nicely.
Creates a file containing LaTex that will display this circuit using the Qcircuit.tex LaTex import (compiling the LaTex requires that you have the Qcircuit.tex file).
 Parameters
filename (str) – The file to write the LaTex into. Should end with ‘.tex’
 Returns
None
 convert_to_cirq(self, qubit_conversion, wait_duration=None, gatename_conversion=None, idle_gate_name='Gi')¶
Converts this circuit to a Cirq circuit.
 Parameters
qubit_conversion (dict) – Mapping from qubit labels (e.g. integers) to Cirq qubit objects.
wait_duration (cirq.Duration, optional) – If no gatename_conversion dict is given, the idle operation is not converted to a gate. If wait_diration is specified and gatename_conversion is not specified, then the idle operation will be converted to a cirq.WaitGate with the specified duration.
gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the Cirq gates that will appear in the Cirq circuit. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard Cirq names will be implemented.
idle_gate_name (str, optional) – Name to use for idle gates. Defaults to ‘Gi’
 Returns
A Cirq Circuit object.
 convert_to_quil(self, num_qubits=None, gatename_conversion=None, qubit_conversion=None, readout_conversion=None, block_between_layers=True, block_idles=True, gate_declarations=None)¶
Converts this circuit to a quil string.
 Parameters
num_qubits (int, optional) – The number of qubits for the quil file. If None, then this is assumed to equal the number of line labels in this circuit.
gatename_conversion (dict, optional) – A dictionary mapping gate names contained in this circuit to the corresponding gate names used in the rendered quil. If None, a standard set of conversions is used (see :function:`standard_gatenames_quil_conversions`).
qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the quil output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).
readout_conversion (dict, optional) – If not None, a dictionary converting the qubit labels mapped through qubit_conversion to the bit labels for readot. E.g. Suppose only qubit 2 (on Rigetti hardware) is in use. Then the pyGSTi string will have only one qubit (labeled 0); it will get remapped to 2 via qubit_conversion={0:2}. At the end of the quil circuit, readout should go recorded in bit 0, so readout_conversion = {0:0}. (That is, qubit with pyGSTi label 0 gets read to Rigetti bit 0, even though that qubit has Rigetti label 2.)
block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such “pragma” blocks can be important for QCVV testing, as this can help reduce the “behindthescenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.
block_idles (bool, optional) – In the special case of global idle gates, pragmablock barriers are inserted even when block_between_layers=False. Set block_idles=False to disable this behavior, whcih typically results in global idle gates being removed by the compiler.
gate_declarations (dict, optional) – If not None, a dictionary that provides unitary maps for particular gates that are not already in the quil syntax.
 Returns
str – A quil string.
 convert_to_openqasm(self, num_qubits=None, standard_gates_version='u3', gatename_conversion=None, qubit_conversion=None, block_between_layers=True, block_between_gates=False, gateargs_map=None)¶
Converts this circuit to an openqasm string.
 Parameters
num_qubits (int, optional) – The number of qubits for the openqasm file. If None, then this is assumed to equal the number of line labels in this circuit.
version (string, optional) – Either ‘u3’ or ‘xsxrz’. Specifies the naming convention for the QASM gates. With ‘u3’, all singlequbit gates are specified in terms of the ‘u3’ gate, used by IBM and QisKit until ~2021 (see the qasm_u3 function). With ‘xsxrz’, all singlegates are specified in terms of ‘x’ (an x pi rotation), ‘sx’ (an x pi/2 rotation) and ‘rz’ (a parameterized rotation around z by an angle theta).
gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the gatenames that will appear in the openqasm output. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard openqasm names will be implemented.
qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the openqasm output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).
block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such barriers can be important for QCVV testing, as this can help reduce the “behindthescenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.
gateargs_map (dict, optional) – If not None, a dict that maps strings (representing pyGSTi standard gate names) to functions that map the parameters of a pyGSTi gate to a string to be combined with the QASM name to specify the specific gate, in QASM. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gzr’, ‘Gczr, etc) or none of the gates are parameterized, this dictionary need not be specified, and an automatic conversion to the standard openqasm format will be implemented.
 Returns
str – An openqasm string.
 simulate(self, model, return_all_outcomes=False)¶
Compute the outcome probabilities of this Circuit using model as a model for the gates.
The order of the outcome strings (e.g., ‘0100’) is w.r.t. to the ordering of the qubits in the circuit. That is, the ith element of the outcome string corresponds to the qubit with label self.line_labels[i].
 Parameters
model (Model) – A description of the gate and SPAM operations corresponding to the labels stored in this Circuit. If this model is over more qubits than the circuit, the output will be the probabilities for the qubits in the circuit marginalized, if possible over the other qubits. But, the simulation is over the full set of qubits in the model, and so the time taken for the simulation scales with the number of qubits in the model. For models where “spectator” qubits do not affect the qubits in this circuit (such as with perfect gates), more efficient simulations will be obtained by first creating a model only over the qubits in this circuit.
return_all_outcomes (bool, optional) – Whether to include outcomes in the returned dictionary that have zero probability. When False, the threshold for discarding an outcome as z ero probability is 10^12.
 Returns
probs (dictionary) – A dictionary with keys equal to all (return_all_outcomes is True) or possibly only some (return_all_outcomes is False) of the possible outcomes, and values that are float probabilities.
 done_editing(self)¶
Make this circuit readonly, so that it can be hashed (e.g. used as a dictionary key).
This is done automatically when attempting to hash a
Circuit
for the first time, so there’s calling this function can usually be skipped (but it’s good for code clarity). Returns
None
 expand_instruments_and_separate_povm(self, model, observed_outcomes=None)¶
Creates a dictionary of
SeparatePOVMCircuit
objects from expanding the instruments of this circuit.Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as
SeparatePOVMCircuit
objects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities. Parameters
model (Model) –
The model used to provide necessary details regarding the expansion, including:
default SPAM layers
definitions of instrumentcontaining layers
expansions of individual instruments and POVMs
 Returns
OrderedDict – A dict whose keys are
SeparatePOVMCircuit
objects and whose values are tuples of the outcome labels corresponding to this circuit, one per POVM effect held in the key.
 class pygsti.circuits.CircuitList(circuits, op_label_aliases=None, circuit_rules=None, circuit_weights=None, name=None)¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
A unmutable list (a tuple) of
Circuit
objects and associated metadata. Parameters
circuits (list) – The list of circuits that constitutes the primary data held by this object.
op_label_aliases (dict, optional) – Dictionary of circuit metadata whose keys are operation label “aliases” and whose values are circuits corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined). e.g. op_label_aliases[‘Gx^3’] = pygsti.obj.Circuit([‘Gx’,’Gx’,’Gx’])
circuit_weights (numpy.ndarray, optional) – If not None, an array of percircuit weights (of length equal to the number of circuits) that are typically used to multiply the counts extracted for each circuit.
name (str, optional) – An optional name for this list, used for status messages.
 classmethod cast(cls, circuits)¶
Convert (if needed) an object into a
CircuitList
. Parameters
circuits (list or CircuitList) – The object to convert.
 Returns
CircuitList
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 __len__(self)¶
 __getitem__(self, index)¶
 __iter__(self)¶
 apply_aliases(self)¶
Applies any operationlabel aliases to this circuit list.
 Returns
list – A list of :class:`Circuit`s.
 truncate(self, circuits_to_keep)¶
Builds a new circuit list containing only a given subset.
This can be safer then just creating a new
CircuitList
because it preserves the aliases, etc., of this list. Parameters
circuits_to_keep (list or set) – The circuits to retain in the returned circuit list.
 Returns
CircuitList
 truncate_to_dataset(self, dataset)¶
Builds a new circuit list containing only those elements in dataset.
 Parameters
dataset (DataSet) – The dataset to check. Aliases are applied to the circuits in this circuit list before they are tested.
 Returns
CircuitList
 __hash__(self)¶
Return hash(self).
 __eq__(self, other)¶
Return self==value.
 __setstate__(self, state_dict)¶
 class pygsti.circuits.CircuitPlaquette(elements, num_rows=None, num_cols=None, op_label_aliases=None, circuit_rules=None)¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
Encapsulates a single “plaquette” or “submatrix” within a circuit plot.
 Parameters
elements (dict) – A dictionary with (i,j) keys, where i and j are row and column indices and
Circuit
values.num_rows (int, optional) – The number of rows in this plaquette. If None, then this is set to one larger than the maximum row index in elements.
num_cols (int, optional) – The number of columns in this plaquette. If None, then this is set to one larger than the maximum colum index in elements.
op_label_aliases (dict, optional) – A dictionary of operation label aliases that is carried along for calls to
expand_aliases()
.circuit_rules (list, optional) – A list of (find,replace) 2tuples which specify string replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 _post_from_nice_serialization_init(self, op_label_aliases, circuit_rules)¶
 property circuits(self)¶
 __iter__(self)¶
Iterate over (row_index, col_index, circuit) tuples.
 __len__(self)¶
 elementvec_to_matrix(self, elementvec, layout, mergeop='sum')¶
Form a matrix of values corresponding to this plaquette from an element vector.
An element vector holds individualoutcome elements (e.g. the bulk probabilities computed by a model).
 Parameters
elementvec (numpy array) – An array containting the values to use when constructing a matrix of values for this plaquette. This array may contain more values than are needed by this plaquette. Indices into this array are given by elindices_lookup.
layout (CircuitOutcomeProbabilityArrayLayout) – The layout of elementvec, giving the mapping between its elements and circuit outcomes.
mergeop ("sum" or format string, optional) – Dictates how to combine the elementvec components corresponding to a single plaquette entry (circuit). If “sum”, the returned array contains summed values. If a format string, e.g. “%.2f”, then the soformatted components are joined together with separating commas, and the resulting array contains string (objecttype) entries.
 Returns
numpy array
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
CircuitPlaquette
 expand_aliases(self, ds_filter=None)¶
Returns a new CircuitPlaquette with any aliases expanded.
Aliases are expanded (i.e. applied) within the circuits of this plaquette. Optionally keeps only those strings which, after alias expansion, are in ds_filter.
 Parameters
ds_filter (DataSet, optional) – If not None, keep only strings that are in this data set.
 Returns
CircuitPlaquette
 truncate(self, circuits_to_keep, keep_rows_cols=False)¶
Remove any circuits from this plaquette that aren’t in circuits_to_keep.
 Parameters
circuits_to_keep (list or set) – List of circuits to keep. If None, then a copy of this object is returned.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
CircuitPlaquette
 copy(self)¶
Returns a copy of this CircuitPlaquette.
 Returns
CircuitPlaquette
 summary_label(self)¶
 element_label(self, irow, icol)¶
 class pygsti.circuits.FiducialPairPlaquette(base, fidpairs, num_rows=None, num_cols=None, op_label_aliases=None, circuit_rules=None)¶
Bases:
CircuitPlaquette
A plaquette whose rows and columns correspond to measurement and preparation fiducial circuits.
Theese fiducials sandwich a “base” circuit.
 Parameters
base (Circuit) – The “base” circuit of this plaquette. Typically the sequence that is sandwiched between fiducial pairs.
fidpairs (list or dict) – A list or dict of (prepFiducial, effectFiducial) tuples specifying how elements is generated from base, i.e. by prepFiducial + base + effectFiducial. If a dictionary, then (i, j) keys give the row and column indices of that fiducial pair (in the case of a list, items are placed sequentially by row.
num_rows (int, optional) – The number of rows in this plaquette. If None, then this is set to one larger than the maximum row index in elements.
num_cols (int, optional) – The number of columns in this plaquette. If None, then this is set to one larger than the maximum colum index in elements.
op_label_aliases (dict, optional) – A dictionary of operation label aliases that is carried along for calls to
expand_aliases()
.circuit_rules (list, optional) – A list of (find,replace) 2tuples which specify string replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 _post_from_nice_serialization_init(self, op_label_aliases, circuit_rules)¶
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
CircuitPlaquette
 expand_aliases(self, ds_filter=None)¶
Returns a new CircuitPlaquette with any aliases expanded.
Aliases are expanded (i.e. applied) within the circuits of this plaquette. Optionally keeps only those strings which, after alias expansion, are in ds_filter.
 Parameters
ds_filter (DataSet, optional) – If not None, keep only strings that are in this data set.
 Returns
CircuitPlaquette
 truncate(self, circuits_to_keep, keep_rows_cols=False)¶
Remove any circuits from this plaquette that aren’t in circuits_to_keep.
 Parameters
circuits_to_keep (list or set) – List of circuits to keep. If None, then a copy of this object is returned.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
FiducialPairPlaquette
 copy(self)¶
Returns a copy of this CircuitPlaquette.
 Returns
FiducialPairPlaquette
 summary_label(self)¶
 element_label(self, irow, icol)¶
 class pygsti.circuits.GermFiducialPairPlaquette(germ, power, fidpairs, num_rows=None, num_cols=None, op_label_aliases=None, circuit_rules=None)¶
Bases:
FiducialPairPlaquette
A plaquette whose rows and columns correspond to fiducial pairs and whose base is a germpower.
 Parameters
germ (Circuit) – The “germ” circuit of this plaquette.
power (int) – The number of times germ is repeated to get the base circuit (that is sandwiched between different fiducial pairs).
fidpairs (list or dict) – A list or dict of (prepStr, effectStr) tuples specifying how elements is generated from base, i.e. by prepStr + base + effectStr. If a dictionary, then (i, j) keys give the row and column indices of that fiducial pair (in the case of a list, items are placed sequentially by row.
num_rows (int, optional) – The number of rows in this plaquette. If None, then this is set to one larger than the maximum row index in elements.
num_cols (int, optional) – The number of columns in this plaquette. If None, then this is set to one larger than the maximum colum index in elements.
op_label_aliases (dict, optional) – A dictionary of operation label aliases that is carried along for calls to
expand_aliases()
.circuit_rules (list, optional) – A list of (find,replace) 2tuples which specify string replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 _post_from_nice_serialization_init(self, op_label_aliases, circuit_rules)¶
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
CircuitPlaquette
 expand_aliases(self, ds_filter=None)¶
Returns a new CircuitPlaquette with any aliases expanded.
Aliases are expanded (i.e. applied) within the circuits of this plaquette. Optionally keeps only those strings which, after alias expansion, are in ds_filter.
 Parameters
ds_filter (DataSet, optional) – If not None, keep only strings that are in this data set.
 Returns
CircuitPlaquette
 truncate(self, circuits_to_keep, keep_rows_cols=False)¶
Remove any circuits from this plaquette that aren’t in circuits_to_keep.
 Parameters
circuits_to_keep (list or set) – List of circuits to keep. If None, then a copy of this object is returned.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
GermFiducialPairPlaquette
 copy(self)¶
Returns a copy of this CircuitPlaquette.
 Returns
GermFiducialPairPlaquette
 summary_label(self)¶
 class pygsti.circuits.PlaquetteGridCircuitStructure(plaquettes, x_values, y_values, xlabel, ylabel, additional_circuits=None, op_label_aliases=None, circuit_rules=None, circuit_weights_dict=None, additional_circuits_location='start', name=None)¶
Bases:
pygsti.circuits.circuitlist.CircuitList
Encapsulates a set of circuits, along with an associated structure.
By “structure”, we mean the ability to index the circuits by a 4tuple (x, y, minor_x, minor_y) for displaying in nested color box plots, along with any aliases.
 classmethod cast(cls, circuits_or_structure)¶
Convert (if needed) an object into a circuit structure.
 Parameters
circuits_or_structure (list or CircuitList) – The object to convert. If a
PlaquetteGridCircuitStructure
, then the object is simply returned. Lists of circuits (including :class:`CircuitList`s are converted to structures having no plaquettes. Returns
PlaquetteGridCircuitStructure
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property plaquettes(self)¶
 iter_plaquettes(self)¶
 plaquette(self, x, y, empty_if_missing=False)¶
The plaquette at (x,y).
 Parameters
x (various) – xvalue (not index)
y (various) – yvalue (not index)
empty_if_missing (bool, optional) – Whether an empty (0element) plaquette should be returned when the requested (x,y) is missing.
 Returns
CircuitPlaquette
 property used_xs(self)¶
The xvalues which have at least one nonempty plaquette
 Returns
list
 property used_ys(self)¶
The yvalues which have at least one nonempty plaquette
 Returns
list
 truncate(self, circuits_to_keep=None, xs_to_keep=None, ys_to_keep=None, keep_rows_cols=True)¶
Truncate this circuit structure to a subset of its current circuits.
 Parameters
circuits_to_keep (list) – Keep only the circuits present in this list (of Circuit objects).
xs_to_keep (list, optional) – The xvalues to keep. If None, then all are kept.
ys_to_keep (list, optional) – The yvalues to keep. If None, then all are kept.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty). By default, this is True because we usually want all the plaquettes of a
PlaquetteGridCircuitStructure
to have the same number of rows and columns.
 Returns
PlaquetteGridCircuitStructure
 nested_truncations(self, axis='x', keep_rows_cols=False)¶
Get the nested truncations of this circuit structure along an axis.
When axis == ‘x’, a list of truncations (of this structure) that keep an incrementally larger set of all the xvalues. E.g., if the xvalues are [1,2,4], truncations to [1], [1,2], and [1,2,4] (no truncation) would be returned.
Setting axis ==’y’ gives the same behavior except using the yvalues.
 Parameters
axis ({'x', 'y'}) – Which axis to truncate along (see above).
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
list – A list of
PlaquetteGridCircuitStructure
objects (truncations of this object).
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
PlaquetteGridCircuitStructure
 copy(self)¶
Returns a copy of this circuit structure.
 Returns
PlaquetteGridCircuitStructure
 class pygsti.circuits._Lbl¶
Bases:
object
A label used to identify a gate, circuit layer, or (sub)circuit.
A label consisting of a string along with a tuple of integers or sectornames specifying which qubits, or more generally, parts of the Hilbert space that is acted upon by an object solabeled.
 property depth(self)¶
The depth of this label, viewed as a subcircuit.
 property reps(self)¶
Number of repetitions (of this label’s components) that this label represents.
 property has_nontrivial_components(self)¶
 collect_args(self)¶
 strip_args(self)¶
 expand_subcircuits(self)¶
Expand any subcircuits within this label.
Returns a list of component labels which doesn’t include any
CircuitLabel
labels. This effectively expands any “boxes” or “exponentiation” within this label. Returns
tuple – A tuple of component Labels (none of which should be :class:`CircuitLabel`s).
 pygsti.circuits._run_expression(str_expression, my_locals)¶
 pygsti.circuits.create_circuits(*args, **kwargs)¶
Create a list of circuits using a nested loop.
Positional arguments specify evaluation strings, which are evaluated within the innerloop for a nested loop over all list or tuple type keyword arguments.
 Parameters
args (list of strings) – Positional arguments are strings that python can evaluate into either a tuple of operation labels or a Circuit instance. If evaluation raises an AssertionError (an assert statement fails) then that inner loop evaluation is skipped and list construction proceeds.
kwargs (dict) – keys specify variable names that can be used in positional argument strings.
 Returns
list of Circuit
Examples
>>> from pygsti.circuits import create_circuits >>> As = [('a1',), ('a2',)] >>> Bs = [('b1',), ('b2',)] >>> list1 = create_circuits('a', 'a+b', a=As, b=Bs) >>> print(list(map(str, list1))) ['a1', 'a2', 'a1b1', 'a1b2', 'a2b1', 'a2b2']
You can change the order in which the different iterables are advanced.
>>> list2 = create_circuits('a+b', a=As, b=Bs, order=['a', 'b']) >>> print(list(map(str, list2))) ['a1b1', 'a1b2', 'a2b1', 'a2b2'] >>> list3 = create_circuits('a+b', a=As, b=Bs, order=['b', 'a']) >>> print(list(map(str, list3))) ['a1b1', 'a2b1', 'a1b2', 'a2b2']
 pygsti.circuits.repeat(x, num_times, assert_at_least_one_rep=False)¶
Repeat x num_times times.
 Parameters
x (tuple or Circuit) – the operation sequence to repeat
num_times (int) – the number of times to repeat x
assert_at_least_one_rep (bool, optional) – if True, assert that num_times > 0. This can be useful when used within a create_circuits inner loop to build a operation sequence lists where a string must be repeated at least once to be added to the list.
 Returns
tuple or Circuit (whichever x was)
 pygsti.circuits.repeat_count_with_max_length(x, max_length, assert_at_least_one_rep=False)¶
The maximum number of times x can be repeated such that its length is <= max_length.
 Parameters
x (tuple or Circuit) – the operation sequence to repeat
max_length (int) – the maximum length
assert_at_least_one_rep (bool, optional) – if True, assert that number of repetitions is > 0. This can be useful when used within a create_circuits inner loop to build a operation sequence lists where a string must be repeated at least once to be added to the list.
 Returns
int – the number of repetitions.
 pygsti.circuits.repeat_with_max_length(x, max_length, assert_at_least_one_rep=False)¶
Repeat the x an integer number of times such that the result has length <= max_length.
 Parameters
x (tuple or Circuit) – the operation sequence to repeat.
max_length (int) – the maximum length.
assert_at_least_one_rep (bool, optional) – if True, assert that number of repetitions is > 0. This can be useful when used within a create_circuits inner loop to build a operation sequence lists where a string must be repeated at least once to be added to the list.
 Returns
tuple or Circuit (whichever x was) – the repeated operation sequence
 pygsti.circuits.repeat_and_truncate(x, n, assert_at_least_one_rep=False)¶
Repeat and truncate x to yield a sequence with exactly length n.
Repeats x so the result has length greater than n, then truncates it to have exactly length n.
 Parameters
x (tuple or Circuit) – the operation sequence to repeat & truncate.
n (int) – the truncation length.
assert_at_least_one_rep (bool, optional) – if True, assert that number of repetitions is > 0. This is always the case when x has length > 0.
 Returns
tuple or Circuit (whichever x was) – the repeatedthentruncated operation sequence
 pygsti.circuits._repeat_remainder_for_truncation(x, n, assert_at_least_one_rep=False)¶
Returns the portion truncated by :function:`repeat_and_truncate`.
Repeat the operation sequence x the fewest number of times such that the repeated sequence has length greater than or equal to n. Return the portion of this repeated string from the nth position to the end. Note that this corresponds to what is truncated in a call to repeate_and_truncate(x,n,assert_at_least_one_rep).
 Parameters
x (tuple or Circuit) – the operation sequence to operate on.
n (int) – the truncation length.
assert_at_least_one_rep (bool, optional) – if True, assert that number of repetitions is > 0. This is always the case when x has length > 0.
 Returns
tuple or Circuit (whichever x was) – the remainder operation sequence
 pygsti.circuits._simplify_circuit_string(circuit_str)¶
Simplify a string representation of a circuit.
The simplified string should evaluate to the same operation label tuple as the original.
 Parameters
circuit_str (string) – the string representation of a circuit to be simplified. (e.g. “Gx{}”, “Gy^1Gx”)
 Returns
string – the simplified string representation.
 pygsti.circuits.list_all_circuits(op_labels, minlength, maxlength)¶
List all the circuits in a given length range.
 Parameters
op_labels (tuple) – tuple of operation labels to include in circuits.
minlength (int) – the minimum circuit length to return
maxlength (int) – the maximum circuit length to return
 Returns
list – A list of Circuit objects.
 pygsti.circuits.iter_all_circuits(op_labels, minlength, maxlength)¶
Iterative version of :function:`list_all_circuits`
 Parameters
op_labels (tuple) – tuple of operation labels to include in circuits.
minlength (int) – the minimum circuit length to return
maxlength (int) – the maximum circuit length to return
 pygsti.circuits.list_all_circuits_onelen(op_labels, length)¶
List all the circuits of a given length.
 Parameters
op_labels (tuple) – tuple of operation labels to include in circuits.
length (int) – the circuit length
 Returns
list – A list of Circuit objects.
 pygsti.circuits.iter_all_circuits_onelen(op_labels, length)¶
Iterative version of :function:`list_all_circuits_onelen`
 Parameters
op_labels (tuple) – tuple of operation labels to include in circuits.
length (int) – the circuit length
 pygsti.circuits.list_all_circuits_without_powers_and_cycles(op_labels, max_length)¶
List all distinct aperiodic circuits up to a maximum length.
That is, list all sequences that are not a shorter gate sequence raised to a power, and are also distinct up to cycling (e.g. (‘Gx’,’Gy’,’Gy’) and (‘Gy’,’Gy’,’Gx’) are considered equivalent and only one would be included in the returned list).
 Parameters
op_labels (list) – A list of the operation (gate) labels to form circuits from.
max_length (int) – The maximum length strings to return. Circuits from length 1 to max_length will be returned.
 Returns
list – Of
Circuit
objects.
 pygsti.circuits.list_random_circuits_onelen(op_labels, length, count, seed=None)¶
Create a list of random circuits of a given length.
 Parameters
op_labels (tuple) – tuple of operation labels to include in circuits.
length (int) – the circuit length.
count (int) – the number of random strings to create.
seed (int, optional) – If not None, a seed for numpy’s random number generator.
 Returns
list of Circuits – A list of random circuits as Circuit objects.
 pygsti.circuits.list_partial_circuits(circuit)¶
List the partial subcircuits of circuit.
The “parital circuits” are defined as the slices circuit[0:n] for 0 <= n <= len(circuit).
 Parameters
circuit (tuple of operation labels or Circuit) – The circuit to act upon.
 Returns
list of Circuit objects. – The parial circuits.
 pygsti.circuits.create_lgst_circuits(prep_fiducials, meas_fiducials, op_label_src)¶
List the circuits required for running LGST.
 Parameters
prep_fiducials (list of Circuits) – The preparation fiducial circuits, used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – The measurement fiducial circuits, used to construct an informationally complete effective measurement.
op_label_src (tuple or Model) – List/tuple of operation labels OR a Model whose gate and instrument labels should be used.
 Returns
list of Circuit objects – The list of required circuits, without duplicates.
 pygsti.circuits.list_circuits_lgst_can_estimate(dataset, prep_fiducials, meas_fiducials)¶
Compute the circuits that LGST is able to estimate from dataset and sets of fiducials.
Here “estimate a circuit” means that LGST can estimate the process matrix associated with that circuit.
 Parameters
dataset (DataSet) – The data used to generate the LGST estimates
prep_fiducials (list of Circuits) – The preparation fiducial circuits, used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – The measurement fiducial circuits, used to construct an informationally complete effective measurement.
 Returns
list of lists of tuples – each list of tuples specifyies a circuit that LGST can estimate.
 pygsti.circuits.to_circuits(list_of_op_label_tuples_or_strings, line_labels='auto')¶
Converts a list of operation label tuples or strings to a list of
Circuit
objects. Parameters
list_of_op_label_tuples_or_strings (list) – List which may contain a mix of Circuit objects, tuples of gate labels, and strings in standardtextformat.
line_labels ("auto" or tuple, optional) – The line labels to use when creating Circuit objects from nonCircuit elements of list_of_op_label_tuples_or_strings. If “auto” then the line labels are determined automatically based on the linelabels which are present in the layer labels.
 Returns
list of Circuit objects – Each item of list_of_op_label_tuples_or_strings converted to a Circuit.
 pygsti.circuits.translate_circuit(circuit, alias_dict)¶
Translates circuit according to the aliases in alias_dict.
Creates a new
Circuit
object from an existing one by replacing operation labels in circuit by (possibly multiple) new labels according to alias_dict. Parameters
circuit (Circuit) – The circuit to use as the base for find & replace operations.
alias_dict (dict) – A dictionary whose keys are single operation labels and whose values are lists or tuples of the new operation labels that should replace that key. If alias_dict is None then circuit is returned.
 Returns
Circuit
 pygsti.circuits.translate_circuits(circuits, alias_dict)¶
Applies :function:`translate_circuit` to each element of circuits.
Creates a new list of Circuit objects from an existing one by replacing operation labels in circuits by (possibly multiple) new labels according to alias_dict.
 Parameters
circuits (list of Circuits) – The list of circuits to use as the base for find & replace operations.
alias_dict (dict) – A dictionary whose keys are single operation labels and whose values are lists or tuples of the new operation labels that should replace that key. If alias_dict is None then circuits is returned.
 Returns
list of Circuits
 pygsti.circuits._compose_alias_dicts(alias_dict_1, alias_dict_2)¶
Composes two alias dicts.
Assumes alias_dict_1 maps “A” labels to “B” labels and alias_dict_2 maps “B” labels to “C” labels. The returned dictionary then maps “A” labels directly to “C” labels, and satisfies:
returned[A_label] = alias_dict_2[ alias_dict_1[ A_label ] ]
 Parameters
alias_dict_1 (dict) – The first alias dictionary to compose.
alias_dict_2 (dict) – The second alias dictionary to compose.
 Returns
dict
 pygsti.circuits.manipulate_circuit(circuit, rules, line_labels='auto')¶
Manipulates a Circuit object according to rules.
Each element of rules is of the form (find,replace), and specifies a replacement rule. For example, (‘A’,), (‘B’,’C’) simply replaces each A with B,C. (‘A’, ‘B’), (‘A’, ‘B2’)) replaces B with B2 when it follows A. (‘B’, ‘A’), (‘B2’, ‘A’)) replaces B with B2 when it precedes A.
 Parameters
circuit (Circuit or tuple) – The circuit to manipulate.
rules (list) – A list of (find,replace) 2tuples which specify the replacement rules. Both find and replace are tuples of operation labels (or Circuit objects). If rules is None then circuit is returned.
line_labels ("auto" or tuple, optional) – The line labels to use when creating a the output Circuit objects. If “auto” then the line labels are determined automatically based on the linelabels which are present in the corresponding layer labels.
 Returns
list of Circuits
 pygsti.circuits.manipulate_circuits(circuits, rules, line_labels='auto')¶
Applies :function:`manipulate_circuit` to each element of circuits.
This creates a new list of Circuit objects from an existing one by performing replacements according to rules (see
manipulate_circuit()
). Parameters
circuits (list of Circuits) – The list of circuits to use as the base for find & replace operations.
rules (list) – A list of (find,replace) 2tuples which specify the replacement rules. Both find and replace are tuples of operation labels (or Circuit objects). If rules is None then circuits is returned.
line_labels ("auto" or tuple, optional) – The line labels to use when creating output Circuit objects. If “auto” then the line labels are determined automatically based on the linelabels which are present in the corresponding layer labels.
 Returns
list of Circuits
 pygsti.circuits.filter_circuits(circuits, sslbls_to_keep, new_sslbls=None, drop=False, idle=())¶
Applies :function:`filter_circuit` to each element of circuits.
Removes any labels from circuits whose statespace labels are not entirely in sslbls_to_keep. If a gates label’s statespace labels (its .sslbls) is None, then the label is retained in the returned string.
Furthermore, by specifying new_sslbls one can map the statespace labels in sslbls_to_keep to new labels (useful for “rebasing” a set of qubit strings.
 Parameters
circuits (list) – A list of circuits to act on.
sslbls_to_keep (list) – A list of state space labels specifying which operation labels should be retained.
new_sslbls (list, optional) – If not None, a list of the same length as sslbls_to_keep specifying a new set of state space labels to replace those in sslbls_to_keep.
drop (bool, optional) – If True, then nonempty circuits which become empty after filtering are not included in (i.e. dropped from) the returned list. If False, then the returned list is always the same length as the input list.
idle (string or Label, optional) – The operation label to be used when there are no kept components of a “layer” (element) of a circuit.
 Returns
list – A list of Circuits
 pygsti.circuits.filter_circuit(circuit, sslbls_to_keep, new_sslbls=None, idle=())¶
Filters circuit by keeping only a subset of its “lines” (i.e. state space labels, often qubits).
Removes any labels from circuit whose statespace labels are not entirely in sslbls_to_keep. If a gates label’s statespace labels (its .sslbls) is None, then the label is retained in the returned string.
Furthermore, by specifying new_sslbls one can map the statespace labels in sslbls_to_keep to new labels (useful for “rebasing” a set of qubit strings.
 Parameters
circuit (Circuit) – The circuit to act on.
sslbls_to_keep (list) – A list of state space labels specifying which operation labels should be retained.
new_sslbls (list, optional) – If not None, a list of the same length as sslbls_to_keep specifying a new set of state space labels to replace those in sslbls_to_keep.
idle (string or Label, optional) – The operation label to be used when there are no kept components of a “layer” (element) of circuit.
 Returns
Circuit
 class pygsti.circuits._Circuit(layer_labels=(), line_labels='auto', num_lines=None, editable=False, stringrep=None, name='', check=True, expand_subcircuits='default', occurrence=None, compilable_layer_indices=None)¶
Bases:
object
A quantum circuit.
A Circuit represents a quantum circuit, consisting of state preparation, gates, and measurement operations. It is composed of some number of “lines”, typically one per qubit, and stores the operations on these lines as a sequence of
Label
objects, one per circuit layer, whose .sslbls members indicate which line(s) the label belongs on. When a circuit is created with ‘editable=True’, a rich set of operations may be used to construct the circuit in place, after which done_editing() should be called so that the Circuit can be properly hashed as needed. Parameters
layer_labels (iterable of Labels or str) –
This argument provides a list of the layer labels specifying the state preparations, gates, and measurements for the circuit. This argument can also be a
Circuit
or a string, in which case it is parsed as a textformatted circuit. Internally this will eventually be converted to a list of Label objects, one per layer, but it may be specified using anything that can be readily converted to a Label objects. For example, any of the following are allowed:[‘Gx’,’Gx’] : X gate on each of 2 layers
`[Label(‘Gx’),Label(‘Gx’)] : same as above
[(‘Gx’,0),(‘Gy’,0)] : X then Y on qubit 0 (2 layers)
[[(‘Gx’,0),(‘Gx’,1)],[(‘Gy’,0),(‘Gy’,1)]] : parallel X then Y on qubits 0 & 1
line_labels (iterable, optional) – The (string valued) label for each circuit line. If ‘auto’, then line_labels is taken to be the list of all statespace labels present within layer_labels. If there are no such labels (e.g. if layer_labels contains just gate names like (‘Gx’,’Gy’)), then the special value ‘*’ is used as a single line label.
num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines1.
editable (bool, optional) – Whether the created Circuit is created in able to be modified. If True, then you should call done_editing() once the circuit is completely assembled, as this makes the circuit readonly and allows it to be hashed.
stringrep (string, optional) – A string representation for the circuit. If None (the default), then this will be generated automatically when needed. One reason you’d want to specify this is if you know of a nice compact string representation that you’d rather use, e.g. “Gx^4” instead of the automatically generated “GxGxGxGx”. If you want to initialize a Circuit entirely from a string representation you can either specify the string in as layer_labels or set layer_labels to None and stringrep to any valid (oneline) circuit string.
name (str, optional) – A name for this circuit (useful if/when used as a block within larger circuits).
check (bool, optional) – Whether stringrep should be checked against layer_labels to ensure they are consistent, and whether the labels in layer_labels are a subset of line_labels. The only reason you’d want to set this to False is if you’re absolutely sure stringrep and line_labels are consistent and want to save computation time.
expand_subcircuits (bool or "default") – If “default”, then the value of Circuit.default_expand_subcircuits is used. If True, then any subcircuits (e.g. anything exponentiated like “(GxGy)^4”) will be expanded when it is stored within the created Circuit. If False, then such subcircuits will be left asis. It’s typically more robust to expand subcircuits as this facilitates comparison (e.g. so “GxGx” == “Gx^2”), but in cases when you have massive exponents (e.g. “Gx^8192”) it may improve performance to set expand_subcircuits=False.
occurrence (hashable, optional) – A value to set as the “occurrence id” for this circuit. This value doesn’t affect the circuit an any way except by affecting it’s hashing and equivalence testing. Circuits with different occurrence ids are not equivalent. Occurrence values effectively allow multiple copies of the same ciruit to be stored in a dictionary or
DataSet
.compilable_layer_indices (tuple, optional) – The circuitlayer indices that may be internally altered (but retaining the same target operation) and/or combined with the following circuit layer by a hardware compiler.when executing this circuit. Layers that are not “compilable” are effectively followed by a barrier which prevents the hardward compiler from restructuring the circuit across the layer boundary.
 default_expand_subcircuits¶
By default, expand subcircuit labels.
 Type
bool
 line_labels¶
The line labels (often qubit labels) of this circuit.
 Type
tuple
 layertup¶
This Circuit’s layers as a standard Python tuple of layer Labels.
 Type
tuple
 tup¶
This Circuit as a standard Python tuple of layer Labels and line labels.
 Type
tuple
 str¶
The Python string representation of this Circuit.
 Type
str
 default_expand_subcircuits = True¶
 classmethod cast(cls, obj)¶
Convert obj into a
Circuit
. Parameters
obj (object) – Object to convert
 Returns
Circuit
 classmethod from_tuple(cls, tup)¶
Creates a
Circuit
from a tuple Parameters
tup (tuple) – The tuple to convert.
 Returns
Circuit
 classmethod _fastinit(cls, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)¶
 _bare_init(self, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)¶
 to_label(self, nreps=1)¶
Construct and return this entire circuit as a
CircuitLabel
.Note: occurrenceid information is not stored in a circuit label, so circuits that differ only in their occurence_id will return circuit labels that are equal.
 Parameters
nreps (int, optional) – The number of times this circuit will be repeated (CircuitLabels support exponentiation and you can specify this here).
 Returns
CircuitLabel
 property line_labels(self)¶
The line labels (often qubit labels) of this circuit.
 property name(self)¶
The name of this circuit.
Note: the name is not a part of the hashed value. The name is used to name the
CircuitLabel
returned from :method:`to_label`.
 property occurrence(self)¶
The occurrence id of this circuit.
 property layertup(self)¶
This Circuit’s layers as a standard Python tuple of layer Labels.
 Returns
tuple
 property tup(self)¶
This Circuit as a standard Python tuple of layer Labels and line labels.
 Returns
tuple
 property compilable_layer_indices(self)¶
Tuple of the layer indices corresponding to “compilable” layers.
 property compilable_by_layer(self)¶
Boolean array indicating whether each layer is “compilable” or not.
 property str(self)¶
The Python string representation of this Circuit.
 Returns
str
 property layerstr(self)¶
Just the string representation of the circuit layers (no ‘@<line_labels>’ suffix)
 property linesstr(self)¶
Just the string representation of the circuit’s line labels (the ‘@<line_labels>’ suffix)
 _labels_lines_str(self)¶
Split the string representation up into layerlabels & linelabels parts
 __hash__(self)¶
Return hash(self).
 __len__(self)¶
 __iter__(self)¶
 __contains__(self, x)¶
Note: this is not covered by __iter__ for case of contained CircuitLabels
 __radd__(self, x)¶
 __add__(self, x)¶
 repeat(self, ntimes, expand='default')¶
Repeat this circuit ntimes times.
 Parameters
ntimes (int) – Number of repetitions.
expand (bool or "default", optional) – When False, the returned circuit will contain a
CircuitLabel
encapsulating the repetitions without explicitly storing them. When True, the returned circuit will be expanded into the ntimes repetitions. “default” means to use the value in the class variable Circuit.default_expand_subcircuits.
 __mul__(self, x)¶
 __pow__(self, x)¶
 __eq__(self, x)¶
Return self==value.
 __lt__(self, x)¶
Return self<value.
 __gt__(self, x)¶
Return self>value.
 property num_lines(self)¶
The number of lines in this circuit.
 Returns
int
 copy(self, editable='auto')¶
Returns a copy of the circuit.
 Parameters
editable ({True,False,"auto"}) – Whether returned copy is editable. If “auto” is given, then the copy is editable if and only if this Circuit is.
 Returns
Circuit
 clear(self)¶
Removes all the gates in a circuit (preserving the number of lines).
 Returns
None
 _proc_layers_arg(self, layers)¶
Preprocess the layers argument used by many methods
 _proc_lines_arg(self, lines)¶
Preprocess the lines argument used by many methods
 _proc_key_arg(self, key)¶
Preprocess the key argument used by many methods
 _layer_components(self, ilayer)¶
Get the components of the ilayerth layer as a list/tuple.
 _remove_layer_component(self, ilayer, indx)¶
Removes the indxth component from the ilayerth layer
 _append_layer_component(self, ilayer, val)¶
Add val to the ilayerth layer
 _replace_layer_component(self, ilayer, indx, val)¶
 extract_labels(self, layers=None, lines=None, strict=True)¶
Get a subregion  a “rectangle”  of this Circuit.
This can be used to select multiple layers and/or lines of this Circuit. The strict argument controls whether gates need to be entirely within the given rectangle or can be intersecting it. If layers is a single integer then a
Label
is returned (representing a layer or a part of a layer), otherwise aCircuit
is returned. Parameters
layers (int, slice, or list/tuple of ints) – Which layers to select (the horizontal dimension of the selection rectangle). Layers are always selected by index, and this argument can be a single (integer) index  in which case a Label is returned  or multiple indices as given by a slice or list  in which case a Circuit is returned. Note that, even though we speak of a “rectangle”, layer indices do not need to be contiguous. The special value None selects all layers.
lines (str/int, slice, or list/tuple of strs/ints) – Which lines to select (the vertical dimension of the selection rectangle). Lines are selected by their linelabels (elements of the circuit’s .line_labels property), which can be strings and/or integers. A single or multiple linelabels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to select multiple of them. Note that linelabels do not need to be contiguous. The special value None selects all lines.
strict (bool, optional) – When True, only gates lying completely within the selected region are included in the return value. If a gate straddles the region boundary (e.g. if we select just line 1 and the circuit contains “Gcnot:1:2”) then it is silently notincluded in the returned label or circuit. If False, then gates which straddle the region boundary are included. Note that this may result in a Label or Circuit containing more line labels than where requested in the call to extract_labels(…)..
 Returns
Label or Circuit – The requested portion of this circuit, given as a Label if layers is a single integer and as a Circuit otherwise. Note: if you want a Circuit when only selecting one layer, set layers to a slice or tuple containing just a single index.
 set_labels(self, lbls, layers=None, lines=None)¶
Write lbls to the block defined by the layers and lines arguments.
Note that lbls can be anything interpretable as a
Label
or list of labels. Parameters
lbls (Label, list/tuple of Labels, or Circuit) – When layers is a single integer, lbls should be a single “layer label” of type Label. Otherwise, lbls should be a list or tuple of Label objects with length equal to the number of layers being set. A Circuit may also be used in this case.
layers (int, slice, or list/tuple of ints) – Which layers to set (the horizontal dimension of the destination rectangle). Layers are always selected by index, and this argument can be a single (integer) index or multiple indices as given by a slice or list. Note that these indices do not need to be contiguous. The special value None stands for all layers.
lines (str/int, slice, or list/tuple of strs/ints) – Which lines to set (the vertical dimension of the destination rectangle). Lines are selected by their linelabels, which can be strings and/or integers. A single or multiple linelabels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to specify multiple of them. The linelabels do not need to be contiguous. The special value None stands for all lines, and in this case new lines will be created if there are new statespace labels in lbls (when lines is not None an error is raised instead).
 Returns
None
 insert_idling_layers(self, insert_before, num_to_insert, lines=None)¶
Inserts into this circuit one or more idling (blank) layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
num_to_insert (int) – The number of new layers to insert.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple linelabels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.
 Returns
Circuit
 insert_idling_layers_inplace(self, insert_before, num_to_insert, lines=None)¶
Inserts into this circuit one or more idling (blank) layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
num_to_insert (int) – The number of new layers to insert.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple linelabels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.
 Returns
None
 _append_idling_layers_inplace(self, num_to_insert, lines=None)¶
Adds one or more idling (blank) layers to the end of this circuit.
By default, complete layer(s) are appended. The lines argument allows you to add partial layers (on only a subset of the lines).
 Parameters
num_to_insert (int) – The number of new layers to append.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple linelabels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.
 Returns
None
 insert_labels_into_layers(self, lbls, layer_to_insert_before, lines=None)¶
Inserts into this circuit the contents of lbls into new full or partial layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.
 Returns
Circuit
 insert_labels_into_layers_inplace(self, lbls, layer_to_insert_before, lines=None)¶
Inserts into this circuit the contents of lbls into new full or partial layers.
By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).
 Parameters
lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.
lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.
 Returns
None
 insert_idling_lines(self, insert_before, line_labels)¶
Insert one or more idling (blank) lines into this circuit.
 Parameters
insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.
line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).
 Returns
Circuit
 insert_idling_lines_inplace(self, insert_before, line_labels)¶
Insert one or more idling (blank) lines into this circuit.
 Parameters
insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.
line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).
 Returns
None
 _append_idling_lines(self, line_labels)¶
Add one or more idling (blank) lines onto the bottom of this circuit.
 Parameters
line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).
 Returns
None
 insert_labels_as_lines_inplace(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')¶
Inserts into this circuit the contents of lbls into new lines.
By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.
 Parameters
lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The statespace (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.
line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.
line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.
 Returns
None
 insert_labels_as_lines(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')¶
Inserts into this circuit the contents of lbls into new lines.
By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.
 Parameters
lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The statespace (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.
line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.
line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.
 Returns
None
 _append_labels_as_lines(self, lbls, layer_to_insert_before=None, line_labels='auto')¶
Adds the contents of lbls as new lines at the bottom of this circuit.
By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.
 Parameters
lbls (list/tuple of Labels, or Circuit) – A list of layer labels to append as new lines. The statespace (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.
layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.
line_labels (list, tuple, or "auto") – The labels of the new lines being added. If “auto”, then these are inferred from lbls.
 Returns
None
 _clear_labels(self, layers, lines, clear_straddlers=False)¶
remove all labels in a block given by layers and lines Note: layers & lines must be lists/tuples of values; they can’t be slices or single vals
 clear_labels(self, layers=None, lines=None, clear_straddlers=False)¶
Removes all the gates within the given circuit region. Does not reduce the number of layers or lines.
 Parameters
layers (int, slice, or list/tuple of ints) – Defines the horizontal dimension of the region to clear. See :method:`extract_labels` for details.
lines (str/int, slice, or list/tuple of strs/ints) – Defines the vertical dimension of the region to clear. See :method:`extract_labels` for details.
clear_straddlers (bool, optional) – Whether or not gates which straddle cleared and noncleared lines should be cleared. If False and straddling gates exist, an error will be raised.
 Returns
None
 delete_layers(self, layers=None)¶
Deletes one or more layers from the circuit.
 Parameters
layers (int, slice, or list/tuple of ints) – The layer index or indices to delete. See :method:`extract_labels` for details.
 Returns
None
 delete_lines(self, lines, delete_straddlers=False)¶
Deletes one or more lines from the circuit.
 Parameters
lines (str/int, slice, or list/tuple of strs/ints) – The line label(s) to delete. See :method:`extract_labels` for details.
delete_straddlers (bool, optional) – Whether or not gates which straddle deleted and nondeleted lines should be removed. If False and straddling gates exist, an error will be raised.
 Returns
None
 __getitem__(self, key)¶
 __setitem__(self, key, val)¶
 __delitem__(self, key)¶
 to_pythonstr(self, op_labels)¶
Convert this circuit to an “encoded” python string.
In the returned string each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This can be useful for processing operation sequences using python’s string tools (regex in particular).
 Parameters
op_labels (tuple) – An iterable containing at least all the layerLabels that appear in this Circuit, and which will be mapped to alphabet characters, beginning with ‘A’.
 Returns
string – The converted operation sequence.
Examples
(‘Gx’,’Gx’,’Gy’,’Gx’) => “AABA”
 classmethod from_pythonstr(cls, python_string, op_labels)¶
Decode an “encoded string” into a
Circuit
.Create a Circuit from a python string where each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This performs the inverse of :method:`to_pythonstr`.
 Parameters
python_string (string) – string whose individual characters correspond to the operation labels of a operation sequence.
op_labels (tuple) – tuple containing all the operation labels that will be mapped from alphabet characters, beginning with ‘A’.
 Returns
Circuit
Examples
“AABA” => (‘Gx’,’Gx’,’Gy’,’Gx’)
 serialize(self)¶
Serialize the parallel gate operations of this Circuit.
Construct a new Circuit whereby all layers containing multiple gates are converted to separate singlegate layers, effectively putting each elementary gate operation into its own layer. Ordering is dictated by the ordering of the compound layer labels.
 Returns
Circuit
 parallelize(self, can_break_labels=True, adjacent_only=False)¶
Compress a circuit’s gates by performing them in parallel.
Construct a circuit with the same underlying labels as this one, but with as many gates performed in parallel as possible (with some restrictions  see the Parameters section below). Generally, gates are moved as far left (toward the start) of the circuit as possible.
 Parameters
can_break_labels (bool, optional) – Whether compound (parallelgate) labels in this Circuit can be separated during the parallelization process. For example, if can_break_labels=True then “Gx:0[Gy:0Gy:1]” => “[Gx:0Gy:1]Gy:0” whereas if can_break_labels=False the result would remain “Gx:0[Gy:0Gy:1]” because [Gy:0Gy:1] cannot be separated.
adjacent_only (bool, optional) – It True, then operation labels are only allowed to move into an adjacent label, that is, they cannot move “through” other operation labels. For example, if adjacent_only=True then “Gx:0Gy:0Gy:1” => “Gx:0[Gy:0Gy:1]” whereas if adjacent_only=False the result would be “[Gx:0Gy:1]Gy:0. Setting this to True is sometimes useful if you want to parallelize a serial string in such a way that subsequently calling .serialize() will give you back the original string.
 Returns
Circuit
 expand_subcircuits_inplace(self)¶
Expands all
CircuitLabel
labels within this circuit.This operation is done in place and so can only be performed on an editable
Circuit
. Returns
None
 expand_subcircuits(self)¶
Returns a new circuit with
CircuitLabel
labels expanded. Returns
Circuit
 factorize_repetitions_inplace(self)¶
Attempt to replace repeated subcircuits with
CircuitLabel
objects.More or less the reverse of :method:`expand_subcircuits`, this method attempts to collapse repetitions of the same labels into single
CircuitLabel
labels within this circuit.This operation is done in place and so can only be performed on an editable
Circuit
. Returns
None
 insert_layer(self, circuit_layer, j)¶
Inserts a single layer into a circuit.
The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.
 Parameters
circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.
j (int) – The layer index (depth) at which to insert the circuit_layer.
 Returns
Circuit
 insert_layer_inplace(self, circuit_layer, j)¶
Inserts a single layer into a circuit.
The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.
 Parameters
circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.
j (int) – The layer index (depth) at which to insert the circuit_layer.
 Returns
None
 insert_circuit(self, circuit, j)¶
Inserts a circuit into this circuit.
The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all nonidling qubits must be a subset of the labels of this circuit.
 Parameters
circuit (Circuit) – The circuit to be inserted.
j (int) – The layer index (depth) at which to insert the circuit.
 Returns
Circuit
 insert_circuit_inplace(self, circuit, j)¶
Inserts a circuit into this circuit.
The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all nonidling qubits must be a subset of the labels of this circuit.
 Parameters
circuit (Circuit) – The circuit to be inserted.
j (int) – The layer index (depth) at which to insert the circuit.
 Returns
None
 append_circuit(self, circuit)¶
Append a circuit to the end of this circuit.
This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be appended.
 Returns
Circuit
 append_circuit_inplace(self, circuit)¶
Append a circuit to the end of this circuit.
This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be appended.
 Returns
None
 prefix_circuit(self, circuit)¶
Prefix a circuit to the beginning of this circuit.
This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be prefixed.
 Returns
Circuit
 prefix_circuit_inplace(self, circuit)¶
Prefix a circuit to the beginning of this circuit.
This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.
 Parameters
circuit (A Circuit object) – The circuit to be prefixed.
 Returns
None
 tensor_circuit_inplace(self, circuit, line_order=None)¶
The tensor product of this circuit and circuit.
That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.
 Parameters
circuit (A Circuit object) – The circuit to be tensored.
line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.
 Returns
None
 tensor_circuit(self, circuit, line_order=None)¶
The tensor product of this circuit and circuit.
That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.
 Parameters
circuit (A Circuit object) – The circuit to be tensored.
line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.
 Returns
Circuit
 replace_layer_with_circuit_inplace(self, circuit, j)¶
Replaces the jth layer of this circuit with circuit.
 Parameters
circuit (Circuit) – The circuit to insert
j (int) – The layer index to replace.
 Returns
None
 replace_layer_with_circuit(self, circuit, j)¶
Replaces the jth layer of this circuit with circuit.
 Parameters
circuit (Circuit) – The circuit to insert
j (int) – The layer index to replace.
 Returns
Circuit
 replace_gatename_inplace(self, old_gatename, new_gatename)¶
Changes the name of a gate throughout this Circuit.
Note that the name is only a part of the label identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.
 Parameters
old_gatename (str) – The gate name to replace.
new_gatename (str) – The name to replace old_gatename with.
 Returns
None
 replace_gatename(self, old_gatename, new_gatename)¶
Returns a copy of this Circuit except that old_gatename is changed to new_gatename.
Note that the “name” is only a part of the “label” identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.
 Parameters
old_gatename (str) – The gate name to replace.
new_gatename (str) – The name to replace old_gatename with.
 Returns
Circuit
 replace_gatename_with_idle_inplace(self, gatename)¶
Treats a given gatename as an idle gate throughout this Circuit.
This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.
 Parameters
gatename (str) – The gate name to replace.
 Returns
None
 replace_gatename_with_idle(self, gatename)¶
Returns a copy of this Circuit with a given gatename treated as an idle gate.
This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.
 Parameters
gatename (str) – The gate name to replace.
 Returns
Circuit
 replace_layer(self, old_layer, new_layer)¶
Returns a copy of this Circuit except that old_layer is changed to new_layer.
 replace_layers_with_aliases(self, alias_dict)¶
Performs a find and replace using layer aliases.
Returns a copy of this Circuit except that it’s layers that match keys of alias_dict are replaced with the corresponding values.
 Parameters
alias_dict (dict) – A dictionary whose keys are layer Labels (or equivalent tuples or strings), and whose values are Circuits.
 Returns
Circuit
 change_gate_library(self, compilation, allowed_filter=None, allow_unchanged_gates=False, depth_compression=True, one_q_gate_relations=None)¶
Reexpress a circuit over a different model.
 Parameters
compilation (dict or CompilationLibrary.) –
If a dictionary, the keys are some or all of the gates that appear in the circuit, and the values are replacement circuits that are normally compilations for each of these gates (if they are not, the action of the circuit will be changed). The circuits need not be on all of the qubits, and need only satisfy the requirements of the insert_circuit method. There must be a key for every gate except the self.identity gate, unless allow_unchanged_gates is False. In that case, gate that aren’t a key in this dictionary are left unchanged.
If a CompilationLibrary, this will be queried via the retrieve_compilation_of() method to find compilations for all of the gates in the circuit. So this CompilationLibrary must contain or be able to autogenerate compilations for the requested gates, except when allow_unchanged_gates is True. In that case, gates that a compilation is not returned for are left unchanged.
allowed_filter (dict or set, optional) – Specifies which gates are allowed to be used when generating compilations from compilation. Can only be not None if compilation is a CompilationLibrary. If a dict, keys must be gate names (like “Gcnot”) and values
QubitGraph
objects indicating where that gate (if it’s present in the library) may be used. If a set, then it specifies a set of qubits and any gate in the current library that is confined within that set is allowed. If None, then all gates within the library are allowed.allow_unchanged_gates (bool, optional) – Whether to allow some gates to remain unchanged, and therefore to be absent from compilation. When True such gates are left alone; when False an error is raised if any such gates are encountered.
depth_compression (bool, optional) – Whether to perform depth compression after changing the gate library. If one_q_gate_relations is None this will only remove idle layers and compress the circuit by moving everything as far forward as is possible without knowledge of the action of any gates other than self.identity. See the depth_compression method for more details. Under most circumstances this should be true; if it is False changing gate library will often result in a massive increase in circuit depth.
one_q_gate_relations (dict, optional) – Gate relations for the onequbit gates in the new gate library, that are used in the depth compression, to cancel / combine gates. E.g., one keyvalue pair might be (‘Gh’,’Gh’) : ‘I’, to signify that two Hadamards c ompose to the idle gate ‘Gi’. See the depth_compression() method for more details.
 Returns
None
 map_names_inplace(self, mapper)¶
The names of all of the simple labels are updated inplace according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing gate name values and whose values are the new names (strings) or a function which takes a single (existing name) argument and returns a new name.
 Returns
None
 map_state_space_labels_inplace(self, mapper)¶
The labels of all of the lines (wires/qubits) are updated according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing linelabel) argument and returns a new linelabel.
 Returns
None
 map_state_space_labels(self, mapper)¶
Creates a new Circuit whose line labels are updated according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing linelabel) argument and returns a new linelabel.
 Returns
Circuit
 reorder_lines_inplace(self, order)¶
Reorders the lines (wires/qubits) of the circuit.
Note that the ordering of the lines is unimportant for most purposes.
 Parameters
order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.
 Returns
None
 reorder_lines(self, order)¶
Reorders the lines (wires/qubits) of the circuit.
Note that the ordering of the lines is unimportant for most purposes.
 Parameters
order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.
 Returns
Circuit
 _is_line_idling(self, line_label, idle_layer_labels=None)¶
Whether the line in question is idling in every circuit layer.
 Parameters
line_label (str or int) – The label of the line (i.e., “wire” or qubit).
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
bool – True if the line is idling. False otherwise.
 idling_lines(self, idle_layer_labels=None)¶
Returns the line labels corresponding to idling lines.
 Parameters
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
tuple
 delete_idling_lines_inplace(self, idle_layer_labels=None)¶
Removes from this circuit all lines that are idling at every layer.
 Parameters
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
None
 delete_idling_lines(self, idle_layer_labels=None)¶
Removes from this circuit all lines that are idling at every layer.
 Parameters
idle_layer_labels (iterable, optional) – A list or tuple of layerlabels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.
 Returns
Circuit
 replace_with_idling_line_inplace(self, line_label, clear_straddlers=True)¶
Converts the specified line to an idling line, by removing all its gates.
If there are any multiqubit gates acting on this line, this function will raise an error when clear_straddlers=False.
 Parameters
line_label (str or int) – The label of the line to convert to an idling line.
clear_straddlers (bool, optional) – Whether or not gates which straddle the line_label should also be cleared. If False and straddling gates exist, an error will be raised.
 Returns
None
 reverse_inplace(self)¶
Reverses the order of the circuit.
 Returns
None
 _combine_one_q_gates_inplace(self, one_q_gate_relations)¶
Compresses sequences of 1qubit gates in the circuit, using the provided gate relations.
One of the steps of the depth_compression() method, and in most cases that method will be more useful.
 Parameters
one_q_gate_relations (dict) –
Keys that are pairs of strings, corresponding to 1qubit gate names, with values that are a single string, also corresponding to a 1qubit gate name. Whenever a 1qubit gate with name name1 is followed in the circuit by a 1qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 > name3 and name2 > self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) > name12, (name12,name3) > name123 etc then the entire sequence of 1qubit gates will be compressed into a single possibly nonidle 1qubit gate followed by idle gates in place of the previous 1qubit gates. Note that None can be used as name3 to signify that the result is the identity (no gate labels).
If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and autogenerated) one_q_gate_relations.
Note that this function will not compress sequences of 1qubit gates that cannot be compressed by independently inspecting sequential nonidle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) > Gypi, even though the sequence is the identity).
 Returns
bool – False if the circuit is unchanged, and True otherwise.
 _shift_gates_forward_inplace(self)¶
Shift all gates forward (left) as far as is possible.
This operation is performed without any knowledge of what any of the gates are. One of the steps of :method:`depth_compression()`.
 Returns
bool – False if the circuit is unchanged, and True otherwise.
 delete_idle_layers_inplace(self)¶
Deletes all layers in this circuit that contain no gate operations.
One of the steps of the depth_compression() method.
 Returns
bool – False if the circuit is unchanged, and True otherwise.
 compress_depth_inplace(self, one_q_gate_relations=None, verbosity=0)¶
Compresses the depth of this circuit using very simple rewrite rules.
If one_q_gate_relations is provided, all sequences of 1qubit gates in the circuit are compressed as far as is possible using only the pairwise combination rules provided by this dict (see below).
All gates are shifted forwarded as far as is possible without any knowledge of what any of the gates are.
All idleonly layers are deleted.
 Parameters
one_q_gate_relations (dict) –
Keys that are pairs of strings, corresponding to 1qubit gate names, with values that are a single string, also corresponding to a 1qubit gate name. Whenever a 1qubit gate with name name1 is followed in the circuit by a 1qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 > name3 and name2 > self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) > name12, (name12,name3) > name123 etc then the entire sequence of 1qubit gates will be compressed into a single possibly nonidle 1qubit gate followed by idle gates in place of the previous 1qubit gates.
If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and autogenerated) one_q_gate_relations.
Note that this function will not compress sequences of 1qubit gates that cannot be compressed by independently inspecting sequential nonidle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) > Gypi, even though the sequence is the identity).
verbosity (int, optional) – If > 0, information about the depth compression is printed to screen.
 Returns
None
 layer(self, j)¶
Returns a tuple of the components, i.e. the (nonidentity) gates, in the layer at depth j.
These are the .components of the
Label
returned by indexing this Circuit (using square brackets) with j, i.e. this returns this_circuit[j].components. Parameters
j (int) – The index (depth) of the layer to be returned
 Returns
tuple
 layer_label(self, j)¶
Returns the layer, as a
Label
, at depth j.This label contains as components all the (nonidentity) gates in the layer..
 Parameters
j (int) – The index (depth) of the layer to be returned
 Returns
Label
 layer_with_idles(self, j, idle_gate_name='I')¶
Returns a tuple of the components of the layer at depth j, with idle_gate_name at empty circuit locations.
This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.
 Parameters
j (int) – The index (depth) of the layer to be returned
idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a
Label
.
 Returns
tuple
 layer_label_with_idles(self, j, idle_gate_name='I')¶
Returns the layer, as a
Label
, at depth j, with idle_gate_name at empty circuit locations.This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.
 Parameters
j (int) – The index (depth) of the layer to be returned
idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a
Label
.
 Returns
Label
 property num_layers(self)¶
The number of circuit layers.
In simple circuits, this is the same as the depth (given by :method:`depth`). For circuits containing subcircuit blocks, this gives the number of toplevel layers in this circuit.
 Returns
int
 property depth(self)¶
The circuit depth.
This is the number of layers in simple circuits. For circuits containing subcircuit blocks, this includes the full depth of these blocks. If you just want the number of toplevel layers, use :method:`num_layers`.
 Returns
int
 property width(self)¶
The circuit width.
This is the number of qubits on which the circuit acts. This includes qubits that only idle, but are included as part of the circuit according to self.line_labels.
 Returns
int
 property size(self)¶
Returns the circuit size.
This is the sum of the sizes of all the gates in the circuit. A gate that acts on nqubits has a size of n, with the exception of the idle which has a size of 0. Hence, the circuit is given by: size = depth * num_lines  num_1Q_idles.
 Returns
int
 property duration(self)¶
 two_q_gate_count(self)¶
The number of twoqubit gates in the circuit.
(Note that this cannot distinguish between “true” 2qubit gates and gate that have been defined to act on two qubits but that represent some tensorproduct gate.)
 Returns
int
 num_nq_gates(self, nq)¶
The number of nqqubit gates in the circuit.
(Note that this cannot distinguish between “true” nqqubit gates and gate that have been defined to act on nq qubits but that represent some tensorproduct gate.)
 Parameters
nq (int) – The qubitcount of the gates to count. For example, if nq == 3, this function returns the number of 3qubit gates.
 Returns
int
 property num_multiq_gates(self)¶
The number of multiqubit (2+ qubits) gates in the circuit.
(Note that this cannot distinguish between “true” multiqubit gates and gate that have been defined to act on more than one qubit but that represent some tensorproduct gate.)
 Returns
int
 _togrid(self, identity_name)¶
return a listoflists rep?
 __str__(self)¶
A text rendering of the circuit.
 __repr__(self)¶
Return repr(self).
 format_display_str(self, width=80)¶
Formats a string for displaying this circuit suject to a maximum width.
 Parameters
width (int, optional) – The maximum width in characters. If the circuit is longer than this width it is wrapped using multiple lines (like a musical score).
 Returns
str
 _print_labelinfo(self)¶
A useful debug routine for printing the internal label structure of a circuit
 abstract _write_q_circuit_tex(self, filename)¶
Writes a LaTeX file for rendering this circuit nicely.
Creates a file containing LaTex that will display this circuit using the Qcircuit.tex LaTex import (compiling the LaTex requires that you have the Qcircuit.tex file).
 Parameters
filename (str) – The file to write the LaTex into. Should end with ‘.tex’
 Returns
None
 convert_to_cirq(self, qubit_conversion, wait_duration=None, gatename_conversion=None, idle_gate_name='Gi')¶
Converts this circuit to a Cirq circuit.
 Parameters
qubit_conversion (dict) – Mapping from qubit labels (e.g. integers) to Cirq qubit objects.
wait_duration (cirq.Duration, optional) – If no gatename_conversion dict is given, the idle operation is not converted to a gate. If wait_diration is specified and gatename_conversion is not specified, then the idle operation will be converted to a cirq.WaitGate with the specified duration.
gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the Cirq gates that will appear in the Cirq circuit. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard Cirq names will be implemented.
idle_gate_name (str, optional) – Name to use for idle gates. Defaults to ‘Gi’
 Returns
A Cirq Circuit object.
 convert_to_quil(self, num_qubits=None, gatename_conversion=None, qubit_conversion=None, readout_conversion=None, block_between_layers=True, block_idles=True, gate_declarations=None)¶
Converts this circuit to a quil string.
 Parameters
num_qubits (int, optional) – The number of qubits for the quil file. If None, then this is assumed to equal the number of line labels in this circuit.
gatename_conversion (dict, optional) – A dictionary mapping gate names contained in this circuit to the corresponding gate names used in the rendered quil. If None, a standard set of conversions is used (see :function:`standard_gatenames_quil_conversions`).
qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the quil output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).
readout_conversion (dict, optional) – If not None, a dictionary converting the qubit labels mapped through qubit_conversion to the bit labels for readot. E.g. Suppose only qubit 2 (on Rigetti hardware) is in use. Then the pyGSTi string will have only one qubit (labeled 0); it will get remapped to 2 via qubit_conversion={0:2}. At the end of the quil circuit, readout should go recorded in bit 0, so readout_conversion = {0:0}. (That is, qubit with pyGSTi label 0 gets read to Rigetti bit 0, even though that qubit has Rigetti label 2.)
block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such “pragma” blocks can be important for QCVV testing, as this can help reduce the “behindthescenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.
block_idles (bool, optional) – In the special case of global idle gates, pragmablock barriers are inserted even when block_between_layers=False. Set block_idles=False to disable this behavior, whcih typically results in global idle gates being removed by the compiler.
gate_declarations (dict, optional) – If not None, a dictionary that provides unitary maps for particular gates that are not already in the quil syntax.
 Returns
str – A quil string.
 convert_to_openqasm(self, num_qubits=None, standard_gates_version='u3', gatename_conversion=None, qubit_conversion=None, block_between_layers=True, block_between_gates=False, gateargs_map=None)¶
Converts this circuit to an openqasm string.
 Parameters
num_qubits (int, optional) – The number of qubits for the openqasm file. If None, then this is assumed to equal the number of line labels in this circuit.
version (string, optional) – Either ‘u3’ or ‘xsxrz’. Specifies the naming convention for the QASM gates. With ‘u3’, all singlequbit gates are specified in terms of the ‘u3’ gate, used by IBM and QisKit until ~2021 (see the qasm_u3 function). With ‘xsxrz’, all singlegates are specified in terms of ‘x’ (an x pi rotation), ‘sx’ (an x pi/2 rotation) and ‘rz’ (a parameterized rotation around z by an angle theta).
gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the gatenames that will appear in the openqasm output. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard openqasm names will be implemented.
qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the openqasm output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).
block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such barriers can be important for QCVV testing, as this can help reduce the “behindthescenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.
gateargs_map (dict, optional) – If not None, a dict that maps strings (representing pyGSTi standard gate names) to functions that map the parameters of a pyGSTi gate to a string to be combined with the QASM name to specify the specific gate, in QASM. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gzr’, ‘Gczr, etc) or none of the gates are parameterized, this dictionary need not be specified, and an automatic conversion to the standard openqasm format will be implemented.
 Returns
str – An openqasm string.
 simulate(self, model, return_all_outcomes=False)¶
Compute the outcome probabilities of this Circuit using model as a model for the gates.
The order of the outcome strings (e.g., ‘0100’) is w.r.t. to the ordering of the qubits in the circuit. That is, the ith element of the outcome string corresponds to the qubit with label self.line_labels[i].
 Parameters
model (Model) – A description of the gate and SPAM operations corresponding to the labels stored in this Circuit. If this model is over more qubits than the circuit, the output will be the probabilities for the qubits in the circuit marginalized, if possible over the other qubits. But, the simulation is over the full set of qubits in the model, and so the time taken for the simulation scales with the number of qubits in the model. For models where “spectator” qubits do not affect the qubits in this circuit (such as with perfect gates), more efficient simulations will be obtained by first creating a model only over the qubits in this circuit.
return_all_outcomes (bool, optional) – Whether to include outcomes in the returned dictionary that have zero probability. When False, the threshold for discarding an outcome as z ero probability is 10^12.
 Returns
probs (dictionary) – A dictionary with keys equal to all (return_all_outcomes is True) or possibly only some (return_all_outcomes is False) of the possible outcomes, and values that are float probabilities.
 done_editing(self)¶
Make this circuit readonly, so that it can be hashed (e.g. used as a dictionary key).
This is done automatically when attempting to hash a
Circuit
for the first time, so there’s calling this function can usually be skipped (but it’s good for code clarity). Returns
None
 expand_instruments_and_separate_povm(self, model, observed_outcomes=None)¶
Creates a dictionary of
SeparatePOVMCircuit
objects from expanding the instruments of this circuit.Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as
SeparatePOVMCircuit
objects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities. Parameters
model (Model) –
The model used to provide necessary details regarding the expansion, including:
default SPAM layers
definitions of instrumentcontaining layers
expansions of individual instruments and POVMs
 Returns
OrderedDict – A dict whose keys are
SeparatePOVMCircuit
objects and whose values are tuples of the outcome labels corresponding to this circuit, one per POVM effect held in the key.
 class pygsti.circuits._FiducialPairPlaquette(base, fidpairs, num_rows=None, num_cols=None, op_label_aliases=None, circuit_rules=None)¶
Bases:
CircuitPlaquette
A plaquette whose rows and columns correspond to measurement and preparation fiducial circuits.
Theese fiducials sandwich a “base” circuit.
 Parameters
base (Circuit) – The “base” circuit of this plaquette. Typically the sequence that is sandwiched between fiducial pairs.
fidpairs (list or dict) – A list or dict of (prepFiducial, effectFiducial) tuples specifying how elements is generated from base, i.e. by prepFiducial + base + effectFiducial. If a dictionary, then (i, j) keys give the row and column indices of that fiducial pair (in the case of a list, items are placed sequentially by row.
num_rows (int, optional) – The number of rows in this plaquette. If None, then this is set to one larger than the maximum row index in elements.
num_cols (int, optional) – The number of columns in this plaquette. If None, then this is set to one larger than the maximum colum index in elements.
op_label_aliases (dict, optional) – A dictionary of operation label aliases that is carried along for calls to
expand_aliases()
.circuit_rules (list, optional) – A list of (find,replace) 2tuples which specify string replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 _post_from_nice_serialization_init(self, op_label_aliases, circuit_rules)¶
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
CircuitPlaquette
 expand_aliases(self, ds_filter=None)¶
Returns a new CircuitPlaquette with any aliases expanded.
Aliases are expanded (i.e. applied) within the circuits of this plaquette. Optionally keeps only those strings which, after alias expansion, are in ds_filter.
 Parameters
ds_filter (DataSet, optional) – If not None, keep only strings that are in this data set.
 Returns
CircuitPlaquette
 truncate(self, circuits_to_keep, keep_rows_cols=False)¶
Remove any circuits from this plaquette that aren’t in circuits_to_keep.
 Parameters
circuits_to_keep (list or set) – List of circuits to keep. If None, then a copy of this object is returned.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
FiducialPairPlaquette
 copy(self)¶
Returns a copy of this CircuitPlaquette.
 Returns
FiducialPairPlaquette
 summary_label(self)¶
 element_label(self, irow, icol)¶
 class pygsti.circuits._GermFiducialPairPlaquette(germ, power, fidpairs, num_rows=None, num_cols=None, op_label_aliases=None, circuit_rules=None)¶
Bases:
FiducialPairPlaquette
A plaquette whose rows and columns correspond to fiducial pairs and whose base is a germpower.
 Parameters
germ (Circuit) – The “germ” circuit of this plaquette.
power (int) – The number of times germ is repeated to get the base circuit (that is sandwiched between different fiducial pairs).
fidpairs (list or dict) – A list or dict of (prepStr, effectStr) tuples specifying how elements is generated from base, i.e. by prepStr + base + effectStr. If a dictionary, then (i, j) keys give the row and column indices of that fiducial pair (in the case of a list, items are placed sequentially by row.
num_rows (int, optional) – The number of rows in this plaquette. If None, then this is set to one larger than the maximum row index in elements.
num_cols (int, optional) – The number of columns in this plaquette. If None, then this is set to one larger than the maximum colum index in elements.
op_label_aliases (dict, optional) – A dictionary of operation label aliases that is carried along for calls to
expand_aliases()
.circuit_rules (list, optional) – A list of (find,replace) 2tuples which specify string replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 _post_from_nice_serialization_init(self, op_label_aliases, circuit_rules)¶
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
CircuitPlaquette
 expand_aliases(self, ds_filter=None)¶
Returns a new CircuitPlaquette with any aliases expanded.
Aliases are expanded (i.e. applied) within the circuits of this plaquette. Optionally keeps only those strings which, after alias expansion, are in ds_filter.
 Parameters
ds_filter (DataSet, optional) – If not None, keep only strings that are in this data set.
 Returns
CircuitPlaquette
 truncate(self, circuits_to_keep, keep_rows_cols=False)¶
Remove any circuits from this plaquette that aren’t in circuits_to_keep.
 Parameters
circuits_to_keep (list or set) – List of circuits to keep. If None, then a copy of this object is returned.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
GermFiducialPairPlaquette
 copy(self)¶
Returns a copy of this CircuitPlaquette.
 Returns
GermFiducialPairPlaquette
 summary_label(self)¶
 class pygsti.circuits._PlaquetteGridCircuitStructure(plaquettes, x_values, y_values, xlabel, ylabel, additional_circuits=None, op_label_aliases=None, circuit_rules=None, circuit_weights_dict=None, additional_circuits_location='start', name=None)¶
Bases:
pygsti.circuits.circuitlist.CircuitList
Encapsulates a set of circuits, along with an associated structure.
By “structure”, we mean the ability to index the circuits by a 4tuple (x, y, minor_x, minor_y) for displaying in nested color box plots, along with any aliases.
 classmethod cast(cls, circuits_or_structure)¶
Convert (if needed) an object into a circuit structure.
 Parameters
circuits_or_structure (list or CircuitList) – The object to convert. If a
PlaquetteGridCircuitStructure
, then the object is simply returned. Lists of circuits (including :class:`CircuitList`s are converted to structures having no plaquettes. Returns
PlaquetteGridCircuitStructure
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property plaquettes(self)¶
 iter_plaquettes(self)¶
 plaquette(self, x, y, empty_if_missing=False)¶
The plaquette at (x,y).
 Parameters
x (various) – xvalue (not index)
y (various) – yvalue (not index)
empty_if_missing (bool, optional) – Whether an empty (0element) plaquette should be returned when the requested (x,y) is missing.
 Returns
CircuitPlaquette
 property used_xs(self)¶
The xvalues which have at least one nonempty plaquette
 Returns
list
 property used_ys(self)¶
The yvalues which have at least one nonempty plaquette
 Returns
list
 truncate(self, circuits_to_keep=None, xs_to_keep=None, ys_to_keep=None, keep_rows_cols=True)¶
Truncate this circuit structure to a subset of its current circuits.
 Parameters
circuits_to_keep (list) – Keep only the circuits present in this list (of Circuit objects).
xs_to_keep (list, optional) – The xvalues to keep. If None, then all are kept.
ys_to_keep (list, optional) – The yvalues to keep. If None, then all are kept.
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty). By default, this is True because we usually want all the plaquettes of a
PlaquetteGridCircuitStructure
to have the same number of rows and columns.
 Returns
PlaquetteGridCircuitStructure
 nested_truncations(self, axis='x', keep_rows_cols=False)¶
Get the nested truncations of this circuit structure along an axis.
When axis == ‘x’, a list of truncations (of this structure) that keep an incrementally larger set of all the xvalues. E.g., if the xvalues are [1,2,4], truncations to [1], [1,2], and [1,2,4] (no truncation) would be returned.
Setting axis ==’y’ gives the same behavior except using the yvalues.
 Parameters
axis ({'x', 'y'}) – Which axis to truncate along (see above).
keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).
 Returns
list – A list of
PlaquetteGridCircuitStructure
objects (truncations of this object).
 process_circuits(self, processor_fn, updated_aliases=None)¶
Create a new plaquette with circuits manipulated according to processor_fn.
 Parameters
processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.
updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label > Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.
 Returns
PlaquetteGridCircuitStructure
 copy(self)¶
Returns a copy of this circuit structure.
 Returns
PlaquetteGridCircuitStructure
 pygsti.circuits._manipulate_circuits(circuits, rules, line_labels='auto')¶
Applies :function:`manipulate_circuit` to each element of circuits.
This creates a new list of Circuit objects from an existing one by performing replacements according to rules (see
manipulate_circuit()
). Parameters
circuits (list of Circuits) – The list of circuits to use as the base for find & replace operations.
rules (list) – A list of (find,replace) 2tuples which specify the replacement rules. Both find and replace are tuples of operation labels (or Circuit objects). If rules is None then circuits is returned.
line_labels ("auto" or tuple, optional) – The line labels to use when creating output Circuit objects. If “auto” then the line labels are determined automatically based on the linelabels which are present in the corresponding layer labels.
 Returns
list of Circuits
 class pygsti.circuits._VerbosityPrinter(verbosity=1, filename=None, comm=None, warnings=True, split=False, clear_file=True)¶
Bases:
object
Class responsible for logging things to stdout or a file.
Controls verbosity and can print progress bars. ex:
>>> VerbosityPrinter(1)
would construct a printer that printed out messages of level one or higher to the screen.
>>> VerbosityPrinter(3, 'output.txt')
would construct a printer that sends verbose output to a text file
The static function
create_printer()
will construct a printer from either an integer or an already existing printer. it is a static method of the VerbosityPrinter class, so it is called like so:>>> VerbosityPrinter.create_printer(2)
or
>>> VerbostityPrinter.create_printer(VerbosityPrinter(3, 'output.txt'))
printer.log('status')
would log ‘status’ if the printers verbosity was one or higher.printer.log('status2', 2)
would log ‘status2’ if the printer’s verbosity was two or higherprinter.error('something terrible happened')
would ALWAYS log ‘something terrible happened’.printer.warning('something worrisome happened')
would log if verbosity was one or higher  the same as a normal status.Both printer.error and printer.warning will prepend ‘ERROR: ‘ or ‘WARNING: ‘ to the message they are given. Optionally, printer.log() can also prepend ‘Status_n’ to the message, where n is the message level.
Logging of progress bars/iterations:
>>> with printer_instance.progress_logging(verbosity): >>> for i, item in enumerate(data): >>> printer.show_progress(i, len(data)) >>> printer.log(...)
will output either a progress bar or iteration statuses depending on the printer’s verbosity
 Parameters
verbosity (int) – How verbose the printer should be.
filename (str, optional) – Where to put output (If none, output goes to screen)
comm (mpi4py.MPI.Comm or ResourceAllocation, optional) – Restricts output if the program is running in parallel (By default, if the rank is 0, output is sent to screen, and otherwise sent to commfiles 1, 2, …
warnings (bool, optional) – Whether or not to print warnings
split (bool, optional) – Whether to split output between stdout and stderr as appropriate, or to combine the streams so everything is sent to stdout.
clear_file (bool, optional) – Whether or not filename should be cleared (overwritten) or simply appended to.
 _comm_path¶
relative path where comm files (outputs of nonroot ranks) are stored.
 Type
str
 _comm_file_name¶
root filename for comm files (outputs of nonroot ranks).
 Type
str
 _comm_file_ext¶
filename extension for comm files (outputs of nonroot ranks).
 Type
str
 _comm_path =¶
 _comm_file_name =¶
 _comm_file_ext = .txt¶
 _create_file(self, filename)¶
 _get_comm_file(self, comm_id)¶
 clone(self)¶
Instead of deepcopy, initialize a new printer object and feed it some select deepcopied members
 Returns
VerbosityPrinter
 static create_printer(verbosity, comm=None)¶
Function for converting between interfaces
 Parameters
verbosity (int or VerbosityPrinter object, required:) – object to build a printer from
comm (mpi4py.MPI.Comm object, optional) – Comm object to build printers with. !Will override!
 Returns
VerbosityPrinter – The printer object, constructed from either an integer or another printer
 __add__(self, other)¶
Increase the verbosity of a VerbosityPrinter
 __sub__(self, other)¶
Decrease the verbosity of a VerbosityPrinter
 __getstate__(self)¶
 __setstate__(self, state_dict)¶
 _append_to(self, filename, message)¶
 _put(self, message, flush=True, stderr=False)¶
 _record(self, typ, level, message)¶
 error(self, message)¶
Log an error to the screen/file
 Parameters
message (str) – the error message
 Returns
None
 warning(self, message)¶
Log a warning to the screen/file if verbosity > 1
 Parameters
message (str) – the warning message
 Returns
None
 log(self, message, message_level=None, indent_char=' ', show_statustype=False, do_indent=True, indent_offset=0, end='\n', flush=True)¶
Log a status message to screen/file.
Determines whether the message should be printed based on current verbosity setting, then sends the message to the appropriate output
 Parameters
message (str) – the message to print (or log)
message_level (int, optional) – the minimum verbosity level at which this level is printed.
indent_char (str, optional) – what constitutes an “indent” (messages at higher levels are indented more when do_indent=True).
show_statustype (bool, optional) – if True, prepend lines with “Status Level X” indicating the message_level.
do_indent (bool, optional) – whether messages at higher message levels should be indented. Note that if this is False it may be helpful to set show_statustype=True.
indent_offset (int, optional) – an additional number of indentations to add, on top of any due to the message level.
end (str, optional) – the character (or string) to end message lines with.
flush (bool, optional) – whether stdout should be flushed right after this message is printed (this avoids delays in onscreen output due to buffering).
 Returns
None
 _progress_bar(self, iteration, total, bar_length, num_decimals, fill_char, empty_char, prefix, suffix, indent)¶
 _verbose_iteration(self, iteration, total, prefix, suffix, verbose_messages, indent, end)¶
 __str__(self)¶
Return str(self).
 verbosity_env(self, level)¶
Create a temporary environment with a different verbosity level.
This is context manager, controlled using Python’s with statement:
>>> with printer.verbosity_env(2): printer.log('Message1') # printed at verbosity level 2 printer.log('Message2') # printed at verbosity level 2
 Parameters
level (int) – the verbosity level of the environment.
 progress_logging(self, message_level=1)¶
Context manager for logging progress bars/iterations.
(The printer will return to its normal, unrestricted state when the progress logging has finished)
 Parameters
message_level (int, optional) – progress messages will not be shown until the verbosity level reaches message_level.
 show_progress(self, iteration, total, bar_length=50, num_decimals=2, fill_char='#', empty_char='', prefix='Progress:', suffix='', verbose_messages=[], indent_char=' ', end='\n')¶
Displays a progress message (to be used within a progress_logging block).
 Parameters
iteration (int) – the 0based current iteration – the interation number this message is for.
total (int) – the total number of iterations expected.
bar_length (int, optional) – the length, in characters, of a textformat progress bar (only used when the verbosity level is exactly equal to the progress_logging message level.
num_decimals (int, optional) – number of places after the decimal point that are displayed in progress bar’s percentage complete.
fill_char (str, optional) – replaces ‘#’ as the barfilling character
empty_char (str, optional) – replaces ‘’ as the emptybar character
prefix (str, optional) – message in front of the bar
suffix (str, optional) – message after the bar
verbose_messages (list, optional) – A list of strings to display after an initial “Iter X of Y” line when the verbosity level is higher than the progress_logging message level and so more verbose messages are shown (and a progress bar is not). The elements of verbose_messages will occur, one per line, after the initial “Iter X of Y” line.
indent_char (str, optional) – what constitutes an “indentation”.
end (str, optional) – the character (or string) to end message lines with.
 Returns
None
 _end_progress(self)¶
 start_recording(self)¶
Begins recording the output (to memory).
Begins recording (in memory) a list of (type, verbosityLevel, message) tuples that is returned by the next call to :method:`stop_recording`.
 Returns
None
 is_recording(self)¶
Returns whether this VerbosityPrinter is currently recording.
 Returns
bool
 stop_recording(self)¶
Stops recording and returns recorded output.
Stops a “recording” started by :method:`start_recording` and returns the list of (type, verbosityLevel, message) tuples that have been recorded since then.
 Returns
list
 pygsti.circuits._deprecated_fn(replacement=None)¶
Decorator for deprecating a function.
 Parameters
replacement (str, optional) – the name of the function that should replace it.
 Returns
function
 pygsti.circuits._create_raw_lsgst_lists(op_label_src, prep_strs, effect_strs, germ_list, max_length_list, fid_pairs=None, trunc_scheme='whole germ powers', nest=True, keep_fraction=1, keep_seed=None, include_lgst=True, germ_length_limits=None)¶
Create a set of circuit lists for LSGST based on germs and maxlengths.
Constructs a series (a list) of circuit lists used by longsequence GST (LSGST) algorithms. If include_lgst == True then the starting list is the list of LGST strings, otherwise the starting list is empty. For each nonzero element of max_length_list, call it L, a list of circuits is created with the form:
 Case: trunc_scheme == ‘whole germ powers’:
prepStr + pygsti.circuits.repeat_with_max_length(germ,L) + effectStr
 Case: trunc_scheme == ‘truncated germ powers’:
prepStr + pygsti.circuits.repeat_and_truncate(germ,L) + effectStr
 Case: trunc_scheme == ‘length as exponent’:
prepStr + germ^L + effectStr
If nest == True, the above list is iteratively added (w/duplicates removed) to the current list of circuits to form a final list for the given L. This results in successively larger lists, each of which contains all the elements of previousL lists. If nest == False then the above list is the final list for the given L.
 Parameters
op_label_src (list or Model) – List of operation labels to determine needed LGST strings. If a Model, then the model’s gate and instrument labels are used. Only relevant when include_lgst == True.
prep_strs (list of Circuits) – List of the preparation fiducial circuits, which follow state preparation.
effect_strs (list of Circuits) – List of the measurement fiducial circuits, which precede measurement.
germ_list (list of Circuits) – List of the germ circuits.
max_length_list (list of ints) – List of maximum lengths. A zero value in this list has special meaning, and corresponds to the LGST sequences.
fid_pairs (list of 2tuples or dict, optional) – Specifies a subset of all fiducial string pairs (prepStr, effectStr) to be used in the circuit lists. If a list, each element of fid_pairs is a (iPrepStr, iEffectStr) 2tuple of integers, each indexing a string within prep_strs and effect_strs, respectively, so that prepStr = prep_strs[iPrepStr] and effectStr = effect_strs[iEffectStr]. If a dictionary, keys are germs (elements of germ_list) and values are lists of 2tuples specifying the pairs to use for that germ.
trunc_scheme (str, optional) –
Truncation scheme used to interpret what the list of maximum lengths means. If unsure, leave as default. Allowed values are:
’whole germ powers’ – germs are repeated an integer number of times such that the length is less than or equal to the max.
’truncated germ powers’ – repeated germ string is truncated to be exactly equal to the max (partial germ at end is ok).
’length as exponent’ – max. length is instead interpreted as the germ exponent (the number of germ repetitions).
nest (boolean, optional) – If True, the returned circuits lists are “nested”, meaning that each successive list of circuits contains all the gate strings found in previous lists (and usually some additional new ones). If False, then the returned circuit list for maximum length == L contains only those circuits specified in the description above, and not those for previous values of L.
keep_fraction (float, optional) – The fraction of fiducial pairs selected for each germpower base string. The default includes all fiducial pairs. Note that for each germpower the selected pairs are different random sets of all possible pairs (unlike fid_pairs, which specifies the same fiducial pairs for all samegerm base strings). If fid_pairs is used in conjuction with keep_fraction, the pairs specified by fid_pairs are always selected, and any additional pairs are randomly selected.
keep_seed (int, optional) – The seed used for random fiducial pair selection (only relevant when keep_fraction < 1).
include_lgst (boolean, optional) – If true, then the starting list (only applicable when nest == True) is the list of LGST strings rather than the empty list. This means that when nest == True, the LGST sequences will be included in all the lists.
germ_length_limits (dict, optional) – A dictionary limiting the maxlength values used for specific germs. Keys are germ sequences and values are integers. For example, if this argument is {(‘Gx’,): 4} and max_length_list = [1,2,4,8,16], then the germ (‘Gx’,) is only repeated using maxlengths of 1, 2, and 4 (whereas other germs use all the values in max_length_list).
 Returns
list of (lists of Circuits) – The ith list corresponds to a circuit list containing repeated germs limited to length max_length_list[i]. If nest == True, then repeated germs limited to previous maxlengths are also included. Note that a “0” maximumlength corresponds to the LGST strings.
 pygsti.circuits.make_lsgst_structs(op_label_src, prep_strs, effect_strs, germ_list, max_length_list, fid_pairs=None, trunc_scheme='whole germ powers', nest=True, keep_fraction=1, keep_seed=None, include_lgst=True, op_label_aliases=None, sequence_rules=None, dscheck=None, action_if_missing='raise', germ_length_limits=None, verbosity=0)¶
Deprecated function.
 pygsti.circuits.create_lsgst_circuit_lists(op_label_src, prep_fiducials, meas_fiducials, germs, max_lengths, fid_pairs=None, trunc_scheme='whole germ powers', nest=True, keep_fraction=1, keep_seed=None, include_lgst=True, op_label_aliases=None, circuit_rules=None, dscheck=None, action_if_missing='raise', germ_length_limits=None, verbosity=0)¶
Create a set of longsequence GST circuit lists (including structure).
Constructs a series (a list) of circuit structures used by longsequence GST (LSGST) algorithms. If include_lgst == True then the starting structure contains the LGST strings, otherwise the starting structure is empty. For each nonzero element of max_length_list, call it L, a set of circuits is created with the form:
 Case: trunc_scheme == ‘whole germ powers’:
prep_fiducial + pygsti.circuits.repeat_with_max_length(germ,L) + meas_fiducial
 Case: trunc_scheme == ‘truncated germ powers’:
prep_fiducial + pygsti.circuits.repeat_and_truncate(germ,L) + meas_fiducial
 Case: trunc_scheme == ‘length as exponent’:
prep_fiducial + germ^L + meas_fiducial
If nest == True, the above set is iteratively added (w/duplicates removed) to the current circuit structure to form a final structure for the given L. This results in successively larger structures, each of which contains all the elements of previousL structures. If nest == False then the above set is the final structure for the given L.
 Parameters
op_label_src (list or Model) – List of operation labels to determine needed LGST circuits. If a Model, then the model’s gate and instrument labels are used. Only relevant when include_lgst == True.
prep_fiducials (list of Circuits) – List of the preparation fiducial circuits, which follow state preparation.
effect_fiducials (list of Circuits) – List of the measurement fiducial circuits, which precede measurement.
germs (list of Circuits) – List of the germ circuits.
max_lengths (list of ints) – List of maximum lengths. A zero value in this list has special meaning, and corresponds to the LGST circuits.
fid_pairs (list of 2tuples or dict, optional) – Specifies a subset of all fiducial string pairs (prepStr, effectStr) to be used in the circuit lists. If a list, each element of fid_pairs is a (iPrepStr, iEffectStr) 2tuple of integers, each indexing a string within prep_strs and effect_strs, respectively, so that prepStr = prep_strs[iPrepStr] and effectStr = effect_strs[iEffectStr]. If a dictionary, keys are germs (elements of germ_list) and values are lists of 2tuples specifying the pairs to use for that germ.
trunc_scheme (str, optional) –
Truncation scheme used to interpret what the list of maximum lengths means. If unsure, leave as default. Allowed values are:
’whole germ powers’ – germs are repeated an integer number of times such that the length is less than or equal to the max.
’truncated germ powers’ – repeated germ string is truncated to be exactly equal to the max (partial germ at end is ok).
’length as exponent’ – max. length is instead interpreted as the germ exponent (the number of germ repetitions).
nest (boolean, optional) – If True, the returned circuit lists are “nested”, meaning that each successive list of circuits contains all the gate strings found in previous lists (and usually some additional new ones). If False, then the returned string list for maximum length == L contains only those circuits specified in the description above, and not those for previous values of L.
keep_fraction (float, optional) – The fraction of fiducial pairs selected for each germpower base string. The default includes all fiducial pairs. Note that for each germpower the selected pairs are different random sets of all possible pairs (unlike fid_pairs, which specifies the same fiducial pairs for all samegerm base strings). If fid_pairs is used in conjuction with keep_fraction, the pairs specified by fid_pairs are always selected, and any additional pairs are randomly selected.
keep_seed (int, optional) – The seed used for random fiducial pair selection (only relevant when keep_fraction < 1).
include_lgst (boolean, optional) – If true, then the starting list (only applicable when nest == True) is the list of LGST strings rather than the empty list. This means that when nest == True, the LGST circuits will be included in all the lists.
op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. This information is stored within the returned circuit structures. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
circuit_rules (list, optional) – A list of (find,replace) 2tuples which specify string replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).
dscheck (DataSet, optional) – A data set which is checked for each of the generated circuits. When a generated circuit is missing from this DataSet, action is taken according to action_if_missing.
action_if_missing ({"raise","drop"}, optional) – The action to take when a generated circuit is missing from dscheck (only relevant when dscheck is not None). “raise” causes a ValueError to be raised; “drop” causes the missing circuits to be dropped from the returned set.
germ_length_limits (dict, optional) – A dictionary limiting the maxlength values used for specific germs. Keys are germ circuits and values are integers. For example, if this argument is {(‘Gx’,): 4} and max_length_list = [1,2,4,8,16], then the germ (‘Gx’,) is only repeated using maxlengths of 1, 2, and 4 (whereas other germs use all the values in max_length_list).
verbosity (int, optional) – The level of output to print to stdout.
 Returns
list of PlaquetteGridCircuitStructure objects – The ith object corresponds to a circuit list containing repeated germs limited to length max_length_list[i]. If nest == True, then repeated germs limited to previous maxlengths are also included. Note that a “0” maximumlength corresponds to the LGST strings.
 pygsti.circuits.create_lsgst_circuits(op_label_src, prep_strs, effect_strs, germ_list, max_length_list, fid_pairs=None, trunc_scheme='whole germ powers', keep_fraction=1, keep_seed=None, include_lgst=True)¶
List all the circuits (i.e. experiments) required for longsequence GST (LSGST).
Returns a single list containing, without duplicates, all the gate strings required throughout all the iterations of LSGST given by max_length_list. Thus, the returned list is equivalently the list of the experiments required to run LSGST using the supplied parameters, and so commonly used when construting data set templates or simulated data sets. The breakdown of which circuits are used for which iteration(s) of LSGST is given by create_lsgst_circuit_lists(…).
 Parameters
op_label_src (list or Model) – List of operation labels to determine needed LGST strings. If a Model, then the model’s gate and instrument labels are used. Only relevant when include_lgst == True.
prep_strs (list of Circuits) – List of the preparation fiducial circuits, which follow state preparation.
effect_strs (list of Circuits) – List of the measurement fiducial circuits, which precede measurement.
germ_list (list of Circuits) – List of the germ circuits.
max_length_list (list of ints) – List of maximum lengths.
fid_pairs (list of 2tuples, optional) – Specifies a subset of all fiducial string pairs (prepStr, effectStr) to be used in the circuit lists. If a list, each element of fid_pairs is a (iPrepStr, iEffectStr) 2tuple of integers, each indexing a string within prep_strs and effect_strs, respectively, so that prepStr = prep_strs[iPrepStr] and effectStr = effect_strs[iEffectStr]. If a dictionary, keys are germs (elements of germ_list) and values are lists of 2tuples specifying the pairs to use for that germ.
trunc_scheme (str, optional) –
Truncation scheme used to interpret what the list of maximum lengths means. If unsure, leave as default. Allowed values are:
’whole germ powers’ – germs are repeated an integer number of times such that the length is less than or equal to the max.
’truncated germ powers’ – repeated germ string is truncated to be exactly equal to the max (partial germ at end is ok).
’length as exponent’ – max. length is instead interpreted as the germ exponent (the number of germ repetitions).
keep_fraction (float, optional) – The fraction of fiducial pairs selected for each germpower base string. The default includes all fiducial pairs. Note that for each germpower the selected pairs are different random sets of all possible pairs (unlike fid_pairs, which specifies the same fiduicial pairs for all samegerm base strings). If fid_pairs is used in conjuction with keep_fraction, the pairs specified by fid_pairs are always selected, and any additional pairs are randomly selected.
keep_seed (int, optional) – The seed used for random fiducial pair selection (only relevant when keep_fraction < 1).
include_lgst (boolean, optional) – If true, then ensure that LGST sequences are included in the returned list.
 Returns
PlaquetteGridCircuitStructure
 pygsti.circuits.create_elgst_lists(op_label_src, germ_list, max_length_list, trunc_scheme='whole germ powers', nest=True, include_lgst=True)¶
Create a set of circuit lists for eLGST based on germs and maxlengths
Constructs a series (a list) of circuit lists used by the extended LGST (eLGST) algorithm. If include_lgst == True then the starting list is the list of length1 operation label strings, otherwise the starting list is empty. For each nonzero element of max_length_list, call it L, a list of circuits is created with the form:
 Case: trunc_scheme == ‘whole germ powers’:
pygsti.circuits.repeat_with_max_length(germ,L)
 Case: trunc_scheme == ‘truncated germ powers’:
pygsti.circuits.repeat_and_truncate(germ,L)
 Case: trunc_scheme == ‘length as exponent’:
germ^L
If nest == True, the above list is iteratively added (w/duplicates removed) to the current list of circuits to form a final list for the given L. This results in successively larger lists, each of which contains all the elements of previousL lists. If nest == False then the above list is the final list for the given L.
 Parameters
op_label_src (list or Model) – List of operation labels to determine needed LGST strings. If a Model, then the model’s gate and instrument labels are used. Only relevant when include_lgst == True.
germ_list (list of Circuits) – List of the germ circuits.
max_length_list (list of ints) – List of maximum lengths. A zero value in this list has special meaning, and corresponds to the length1 operation label strings.
trunc_scheme (str, optional) –
Truncation scheme used to interpret what the list of maximum lengths means. If unsure, leave as default. Allowed values are:
’whole germ powers’ – germs are repeated an integer number of times such that the length is less than or equal to the max.
’truncated germ powers’ – repeated germ string is truncated to be exactly equal to the max (partial germ at end is ok).
’length as exponent’ – max. length is instead interpreted as the germ exponent (the number of germ repetitions).
nest (boolean, optional) – If True, the returned circuit lists are “nested”, meaning that each successive list of circuits contains all the gate strings found in previous lists (and usually some additional new ones). If False, then the returned string list for maximum length == L contains only those circuits specified in the description above, and not those for previous values of L.
include_lgst (boolean, optional) – If true, then the starting list (only applicable when nest == True) is the list of length1 operation label strings rather than the empty list. This means that when nest == True, the length1 sequences will be included in all the lists.
 Returns
list of (lists of Circuits) – The ith list corresponds to a circuit list containing repeated germs limited to length max_length_list[i]. If nest == True, then repeated germs limited to previous maxlengths are also included. Note that a “0” maximumlength corresponds to the gate label strings.
 pygsti.circuits.create_elgst_experiment_list(op_label_src, germ_list, max_length_list, trunc_scheme='whole germ powers', include_lgst=True)¶
List of all the circuits (i.e. experiments) required for extended LGST (eLGST).
Returns a single list containing, without duplicates, all the gate strings required throughout all the iterations of eLGST given by max_length_list. Thus, the returned list is equivalently the list of the experiments required to run eLGST using the supplied parameters, and so commonly used when construting data set templates or simulated data sets. The breakdown of which circuits are used for which iteration(s) of eLGST is given by create_elgst_lists(…).
 Parameters
op_label_src (list or Model) – List of operation labels to determine needed LGST strings. If a Model, then the model’s gate and instrument labels are used. Only relevant when include_lgst == True.
germ_list (list of Circuits) – List of the germ circuits.
max_length_list (list of ints) – List of maximum lengths. A zero value in this list has special meaning, and corresponds to the length1 operation label strings.
trunc_scheme (str, optional) –
Truncation scheme used to interpret what the list of maximum lengths means. If unsure, leave as default. Allowed values are:
’whole germ powers’ – germs are repeated an integer number of times such that the length is less than or equal to the max.
’truncated germ powers’ – repeated germ string is truncated to be exactly equal to the max (partial germ at end is ok).
’length as exponent’ – max. length is instead interpreted as the germ exponent (the number of germ repetitions).
include_lgst (boolean, optional) – If true, then ensure that length1 sequences are included in the returned list.
 Returns
list of Circuits
 pygsti.circuits._get_trunc_function(trunc_scheme)¶