pygsti.algorithms
LinearOperator Set Tomography Algorithms Python Package
Submodules
pygsti.algorithms.compilers
pygsti.algorithms.contract
pygsti.algorithms.core
pygsti.algorithms.directx
pygsti.algorithms.fiducialpairreduction
pygsti.algorithms.fiducialselection
pygsti.algorithms.gaugeopt
pygsti.algorithms.germselection
pygsti.algorithms.grammatrix
pygsti.algorithms.grasp
pygsti.algorithms.mirroring
pygsti.algorithms.randomcircuit
pygsti.algorithms.rbfit
pygsti.algorithms.robust_phase_estimation
pygsti.algorithms.scoring
Package Contents
Classes
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. 
Functions

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. 

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. 

Performs Iterative Gate Set Tomography on the dataset. 

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

Calculates the parts of the eigenvalue update loop algorithm that we can 

This function performs a lowrank update to the components of 

Generate the compact eigenvalue decomposition of the input matrix. 

Generate the compact eigenvalue decomposition of the input matrix. 

Parameters 

Print matrix in pretty format. 

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. 

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

Tests a set of global or pergerm fiducial pairs. 





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



Function for precomputing the jacobian dictionaries from bulk_dprobs 

Returns the square of the frobenius distance between arrays: (a  b_Fro)^2. 

Calculates the parts of the eigenvalue update loop algorithm that we can 

This function performs a lowrank update to the components of 

Generate the compact eigenvalue decomposition of the input matrix. 

Generate the compact eigenvalue decomposition of the input matrix. 

Generate prep and measurement fiducials for a given target model. 

Implements logical xor function for arbitrary number of inputs. 



Function for generating a cache of PTMs for the available fiducials. 

Make a dictionary structure mapping native state preps and circuits to numpy 

Make a dictionary structure mapping native measurements and circuits to numpy 

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. 



Parameters 

Generate prep and measurement fiducials for a given target model. 

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. 

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

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

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

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

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

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. 

Use GRASP to find a highperforming germ set. 



Function for generating a cache of PTMs for the available fiducials. 

Function for dropping a random fraction of the candidate germ list. 

Generate the compact eigenvalue decomposition of the input matrix. 

Generate the compact eigenvalue decomposition of the input matrix. 

Calculates the parts of the eigenvalue update loop algorithm that we can 

This function performs a lowrank update to the spectrum of 

This function performs a lowrank update to the components of 

Greedy algorithm starting with 0 germs. 

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

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





Parameters 

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

Calculates the parts of the psuedoinverse update loop algorithm that we can 

Helper function for calculating rankone updates to the trace of the psuedoinverse. 

Helper function for calculating rankone psuedoinverse updates. 

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 
Attributes
 pygsti.algorithms.compile_clifford(s, p, pspec=None, absolute_compilation=None, paulieq_compilation=None, qubit_labels=None, iterations=20, algorithm='ROGGE', aargs=None, 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
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
 sarray over [0,1]
An (2n X 2n) symplectic matrix of 0s and 1s integers.
 parray over [0,1]
A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate.
 pspecQubitProcessorSpec, 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_compilationCompilationRules
Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
 paulieq_compilationCompilationRules
Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
 qubit_labelslist, 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.
 iterationsint, 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).
 algorithmstr, 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.
 aargslist, 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.
 costfunctionfunction 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.
 prefixpaulisbool, 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.
 paulirandomizebool, 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=None, 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
compile_stabilizer_state()
for the inverse of this.Parameters
 sarray 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.
 parray 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, pspecQubitProcessorSpec, 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_compilationCompilationRules
Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
 paulieq_compilationCompilationRules
Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
 qubit_labelsList, 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.
 iterationsint, 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).
 paulirandomizebool, 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.
 algorithmstr, 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.
 aargslist, optional
If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
 costfunctionfunction 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=None, 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 C`0,0,0,…>` where C is the Clifford represented by s and p.
Parameters
 sarray 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.
 parray 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.
 pspecQubitProcessorSpec, 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_compilationCompilationRules
Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
 paulieq_compilationCompilationRules
Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
 qubit_labelsList, 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.
 iterationsint, 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).
 paulirandomizebool, 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.
 algorithmstr, 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.
 aargslist, optional
If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
 costfunctionfunction 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=None, 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
 sarray 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).
 pspecQubitProcessorSpec
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.
 compilationCompilationRules
Rules for compiling the “native” gates of pspec into clifford gates, used if compile_to_native==True.
 qubit_labelslist, 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.
 algorithmstr, 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_nativebool, optional
Whether the circuit should be given in terms of the native gates of the processor defined in pspec.
 checkbool, optional
Whether to check the output is correct.
 aargslist, 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
 modelModel
The model to contract
 to_whatstring
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.
 datasetDataSet, optional
Dataset to use to determine whether a model is in the “experimentallypositive” (XP) space. Required only when contracting to XP or XPTP.
 maxiterint, optional
Maximum number of iterations for iterative contraction routines.
 tolfloat, optional
Tolerance for iterative contraction routines.
 use_direct_cpbool, 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.
 methodstring, optional
The method used when contracting to XP and nondirectly to CP (i.e. use_direct_cp == False).
 verbosityint, optional
How much detail to send to stdout.
Returns
 Model
The contracted model
 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_statespaceint 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”).
 sparsebool, optional
Whether basis elements should be stored as SciPy CSR sparse matrices or dense numpy arrays (the default).
Creates a new LazyBasis. Parameters are the same as those to
Basis.__init__()
. property dim
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size
The number of elements (or vectorelements) in the basis.
 property elshape
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).
 property first_element_is_identity
True if the first element of this basis is proportional to the identity matrix, False otherwise.
 is_equivalent(other, sparseness_must_match=True)
Tests whether this basis is equal to another basis, optionally ignoring sparseness.
Parameters
 otherBasis or str
The basis to compare with.
 sparseness_must_matchbool, optional
If False then comparison ignores differing sparseness, and this function returns True when the two bases are equal except for their .sparse values.
Returns
bool
 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
 verbosityint
How verbose the printer should be.
 filenamestr, optional
Where to put output (If none, output goes to screen)
 commmpi4py.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, …
 warningsbool, optional
Whether or not to print warnings
 splitbool, optional
Whether to split output between stdout and stderr as appropriate, or to combine the streams so everything is sent to stdout.
 clear_filebool, optional
Whether or not filename should be cleared (overwritten) or simply appended to.
Attributes
 _comm_pathstr
relative path where comm files (outputs of nonroot ranks) are stored.
 _comm_file_namestr
root filename for comm files (outputs of nonroot ranks).
 _comm_file_extstr
filename extension for comm files (outputs of nonroot ranks).
Customize a verbosity printer object
Parameters
 verbosityint, optional
How verbose the printer should be.
 filenamestr, optional
Where to put output (If none, output goes to screen)
 commmpi4py.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, …
 warningsbool, optional
Whether or not to print warnings
 clone()
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
 verbosityint or VerbosityPrinter object, required:
object to build a printer from
 commmpi4py.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
 error(message)
Log an error to the screen/file
Parameters
 messagestr
the error message
Returns
None
 warning(message)
Log a warning to the screen/file if verbosity > 1
Parameters
 messagestr
