Welcome to pyGSTi’s documentation¶
pyGSTi is a python implementation of Gate Set Tomography (GST).
Packages¶
LinearOperator Set Tomography Algorithms Python Package 

A subpackage holding utility objects 

A subpackage holding circuitrelated objects 

A subpackage holding data set objects and supporting analysis objects 

pyGSTi HighLevel Drivers Python Package 

Subpackage of evolution types, or "evotypes". 

Container for beyondGST subpackages 

pyGSTi Forward Simulators Python Package 

pyGSTi Input/Output Python Package 

pyGSTi Layouts Python Package 

A subpackage containing the objects that are held within 

Preset definitions for working with wellknown common models 

pyGSTi Models Python Package 

Package of objective functions of a model and data set, which can be optimized. 

pyGSTi Optimization Python Package 

pyGSTi Processors Python Package 

Subpackage containing protocol objects and related inputs, data, and results 

pyGSTi Reporting Python Package 

pyGSTi Serialization Python Package 

pyGSTi Tools Python Package 
License & Copyright¶
Apache License¶
 Version
2.0
 Date
January 2004
 URL
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION¶
1. Definitions.¶
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License.¶
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, nonexclusive, nocharge, royaltyfree, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License.¶
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, nonexclusive, nocharge, royaltyfree, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a crossclaim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.¶
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a
"NOTICE"
text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within suchNOTICE
file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within aNOTICE
text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such thirdparty notices normally appear. The contents of theNOTICE
file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to theNOTICE
text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions.¶
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks.¶
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE
file.
7. Disclaimer of Warranty.¶
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NONINFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability.¶
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.¶
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work¶
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets “[]” replaced with your own identifying information. (Don’t include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same “printed page” as the copyright notice for easier identification within thirdparty archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright Notice¶
Python GST Implementation (PyGSTi) v. 0.9 Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
Under the terms of Contract DENA0003525 with NTESS, the U.S. Government retains certain rights in this software.
API Reference¶
This page contains autogenerated API reference documentation 1.
pygsti
¶
A Python implementation of LinearOperator Set Tomography
Subpackages¶
pygsti.algorithms
¶
LinearOperator Set Tomography Algorithms Python Package
pygsti.algorithms.compilers
¶Clifford circuit, CNOT circuit, and stabilizer state/measurement generation compilation routines
Creates the standard 'costfunctions' from an input string. 


Compiles an nqubit Clifford gate into a circuit over a given processor specification. 

Creates a 

Creates a 

Creates a 

Creates a 

Creates a 

Creates a 

Creates a 

A CNOT circuit compiler. 

Compile a CNOT circuit. 

A helper function for CNOT circuit compilations. 

An ordered and connectivityadjusted Gaussianelimination (OCAGE) algorithm for compiling a CNOT circuit. 

An improved, ordered and connectivityadjusted Gaussianelimination (OiCAGE) algorithm for compiling a CNOT circuit. 

Generates a circuit to create the stabilizer state from the standard input state 0,0,0,...>. 

Generates a circuit to map the stabilizer state to the standard state 0,0,0,...>. 

Converts a submatrix of s to row or columnechelon form. 

Converts a submatrix of s to the identity matrix using CNOTs. 

Uses rowaction or columnaction Hadamard gates to make a submatrix of s invertable. 

Uses rowaction or columnaction Phase gates to make a submatrix of s invertable. 

Performs an Albert factorization transform on s. 

Applies phase gates to all qubits 

Applies Hadamard gates to all qubits 

Finds circuits that partially (conditional on the input) implement the Clifford given by s. 
 pygsti.algorithms.compilers._create_standard_costfunction(name)¶
Creates the standard ‘costfunctions’ from an input string.
This is used for calculating the “cost” of a circuit created by some compilation algorithms.
 Parameters
name (str) –
 Allowed values are:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
 Returns
function – A function that takes a circuit as the first argument, a QubitProcessorSpec as the second argument (or a “junk” input when a QubitProcessorSpec is not needed), and returns the cost of the circuit.
 pygsti.algorithms.compilers.compile_clifford(s, p, pspec=None, absolute_compilation=None, paulieq_compilation=None, qubit_labels=None, iterations=20, algorithm='ROGGE', aargs=[], costfunction='2QGC:10:depth:1', prefixpaulis=False, paulirandomize=False, rand_state=None)¶
Compiles an nqubit Clifford gate into a circuit over a given processor specification.
Compiles an nqubit Clifford gate, described by the symplectic matrix s and vector p, into a circuit over the gates given by a processor specification or a standard processor. Clifford gates/circuits can be converted to, or sampled in, the symplectic representation using the functions in :module:`pygsti.tools.symplectic`.
The circuit created by this function will be over the gates in the given processor spec, respecting its connectivity, when a QubitProcessorSpec object is provided. Otherwise, it is over a canonical processor containing alltoall CNOTs, Hadamard, Phase, 3 products of Hadamard and Phase, and the Pauli gates.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the Clifford is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input Clifford needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – Some of the allowed algorithms are randomized. This is the number of iterations used in algorithm if it is a randomized algorithm specified. If any randomized algorithms are specified, the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
algorithm (str, optional) –
Specifies the algorithm used for the core part of the compilation: finding a circuit that is a Clifford with s the symplectic matrix in its symplectic representation (a circuit that implements that desired Clifford up to Pauli operators). The allowed values of this are:
 ’BGGE’: A basic, deterministic global Gaussian elimination algorithm. Circuits obtained from this algorithm
contain, in expectation, O(n^2) 2qubit gates. Although the returned circuit will respect device connectivity, this algorithm does not take connectivity into account in an intelligient way. More details on this algorithm are given in compile_symplectic_with_ordered_global_gaussian_elimination(); it is the algorithm described in that docstring but with the qubit ordering fixed to the order in the input s.
 ’ROGGE’: A randomized elimination order global Gaussian elimination algorithm. This is the same algorithm as
’BGGE’ except that the order that the qubits are eliminated in is randomized. This results in significantly lowercost circuits than the ‘BGGE’ method (given sufficiently many iterations). More details are given in the compile_symplectic_with_random_ordered_global_gaussian_elimination() docstring.
’iAGvGE’: Our improved version of the AaraonsonGottesman method for compiling a Clifford circuit, which uses 3 CNOT circuits and 3 1Qgate layers (rather than the 5 CNOT circuit used in the algorithm of AG in Phys. Rev. A 70 052328 (2004)), with the CNOT circuits compiled using Gaussian elimination. Note that this algorithm appears to perform substantially worse than ‘ROGGE’, even though with an upgraded CNOT compiler it is asymptotically optimal (unlike any of the GGE methods). Also, note that this algorithm is randomized: there are many possible CNOT circuits (with nonequivalent action, individually) for the 2 of the 3 CNOT stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization used in the stabilizer state/measurement compilers.
aargs (list, optional) – If the algorithm can take optional arguments, not already specified as separate arguments above, then this list is passed to the compile_symplectic algorithm as its final arguments.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
prefixpaulis (bool, optional) – A Pauli layer is needed to compile the correct Clifford (and not just the correct Clifford up to Paulis). When prefixpaulis = True this Pauli layer is placed at the beginning of the circuit; when False, it is placed at the end. Note that the required Pauli layer depends on whether we prefix or postfix it to the main symplecticgenerating circuit.
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this Clifford circuit. This can be useful for preventing coherent addition of errors in the circuit.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit implementing the input Clifford gate/circuit.
 pygsti.algorithms.compilers.compile_symplectic(s, pspec=None, absolute_compilation=None, paulieq_compilation=None, qubit_labels=None, iterations=20, algorithms=['ROGGE'], costfunction='2QGC:10:depth:1', paulirandomize=False, aargs={}, check=True, rand_state=None)¶
Creates a
Circuit
that implements a Clifford gate given in the symplectic representation.Returns an nqubit circuit that implements an nqubit Clifford gate that is described by the symplectic matrix s and some vector p. The circuit created by this function will be over the gates in the processor specification pspec, respecting any desired connectivity if a QubitProcessorSpec object is provided. Otherwise, the circuit is over the gates of a canonical processor containing alltoall CNOTs, Hadamard, Phase, 3 products of Hadamard and Phase, and the Pauli gates.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – Some of the allowed algorithms are randomized. This is the number of iterations used in each algorithm specified that is a randomized algorithm.
algorithms (list of strings, optional) –
Specifies the algorithms used. If more than one algorithm is specified, then all the algorithms are implemented and the lowest “cost” circuit obtained from all the algorithms (and iterations of those algorithms, if randomized) is returned.
The allowed elements of this list are:
 ’BGGE’: A basic, deterministic global Gaussian elimination algorithm. Circuits obtained from this algorithm
contain, in expectation, O(n^2) 2qubit gates. Although the returned circuit will respect device connectivity, this algorithm does not take connectivity into account in an intelligient way. More details on this algorithm are given in compile_symplectic_with_ordered_global_gaussian_elimination(); it is the algorithm described in that docstring but with the qubit ordering fixed to the order in the input s.
 ’ROGGE’: A randomized elimination order global Gaussian elimination algorithm. This is the same algorithm as
’BGGE’ except that the order that the qubits are eliminated in is randomized. This results in significantly lowercost circuits than the ‘BGGE’ method (given sufficiently many iterations). More details are given in the compile_symplectic_with_random_ordered_global_gaussian_elimination() docstring.
’iAGvGE’: Our improved version of the AaraonsonGottesman method for compiling a symplectic matrix, which uses 3 CNOT circuits and 3 1Qgate layers (rather than the 5 CNOT circuit used in the algorithm of AG in Phys. Rev. A 70 052328 (2004)), with the CNOT circuits compiled using Gaussian elimination. Note that this algorithm appears to perform substantially worse than ‘ROGGE’, even though with an upgraded CNOT compiler it is asymptotically optimal (unlike any of the GGE methods). Also, note that this algorithm is randomized: there are many possible CNOT circuits (with nonequivalent action, individually) for the 2 of the 3 CNOT stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization used in the stabilizer state/measurement compilers.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a cost (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this Clifford circuit. This can be useful for preventing coherent addition of errors in the circuit.
aargs (dict, optional) – If the algorithm can take optional arguments, not already specified as separate arguments above, then the list arrgs[algorithmname] is passed to the compile_symplectic algorithm as its final arguments, where algorithmname is the name of algorithm specified in the list algorithms.
check (bool, optional) – Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm success).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit implementing the input Clifford gate/circuit.
 pygsti.algorithms.compilers._compile_symplectic_using_rogge_algorithm(s, pspec=None, paulieq_compilation=None, qubit_labels=None, ctype='basic', costfunction='2QGC:10:depth:1', iterations=10, check=True, rand_state=None)¶
Creates a
Circuit
that implements a Clifford gate using the ROGGE algorithm.The order global Gaussian elimiation algorithm of _compile_symplectic_using_ogge_algorithm() with the qubit elimination order randomized. See that function for further details on the algorithm, This algorithm is more conveniently and flexibly accessed via the compile_symplectic() or compile_clifford() wraparound functions.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
ctype (str, optional) – The particular variant on the global Gaussian elimiation core algorithm. Currently there is only one such variant, corresponding to the string “basic”.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a cost (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
iterations (int, optional) – The number of different random orderings tried. The lowest “cost” circuit obtained from the different orderings is what is returned.
check (bool, optional) – Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm success).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit implementing the input symplectic matrix.
 pygsti.algorithms.compilers._compile_symplectic_using_ogge_algorithm(s, eliminationorder, pspec=None, paulieq_compilation=None, qubit_labels=None, ctype='basic', check=True)¶
Creates a
Circuit
that implements a Clifford gate using the OGGE algorithm.An ordered global Gaussian elimiation algorithm for creating a circuit that implements a Clifford that is represented by the symplectic matrix s (and some phase vector). This algorithm is more conveniently and flexibly accessed via the compile_symplectic() or compile_clifford() wraparound functions.
The algorithm works as follows:
The s matrix is permuted so that the index for the jth qubit to eliminate becomes index j.
The “global Gaussian elimination” algorithm of E. Hostens, J. Dehaene, and B. De Moor, PRA 71 042315 (2015) is implemented, which can be used to decompose s into a circuit over CNOT, SWAP, H, and P. That algorithm is for ddimensional qudits, and simplifies significantly for d=2 (qubits), which is the case implemented here. However, we are unware of anywhere else that this algorithm is clearly stated for the qubit case (although this basic algorithm is widely known).
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
eliminationorder (list) – The elimination order for the qubits. If pspec is specified, this should be a list consisting of the qubit labels that s is over (this can be a subset of all qubits in pspec is qubit_labels is None). If pspec is not specified this list should consist of the integers between 0 and n1 in any order, corresponding to the indices of s.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
ctype (str, optional) – The particular variant on the global Gaussian elimiation core algorithm. Currently there is only one such variant, corresponding to the string “basic”.
check (bool, optional) – Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm success).
 Returns
Circuit – A circuit implementing the input symplectic matrix.
 pygsti.algorithms.compilers._compile_symplectic_using_gge_core(s, check=True)¶
Creates a
Circuit
that implements a Clifford gate using the GGE algorithm.Creates a circuit over ‘I’,’H’,’HP’,’PH’,’HPH’, and ‘CNOT’ that implements a Clifford gate with s as its symplectic matrix in the symplectic representation (and with any phase vector). This circuit is generated using a basic Gaussian elimination algorithm, which is described in more detail in _compile_symplectic_using_ogge_algorithm(), which is a wraparound for this algorithm that implements a more flexible compilation method.
This algorithm is more conveniently accessed via the compile_symplectic() or compile_clifford() functions.
 Parameters
s (array) – A 2n X 2n symplectic matrix over [0,1] for any positive integer n. The returned circuit is over n qubits.
check (bool, optional) – Whether to check that the generated circuit does implement s.
 Returns
Circuit – A circuit that implements a Clifford that is represented by the symplectic matrix s.
 pygsti.algorithms.compilers._compile_symplectic_using_ag_algorithm(s, pspec=None, qubit_labels=None, cnotmethod='PMH', check=False)¶
Creates a
Circuit
that implements a Clifford gate using the AG algorithm.The AaraonsonGottesman method for compiling a symplectic matrix using 5 CNOT circuits + local layers. This algorithm is presented in PRA 70 052328 (2014).
If cnotmethod = GE then the CNOT circuits are compiled using Gaussian elimination (which is O(n^2)). There are multiple GE algorithms for compiling a CNOT in pyGSTi. This function has the overall best variant of this algorithm hardcoded into this function.
If cnotmethod = PMH then the CNOT circuits are compiled using the asymptotically optimal O(n^2/logn) CNOT circuit algorithm of PMH.
* This function has not yet been implemented *
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec (QubitProcessorSpec, optional) – An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
ctype (str, optional) – The particular variant on the global Gaussian elimiation core algorithm. Currently there is only one such variant, corresponding to the string “basic”.
cnotmethod ({"GE", "PMH"}) – See above.
check (bool, optional) – Whether to check that the generated circuit does implement s.
 Returns
Circuit – A circuit that implements a Clifford that is represented by the symplectic matrix s.
 pygsti.algorithms.compilers._compile_symplectic_using_riag_algoritm(s, pspec, paulieq_compilation, qubit_labels=None, iterations=20, cnotalg='COiCAGE', cargs=[], costfunction='2QGC:10:depth:1', check=True, rand_state=None)¶
Creates a
Circuit
that implements a Clifford gate using the RIAG algorithm.Our improved version of AaraonsonGottesman method [PRA 70 052328 (2014)] for compiling a symplectic matrix using 5 CNOT circuits + local layers. Our version of this algorithm uses 3 CNOT circuits, and 3 layers of 1qubit gates. Also, note that this algorithm is randomized: there are many possible CNOT circuits (with nonequivalent action, individually) for the 2 of the 3 CNOT stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization used in the stabilizer state/measurement compilers.
Note that this algorithm currently performs substantially worse than ‘ROGGE’, even though with an upgraded CNOT compiler it is asymptotically optimal (unlike any of the GGE methods).
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec (QubitProcessorSpec) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – The number of different random orderings tried. The lowest “cost” circuit obtained from the different orderings is what is returned.
cnotalg (str, optional) – The CNOT compiler to use. See compile_cnot_circuit() for the options. The default is probably the current best CNOT circuit compiler in pyGSTI.
cargs (list, optional) – Arguments handed to the CNOT compilation algorithm. For some choices of cnotalg this is not optional.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a cost (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
check (bool, optional) – Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm success).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit implementing the input symplectic matrix.
 pygsti.algorithms.compilers._compile_symplectic_using_iag_algorithm(s, pspec, qubit_labels=None, cnotalg='COCAGE', cargs=[], check=True, rand_state=None)¶
Creates a
Circuit
that implements a Clifford gate using the IAG algorithm.A single iteration of the algorithm in _compile_symplectic_using_riag_algoritm(). See that functions docstring for more information. Note that it is normallly better to access this algorithm through that function even when only a single iteration of the randomization is desired: this function does not change into the native gate library of pspec.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec (QubitProcessorSpec, optional) – An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
cnotalg (str, optional) – The algorithm argument to pass internally to :function:`compile_cnot_circuit` when compiling CNOT gates.
cargs (various, optional) – The aargs argument to pass internally to :function:`compile_cnot_circuit` when compiling CNOT gates.
check (bool, optional) – Whether to check that the generated circuit does implement s.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that implements a Clifford that is represented by the symplectic matrix s.
 pygsti.algorithms.compilers.compile_cnot_circuit(s, pspec, compilation, qubit_labels=None, algorithm='COiCAGE', compile_to_native=False, check=True, aargs=[], rand_state=None)¶
A CNOT circuit compiler.
Takes an arbitrary CNOT circuit, input as a symplectic matrix s that corresponds to the matrix portion of the symplectic representation of this Clifford circuit, and decomposes it into a sequences of gates from the processor spec pspec.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers that represents a Clifford circuit: so it must be blockdiagonal. Specifically, it has the form s = ((A,0),(0,B)) where B is the inverse transpose of A (over [0,1] mod 2).
pspec (QubitProcessorSpec) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
compilation (CompilationRules) – Rules for compiling the “native” gates of pspec into clifford gates, used if compile_to_native==True.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
algorithm (str, optional) –
The algorithm to use. The optionas are:
 ’BGE’A basic Gaussian elimination algorithm, that uses CNOT to perform rowreduction on the upper
LHS (or lower RHS) of s. This algorithm does not take device connectivity into account.
 ’OCAGE’Userordered connectivityadjusted Gaussian elimination. The qubits are eliminated in the
specified order; the first element of arrgs must be a list specify this order. The algorithm is also “connectivityadjusted” in the sense that it uses the connectivity graph (in pspec.qubit_graph) to try and avoid using CNOTs between unconnected pairs whenever possible, and to decide the order of various operations.
 ’OiCAGE’The same as ‘OCAGE’ except that it has some improvements, and it requires connectivity
graph of the remaining qubits, after each qubit has been ‘eliminated’, to be connected. In the current format this algorithm is only slightly betterperforming than ‘OCAGE’, and only on average. (This algorithm will possibly be improved in the future, whereas ‘OCAGE’ will remain asis for reproducability of previously obtained results.)
 ’ROCAGE’: Same as ‘OCAGE’ except that the elimination order is chosen at random, rather than user
specified.
 ’COCAGE’, ‘COiCAGE’The same as ‘OCAGE’ and ‘OiCAGE’, respectively, except that the elimination order
is fixed to eliminate qubits with the worse connectivity before those with better connectivity.
compile_to_native (bool, optional) – Whether the circuit should be given in terms of the native gates of the processor defined in pspec.
check (bool, optional) – Whether to check the output is correct.
aargs (list, optional) – A list of arguments handed to the CNOT compiler algorithm. For some choices of algorithm (e.g., ‘OCAGE’) this list must not be empty. For algorithms where there are X nonoptional arguements after s and pspec these are specified as the first X arguments of aargs. The remaining elements in aargs, if any, are handed to the algorithm as the arguments after the optional qubit_labels and check arguments (the first of which is set by the input qubit_labels in this function).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that implements the same unitary as the CNOT circuit represented by s.
 pygsti.algorithms.compilers._compile_cnot_circuit_using_bge_algorithm(s, pspec, qubit_labels=None, compile_to_native=False, check=True)¶
Compile a CNOT circuit.
Compilation uses a basic Gaussian elimination algorithm, that uses CNOT to perform rowreduction on the upper LHS (or lower RHS) of s. This algorithm does not take device connectivity into account.
See the docstring of compile_cnot_circuit() for information on the parameters. This function should normally be accessed via compile_cnot_circuit().
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers, that represents the CNOT circuit. This should be a (2x2) blockdiagonal matrix, whereby the upper left block is any invertable transformation over [0,1]^n, and the lower right block is the inverse transpose of this transformation.
pspec (QubitProcessorSpec) – An nbarqubit QubitProcessorSpec object that encodes the device that the CNOT circuit is being compiled for, where nbar >= n. The algorithm is takes into account the connectivity of the device as specified by pspec.qubit_graph. If nbar > n it is necessary to provide qubit_labels, to specify which qubits in pspec the CNOT circuit acts on (all other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input CNOT circuit needs to be ``padded’’ to be the identity on those qubits). The ordering of the qubits in s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
qubit_labels (list, optional) – Required if the CNOT circuit to compile is over less qubits than in pspec. In this case this is a list of the qubits to compile the CNOT circuit for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in s is taken w.r.t the ordering of this list.
compile_to_native (bool, optional) – Unused.
check (bool, optional) – Whether to check the algorithm was successful.
 Returns
Circuit – A circuit implementing the input CNOT circuit.
 pygsti.algorithms.compilers._add_cnot(qubitgraph, controllabel, targetlabel)¶
A helper function for CNOT circuit compilations.
Returns an instruction list that is CNOTs along the shortest path from the qubits with label controlabel and targetlabel.
 Parameters
qubitgraph (QubitGraph) – The qubit graph from which the shortest path between the qubits is extracted.
controllabel (str) – The label for the control qubit.
targetlabel (str) – The label for the target qubit.
 Returns
list – The list of instructions for implementing the requested CNOT via the available CNOT gates, as specified by qubitgraph.
 pygsti.algorithms.compilers._compile_cnot_circuit_using_ocage_algorithm(s, pspec, qubitorder, qubit_labels=None, check=True, respect_connectivity=True)¶
An ordered and connectivityadjusted Gaussianelimination (OCAGE) algorithm for compiling a CNOT circuit.
The algorithm takes as input a symplectic matrix s, that defines the action of a CNOT circuit, and it generates a CNOT circuit (converted to a native gate set, if requested) that implements the same unitary.
The algorithm works by mapping s > identity using CNOTs acting from the LHS and RHS. I.e., it finds two CNOT circuits Ccnot1, Ccnot2 such that symp(Ccnot1) * s * symp(Ccnot2) = identity (where symp(c) is the symplectic matrix representing the circuit c). A circuit implementing s is then obtained as rev(Cnot1)rev(Cnot2) where rev(c) denotes the reverse of circuit c.
To find such circuits Ccnot1/2 we use the following algorithm. We eliminate the qubits in the order specified, whereby “eliminating” a qubit means mapping the column and row of s associated with that qubit to the identity column and row. To eliminate the ith qubit in the list we:
1. Look at the current value of s[i,i]. If s[i,i] = 1 continue. Else, find the closest qubit to do a CNOT between i and that qubit to make s[i,i] = 1. 2. List the remaining qubits to eliminate (the i+1th qubit onwards), and going from the qubit
 in this list that is further from i to the closest implement the following steps:
2.1. Denote this qubit by ii. 2.1 If s[ii,i] = 0, pass. Else, map s[ii,i] > 0 with the following method:
find the shortest path from i > ii,
If the shortest path contains already eliminated qubits, using a LHSaction SWAPlike set of chains of CNOTs along the shortest path i > ii to do a CNOT from i > ii whilst leaving all other qubits unchanged. Then skip to 2.3.
If the shortest path doesn’t contain already eliminated qubits, do LHSaction CNOTs between neighbouring qubits along this path to set all the s matrix elements in the column s[:,i] for the qubits along this path to 1.
Use the qubit next to ii in this path to set s[ii,i] using a LHSaction CNOT, and don’t undo any of the changes to the other qubits along that path.
 2.3. If s[i,ii] = 0, pass. Else, map s[i,ii] > 0 as in step 2.3 except that now we use RHSaction
CNOTs.
Steps 1  3 do not change the already eliminated qubits, so after steps 1  2 are repeated for each of the yettobeeliminated qubits, s should be some smaller matrix s’ between the yettobeeliminated qubits embedded in a identity matrix on the already eliminated qubits.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers, that represents the CNOT circuit. This should be a (2x2) blockdiagonal matrix, whereby the upper left block is any invertable transformation over [0,1]^n, and the lower right block is the inverse transpose of this transformation.
pspec (QubitProcessorSpec) – An nbarqubit QubitProcessorSpec object that encodes the device that the CNOT circuit is being compiled for, where nbar >= n. The algorithm is takes into account the connectivity of the device as specified by pspec.qubit_graph. The output circuit is over the gates available in this device is compile_to_native is True. If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the CNOT circuit acts on (all other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input CNOT circuit needs to be ``padded’’ to be the identity on those qubits). The ordering of the qubits in s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
qubitorder (list) – A list of the qubit labels in the order in which they are to be eliminated. For autogenerated orderings use the compile_cnot_circuit() wraparound function.
qubit_labels (list, optional) – Required if the CNOT circuit to compile is over less qubits than in pspec. In this case this is a list of the qubits to compile the CNOT circuit for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in s is taken w.r.t the ordering of this list.
check (bool, optional) – Whether to check the algorithm was successful.
respect_connectivity (bool, optional) – This algorithm takes the connectivity into account, but sometimes resorts to ‘nonlocal’ CNOTs. If respect_connectivity is True these gates are reexpressed over the available gates using a SWAPlike decomposition. If False, the algorithm does not compile these gates automatically. However, they will still be converted to native gates from pspec if compile_to_native is True, using whatever the user specified algorithm for compiling nonlocal CNOT gates this implies.
 Returns
Circuit – A circuit implementing the input CNOT circuit.
 pygsti.algorithms.compilers._compile_cnot_circuit_using_oicage_algorithm(s, pspec, qubitorder, qubit_labels=None, compile_to_native=False, check=True)¶