the warning message
Returns
None
 log(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
 messagestr
the message to print (or log)
 message_levelint, optional
the minimum verbosity level at which this level is printed.
 indent_charstr, optional
what constitutes an “indent” (messages at higher levels are indented more when do_indent=True).
 show_statustypebool, optional
if True, prepend lines with “Status Level X” indicating the message_level.
 do_indentbool, 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_offsetint, optional
an additional number of indentations to add, on top of any due to the message level.
 endstr, optional
the character (or string) to end message lines with.
 flushbool, optional
whether stdout should be flushed right after this message is printed (this avoids delays in onscreen output due to buffering).
Returns
None
 verbosity_env(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
 levelint
the verbosity level of the environment.
 progress_logging(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_levelint, optional
progress messages will not be shown until the verbosity level reaches message_level.
 show_progress(iteration, total, bar_length=50, num_decimals=2, fill_char='#', empty_char='', prefix='Progress:', suffix='', verbose_messages=None, indent_char=' ', end='\n')
Displays a progress message (to be used within a progress_logging block).
Parameters
 iterationint
the 0based current iteration – the interation number this message is for.
 totalint
the total number of iterations expected.
 bar_lengthint, 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_decimalsint, optional
number of places after the decimal point that are displayed in progress bar’s percentage complete.
 fill_charstr, optional
replaces ‘#’ as the barfilling character
 empty_charstr, optional
replaces ‘’ as the emptybar character
 prefixstr, optional
message in front of the bar
 suffixstr, optional
message after the bar
 verbose_messageslist, 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_charstr, optional
what constitutes an “indentation”.
 endstr, optional
the character (or string) to end message lines with.
Returns
None
 start_recording()
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
stop_recording()
.Returns
None
 stop_recording()
Stops recording and returns recorded output.
Stops a “recording” started by
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_basesiterable
A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to
Basis.cast()
, e.g. (‘pp’,4). namestr, optional
The name of this basis. If None, the names of the component bases joined with “+” is used.
 longnamestr, optional
A longer description of this basis. If None, then a long name is automatically generated.
Attributes
 vector_elementslist
The “vectors” of this basis, always 1D (sparse or dense) arrays.
Create a new DirectSumBasis  a basis for a space that is the directsum of the spaces spanned by other “component” bases.
Parameters
 component_basesiterable
A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to
Basis.cast()
, e.g. (‘pp’,4). namestr, optional
The name of this basis. If None, the names of the component bases joined with “+” is used.
 longnamestr, optional
A longer description of this basis. If None, then a long name is automatically generated.
 property dim
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size
The number of elements (or vectorelements) in the basis.
 property elshape
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).
 property vector_elements
The “vectors” of this basis, always 1D (sparse or dense) arrays.
Returns
list
 property to_std_transform_matrix
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
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).
 is_equivalent(other, sparseness_must_match=True)
Tests whether this basis is equal to another basis, optionally ignoring sparseness.
Parameters
 otherBasis or str
The basis to compare with.
 sparseness_must_matchbool, optional
If False then comparison ignores differing sparseness, and this function returns True when the two bases are equal except for their .sparse values.
Returns
bool
 create_equivalent(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_namestr
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(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_namestr, 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
 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, check=True)
Performs Linearinversion Gate Set Tomography on the dataset.
Parameters
 datasetDataSet
The data used to generate the LGST estimates
 prep_fiducialslist of Circuits
Fiducial Circuits used to construct a informationally complete effective preparation.
 effect_fiducialslist of Circuits
Fiducial Circuits used to construct a informationally complete effective measurement.
 target_modelModel
A model used to specify which operation labels should be estimated, a guess for which gauge these estimates should be returned in.
 op_labelslist, 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_aliasesdictionary, 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.baseobjs.Circuit([‘Gx’,’Gx’,’Gx’])
 guess_model_for_gaugeModel, 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_toint, 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.
 verbosityint, optional
How much detail to send to stdout.
 checkbool, optional
Specifies whether we perform computationally expensive assertion checks. Computationally cheap assertions will always be checked.
Returns
 Model
A model containing all of the estimated labels (or aliases)
 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
 datasetDataSet
The data used to populate the Gram matrix
 prep_fiducialslist of Circuits
Fiducial Circuits used to construct a informationally complete effective preparation.
 effect_fiducialslist of Circuits
Fiducial Circuits used to construct a informationally complete effective measurement.
 target_modelModel
A model used to make sense of circuit elements, and to compute the theoretical gram matrix eigenvalues (returned as svalues_target).
Returns
 rankint
the rank of the Gram matrix
 svaluesnumpy array
the singular values of the Gram matrix
 svalues_targetnumpy 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
 datasetDataSet
The dataset to obtain counts from.
 start_modelModel
The Model used as a starting point for the leastsquares optimization.
 circuitslist 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’) ]
 optimizerOptimizer or dict
The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
 objective_function_builderObjectiveFunctionBuilder
Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”.
 resource_allocResourceAllocation
A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
 verbosityint, optional
How much detail to send to stdout.
Returns
 resultOptimizerResult
the result of the optimization
 modelModel
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_storeModelDatasetCircuitsStore
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.
 optimizerOptimizer or dict
The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
 objective_function_builderObjectiveFunctionBuilder
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.
 verbosityint, optional
How much detail to send to stdout.
Returns
 resultOptimizerResult
the result of the optimization
 objfn_storeMDCObjectiveFunction
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
 datasetDataSet
The data used to generate MLGST gate estimates
 start_modelModel
The Model used as a starting point for the leastsquares optimization.
 circuit_listslist 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’) ] ]
 optimizerOptimizer or dict
The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
 iteration_objfn_builderslist
List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on each iteration.
 final_objfn_builderslist
List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on the final iteration.
 resource_allocResourceAllocation
A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
 verbosityint, optional
How much detail to send to stdout.
Returns
 modelslist of Models
list whose ith element is the model corresponding to the results of the ith iteration.
 optimumslist of OptimizerResults
list whose ith element is the final optimizer result from that iteration.
 final_objfnMDSObjectiveFunction
The final iteration’s objective function / store, which encapsulated the final objective function evaluated at the bestfit point (an “evaluated” modeldataSetcircuits store).
 pygsti.algorithms.iterative_gst_generator(dataset, start_model, circuit_lists, optimizer, iteration_objfn_builders, final_objfn_builders, resource_alloc, starting_index=0, verbosity=0)
Performs Iterative Gate Set Tomography on the dataset. Same as run_iterative_gst, except this function produces a generator for producing the output for each iteration instead of returning the lists of outputs all at once.
Parameters
 datasetDataSet
The data used to generate MLGST gate estimates
 start_modelModel
The Model used as a starting point for the leastsquares optimization.
 circuit_listslist 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’) ] ]
 optimizerOptimizer or dict
The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
 iteration_objfn_builderslist
List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on each iteration.
 final_objfn_builderslist
List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on the final iteration.
 resource_allocResourceAllocation
A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
 starting_indexint, optional (default 0)
Index of the iteration to start the optimization at. Primarily used when warmstarting the iterative optimization from a checkpoint.
 verbosityint, optional
How much detail to send to stdout.
Returns
 generator
Returns a generator which when queried the ith time returns a tuple containing:
model: the model corresponding to the results of the ith iteration.
optimums : the final OptimizerResults from the ith iteration.
final_objfn : If the final iteration the MDSObjectiveFunction function / store, which encapsulated the final objective function evaluated at the bestfit point (an “evaluated” modeldatasetcircuits store).
 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_mxnumpy array
The operation matrix to act on.
Returns
 numpy array
The resulting closest unitary operation matrix.
 pygsti.algorithms.construct_update_cache(mat, evd_tol=1e10)
Calculates the parts of the eigenvalue update loop algorithm that we can precompute and reuse throughout all of the potential updates.
Input:
 matndarray
The matrix to construct a set of reusable objects for performing the updates. mat is assumed to be a symmetric square matrix.
 evd_tolfloat (optional)
A threshold value for setting eigenvalues to zero.
Output:
 U, endarrays
The components of the compact eigenvalue decomposition of mat such that U@diag(s)@U.conj().T= mat e in this case is a 1D array of the nonzero eigenvalues.
 projUndarray
A projector onto the complement of the column space of U Corresponds to (IU@U.T)
 pygsti.algorithms.minamide_style_inverse_trace(update, orig_e, U, proj_U, force_rank_increase=False)
This function performs a lowrank update to the components of the psuedo inverse of a matrix relevant to the calculation of that matrix’s updated trace. It takes as input a symmetric update of the form: A@A.T, in other words a symmetric rankdecomposition of the update matrix. Since the update is symmetric we only pass as input one half (i.e. we only need A, since A.T in numpy is treated simply as a different view of A). We also pass in the original spectrum as well as a projector onto the complement of the column space of the original matrix’s eigenvector matrix.
Based on an update formula for psuedoinverses by minamide combined with a result on updating compact SVDs by M. Brand.
input:
 updatendarray
symmetric lowrank update to perform. This is the first half the symmetric rank decomposition s.t. update@update.T= the full update matrix.
 orig_endarray
Spectrum of the original matrix. This is a 1D array.
 proj_Undarray
Projector onto the complement of the column space of the original matrix’s eigenvectors.
 updated_tracefloat
Value of the trace of the updated psuedoinverse matrix.
 updated_rankint
total rank of the updated matrix.
 rank_increase_flagbool
a flag that is returned to indicate is a candidate germ failed to amplify additional parameters. This indicates things short circuited and so the scoring function should skip this germ.
 pygsti.algorithms.compact_EVD(mat, threshold=1e10)
Generate the compact eigenvalue decomposition of the input matrix. Assumes of course that the user has specified a diagonalizable matrix, there are no safety checks for that made a priori.
input:
 matndarray
input matrix we want the compact EVD for. Assumed to be diagonalizable.
 thresholdfloat, optional
threshold value for deciding if an eigenvalue is zero.
output:
 endarray
1D numpy array of the nonzero eigenvalues of mat.
 Undarray
Matrix such that U@diag(s)@U.conj().T=mat.
 pygsti.algorithms.compact_EVD_via_SVD(mat, threshold=1e10)
Generate the compact eigenvalue decomposition of the input matrix. Assumes of course that the user has specified a diagonalizable matrix, there are no safety checks for that made a priori.
input:
 matndarray
input matrix we want the compact EVD for. Assumed to be diagonalizable.
 thresholdfloat, optional
threshold value for deciding if an eigenvalue is zero.
output:
 endarray
1D numpy array of the nonzero eigenvalues of mat.
 Undarray
Matrix such that U@diag(s)@U.conj().T=mat.
 pygsti.algorithms.germ_set_spanning_vectors(target_model, germ_list, assume_real=False, float_type=_np.cdouble, num_nongauge_params=None, tol=1e06, pretest=False, evd_tol=1e10, verbosity=1, threshold=1000000.0, mode='greedy', update_cache_low_rank=False, final_test=True, comm=None)
Parameters
 target_modelModel 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).
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typenumpy dtype object, optional
Numpy data type to use for floating point arrays.
 tolfloat, optional
Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate. pretestboolean, optional
Whether germ list should be initially checked for completeness.
 evd_tolfloat, optional
A threshold value to use when taking eigenvalue decompositions/SVDs such that values below this are set to zero.
 verbosityint, optional
Level of detail printed to stdout.
 thresholdfloat, optional
Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC
 modestring, optional (default ‘greedy)’
An optional mode string for specifying the search heuristic used for constructing the germ vector set. If ‘greedy’ we use a greedy search algorithm based on lowrank updates. If ‘RRQR’ we use a heuristic for the subset selection problem due to Golub, Klema and Stewart (1976), detailed in chapter 12 of the book “Matrix Computations” by Golub and Van Loan.
 update_cache_low_rankbool, optional (default = False)
A flag indicating whether the psuedoinverses in the update cache used as part of the lowrank update routine should themselves be updated between iterations using lowrank updates. Setting this to True gives a notable performance boost, but I have found that this can also give rise to numerical stability issues, so caveat emptor. Only set to True if you’re sure of what you’re doing.
 final_testbool, optional (default True)
A flag indicating whether a final test should be performed to validate the final score of the germvector set found using either the greedy or RRQR based search heuristics. Can be useful in conjunction with the use of update_cache_low_rank, as this can help detect numerical stability problems in the use of lowrank updates for cache construction.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
Returns
 germ_vec_dictdict
A dictionary whose keys are germs and whose elements are numpy arrays whose columns correspond to the amplified directions in parameter space identified for that germ such that when combined with the amplified directions selected for each other germ in the set we maintain amplificational completeness.
 currentDDDndarray
The J^T@J matrix for subset of twirled derivative columns selected accross all of the germs. The spectrum of this matrix provides information about the amplificational properties of the reduced vector set.
 pygsti.algorithms.print_mx(mx, width=9, prec=4, withbrackets=False)
Print matrix in pretty format.
Will print real or complex matrices with a desired precision and “cell” width.
Parameters
 mxnumpy array
the matrix (2D array) to print.
 widthint, opitonal
the width (in characters) of each printed element
 precint optional
the precision (in characters) of each printed element
 withbracketsbool, optional
whether to print brackets and commas to make the result something that Python can read back in.
Returns
None
 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_modelModel
The target model used to determine amplificational completeness.
 prep_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective preparation.
 meas_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective measurement.
 germslist 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_tupleslist 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.
 tolfloat, 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_randomint, optional
The number of randompairsets to consider for a given set size.
 seedint, optional
The seed to use for generating randompairsets.
 verbosityint, optional
How much detail to print to stdout.
 test_pair_listlist 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_limitint, optional
A memory limit in bytes.
 minimum_pairsint, 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, prep_povm_tuples='first', search_mode='random', constrain_to_tp=True, n_random=100, min_iterations=None, base_loweig_tol=0.1, seed=None, verbosity=0, num_soln_returned=1, type_soln_returned='best', retry_for_smaller=True, 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_modelModel
The target model used to determine amplificational completeness.
 prep_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective preparation.
 meas_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective measurement.
 germslist of Circuits
The germ circuits that are repeated to amplify errors.
 prep_povm_tupleslist 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_tpbool, 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_randomint, optional
The number of randompairsets to consider for a given set size.
 min_iterationsint, optional
A minimum number of candidate fiducial sets to try for a given set size before allowing the search to exit early in the event an acceptable candidate solution has already been found.
 base_loweig_tolfloat, optional (default 1e1)
A relative threshold value for determining if a fiducial set is an acceptable candidate solution. The tolerance value indicates the decrease in the magnitude of the smallest eigenvalue of the Jacobian we’re will to accept relative to that of the full fiducial set.
 seedint, optional
The seed to use for generating randompairsets.
 verbosityint, optional
How much detail to print to stdout.
 num_soln_returnedint, optional
The number of candidate solutions to return for each run of the fiducial pair search.
 type_soln_returnedstr, optional
Which type of criteria to use when selecting which of potentially many candidate fiducial pairs to search through. Currently only “best” supported which returns the num_soln_returned best candidates as measured by minimum eigenvalue.
 retry_for_smallerbool, optional
If true then a second search is performed seeded by the candidate solution sets found in the first pass. The search routine then randomly subsamples sets of fiducial pairs from these candidate solutions to see if a smaller subset will suffice.
 mem_limitint, 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_greedy(target_model, prep_fiducials, meas_fiducials, germs, prep_povm_tuples='first', constrain_to_tp=True, inv_trace_tol=10, initial_seed_mode='random', evd_tol=1e10, sensitivity_threshold=1e10, seed=None, verbosity=0, check_complete_fid_set=True, 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_modelModel
The target model used to determine amplificational completeness.
 prep_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective preparation.
 meas_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective measurement.
 germslist of Circuits
The germ circuits that are repeated to amplify errors.
 prep_povm_tupleslist 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.
 constrain_to_tpbool, optional (default True)
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.
 inv_trace_tolfloat, optional (default 10)
Tolerance used to identify whether a candidate fiducial set has a feasible cost function value and for comparing among both complete and incomplete candidate sets. The cost function corresonds to trace(pinv(sum_i(dot(J_i,J_i^T)))), where the J_i’s are described above, which is related to a condition in optimal design theory called aoptimality. The tolerance is a relative tolerance compared to the complete fiducial set. This essentially measures the relative sensitivity loss we’re willing to accept as part of applying FPR.
 initial_seed_modestr, optional (default ‘random’)
A string corresponding to the method used to seed an initial set of fiducial pairs in starting the greedy search routine. The default ‘random’ identifies the minimum number of fiducial pairs required for sensitivity to every parameter of a given germ and then randomly samples that number of fiducial pairs to use as an initial seed. Also supports the option ‘greedy’ in which case we start the greedy search from scratch using an empty seed set and select every fiducial pair greedily. Random is generally faster computationally, but greedy has been fount to often (but not always) find a smaller solution.
 evd_tolfloat, optional (default 1e10)
Threshold value for eigenvalues below which they are treated as zero. Used in the construction of compact eigenvalue decompositions (technically rankdecompositions) of jacobians. If encountering an error related to failing Cholesky decompositions consider increasing the value of this tolerance.
 sensitivity_thresholdfloat, optional (default 1e10)
Threshold used for determing is a fiducial pair is useless for measuring a given germ’s amplified parameters due to trivial sensitivity to the germ kite parameters (norm of jacobian w.r.t. the kite parameters is <sensitivity_threshold).
 seedint, optional
The seed to use for generating randompairsets.
 verbosityint, optional
How much detail to print to stdout.
 mem_limitint, 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, prep_povm_tuples='first', search_mode='random', constrain_to_tp=True, trunc_scheme='whole germ powers', n_random=100, min_iterations=None, base_loweig_tol=0.1, seed=None, verbosity=0, mem_limit=None, per_germ_candidate_set=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:
 Case: trunc_scheme == ‘whole germ powers’:
state_prep + prep_fiducial + pygsti.circuits.repeat_with_max_length(germ,L) + meas_fiducial + meas
 Case: trunc_scheme == ‘truncated germ powers’:
state_prep + prep_fiducial + pygsti.circuits.repeat_and_truncate(germ,L) + meas_fiducial + meas
 Case: trunc_scheme == ‘length as exponent’:
state_prep + prep_fiducial + germ^L + meas_fiducial + meas
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_modelModel
The target model used to determine amplificational completeness.
 prep_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective preparation.
 meas_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective measurement.
 germslist 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.
 prep_povm_tupleslist 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_tpbool, 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_randomint, optional
The number of randompairsets to consider for a given set size.
 min_iterations: int, optional
The number of randompairsets to consider before we allow the algorithm to terminate early if it has found an acceptable candidate fiducial set. If left with the default value of None then this is 1/2 the value of n_random.
 base_loweig_tol: float, optional
A relative tolerance to apply to candidate fiducial pair sets. Gives the multiplicative reduction in the magnitude of the minimum eigenvalue relative to the value for the full fiducial set the user is willing to tolerate.
 seedint, optional
The seed to use for generating randompairsets.
 verbosityint, optional
How much detail to print to stdout.
 mem_limitint, optional
A memory limit in bytes.
 per_germ_candidate_setdict, optional
If specified, this is a dictionary with keys given by the germ set. This dictionary is a previously found candidate set of fiducials output from the pergerm FPR function find_sufficient_fiducial_pairs_per_germ.
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), prep_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_pairslist 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_modelModel
The target model used to determine amplificational completeness.
 prep_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective preparation.
 meas_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective measurement.
 germslist 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_tupleslist 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.
 tolfloat, optional
The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
 verbosityint, optional
How much detail to print to stdout.
 mem_limitint, optional