An improved, ordered and connectivityadjusted Gaussianelimination (OiCAGE) algorithm for compiling a CNOT circuit.
This is a slight improvement (for some CNOT circuits), on the algorithm in :function:`_compile_cnot_circuit_using_ocage_algorithm()`, which is the meaning of the “improved”. See the docstring for that function for information on the parameters of this function and the basic outline of the algorithm.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers, that represents the CNOT circuit. This should be a (2x2) blockdiagonal matrix, whereby the upper left block is any invertable transformation over [0,1]^n, and the lower right block is the inverse transpose of this transformation.
pspec (QubitProcessorSpec) – An nbarqubit QubitProcessorSpec object that encodes the device that the CNOT circuit is being compiled for, where nbar >= n. The algorithm is takes into account the connectivity of the device as specified by pspec.qubit_graph. If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the CNOT circuit acts on (all other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input CNOT circuit needs to be ``padded’’ to be the identity on those qubits). The ordering of the qubits in s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
qubitorder (list) – A list of the qubit labels in the order in which they are to be eliminated. For autogenerated orderings use the compile_cnot_circuit() wraparound function.
qubit_labels (list, optional) – Required if the CNOT circuit to compile is over less qubits than in pspec. In this case this is a list of the qubits to compile the CNOT circuit for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in s is taken w.r.t the ordering of this list.
compile_to_native (bool, optional) – Unused.
check (bool, optional) – Whether to check the algorithm was successful.
 Returns
Circuit – A circuit implementing the input CNOT circuit.
 pygsti.algorithms.compilers.compile_stabilizer_state(s, p, pspec, absolute_compilation, paulieq_compilation, qubit_labels=None, iterations=20, paulirandomize=False, algorithm='COiCAGE', aargs=[], costfunction='2QGC:10:depth:1', rand_state=None)¶
Generates a circuit to create the stabilizer state from the standard input state 0,0,0,…>.
The stabilizer state is specified by s and p. The circuit returned is over the gates in the processor spec. See :function:`compile_stabilizer_state()` for the inverse of this.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers. This is a symplectic matrix representing any Clifford gate that, when acting on 0,0,0,…>, generates the desired stabilizer state. So s is not unique.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate. This phase vector matrix should, together with s, represent any Clifford gate that, when acting on 0,0,0,…>, generates the desired stabilizer state. So p is not unique.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
pspec –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the stabilizer state is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – This algorithm is randomized. This is the number of iterations used in the algorithm. the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this circuit. This can be useful for preventing coherent addition of errors in the circuit.
algorithm (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. algorithm specifies the CNOTcompilation algorithm to use. The allowe values are all those algorithms that permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances.
aargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that creates the specified stabilizer state from 0,0,0,…>
 pygsti.algorithms.compilers.compile_stabilizer_measurement(s, p, pspec, absolute_compilation, paulieq_compilation, qubit_labels=None, iterations=20, paulirandomize=False, algorithm='COCAGE', aargs=[], costfunction='2QGC:10:depth:1', rand_state=None)¶
Generates a circuit to map the stabilizer state to the standard state 0,0,0,…>.
The stabilizer state is specified by s and p. The circuit returned is over the gates in the processor spec pspec. See :function”compile_stabilizer_state() for the inverse of this. So, this circuit followed by a Zbasis measurement can be used to simulate a projection onto the stabilizer state C0,0,0,…> where C is the Clifford represented by s and p.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers. This is a symplectic matrix representing any Clifford gate that, when acting on 0,0,0,…>, generates the stabilizer state that we need to map to 0,0,0,…>. So s is not unique.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate. This phase vector matrix should, together with s, represent any Clifford gate that, when acting on 0,0,0,…>, generates the stabilizer state that we need to map to 0,0,0,…>. So p is not unique.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the stabilizer state is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – This algorithm is randomized. This is the number of iterations used in the algorithm. the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this circuit. This can be useful for preventing coherent addition of errors in the circuit.
algorithm (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. algorithm specifies the CNOTcompilation algorithm to use. The allowe values are all those algorithms that permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances.
aargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that maps the specified stabilizer state to 0,0,0,…>
 pygsti.algorithms.compilers._convert_submatrix_to_echelon_form_using_cnots(s, optype, position, qubit_labels)¶
Converts a submatrix of s to row or columnechelon form.
Converts one of the 4 submatrices of the symplectic matrix s to row or columnechelon form, using a CNOT circuit acting after or before this circuit. The conversion is only performed if the submatrix is invertable, and otherwise the function reports that this submatrix is not invertable.
The function does not alter s, but rather returns an updated version of s.
 Parameters
s (np.array) – The (2n,2n) matrix over [0,1] that we are transforming one of the 4 (n,n) submatrices of to row/column echolon form.
optype ('row' or 'column') – If ‘row’, we peform rowoperation CNOTs (CNOTs from the LHS) to convert the the submatrix to rowechelon form, If ‘column’, we peform columnoperation CNOTs (CNOTs from the RHS) to convert the submatrix to columnechelon form.
position ('UL', 'UR', 'LL', or 'LR') – The submatrix to perform the row/column reduction on. ‘UL’ and ‘UR’ correspond to the upper left and right submatrices, respecively. ‘LL’ and ‘LR’ correspond to the lower left and right submatrices, respecively.
qubit_labels (list) – The qubit labels corresponding to the indices of s. This is required because othewise it is ambigious as to what the ‘name’ of a qubit associated with each indices is, so it is not possible to return a suitable list of CNOTs.
 Returns
np.array – The updated s matrix. If the submatrix is not invertable, then the updated s at the point at which this becomes apparent is returned.
bool – True if the row/column reduction has managed to create a matrix with 1s on the diagonal, or equivalently when the submatrix is invertable (over [0,1] mod 2)
list – A list of the CNOT instructions used to convert s to row/column echolon form. If optype`=’row’, this list is the CNOTs in the order that they should be applied *after* a unitary represented by `s so that the composite unitary has rowecholon form in the specified submatrix of its s matrix. If otptype `=’column’ then this list is the CNOTs in the order they should be applied *before* a unitary represented by `s so that the composite unitary has rowecholon form in the specified submatrix of its s matrix.
When the returned bool is False, this list is None.
 pygsti.algorithms.compilers._submatrix_gaussian_elimination_using_cnots(s, optype, position, qubit_labels)¶
Converts a submatrix of s to the identity matrix using CNOTs.
Converts one of the 4 submatrices of the symplectic matrix s to the identity matrix, using a CNOT circuit acting after or before this circuit. The CNOT circuit is found using Gaussian elimination. The CNOT circuit acts before this circuit if optype is ‘column’ and acts after this if optype is ‘row’. The conversion is only performed if the submatrix is invertable (otherwise it is not possible), and otherwise the function reports that this submatrix is not invertable.
The function does not alter s, but rather returns an updated version of s.
 Parameters
s (np.array) – The (2n,2n) matrix over [0,1] that we are transforming one of the 4 (n,n) submatrices of to I.
optype ('row' or 'column') – If ‘row’, we peform rowoperation CNOTs (CNOTs from the LHS) to convert the the submatrix to I, If ‘column’, we peform columnoperation CNOTs (CNOTs from the RHS) to convert the submatrix to I.
position ('UL', 'UR', 'LL', or 'LR') – The submatrix to perform the transformation on. ‘UL’ and ‘UR’ correspond to the upper left and right submatrices, respecively. ‘LL’ and ‘LR’ correspond to the lower left and right submatrices, respecively.
qubit_labels (list) – The qubit labels corresponding to the indices of s. This is required because othewise it is ambigious as to what the ‘name’ of a qubit associated with each indices is, so it is not possible to return a suitable list of CNOTs.
 Returns
np.array – The updated s matrix. If the submatrix is not invertable, then the updated s at the point at which this becomes apparent is returned.
bool – True if the transformation was successful (the submatrix was invertable)
list – A list of the CNOT instructions used to convert s to I. If optype`=’row’, this list is the CNOTs in the order that they should be applied *after* a unitary represented by `s so that the composite unitary has I as the specified submatrix of its s matrix. If otptype `=’column’ then this list is the CNOTs in the order they should be applied *before* a unitary represented by `s so that the composite unitary has I as the specified submatrix of its s matrix.
When the returned bool is False, this list is None.
 pygsti.algorithms.compilers._make_submatrix_invertable_using_hadamards(s, optype, position, qubit_labels, rand_state=None)¶
Uses rowaction or columnaction Hadamard gates to make a submatrix of s invertable.
The function does not alter s, but rather returns an updated version of s.
 Parameters
s (np.array) – A (2n,2n) matrix over [0,1].
optype ('row' or 'column') – If ‘row’, we use rowoperation Hadamards (Hs from the LHS). If ‘column’, we use columnoperation Hadamards (Hs from the RHS).
position ('UL', 'UR', 'LL', or 'LR') – The submatrix to perform the transformation on. ‘UL’ and ‘UR’ correspond to the upper left and right submatrices, respecively. ‘LL’ and ‘LR’ correspond to the lower left and right submatrices, respecively.
qubit_labels (list) – The qubit labels corresponding to the indices of s. This is required because othewise it is ambigious as to what the ‘name’ of a qubit associated with each indices is, so it is not possible to return a suitable list of CNOTs.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
np.array – The updated s matrix. If the submatrix is not invertable, then the updated s at the point at which this becomes apparent is returned.
list – A list of the Hadamards.
 pygsti.algorithms.compilers._make_submatrix_invertable_using_phases_and_idsubmatrix(s, optype, position, qubit_labels)¶
Uses rowaction or columnaction Phase gates to make a submatrix of s invertable.
This uses an identity submatrix in s, and does not alter s, but rather returns an updated version of s.
 Parameters
s (np.array) – A (2n,2n) matrix over [0,1].
optype ('row' or 'column') – If ‘row’, we use rowoperation Ps (Ps from the LHS). In that case ‘position’ must be ‘LL’ or ‘LR’ and it is submatrix above optype that must be the identity for this function to have the desired action. If ‘column’, we use columnoperation Ps (Ps from the RHS). In that case ‘position’ must be ‘UL’ or ‘LL’ and it is submatrix to the RHS of optype that must be the identity for this function to have the desired action.
position ('UL', 'UR', 'LL', or 'LR') – The submatrix to perform the transformation on. ‘UL’ and ‘UR’ correspond to the upper left and right submatrices, respecively. ‘LL’ and ‘LR’ correspond to the lower left and right submatrices, respecively.
qubit_labels (list) – The qubit labels corresponding to the indices of s. This is required because othewise it is ambigious as to what the ‘name’ of a qubit associated with each indices is, so it is not possible to return a suitable list of CNOTs.
 Returns
np.array – The updated s matrix. If the submatrix is not invertable, then the updated s at the point at which this becomes apparent is returned.
list – A list of the phase gates.
 pygsti.algorithms.compilers.find_albert_factorization_transform_using_cnots(s, optype, position, qubit_labels)¶
Performs an Albert factorization transform on s.
Given a symplectic s matrix of the form ((A,B),(C,D)) with the submatrix in the position specified by position symmetric, this function
1. Finds an invertable M such that F = M M.T where F is the submatrix in position position, i.e., F is one of A, B, C and D. (this is known as an albert factorization).
2. Applies a CNOT circuit from the LHS (if optype = ‘row’) or RHS (if optyp`=’colum’)) to `s so that F  > M.
For example, if s = ((A,I),(C,D)), position = ‘LR’ and optype = ‘column’ then it finds an M such that we may write s = ((A,I),(C,M M.T)) and it applies the CNOT circuit ((M,0),(0,M^(1)^T) to the RHS of s, mapping s to s = ((AM,M),(CM^(1)^T) ,M)), so that the upper RHS and lower RHS matrix of the new s are the same and are invertable.
This function returns a CNOT circuit that performs this action, with this CNOT circuit obtained from basic Gaussian elimination on M. Note that neither the returned s nor the CNOT circuit is deterministic: Both depend on M from albert factorisation, but this M is nonunique and our algorithm for finding such an M is randomized.
This function does not alter s, but rather returns an updated version of s.
 Parameters
s (np.array) – A (2n,2n) matrix over [0,1].
optype ('row' or 'column') – If ‘row’, we use rowoperation CNOTs (CNOTs from the LHS). If ‘column’, we use columnoperation CNOTs (CNOTs from the RHS).
position ('UL', 'UR', 'LL', or 'LR') – The submatrix to perform the transformation on. ‘UL’ and ‘UR’ correspond to the upper left and right submatrices, respecively. ‘LL’ and ‘LR’ correspond to the lower left and right submatrices, respecively.
qubit_labels (list) – The qubit labels corresponding to the indices of s. This is required because othewise it is ambigious as to what the ‘name’ of a qubit associated with each indices is, so it is not possible to return a suitable list of CNOTs.
 Returns
np.array – The updated s matrix.
list – A list of CNOT gates to implement the transformation requested.
 pygsti.algorithms.compilers._apply_phase_to_all_qubits(s, optype, qubit_labels)¶
Applies phase gates to all qubits
 Parameters
s (np.array) – A (2n,2n) matrix over [0,1].
optype ('row' or 'column') – If ‘row’, we use rowoperation phase gates. If ‘column’, we use columnoperation phase gates.
qubit_labels (list) – The qubit labels corresponding to the indices of s.
 Returns
np.array – The updated s matrix.
list – A list containing phase gates on all the qubits.
 pygsti.algorithms.compilers._apply_hadamard_to_all_qubits(s, optype, qubit_labels)¶
Applies Hadamard gates to all qubits
 Parameters
s (np.array) – A (2n,2n) matrix over [0,1].
optype ('row' or 'column') – If ‘row’, we use rowoperation Hadamard gates. If ‘column’, we use columnoperation Hadamard gates.
qubit_labels (list) – The qubit labels corresponding to the indices of s.
 Returns
np.array – The updated s matrix.
list – A list containing Hadamard gates on all the qubits.
 pygsti.algorithms.compilers.compile_conditional_symplectic(s, pspec, qubit_labels=None, calg='COiCAGE', cargs=[], check=True, rand_state=None)¶
Finds circuits that partially (conditional on the input) implement the Clifford given by s.
The core of the compile_stabilizer_state() and compile_stabilizer_measurement() functions. Finds circuits C1 and C2 so that:
C1 is a CNOT circuit
C2 is a circuit with the form 1qubitgates – CNOT circuit – 1qubit gates.
3. The symplectic rep of the circuit consisting of C1 followed by C2 has the form ((.,B)(.,D)) when s has the form ((A,B),(C,D)).
Therefore, the circuit C2 acting on 0,0,0,…> generates the same stabilizer state (up to Paulis) as a circuit that has the symplectic rep (s,p) for any valid p. The circuit is only “conditionally” equivalent to another circuit with the rep (s,p) – conditional on the input state – which is the meaning of the name compile_conditional_symplectic.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec (QubitProcessorSpec, optional) – An nbarqubit QubitProcessorSpec object that encodes the device that s is being “conditionally” compiled for, where nbar >= n. If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits). The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
qubit_labels (List, optional) – Required if the s is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
calg (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. calg specifies the CNOTcompilation algorithm to use. The allowed values are all those algorithms that are permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances. Note that this is only used to recompile the CNOT circuit in C2, because the main use for this function only needs C1 for reference, rather than as a part of a final output.
cargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
check (bool, optional) – Whether to check that the output is correct.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – The circuit C2 described above.
Circuit – The circuit C1 described above.
pygsti.algorithms.contract
¶GST contraction algorithms

Contract a Model to a specified space. 









Contract the surface preparation and measurement operations of 
 pygsti.algorithms.contract.contract(model, to_what, dataset=None, maxiter=1000000, tol=0.01, use_direct_cp=True, method='NelderMead', verbosity=0)¶
Contract a Model to a specified space.
All contraction operations except ‘vSPAM’ operate entirely on the gate matrices and leave state preparations and measurments alone, while ‘vSPAM’ operations only on SPAM.
 Parameters
model (Model) – The model to contract
to_what (string) –
Specifies which space is the model is contracted to. Allowed values are:
’TP’ – All gates are manifestly tracepreserving maps.
’CP’ – All gates are manifestly completelypositive maps.
’CPTP’ – All gates are manifestly completelypositive and tracepreserving maps.
’XP’ – All gates are manifestly “experimentallypositive” maps.
’XPTP’ – All gates are manifestly “experimentallypositive” and tracepreserving maps.
’vSPAM’ – state preparation and measurement operations are valid.
’nothing’ – no contraction is performed.
dataset (DataSet, optional) – Dataset to use to determine whether a model is in the “experimentallypositive” (XP) space. Required only when contracting to XP or XPTP.
maxiter (int, optional) – Maximum number of iterations for iterative contraction routines.
tol (float, optional) – Tolerance for iterative contraction routines.
use_direct_cp (bool, optional) – Whether to use a faster directcontraction method for CP contraction. This method essentially transforms to the Choi matrix, truncates any negative eigenvalues to zero, then transforms back to a operation matrix.
method (string, optional) – The method used when contracting to XP and nondirectly to CP (i.e. use_direct_cp == False).
verbosity (int, optional) – How much detail to send to stdout.
 Returns
Model – The contracted model
 pygsti.algorithms.contract._contract_to_xp(model, dataset, verbosity, method='NelderMead', maxiter=100000, tol=1e10)¶
 pygsti.algorithms.contract._contract_to_cp(model, verbosity, method='NelderMead', maxiter=100000, tol=0.01)¶
 pygsti.algorithms.contract._contract_to_cp_direct(model, verbosity, tp_also=False, maxiter=100000, tol=1e08)¶
 pygsti.algorithms.contract._contract_to_tp(model, verbosity)¶
 pygsti.algorithms.contract._contract_to_valid_spam(model, verbosity=0)¶
Contract the surface preparation and measurement operations of a Model to the space of valid quantum operations.
 Parameters
model (Model) – The model to contract
verbosity (int) – How much detail to send to stdout.
 Returns
Model – The contracted model
pygsti.algorithms.core
¶Core GST algorithms

Performs Linearinversion Gate Set Tomography on the dataset. 













Returns the rank and singular values of the Gram matrix for a dataset. 

Performs core Gate Set Tomography function of model optimization. 

Performs core Gate Set Tomography function of model optimization. 

Performs Iterative Gate Set Tomography on the dataset. 

Runs the core modeloptimization step within a GST routine by optimizing 

Runs the core modeloptimization step for models using the 

Find the closest (in fidelity) unitary superoperator to operation_mx. 
 pygsti.algorithms.core._dummy_profiler¶
 pygsti.algorithms.core.CUSTOMLM = True¶
 pygsti.algorithms.core.FLOATSIZE = 8¶
 pygsti.algorithms.core.run_lgst(dataset, prep_fiducials, effect_fiducials, target_model, op_labels=None, op_label_aliases=None, guess_model_for_gauge=None, svd_truncate_to=None, verbosity=0)¶
Performs Linearinversion Gate Set Tomography on the dataset.
 Parameters
dataset (DataSet) – The data used to generate the LGST estimates
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to specify which operation labels should be estimated, a guess for which gauge these estimates should be returned in.
op_labels (list, optional) – A list of which operation labels (or aliases) should be estimated. Overrides the operation labels in target_model. e.g. [‘Gi’,’Gx’,’Gy’,’Gx2’]
op_label_aliases (dictionary, optional) – Dictionary 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’])
guess_model_for_gauge (Model, optional) – A model used to compute a gauge transformation that is applied to the LGST estimates before they are returned. This gauge transformation is computed such that if the estimated gates matched the model given, then the operation matrices would match, i.e. the gauge would be the same as the model supplied. Defaults to target_model.
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
Model – A model containing all of the estimated labels (or aliases)
 pygsti.algorithms.core._lgst_matrix_dims(model, prep_fiducials, effect_fiducials)¶
 pygsti.algorithms.core._construct_ab(prep_fiducials, effect_fiducials, model, dataset, op_label_aliases=None)¶
 pygsti.algorithms.core._construct_x_matrix(prep_fiducials, effect_fiducials, model, op_label_tuple, dataset, op_label_aliases=None)¶
 pygsti.algorithms.core._construct_a(effect_fiducials, model)¶
 pygsti.algorithms.core._construct_b(prep_fiducials, model)¶
 pygsti.algorithms.core._construct_target_ab(prep_fiducials, effect_fiducials, target_model)¶
 pygsti.algorithms.core.gram_rank_and_eigenvalues(dataset, prep_fiducials, effect_fiducials, target_model)¶
Returns the rank and singular values of the Gram matrix for a dataset.
 Parameters
dataset (DataSet) – The data used to populate the Gram matrix
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to make sense of circuit elements, and to compute the theoretical gram matrix eigenvalues (returned as svalues_target).
 Returns
rank (int) – the rank of the Gram matrix
svalues (numpy array) – the singular values of the Gram matrix
svalues_target (numpy array) – the corresponding singular values of the Gram matrix generated by target_model.
 pygsti.algorithms.core.run_gst_fit_simple(dataset, start_model, circuits, optimizer, objective_function_builder, resource_alloc, verbosity=0)¶
Performs core Gate Set Tomography function of model optimization.
Optimizes the parameters of start_model by minimizing the objective function built by objective_function_builder. Probabilities are computed by the model, and outcome counts are supplied by dataset.
 Parameters
dataset (DataSet) – The dataset to obtain counts from.
start_model (Model) – The Model used as a starting point for the leastsquares optimization.
circuits (list of (tuples or Circuits)) – Each tuple contains operation labels and specifies a circuit whose probabilities are considered when trying to leastsquaresfit the probabilities given in the dataset. e.g. [ (), (‘Gx’,), (‘Gx’,’Gy’) ]
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
objective_function_builder (ObjectiveFunctionBuilder) – Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”.
resource_alloc (ResourceAllocation) – A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
result (OptimizerResult) – the result of the optimization
model (Model) – the bestfit model.
 pygsti.algorithms.core.run_gst_fit(mdc_store, optimizer, objective_function_builder, verbosity=0)¶
Performs core Gate Set Tomography function of model optimization.
Optimizes the model to the data within mdc_store by minimizing the objective function built by objective_function_builder.
 Parameters
mdc_store (ModelDatasetCircuitsStore) – An object holding a model, data set, and set of circuits. This defines the model to be optimized, the data to fit to, and the circuits where predicted vs. observed comparisons should be made. This object also contains additional information specific to the given model, data set, and circuit list, doubling as a cache for increased performance. This information is also specific to a particular resource allocation, which affects how cached values stored.
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
objective_function_builder (ObjectiveFunctionBuilder) – Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”. If None, then mdc_store must itself be an alreadybuilt objective function.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
result (OptimizerResult) – the result of the optimization
objfn_store (MDCObjectiveFunction) – the objective function and store containing the bestfit model evaluated at the bestfit point.
 pygsti.algorithms.core.run_iterative_gst(dataset, start_model, circuit_lists, optimizer, iteration_objfn_builders, final_objfn_builders, resource_alloc, verbosity=0)¶
Performs Iterative Gate Set Tomography on the dataset.
 Parameters
dataset (DataSet) – The data used to generate MLGST gate estimates
start_model (Model) – The Model used as a starting point for the leastsquares optimization.
circuit_lists (list of lists of (tuples or Circuits)) – The ith element is a list of the circuits to be used in the ith iteration of the optimization. Each element of these lists is a circuit, specifed as either a Circuit object or as a tuple of operation labels (but all must be specified using the same type). e.g. [ [ (), (‘Gx’,) ], [ (), (‘Gx’,), (‘Gy’,) ], [ (), (‘Gx’,), (‘Gy’,), (‘Gx’,’Gy’) ] ]
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
iteration_objfn_builders (list) – List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on each iteration.
final_objfn_builders (list) – List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on the final iteration.
resource_alloc (ResourceAllocation) – A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
models (list of Models) – list whose ith element is the model corresponding to the results of the ith iteration.
optimums (list of OptimizerResults) – list whose ith element is the final optimizer result from that iteration.
final_objfn (MDSObjectiveFunction) – The final iteration’s objective function / store, which encapsulated the final objective function evaluated at the bestfit point (an “evaluated” modeldataSetcircuits store).
 pygsti.algorithms.core._do_runopt(objective, optimizer, printer)¶
Runs the core modeloptimization step within a GST routine by optimizing objective using optimizer.
This is factored out as a separate function because of the differences when running Taylorterm simtype calculations, which utilize this as a subroutine (see :function:`_do_term_runopt`).
 Parameters
objective (MDSObjectiveFunction) – A “modeldataset” objective function to optimize.
optimizer (Optimizer) – The optimizer to use.
printer (VerbosityPrinter) – An object for printing output.
 Returns
OptimizerResult
 pygsti.algorithms.core._do_term_runopt(objective, optimizer, printer)¶
Runs the core modeloptimization step for models using the Taylorterm (path integral) method of computing probabilities.
This routine serves the same purpose as :function:`_do_runopt`, but is more complex because an appropriate “path set” must be found, requiring a loop of model optimizations with fixed path sets until a sufficient “good” path set is obtained.
 Parameters
objective (MDSObjectiveFunction) – A “modeldataset” objective function to optimize.
optimizer (Optimizer) – The optimizer to use.
printer (VerbosityPrinter) – An object for printing output.
 Returns
OptimizerResult
 pygsti.algorithms.core.find_closest_unitary_opmx(operation_mx)¶
Find the closest (in fidelity) unitary superoperator to operation_mx.
Finds the closest operation matrix (by maximizing fidelity) to operation_mx that describes a unitary quantum gate.
 Parameters
operation_mx (numpy array) – The operation matrix to act on.
 Returns
numpy array – The resulting closest unitary operation matrix.
pygsti.algorithms.directx
¶Functions for generating Direct(LGST, MC2GST, MLGST) models

Constructs a model that contains LGST estimates for circuits_to_estimate. 

Constructs a model of LGST estimates for target gates and circuit_to_estimate. 

Constructs a dictionary with keys == circuits and values == DirectLGST Models. 

Constructs a model of LSGST estimates for target gates and circuit_to_estimate. 

Constructs a dictionary with keys == circuits and values == DirectLSGST Models. 

Constructs a model of MLEGST estimates for target gates and circuit_to_estimate. 

Constructs a dictionary with keys == circuits and values == DirectMLEGST Models. 

Constructs a model containing a single LSGST estimate of circuit_to_estimate. 

Constructs a dictionary with keys == circuits and values == FocusedLSGST Models. 
 pygsti.algorithms.directx.model_with_lgst_circuit_estimates(circuits_to_estimate, dataset, prep_fiducials, meas_fiducials, target_model, include_target_ops=True, op_label_aliases=None, guess_model_for_gauge=None, circuit_labels=None, svd_truncate_to=None, verbosity=0)¶
Constructs a model that contains LGST estimates for circuits_to_estimate.
For each circuit in circuits_to_estimate, the constructed model contains the LGST estimate for s as separate gate, labeled either by the corresponding element of circuit_labels or by the tuple of s itself.
 Parameters
circuits_to_estimate (list of Circuits or tuples) – The circuits to estimate using LGST
dataset (DataSet) – The data to use for LGST
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – A model used by LGST to specify which operation labels should be estimated, a guess for which gauge these estimates should be returned in, and used to simplify circuits.
include_target_ops (bool, optional) – If True, the operation labels in target_model will be included in the returned model.
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
guess_model_for_gauge (Model, optional) – A model used to compute a gauge transformation that is applied to the LGST estimates. This gauge transformation is computed such that if the estimated gates matched the model given, then the gate matrices would match, i.e. the gauge would be the same as the model supplied. Defaults to the target_model.
circuit_labels (list of strings, optional) – A list of labels in onetoone correspondence with the circuit in circuits_to_estimate. These labels are the keys to access the operation matrices in the returned Model, i.e. op_matrix = returned_model[op_label]
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
verbosity (int, optional) – Verbosity value to send to run_lgst(…) call.
 Returns
Model – A model containing LGST estimates for all the requested circuits and possibly the gates in target_model.
 pygsti.algorithms.directx.direct_lgst_model(circuit_to_estimate, circuit_label, dataset, prep_fiducials, meas_fiducials, target_model, op_label_aliases=None, svd_truncate_to=None, verbosity=0)¶
Constructs a model of LGST estimates for target gates and circuit_to_estimate.
 Parameters
circuit_to_estimate (Circuit or tuple) – The single circuit to estimate using LGST
circuit_label (string) – The label for the estimate of circuit_to_estimate. i.e. op_matrix = returned_model[op_label]
dataset (DataSet) – The data to use for LGST
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – The target model used by LGST to extract operation labels and an initial gauge
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
verbosity (int, optional) – Verbosity value to send to run_lgst(…) call.
 Returns
Model – A model containing LGST estimates of circuit_to_estimate and the gates of target_model.
 pygsti.algorithms.directx.direct_lgst_models(circuits, dataset, prep_fiducials, meas_fiducials, target_model, op_label_aliases=None, svd_truncate_to=None, verbosity=0)¶
Constructs a dictionary with keys == circuits and values == DirectLGST Models.
 Parameters
circuits (list of Circuit or tuple objects) – The circuits to estimate using LGST. The elements of this list are the keys of the returned dictionary.
dataset (DataSet) – The data to use for all LGST estimates.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – The target model used by LGST to extract operation labels and an initial gauge
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
verbosity (int, optional) – Verbosity value to send to run_lgst(…) call.
 Returns
dict – A dictionary that relates each circuit to a Model containing the LGST estimate of that circuit’s action (as a SPAMless operation sequence) stored under the operation label “GsigmaLbl”, along with LGST estimates of the gates in target_model.
 pygsti.algorithms.directx.direct_mc2gst_model(circuit_to_estimate, circuit_label, dataset, prep_fiducials, meas_fiducials, target_model, op_label_aliases=None, svd_truncate_to=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=( 1000000.0, 1000000.0), verbosity=0)¶
Constructs a model of LSGST estimates for target gates and circuit_to_estimate.
Starting with a DirectLGST estimate for circuit_to_estimate, runs LSGST using the same strings that LGST would have used to estimate circuit_to_estimate and each of the target gates. That is, LSGST is run with strings of the form:
prep_fiducial
meas_fiducial
prep_fiducial + meas_fiducial
prep_fiducial + single_gate + meas_fiducial
prep_fiducial + circuit_to_estimate + meas_fiducial
and the resulting Model estimate is returned.
 Parameters
circuit_to_estimate (Circuit) – The single circuit to estimate using LSGST
circuit_label (string) – The label for the estimate of circuit_to_estimate. i.e. op_matrix = returned_mode[op_label]
dataset (DataSet) – The data to use for LGST
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – The target model used by LGST to extract operation labels and an initial gauge
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight used within the chi^2 function (see chi2fn).
prob_clip_interval (2tuple, optional) – (min,max) to clip probabilities to within Model probability computation routines (see Model.bulk_fill_probs)
verbosity (int, optional) – Verbosity value to send to run_lgst(…) and do_mc2gst(…) calls.
 Returns
Model – A model containing LSGST estimates of circuit_to_estimate and the gates of target_model.
 pygsti.algorithms.directx.direct_mc2gst_models(circuits, dataset, prep_fiducials, meas_fiducials, target_model, op_label_aliases=None, svd_truncate_to=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=( 1000000.0, 1000000.0), verbosity=0)¶
Constructs a dictionary with keys == circuits and values == DirectLSGST Models.
 Parameters
circuits (list of Circuit or tuple objects) – The circuits to estimate using LSGST. The elements of this list are the keys of the returned dictionary.
dataset (DataSet) – The data to use for all LGST and LSGST estimates.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – The target model used by LGST to extract operation labels and an initial gauge
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight used within the chi^2 function (see chi2fn).
prob_clip_interval (2tuple, optional) – (min,max) to clip probabilities to within Model probability computation routines (see Model.bulk_fill_probs)
verbosity (int, optional) – Verbosity value to send to run_lgst(…) and do_mc2gst(…) calls.
 Returns
dict – A dictionary that relates each circuit to a Model containing the LGST estimate of that circuit’s action (as a SPAMless operation sequence) stored under the operation label “GsigmaLbl”, along with LSGST estimates of the gates in target_model.
 pygsti.algorithms.directx.direct_mlgst_model(circuit_to_estimate, circuit_label, dataset, prep_fiducials, meas_fiducials, target_model, op_label_aliases=None, svd_truncate_to=None, min_prob_clip=1e06, prob_clip_interval=( 1000000.0, 1000000.0), verbosity=0)¶
Constructs a model of MLEGST estimates for target gates and circuit_to_estimate.
Starting with a DirectLGST estimate for circuit_to_estimate, runs MLEGST using the same strings that LGST would have used to estimate circuit_to_estimate and each of the target gates. That is, MLEGST is run with strings of the form:
prep_fiducial
meas_fiducial
prep_fiducial + meas_fiducial
prep_fiducial + singleGate + meas_fiducial
prep_fiducial + circuit_to_estimate + meas_fiducial
and the resulting Model estimate is returned.
 Parameters
circuit_to_estimate (Circuit or tuple) – The single circuit to estimate using LSGST
circuit_label (string) – The label for the estimate of circuit_to_estimate. i.e. op_matrix = returned_model[op_label]
dataset (DataSet) – The data to use for LGST
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – The target model used by LGST to extract operation labels and an initial gauge
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
min_prob_clip (float, optional) – defines the minimum probability “patch point” used within the logl function.
prob_clip_interval (2tuple, optional) – (min,max) to clip probabilities to within Model probability computation routines (see Model.bulk_fill_probs)
verbosity (int, optional) – Verbosity value to send to run_lgst(…) and do_mlgst(…) calls.
 Returns
Model – A model containing MLEGST estimates of circuit_to_estimate and the gates of target_model.
 pygsti.algorithms.directx.direct_mlgst_models(circuits, dataset, prep_fiducials, meas_fiducials, target_model, op_label_aliases=None, svd_truncate_to=None, min_prob_clip=1e06, prob_clip_interval=( 1000000.0, 1000000.0), verbosity=0)¶
Constructs a dictionary with keys == circuits and values == DirectMLEGST Models.
 Parameters
circuits (list of Circuit or tuple objects) – The circuits to estimate using MLEGST. The elements of this list are the keys of the returned dictionary.
dataset (DataSet) – The data to use for all LGST and LSGST estimates.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
target_model (Model) – The target model used by LGST to extract operation labels and an initial gauge
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
min_prob_clip (float, optional) – defines the minimum probability “patch point” used within the logl function.
prob_clip_interval (2tuple, optional) – (min,max) to clip probabilities to within Model probability computation routines (see Model.bulk_fill_probs)
verbosity (int, optional) – Verbosity value to send to run_lgst(…) and do_mlgst(…) calls.
 Returns
dict – A dictionary that relates each circuit to a Model containing the LGST estimate of that circuit’s action (as a SPAMless operation sequence) stored under the operation label “GsigmaLbl”, along with MLEGST estimates of the gates in target_model.
 pygsti.algorithms.directx.focused_mc2gst_model(circuit_to_estimate, circuit_label, dataset, prep_fiducials, meas_fiducials, start_model, op_label_aliases=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=( 1000000.0, 1000000.0), verbosity=0)¶
Constructs a model containing a single LSGST estimate of circuit_to_estimate.
Starting with start_model, run LSGST with the same circuits that LGST would use to estimate circuit_to_estimate. That is, LSGST is run with strings of the form: prep_fiducial + circuit_to_estimate + meas_fiducial and return the resulting Model.
 Parameters
circuit_to_estimate (Circuit or tuple) – The single circuit to estimate using LSGST
circuit_label (string) – The label for the estimate of circuit_to_estimate. i.e. op_matrix = returned_model[op_label]
dataset (DataSet) – The data to use for LGST
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
start_model (Model) – The model to seed LSGST with. Often times obtained via LGST.
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight used within the chi^2 function (see chi2fn).
prob_clip_interval (2tuple, optional) – (min,max) to clip probabilities to within Model probability computation routines (see Model.bulk_fill_probs)
verbosity (int, optional) – Verbosity value to send do_mc2gst(…) call.
 Returns
Model – A model containing LSGST estimate of circuit_to_estimate.
 pygsti.algorithms.directx.focused_mc2gst_models(circuits, dataset, prep_fiducials, meas_fiducials, start_model, op_label_aliases=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=( 1000000.0, 1000000.0), verbosity=0)¶
Constructs a dictionary with keys == circuits and values == FocusedLSGST Models.
 Parameters
circuits (list of Circuit or tuple objects) – The circuits to estimate using LSGST. The elements of this list are the keys of the returned dictionary.
dataset (DataSet) – The data to use for all LGST and LSGST estimates.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
start_model (Model) – The model to seed LSGST with. Often times obtained via LGST.
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. Defaults to the empty dictionary (no aliases defined) e.g. opLabelAliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)
min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight used within the chi^2 function (see chi2fn).
prob_clip_interval (2tuple, optional) – (min,max) to clip probabilities to within Model probability computation routines (see Model.bulk_fill_probs)
verbosity (int, optional) – Verbosity value to send to do_mc2gst(…) call.
 Returns