A memory limit in bytes.
Returns
numAmplified : int
 pygsti.algorithms.construct_compact_evd_cache(fiducial_indices, complete_jacobian, element_map, eigenvalue_tolerance=1e10)
 pygsti.algorithms.filter_useless_fid_pairs(fiducial_indices, element_map, complete_jacobian, sensitivity_threshold=1e10)
 pygsti.algorithms.find_sufficient_fiducial_pairs_per_germ_global(target_model, prep_fiducials, meas_fiducials, germ_vector_spanning_set=None, germs=None, prep_povm_tuples='first', mem_limit=None, inv_trace_tol=10, initial_seed_mode='greedy', evd_tol=1e10, seed=None, verbosity=0, float_type=_np.cdouble, germ_set_spanning_kwargs=None, precomputed_jacobians=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 amplified parameter.
Parameters
 target_modelModel
The target model used to determine amplificational completeness.
 prep_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective preparation.
 meas_fiducialslist of Circuits
Fiducial circuits used to construct an informationally complete effective measurement.
 germ_vector_spanning_setdictionary of lists
A dictionary with keys corresponding to germs and values corresponding to lists of parameter vectors (less spam parameters) for which we need sensitivity.
 germslist of circuits
If passed in and germ_vector_spanning_set is None then we’ll use this in the calculation of the germ vector spanning set.
 prep_povm_tupleslist 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.
 verbosityint, optional
How much detail to print to stdout.
 mem_limitint, optional
A memory limit in bytes.
 inv_trace_tolfloat, optional (default 10)
A threshold tolerance value corresponding to the maximum reduction in sensitivity we are willing to tolerate relative to the complete set of fiducial pairs. Specifically the increase in the trace of the inverse/psuedoinverse of the directional derivative matrix for a germ’s specified amplified parameters that we are willing to tolerate.
 initial_seed_modestr, optional (default ‘greedy’)
Specifies the manner in which an initial set of fiducial pairs is selected for a germ to seed the greedy search routine. Currently only supports ‘greedy’ wherein we start from scratch from an empty set of fiducial pairs and select them entirely greedily.
 evd_tolfloat, optional (default 1e10)
Threshold value for eigenvalues below which they are treated as zero. Used in the construction of compact eigenvalue decompositions (technically rankdecompositions) for directional derivative matrices.
 seedint, optional (default None)
Seed for PRNGs. Not currently used.
 float_typenumpy dtype, optional (default numpy.cdouble)
Numpy data type to use for floating point arrays.
 germ_set_spanning_kwargsdict, optional (default None)
A dictionary of optional kwargs for the function pygsti.algorithms.germselection.germ_set_spanning_vectors. See doctring for that function for more details. Only utilized if the germ_vector_spanning_set argument of this function is None.
 precomputed_jacobiansdict, optional (default None)
An optional dictionary of precomputed jacobian dictionaries for the germ fiducial pair set. The keys are germs and the values are the dictionaries corresponding that that germfiducialpair set’s jacobian.
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.get_per_germ_fid_pairs_global(prep_fiducials, meas_fiducials, prep_povm_tuples, target_model, germ, germ_vector_list, mem_limit, printer, dof_per_povm, inv_trace_tol=10, initial_seed_mode='greedy', evd_tol=1e10, float_type=_np.cdouble, dprobs_dict=None)
 pygsti.algorithms.compute_jacobian_dicts(model, germs, prep_fiducials, meas_fiducials, prep_povm_tuples='first', comm=None, mem_limit=None, verbosity=0)
Function for precomputing the jacobian dictionaries from bulk_dprobs for a model with its SPAM parameters frozen, as needed for certain FPR applications. Can take a comm object for parallelization of the jacobian calculation using MPI.
 modelModel
The model used for calculating the jacobian with respect to.
 germs :list of Circuits
Germs to construct the jacobian dictionaries for.
 prep_fiducialslist of Circuits
A list of preparation fiducials circuits.
 meas_fiducialslist of Circuits
A list of measurement fiducial circuits.
 prep_povm_tuplesstr or list of tuples (default ‘first’)
Either a string or list of tuples. When a list of tuples these correspond to native state prep and native POVM pairs. When the special keyword argument ‘first’ is passed in the first native prep and first native POVM are used.
 commmpi4py.MPI.Comm, optional
When not
None
, an MPI communicator for distributing the computation across multiple processors is used for the jacobian calculation. mem_limitint, optional (default None)
An optional perworker memory limit, in bytes.
Returns
 jacobian_dictsdictionary of dictionaries
A dictionary whose keys correspond to germs and whose values correspond the jacobian dictionaries for the list of circuits induced by that germ together with the set of fiducials pairs. Format of these correspond to the format returned by bulk_dprobs.
 pygsti.algorithms.frobeniusdist_squared(a, b)
Returns the square of the frobenius distance between arrays: (a  b_Fro)^2.
This could be inlined, but we’re keeping it for API consistency with other distance functions.
Parameters
 anumpy array
First matrix.
 bnumpy array
Second matrix.
Returns
 float
The resulting frobenius distance.
 pygsti.algorithms.construct_update_cache(mat, evd_tol=1e10)
Calculates the parts of the eigenvalue update loop algorithm that we can precompute and reuse throughout all of the potential updates.
Input:
 matndarray
The matrix to construct a set of reusable objects for performing the updates. mat is assumed to be a symmetric square matrix.
 evd_tolfloat (optional)
A threshold value for setting eigenvalues to zero.
Output:
 U, endarrays
The components of the compact eigenvalue decomposition of mat such that U@diag(s)@U.conj().T= mat e in this case is a 1D array of the nonzero eigenvalues.
 projUndarray
A projector onto the complement of the column space of U Corresponds to (IU@U.T)
 pygsti.algorithms.minamide_style_inverse_trace(update, orig_e, U, proj_U, force_rank_increase=False)
This function performs a lowrank update to the components of the psuedo inverse of a matrix relevant to the calculation of that matrix’s updated trace. It takes as input a symmetric update of the form: A@A.T, in other words a symmetric rankdecomposition of the update matrix. Since the update is symmetric we only pass as input one half (i.e. we only need A, since A.T in numpy is treated simply as a different view of A). We also pass in the original spectrum as well as a projector onto the complement of the column space of the original matrix’s eigenvector matrix.
Based on an update formula for psuedoinverses by minamide combined with a result on updating compact SVDs by M. Brand.
input:
 updatendarray
symmetric lowrank update to perform. This is the first half the symmetric rank decomposition s.t. update@update.T= the full update matrix.
 orig_endarray
Spectrum of the original matrix. This is a 1D array.
 proj_Undarray
Projector onto the complement of the column space of the original matrix’s eigenvectors.
 updated_tracefloat
Value of the trace of the updated psuedoinverse matrix.
 updated_rankint
total rank of the updated matrix.
 rank_increase_flagbool
a flag that is returned to indicate is a candidate germ failed to amplify additional parameters. This indicates things short circuited and so the scoring function should skip this germ.
 pygsti.algorithms.compact_EVD(mat, threshold=1e10)
Generate the compact eigenvalue decomposition of the input matrix. Assumes of course that the user has specified a diagonalizable matrix, there are no safety checks for that made a priori.
input:
 matndarray
input matrix we want the compact EVD for. Assumed to be diagonalizable.
 thresholdfloat, optional
threshold value for deciding if an eigenvalue is zero.
output:
 endarray
1D numpy array of the nonzero eigenvalues of mat.
 Undarray
Matrix such that U@diag(s)@U.conj().T=mat.
 pygsti.algorithms.compact_EVD_via_SVD(mat, threshold=1e10)
Generate the compact eigenvalue decomposition of the input matrix. Assumes of course that the user has specified a diagonalizable matrix, there are no safety checks for that made a priori.
input:
 matndarray
input matrix we want the compact EVD for. Assumed to be diagonalizable.
 thresholdfloat, optional
threshold value for deciding if an eigenvalue is zero.
output:
 endarray
1D numpy array of the nonzero eigenvalues of mat.
 Undarray
Matrix such that U@diag(s)@U.conj().T=mat.
 pygsti.algorithms.find_fiducials(target_model, omit_identity=True, eq_thresh=1e06, ops_to_omit=None, force_empty=True, candidate_fid_counts=2, algorithm='grasp', algorithm_kwargs=None, verbosity=1, prep_fids=True, meas_fids=True, candidate_list=None, return_candidate_list=False, final_test=False, assume_clifford=False, candidate_seed=None, max_fid_length=None)
Generate prep and measurement fiducials for a given target model.
Parameters
 target_modelModel
The model you are aiming to implement.
 omit_identitybool, 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_threshfloat, 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_omitlist 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_emptybool, optional (default is True)
Whether or not to force all fiducial sets to contain the empty gate string as a fiducial.
 candidate_fid_countsint or dic, optional
A dictionary of fid_length : count keyvalue pairs, specifying the fiducial “candidate list”  a list of potential fiducials to draw from. count is either an integer specifying the number of random fiducials considered at the given fid_length or the special values “all upto” that considers all of the of all the fiducials of length up to the corresponding fid_length. If the keyword ‘all’ is used for the count value then all circuits at that particular length are added. If and integer, all germs of up to length that length are used, the equivalent of {specified_int: ‘all upto’}.
 algorithm{‘slack’, ‘grasp’, ‘greedy’}, 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. ‘greedy’
Use a greedy algorithm accelerated using lowrank update techniques. See
_find_fiducials_greedy()
for more details.
 algorithm_kwargsdict
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. verbosityint, optional
How much detail to send to stdout.
 candidate_listlist of circuits, optional
A user specified manually selected list of candidate fiducial circuits. Can speed up testing multiple objective function options, for example.
 return_candidate_list: bool, optional (default False)
When True we return the full list of deduped candidate fiducials considered along with the final fiducial lists.
 final_testbool, optional (default False)
When true a final check is performed on the returned solution for the candidate prep and measurement lists using the function test_fiducial_list to verify we have an acceptable candidate set (this uses a different code path in some cases so can be used to detect errors).
 assume_cliffordbool, optional (default False)
When true then we assume that all of the circuits are clifford circuits, which allows us to use a faster deduping routine exploiting the properties of clifford circuits.
 max_fid_lengthint, optional (deprecated)
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). This keyword is now deprecated. The behavior of the keyword is now equivalent to passing in an int for the candidate_fid_counts argument.
Returns
 prepFidListlist of Circuits
A list containing the circuits for the prep fiducials.
 measFidListlist of Circuits
A list containing the circuits for the measurement fiducials.
 pygsti.algorithms.xor(*args)
Implements logical xor function for arbitrary number of inputs.
Parameters
 argsboollikes
All the boolean (or booleanlike) objects to be checked for xor satisfaction.
Returns
 outputbool
True if and only if one and only one element of args is True and the rest are False. False otherwise.
 pygsti.algorithms.clean_fid_list(model, circuit_cache, available_fid_list, drop_identities=True, drop_duplicates=True, eq_thresh=1e06, assume_clifford=False)
 pygsti.algorithms.create_circuit_cache(model, circuit_list)
Function for generating a cache of PTMs for the available fiducials.
Parameters
 modelModel
The model (associates operation matrices with operation labels).
 ckt_listlist of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete state preparation.
Returns
 dictionary
A dictionary with keys given by circuits with corresponding entries being the PTMs for that circuit.
 pygsti.algorithms.create_prep_cache(model, available_prep_fid_list, circuit_cache=None)
Make a dictionary structure mapping native state preps and circuits to numpy column vectors for the corresponding effective state prep.
This can then be passed into ‘create_prep_mxs’ to more efficiently generate the matrices for score function evaluation.
Parameters
 modelModel
The model (associates operation matrices with operation labels).
 available_prep_fid_listlist of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete state preparation.
 circuit_cachedict
dictionary of PTMs for the circuits in the available_prep_fid_list
Returns
 dictionary
A dictionary with keys given be tuples of the form (native_prep, ckt) with corresponding entries being the numpy vectors for that state prep.
 pygsti.algorithms.create_meas_cache(model, available_meas_fid_list, circuit_cache=None)
Make a dictionary structure mapping native measurements and circuits to numpy column vectors corresponding to the transpose of the effective measurement effects.
This can then be passed into ‘create_meas_mxs’ to more efficiently generate the matrices for score function evaluation.
Parameters
 modelModel
The model (associates operation matrices with operation labels).
 available_meas_fid_listlist of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete measurements.
 circuit_cachedict
dictionary of PTMs for the circuits in the available_meas_fid_list
Returns
 tuple with dictionary and lists of POVM and Effect Key pairs.
A dictionary with keys given be tuples of the form (native_povm, native_povm_effect, ckt) with corresponding entries being the numpy vectors for the transpose of that effective measurement effect.
 pygsti.algorithms.create_prep_mxs(model, prep_fid_list, prep_cache=None)
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
 modelModel
The model (associates operation matrices with operation labels).
 prep_fid_listlist of Circuits
List of fiducial circuits for constructing an informationally complete state preparation.
 prep_cachedictionary of effective state preps
Dictionary of effective state preps cache used to accelerate the generation of the matrices used for score function evaluation. Default value is None.
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.create_meas_mxs(model, meas_fid_list, meas_cache=None)
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
 modelModel
The model (associates operation matrices with operation labels).
 meas_fid_listlist of Circuits
List of fiducial circuits for constructing an informationally complete measurement.
 meas_cachedictionary of effective measurement effects
Dictionary of effective measurement effects cache used to accelerate the generation of the matrices used for score function evaluation. Entries are columns of the transpose of the effects. Default value is None.
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.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, gate_penalty=None, fid_cache=None)
Compute a composite score for a fiducial list.
Parameters
 modelModel
The model (associates operation matrices with operation labels).
 fid_listlist of Circuits
List of fiducial circuits to test.
 prep_or_measstring (“prep” or “meas”)
Are we testing preparation or measurement fiducials?
 score_funcstr (‘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.)
 thresholdfloat, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
 return_allbool, optional (default is False)
Whether the spectrum should be returned along with the score.
 op_penaltyfloat, optional (default is 0.0)
Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
. l1_penaltyfloat, optional (default is 0.0)
Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
. gate_penaltydict, optional
A dictionary with keys given by individual gates and values corresponding to the penalty to add for each instance of that gate in the fiducial set.
 fid_cachedict, optional (default is None)
A dictionary of either effective state preparations or measurement effects used to accelerate the generation of the matrix used for scoring. It’s assumed that the user will pass in the correct cache based on the type of fiducial set being created (if wrong a fall back will revert to redoing all the matrix multiplication again).
Returns
 scoreCompositeScore
The score of the fiducials.
 spectrumnumpy.array, optional
The eigenvalues of the square of the absolute value of the score matrix.
 pygsti.algorithms.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, fid_cache=None)
Tests a prep or measure fiducial list for informational completeness.
Parameters
 modelModel
The model (associates operation matrices with operation labels).
 fid_listlist of Circuits
List of fiducial circuits to test.
 prep_or_measstring (“prep” or “meas”)
Are we testing preparation or measurement fiducials?
 score_funcstr (‘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_allbool, 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
 thresholdfloat, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
 l1_penaltyfloat, optional (default is 0.0)
Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
. op_penaltyfloat, optional (default is 0.0)
Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
. fid_cachedict, optional (default is None)
A dictionary of either effective state preparations or measurement effects used to accelerate the generation of the matrix used for scoring. It’s assumed that the user will pass in the correct cache based on the type of fiducial set being created (if wrong a fall back will revert to redoing all the matrix multiplication again).
Returns
 testResultbool
Whether or not the specified fiducial list is informationally complete for the provided model, to within the tolerance specified by threshold.
 spectrumarray, optional
The number of fiducials times the reciprocal of the spectrum of the score matrix. Only returned if return_all == True.
 scorefloat, optional
The score for the fiducial set; only returned if return_all == True.
 pygsti.algorithms.build_bitvec_mx(n, k)
Create an array of all lengthn and Hamming weight k binary vectors.
Parameters
 nint
The length of each bit string.
 kint
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.construct_compact_evd_cache(model, fids_list, prep_or_meas, fid_cache, eigenvalue_tolerance=1e10)
 pygsti.algorithms.add_penalties_greedy(unpenalized_score, fid_list, l1_penalty=0, op_penalty=0, gate_penalty=None)
Parameters
 unpenalized_scorefloat
The score function value to add penalty terms to.
 l1_penaltyfloat, optional (default 0.0)
A penalty term associated with the number of fiducials in a candidate list.
 op_penaltyfloat, optional (default 0.0)
A penalty term associated with the total number of gate operations used in aggregate across all of the fiducials in a candidate set.
 gate_penaltydict, optional (default None)
A dictionary with keys given by gate labels and values corresponding to a penalty term for that gate. This penalty is added for each instance of a gate in the dictionary across all fiducials in a candidate list of fiducials.
 pygsti.algorithms.create_candidate_fiducial_list(target_model, omit_identity=True, ops_to_omit=None, candidate_fid_counts=2, max_fid_length=None, eq_thresh=1e06, candidate_seed=None)
Generate prep and measurement fiducials for a given target model.
Parameters
 target_modelModel
The model you are aiming to implement.
 omit_identitybool, 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.
 ops_to_omitlist 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.
 candidate_fid_countsint or dic, optional
A dictionary of fid_length : count keyvalue pairs, specifying the fiducial “candidate list”  a list of potential fiducials to draw from. count is either an integer specifying the number of random fiducials considered at the given fid_length or the special values “all upto” that considers all of the of all the fiducials of length up to the corresponding fid_length. If the keyword ‘all’ is used for the count value then all circuits at that particular length are added. If and integer, all germs of up to length that length are used, the equivalent of {specified_int: ‘all upto’}.
 max_fid_lengthint, optional (deprecated)
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). This keyword is now deprecated. The behavior of the keyword is now equivalent to passing in an int for the candidate_fid_counts argument.
Returns
 availableFidListlist of Circuits
A list containing candidate fiducial circuits.
 pygsti.algorithms.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, convert_model_to=None, 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
 modelModel
The model to gaugeoptimize
 target_modelModel
The model to optimize to. The metric used for comparing models is given by gates_metric and spam_metric.
 item_weightsdict, 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_factorfloat, 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_factorfloat, 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_groupGaugeGroup, optional
The gauge group which defines which gauge trasformations are optimized over. If None, then the model’s default gauge group is used.
 methodstring, 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
 maxiterint, optional
Maximum number of iterations for the gauge optimization.
 maxfevint, optional
Maximum number of function evaluations for the gauge optimization. Defaults to maxiter.
 tolfloat, optional
The tolerance for the gauge optimization.
 oob_check_intervalint, 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.
 convert_model_tostr, dict, list, optional
For use when model is an ExplicitOpModel. When not None, calls model.convert_members_inplace(convert_model_to, set_default_gauge_group=False) if convert_model_to is a string, model.convert_members_inplace(**convert_model_to) if it is a dict, and repeated calls to either of the above instances when convert_model_to is a list or tuple prior to performing the gauge optimization. This allows the gauge optimization to be performed using a differently constrained model.
 return_allbool, optional
When True, return best “goodness” value and gauge matrix in addition to the gauge optimized model.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 verbosityint, optional
How much detail to send to stdout.
 check_jacbool
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_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
 modelModel
The model to gaugeoptimize
 objective_fnfunction
The function to be minimized. The function must take a single Model argument and return a float.
 gauge_groupGaugeGroup, optional
The gauge group which defines which gauge trasformations are optimized over. If None, then the model’s default gauge group is used.
 methodstring, 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
 maxiterint, optional
Maximum number of iterations for the gauge optimization.
 maxfevint, optional