dict – A dictionary that relates each circuit to a Model containing the LSGST estimate of that circuit’s action, stored under the operation label “GsigmaLbl”.
pygsti.algorithms.fiducialpairreduction
¶Functions for reducing the number of required fiducial pairs for analysis.

Number of combinations of r items out of a set of n. Equals n!/(r!(nr)!) 

Random selection from itertools.combinations(indices_tuple, r) 

Finds a (global) set of fiducial pairs that are amplificationally complete. 

Finds a pergerm set of fiducial pairs that are amplificationally complete. 

Finds a pergerm set of fiducial pairs that are amplificationally complete. 

Tests a set of global or pergerm fiducial pairs. 

 pygsti.algorithms.fiducialpairreduction._nCr(n, r)¶
Number of combinations of r items out of a set of n. Equals n!/(r!(nr)!)
 pygsti.algorithms.fiducialpairreduction._random_combination(indices_tuple, r)¶
 Random selection from itertools.combinations(indices_tuple, r)
from http://docs.python.org/2/library/itertools.html#recipes
 pygsti.algorithms.fiducialpairreduction.find_sufficient_fiducial_pairs(target_model, prep_fiducials, meas_fiducials, germs, test_lengths=(256, 2048), prep_povm_tuples='first', tol=0.75, search_mode='sequential', n_random=100, seed=None, verbosity=0, test_pair_list=None, mem_limit=None, minimum_pairs=1)¶
Finds a (global) set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find a set of fiducial pairs that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). The test for amplification is performed using the two germpower lengths given by test_lengths, and tests whether the magnitudes of the Jacobian’s singular values scale linearly with the germpower length.
In the special case when test_pair_list is not None, the function tests the given set of fiducial pairs for amplificational completeness, and does not perform any search.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
test_lengths ((L1,L2) tuple of ints, optional) – A tuple of integers specifying the germpower lengths to use when checking for amplificational completeness.
prep_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
tol (float, optional) – The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
test_pair_list (list or None, optional) – If not None, a list of (prepfid_index,measfid_index) tuples of integers, specifying a list of fiducial pairs (indices are into prep_fiducials and meas_fiducials, respectively). These pairs are then tested for amplificational completeness and the number of amplified parameters is printed to stdout. (This is a special debugging functionality.)
mem_limit (int, optional) – A memory limit in bytes.
minimum_pairs (int, optional) – The minimium number of fiducial pairs to try (default == 1). Set this to integers larger than 1 to avoid trying pair sets that are known to be too small.
 Returns
list – A list of (prepfid_index,measfid_index) tuples of integers, specifying a list of fiducial pairs (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.fiducialpairreduction.find_sufficient_fiducial_pairs_per_germ(target_model, prep_fiducials, meas_fiducials, germs, pre_povm_tuples='first', search_mode='sequential', constrain_to_tp=True, n_random=100, seed=None, verbosity=0, mem_limit=None)¶
Finds a pergerm set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find sets of fiducial pairs, one set per germ, that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). For each germ, a fiducial pair set is found that amplifies all of the “parameters” (really linear combinations of them) that the particular germ amplifies.
To test whether a set of fiducial pairs satisfies this condition, the sum of projectors P_i = dot(J_i,J_i^T), where J_i is a matrix of the derivatives of each of the selected (prepFiducial+germ+effectFiducial) sequence probabilities with respect to the ith germ eigenvalue (or more generally, amplified parameter), is computed. If the fiducialpair set is sufficient, the rank of the resulting sum (an operator) will be equal to the total (maximal) number of parameters the germ can amplify.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence (per germ) before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
constrain_to_tp (bool, optional) – Whether or not to consider nonTP parameters the the germs amplify. If the fiducal pairs will be used in a GST estimation where the model is constrained to being tracepreserving (TP), this should be set to True.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
dict – A dictionary whose keys are the germ circuits and whose values are lists of (iRhoFid,iMeasFid) tuples of integers, each specifying the list of fiducial pairs for a particular germ (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.fiducialpairreduction.find_sufficient_fiducial_pairs_per_germ_power(target_model, prep_fiducials, meas_fiducials, germs, max_lengths, pre_povm_tuples='first', search_mode='sequential', constrain_to_tp=True, n_random=100, seed=None, verbosity=0, mem_limit=None)¶
Finds a pergerm set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find sets of fiducial pairs, one set per germ, that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). For each germ, a fiducial pair set is found that amplifies all of the “parameters” (really linear combinations of them) that the particular germ amplifies.
To test whether a set of fiducial pairs satisfies this condition, the sum of projectors P_i = dot(J_i,J_i^T), where J_i is a matrix of the derivatives of each of the selected (prepFiducial+germ+effectFiducial) sequence probabilities with respect to the ith germ eigenvalue (or more generally, amplified parameter), is computed. If the fiducialpair set is sufficient, the rank of the resulting sum (an operator) will be equal to the total (maximal) number of parameters the germ can amplify.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
max_lengths (list of int) – The germ powers (number of repetitions) to be used to amplify errors.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence (per germ) before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
constrain_to_tp (bool, optional) – Whether or not to consider nonTP parameters the the germs amplify. If the fiducal pairs will be used in a GST estimation where the model is constrained to being tracepreserving (TP), this should be set to True.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
dict – A dictionary whose keys are the germ circuits and whose values are lists of (iRhoFid,iMeasFid) tuples of integers, each specifying the list of fiducial pairs for a particular germ (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.fiducialpairreduction.test_fiducial_pairs(fid_pairs, target_model, prep_fiducials, meas_fiducials, germs, test_lengths=(256, 2048), pre_povm_tuples='first', tol=0.75, verbosity=0, mem_limit=None)¶
Tests a set of global or pergerm fiducial pairs.
Determines how many model parameters (of target_model) are amplified by the fiducial pairs given by fid_pairs, which can be either a list of 2tuples (for globalFPR) or a dictionary (for pergerm FPR).
 Parameters
fid_pairs (list or dict) – Either a single list of fiducialindex pairs (2tuples) that is applied to every germ (global FPR) OR a pergerm dictionary of lists, each containing the fiducialindex pairs (2tuples) for that germ (for pergerm FPR).
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
test_lengths ((L1,L2) tuple of ints, optional) – A tuple of integers specifying the germpower lengths to use when checking for amplificational completeness.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
tol (float, optional) – The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
numAmplified (int)
 pygsti.algorithms.fiducialpairreduction._get_per_germ_fidpairs(prep_fiducials, meas_fiducials, pre_povm_tuples, gsGerm, mem_limit, printer, search_mode, seed, n_random)¶
pygsti.algorithms.fiducialselection
¶Functions for selecting a complete set of fiducials for a GST analysis.

Generate prep and measurement fiducials for a given target model. 

Implements logical xor function for arbitrary number of inputs. 

Make a list of matrices for the model preparation operations. 

Make a list of matrices for the model measurement operations. 

Compute a composite score for a fiducial list. 

Tests a prep or measure fiducial list for informational completeness. 

Create an array of all lengthn and Hamming weight k binary vectors. 

Find a locally optimal subset of the fiducials in fid_list. 

Use GRASP to find a highperforming set of fiducials. 
 pygsti.algorithms.fiducialselection.find_fiducials(target_model, omit_identity=True, eq_thresh=1e06, ops_to_omit=None, force_empty=True, max_fid_length=2, algorithm='grasp', algorithm_kwargs=None, verbosity=1)¶
Generate prep and measurement fiducials for a given target model.
 Parameters
target_model (Model) – The model you are aiming to implement.
omit_identity (bool, optional) – Whether to remove the identity gate from the set of gates with which fiducials are constructed. Identity gates do nothing to alter fiducials, and so should almost always be left out.
eq_thresh (float, optional) – Threshold for determining if a gate is the identity gate. If the square Frobenius distance between a given gate and the identity gate is less than this threshold, the gate is considered to be an identity gate and will be removed from the list of gates from which to construct fiducials if omit_identity is
True
.ops_to_omit (list of string, optional) – List of strings identifying gates in the model that should not be used in fiducials. Oftentimes this will include the identity gate, and may also include entangling gates if their fidelity is anticipated to be much worse than that of singlesystem gates.
force_empty (bool, optional (default is True)) – Whether or not to force all fiducial sets to contain the empty gate string as a fiducial.
max_fid_length (int, optional) – The maximum number of gates to include in a fiducial. The default is not guaranteed to work for arbitrary models (particularly for quantum systems larger than a single qubit).
algorithm ({'slack', 'grasp'}, optional) –
Specifies the algorithm to use to generate the fiducials. Current options are:
 ’slack’
See
_find_fiducials_integer_slack()
for more details. ’grasp’
Use GRASP to generate random greedy fiducial sets and then locally optimize them. See
_find_fiducials_grasp()
for more details.
algorithm_kwargs (dict) – Dictionary of
{'keyword': keyword_arg}
pairs providing keyword arguments for the specified algorithm function. See the documentation for functions referred to in the algorithm keyword documentation for what options are available for each algorithm.verbosity (int, optional) – How much detail to send to stdout.
 Returns
prepFidList (list of Circuits) – A list containing the circuits for the prep fiducials.
measFidList (list of Circuits) – A list containing the circuits for the measurement fiducials.
 pygsti.algorithms.fiducialselection.xor(*args)¶
Implements logical xor function for arbitrary number of inputs.
 Parameters
args (boollikes) – All the boolean (or booleanlike) objects to be checked for xor satisfaction.
 Returns
output (bool) – True if and only if one and only one element of args is True and the rest are False. False otherwise.
 pygsti.algorithms.fiducialselection.create_prep_mxs(model, prep_fid_list)¶
Make a list of matrices for the model preparation operations.
Makes a list of matrices, where each matrix corresponds to a single preparation operation in the model, and the column of each matrix is a fiducial acting on that state preparation.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
prep_fid_list (list of Circuits) – List of fiducial circuits for constructing an informationally complete state preparation.
 Returns
list – A list of matrices, each of shape (dim, len(prep_fid_list)) where dim is the dimension of model (4 for a single qubit). The length of this list is equal to the number of state preparations in model.
 pygsti.algorithms.fiducialselection.create_meas_mxs(model, meas_fid_list)¶
Make a list of matrices for the model measurement operations.
Makes a list of matrices, where each matrix corresponds to a single measurement effect in the model, and the column of each matrix is the transpose of the measurement effect acting on a fiducial.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
meas_fid_list (list of Circuits) – List of fiducial circuits for constructing an informationally complete measurement.
 Returns
list – A list of matrices, each of shape (dim, len(meas_fid_list)) where dim is the dimension of model (4 for a single qubit). The length of this list is equal to the number of POVM effects in model.
 pygsti.algorithms.fiducialselection.compute_composite_fiducial_score(model, fid_list, prep_or_meas, score_func='all', threshold=1000000.0, return_all=False, op_penalty=0.0, l1_penalty=0.0)¶
Compute a composite score for a fiducial list.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fid_list (list of Circuits) – List of fiducial circuits to test.
prep_or_meas (string ("prep" or "meas")) – Are we testing preparation or measurement fiducials?
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
return_all (bool, optional (default is False)) – Whether the spectrum should be returned along with the score.
op_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
.l1_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
.
 Returns
score (CompositeScore) – The score of the fiducials.
spectrum (numpy.array, optional) – The eigenvalues of the square of the absolute value of the score matrix.
 pygsti.algorithms.fiducialselection.test_fiducial_list(model, fid_list, prep_or_meas, score_func='all', return_all=False, threshold=1000000.0, l1_penalty=0.0, op_penalty=0.0)¶
Tests a prep or measure fiducial list for informational completeness.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fid_list (list of Circuits) – List of fiducial circuits to test.
prep_or_meas (string ("prep" or "meas")) – Are we testing preparation or measurement fiducials?
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
return_all (bool, optional (default is False)) – If true, function returns reciprocals of eigenvalues of fiducial score matrix, and the score of the fiducial set as specified by score_func, in addition to a boolean specifying whether or not the fiducial set is informationally complete
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
l1_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
.op_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
.
 Returns
testResult (bool) – Whether or not the specified fiducial list is informationally complete for the provided model, to within the tolerance specified by threshold.
spectrum (array, optional) – The number of fiducials times the reciprocal of the spectrum of the score matrix. Only returned if return_all == True.
score (float, optional) – The score for the fiducial set; only returned if return_all == True.
 pygsti.algorithms.fiducialselection.build_bitvec_mx(n, k)¶
Create an array of all lengthn and Hamming weight k binary vectors.
 Parameters
n (int) – The length of each bit string.
k (int) – The hamming weight of each bit string.
 Returns
numpy.ndarray – An array of shape (binom(n,k), n) whose rows are the sought binary vectors.
 pygsti.algorithms.fiducialselection._find_fiducials_integer_slack(model, fid_list, prep_or_meas=None, initial_weights=None, score_func='all', max_iter=100, fixed_slack=None, slack_frac=None, return_all=False, force_empty=True, force_empty_score=1e+100, fixed_num=None, threshold=1000000.0, verbosity=1)¶
Find a locally optimal subset of the fiducials in fid_list.
Locally optimal here means that no single fiducial can be excluded without increasing the sum of the reciprocals of the singular values of the “score matrix” (the matrix whose columns are the fiducials acting on the preparation, or the transpose of the measurement acting on the fiducials), by more than a fixed or variable amount of “slack”, as specified by fixed_slack or slack_frac.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fid_list (list of Circuits) – List of all fiducials circuits to consider.
prep_or_meas ({'prep', 'meas'}) – Whether preparation or measturement fiducials are being selected.
initial_weights (listlike) – List or array of either booleans or (0 or 1) integers specifying which fiducials in fid_list comprise the initial fiduial set. If None, then starting point includes all fiducials.
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
max_iter (int, optional) – The maximum number of iterations before stopping.
fixed_slack (float, optional) – If not None, a floating point number which specifies that excluding a fiducial is allowed to increase the fiducial set score additively by fixed_slack. You must specify either fixed_slack or slack_frac.
slack_frac (float, optional) – If not None, a floating point number which specifies that excluding a fiducial is allowed to increase the fiducial set score multiplicatively by (1+slack_frac). You must specify either fixed_slack or slack_frac.
return_all (bool, optional) – If True, return the final “weights” vector and score dictionary in addition to the optimal fiducial list (see below).
force_empty (bool, optional (default is True)) –
Whether or not to force all fiducial sets to contain the empty gate string as a fiducial.
IMPORTANT: This only works if the first element of fid_list is the empty circuit.
force_empty_score (float, optional (default is 1e100)) – When force_empty is True, what score to assign any fiducial set that does not contain the empty circuit as a fiducial.
fixed_num (int, optional) – Require the output list of fiducials to contain exactly fixed_num elements.
threshold (float, optional (default is 1e6)) – Entire fiducial list is first scored before attempting to select fiducials; if score is above threshold, then fiducial selection will autofail. If final fiducial set selected is above threshold, then fiducial selection will print a warning, but return selected set.
verbosity (int, optional) – Integer >= 0 indicating the amount of detail to print.
 Returns
fiducial_list (list) – A list of the selected (optimized) fiducial circuits.
weights (list) – Only returned if return_all=True. The internal weights for each candidate germ.
score (dict) – Only returned if return_all=True. The internal dictionary mapping weights (as a tuple) to scores.
 pygsti.algorithms.fiducialselection._find_fiducials_grasp(model, fids_list, prep_or_meas, alpha, iterations=5, score_func='all', op_penalty=0.0, l1_penalty=0.0, return_all=False, force_empty=True, threshold=1000000.0, seed=None, verbosity=0)¶
Use GRASP to find a highperforming set of fiducials.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fids_list (list of Circuits) – List of fiducial circuits to test.
prep_or_meas (string ("prep" or "meas")) – Are we testing preparation or measurement fiducials?
alpha (float) – A number between 0 and 1 that roughly specifies a score threshold relative to the spread of scores that a germ must score better than in order to be included in the RCL. A value of 0 for alpha corresponds to a purely greedy algorithm (only the bestscoring element is included in the RCL), while a value of 1 for alpha will include all elements in the RCL.
iterations (int, optional) – Number of GRASP iterations.
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
op_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
.l1_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
.return_all (bool, optional (default is False)) – If true, function returns reciprocals of eigenvalues of fiducial score matrix, and the score of the fiducial set as specified by score_func, in addition to a boolean specifying whether or not the fiducial set is informationally complete
force_empty (bool, optional) – When True, the empty circuit must be a member of the chosen set.
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
seed (int, optional) – The seed value used for each individual iteration.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
best_fiducials (list) – The bestscoring list of fiducial circuits.
initial_fiducials (list of lists) – Only returned if return_all=True. A list of the initial solution (a solution is a list of fiducial circuits) for each grasp iteration.
local_solutions (list of lists) – Only returned if return_all=True. A list of the best solution (a solution is a list of fiducial circuits) for each grasp iteration.
pygsti.algorithms.gaugeopt
¶GST gauge optimization algorithms

Optimize the gauge degrees of freedom of a model to that of a target. 

Optimize the gauge of a model using a custom objective function. 

Creates the objective function and jacobian (if available) 

Helper function  same as that in core.py. 

Helper function  same as that in core.py. 

Helper function  CPTP penalty: (sum of tracenorms of gates), 

Helper function  CPTP penalty: (sum of tracenorms of gates), 

Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) 

Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) 
 pygsti.algorithms.gaugeopt.gaugeopt_to_target(model, target_model, item_weights=None, cptp_penalty_factor=0, spam_penalty_factor=0, gates_metric='frobenius', spam_metric='frobenius', gauge_group=None, method='auto', maxiter=100000, maxfev=None, tol=1e08, oob_check_interval=0, return_all=False, comm=None, verbosity=0, check_jac=False)¶