Maximum number of function evaluations for the gauge optimization. Defaults to maxiter.
 tolfloat, optional
The tolerance for the gauge optimization.
 oob_check_intervalint, 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_allbool, optional
When True, return best “goodness” value and gauge matrix in addition to the gauge optimized model.
 jacobian_fnfunction, 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.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 verbosityint, 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.FLOATSIZE = '8'
 pygsti.algorithms.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, num_nongauge_params=None, assume_real=False, float_type=_np.cdouble, mode='allJac', toss_random_frac=None, force_rank_increase=False, save_cevd_cache_filename=None, load_cevd_cache_filename=None, file_compression=False)
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_modelModel 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).
 randomizebool, optional
Whether or not to add random unitary perturbations to the model(s) provided.
 randomization_strengthfloat, optional
The size of the random unitary perturbations applied to gates in the model. See
randomize_with_unitary()
for more details. num_gs_copiesint, optional
The number of copies of the original model that should be used.
 seedint, optional
Seed for generating random unitary perturbations to models. Also passed along to stochastic germselection algorithms and to the rng for dropping random fraction of germs.
 candidate_germ_countsdict, 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_seedint, 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.
 forcestr 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_kwargsdict
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_limitint, optional
A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 profilerProfiler, optional
A profiler object used for to track timing and memory usage.
 verbosityint, optional
The verbosity level of the
VerbosityPrinter
used to print log messages. num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typenumpy dtype object, optional
Numpy data type to use for floating point arrays.
 toss_random_fracfloat, optional
If specified this is a number between 0 and 1 that indicates the random fraction of candidate germs to drop randomly following the deduping procedure.
 mode{‘allJac’, ‘singleJac’, ‘compactEVD’}, optional (default ‘allJac’)
A flag to indicate the caching scheme used for storing the Jacobians for the candidate germs. Default value of ‘allJac’ caches all of the Jacobians and requires the most memory. ‘singleJac’ doesn’t cache anything and instead generates these Jacobians on the fly. The final option, ‘compactEVD’, is currently only configured to work with the greedy search algorithm. When selected the compact eigenvalue decomposition/compact SVD of each of the Jacobians is constructed and is cached. This uses an intermediate amount of memory between singleJac and allJac. When compactEVD mode is selected perform the greedy search iterations using an alternative method based on lowrank updates to the psuedoinverse. This alternative approach means that this mode also only works with the score function option set to ‘all’.
 force_rank_increasebool, optional (default False)
Optional flag that can be used in conjunction with the greedy search algorithm in compactEVD mode. When set we require that each subsequant addition to the germ set must increase the rank of the experiment design’s composite Jacobian. Can potentially speed up the search when set to True.
 save_cevd_cache_filenamestr, optional (default None)
When set and using the greedy search algorithm in ‘compactEVD’ mode this writes the compact EVD cache to disk using the specified filename.
 load_cevd_cache_filenamestr, optional (default None)
A filename/path to load an existing compact EVD cache from. Useful for warmstarting a germ set search with various cost function parameters, or for restarting a search that failed/crashed/ran out of memory. Note that there are no safety checks to confirm that the compact EVD cache indeed corresponds to that for of currently specified candidate circuit list, so care must be take to confirm that the candidate germ lists are consistent across runs.
 file_compressionbool, optional (default False)
When True and a filename is given for the save_cevd_cache_filename the corresponding numpy arrays are stored in a compressed format using numpy’s savez_compressed. Can significantly decrease the storage requirements on disk at the expense of some additional computational cost writing and loading the files.
Returns
 list of Circuit
A list containing the germs making up the germ set.
 pygsti.algorithms.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, num_nongauge_params=None, float_type=_np.cdouble)
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
 germslist
The germ set
 target_modelModel, optional
The target model, used to generate a neighborhood of randomized models.
 neighborhoodlist 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_sizeint, optional
Number of randomized models to construct around target_model.
 randomization_strengthfloat, optional
Strength of unitary randomizations, as passed to
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_penaltyfloat, optional
Coefficient for a penalty linear in the sum of the germ lengths.
 l1_penaltyfloat, optional
Coefficient for a penalty linear in the number of germs.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typenumpy dtype object, optional
Numpy data type to use for floating point arrays.
Returns
 CompositeScore
The maximum score for germs, indicating how many parameters it amplifies.
 pygsti.algorithms.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, germ_lengths=None, op_penalty=0.0, l1_penalty=0.0, num_nongauge_params=None, float_type=_np.cdouble)
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_fncallable
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_acfloat, optional
Value which the score (before penalties are applied) must be lower than for the germ set to be considered AC.
 init_nint
The number of largest eigenvalues to begin with checking.
 partial_deriv_dagger_derivnumpy.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.
 modelModel, optional
The model against which the germ set is to be scored. Not needed if partial_deriv_dagger_deriv is provided.
 partial_germs_listlist 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. epsfloat, 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. op_penaltyfloat, optional
Coefficient for a penalty linear in the sum of the germ lengths.
 germ_lengthsnumpy.array, optional
The length of each germ. Not needed if op_penalty is
0.0
or partial_germs_list is provided. l1_penaltyfloat, optional
Coefficient for a penalty linear in the number of germs.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
Returns
 CompositeScore
The score for the germ set indicating how many parameters it amplifies and its numerical score restricted to those parameters.
 pygsti.algorithms.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_listModel or list
A list of Model objects.
 randomization_strengthfloat, optional
Strength of unitary randomizations, as passed to
Model.randomize_with_unitary()
. num_copiesint
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.
 seedint, 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.test_germs_list_completeness(model_list, germs_list, score_func, threshold, float_type=_np.cdouble, comm=None, num_gauge_params=None)
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_listlist
A list of models to test. Often this list is a neighborhood (“cloud”) of models around a model of interest.
 germs_listlist
A list of the germ
Circuit
objects (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)
. thresholdfloat, 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.
 float_typenumpy dtype object, optional
Numpy data type to use for floating point arrays.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 num_gauge_paramsint, optional (default None)
A optional kwarg for specifying the number of gauge parameters. Specifying this if already precomputed can save on computation.
Returns
 int
The index of the first model in model_list to fail the amplficational completeness test. Returns 1 if germ set is AC for all tested models.
 pygsti.algorithms.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
 modelModel
The Model (associates operation matrices with operation labels).
 germs_to_testlist of Circuits
List of germ circuits to test for completeness.
 lengthint
The finite length to use in amplification testing. Larger values take longer to compute but give more robust results.
 weightsnumpy 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_spectrumbool, optional
If True, return the jacobian^T*jacobian spectrum in addition to the success flag.
 tolfloat, optional
Tolerance: an eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when it is less than tol.
Returns
 successbool
Whether all nongauge parameters were amplified.
 spectrumnumpy 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.test_germ_set_infl(model, germs_to_test, score_func='all', weights=None, return_spectrum=False, threshold=1000000.0, check=False, float_type=_np.cdouble, comm=None, nGaugeParams=None)
Test whether a set of germs is able to amplify all nongauge parameters.
Parameters
 modelModel
The Model (associates operation matrices with operation labels).
 germs_to_testlist of Circuit
List of germ circuits to test for completeness.
 score_funcstring
Label to indicate how a germ set is scored. See
list_score()
for details. weightsnumpy 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_spectrumbool, optional
If
True
, return the jacobian^T*jacobian spectrum in addition to the success flag. thresholdfloat, 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.
 checkbool, optional
Whether to perform internal consistency checks, at the expense of making the function slower.
 float_type: numpy dtype object, optional
Optional numpy data type to use for internal numpy array calculations.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 nGaugeParamsint, optional (default None)
A optional kwarg for specifying the number of gauge parameters. Specifying this if already precomputed can save on computation.
Returns
 successbool
Whether all nongauge parameters were amplified.
 spectrumnumpy 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.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, float_type=_np.cdouble)
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_listModel or list
The model or list of Models to select germs for.
 germs_listlist of Circuit
The list of germs to contruct a germ set from.
 randomizebool, 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_strengthfloat, optional
The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. num_copiesint, 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.
 seedint, optional
Seed for generating random unitary perturbations to models.
 op_penaltyfloat, 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)
. tolfloat, optional
Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate. thresholdfloat, optional
Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
 checkbool, optional
Whether to perform internal checks (will slow down run time substantially).
 forcelist 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.
 verbosityint, optional
Level of detail printed to stdout.
Returns
 list
A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.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, num_nongauge_params=None, float_type=_np.cdouble, mode='allJac')
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_listModel or list
The model or list of Model objects to select germs for.
 germs_listlist of Circuit
The list of germs to contruct a germ set from.
 randomizebool, 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_strengthfloat, optional
The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. num_copiesint, 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.
 seedint, optional
Seed for generating random unitary perturbations to models.
 op_penaltyfloat, 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)
. tolfloat, optional
Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate. thresholdfloat, optional
Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
 checkbool, optional
Whether to perform internal checks (will slow down run time substantially).
 forcelist 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.
 pretestboolean, optional
Whether germ list should be initially checked for completeness.
 mem_limitint, optional
A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 profilerProfiler, optional
A profiler object used for to track timing and memory usage.
 verbosityint, optional
Level of detail printed to stdout.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typenumpy dtype object, optional
Use an alternative data type for the values of the numpy arrays generated.
Returns
 list
A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.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, float_type=_np.cdouble)
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_listModel 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_listlist of Circuit
List of all germ circuits to consider.
 randomizeBool, 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_strengthfloat, optional
The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. Default is1e3
. num_copiesint, 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. seedfloat, 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_penaltyfloat, optional
How strong the penalty should be for increasing the germ set list by a single germ. Default is 1e2.
 op_penaltyfloat, optional
How strong the penalty should be for increasing a germ in the germ set list by a single gate. Default is 0.
 initial_weightslistlike
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_funcstring
Label to indicate how a germ set is scored. See
list_score()
for details. max_iterint, optional
The maximum number of iterations before giving up.
 fixed_slackfloat, 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_fracfloat, 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_allbool, optional
If
True
, return the finalweights
vector and score dictionary in addition to the optimal germ list (see below). tolfloat, optional
Tolerance used for eigenvector degeneracy testing in twirling operation.
 checkbool, optional
Whether to perform internal consistency checks, at the expense of making the function slower.
 forcestr 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_scorefloat, 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.
 thresholdfloat, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the germ set is rejected as amplificationally incomplete.
 verbosityint, optional
Integer >= 0 indicating the amount of detail to print.
See Also
Model
Circuit
 pygsti.algorithms.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, num_nongauge_params=None, float_type=_np.cdouble)
Use GRASP to find a highperforming germ set.
Parameters
 model_listModel 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_listlist of Circuit
List of all germ circuits to consider.
 alphafloat
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. randomizeBool, 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_strengthfloat, optional
The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. Default is1e3
. num_copiesint, 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. seedfloat, optional
The starting seed used for unitary randomization. If multiple Models are to be randomized,
model_list[i]
is randomized withseed + i
. l1_penaltyfloat, 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_penaltyfloat, optional
How strong the penalty should be for increasing a germ in the germ set list by a single gate.
 score_funcstring
Label to indicate how a germ set is scored. See
list_score()
for details. tolfloat, optional
Tolerance used for eigenvector degeneracy testing in twirling operation.
 thresholdfloat, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the germ set is rejected as amplificationally incomplete.
 checkbool, optional
Whether to perform internal consistency checks, at the expense of making the function slower.
 forcestr 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.
 iterationsint, optional
The number of GRASP iterations to perform.
 return_allbool, 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).
 shufflebool, 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).
 verbosityint, optional
Integer >= 0 indicating the amount of detail to print.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typeNumpy dtype object, optional
Numpy data type to use for floating point arrays
Returns
 finalGermListlist of Circuit
Sublist of germs_list specifying the final, optimal set of germs.
 pygsti.algorithms.clean_germ_list(model, circuit_cache, eq_thresh=1e06)
 pygsti.algorithms.create_circuit_cache(model, circuit_list)
Function for generating a cache of PTMs for the available fiducials.
Parameters
 modelModel
The model (associates operation matrices with operation labels).
 ckt_listlist of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete state preparation.
Returns
 dictionary
A dictionary with keys given by circuits with corresponding entries being the PTMs for that circuit.
 pygsti.algorithms.drop_random_germs(candidate_list, rand_frac, target_model, keep_bare=True, seed=None)
Function for dropping a random fraction of the candidate germ list.
Parameters
 candidate_listlist of Circuits
List of candidate germs
 target_modelModel
The model (associates operation matrices with operation labels)
 rand_fracfloat between 0 and 1
random fraction of candidate germs to drop
 keep_barebool
Whether to always include the bare germs in the returned set.
Returns
 availableGermsListList
list of candidate germs with random fraction dropped.
 pygsti.algorithms.compact_EVD(mat, threshold=1e10)
Generate the compact eigenvalue decomposition of the input matrix. Assumes of course that the user has specified a diagonalizable matrix, there are no safety checks for that made a priori.
input:
 matndarray
input matrix we want the compact EVD for. Assumed to be diagonalizable.
 thresholdfloat, optional
threshold value for deciding if an eigenvalue is zero.
output:
 endarray
1D numpy array of the nonzero eigenvalues of mat.
 Undarray
Matrix such that U@diag(s)@U.conj().T=mat.
 pygsti.algorithms.compact_EVD_via_SVD(mat, threshold=1e10)
Generate the compact eigenvalue decomposition of the input matrix. Assumes of course that the user has specified a diagonalizable matrix, there are no safety checks for that made a priori.
input:
 matndarray
input matrix we want the compact EVD for. Assumed to be diagonalizable.
 thresholdfloat, optional
threshold value for deciding if an eigenvalue is zero.
output:
 endarray
1D numpy array of the nonzero eigenvalues of mat.
 Undarray
Matrix such that U@diag(s)@U.conj().T=mat.
 pygsti.algorithms.construct_update_cache(mat, evd_tol=1e10)
Calculates the parts of the eigenvalue update loop algorithm that we can precompute and reuse throughout all of the potential updates.
Input:
 matndarray
The matrix to construct a set of reusable objects for performing the updates. mat is assumed to be a symmetric square matrix.
 evd_tolfloat (optional)
A threshold value for setting eigenvalues to zero.
Output:
 U, endarrays
The components of the compact eigenvalue decomposition of mat such that U@diag(s)@U.conj().T= mat e in this case is a 1D array of the nonzero eigenvalues.
 projUndarray
A projector onto the complement of the column space of U Corresponds to (IU@U.T)
 pygsti.algorithms.symmetric_low_rank_spectrum_update(update, orig_e, U, proj_U, force_rank_increase=False)
This function performs a lowrank update to the spectrum of a matrix. It takes as input a symmetric update of the form: A@A.T, in other words a symmetric rankdecomposition of the update matrix. Since the update is symmetric we only pass as input one half (i.e. we only need A, since A.T in numpy is treated simply as a different view of A). We also pass in the original spectrum as well as a projector onto the complement of the column space of the original matrix’s eigenvector matrix.
input:
 updatendarray
symmetric lowrank update to perform. This is the first half the symmetric rank decomposition s.t. update@update.T= the full update matrix.
 orig_endarray
Spectrum of the original matrix. This is a 1D array.
 proj_Undarray
Projector onto the complement of the column space of the original matrix’s eigenvectors.
 force_rank_increasebool
A flag to indicate whether we are looking to force a rank increase. If so, then after the rrqr calculation we can check the rank of the projection of the update onto the complement of the column space of the base matrix and abort early if that is zero.
 pygsti.algorithms.minamide_style_inverse_trace(update, orig_e, U, proj_U, force_rank_increase=False)
This function performs a lowrank update to the components of the psuedo inverse of a matrix relevant to the calculation of that matrix’s updated trace. It takes as input a symmetric update of the form: A@A.T, in other words a symmetric rankdecomposition of the update matrix. Since the update is symmetric we only pass as input one half (i.e. we only need A, since A.T in numpy is treated simply as a different view of A). We also pass in the original spectrum as well as a projector onto the complement of the column space of the original matrix’s eigenvector matrix.
Based on an update formula for psuedoinverses by minamide combined with a result on updating compact SVDs by M. Brand.
input:
 updatendarray
symmetric lowrank update to perform. This is the first half the symmetric rank decomposition s.t. update@update.T= the full update matrix.
 orig_endarray
Spectrum of the original matrix. This is a 1D array.
 proj_Undarray
Projector onto the complement of the column space of the original matrix’s eigenvectors.
 updated_tracefloat
Value of the trace of the updated psuedoinverse matrix.
 updated_rankint
total rank of the updated matrix.
 rank_increase_flagbool
a flag that is returned to indicate is a candidate germ failed to amplify additional parameters. This indicates things short circuited and so the scoring function should skip this germ.
 pygsti.algorithms.find_germs_breadthfirst_greedy(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, num_nongauge_params=None, float_type=_np.cdouble, mode='allJac', force_rank_increase=False, save_cevd_cache_filename=None, load_cevd_cache_filename=None, file_compression=False, evd_tol=1e10, initial_germ_set_test=True)
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_listModel or list
The model or list of Models to select germs for.
 germs_listlist of Circuit
The list of germs to contruct a germ set from.
 randomizebool, 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_strengthfloat, optional
The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. num_copiesint, 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.
 seedint, optional
Seed for generating random unitary perturbations to models.
 op_penaltyfloat, 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)
. tolfloat, optional
Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate. thresholdfloat, optional
Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
 checkbool, optional
Whether to perform internal checks (will slow down run time substantially).
 forcestr or list of Circuits, optional (default ‘singletons’)
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. If none then not circuits are forcibly included.
 pretestboolean, optional
Whether germ list should be initially checked for completeness.
 mem_limitint, optional
A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
 profilerProfiler, optional
A profiler object used for to track timing and memory usage.
 verbosityint, optional
Level of detail printed to stdout.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typenumpy dtype object, optional
Use an alternative data type for the values of the numpy arrays generated.
 force_rank_increasebool, optional
Whether to force the greedy iteration to select a new germ that increases the rank of the jacobian at each iteration (this may result in choosing a germ that is suboptimal with respect to the chosen score function). Also results in pruning in subsequent optimization iterations. Defaults to False.
 evd_tolfloat, optional
A threshold value to use when taking eigenvalue decompositions/SVDs such that values below this are set to zero.
 initial_germ_set_testbool, optional (default True)
A flag indicating whether or not to check the initially constructed germ set, which is either the list of singleton germs (if force=’singletons’), a user specified list of circuits is such a list if passed in for the value of force, or a greedily selected initial germ if force=None. This can be skipped to save computational time (the test can be expensive) if the user has reason to believe this initial set won’t be AC. Most of the time this initial set won’t be.
Returns
 list