Optimize the gauge degrees of freedom of a model to that of a target.
 Parameters
model (Model) – The model to gaugeoptimize
target_model (Model) – The model to optimize to. The metric used for comparing models is given by gates_metric and spam_metric.
item_weights (dict, optional) – Dictionary of weighting factors for gates and spam operators. Keys can be gate, state preparation, or POVM effect, as well as the special values “spam” or “gates” which apply the given weighting to all spam operators or gates respectively. Values are floating point numbers. Values given for specific gates or spam operators take precedence over “gates” and “spam” values. The precise use of these weights depends on the model metric(s) being used.
cptp_penalty_factor (float, optional) – If greater than zero, the objective function also contains CPTP penalty terms which penalize nonCPTPness of the gates being optimized. This factor multiplies these CPTP penalty terms.
spam_penalty_factor (float, optional) – If greater than zero, the objective function also contains SPAM penalty terms which penalize nonpositiveness of the state preps being optimized. This factor multiplies these SPAM penalty terms.
gates_metric ({"frobenius", "fidelity", "tracedist"}, optional) – The metric used to compare gates within models. “frobenius” computes the normalized sqrt(sumofsquareddifferences), with weights multiplying the squared differences (see
Model.frobeniusdist()
). “fidelity” and “tracedist” sum the individual infidelities or trace distances of each gate, weighted by the weights.spam_metric ({"frobenius", "fidelity", "tracedist"}, optional) – The metric used to compare spam vectors within models. “frobenius” computes the normalized sqrt(sumofsquareddifferences), with weights multiplying the squared differences (see
Model.frobeniusdist()
). “fidelity” and “tracedist” sum the individual infidelities or trace distances of each “SPAM gate”, weighted by the weights.gauge_group (GaugeGroup, optional) – The gauge group which defines which gauge trasformations are optimized over. If None, then the model’s default gauge group is used.
method (string, optional) –
The method used to optimize the objective function. Can be any method known by scipy.optimize.minimize such as ‘BFGS’, ‘NelderMead’, ‘CG’, ‘LBFGSB’, or additionally:
’auto’ – ‘ls’ when allowed, otherwise ‘LBFGSB’
’ls’ – custom leastsquares optimizer.
’custom’ – custom CG that often works better than ‘CG’
’supersimplex’ – repeated application of ‘NelderMead’ to converge it
’basinhopping’ – scipy.optimize.basinhopping using LBFGSB as a local optimizer
’swarm’ – particle swarm global optimization algorithm
’evolve’ – evolutionary global optimization algorithm using DEAP
’brute’ – Experimental: scipy.optimize.brute using 4 points along each dimensions
maxiter (int, optional) – Maximum number of iterations for the gauge optimization.
maxfev (int, optional) – Maximum number of function evaluations for the gauge optimization. Defaults to maxiter.
tol (float, optional) – The tolerance for the gauge optimization.
oob_check_interval (int, optional) – If greater than zero, gauge transformations are allowed to fail (by raising any exception) to indicate an outofbounds condition that the gauge optimizer will avoid. If zero, then any gaugetransform failures just terminate the optimization.
return_all (bool, optional) – When True, return best “goodness” value and gauge matrix in addition to the gauge optimized model.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
verbosity (int, optional) – How much detail to send to stdout.
check_jac (bool) – When True, check least squares analytic jacobian against finite differences
 Returns
model if return_all == False
(goodnessMin, gaugeMx, model) if return_all == True – where goodnessMin is the minimum value of the goodness function (the best ‘goodness’) found, gaugeMx is the gauge matrix used to transform the model, and model is the final gaugetransformed model.
 pygsti.algorithms.gaugeopt.gaugeopt_custom(model, objective_fn, gauge_group=None, method='LBFGSB', maxiter=100000, maxfev=None, tol=1e08, oob_check_interval=0, return_all=False, jacobian_fn=None, comm=None, verbosity=0)¶
Optimize the gauge of a model using a custom objective function.
 Parameters
model (Model) – The model to gaugeoptimize
objective_fn (function) – The function to be minimized. The function must take a single Model argument and return a float.
gauge_group (GaugeGroup, optional) – The gauge group which defines which gauge trasformations are optimized over. If None, then the model’s default gauge group is used.
method (string, optional) –
The method used to optimize the objective function. Can be any method known by scipy.optimize.minimize such as ‘BFGS’, ‘NelderMead’, ‘CG’, ‘LBFGSB’, or additionally:
’custom’ – custom CG that often works better than ‘CG’
’supersimplex’ – repeated application of ‘NelderMead’ to converge it
’basinhopping’ – scipy.optimize.basinhopping using LBFGSB as a local optimizer
’swarm’ – particle swarm global optimization algorithm
’evolve’ – evolutionary global optimization algorithm using DEAP
’brute’ – Experimental: scipy.optimize.brute using 4 points along each dimensions
maxiter (int, optional) – Maximum number of iterations for the gauge optimization.
maxfev (int, optional) – Maximum number of function evaluations for the gauge optimization. Defaults to maxiter.
tol (float, optional) – The tolerance for the gauge optimization.
oob_check_interval (int, optional) – If greater than zero, gauge transformations are allowed to fail (by raising any exception) to indicate an outofbounds condition that the gauge optimizer will avoid. If zero, then any gaugetransform failures just terminate the optimization.
return_all (bool, optional) – When True, return best “goodness” value and gauge matrix in addition to the gauge optimized model.
jacobian_fn (function, optional) – The jacobian of objective_fn. The function must take three parameters, 1) the untransformed Model, 2) the transformed Model, and 3) the GaugeGroupElement representing the transformation that brings the first argument into the second.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
model if return_all == False
(goodnessMin, gaugeMx, model) if return_all == True – where goodnessMin is the minimum value of the goodness function (the best ‘goodness’) found, gaugeMx is the gauge matrix used to transform the model, and model is the final gaugetransformed model.
 pygsti.algorithms.gaugeopt._create_objective_fn(model, target_model, item_weights=None, cptp_penalty_factor=0, spam_penalty_factor=0, gates_metric='frobenius', spam_metric='frobenius', method=None, comm=None, check_jac=False)¶
Creates the objective function and jacobian (if available) for gaugeopt_to_target
 pygsti.algorithms.gaugeopt._cptp_penalty_size(mdl)¶
Helper function  same as that in core.py.
 pygsti.algorithms.gaugeopt._spam_penalty_size(mdl)¶
Helper function  same as that in core.py.
 pygsti.algorithms.gaugeopt._cptp_penalty(mdl, prefactor, op_basis)¶
Helper function  CPTP penalty: (sum of tracenorms of gates), which in least squares optimization means returning an array of the sqrt(tracenorm) of each gate. This function is the same as that in core.py.
 Returns
numpy array – a (real) 1D array of length len(mdl.operations).
 pygsti.algorithms.gaugeopt._spam_penalty(mdl, prefactor, op_basis)¶
Helper function  CPTP penalty: (sum of tracenorms of gates), which in least squares optimization means returning an array of the sqrt(tracenorm) of each gate. This function is the same as that in core.py.
 Returns
numpy array – a (real) 1D array of length _spam_penalty_size(mdl)
 pygsti.algorithms.gaugeopt._cptp_penalty_jac_fill(cp_penalty_vec_grad_to_fill, mdl_pre, mdl_post, gauge_group_el, prefactor, op_basis, wrt_filter)¶
Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) Returns a (real) array of shape (len(mdl.operations), gauge_group_el.num_params).
 pygsti.algorithms.gaugeopt._spam_penalty_jac_fill(spam_penalty_vec_grad_to_fill, mdl_pre, mdl_post, gauge_group_el, prefactor, op_basis, wrt_filter)¶
Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) Returns a (real) array of shape (_spam_penalty_size(mdl), gauge_group_el.num_params).
pygsti.algorithms.germselection
¶Functions for selecting a complete set of germs for a GST analysis.

Generate a germ set for doing GST with a given target model. 

Calculate the score of a germ set with respect to a model. 

Get the number of gates and gauge parameters of the models in a list. 

Sets up a list of randomize models (helper function). 

Compute the score for a germ set when it is not AC against a model. 

Calculate the positive squares of the germ Jacobians. 

Calculate the positive squares of the germ Jacobian. 

Returns a germ set "score" in which smaller is better. 

Applies random unitary perturbations to a model or list of models. 

Check to see if the germs_list is amplificationally complete (AC). 

Returns a copy of model with state preparations and effects removed. 

Return the number of nongauge, nonSPAM parameters in model. 

Return super operator for doing a perfect twirl with respect to wrt. 

Calculate the squared singular values of the Jacobian of the germ set. 

Compute the "Twirled Derivative" of a circuit. 

Compute the "Twirled Derivative" of a set of circuits. 

Test whether a set of germs is able to amplify all nongauge parameters. 

Test whether a set of germs is able to amplify all nongauge parameters. 

Greedy germ selection algorithm starting with 0 germs. 

Greedy algorithm starting with 0 germs. 

Find a locally optimal subset of the germs in germs_list. 

Score a germ set against a collection of models. 

Use GRASP to find a highperforming germ set. 
 pygsti.algorithms.germselection.FLOATSIZE = 8¶
 pygsti.algorithms.germselection.find_germs(target_model, randomize=True, randomization_strength=0.01, num_gs_copies=5, seed=None, candidate_germ_counts=None, candidate_seed=None, force='singletons', algorithm='greedy', algorithm_kwargs=None, mem_limit=None, comm=None, profiler=None, verbosity=1)¶
Generate a germ set for doing GST with a given target model.
This function provides a streamlined interface to a variety of germ selection algorithms. It’s goal is to provide a method that typical users can run by simply providing a target model and leaving all other settings at their default values, while providing flexibility for users desiring more control to fine tune some of the general and algorithmspecific details.
Currently, to break troublesome degeneracies and provide some confidence that the chosen germ set is amplificationally complete (AC) for all models in a neighborhood of the target model (rather than only the target model), an ensemble of models with random unitary perturbations to their gates must be provided or generated.
 Parameters
target_model (Model or list of Model) – The model you are aiming to implement, or a list of models that are copies of the model you are trying to implement (either with or without random unitary perturbations applied to the models).
randomize (bool, optional) – Whether or not to add random unitary perturbations to the model(s) provided.
randomization_strength (float, optional) – The size of the random unitary perturbations applied to gates in the model. See
randomize_with_unitary()
for more details.num_gs_copies (int, optional) – The number of copies of the original model that should be used.
seed (int, optional) – Seed for generating random unitary perturbations to models. Also passed along to stochastic germselection algorithms.
candidate_germ_counts (dict, optional) – A dictionary of germ_length : count keyvalue pairs, specifying the germ “candidate list”  a list of potential germs to draw from. count is either an integer specifying the number of random germs considered at the given germ_length or the special values “all upto” that considers all of the of all nonequivalent germs of length up to the corresponding germ_length. If None, all germs of up to length 6 are used, the equivalent of {6: ‘all upto’}.
candidate_seed (int, optional) – A seed value used when randomly selecting candidate germs. For each germ length being randomly selected, the germ length is added to the value of candidate_seed to get the actual seed used.
force (str or list, optional) – A list of Circuits which must be included in the final germ set. If set to the special string “singletons” then all length1 strings will be included. Seting to None is the same as an empty list.
algorithm ({'greedy', 'grasp', 'slack'}, optional) –
Specifies the algorithm to use to generate the germ set. Current options are: ‘greedy’
Add germs oneatatime until the set is AC, picking the germ that improves the germset score by the largest amount at each step. See
find_germs_breadthfirst()
for more details. ’grasp’
Use GRASP to generate random greedy germ sets and then locally optimize them. See
find_germs_grasp()
for more details. ’slack’
From a initial set of germs, add or remove a germ at each step in an attempt to improve the germset score. Will allow moves that degrade the score in an attempt to escape local optima as long as the degredation is within some specified amount of “slack”. See
find_germs_integer_slack()
for more details.
algorithm_kwargs (dict) – Dictionary of
{'keyword': keyword_arg}
pairs providing keyword arguments for the specified algorithm function. See the documentation for functions referred to in the algorithm keyword documentation for what options are available for each algorithm.mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
profiler (Profiler, optional) – A profiler object used for to track timing and memory usage.
verbosity (int, optional) – The verbosity level of the
VerbosityPrinter
used to print log messages.
 Returns
list of Circuit – A list containing the germs making up the germ set.
 pygsti.algorithms.germselection.compute_germ_set_score(germs, target_model=None, neighborhood=None, neighborhood_size=5, randomization_strength=0.01, score_func='all', op_penalty=0.0, l1_penalty=0.0)¶
Calculate the score of a germ set with respect to a model.
More precisely, this function computes the maximum score (roughly equal to the number of amplified parameters) for a cloud of models. If target_model is given, it serves as the center of the cloud, otherwise the cloud must be supplied directly via neighborhood.
 Parameters
germs (list) – The germ set
target_model (Model, optional) – The target model, used to generate a neighborhood of randomized models.
neighborhood (list of Models, optional) – The “cloud” of models for which scores are computed. If not None, this overrides target_model, neighborhood_size, and randomization_strength.
neighborhood_size (int, optional) – Number of randomized models to construct around target_model.
randomization_strength (float, optional) – Strength of unitary randomizations, as passed to :method:`target_model.randomize_with_unitary`.
score_func ({'all', 'worst'}) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/input_array)
. If ‘worst’, score is1/min(input_array)
.op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
l1_penalty (float, optional) – Coefficient for a penalty linear in the number of germs.
 Returns
CompositeScore – The maximum score for germs, indicating how many parameters it amplifies.
 pygsti.algorithms.germselection._get_model_params(model_list)¶
Get the number of gates and gauge parameters of the models in a list.
Also verifies all models have the same number of gates and gauge parameters.
 Parameters
model_list (list of Model) – A list of models for which you want an AC germ set.
 Returns
reducedModelList (list of Model) – The original list of models with SPAM removed
numGaugeParams (int) – The number of nonSPAM gauge parameters for all models.
numNonGaugeParams (int) – The number of nonSPAM nongauge parameters for all models.
numOps (int) – The number of gates for all models.
 Raises
ValueError – If the number of gauge parameters or gates varies among the models.
 pygsti.algorithms.germselection._setup_model_list(model_list, randomize, randomization_strength, num_copies, seed)¶
Sets up a list of randomize models (helper function).
 pygsti.algorithms.germselection.compute_composite_germ_set_score(score_fn, threshold_ac=1000000.0, init_n=1, partial_deriv_dagger_deriv=None, model=None, partial_germs_list=None, eps=None, num_gauge_params=None, op_penalty=0.0, germ_lengths=None, l1_penalty=0.0)¶
Compute the score for a germ set when it is not AC against a model.
Normally scores computed for germ sets against models for which they are not AC will simply be astronomically large. This is fine if AC is all you care about, but not so useful if you want to compare partial germ sets against one another to see which is closer to being AC. This function will see if the germ set is AC for the parameters corresponding to the largest N eigenvalues for increasing N until it finds a value of N for which the germ set is not AC or all the non gauge parameters are accounted for and report the value of N as well as the score. This allows partial germ set scores to be compared against oneanother sensibly, where a larger value of N always beats a smaller value of N, and ties in the value of N are broken by the score for that value of N.
 Parameters
score_fn (callable) – A function that takes as input a list of sorted eigenvalues and returns a score for the partial germ set based on those eigenvalues, with lower scores indicating better germ sets. Usually some flavor of
list_score()
.threshold_ac (float, optional) – Value which the score (before penalties are applied) must be lower than for the germ set to be considered AC.
init_n (int) – The number of largest eigenvalues to begin with checking.
partial_deriv_dagger_deriv (numpy.array, optional) – Array with three axes, where the first axis indexes individual germs within the partial germ set and the remaining axes index entries in the positive square of the Jacobian of each individual germ’s parameters with respect to the model parameters. If this array is not supplied it will need to be computed from germs_list and model, which will take longer, so it is recommended to precompute this array if this routine will be called multiple times.
model (Model, optional) – The model against which the germ set is to be scored. Not needed if partial_deriv_dagger_deriv is provided.
partial_germs_list (list of Circuit, optional) – The list of germs in the partial germ set to be evaluated. Not needed if partial_deriv_dagger_deriv (and germ_lengths when
op_penalty > 0
) are provided.eps (float, optional) – Used when calculating partial_deriv_dagger_deriv to determine if two eigenvalues are equal (see
_bulk_twirled_deriv()
for details). Not used if partial_deriv_dagger_deriv is provided.num_gauge_params (int) – The number of gauge parameters of the model. Not needed if model is provided.
op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths (numpy.array, optional) – The length of each germ. Not needed if op_penalty is
0.0
or partial_germs_list is provided.l1_penalty (float, optional) – Coefficient for a penalty linear in the number of germs.
 Returns
CompositeScore – The score for the germ set indicating how many parameters it amplifies and its numerical score restricted to those parameters.
 pygsti.algorithms.germselection._compute_bulk_twirled_ddd(model, germs_list, eps=1e06, check=False, germ_lengths=None, comm=None)¶
Calculate the positive squares of the germ Jacobians.
twirledDerivDaggerDeriv == array J.H*J contributions from each germ (J=Jacobian) indexed by (iGerm, iModelParam1, iModelParam2) size (nGerms, vec_model_dim, vec_model_dim)
 Parameters
model (Model) – The model defining the parameters to differentiate with respect to.
germs_list (list) – The germ set
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
germ_lengths (numpy.ndarray, optional) – A precomputed array of the length (depth) of each germ.
comm (mpi4py.MPI.Comm, optional) – When not
None
, an MPI communicator for distributing the computation across multiple processors.
 Returns
twirledDerivDaggerDeriv (numpy.ndarray) – A complex array of shape (len(germs), model.num_params, model.num_params).
 pygsti.algorithms.germselection._compute_twirled_ddd(model, germ, eps=1e06)¶
Calculate the positive squares of the germ Jacobian.
twirledDerivDaggerDeriv == array J.H*J contributions from germ (J=Jacobian) indexed by (iModelParam1, iModelParam2) size (vec_model_dim, vec_model_dim)
 Parameters
model (Model) – The model defining the parameters to differentiate with respect to.
germ (Circuit) – The (single) germ circuit to consider. J above is the twirled derivative of this circuit’s action (process matrix).
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
 Returns
numpy.ndarray
 pygsti.algorithms.germselection._germ_set_score_slack(weights, model_num, score_func, deriv_dagger_deriv_list, force_indices, force_score, n_gauge_params, op_penalty, germ_lengths, l1_penalty=0.01, score_dict=None)¶
Returns a germ set “score” in which smaller is better.
Also returns intentionally bad score (force_score) if weights is zero on any of the “forced” germs (i.e. at any index in forcedIndices). This function is included for use by
find_germs_integer_slack()
, but is not convenient for just computing the score of a germ set. For that, usecompute_germ_set_score()
. Parameters
weights (list) – The pergerm “selection weight”, indicating whether the germ is present in the selected germ set or not.
model_num (int) – index into deriv_dagger_deriv_list indicating which model (typically in a neighborhood) we’re computing scores for.
score_func ({'all', 'worst'}) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/input_array)
. If ‘worst’, score is1/min(input_array)
.deriv_dagger_deriv_list (numpy.ndarray) – Array of J.T * J contributions for each model.
force_indices (list of ints) – Indices marking the germs that must be in the final set (or else force_score will be returned).
force_score (float) – The score that is returned when any of the germs indexed by force_indices are not present (i.e. their weights are <= 0).
n_gauge_params (int) – The number of gauge (not amplifiable) parameters in the model.
op_penalty (float) – Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths (numpy.ndarray) – A precomputed array of the length (depth) of each germ.
l1_penalty (float) – Coefficient for a penalty linear in the number of germs.
score_dict (dict, optional) – A dictionary to cache the score valies for the given model_num and weights, i.e. score_dict[model_num, tuple(weights)] is set to the returned value.
 Returns
float
 pygsti.algorithms.germselection.randomize_model_list(model_list, randomization_strength, num_copies, seed=None)¶
Applies random unitary perturbations to a model or list of models.
If model_list is a length1 list, then num_copies determines how many randomizations to create. If model_list containes multiple models, then num_copies must be None and each model is randomized once to create the corresponding returned model.
 Parameters
model_list (Model or list) – A list of Model objects.
randomization_strength (float, optional) – Strength of unitary randomizations, as passed to :method:`Model.randomize_with_unitary`.
num_copies (int) – The number of random perturbations of model_list[0] to generate when len(model_list) == 1. A value of None will result in 1 copy. If len(model_list) > 1 then num_copies must be set to None.
seed (int, optional) – Starting seed for randomization. Successive randomizations receive successive seeds. None results in random seeds.
 Returns
list – A list of the randomized Models.
 pygsti.algorithms.germselection.test_germs_list_completeness(model_list, germs_list, score_func, threshold)¶
Check to see if the germs_list is amplificationally complete (AC).
Checks for AC with respect to all the Models in model_list, returning the index of the first Model for which it is not AC or 1 if it is AC for all Models.
 Parameters
model_list (list) – A list of models to test. Often this list is a neighborhood (“cloud”) of models around a model of interest.
germs_list (list) – A list of the germ :class:`Circuit`s (the “germ set”) to test for completeness.
score_func ({'all', 'worst'}) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/eigval_array)
. If ‘worst’, score is1/min(eigval_array)
.threshold (float, optional) – An eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when its reciprocal is greater than threshold. Also used for eigenvector degeneracy testing in twirling operation.
 Returns
int – The index of the first model in model_list to fail the amplficational completeness test.
 pygsti.algorithms.germselection._remove_spam_vectors(model)¶
Returns a copy of model with state preparations and effects removed.
 Parameters
model (Model) – The model to act on.
 Returns
Model
 pygsti.algorithms.germselection._num_non_spam_gauge_params(model)¶
Return the number of nongauge, nonSPAM parameters in model.
Equivalent to _remove_spam_vectors(model).num_gauge_params.
 Parameters
model (Model) –
model – The model to act on.
 Returns
int
 pygsti.algorithms.germselection._super_op_for_perfect_twirl(wrt, eps)¶
Return super operator for doing a perfect twirl with respect to wrt.
 pygsti.algorithms.germselection._sq_sing_vals_from_deriv(deriv, weights=None)¶
Calculate the squared singular values of the Jacobian of the germ set.
 Parameters
deriv (numpy.array) – Array of shape
(nGerms, flattened_op_dim, vec_model_dim)
. Each subarray corresponding to an individual germ is the Jacobian of the vectorized gate representation of that germ raised to some power with respect to the model parameters, normalized by dividing by the length of each germ after repetition.weights (numpy.array) – Array of length
nGerms
, giving the relative contributions of each individual germ’s Jacobian to the combined Jacobian (which is calculated as a convex combination of the individual Jacobians).
 Returns
numpy.array – The sorted squared singular values of the combined Jacobian of the germ set.
 pygsti.algorithms.germselection._twirled_deriv(model, circuit, eps=1e06)¶
Compute the “Twirled Derivative” of a circuit.
The twirled derivative is obtained by acting on the standard derivative of a circuit with the twirling superoperator.
 Parameters
model (Model object) – The Model which associates operation labels with operators.
circuit (Circuit object) – A twirled derivative of this circuit’s action (process matrix) is taken.
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
 Returns
numpy array – An array of shape (op_dim^2, num_model_params)
 pygsti.algorithms.germselection._bulk_twirled_deriv(model, circuits, eps=1e06, check=False, comm=None)¶
Compute the “Twirled Derivative” of a set of circuits.
The twirled derivative is obtained by acting on the standard derivative of a circuit with the twirling superoperator.
 Parameters
model (Model object) – The Model which associates operation labels with operators.
circuits (list of Circuit objects) – A twirled derivative of this circuit’s action (process matrix) is taken.
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
 Returns
numpy array – An array of shape (num_simplified_circuits, op_dim^2, num_model_params)
 pygsti.algorithms.germselection.test_germ_set_finitel(model, germs_to_test, length, weights=None, return_spectrum=False, tol=1e06)¶
Test whether a set of germs is able to amplify all nongauge parameters.
 Parameters
model (Model) – The Model (associates operation matrices with operation labels).
germs_to_test (list of Circuits) – List of germ circuits to test for completeness.
length (int) – The finite length to use in amplification testing. Larger values take longer to compute but give more robust results.
weights (numpy array, optional) – A 1D array of weights with length equal len(germs_to_test), which multiply the contribution of each germ to the total jacobian matrix determining parameter amplification. If None, a uniform weighting of 1.0/len(germs_to_test) is applied.
return_spectrum (bool, optional) – If True, return the jacobian^T*jacobian spectrum in addition to the success flag.
tol (float, optional) – Tolerance: an eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when it is less than tol.
 Returns