A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.compute_composite_germ_set_score_compactevd(current_update_cache, germ_update, score_fn='all', threshold_ac=1000000.0, init_n=1, model=None, partial_germs_list=None, eps=None, num_germs=None, op_penalty=0.0, l1_penalty=0.0, num_nongauge_params=None, num_params=None, force_rank_increase=False, germ_lengths=None, float_type=_np.cdouble)
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
 current_update_cachetuple
A tuple whose elements are the components of the current update cache for performing a lowrank update. Elements are (e, U , projU).
 germ_updatendarray
A numpy array corresponding to one half of the lowrank symmetric update to to perform.
 score_fncallable
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_acfloat, optional
Value which the score (before penalties are applied) must be lower than for the germ set to be considered AC.
 init_nint
The number of largest eigenvalues to begin with checking.
 modelModel, optional
The model against which the germ set is to be scored. Not needed if partial_deriv_dagger_deriv is provided.
 partial_germs_listlist 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. epsfloat, 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. op_penaltyfloat, optional
Coefficient for a penalty linear in the sum of the germ lengths.
 germ_lengthsnumpy.array, optional
The length of each germ. Not needed if op_penalty is
0.0
or partial_germs_list is provided. l1_penaltyfloat, optional
Coefficient for a penalty linear in the number of germs.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 num_paramsint
Total number of model parameters.
 force_rank_increasebool, optional
Whether to force the greedy iteration to select a new germ that increases the rank of the jacobian at each iteration (this may result in choosing a germ that is suboptimal with respect to the chosen score function). Also results in pruning in subsequent optimization iterations. Defaults to False.
Returns
 CompositeScore
The score for the germ set indicating how many parameters it amplifies and its numerical score restricted to those parameters.
 pygsti.algorithms.compute_composite_germ_set_score_low_rank_trace(current_update_cache, germ_update, score_fn='all', threshold_ac=1000000.0, init_n=1, model=None, partial_germs_list=None, eps=None, num_germs=None, op_penalty=0.0, l1_penalty=0.0, num_nongauge_params=None, num_params=None, force_rank_increase=False, germ_lengths=None, float_type=_np.cdouble)
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
 current_update_cachetuple
A tuple whose elements are the components of the current update cache for performing a lowrank update. Elements are (e, U , projU).
 germ_updatendarray
A numpy array corresponding to one half of the lowrank symmetric update to to perform.
 score_fncallable
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_acfloat, optional
Value which the score (before penalties are applied) must be lower than for the germ set to be considered AC.
 init_nint
The number of largest eigenvalues to begin with checking.
 modelModel, optional
The model against which the germ set is to be scored. Not needed if partial_deriv_dagger_deriv is provided.
 partial_germs_listlist 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. epsfloat, 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. op_penaltyfloat, optional
Coefficient for a penalty linear in the sum of the germ lengths.
 germ_lengthsnumpy.array, optional
The length of each germ. Not needed if op_penalty is
0.0
or partial_germs_list is provided. l1_penaltyfloat, optional
Coefficient for a penalty linear in the number of germs.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 num_paramsint
Total number of model parameters.
 force_rank_increasebool, optional
Whether to force the greedy iteration to select a new germ that increases the rank of the jacobian at each iteration (this may result in choosing a germ that is suboptimal with respect to the chosen score function). Also results in pruning in subsequent optimization iterations. Defaults to False.
Returns
 CompositeScore
The score for the germ set indicating how many parameters it amplifies and its numerical score restricted to those parameters.
 rank_increase_flagbool
A flag that indicates whether the candidate update germ increases the rank of the overall Jacobian.
 pygsti.algorithms.fast_kron(a, b)
 pygsti.algorithms.stable_pinv(mat)
 pygsti.algorithms.germ_set_spanning_vectors(target_model, germ_list, assume_real=False, float_type=_np.cdouble, num_nongauge_params=None, tol=1e06, pretest=False, evd_tol=1e10, verbosity=1, threshold=1000000.0, mode='greedy', update_cache_low_rank=False, final_test=True, comm=None)
Parameters
 target_modelModel 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).
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 float_typenumpy dtype object, optional
Numpy data type to use for floating point arrays.
 tolfloat, optional
Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate. pretestboolean, optional
Whether germ list should be initially checked for completeness.
 evd_tolfloat, optional
A threshold value to use when taking eigenvalue decompositions/SVDs such that values below this are set to zero.
 verbosityint, optional
Level of detail printed to stdout.
 thresholdfloat, optional
Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC
 modestring, optional (default ‘greedy)’
An optional mode string for specifying the search heuristic used for constructing the germ vector set. If ‘greedy’ we use a greedy search algorithm based on lowrank updates. If ‘RRQR’ we use a heuristic for the subset selection problem due to Golub, Klema and Stewart (1976), detailed in chapter 12 of the book “Matrix Computations” by Golub and Van Loan.
 update_cache_low_rankbool, optional (default = False)
A flag indicating whether the psuedoinverses in the update cache used as part of the lowrank update routine should themselves be updated between iterations using lowrank updates. Setting this to True gives a notable performance boost, but I have found that this can also give rise to numerical stability issues, so caveat emptor. Only set to True if you’re sure of what you’re doing.
 final_testbool, optional (default True)
A flag indicating whether a final test should be performed to validate the final score of the germvector set found using either the greedy or RRQR based search heuristics. Can be useful in conjunction with the use of update_cache_low_rank, as this can help detect numerical stability problems in the use of lowrank updates for cache construction.
 commmpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation across multiple processors.
Returns
 germ_vec_dictdict
A dictionary whose keys are germs and whose elements are numpy arrays whose columns correspond to the amplified directions in parameter space identified for that germ such that when combined with the amplified directions selected for each other germ in the set we maintain amplificational completeness.
 currentDDDndarray
The J^T@J matrix for subset of twirled derivative columns selected accross all of the germs. The spectrum of this matrix provides information about the amplificational properties of the reduced vector set.
 pygsti.algorithms.compute_composite_vector_set_score(current_update_cache, vector_update, model=None, num_nongauge_params=None, force_rank_increase=False, float_type=_np.cdouble)
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
 current_update_cachetuple
A tuple whose elements are the components of the current update cache for performing a lowrank update. Elements are (pinv(A), proj_A).
 vector_updatendarray
A numpy array corresponding to one half of the lowrank symmetric update to to perform.
 modelModel, optional
The model against which the germ set is to be scored. Not needed if partial_deriv_dagger_deriv is provided.
 num_nongauge_paramsint, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
 force_rank_increasebool, optional
Whether to force the greedy iteration to select a new germ that increases the rank of the jacobian at each iteration (this may result in choosing a germ that is suboptimal with respect to the chosen score function). Also results in pruning in subsequent optimization iterations. Defaults to False.
Returns
 CompositeScore
The score for the germ set indicating how many parameters it amplifies and its numerical score restricted to those parameters.
 rank_increase_flagbool
A flag that indicates whether the candidate update germ increases the rank of the overall Jacobian.
 pygsti.algorithms.construct_update_cache_rank_one(mat, evd_tol=1e10, prev_update_cache=None, rank_one_update=None)
Calculates the parts of the psuedoinverse update loop algorithm that we can precompute and reuse throughout all of the potential updates.
This is based on a result from Carl Meyer in Generalized Inversion of Modified Matrices, and summarized in 3.2.7 of the matrix cookbook.
quantities we can precompute are (for initial matrix A): pinv(A) IA@pinv(A)
Input:
 matndarray
The matrix to construct a set of reusable objects for performing the updates. mat is assumed to be a symmetric square matrix.
 evd_tolfloat (optional)
A threshold value for setting eigenvalues to zero.
Output:
 pinv_Andarray
The psuedoinverse of the input matrix
 proj_Andarray
A projectors onto the orthogonal complement of the column space of the input matrix.
 pinv_A_tracefloat
The trace of pinv_A.
 rankint
The current rank of A/pinv_A
 pygsti.algorithms.rank_one_inverse_trace_update(vector_update, pinv_A, proj_A, pinv_A_trace, force_rank_increase=False)
Helper function for calculating rankone updates to the trace of the psuedoinverse. Takes as input a rankone update, the psuedoinverse of the matrix we’re updating, the projector onto the column space for the matrix whose psuedoinverse we are updating and a flag for specifying if we’re requiring the rank to increase.
 pygsti.algorithms.rank_one_psuedoinverse_update(vector_update, pinv_A, proj_A, force_rank_increase=False)
Helper function for calculating rankone psuedoinverse updates. Takes as input a rankone update, the psuedoinverse of the matrix we’re updating, the projector onto the column space for the matrix whose psuedoinverse we are updating and a flag for specifying if we’re requiring the rank to increase.
 pygsti.algorithms.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_labelslist or tuple
the operation labels to use in Gram matrix basis strings
 datasetDataSet
the dataset to use when constructing the Gram matrix
 max_lengthint, 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.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
 datasetDataSet
the dataset to use when constructing the Gram matrix
 target_modelModel
A model used to make sense of circuits and for the construction of a theoretical gram matrix and spectrum.
 max_basis_string_lengthint, 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.create_mirror_circuit(circ, pspec, circ_type='clifford+zxzxz')
circ_type : clifford+zxzxz, cz(theta)+zxzxz