success (bool) – Whether all nongauge parameters were amplified.
spectrum (numpy array) – Only returned when return_spectrum is
True
. Sorted array of eigenvalues (from small to large) of the jacobian^T * jacobian matrix used to determine parameter amplification.
 pygsti.algorithms.germselection.test_germ_set_infl(model, germs_to_test, score_func='all', weights=None, return_spectrum=False, threshold=1000000.0, check=False)¶
Test whether a set of germs is able to amplify all nongauge parameters.
 Parameters
model (Model) – The Model (associates operation matrices with operation labels).
germs_to_test (list of Circuit) – List of germ circuits to test for completeness.
score_func (string) – Label to indicate how a germ set is scored. See
list_score()
for details.weights (numpy array, optional) – A 1D array of weights with length equal len(germs_to_test), which multiply the contribution of each germ to the total jacobian matrix determining parameter amplification. If None, a uniform weighting of 1.0/len(germs_to_test) is applied.
return_spectrum (bool, optional) – If
True
, return the jacobian^T*jacobian spectrum in addition to the success flag.threshold (float, optional) – An eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when its reciprocal is greater than threshold. Also used for eigenvector degeneracy testing in twirling operation.
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
 Returns
success (bool) – Whether all nongauge parameters were amplified.
spectrum (numpy array) – Only returned when return_spectrum is
True
. Sorted array of eigenvalues (from small to large) of the jacobian^T * jacobian matrix used to determine parameter amplification.
 pygsti.algorithms.germselection.find_germs_depthfirst(model_list, germs_list, randomize=True, randomization_strength=0.001, num_copies=None, seed=0, op_penalty=0, score_func='all', tol=1e06, threshold=1000000.0, check=False, force='singletons', verbosity=0)¶
Greedy germ selection algorithm starting with 0 germs.
Tries to minimize the number of germs needed to achieve amplificational completeness (AC). Begins with 0 germs and adds the germ that increases the score used to check for AC by the largest amount at each step, stopping when the threshold for AC is achieved.
 Parameters
model_list (Model or list) – The model or list of `Model`s to select germs for.
germs_list (list of Circuit) – The list of germs to contruct a germ set from.
randomize (bool, optional) – Whether or not to randomize model_list (usually just a single Model) with small (see randomizationStrengh) unitary maps in order to avoid “accidental” symmetries which could allow for fewer germs but only for that particular model. Setting this to True will increase the run time by a factor equal to the numer of randomized copies (num_copies).
randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
.num_copies (int, optional) – The number of randomized models to create when only a single gate set is passed via model_list. Otherwise, num_copies must be set to None.
seed (int, optional) – Seed for generating random unitary perturbations to models.
op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
score_func ({'all', 'worst'}, optional) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/eigenvalues)
. If ‘worst’, score is1/min(eiganvalues)
.tol (float, optional) – Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate.threshold (float, optional) – Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
check (bool, optional) – Whether to perform internal checks (will slow down run time substantially).
force (list of Circuits) – A list of Circuit objects which must be included in the final germ set. If the special string “singletons” is given, then all of the single gates (length1 sequences) must be included.
verbosity (int, optional) – Level of detail printed to stdout.
 Returns
list – A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.germselection.find_germs_breadthfirst(model_list, germs_list, randomize=True, randomization_strength=0.001, num_copies=None, seed=0, op_penalty=0, score_func='all', tol=1e06, threshold=1000000.0, check=False, force='singletons', pretest=True, mem_limit=None, comm=None, profiler=None, verbosity=0)¶
Greedy algorithm starting with 0 germs.
Tries to minimize the number of germs needed to achieve amplificational completeness (AC). Begins with 0 germs and adds the germ that increases the score used to check for AC by the largest amount (for the model that currently has the lowest score) at each step, stopping when the threshold for AC is achieved. This strategy is something of a “breadthfirst” approach, in contrast to
find_germs_depthfirst()
, which only looks at the scores for one model at a time until that model achieves AC, then turning it’s attention to the remaining models. Parameters
model_list (Model or list) – The model or list of `Model`s to select germs for.
germs_list (list of Circuit) – The list of germs to contruct a germ set from.
randomize (bool, optional) – Whether or not to randomize model_list (usually just a single Model) with small (see randomizationStrengh) unitary maps in order to avoid “accidental” symmetries which could allow for fewer germs but only for that particular model. Setting this to True will increase the run time by a factor equal to the numer of randomized copies (num_copies).
randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
.num_copies (int, optional) – The number of randomized models to create when only a single gate set is passed via model_list. Otherwise, num_copies must be set to None.
seed (int, optional) – Seed for generating random unitary perturbations to models.
op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
score_func ({'all', 'worst'}, optional) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/eigenvalues)
. If ‘worst’, score is1/min(eiganvalues)
.tol (float, optional) – Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate.threshold (float, optional) – Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
check (bool, optional) – Whether to perform internal checks (will slow down run time substantially).
force (list of Circuits) – A list of Circuit objects which must be included in the final germ set. If the special string “singletons” is given, then all of the single gates (length1 sequences) must be included.
pretest (boolean, optional) – Whether germ list should be initially checked for completeness.
mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
profiler (Profiler, optional) – A profiler object used for to track timing and memory usage.
verbosity (int, optional) – Level of detail printed to stdout.
 Returns
list – A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.germselection.find_germs_integer_slack(model_list, germs_list, randomize=True, randomization_strength=0.001, num_copies=None, seed=0, l1_penalty=0.01, op_penalty=0, initial_weights=None, score_func='all', max_iter=100, fixed_slack=False, slack_frac=False, return_all=False, tol=1e06, check=False, force='singletons', force_score=1e+100, threshold=1000000.0, verbosity=1)¶
Find a locally optimal subset of the germs in germs_list.
Locally optimal here means that no single germ can be excluded without making the smallest nongauge eigenvalue of the Jacobian.H*Jacobian matrix smaller, i.e. less amplified, by more than a fixed or variable amount of “slack”, as specified by fixed_slack or slack_frac.
 Parameters
model_list (Model or list of Model) – The list of Models to be tested. To ensure that the returned germ set is amplficationally complete, it is a good idea to score potential germ sets against a collection (~510) of similar models. The user may specify a single Model and a number of unitarily close copies to be made (set by the kwarg num_copies), or the user may specify their own list of Models, each of which in turn may or may not be randomized (set by the kwarg randomize).
germs_list (list of Circuit) – List of all germ circuits to consider.
randomize (Bool, optional) – Whether or not the input Model(s) are first subject to unitary randomization. If
False
, the user should perform the unitary randomization themselves. Note: If the Model(s) are perfect (e.g.std1Q_XYI.target_model()
), then the germ selection output should not be trusted, due to accidental degeneracies in the Model. If the Model(s) include stochastic (nonunitary) error, then germ selection will fail, as we score amplificational completeness in the limit of infinite sequence length (so any stochastic noise will completely depolarize any sequence in that limit). Default isTrue
.randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. Default is1e3
.num_copies (int, optional) – The number of Model copies to be made of the input Model (prior to unitary randomization). If more than one Model is passed in, num_copies should be
None
. If only one Model is passed in and num_copies isNone
, no extra copies are made.seed (float, optional) – The starting seed used for unitary randomization. If multiple Models are to be randomized,
model_list[i]
is randomized withseed + i
. Default is 0.l1_penalty (float, optional) – How strong the penalty should be for increasing the germ set list by a single germ. Default is 1e2.
op_penalty (float, optional) – How strong the penalty should be for increasing a germ in the germ set list by a single gate. Default is 0.
initial_weights (listlike) – List or array of either booleans or (0 or 1) integers specifying which germs in germ_list comprise the initial germ set. If
None
, then starting point includes all germs.score_func (string) – Label to indicate how a germ set is scored. See
list_score()
for details.max_iter (int, optional) – The maximum number of iterations before giving up.
fixed_slack (float, optional) – If not
None
, a floating point number which specifies that excluding a germ is allowed to increase 1.0/smallestnongaugeeigenvalue by fixed_slack. You must specify either fixed_slack or slack_frac.slack_frac (float, optional) – If not
None
, a floating point number which specifies that excluding a germ is allowed to increase 1.0/smallestnongaugeeigenvalue by fixedFrac`*100 percent. You must specify *either* `fixed_slack or slack_frac.return_all (bool, optional) – If
True
, return the finalweights
vector and score dictionary in addition to the optimal germ list (see below).tol (float, optional) – Tolerance used for eigenvector degeneracy testing in twirling operation.
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
force (str or list, optional) – A list of Circuits which must be included in the final germ set. If set to the special string “singletons” then all length1 strings will be included. Seting to None is the same as an empty list.
force_score (float, optional (default is 1e100)) – When force designates a nonempty set of circuits, the score to assign any germ set that does not contain each and every required germ.
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the germ set is rejected as amplificationally incomplete.
verbosity (int, optional) – Integer >= 0 indicating the amount of detail to print.
See also
Model
,Circuit
 pygsti.algorithms.germselection._germ_set_score_grasp(germ_set, germs_list, twirled_deriv_dagger_deriv_list, non_ac_kwargs, init_n=1)¶
Score a germ set against a collection of models.
Calculate the score of the germ set with respect to each member of a collection of models and return the worst score among that collection.
 Parameters
germ_set (list of Circuit) – The set of germs to score.
germs_list (list of Circuit) – The list of all germs whose Jacobians are provided in twirled_deriv_dagger_deriv_list.
twirled_deriv_dagger_deriv_list (numpy.array) – Jacobians for all the germs in germs_list stored as a 3dimensional array, where the first index indexes the particular germ.
non_ac_kwargs (dict) – Dictionary containing further arguments to pass to
compute_composite_germ_set_score()
for the scoring of the germ set against individual models.init_n (int) – The number of eigenvalues to begin checking for amplificational completeness with respect to. Passed as an argument to
compute_composite_germ_set_score()
.
 Returns
CompositeScore – The worst score over all models of the germ set.
 pygsti.algorithms.germselection.find_germs_grasp(model_list, germs_list, alpha, randomize=True, randomization_strength=0.001, num_copies=None, seed=None, l1_penalty=0.01, op_penalty=0.0, score_func='all', tol=1e06, threshold=1000000.0, check=False, force='singletons', iterations=5, return_all=False, shuffle=False, verbosity=0)¶
Use GRASP to find a highperforming germ set.
 Parameters
model_list (Model or list of Model) – The list of Models to be tested. To ensure that the returned germ set is amplficationally complete, it is a good idea to score potential germ sets against a collection (~510) of similar models. The user may specify a single Model and a number of unitarily close copies to be made (set by the kwarg num_copies, or the user may specify their own list of Models, each of which in turn may or may not be randomized (set by the kwarg randomize).
germs_list (list of Circuit) – List of all germ circuits to consider.
alpha (float) – A number between 0 and 1 that roughly specifies a score theshold relative to the spread of scores that a germ must score better than in order to be included in the RCL. A value of 0 for alpha corresponds to a purely greedy algorithm (only the bestscoring germ set is included in the RCL), while a value of 1 for alpha will include all germs in the RCL. See
pygsti.algorithms.scoring.filter_composite_rcl()
for more details.randomize (Bool, optional) – Whether or not the input Model(s) are first subject to unitary randomization. If
False
, the user should perform the unitary randomization themselves. Note: If the Model(s) are perfect (e.g.std1Q_XYI.target_model()
), then the germ selection output should not be trusted, due to accidental degeneracies in the Model. If the Model(s) include stochastic (nonunitary) error, then germ selection will fail, as we score amplificational completeness in the limit of infinite sequence length (so any stochastic noise will completely depolarize any sequence in that limit).randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. Default is1e3
.num_copies (int, optional) – The number of Model copies to be made of the input Model (prior to unitary randomization). If more than one Model is passed in, num_copies should be
None
. If only one Model is passed in and num_copies isNone
, no extra copies are made.seed (float, optional) – The starting seed used for unitary randomization. If multiple Models are to be randomized,
model_list[i]
is randomized withseed + i
.l1_penalty (float, optional) – How strong the penalty should be for increasing the germ set list by a single germ. Used for choosing between outputs of various GRASP iterations.
op_penalty (float, optional) – How strong the penalty should be for increasing a germ in the germ set list by a single gate.
score_func (string) – Label to indicate how a germ set is scored. See
list_score()
for details.tol (float, optional) – Tolerance used for eigenvector degeneracy testing in twirling operation.
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the germ set is rejected as amplificationally incomplete.
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
force (str or list, optional) – A list of Circuits which must be included in the final germ set. If set to the special string “singletons” then all length1 strings will be included. Seting to None is the same as an empty list.
iterations (int, optional) – The number of GRASP iterations to perform.
return_all (bool, optional) – Flag set to tell the routine if it should return lists of all initial constructions and local optimizations in addition to the optimal solution (useful for diagnostic purposes or if you’re not sure what your finalScoreFn should really be).
shuffle (bool, optional) – Whether the neighborhood should be presented to the optimizer in a random order (important since currently the local optimizer updates the solution to the first better solution it finds in the neighborhood).
verbosity (int, optional) – Integer >= 0 indicating the amount of detail to print.
 Returns
finalGermList (list of Circuit) – Sublist of germs_list specifying the final, optimal set of germs.
pygsti.algorithms.grammatrix
¶Utility functions related to Gram matrix construction.

Compute a maximal set of basis circuits for a Gram matrix. 

Compute the rank and singular values of a maximal Gram matrix. 
 pygsti.algorithms.grammatrix.max_gram_basis(op_labels, dataset, max_length=0)¶
Compute a maximal set of basis circuits for a Gram matrix.
That is, a maximal set of strings {S_i} such that the gate strings { S_i S_j } are all present in dataset. If max_length > 0, then restrict len(S_i) <= max_length.
 Parameters
op_labels (list or tuple) – the operation labels to use in Gram matrix basis strings
dataset (DataSet) – the dataset to use when constructing the Gram matrix
max_length (int, optional) – the maximum string length considered for Gram matrix basis elements. Defaults to 0 (no limit).
 Returns
list of tuples – where each tuple contains operation labels and specifies a single circuit.
 pygsti.algorithms.grammatrix.max_gram_rank_and_eigenvalues(dataset, target_model, max_basis_string_length=10, fixed_lists=None)¶
Compute the rank and singular values of a maximal Gram matrix.
That is, compute the rank and singular values of the Gram matrix computed using the basis: max_gram_basis(dataset.gate_labels(), dataset, max_basis_string_length).
 Parameters
dataset (DataSet) – the dataset to use when constructing the Gram matrix
target_model (Model) – A model used to make sense of circuits and for the construction of a theoretical gram matrix and spectrum.
max_basis_string_length (int, optional) – the maximum string length considered for Gram matrix basis elements. Defaults to 10.
fixed_lists ((prep_fiducials, effect_fiducials), optional) – 2tuple of
Circuit
lists, specifying the preparation and measurement fiducials to use when constructing the Gram matrix, and thereby bypassing the search for such lists.
 Returns
rank (integer)
singularvalues (numpy array)
targetsingularvalues (numpy array)
pygsti.algorithms.grasp
¶Functions to facilitate using GRASP.

Return the list of weights in the neighborhood of a given weight vector. 

Constructs a subset of elements that represents a feasible solution. 

Perfom the localsearch part of a grasp iteration. 

Perform one iteration of GRASP (greedy construction and local search). 

Perform GRASP to come up with an optimal feasible set of elements. 
 pygsti.algorithms.grasp.neighboring_weight_vectors(weights, forced_weights=None, shuffle=False)¶
Return the list of weights in the neighborhood of a given weight vector.
A weight vector is in the neighborhood of a given weight vector if it is only a single swap away from the given weight vector. There is an option to use forced_weights to indicate elements you don’t want to swap out.
 Parameters
weights (numpy.array) – Binary vector to find the neighborhood of.
forced_weights (numpy.array, optional) – Binary vector indicating elements that must be included in all neighboring vectors (these elements are assumed to already be present in weights.
shuffle (bool, optional) – Whether the neighborhood should be presented to the optimizer in a random order (important if the local optimizer updates the solution to the first better solution it finds in the neighborhood instead of exhaustively searching the neighborhood for the best solution).
 Returns
list of numpy.array – List of binary vectors corresponding to all the neighbors of weights.
 pygsti.algorithms.grasp._grasp_construct_feasible_solution(elements, score_fn, rcl_fn, feasible_threshold=None, feasible_fn=None, initial_elements=None)¶
Constructs a subset of elements that represents a feasible solution.
This function performs the “greedyconstruction” part of a grasp iteration (see
run_grasp_iteration()
). The returned solution subset is built up by repeating the following step until a feasible solution (using feasible_threshold OR feasible_fn):Build a candidate list from elements that haven’t been chosen.
Based on the scores of the candidates (using score_fn), construct a “reduced candidate list” (using rcl_fn) that need not (but could) be just the single bestscoring element.
Choose a random element from the reduced candidate list and add it to the solution subset.
 Parameters
elements (list) – A list containing some representation of the elements that can be used by the verious score functions.
score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores.
rcl_fn (callable) – Function that takes a list of sublists of elements (that is, a list of candidate partial solutions) and returns the indices within that list of partial solutions to be included in the restricted candidate list.
feasible_threshold (score) – A value comparable with the return value of the various score functions against which a score may be compared to test if the solution is feasible (the solution is feasible iff
solnScore < feasible_threshold
). Overrides feasible_fn if set to a value other thanNone
.feasible_fn (callable) – Function that takes a sublist of elements defining a potential solution and returns
True
if that solution is feasible (otherwise should returnFalse
). Not used if feasible_threshold is notNone
.initial_elements (numpy.array) – Binary vector indicating whether the corresponding elements in elements should be automatically included at the start of this construction.
 Returns
list – A sublist of elements.
 pygsti.algorithms.grasp._grasp_local_search(initial_solution, score_fn, elements, get_neighbors_fn, feasible_threshold=None, feasible_fn=None)¶
Perfom the localsearch part of a grasp iteration.
Attempts to find a better (lowerscoring) solution based on successive “local” (as determined by get_neighbors_fn) steps from initialSolution.
 Parameters
initial_solution (list) – A list of some (or all) of the items in elements, representing an initial solution. This solution must be “feasbile” as determined by feasible_threshold or feasible_fn.
score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores. Used by the local search to find a locally optimal feasible subset.
elements (list) – A list containing some representation of the elements that can be used by the verious score functions.
get_neighbors_fn (callable) – Function that takes a binary vector indicating which members of elements are included in the current solution and returns a list of binary vectors indicating which potential solutions are in the neighborhood of the current solution for the purposes of local optimization.
feasible_threshold (score) – A value comparable with the return value of the various score functions against which a score may be compared to test if the solution is feasible (the solution is feasible iff
solnScore < feasible_threshold
). Overrides feasible_fn if set to a value other thanNone
.feasible_fn (callable) – Function that takes a sublist of elements defining a potential solution and returns
True
if that solution is feasible (otherwise should returnFalse
). Not used if feasible_threshold is notNone
.
 Returns
list – A sublist of elements, representing the locallyimproved solution.
 pygsti.algorithms.grasp.run_grasp_iteration(elements, greedy_score_fn, rcl_fn, local_score_fn, get_neighbors_fn, feasible_threshold=None, feasible_fn=None, initial_elements=None, seed=None, verbosity=0)¶
Perform one iteration of GRASP (greedy construction and local search).
 Parameters
elements (list) – A list containing some representation of the elements that can be used by the verious score functions.
greedy_score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores. Used by the greedy construction to construct the initial feasible subset.
rcl_fn (callable) – Function that takes a list of sublists of elements (that is, a list of candidate partial solutions) and returns the indices within that list of partial solutions to be included in the restricted candidate list.
local_score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores. Used by the local search to find a locally optimal feasible subset.
get_neighbors_fn (callable) – Function that takes a binary vector indicating which members of elements are included in the current solution and returns a list of binary vectors indicating which potential solutions are in the neighborhood of the current solution for the purposes of local optimization.
feasible_threshold (score) – A value comparable with the return value of the various score functions against which a score may be compared to test if the solution is feasible (the solution is feasible iff
solnScore < feasible_threshold
). Overrides feasible_fn if set to a value other thanNone
.feasible_fn (callable) – Function that takes a sublist of elements defining a potential solution and returns
True
if that solution is feasible (otherwise should returnFalse
). Not used if feasible_threshold is notNone
.initial_elements (numpy.array) – Binary vector indicating whether the corresponding elements in elements should be automatically included by the greedy construction routine at the start of its construction.
seed (int) – Seed for the random number generator.
verbosity (int) – Sets the level of logging messages the printer will display.
 Returns
initialSoln (list) – The sublist of elements given by the greedy construction.
localSoln (list) – The sublist of elements given by the local search.
 pygsti.algorithms.grasp.run_grasp(elements, greedy_score_fn, rcl_fn, local_score_fn, get_neighbors_fn, final_score_fn, iterations, feasible_threshold=None, feasible_fn=None, initial_elements=None, seed=None, verbosity=0)¶
Perform GRASP to come up with an optimal feasible set of elements.
 Parameters
elements (list) – A list containing some representation of the elements that can be used by the verious score functions.
greedy_score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores. Used by the greedy construction to construct the initial feasible subset.
rcl_fn (callable) – Function that takes a list of sublists of elements (that is, a list of candidate partial solutions) and returns the indices within that list of partial solutions to be included in the restricted candidate list.
local_score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores. Used by the local search to find a locally optimal feasible subset.
get_neighbors_fn (callable) – Function that takes a binary vector indicating which members of elements are included in the current solution and returns a list of binary vectors indicating which potential solutions are in the neighborhood of the current solution for the purposes of local optimization.
final_score_fn (callable) – Function that takes a sublist of elements and returns a score to minimize that is comparable with other scores. Used to compare the solutions from various iterations in order to choose an optimum.
iterations (int) – How many iterations of greedy construction followed by local search to perform.
feasible_threshold (score) – A value comparable with the return value of the various score functions against which a score may be compared to test if the solution is feasible (the solution is feasible iff
solnScore < feasible_threshold
). Overrides feasible_fn if set to a value other thanNone
.feasible_fn (callable) – Function that takes a sublist of elements defining a potential solution and returns
True
if that solution is feasible (otherwise should returnFalse
). Not used if feasible_threshold is notNone
.initial_elements (numpy.array) – Binary vector with 1s at indices corresponding to elements in elements that the greedy construction routine will include at the start of its construction.
seed (int) – Seed for the random number generator.
verbosity (int) – Sets the level of logging messages the printer will display.
 Returns
list of Circuits – The best germ set from all locallyoptimal germ sets constructed.
pygsti.algorithms.mirroring
¶circuit mirroring functions.

circ_type : clifford+zxzxz, cz(theta)+zxzxz 
 pygsti.algorithms.mirroring.create_mirror_circuit(circ, pspec, circ_type='clifford+zxzxz')¶
circ_type : clifford+zxzxz, cz(theta)+zxzxz
pygsti.algorithms.randomcircuit
¶Random circuit sampling functions.
TODO: docstring 


TODO: docstring #generate layer of random unitaries and make a series of circuit layers with the compiled versions 

TODO: docstring 

TODO: docstring 

TODO: docstring 

Samples a random circuit layer by eliminating qubits one by one. 

Samples a random circuit layer using the specified list of "compatible twoqubit gates" (co2_q_gates). 

Samples a random circuit layer containing only 1qubit gates. 

Samples a random circuit of the specified length (or ~ twice this length). 

Generates a "direct randomized benchmarking" (DRB) circuit. 

Generates a "Clifford randomized benchmarking" (CRB) circuit. 

Samples a uniformly random nqubit Pauli and converts it to the gateset of pspec. 

Samples a uniformly random layer of 1qubit Cliffords. 

Generates a "mirror randomized benchmarking" (MRB) circuit. 

TODO: docstring 

TODO: docstring 

TODO: docstring 
 pygsti.algorithms.randomcircuit.sample_haar_random_one_qubit_unitary_parameters()¶
TODO: docstring
 pygsti.algorithms.randomcircuit.sample_compiled_haar_random_one_qubit_gates_zxzxz_circuit(pspec, zname='Gzr', xname='Gxpi2', qubit_labels=None)¶
 TODO: docstring #generate layer of random unitaries and make a series of circuit layers with the compiled versions
of these
 pygsti.algorithms.randomcircuit.sample_random_cz_zxzxz_circuit(pspec, length, qubit_labels=None, two_q_gate_density=0.25, two_q_gate_args_lists={'Gczr': [(str(_np.pi / 2),), (str( _np.pi / 2),)]})¶
TODO: docstring Generates a forward circuits with benchmark depth d for nonclifford mirror randomized benchmarking. The circuits alternate Haarrandom 1q unitaries and layers of Gczr gates
 pygsti.algorithms.randomcircuit.find_all_sets_of_compatible_two_q_gates(edgelist, n, gatename='Gcnot', aslabel=False)¶
TODO: docstring <TODO summary>
 Parameters
edgelist (<TODO typ>) – <TODO description>
n (int) – The number of twoqubit gates to have in the set.
gatename (<TODO typ>, optional) – <TODO description>
aslabel (<TODO typ>, optional) – <TODO description>
 Returns
<TODO typ>
 pygsti.algorithms.randomcircuit.sample_circuit_layer_by_edgegrab(pspec, qubit_labels=None, two_q_gate_density=0.25, one_q_gate_names=None, gate_args_lists=None, rand_state=None)¶
TODO: docstring <TODO summary>
 Parameters
pspec (<TODO typ>) – <TODO description>
qubit_labels (<TODO typ>, optional) – <TODO description>
mean_two_q_gates (<TODO typ>, optional) – <TODO description>
modelname (<TODO typ>, optional) – <TODO description>
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
<TODO typ>
 pygsti.algorithms.randomcircuit.sample_circuit_layer_by_q_elimination(pspec, qubit_labels=None, two_q_prob=0.5, rand_state=None)¶
Samples a random circuit layer by eliminating qubits one by one.
This sampler works with any connectivity, but the expected number of 2qubit gates in a layer depends on both the specified 2qubit gate probability and the exact connectivity graph.
This sampler is the following algorithm: List all the qubits, and repeat the following steps until all qubits are deleted from this list. 1) Uniformly at random pick a qubit from the list, and delete it from the list 2) Flip a coin with bias two_q_prob to be “Heads”. 3) If “Heads” then – if there is one or more 2qubit gates from this qubit to other qubits still in the list – pick one of these at random. 4) If we haven’t chosen a 2qubit gate for this qubit (“Tails” or “Heads” but there are no possible 2qubit gates) then pick a uniformly random 1qubit gate to apply to this qubit.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit layer is being sampled for. Unless qubit_labels is not None, a circuit layer is sampled over all the qubits in pspec.
qubit_labels (list, optional) – If not None, a list of the qubits to sample the circuit layer for. This is a subset of pspec.qubit_labels. If None, the circuit layer is sampled to acton all the qubits in pspec.
two_q_prob (float, optional) – If a 2qubit can is still possible on a qubit at that stage of the sampling, this is the probability a 2qubit gate is chosen for that qubit. The expected number of 2qubit gates per layer depend on this quantity and the connectivity graph of the device.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
list of gates – A list of gate Labels that defines a “complete” circuit layer (there is one and only one gate acting on each qubit in pspec or qubit_labels).
 pygsti.algorithms.randomcircuit.sample_circuit_layer_by_co2_q_gates(pspec, qubit_labels, co2_q_gates, co2_q_gates_prob='uniform', two_q_prob=1.0, one_q_gate_names='all', rand_state=None)¶
Samples a random circuit layer using the specified list of “compatible twoqubit gates” (co2_q_gates).
That is, the user inputs a list (co2_q_gates) specifying 2qubit gates that are “compatible” – meaning that they can be implemented simulatenously – and a distribution over the different compatible sets, and a layer is sampled from this via:
1. Pick a set of compatible twoqubit gates from the list co2_q_gates, according to the distribution specified by co2_q_gates_prob. 2. For each 2qubit gate in the chosen set of compatible gates, with probability two_q_prob add this gate to the layer. 3. Uniformly sample 1qubit gates for any qubits that don’t yet have a gate on them, from those 1qubit gates specified by one_q_gate_names.
For example, consider 4 qubits with linear connectivity. a valid co2_q_gates list is co2_q_gates = [[,],[Label(Gcphase,(0,1)),Label(Gcphase,(2,3))]] which consists of an element containing zero 2qubit gates and an element containing two 2qubit gates that can be applied in parallel. In this example there are 5 possible sets of compatible 2qubit gates:
[,] (zero 2qubit gates)
[Label(Gcphase,(0,1)),] (one of the three 2qubit gate)
[Label(Gcphase,(1,2)),] (one of the three 2qubit gate)
[Label(Gcphase,(2,3)),] (one of the three 2qubit gate)
[Label(Gcphase,(0,1)), Label(Gcphase,(2,3)),] (the only compatible pair of 2qubit gates).
The list of compatible twoqubit gates co2_q_gates can be any list containing anywhere from 1 to all 5 of these lists.
In order to allow for convenient sampling of some commonly useful distributions, co2_q_gates can be a list of lists of lists of compatible 2qubit gates (“nested” sampling). In this case, a list of lists of compatible 2qubit gates is picked according to the distribution co2_q_gates_prob, and then one of the sublists of compatible 2qubit gates in the selected list is then chosen uniformly at random. For example, this is useful for sampling a layer containing one uniformly random 2qubit gate with probability p and a layer of 1qubit gates with probability 1p. Here, we can specify co2_q_gates as [[],[[the 1st 2Qgate,],[the 2nd 2Qgate,], …]] and set two_q_prob=1 and `co2_q_gates_prob = [1p,p].
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit layer is being sampled for. Unless qubit_labels is not None, a circuit layer is sampled over all the qubits in pspec.
qubit_labels (list) – If not None, a list of the qubits to sample the circuit layer for. This is a subset of pspec.qubit_labels. If None, the circuit layer is sampled to act on all the qubits in pspec.
co2_q_gates (list) –
This is either:
A list of lists of 2qubit gate Labels that can be applied in parallel.
A list of lists of lists of 2qubit gate Labels that can be applied in parallel.
In case (1) each list in co2_q_gates should contain 2qubit gates, in the form of Labels, that can be applied in parallel and act only on the qubits in pspec if qubit_labels is None, or act only on the qubits in qubit_labels if qubit_labels is not None. The sampler then picks one of these compatible sets of gates (with probability specified by co2_q_gates_prob, and converts this into a circuit layer by applying the 2qubit gates it contains with the userspecified probability two_q_prob, and augmenting these 2qubit gates with 1qubit gates on all other qubits.
In case (2) a sublist of lists is sampled from co2_q_gates according to co2_q_gates_prob and then we proceed as in case (1) but as though co2_q_gates_prob is the uniform distribution.
co2_q_gates_prob (str or list of floats) – If a list, they are unnormalized probabilities to sample each of the elements of co2_q_gates. So it is a list of nonnegative floats of the same length as co2_q_gates. If ‘uniform’, then the uniform distribution is used.
two_q_prob (float, optional) – The probability for each twoqubit gate to be applied to a pair of qubits, after a set of compatible 2qubit gates has been chosen. The expected number of 2qubit gates in a layer is two_q_prob times the expected number of 2qubit gates in a set of compatible 2qubit gates sampled according to co2_q_gates_prob.
one_q_gate_names ('all' or list of strs, optional) – If not ‘all’, a list of the names of the 1qubit gates to be sampled from when applying a 1qubit gate to a qubit. If this is ‘all’, the full set of 1qubit gate names is extracted from the QubitProcessorSpec.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
list of gates – A list of gate Labels that defines a “complete” circuit layer (there is one and only one gate acting on each qubit).
 pygsti.algorithms.randomcircuit.sample_circuit_layer_of_one_q_gates(pspec, qubit_labels=None, one_q_gate_names='all', pdist='uniform', modelname='clifford', rand_state=None)¶
Samples a random circuit layer containing only 1qubit gates.
The allowed 1qubit gates are specified by one_q_gate_names, and the 1qubit gates are sampled independently and uniformly.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit layer is being sampled for. Unless qubit_labels is not None, a circuit layer is sampled over all the qubits in pspec.
qubit_labels (list, optional) – If not None, a list of the qubits to sample the circuit layer for. This is a subset of pspec.qubit_labels. If None, the circuit layer is sampled to acton all the qubits in pspec.
one_q_gate_names ('all' or list of strs, optional) – If not ‘all’, a list of the names of the 1qubit gates to be sampled from when applying a 1qubit gate to a qubit. If this is ‘all’, the full set of 1qubit gate names is extracted from the QubitProcessorSpec.
pdist ('uniform' or list of floats, optional) – If a list, they are unnormalized probabilities to sample each of the 1qubit gates in the list one_q_gate_names. If this is not ‘uniform’, then oneQgatename` must not be ‘all’ (it must be a list so that it is unambigious which probability correpsonds to which gate). So if not ‘uniform’, pdist is a list of nonnegative floats of the same length as one_q_gate_names. If ‘uniform’, then the uniform distribution over the gates is used.
modelname (str, optional) – Only used if one_q_gate_names is ‘all’. Specifies which of the pspec.models to use to extract the model. The clifford default is suitable for Clifford or direct RB, but will not use any nonClifford gates in the model.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
list of gates – A list of gate Labels that defines a “complete” circuit layer (there is one and only one gate acting on each qubit).
 pygsti.algorithms.randomcircuit.create_random_circuit(pspec, length, qubit_labels=None, sampler='Qelimination', samplerargs=[], addlocal=False, lsargs=[], rand_state=None)¶
Samples a random circuit of the specified length (or ~ twice this length).
The created circuit’s layers are independently sampled according to the specified sampling distribution.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit is being sampled for. This is always handed to the sampler, as the first argument of the sampler function. Unless qubit_labels is not None, the circuit is sampled over all the qubits in pspec.
length (int) – If addlocal is False, this is the length of the sampled circuit. If addlocal is True the length of the circuits is 2*length+1 with oddindexed layers sampled according to the sampler specified by `sampler, and the the zeroth layer + the evenindexed layers consisting of random 1qubit gates (with the sampling specified by lsargs)
qubit_labels (list, optional) – If not None, a list of the qubits to sample the circuit for. This is a subset of pspec.qubit_labels. If None, the circuit is sampled to act on all the qubits in pspec.
sampler (str or function, optional) – If a string, this should be one of: {‘edgegrab’’, ‘Qelimination’, ‘co2Qgates’, ‘local’}. Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates. If this is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful inbuilt sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.
samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec and samplerargs lists the remaining arguments handed to the sampler. For some inbuilt samplers this is not optional.
addlocal (bool, optional) – If False, the circuit sampled is of length length and each layer is independently sampled according to the sampler specified by sampler. If True, the circuit sampled is of length 2*`length`+1 where: the zeroth + all even layers are consisting of independently random 1qubit gates (with the sampling specified by lsargs); the oddindexed layers are independently sampled according to sampler. So length`+1 layers consist only of 1qubit gates, and `length layers are sampled according to sampler.
lsargs (list, optional) – A list of arguments that are handed to the 1qubit gate layers sampler rb.sampler.circuit_layer_of_oneQgates for the alternating 1qubitonly layers that are included in the circuit if addlocal is True. This argument is not used if addlocal is false. Note that pspec is used as the first, and only required, argument of rb.sampler.circuit_layer_of_oneQgates. If lsargs = [] then all available 1qubit gates are uniformly sampled from. To uniformly sample from only a subset of the available 1qubit gates (e.g., the Paulis to Pauliframerandomize) then lsargs should be a 1element list consisting of a list of the relevant gate names (e.g., lsargs = [‘Gi, ‘Gxpi, ‘Gypi’, ‘Gzpi’]).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A random circuit of length length (if not addlocal) or length 2*`length`+1 (if addlocal) with layers independently sampled using the specified sampling distribution.
 pygsti.algorithms.randomcircuit.create_direct_rb_circuit(pspec, clifford_compilations, length, qubit_labels=None, sampler='Qelimination', samplerargs=[], addlocal=False, lsargs=[], randomizeout=True, cliffordtwirl=True, conditionaltwirl=True, citerations=20, compilerargs=[], partitioned=False, seed=None)¶
Generates a “direct randomized benchmarking” (DRB) circuit.
DRB is the protocol introduced in arXiv:1807.07975 (2018). The length of the “core” circuit is given by length and may be any integer >= 0. An nqubit DRB circuit consists of (1) a circuit the prepares a uniformly random stabilizer state; (2) a lengthl circuit (specified by length) consisting of circuit layers sampled according to some userspecified distribution (specified by sampler), (3) a circuit that maps the output of the preceeding circuit to a computational basis state. See arXiv:1807.07975 (2018) for further details.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit is being sampled for, which defines the “native” gateset and the connectivity of the device. The returned DRB circuit will be over the gates in pspec, and will respect the connectivity encoded by pspec. Note that pspec is always handed to the sampler, as the first argument of the sampler function (this is only of importance when not using an inbuilt sampler for the “core” of the DRB circuit). Unless qubit_labels is not None, the circuit is sampled over all the qubits in pspec.
clifford_compilation (CompilationRules) – Rules for compiling the “native” gates of pspec into Clifford gates.
length (int) – The “direct RB length” of the circuit, which is closely related to the circuit depth. It must be an integer >= 0. Unless addlocal is True, it is the depth of the “core” random circuit, sampled according to sampler, specified in step (2) above. If addlocal is True, each layer in the “core” circuit sampled according to “sampler` is followed by a layer of 1qubit gates, with sampling specified by lsargs (and the first layer is proceeded by a layer of 1qubit gates), and so the circuit of step (2) is length 2*`length` + 1.
qubit_labels (list, optional) – If not None, a list of the qubits to sample the circuit for. This is a subset of pspec.qubit_labels. If None, the circuit is sampled to act on all the qubits in pspec.
sampler (str or function, optional) – If a string, this should be one of: {‘pairingQs’, ‘Qelimination’, ‘co2Qgates’, ‘local’}. Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid form of sampling for nqubit DRB, but is not explicitly forbidden in this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful inbuilt sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.
samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec, the second argument is qubit_labels, and samplerargs lists the remaining arguments handed to the sampler. This is not optional for some choices of sampler.
addlocal (bool, optional) – Whether to follow each layer in the “core” circuit, sampled according to sampler with a layer of 1qubit gates.
lsargs (list, optional) – Only used if addlocal is True. A list of optional arguments handed to the 1Q gate layer sampler circuit_layer_by_oneQgate(). Specifies how to sample 1Qgate layers.
randomizeout (bool, optional) – If False, the ideal output of the circuit (the “success” or “survival” outcome) is the allzeros bit string. If True, the ideal output of the circuit is randomized to a uniformly random bitstring. This setting is useful for, e.g., detecting leakage/loss/measurementbias etc.
cliffordtwirl (bool, optional) – Wether to begin the circuit with a sequence that generates a random stabilizer state. For standard DRB this should be set to True. There are a variety of reasons why it is better to have this set to True.
conditionaltwirl (bool, optional) – DRB only requires that the initial/final sequences of step (1) and (3) create/measure a uniformly random / particular stabilizer state, rather than implement a particular unitary. step (1) and (3) can be achieved by implementing a uniformly random Clifford gate and the unique inversion Clifford, respectively. This is implemented if conditionaltwirl is False. However, steps (1) and (3) can be implemented much more efficiently than this: the sequences of (1) and (3) only need to map a particular input state to a particular output state, if conditionaltwirl is True this more efficient option is chosen – this is option corresponds to “standard” DRB. (the term “conditional” refers to the fact that in this case we essentially implementing a particular Clifford conditional on a known input).
citerations (int, optional) – Some of the stabilizer state / Clifford compilation algorithms in pyGSTi (including the default algorithms) are randomized, and the lowestcost circuit is chosen from all the circuit generated in the iterations of the algorithm. This is the number of iterations used. The time required to generate a DRB circuit is linear in citerations. Lowerdepth / lower 2qubit gate count compilations of steps (1) and (3) are important in order to successfully implement DRB on as many qubits as possible.
compilerargs (list, optional) – A list of arguments that are handed to the compile_stabilier_state/measurement()functions (or the compile_clifford() function if conditionaltwirl `is False). This includes all the optional arguments of these functions *after* the `iterations option (set by citerations). For most purposes the default options will be suitable (or at least nearoptimal from the compilation methods inbuilt into pyGSTi). See the docstrings of these functions for more information.
partitioned (bool, optional) – If False, a single circuit is returned consisting of the full circuit. If True, three circuits are returned in a list consisting of: (1) the stabilizerprep circuit, (2) the core random circuit, (3) the premeasurement circuit. In that case the full circuit is obtained by appended (2) to (1) and then (3) to (1).
seed (int, optional) – A seed to initialize the random number generator used for creating random clifford circuits.
 Returns
Circuit or list of Circuits – If partioned is False, a random DRB circuit sampled as specified. If partioned is True, a list of three circuits consisting of (1) the stabilizerprep circuit, (2) the core random circuit, (3) the premeasurement circuit. In that case the full circuit is obtained by appended (2) to (1) and then (3) to (1) [except in the case of cliffordtwirl=False, when it is a list of two circuits].
Tuple – A lengthn tuple of integers in [0,1], corresponding to the errorfree outcome of the circuit. Always all zeros if randomizeout is False. The ith element of the tuple corresponds to the errorfree outcome for the qubit labelled by: the ith element of qubit_labels, if qubit_labels is not None; the ith element of pspec.qubit_labels, otherwise. In both cases, the ith element of the tuple corresponds to the errorfree outcome for the qubit on the ith wire of the output circuit.
 pygsti.algorithms.randomcircuit.create_clifford_rb_circuit(pspec, clifford_compilations, length, qubit_labels=None, randomizeout=False, citerations=20, compilerargs=[], interleaved_circuit=None, seed=None)¶
Generates a “Clifford randomized benchmarking” (CRB) circuit.
CRB is the currentstandard RB protocol defined in “Scalable and robust randomized benchmarking of quantum processes”, Magesan et al. PRL 106 180504 (2011). This consists of a circuit of length`+1 uniformly random nqubit Clifford gates followed by the unique inversion Clifford, with all the Cliffords compiled into the “native” gates of a device as specified by `pspec. The circuit output by this function will respect the connectivity of the device, as encoded into pspec (see the QubitProcessorSpec object docstring for how to construct the relevant pspec).
Note the convention that the the output Circuit consists of length+2 Clifford gates, rather than the more usual convention of defining the “CRB length” to be the number of Clifford gates  1. This is for consistency with the other RB functions in pyGSTi: in all RBcircuitgenerating functions in pyGSTi length zero corresponds to the minimumlength circuit allowed by the protocol. Note that changing the “RB depths” by a constant additive factor is irrelevant for fitting purposes (except that it changes the obtained “SPAM” fit parameter).
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit is being sampled for, which defines the “native” gateset and the connectivity of the device. The returned CRB circuit will be over the gates in pspec, and will respect the connectivity encoded by pspec.
clifford_compilations (dict) – A dictionary with the potential keys ‘absolute’ and ‘paulieq’ and corresponding
CompilationRules
values. These compilation rules specify how to compile the “native” gates of pspec into Clifford gates.length (int) – The “CRB length” of the circuit – an integer >= 0 – which is the number of Cliffords in the circuit  2 before each Clifford is compiled into the native gateset.
qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuit is to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant. If desired, a circuit that explicitly idles on the other qubits can be obtained by using methods of the Circuit object.
randomizeout (bool, optional) – If False, the ideal output of the circuit (the “success” or “survival” outcome) is the allzeros bit string. This is probably considered to be the “standard” in CRB. If True, the ideal output of the circuit is randomized to a uniformly random bitstring. This setting is useful for, e.g., detecting leakage/loss/measurementbias etc.
citerations (int, optional) – Some of the Clifford compilation algorithms in pyGSTi (including the default algorithm) are randomized, and the lowestcost circuit is chosen from all the circuit generated in the iterations of the algorithm. This is the number of iterations used. The time required to generate a CRB circuit is linear in citerations * (`length`+2). Lowerdepth / lower 2qubit gate count compilations of the Cliffords are important in order to successfully implement CRB on more qubits.
compilerargs (list, optional) –
A list of arguments that are handed to compile_clifford() function, which includes all the optional arguments of compile_clifford() after the iterations option (set by citerations). In order, this list should be values for:
 algorithmstr. A string that specifies the compilation algorithm. The default in
compile_clifford() will always be whatever we consider to be the ‘best’ allround algorith,
aargs : list. A list of optional arguments for the particular compilation algorithm.
 costfunction’str’ or function. The costfunction from which the “best” compilation
for a Clifford is chosen from all citerations compilations. The default costs a circuit as 10x the num. of 2qubit gates in the circuit + 1x the depth of the circuit.
prefixpaulis : bool. Whether to prefix or append the Paulis on each Clifford.
 paulirandomizebool. Whether to follow each layer in the Clifford circuit with a
random Pauli on each qubit (compiled into native gates). I.e., if this is True the native gates are Paulirandomized. When True, this prevents any coherent errors adding (on average) inside the layers of each compiled Clifford, at the cost of increased circuit depth. Defaults to False.
For more information on these options, see the compile_clifford() docstring.
seed (int, optional) – A seed to initialize the random number generator used for creating random clifford circuits.
 Returns
Circuit – A random CRB circuit over the “native” gateset specified.
Tuple – A lengthn tuple of integers in [0,1], corresponding to the errorfree outcome of the circuit. Always all zeros if randomizeout is False. The ith element of the tuple corresponds to the errorfree outcome for the qubit labelled by: the ith element of qubit_labels, if qubit_labels is not None; the ith element of pspec.qubit_labels, otherwise. In both cases, the ith element of the tuple corresponds to the errorfree outcome for the qubit on the ith wire of the output circuit.
 pygsti.algorithms.randomcircuit.sample_pauli_layer_as_compiled_circuit(pspec, absolute_compilation, qubit_labels=None, keepidle=False, rand_state=None)¶
Samples a uniformly random nqubit Pauli and converts it to the gateset of pspec.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
qubit_labels (list, optional) – If not None, a list of a subset of the qubits from pspec that the pauli circuit should act on.
keepidle (bool, optional) – Whether to always have the circuit atleast depth 1.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit corresponding to a uniformly random nqubit Pauli, converted to the native gateset of pspec.
 pygsti.algorithms.randomcircuit.sample_one_q_clifford_layer_as_compiled_circuit(pspec, absolute_compilation, qubit_labels=None, rand_state=None)¶
Samples a uniformly random layer of 1qubit Cliffords.
Create a uniformly random layer of 1qubit Cliffords on all the qubits, and then converts it to the native gateset of pspec. That is, an independent and uniformly random 1qubit Clifford is sampled for each qubit.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
qubit_labels (list, optional) – If not None, a list of a subset of the qubits from pspec that the circuit should act on.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit corresponding to an independent, uniformly random 1qubit Clifford gate on each qubit.
 pygsti.algorithms.randomcircuit.create_mirror_rb_circuit(pspec, absolute_compilation, length, qubit_labels=None, sampler='Qelimination', samplerargs=[], localclifford=True, paulirandomize=True, seed=None)¶
Generates a “mirror randomized benchmarking” (MRB) circuit.
This is specific to the case of Clifford gates and can be performed, optionally, with Paulirandomization and Cliffordtwirling. This RB method is currently in development; this docstring will be updated in the future with further information on this technique.
To implement mirror RB it is necessary for U^(1) to in the gateset for every U in the gateset.
 Parameters
pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit is being sampled for. The pspec is always handed to the sampler, as the first argument of the sampler function.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
length (int) –
The “mirror RB length” of the circuit, which is closely related to the circuit depth. It must be an even integer, and can be zero.
If localclifford and paulirandomize are False, this is the depth of the sampled circuit. The first length/2 layers are all sampled independently according to the sampler specified by sampler. The remaining half of the circuit is the “inversion” circuit that is determined by the first half.
If paulirandomize is True and localclifford is False, the depth of the circuits is 2*length+1 with oddindexed layers sampled according to the sampler specified by `sampler, and the the zeroth layer + the evenindexed layers consisting of random 1qubit Pauli gates.
If paulirandomize and localclifford are True, the depth of the circuits is 2*length+1 + X where X is a random variable (between 0 and normally <= ~1216) that accounts for the depth from the layer of random 1qubit Cliffords at the start and end of the circuit.
If paulirandomize is False and localclifford is True, the depth of the circuits is length + X where X is a random variable (between 0 and normally <= ~1216) that accounts for the depth from the layer of random 1qubit Cliffords at the start and end of the circuit.
qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuit is to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant.
sampler (str or function, optional) – If a string, this should be one of: {‘pairingQs’, ‘Qelimination’, ‘co2Qgates’, ‘local’}. Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid option for nqubit MRB – it results in sim. 1qubit MRB – but it is not explicitly forbidden by this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful inbuilt sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.
samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec and samplerargs lists the remaining arguments handed to the sampler.
localclifford (bool, optional) – Whether to start the circuit with uniformly random 1qubit Cliffords and all of the qubits (compiled into the native gates of the device).
paulirandomize (bool, optional) – Whether to have uniformly random Pauli operators on all of the qubits before and after all of the layers in the “out” and “back” random circuits. At length 0 there is a single layer of random Pauli operators (in between two layers of 1qubit Clifford gates if localclifford is True); at length l there are 2l+1 Pauli layers as there are
seed (int, optional) – A seed to initialize the random number generator used for creating random clifford circuits.
 Returns
Circuit –
A random MRB circuit, sampled as specified, of depth:
length, if not paulirandomize and not local clifford.
2*`length`+1 if paulirandomize and not local clifford.
length + X, if not paulirandomize and local clifford, where X is a random variable that accounts for the depth from the layers of random 1qubit Cliffords (X = 2 if the 1 qubit Clifford gates are “native” gates in the QubitProcessorSpec).
2*`length`+1 + X, if paulirandomize and local clifford, where X is a random variable that accounts for the depth from the layers of random 1qubit Cliffords (X = 2 if the 1 qubit Clifford gates are “native” gates in the QubitProcessorSpec).
Tuple – A lengthn tuple of integers in [0,1], corresponding to the errorfree outcome of the circuit. Always all zeros if randomizeout is False. The ith element of the tuple corresponds to the errorfree outcome for the qubit labelled by: the ith element of qubit_labels, if qubit_labels is not None; the ith element of pspec.qubit_labels, otherwise. In both cases, the ith element of the tuple corresponds to the errorfree outcome for the qubit on the ith wire of the output circuit.
 pygsti.algorithms.randomcircuit.create_random_germ(pspec, depths, interacting_qs_density, qubit_labels, rand_state=None)¶
TODO: docstring <TODO summary>
 Parameters
pspec (<TODO typ>) – <TODO description>
depths (<TODO typ>) – <TODO description>
interacting_qs_density (<TODO typ>) – <TODO description>
qubit_labels (<TODO typ>) – <TODO description>
 Returns
<TODO typ>
 pygsti.algorithms.randomcircuit.create_random_germpower_circuits(pspec, depths, interacting_qs_density, qubit_labels, fixed_versus_depth=False, rand_state=None)¶
TODO: docstring <TODO summary>
 Parameters
pspec (<TODO typ>) – <TODO description>
depths (<TODO typ>) – <TODO description>
interacting_qs_density (<TODO typ>) – <TODO description>
qubit_labels (<TODO typ>) – <TODO description>
fixed_versus_depth (<TODO typ>, optional) – <TODO description>
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 pygsti.algorithms.randomcircuit.create_random_germpower_mirror_circuits(pspec, absolute_compilation, depths, qubit_labels=None, localclifford=True, paulirandomize=True, interacting_qs_density=1 / 8, fixed_versus_depth=False, seed=None)¶
TODO: docstring length : consistent with RB length.
 Parameters
pspec (<TODO typ>) – <TODO description>
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
depths (<TODO typ>) – <TODO description>
qubit_labels (<TODO typ>, optional) – <TODO description>
localclifford (<TODO typ>, optional) – <TODO description>
paulirandomize (<TODO typ>, optional) – <TODO description>
interacting_qs_density (<TODO typ>, optional) – <TODO description>
fixed_versus_depth (<TODO typ>, optional) – <TODO description>
 Returns
<TODO typ>
pygsti.algorithms.rbfit
¶Functions for analyzing RB data
An object to contain the results from fitting RB data. 

Implements a "standard" leastsquares fit of RB data. 

Fits RB average success probabilities to the exponential decay a + Bp^m using leastsquares fitting. 
 pygsti.algorithms.rbfit.std_least_squares_fit(lengths, asps, n, seed=None, asymptote=None, ftype='full', rtype='EI')¶
Implements a “standard” leastsquares fit of RB data.
Fits the average success probabilities to the exponential decay A + Bp^m, using leastsquares fitting.
 Parameters
lengths (list) – The RB lengths to fit to (the ‘m’ values in A + Bp^m).
asps (list) – The average survival probabilities to fit (the observed P_m values to fit to P_m = A + Bp^m).
n (int) – The number of qubits the data was generated from.
seed (list, optional) – Seeds for the fit of B and p (A, if a variable, is seeded to the asymptote defined by asympote).
asymptote (float, optional) – If not None, the A value for the fitting to A + Bp^m with A fixed. Defaults to 1/2^n. Note that this value is used even when fitting A; in that case B and p are estimated with A fixed to this value, and then this A and the estimated B and p are seed for the full fit.
ftype ({'full','FA','full+FA'}, optional) – The fit type to implement. ‘full’ corresponds to fitting all of A, B and p. ‘FA’ corresponds to fixing ‘A’ to the value specified by asymptote. ‘full+FA’ returns the results of both fits.
rtype ({'EI','AGI'}, optional) – The RB error rate rescaling convention. ‘EI’ results in RB error rates that are associated with the entanglement infidelity, which is the error probability with stochastic errors (and is equal to the diamond distance). ‘AGI’ results in RB error rates that are associated with average gate infidelity.
 Returns
Dict or Dicts – If ftype = ‘full’ or ftype = ‘FA’ then a dict containing the results of the relevant fit. If ftype = ‘full+FA’ then two dicts are returned. The first dict corresponds to the full fit and the second to the fixedasymptote fit.
 pygsti.algorithms.rbfit.custom_least_squares_fit(lengths, asps, n, a=None, b=None, seed=None, rtype='EI')¶
Fits RB average success probabilities to the exponential decay a + Bp^m using leastsquares fitting.
 Parameters
lengths (list) – The RB lengths to fit to (the ‘m’ values in a + Bp^m).
asps (list) – The average survival probabilities to fit (the observed P_m values to fit to P_m = a + Bp^m).
n (int) – The number of qubits the data was generated from.
a (float, optional) – If not None, a value to fix a to.
b (float, optional) – If not None, a value to fix b to.
seed (list, optional) – Seeds for variables in the fit, in the order [a,b,p] (with a and/or b dropped if it is set to a fixed value).
rtype ({'EI','AGI'}, optional) – The RB error rate rescaling convention. ‘EI’ results in RB error rates that are associated with the entanglement infidelity, which is the error probability with stochastic errors (and is equal to the diamond distance). ‘AGI’ results in RB error rates that are associated with average gate infidelity.
 Returns
Dict – The fit results. If item with the key ‘success’ is False, the fit has failed.
 class pygsti.algorithms.rbfit.FitResults(fittype, seed, rtype, success, estimates, variable, stds=None, bootstraps=None, bootstraps_failrate=None)¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
An object to contain the results from fitting RB data.
Currently just a container for the results, and does not include any methods.
 Parameters
fittype (str) – A string to identity the type of fit.
seed (list) – The seed used in the fitting.
rtype ({'IE','AGI'}) – The type of RB error rate that the ‘r’ in these fit results corresponds to.
success (bool) – Whether the fit was successful.
estimates (dict) – A dictionary containing the estimates of all parameters
variable (dict) – A dictionary that specifies which of the parameters in “estimates” where variables to estimate (set to True for estimated parameters, False for fixed constants). This is useful when fitting to A + B*p^m and fixing one or more of these parameters: because then the “estimates” dict can still be queried for all three parameters.
stds (dict, optional) – Estimated standard deviations for the parameters.
bootstraps (dict, optional) – Bootstrapped values for the estimated parameters, from which the standard deviations were calculated.
bootstraps_failrate (float, optional) – The proporition of the estimates of the parameters from bootstrapped dataset failed.
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
pygsti.algorithms.robust_phase_estimation
¶Robust Phase Estimation platform agnostic portion
Runs the nonadaptive RPE algorithm. 
 class pygsti.algorithms.robust_phase_estimation.RobustPhaseEstimation(q)¶
Bases:
object
Runs the nonadaptive RPE algorithm.
Runs the nonadaptive RPE algorithm using a dictionary of measurement results, Q.raw_angles, containing the angles calculated from the probabilities:
P^{γ’γ}_{Nₖs} = <γ' y U^Nₖ γ x>² = <γ' x U^Nₖ γ y>² = (1 ± sin(θ))/2 P^{γ'γ}_{Nₖc} = <γ' x U^Nₖ γ x>² = <γ' y U^Nₖ  γ y>² = (1 ± cos(θ))/2
Expect measured[Nₖ] = θ.
Overview:
At each generation, use the previous estimated angle to select the 2π/L window (of which the measurements cannot distinguish).
Returns an result object. theta is the estimated angle, angle_estimates are the estimates from each generation.
 Parameters
q (<TODO typ>) – <TODO description>
 theta_n(self, n)¶
Returns the equivalence class of the measurement Θ.
By definition, Θ is equivalent when any integer multiple of 2π/N is added to it.
 Parameters
n (int) – The RPE ‘N’ parameter, used to determine the equivalence class.
 Returns
float
pygsti.algorithms.scoring
¶Common functions used in scoring germ and fiducial sets.
Class for storing and comparing scores calculated from eigenvalues. 

Score an array of eigenvalues. Smaller scores are better. 

Create a restricted candidate list (RCL) based on CompositeScore objects. 
 pygsti.algorithms.scoring.list_score(input_array, score_func='all')¶
Score an array of eigenvalues. Smaller scores are better.
 Parameters
input_array (numpy array) – The eigenvalues to be scored.
score_func ({'all', 'worst'}, optional) –
Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/input_array)
. If ‘worst’, score is1/min(input_array)
.Note: we use this function in various optimization routines, and sometimes choosing one or the other objective function can help avoid suboptimal local minima.
 Returns
float – Score for the eigenvalues.
 class pygsti.algorithms.scoring.CompositeScore(major, minor, n)¶
Class for storing and comparing scores calculated from eigenvalues.
The comparison functions operate according to the logic that a lower score is better. The score value is broken into two parts: ‘major’ and ‘minor’. A CompositeScore with a smaller ‘major’ part is always smaller than one with a larger ‘major’ part. The ‘minor’ parts are only compared when the major parts are equal. Typically, the negative of the number of nonzero eigenvalues is used to as the major part so that a score that has more nonzero eigenvalues (higher N) will always compare as less than a score that has fewer nonzero eigenvalues (lower N), with ties for N being resolved by comparing the minor score in the straightforward manner (since the nonAC score is assumed to be better for lower values). For bookeeping, the CompositeScore object also separately holds the number of nonzero eigenvalues, as this may not always be recovered from the major part of the score.
 Parameters
major (float) – Major (more significant) component of score.
minor (float) – Minor (less significant) component of score.
n (int) – Number of nonzero eigenvalues.
 __lt__(self, other)¶
Return self<value.
 __eq__(self, other)¶
Return self==value.
 __repr__(self)¶
Return repr(self).
 pygsti.algorithms.scoring.filter_composite_rcl(candidate_scores, alpha)¶
Create a restricted candidate list (RCL) based on CompositeScore objects.
 Parameters
candidate_scores (list of CompositScore) – List of scores to be sorted in RCL and not RCL.
alpha (float) –
A number between 0 and 1 that roughly specifies a score threshold relative to the spread of scores that a germ must score better than in order to be included in the RCL. A value of 0 for alpha corresponds to a purely greedy algorithm (only the bestscoring element is included in the RCL), while a value of 1 for alpha will include all elements in the RCL.
Intermediate values of alpha attempt to mimic the behavior of alpha for simple float scores. For those scores, the score that all elements must beat is
(1  alpha)*best + alpha*worst
. For CompositeScore objects, thresholding is done on the major part of the score unless all the candidates have the same major score, in which case thresholding is performed using only the minor score.
 Returns
numpy.array – The indices of the scores sufficiently good to be in the RCL.
A dummy profiler that doesn't do anything. 

A basis that is included within and integrated into pyGSTi. 

Class responsible for logging things to stdout or a file. 

A basis that is the direct sum of one or more "component" bases. 

A unmutable list (a tuple) of 

Describes available resources and how they should be allocated. 

A LevenbergMarquardt optimizer customized for GSTlike problems. 

An optimizer. Optimizes an objective function. 

A real operation matrix parameterized only by its eigenvalues. 

TODO: docstring 

Element of 

Compiles an nqubit Clifford gate into a circuit over a given processor specification. 

Generates a circuit to create the stabilizer state from the standard input state 0,0,0,...>. 

Generates a circuit to map the stabilizer state to the standard state 0,0,0,...>. 

A CNOT circuit compiler. 

Contract a Model to a specified space. 









Contract the surface preparation and measurement operations of 

Performs Linearinversion Gate Set Tomography on the dataset. 













Returns the rank and singular values of the Gram matrix for a dataset. 

Performs core Gate Set Tomography function of model optimization. 

Performs core Gate Set Tomography function of model optimization. 

Performs Iterative Gate Set Tomography on the dataset. 

Runs the core modeloptimization step within a GST routine by optimizing 

Runs the core modeloptimization step for models using the 

Find the closest (in fidelity) unitary superoperator to operation_mx. 

Remove duplicates from the a list and return the result. 

Number of combinations of r items out of a set of n. Equals n!/(r!(nr)!) 

Random selection from itertools.combinations(indices_tuple, r) 

Finds a (global) set of fiducial pairs that are amplificationally complete. 

Finds a pergerm set of fiducial pairs that are amplificationally complete. 

Finds a pergerm set of fiducial pairs that are amplificationally complete. 

Tests a set of global or pergerm fiducial pairs. 



Returns the square of the frobenius distance between gate or density matrices. 

Generate prep and measurement fiducials for a given target model. 

Implements logical xor function for arbitrary number of inputs. 

Make a list of matrices for the model preparation operations. 

Make a list of matrices for the model measurement operations. 

Compute a composite score for a fiducial list. 

Tests a prep or measure fiducial list for informational completeness. 

Create an array of all lengthn and Hamming weight k binary vectors. 

Find a locally optimal subset of the fiducials in fid_list. 

Use GRASP to find a highperforming set of fiducials. 

Optimize the gauge degrees of freedom of a model to that of a target. 

Optimize the gauge of a model using a custom objective function. 

Creates the objective function and jacobian (if available) 

Helper function  same as that in core.py. 

Helper function  same as that in core.py. 

Helper function  CPTP penalty: (sum of tracenorms of gates), 

Helper function  CPTP penalty: (sum of tracenorms of gates), 

Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) 

Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) 

Generate a germ set for doing GST with a given target model. 

Calculate the score of a germ set with respect to a model. 

Get the number of gates and gauge parameters of the models in a list. 

Sets up a list of randomize models (helper function). 

Compute the score for a germ set when it is not AC against a model. 

Calculate the positive squares of the germ Jacobians. 

Calculate the positive squares of the germ Jacobian. 

Returns a germ set "score" in which smaller is better. 

Applies random unitary perturbations to a model or list of models. 

Check to see if the germs_list is amplificationally complete (AC). 

Returns a copy of model with state preparations and effects removed. 

Return the number of nongauge, nonSPAM parameters in model. 

Return super operator for doing a perfect twirl with respect to wrt. 

Calculate the squared singular values of the Jacobian of the germ set. 

Compute the "Twirled Derivative" of a circuit. 

Compute the "Twirled Derivative" of a set of circuits. 

Test whether a set of germs is able to amplify all nongauge parameters. 

Test whether a set of germs is able to amplify all nongauge parameters. 

Greedy germ selection algorithm starting with 0 germs. 

Greedy algorithm starting with 0 germs. 

Find a locally optimal subset of the germs in germs_list. 

Score a germ set against a collection of models. 

Use GRASP to find a highperforming germ set. 

Returns the rank and singular values of the Gram matrix for a dataset. 

Compute a maximal set of basis circuits for a Gram matrix. 

Compute the rank and singular values of a maximal Gram matrix. 

circ_type : clifford+zxzxz, cz(theta)+zxzxz 
 pygsti.algorithms.compile_clifford(s, p, pspec=None, absolute_compilation=None, paulieq_compilation=None, qubit_labels=None, iterations=20, algorithm='ROGGE', aargs=[], costfunction='2QGC:10:depth:1', prefixpaulis=False, paulirandomize=False, rand_state=None)¶
Compiles an nqubit Clifford gate into a circuit over a given processor specification.
Compiles an nqubit Clifford gate, described by the symplectic matrix s and vector p, into a circuit over the gates given by a processor specification or a standard processor. Clifford gates/circuits can be converted to, or sampled in, the symplectic representation using the functions in :module:`pygsti.tools.symplectic`.
The circuit created by this function will be over the gates in the given processor spec, respecting its connectivity, when a QubitProcessorSpec object is provided. Otherwise, it is over a canonical processor containing alltoall CNOTs, Hadamard, Phase, 3 products of Hadamard and Phase, and the Pauli gates.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the Clifford is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input Clifford needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – Some of the allowed algorithms are randomized. This is the number of iterations used in algorithm if it is a randomized algorithm specified. If any randomized algorithms are specified, the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
algorithm (str, optional) –
Specifies the algorithm used for the core part of the compilation: finding a circuit that is a Clifford with s the symplectic matrix in its symplectic representation (a circuit that implements that desired Clifford up to Pauli operators). The allowed values of this are:
 ’BGGE’: A basic, deterministic global Gaussian elimination algorithm. Circuits obtained from this algorithm
contain, in expectation, O(n^2) 2qubit gates. Although the returned circuit will respect device connectivity, this algorithm does not take connectivity into account in an intelligient way. More details on this algorithm are given in compile_symplectic_with_ordered_global_gaussian_elimination(); it is the algorithm described in that docstring but with the qubit ordering fixed to the order in the input s.
 ’ROGGE’: A randomized elimination order global Gaussian elimination algorithm. This is the same algorithm as
’BGGE’ except that the order that the qubits are eliminated in is randomized. This results in significantly lowercost circuits than the ‘BGGE’ method (given sufficiently many iterations). More details are given in the compile_symplectic_with_random_ordered_global_gaussian_elimination() docstring.
’iAGvGE’: Our improved version of the AaraonsonGottesman method for compiling a Clifford circuit, which uses 3 CNOT circuits and 3 1Qgate layers (rather than the 5 CNOT circuit used in the algorithm of AG in Phys. Rev. A 70 052328 (2004)), with the CNOT circuits compiled using Gaussian elimination. Note that this algorithm appears to perform substantially worse than ‘ROGGE’, even though with an upgraded CNOT compiler it is asymptotically optimal (unlike any of the GGE methods). Also, note that this algorithm is randomized: there are many possible CNOT circuits (with nonequivalent action, individually) for the 2 of the 3 CNOT stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization used in the stabilizer state/measurement compilers.
aargs (list, optional) – If the algorithm can take optional arguments, not already specified as separate arguments above, then this list is passed to the compile_symplectic algorithm as its final arguments.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
prefixpaulis (bool, optional) – A Pauli layer is needed to compile the correct Clifford (and not just the correct Clifford up to Paulis). When prefixpaulis = True this Pauli layer is placed at the beginning of the circuit; when False, it is placed at the end. Note that the required Pauli layer depends on whether we prefix or postfix it to the main symplecticgenerating circuit.
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this Clifford circuit. This can be useful for preventing coherent addition of errors in the circuit.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit implementing the input Clifford gate/circuit.
 pygsti.algorithms.compile_stabilizer_state(s, p, pspec, absolute_compilation, paulieq_compilation, qubit_labels=None, iterations=20, paulirandomize=False, algorithm='COiCAGE', aargs=[], costfunction='2QGC:10:depth:1', rand_state=None)¶
Generates a circuit to create the stabilizer state from the standard input state 0,0,0,…>.
The stabilizer state is specified by s and p. The circuit returned is over the gates in the processor spec. See :function:`compile_stabilizer_state()` for the inverse of this.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers. This is a symplectic matrix representing any Clifford gate that, when acting on 0,0,0,…>, generates the desired stabilizer state. So s is not unique.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate. This phase vector matrix should, together with s, represent any Clifford gate that, when acting on 0,0,0,…>, generates the desired stabilizer state. So p is not unique.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
pspec –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the stabilizer state is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – This algorithm is randomized. This is the number of iterations used in the algorithm. the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this circuit. This can be useful for preventing coherent addition of errors in the circuit.
algorithm (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. algorithm specifies the CNOTcompilation algorithm to use. The allowe values are all those algorithms that permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances.
aargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that creates the specified stabilizer state from 0,0,0,…>
 pygsti.algorithms.compile_stabilizer_measurement(s, p, pspec, absolute_compilation, paulieq_compilation, qubit_labels=None, iterations=20, paulirandomize=False, algorithm='COCAGE', aargs=[], costfunction='2QGC:10:depth:1', rand_state=None)¶
Generates a circuit to map the stabilizer state to the standard state 0,0,0,…>.
The stabilizer state is specified by s and p. The circuit returned is over the gates in the processor spec pspec. See :function”compile_stabilizer_state() for the inverse of this. So, this circuit followed by a Zbasis measurement can be used to simulate a projection onto the stabilizer state C0,0,0,…> where C is the Clifford represented by s and p.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers. This is a symplectic matrix representing any Clifford gate that, when acting on 0,0,0,…>, generates the stabilizer state that we need to map to 0,0,0,…>. So s is not unique.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate. This phase vector matrix should, together with s, represent any Clifford gate that, when acting on 0,0,0,…>, generates the stabilizer state that we need to map to 0,0,0,…>. So p is not unique.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the stabilizer state is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – This algorithm is randomized. This is the number of iterations used in the algorithm. the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this circuit. This can be useful for preventing coherent addition of errors in the circuit.
algorithm (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. algorithm specifies the CNOTcompilation algorithm to use. The allowe values are all those algorithms that permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances.
aargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that maps the specified stabilizer state to 0,0,0,…>
 pygsti.algorithms.compile_cnot_circuit(s, pspec, compilation, qubit_labels=None, algorithm='COiCAGE', compile_to_native=False, check=True, aargs=[], rand_state=None)¶
A CNOT circuit compiler.
Takes an arbitrary CNOT circuit, input as a symplectic matrix s that corresponds to the matrix portion of the symplectic representation of this Clifford circuit, and decomposes it into a sequences of gates from the processor spec pspec.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers that represents a Clifford circuit: so it must be blockdiagonal. Specifically, it has the form s = ((A,0),(0,B)) where B is the inverse transpose of A (over [0,1] mod 2).
pspec (QubitProcessorSpec) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
compilation (CompilationRules) – Rules for compiling the “native” gates of pspec into clifford gates, used if compile_to_native==True.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
algorithm (str, optional) –
The algorithm to use. The optionas are:
 ’BGE’A basic Gaussian elimination algorithm, that uses CNOT to perform rowreduction on the upper
LHS (or lower RHS) of s. This algorithm does not take device connectivity into account.
 ’OCAGE’Userordered connectivityadjusted Gaussian elimination. The qubits are eliminated in the
specified order; the first element of arrgs must be a list specify this order. The algorithm is also “connectivityadjusted” in the sense that it uses the connectivity graph (in pspec.qubit_graph) to try and avoid using CNOTs between unconnected pairs whenever possible, and to decide the order of various operations.
 ’OiCAGE’The same as ‘OCAGE’ except that it has some improvements, and it requires connectivity
graph of the remaining qubits, after each qubit has been ‘eliminated’, to be connected. In the current format this algorithm is only slightly betterperforming than ‘OCAGE’, and only on average. (This algorithm will possibly be improved in the future, whereas ‘OCAGE’ will remain asis for reproducability of previously obtained results.)
 ’ROCAGE’: Same as ‘OCAGE’ except that the elimination order is chosen at random, rather than user
specified.
 ’COCAGE’, ‘COiCAGE’The same as ‘OCAGE’ and ‘OiCAGE’, respectively, except that the elimination order
is fixed to eliminate qubits with the worse connectivity before those with better connectivity.
compile_to_native (bool, optional) – Whether the circuit should be given in terms of the native gates of the processor defined in pspec.
check (bool, optional) – Whether to check the output is correct.
aargs (list, optional) – A list of arguments handed to the CNOT compiler algorithm. For some choices of algorithm (e.g., ‘OCAGE’) this list must not be empty. For algorithms where there are X nonoptional arguements after s and pspec these are specified as the first X arguments of aargs. The remaining elements in aargs, if any, are handed to the algorithm as the arguments after the optional qubit_labels and check arguments (the first of which is set by the input qubit_labels in this function).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that implements the same unitary as the CNOT circuit represented by s.
 pygsti.algorithms.contract(model, to_what, dataset=None, maxiter=1000000, tol=0.01, use_direct_cp=True, method='NelderMead', verbosity=0)¶
Contract a Model to a specified space.
All contraction operations except ‘vSPAM’ operate entirely on the gate matrices and leave state preparations and measurments alone, while ‘vSPAM’ operations only on SPAM.
 Parameters
model (Model) – The model to contract
to_what (string) –
Specifies which space is the model is contracted to. Allowed values are:
’TP’ – All gates are manifestly tracepreserving maps.
’CP’ – All gates are manifestly completelypositive maps.
’CPTP’ – All gates are manifestly completelypositive and tracepreserving maps.
’XP’ – All gates are manifestly “experimentallypositive” maps.
’XPTP’ – All gates are manifestly “experimentallypositive” and tracepreserving maps.
’vSPAM’ – state preparation and measurement operations are valid.
’nothing’ – no contraction is performed.
dataset (DataSet, optional) – Dataset to use to determine whether a model is in the “experimentallypositive” (XP) space. Required only when contracting to XP or XPTP.
maxiter (int, optional) – Maximum number of iterations for iterative contraction routines.
tol (float, optional) – Tolerance for iterative contraction routines.
use_direct_cp (bool, optional) – Whether to use a faster directcontraction method for CP contraction. This method essentially transforms to the Choi matrix, truncates any negative eigenvalues to zero, then transforms back to a operation matrix.
method (string, optional) – The method used when contracting to XP and nondirectly to CP (i.e. use_direct_cp == False).
verbosity (int, optional) – How much detail to send to stdout.
 Returns
Model – The contracted model
 pygsti.algorithms._contract_to_xp(model, dataset, verbosity, method='NelderMead', maxiter=100000, tol=1e10)¶
 pygsti.algorithms._contract_to_cp(model, verbosity, method='NelderMead', maxiter=100000, tol=0.01)¶
 pygsti.algorithms._contract_to_cp_direct(model, verbosity, tp_also=False, maxiter=100000, tol=1e08)¶
 pygsti.algorithms._contract_to_tp(model, verbosity)¶
 pygsti.algorithms._contract_to_valid_spam(model, verbosity=0)¶
Contract the surface preparation and measurement operations of a Model to the space of valid quantum operations.
 Parameters
model (Model) – The model to contract
verbosity (int) – How much detail to send to stdout.
 Returns
Model – The contracted model
 class pygsti.algorithms._DummyProfiler¶
Bases:
object
A dummy profiler that doesn’t do anything.
A class which implements the same interface as Profiler but which doesn’t actually do any profiling (consists of stub functions).
 add_time(self, name, start_time, prefix=0)¶
Stub function that does nothing
 Parameters
name (string) – The name of the timer to add elapsed time into (if the name doesn’t exist, one is created and initialized to the elapsed time).
start_time (float) – The starting time used to compute the elapsed, i.e. the value time.time()start_time, which is added to the named timer.
prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.
 Returns
None
 add_count(self, name, inc=1, prefix=0)¶
Stub function that does nothing
 Parameters
name (string) – The name of the counter to add val into (if the name doesn’t exist, one is created and initialized to val).
inc (int, optional) – The increment (the value to add to the counter).
prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.
 Returns
None
 memory_check(self, name, printme=None, prefix=0)¶
Stub function that does nothing
 Parameters
name (string) – The name of the memory checkpoint. (Later, memory information can be organized by checkpoint name.)
printme (bool, optional) – Whether or not to print the memory usage during this function call (if None, the default, then the value of default_print_memcheck specified during Profiler construction is used).
prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.
 Returns
None
 class pygsti.algorithms.BuiltinBasis(name, dim_or_statespace, sparse=False)¶
Bases:
LazyBasis
A basis that is included within and integrated into pyGSTi.
Such bases may, in most cases be represented merely by its name. (In actuality, a dimension is also required, but this is often able to be inferred from context.)
 Parameters
name ({"pp", "gm", "std", "qt", "id", "cl", "sv"}) – Name of the basis to be created.
dim_or_statespace (int or StateSpace) – The dimension of the basis to be created or the state space for which a basis should be created. Note that when this is an integer it is the dimension of the vectors, which correspond to flattened elements in simple cases. Thus, a 1qubit basis would have dimension 2 in the statevector (name=”sv”) case and dimension 4 when constructing a densitymatrix basis (e.g. name=”pp”).
sparse (bool, optional) – Whether basis elements should be stored as SciPy CSR sparse matrices or dense numpy arrays (the default).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 __hash__(self)¶
Return hash(self).
 _lazy_build_elements(self)¶
 _lazy_build_labels(self)¶
 _copy_with_toggled_sparsity(self)¶
 __eq__(self, other)¶
Return self==value.
 class pygsti.algorithms.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
 class pygsti.algorithms.DirectSumBasis(component_bases, name=None, longname=None)¶
Bases:
LazyBasis
A basis that is the direct sum of one or more “component” bases.
Elements of this basis are the union of the basis elements on each component, each embedded into a common blockdiagonal structure where each component occupies its own block. Thus, when there is more than one component, a DirectSumBasis is not a simple basis because the size of its elements is larger than the size of its vector space (which corresponds to just the diagonal blocks of its elements).
 Parameters
component_bases (iterable) – A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to :function:`Basis.cast`, e.g. (‘pp’,4).
name (str, optional) – The name of this basis. If None, the names of the component bases joined with “+” is used.
longname (str, optional) – A longer description of this basis. If None, then a long name is automatically generated.
 vector_elements¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Type
list
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 __hash__(self)¶
Return hash(self).
 _lazy_build_vector_elements(self)¶
 _lazy_build_elements(self)¶
 _lazy_build_labels(self)¶
 _copy_with_toggled_sparsity(self)¶
 __eq__(self, other)¶
Return self==value.
 property vector_elements(self)¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Returns
list
 property to_std_transform_matrix(self)¶
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.
 Returns
numpy array or scipy.sparse.lil_matrix – An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
 property to_elementstd_transform_matrix(self)¶
Get transformation matrix from this basis to the “element space”.
Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space”  that is, vectors in the same standard basis that the elements of this basis are expressed in.
 Returns
numpy array – An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
 create_equivalent(self, builtin_basis_name)¶
Create an equivalent basis with components of type builtin_basis_name.
Create a Basis that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name.
 Parameters
builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.
 Returns
DirectSumBasis
 create_simple_equivalent(self, builtin_basis_name=None)¶
Create a basis of type builtin_basis_name whose elements are compatible with this basis.
Create a simple basis and one without components (e.g. a
TensorProdBasis
, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_nameanalogue of the standard basis that this basis’s elements are expressed in. Parameters
builtin_basis_name (str, optional) – The name of the builtin basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and componentfree version of the same builtinbasis type.
 Returns
Basis
 class pygsti.algorithms._CircuitList(circuits, op_label_aliases=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.algorithms._ResourceAllocation(comm=None, mem_limit=None, profiler=None, distribute_method='default', allocated_memory=0)¶
Bases:
object
Describes available resources and how they should be allocated.
This includes the number of processors and amount of memory, as well as a strategy for how computations should be distributed among them.
 Parameters
comm (mpi4py.MPI.Comm, optional) – MPI communicator holding the number of available processors.
mem_limit (int, optional) – A rough perprocessor memory limit in bytes.
profiler (Profiler, optional) – A lightweight profiler object for tracking resource usage.
distribute_method (str, optional) – The name of a distribution strategy.
 classmethod cast(cls, arg)¶
Cast arg to a
ResourceAllocation
object.If arg already is a
ResourceAllocation
instance, it just returned. Otherwise this function attempts to create a new instance from arg. Parameters
arg (ResourceAllocation or dict) – An object that can be cast to a
ResourceAllocation
. Returns
ResourceAllocation
 build_hostcomms(self)¶
 property comm_rank(self)¶
A safe way to get self.comm.rank (0 if self.comm is None)
 property comm_size(self)¶
A safe way to get self.comm.size (1 if self.comm is None)
 property is_host_leader(self)¶
True if this processors is the rank0 “leader” of its host (node). False otherwise.
 host_comm_barrier(self)¶
Calls self.host_comm.barrier() when self.host_comm is not None.
This convenience function provides an oftenused barrier that follows code where a single “leader” processor modifies a memory block shared between all members of self.host_comm, and the other processors must wait until this modification is performed before proceeding with their own computations.
 Returns
None
 copy(self)¶
Copy this object.
 Returns
ResourceAllocation
 reset(self, allocated_memory=0)¶
Resets internal allocation counters to given values (defaults to zero).
 Parameters
allocated_memory (int64) – The value to set the memory allocation counter to.
 Returns
None
 add_tracked_memory(self, num_elements, dtype='d')¶
Adds nelements * itemsize bytes to the total amount of allocated memory being tracked.
If the total (tracked) memory exceeds self.mem_limit a
MemoryError
exception is raised. Parameters
num_elements (int) – The number of elements to track allocation of.
dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.
 Returns
None
 check_can_allocate_memory(self, num_elements, dtype='d')¶
Checks that allocating nelements doesn’t cause the memory limit to be exceeded.
This memory isn’t tracked  it’s just added to the current tracked memory and a
MemoryError
exception is raised if the result exceeds self.mem_limit. Parameters
num_elements (int) – The number of elements to track allocation of.
dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.
 Returns
None
 temporarily_track_memory(self, num_elements, dtype='d')¶
Temporarily adds nelements to tracked memory (a context manager).
A
MemoryError
exception is raised if the tracked memory exceeds self.mem_limit. Parameters
num_elements (int) – The number of elements to track allocation of.
dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.
 Returns
contextmanager
 gather_base(self, result, local, slice_of_global, unit_ralloc=None, all_gather=False)¶
Gather or allgather operation using local arrays and a unit resource allocation.
Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final tobe gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.
all_gather (bool, optional) – Whether the final result should be gathered on all the processors of this
ResourceAllocation
or just the root (rank 0) processor.
 Returns
None
 gather(self, result, local, slice_of_global, unit_ralloc=None)¶
Gather local arrays into a global result array potentially with a unit resource allocation.
Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final tobe gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.
The global array is only gathered on the root (rank 0) processor of this resource allocation.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, only needed on the root (rank 0) processor. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allgather(self, result, local, slice_of_global, unit_ralloc=None)¶
Allgather local arrays into global arrays on each processor, potentially using a unit resource allocation.
Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final tobe gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allreduce_sum(self, result, local, unit_ralloc=None)¶
Sum local arrays on different processors, potentially using a unit resource allocation.
Similar to a normal MPI reduce call (with MPI.SUM type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the sum, only processors with unit_ralloc.rank == 0 contribute to the sum. This handles the case where simply summing the local contributions from all processors would result in overcounting because of multiple processors hold the same logical result (summand).
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being summed. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allreduce_sum_simple(self, local, unit_ralloc=None)¶
A simplified sum over quantities on different processors that doesn’t use shared memory.
The shared memory usage of :method:`allreduce_sum` can be overkill when just summing a single scalar quantity. This method provides a way to easily sum a quantity across all the processors in this
ResourceAllocation
object using a unit resource allocation. Parameters
local (int or float) – The local (perprocessor) value to sum.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local value, so that only the unit_ralloc.rank == 0 processors will contribute to the sum. If None, then it is assumed that each processor computes a logically different local value.
 Returns
float or int – The sum of all local quantities, returned on all the processors.
 allreduce_min(self, result, local, unit_ralloc=None)¶
Take elementwise min of local arrays on different processors, potentially using a unit resource allocation.
Similar to a normal MPI reduce call (with MPI.MIN type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the min operation, only processors with unit_ralloc.rank == 0 contribute.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allreduce_max(self, result, local, unit_ralloc=None)¶
Take elementwise max of local arrays on different processors, potentially using a unit resource allocation.
Similar to a normal MPI reduce call (with MPI.MAX type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the max operation, only processors with unit_ralloc.rank == 0 contribute.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 bcast(self, value, root=0)¶
Broadcasts a value from the root processor/host to the others in this resource allocation.
This is similar to a usual MPI broadcast, except it takes advantage of shared memory when it is available. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, then this routine places value in a shared memory buffer and uses the resource allocation’s interhost communicator to broadcast the result from the root host to all the other hosts using all the processor on the root host in parallel (all processors with the same intrahost rank participate in a MPI broadcast). Parameters
value (numpy.ndarray) – The value to broadcast. May be shared memory but doesn’t need to be. Only need to specify this on the rank root processor, other processors can provide any value for this argument (it’s unused).
root (int) – The rank of the processor whose value will be to broadcast.
 Returns
numpy.ndarray – The broadcast value, in a new, nonsharedmemory array.
 __getstate__(self)¶
 class pygsti.algorithms._CustomLMOptimizer(maxiter=100, maxfev=100, tol=1e06, fditer=0, first_fditer=0, damping_mode='identity', damping_basis='diagonal_values', damping_clip=None, use_acceleration=False, uphill_step_threshold=0.0, init_munu='auto', oob_check_interval=0, oob_action='reject', oob_check_mode=0, serial_solve_proc_threshold=100)¶
Bases:
Optimizer
A LevenbergMarquardt optimizer customized for GSTlike problems.
 Parameters
maxiter (int, optional) – The maximum number of (outer) interations.
maxfev (int, optional) – The maximum function evaluations.
tol (float or dict, optional) – The tolerance, specified as a single float or as a dict with keys {‘relx’, ‘relf’, ‘jac’, ‘maxdx’}. A single float sets the ‘relf’ and ‘jac’ elemments and leaves the others at their default values.
fditer (int optional) – Internally compute the Jacobian using a finitedifference method for the first fditer iterations. This is useful when the initial point lies at a special or singular point where the analytic Jacobian is misleading.
first_fditer (int, optional) – Number of finitedifference iterations applied to the first stage of the optimization (only). Unused.
damping_mode ({'identity', 'JTJ', 'invJTJ', 'adaptive'}) – How damping is applied. ‘identity’ means that the damping parameter mu multiplies the identity matrix. ‘JTJ’ means that mu multiplies the diagonal or singular values (depending on scaling_mode) of the JTJ (Fischer information and approx. hessaian) matrix, whereas ‘invJTJ’ means mu multiplies the reciprocals of these values instead. The ‘adaptive’ mode adaptively chooses a damping strategy.
damping_basis ({'diagonal_values', 'singular_values'}) – Whether the the diagonal or singular values of the JTJ matrix are used during damping. If ‘singular_values’ is selected, then a SVD of the Jacobian (J) matrix is performed and damping is performed in the basis of (right) singular vectors. If ‘diagonal_values’ is selected, the diagonal values of relevant matrices are used as a proxy for the the singular values (saving the cost of performing a SVD).
damping_clip (tuple, optional) – A 2tuple giving upper and lower bounds for the values that mu multiplies. If damping_mode == “identity” then this argument is ignored, as mu always multiplies a 1.0 on the diagonal if the identity matrix. If None, then no clipping is applied.
use_acceleration (bool, optional) – Whether to include a geodesic acceleration term as suggested in arXiv:1201.5885. This is supposed to increase the rate of convergence with very little overhead. In practice we’ve seen mixed results.
uphill_step_threshold (float, optional) – Allows uphill steps when taking two consecutive steps in nearly the same direction. The condition for accepting an uphill step is that (uphill_step_thresholdbeta)*new_objective < old_objective, where beta is the cosine of the angle between successive steps. If uphill_step_threshold == 0 then no uphill steps are allowed, otherwise it should take a value between 1.0 and 2.0, with 1.0 being the most permissive to uphill steps.
init_munu (tuple, optional) – If not None, a (mu, nu) tuple of 2 floats giving the initial values for mu and nu.
oob_check_interval (int, optional) – Every oob_check_interval outer iterations, the objective function (obj_fn) is called with a second argument ‘oob_check’, set to True. In this case, obj_fn can raise a ValueError exception to indicate that it is Out Of Bounds. If oob_check_interval is 0 then this check is never performed; if 1 then it is always performed.
oob_action ({"reject","stop"}) – What to do when the objective function indicates (by raising a ValueError as described above). “reject” means the step is rejected but the optimization proceeds; “stop” means the optimization stops and returns as converged at the last knowninbounds point.
oob_check_mode (int, optional) – An advanced option, expert use only. If 0 then the optimization is halted as soon as an attempt is made to evaluate the function out of bounds. If 1 then the optimization is halted only when a wouldbe accepted step is out of bounds.
serial_solve_proc_threshold (int optional) – When there are fewer than this many processors, the optimizer will solve linear systems serially, using SciPy on a single processor, rather than using a parallelized Gaussian Elimination (with partial pivoting) algorithm coded in Python. Since SciPy’s implementation is more efficient, it’s not worth using the parallel version until there are many processors to spread the work among.
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 run(self, objective, profiler, printer)¶
Perform the optimization.
 Parameters
objective (ObjectiveFunction) – The objective function to optimize.
profiler (Profiler) – A profiler to track resource usage.
printer (VerbosityPrinter) – printer to use for sending output to stdout.
 class pygsti.algorithms._Optimizer¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
An optimizer. Optimizes an objective function.
 pygsti.algorithms._dummy_profiler¶
 pygsti.algorithms.CUSTOMLM = True¶
 pygsti.algorithms.FLOATSIZE = 8¶
 pygsti.algorithms.run_lgst(dataset, prep_fiducials, effect_fiducials, target_model, op_labels=None, op_label_aliases=None, guess_model_for_gauge=None, svd_truncate_to=None, verbosity=0)¶
Performs Linearinversion Gate Set Tomography on the dataset.
 Parameters
dataset (DataSet) – The data used to generate the LGST estimates
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to specify which operation labels should be estimated, a guess for which gauge these estimates should be returned in.
op_labels (list, optional) – A list of which operation labels (or aliases) should be estimated. Overrides the operation labels in target_model. e.g. [‘Gi’,’Gx’,’Gy’,’Gx2’]
op_label_aliases (dictionary, optional) – Dictionary 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’])
guess_model_for_gauge (Model, optional) – A model used to compute a gauge transformation that is applied to the LGST estimates before they are returned. This gauge transformation is computed such that if the estimated gates matched the model given, then the operation matrices would match, i.e. the gauge would be the same as the model supplied. Defaults to target_model.
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
Model – A model containing all of the estimated labels (or aliases)
 pygsti.algorithms._lgst_matrix_dims(model, prep_fiducials, effect_fiducials)¶
 pygsti.algorithms._construct_ab(prep_fiducials, effect_fiducials, model, dataset, op_label_aliases=None)¶
 pygsti.algorithms._construct_x_matrix(prep_fiducials, effect_fiducials, model, op_label_tuple, dataset, op_label_aliases=None)¶
 pygsti.algorithms._construct_a(effect_fiducials, model)¶
 pygsti.algorithms._construct_b(prep_fiducials, model)¶
 pygsti.algorithms._construct_target_ab(prep_fiducials, effect_fiducials, target_model)¶
 pygsti.algorithms.gram_rank_and_eigenvalues(dataset, prep_fiducials, effect_fiducials, target_model)¶
Returns the rank and singular values of the Gram matrix for a dataset.
 Parameters
dataset (DataSet) – The data used to populate the Gram matrix
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to make sense of circuit elements, and to compute the theoretical gram matrix eigenvalues (returned as svalues_target).
 Returns
rank (int) – the rank of the Gram matrix
svalues (numpy array) – the singular values of the Gram matrix
svalues_target (numpy array) – the corresponding singular values of the Gram matrix generated by target_model.
 pygsti.algorithms.run_gst_fit_simple(dataset, start_model, circuits, optimizer, objective_function_builder, resource_alloc, verbosity=0)¶
Performs core Gate Set Tomography function of model optimization.
Optimizes the parameters of start_model by minimizing the objective function built by objective_function_builder. Probabilities are computed by the model, and outcome counts are supplied by dataset.
 Parameters
dataset (DataSet) – The dataset to obtain counts from.
start_model (Model) – The Model used as a starting point for the leastsquares optimization.
circuits (list of (tuples or Circuits)) – Each tuple contains operation labels and specifies a circuit whose probabilities are considered when trying to leastsquaresfit the probabilities given in the dataset. e.g. [ (), (‘Gx’,), (‘Gx’,’Gy’) ]
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
objective_function_builder (ObjectiveFunctionBuilder) – Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”.
resource_alloc (ResourceAllocation) – A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
result (OptimizerResult) – the result of the optimization
model (Model) – the bestfit model.
 pygsti.algorithms.run_gst_fit(mdc_store, optimizer, objective_function_builder, verbosity=0)¶
Performs core Gate Set Tomography function of model optimization.
Optimizes the model to the data within mdc_store by minimizing the objective function built by objective_function_builder.
 Parameters
mdc_store (ModelDatasetCircuitsStore) – An object holding a model, data set, and set of circuits. This defines the model to be optimized, the data to fit to, and the circuits where predicted vs. observed comparisons should be made. This object also contains additional information specific to the given model, data set, and circuit list, doubling as a cache for increased performance. This information is also specific to a particular resource allocation, which affects how cached values stored.
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
objective_function_builder (ObjectiveFunctionBuilder) – Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”. If None, then mdc_store must itself be an alreadybuilt objective function.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
result (OptimizerResult) – the result of the optimization
objfn_store (MDCObjectiveFunction) – the objective function and store containing the bestfit model evaluated at the bestfit point.
 pygsti.algorithms.run_iterative_gst(dataset, start_model, circuit_lists, optimizer, iteration_objfn_builders, final_objfn_builders, resource_alloc, verbosity=0)¶
Performs Iterative Gate Set Tomography on the dataset.
 Parameters
dataset (DataSet) – The data used to generate MLGST gate estimates
start_model (Model) – The Model used as a starting point for the leastsquares optimization.
circuit_lists (list of lists of (tuples or Circuits)) – The ith element is a list of the circuits to be used in the ith iteration of the optimization. Each element of these lists is a circuit, specifed as either a Circuit object or as a tuple of operation labels (but all must be specified using the same type). e.g. [ [ (), (‘Gx’,) ], [ (), (‘Gx’,), (‘Gy’,) ], [ (), (‘Gx’,), (‘Gy’,), (‘Gx’,’Gy’) ] ]
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
iteration_objfn_builders (list) – List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on each iteration.
final_objfn_builders (list) – List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on the final iteration.
resource_alloc (ResourceAllocation) – A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
models (list of Models) – list whose ith element is the model corresponding to the results of the ith iteration.
optimums (list of OptimizerResults) – list whose ith element is the final optimizer result from that iteration.
final_objfn (MDSObjectiveFunction) – The final iteration’s objective function / store, which encapsulated the final objective function evaluated at the bestfit point (an “evaluated” modeldataSetcircuits store).
 pygsti.algorithms._do_runopt(objective, optimizer, printer)¶
Runs the core modeloptimization step within a GST routine by optimizing objective using optimizer.
This is factored out as a separate function because of the differences when running Taylorterm simtype calculations, which utilize this as a subroutine (see :function:`_do_term_runopt`).
 Parameters
objective (MDSObjectiveFunction) – A “modeldataset” objective function to optimize.
optimizer (Optimizer) – The optimizer to use.
printer (VerbosityPrinter) – An object for printing output.
 Returns
OptimizerResult
 pygsti.algorithms._do_term_runopt(objective, optimizer, printer)¶
Runs the core modeloptimization step for models using the Taylorterm (path integral) method of computing probabilities.
This routine serves the same purpose as :function:`_do_runopt`, but is more complex because an appropriate “path set” must be found, requiring a loop of model optimizations with fixed path sets until a sufficient “good” path set is obtained.
 Parameters
objective (MDSObjectiveFunction) – A “modeldataset” objective function to optimize.
optimizer (Optimizer) – The optimizer to use.
printer (VerbosityPrinter) – An object for printing output.
 Returns
OptimizerResult
 pygsti.algorithms.find_closest_unitary_opmx(operation_mx)¶
Find the closest (in fidelity) unitary superoperator to operation_mx.
Finds the closest operation matrix (by maximizing fidelity) to operation_mx that describes a unitary quantum gate.
 Parameters
operation_mx (numpy array) – The operation matrix to act on.
 Returns
numpy array – The resulting closest unitary operation matrix.
 class pygsti.algorithms._EigenvalueParamDenseOp(matrix, include_off_diags_in_degen_2_blocks=False, tp_constrained_and_unital=False, evotype='default', state_space=None)¶
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
A real operation matrix parameterized only by its eigenvalues.
These eigenvalues are assumed to be either real or to occur in conjugate pairs. Thus, the number of parameters is equal to the number of eigenvalues.
 Parameters
matrix (numpy array) – a square 2D numpy array that gives the raw operation matrix to paramterize. The shape of this array sets the dimension of the operation.
include_off_diags_in_degen_2_blocks (bool) – If True, include as parameters the (initially zero) offdiagonal elements in degenerate 2x2 blocks of the the diagonalized operation matrix (no offdiagonals are included in blocks larger than 2x2). This is an option specifically used in the intelligent fiducial pair reduction (IFPR) algorithm.
tp_constrained_and_unital (bool) – If True, assume the top row of the operation matrix is fixed to [1, 0, … 0] and should not be parameterized, and verify that the matrix is unital. In this case, “1” is always a fixed (notparamterized0 eigenvalue with eigenvector [1,0,…0] and if include_off_diags_in_degen_2_blocks is True any off diagonal elements lying on the top row are not parameterized as implied by the TP constraint.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 _construct_matrix(self)¶
Build the internal operation matrix using the current parameters.
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 pygsti.algorithms._remove_duplicates(l, index_to_test=None)¶
Remove duplicates from the a list and return the result.
 Parameters
l (iterable) – The list/set to remove duplicates from.
index_to_test (int, optional) – If not None, the index within the elements of l to test. For example, if all the elements of l contain 2 tuples (x,y) then set index_to_test == 1 to remove tuples with duplicate yvalues.
 Returns
list – the list after duplicates have been removed.
 pygsti.algorithms._nCr(n, r)¶
Number of combinations of r items out of a set of n. Equals n!/(r!(nr)!)
 pygsti.algorithms._random_combination(indices_tuple, r)¶
 Random selection from itertools.combinations(indices_tuple, r)
from http://docs.python.org/2/library/itertools.html#recipes
 pygsti.algorithms.find_sufficient_fiducial_pairs(target_model, prep_fiducials, meas_fiducials, germs, test_lengths=(256, 2048), prep_povm_tuples='first', tol=0.75, search_mode='sequential', n_random=100, seed=None, verbosity=0, test_pair_list=None, mem_limit=None, minimum_pairs=1)¶
Finds a (global) set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find a set of fiducial pairs that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). The test for amplification is performed using the two germpower lengths given by test_lengths, and tests whether the magnitudes of the Jacobian’s singular values scale linearly with the germpower length.
In the special case when test_pair_list is not None, the function tests the given set of fiducial pairs for amplificational completeness, and does not perform any search.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
test_lengths ((L1,L2) tuple of ints, optional) – A tuple of integers specifying the germpower lengths to use when checking for amplificational completeness.
prep_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
tol (float, optional) – The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
test_pair_list (list or None, optional) – If not None, a list of (prepfid_index,measfid_index) tuples of integers, specifying a list of fiducial pairs (indices are into prep_fiducials and meas_fiducials, respectively). These pairs are then tested for amplificational completeness and the number of amplified parameters is printed to stdout. (This is a special debugging functionality.)
mem_limit (int, optional) – A memory limit in bytes.
minimum_pairs (int, optional) – The minimium number of fiducial pairs to try (default == 1). Set this to integers larger than 1 to avoid trying pair sets that are known to be too small.
 Returns
list – A list of (prepfid_index,measfid_index) tuples of integers, specifying a list of fiducial pairs (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.find_sufficient_fiducial_pairs_per_germ(target_model, prep_fiducials, meas_fiducials, germs, pre_povm_tuples='first', search_mode='sequential', constrain_to_tp=True, n_random=100, seed=None, verbosity=0, mem_limit=None)¶
Finds a pergerm set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find sets of fiducial pairs, one set per germ, that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). For each germ, a fiducial pair set is found that amplifies all of the “parameters” (really linear combinations of them) that the particular germ amplifies.
To test whether a set of fiducial pairs satisfies this condition, the sum of projectors P_i = dot(J_i,J_i^T), where J_i is a matrix of the derivatives of each of the selected (prepFiducial+germ+effectFiducial) sequence probabilities with respect to the ith germ eigenvalue (or more generally, amplified parameter), is computed. If the fiducialpair set is sufficient, the rank of the resulting sum (an operator) will be equal to the total (maximal) number of parameters the germ can amplify.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence (per germ) before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
constrain_to_tp (bool, optional) – Whether or not to consider nonTP parameters the the germs amplify. If the fiducal pairs will be used in a GST estimation where the model is constrained to being tracepreserving (TP), this should be set to True.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
dict – A dictionary whose keys are the germ circuits and whose values are lists of (iRhoFid,iMeasFid) tuples of integers, each specifying the list of fiducial pairs for a particular germ (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.find_sufficient_fiducial_pairs_per_germ_power(target_model, prep_fiducials, meas_fiducials, germs, max_lengths, pre_povm_tuples='first', search_mode='sequential', constrain_to_tp=True, n_random=100, seed=None, verbosity=0, mem_limit=None)¶
Finds a pergerm set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find sets of fiducial pairs, one set per germ, that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). For each germ, a fiducial pair set is found that amplifies all of the “parameters” (really linear combinations of them) that the particular germ amplifies.
To test whether a set of fiducial pairs satisfies this condition, the sum of projectors P_i = dot(J_i,J_i^T), where J_i is a matrix of the derivatives of each of the selected (prepFiducial+germ+effectFiducial) sequence probabilities with respect to the ith germ eigenvalue (or more generally, amplified parameter), is computed. If the fiducialpair set is sufficient, the rank of the resulting sum (an operator) will be equal to the total (maximal) number of parameters the germ can amplify.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
max_lengths (list of int) – The germ powers (number of repetitions) to be used to amplify errors.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence (per germ) before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
constrain_to_tp (bool, optional) – Whether or not to consider nonTP parameters the the germs amplify. If the fiducal pairs will be used in a GST estimation where the model is constrained to being tracepreserving (TP), this should be set to True.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
dict – A dictionary whose keys are the germ circuits and whose values are lists of (iRhoFid,iMeasFid) tuples of integers, each specifying the list of fiducial pairs for a particular germ (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.test_fiducial_pairs(fid_pairs, target_model, prep_fiducials, meas_fiducials, germs, test_lengths=(256, 2048), pre_povm_tuples='first', tol=0.75, verbosity=0, mem_limit=None)¶
Tests a set of global or pergerm fiducial pairs.
Determines how many model parameters (of target_model) are amplified by the fiducial pairs given by fid_pairs, which can be either a list of 2tuples (for globalFPR) or a dictionary (for pergerm FPR).
 Parameters
fid_pairs (list or dict) – Either a single list of fiducialindex pairs (2tuples) that is applied to every germ (global FPR) OR a pergerm dictionary of lists, each containing the fiducialindex pairs (2tuples) for that germ (for pergerm FPR).
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
test_lengths ((L1,L2) tuple of ints, optional) – A tuple of integers specifying the germpower lengths to use when checking for amplificational completeness.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
tol (float, optional) – The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
numAmplified (int)
 pygsti.algorithms._get_per_germ_fidpairs(prep_fiducials, meas_fiducials, pre_povm_tuples, gsGerm, mem_limit, printer, search_mode, seed, n_random)¶
 class pygsti.algorithms._ComplementPOVMEffect(identity, other_effects)¶
Bases:
pygsti.modelmembers.povms.conjugatedeffect.ConjugatedStatePOVMEffect
TODO: docstring A POVM effect vector that ensures that all the effects of a POVM sum to the identity.
This POVM effect vector is paramterized as I  sum(other_spam_vecs) where I is a (static) identity element and other_param_vecs is a list of other spam vectors in the same parent
POVM
. This only partially implements the modelmember interface (some methods such as to_vector and from_vector will thunk down to base class versions which raise NotImplementedError), as instances are meant to be contained within aPOVM
which takes care of vectorization. Parameters
identity (array_like or POVMEffect) – a 1D numpy array representing the static identity operation from which the sum of the other vectors is subtracted.
other_spamvecs (list of POVMEffects) – A list of the “other” parameterized POVM effect vectors which are subtracted from identity to compute the final value of this “complement” POVM effect vector.
 _construct_vector(self)¶
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 property num_params(self)¶
Get the number of independent parameters which specify this POVM effect vector.
 Returns
int – the number of independent parameters.