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 dummy profiler that doesn't do anything. 

A basis that is included within and integrated into pyGSTi. 

Class responsible for logging things to stdout or a file. 

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

A unmutable list (a tuple) of 

Describes available resources and how they should be allocated. 

A LevenbergMarquardt optimizer customized for GSTlike problems. 

An optimizer. Optimizes an objective function. 

A real operation matrix parameterized only by its eigenvalues. 

TODO: docstring 

Element of 
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. 









Contract the surface preparation and measurement operations of 

Performs Linearinversion Gate Set Tomography on the dataset. 













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

Performs core Gate Set Tomography function of model optimization. 

Performs core Gate Set Tomography function of model optimization. 

Performs Iterative Gate Set Tomography on the dataset. 

Runs the core modeloptimization step within a GST routine by optimizing 

Runs the core modeloptimization step for models using the 

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

Remove duplicates from the a list and return the result. 

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

Random selection from itertools.combinations(indices_tuple, r) 

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

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

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

Tests a set of global or pergerm fiducial pairs. 



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

Generate prep and measurement fiducials for a given target model. 

Implements logical xor function for arbitrary number of inputs. 

Make a list of matrices for the model preparation operations. 

Make a list of matrices for the model measurement operations. 

Compute a composite score for a fiducial list. 

Tests a prep or measure fiducial list for informational completeness. 

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

Find a locally optimal subset of the fiducials in fid_list. 

Use GRASP to find a highperforming set of fiducials. 

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

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

Creates the objective function and jacobian (if available) 

Helper function  same as that in core.py. 

Helper function  same as that in core.py. 

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

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

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

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

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

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

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

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

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

Calculate the positive squares of the germ Jacobians. 

Calculate the positive squares of the germ Jacobian. 

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

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

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

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

Return the number of nongauge, nonSPAM parameters in model. 

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

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

Compute the "Twirled Derivative" of a circuit. 

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

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

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

Greedy germ selection algorithm starting with 0 germs. 

Greedy algorithm starting with 0 germs. 

Find a locally optimal subset of the germs in germs_list. 

Score a germ set against a collection of models. 

Use GRASP to find a highperforming germ set. 

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

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

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

circ_type : clifford+zxzxz, cz(theta)+zxzxz 
Attributes¶
 pygsti.algorithms.compile_clifford(s, p, pspec=None, absolute_compilation=None, paulieq_compilation=None, qubit_labels=None, iterations=20, algorithm='ROGGE', aargs=[], costfunction='2QGC:10:depth:1', prefixpaulis=False, paulirandomize=False, rand_state=None)¶
Compiles an nqubit Clifford gate into a circuit over a given processor specification.
Compiles an nqubit Clifford gate, described by the symplectic matrix s and vector p, into a circuit over the gates given by a processor specification or a standard processor. Clifford gates/circuits can be converted to, or sampled in, the symplectic representation using the functions in :module:`pygsti.tools.symplectic`.
The circuit created by this function will be over the gates in the given processor spec, respecting its connectivity, when a QubitProcessorSpec object is provided. Otherwise, it is over a canonical processor containing alltoall CNOTs, Hadamard, Phase, 3 products of Hadamard and Phase, and the Pauli gates.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the Clifford is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input Clifford needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – Some of the allowed algorithms are randomized. This is the number of iterations used in algorithm if it is a randomized algorithm specified. If any randomized algorithms are specified, the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
algorithm (str, optional) –
Specifies the algorithm used for the core part of the compilation: finding a circuit that is a Clifford with s the symplectic matrix in its symplectic representation (a circuit that implements that desired Clifford up to Pauli operators). The allowed values of this are:
 ’BGGE’: A basic, deterministic global Gaussian elimination algorithm. Circuits obtained from this algorithm
contain, in expectation, O(n^2) 2qubit gates. Although the returned circuit will respect device connectivity, this algorithm does not take connectivity into account in an intelligient way. More details on this algorithm are given in compile_symplectic_with_ordered_global_gaussian_elimination(); it is the algorithm described in that docstring but with the qubit ordering fixed to the order in the input s.
 ’ROGGE’: A randomized elimination order global Gaussian elimination algorithm. This is the same algorithm as
’BGGE’ except that the order that the qubits are eliminated in is randomized. This results in significantly lowercost circuits than the ‘BGGE’ method (given sufficiently many iterations). More details are given in the compile_symplectic_with_random_ordered_global_gaussian_elimination() docstring.
’iAGvGE’: Our improved version of the AaraonsonGottesman method for compiling a Clifford circuit, which uses 3 CNOT circuits and 3 1Qgate layers (rather than the 5 CNOT circuit used in the algorithm of AG in Phys. Rev. A 70 052328 (2004)), with the CNOT circuits compiled using Gaussian elimination. Note that this algorithm appears to perform substantially worse than ‘ROGGE’, even though with an upgraded CNOT compiler it is asymptotically optimal (unlike any of the GGE methods). Also, note that this algorithm is randomized: there are many possible CNOT circuits (with nonequivalent action, individually) for the 2 of the 3 CNOT stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization used in the stabilizer state/measurement compilers.
aargs (list, optional) – If the algorithm can take optional arguments, not already specified as separate arguments above, then this list is passed to the compile_symplectic algorithm as its final arguments.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
prefixpaulis (bool, optional) – A Pauli layer is needed to compile the correct Clifford (and not just the correct Clifford up to Paulis). When prefixpaulis = True this Pauli layer is placed at the beginning of the circuit; when False, it is placed at the end. Note that the required Pauli layer depends on whether we prefix or postfix it to the main symplecticgenerating circuit.
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this Clifford circuit. This can be useful for preventing coherent addition of errors in the circuit.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit implementing the input Clifford gate/circuit.
 pygsti.algorithms.compile_stabilizer_state(s, p, pspec, absolute_compilation, paulieq_compilation, qubit_labels=None, iterations=20, paulirandomize=False, algorithm='COiCAGE', aargs=[], costfunction='2QGC:10:depth:1', rand_state=None)¶
Generates a circuit to create the stabilizer state from the standard input state 0,0,0,…>.
The stabilizer state is specified by s and p. The circuit returned is over the gates in the processor spec. See :function:`compile_stabilizer_state()` for the inverse of this.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers. This is a symplectic matrix representing any Clifford gate that, when acting on 0,0,0,…>, generates the desired stabilizer state. So s is not unique.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate. This phase vector matrix should, together with s, represent any Clifford gate that, when acting on 0,0,0,…>, generates the desired stabilizer state. So p is not unique.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
pspec –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the stabilizer state is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – This algorithm is randomized. This is the number of iterations used in the algorithm. the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this circuit. This can be useful for preventing coherent addition of errors in the circuit.
algorithm (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. algorithm specifies the CNOTcompilation algorithm to use. The allowe values are all those algorithms that permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances.
aargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that creates the specified stabilizer state from 0,0,0,…>
 pygsti.algorithms.compile_stabilizer_measurement(s, p, pspec, absolute_compilation, paulieq_compilation, qubit_labels=None, iterations=20, paulirandomize=False, algorithm='COCAGE', aargs=[], costfunction='2QGC:10:depth:1', rand_state=None)¶
Generates a circuit to map the stabilizer state to the standard state 0,0,0,…>.
The stabilizer state is specified by s and p. The circuit returned is over the gates in the processor spec pspec. See :function”compile_stabilizer_state() for the inverse of this. So, this circuit followed by a Zbasis measurement can be used to simulate a projection onto the stabilizer state C0,0,0,…> where C is the Clifford represented by s and p.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers. This is a symplectic matrix representing any Clifford gate that, when acting on 0,0,0,…>, generates the stabilizer state that we need to map to 0,0,0,…>. So s is not unique.
p (array over [0,1]) – A length2n vector over [0,1,2,3] that, together with s, defines a valid nqubit Clifford gate. This phase vector matrix should, together with s, represent any Clifford gate that, when acting on 0,0,0,…>, generates the stabilizer state that we need to map to 0,0,0,…>. So p is not unique.
pspec (QubitProcessorSpec, optional) –
An nbarqubit QubitProcessorSpec object that encodes the device that the stabilizer is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation. In most circumstances, the output will be more useful if a QubitProcessorSpec is provided.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the stabilizer is over. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input (s,p) needs to be ``padded’’ to be the identity on those qubits).
The ordering of the indices in (s,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
absolute_compilation (CompilationRules) – Rules for exactly (absolutely) compiling the “native” gates of pspec into clifford gates.
paulieq_compilation (CompilationRules) – Rules for compiling, up to singlequbit Pauli gates, the “native” gates of pspec into clifford gates.
qubit_labels (List, optional) – Required if the stabilizer state is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
iterations (int, optional) – This algorithm is randomized. This is the number of iterations used in the algorithm. the time taken by this function increases linearly with iterations. Increasing iterations will often improve the obtained compilation (the “cost” of the obtained circuit, as specified by costfunction may decrease towards some asymptotic value).
paulirandomize (bool, optional) – If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between every layer in the circuit. These Paulis are then compiled into the gates in pspec, if pspec is provided. That is, this Pauliframerandomizes / Paulitwirls the internal layers of this circuit. This can be useful for preventing coherent addition of errors in the circuit.
algorithm (str, optional) – Our algorithm finds a circuit consisting of 1Qgates  a CNOT circuit  1Qgates. The CNOT circuit is found using Gaussian elimination, and it can then be recompiled using a CNOTcircuit compiler. algorithm specifies the CNOTcompilation algorithm to use. The allowe values are all those algorithms that permisable in the compile_cnot_circuit() function. See the docstring of that function for more information. The default is likely to be the best out of the inbuilt CNOT compilers under most circumstances.
aargs (list, optional) – If the CNOT compilation algorithm can take optional arguments, these are specified here. This is passed to compile_cnot_circuit() as aarg.
costfunction (function or string, optional) –
If a function, it is a function that takes a circuit and pspec as the first and second inputs and returns a ‘cost’ (a float) for the circuit. The circuit input to this function will be over the gates in pspec, if a pspec has been provided, and as described above if not. This costfunction is used to decide between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If a string it must be one of:
’2QGC’ : the cost of the circuit is the number of 2qubit gates it contains.
’depth’ : the cost of the circuit is the depth of the circuit.
 ’2QGC:x:depth:y’the cost of the circuit is x * the number of 2qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that maps the specified stabilizer state to 0,0,0,…>
 pygsti.algorithms.compile_cnot_circuit(s, pspec, compilation, qubit_labels=None, algorithm='COiCAGE', compile_to_native=False, check=True, aargs=[], rand_state=None)¶
A CNOT circuit compiler.
Takes an arbitrary CNOT circuit, input as a symplectic matrix s that corresponds to the matrix portion of the symplectic representation of this Clifford circuit, and decomposes it into a sequences of gates from the processor spec pspec.
 Parameters
s (array over [0,1]) – An (2n X 2n) symplectic matrix of 0s and 1s integers that represents a Clifford circuit: so it must be blockdiagonal. Specifically, it has the form s = ((A,0),(0,B)) where B is the inverse transpose of A (over [0,1] mod 2).
pspec (QubitProcessorSpec) –
An nbarqubit QubitProcessorSpec object that encodes the device that s is being compiled for, where nbar >= n. If this is specified, the output circuit is over the gates available in this device. If this is None, the output circuit is over the “canonical” processor of CNOT gates between all qubits, consisting of “H”, “HP”, “PH”, “HPH”, “I”, “X”, “Y” and “Z”, which is the set used internally for the compilation.
If nbar > n it is necessary to provide qubit_labels, that specifies which of the qubits in pspec the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of whether that means an overhead is required to avoid using gates that act on those qubits. If these additional qubits should be used, then the input s needs to be ``padded’’ to be the identity on those qubits).
The indexing s is assumed to be the same as that in the list pspec.qubit_labels, unless qubit_labels is specified. Then, the ordering is taken w.r.t the ordering of the list qubit_labels.
compilation (CompilationRules) – Rules for compiling the “native” gates of pspec into clifford gates, used if compile_to_native==True.
qubit_labels (list, optional) – Required if the Clifford to compile is over less qubits than pspec. In this case this is a list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels. The ordering of the qubits in (s,`p`) is taken w.r.t the ordering of this list.
algorithm (str, optional) –
The algorithm to use. The optionas are:
 ’BGE’A basic Gaussian elimination algorithm, that uses CNOT to perform rowreduction on the upper
LHS (or lower RHS) of s. This algorithm does not take device connectivity into account.
 ’OCAGE’Userordered connectivityadjusted Gaussian elimination. The qubits are eliminated in the
specified order; the first element of arrgs must be a list specify this order. The algorithm is also “connectivityadjusted” in the sense that it uses the connectivity graph (in pspec.qubit_graph) to try and avoid using CNOTs between unconnected pairs whenever possible, and to decide the order of various operations.
 ’OiCAGE’The same as ‘OCAGE’ except that it has some improvements, and it requires connectivity
graph of the remaining qubits, after each qubit has been ‘eliminated’, to be connected. In the current format this algorithm is only slightly betterperforming than ‘OCAGE’, and only on average. (This algorithm will possibly be improved in the future, whereas ‘OCAGE’ will remain asis for reproducability of previously obtained results.)
 ’ROCAGE’: Same as ‘OCAGE’ except that the elimination order is chosen at random, rather than user
specified.
 ’COCAGE’, ‘COiCAGE’The same as ‘OCAGE’ and ‘OiCAGE’, respectively, except that the elimination order
is fixed to eliminate qubits with the worse connectivity before those with better connectivity.
compile_to_native (bool, optional) – Whether the circuit should be given in terms of the native gates of the processor defined in pspec.
check (bool, optional) – Whether to check the output is correct.
aargs (list, optional) – A list of arguments handed to the CNOT compiler algorithm. For some choices of algorithm (e.g., ‘OCAGE’) this list must not be empty. For algorithms where there are X nonoptional arguements after s and pspec these are specified as the first X arguments of aargs. The remaining elements in aargs, if any, are handed to the algorithm as the arguments after the optional qubit_labels and check arguments (the first of which is set by the input qubit_labels in this function).
rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG
 Returns
Circuit – A circuit that implements the same unitary as the CNOT circuit represented by s.
 pygsti.algorithms.contract(model, to_what, dataset=None, maxiter=1000000, tol=0.01, use_direct_cp=True, method='NelderMead', verbosity=0)¶
Contract a Model to a specified space.
All contraction operations except ‘vSPAM’ operate entirely on the gate matrices and leave state preparations and measurments alone, while ‘vSPAM’ operations only on SPAM.
 Parameters
model (Model) – The model to contract
to_what (string) –
Specifies which space is the model is contracted to. Allowed values are:
’TP’ – All gates are manifestly tracepreserving maps.
’CP’ – All gates are manifestly completelypositive maps.
’CPTP’ – All gates are manifestly completelypositive and tracepreserving maps.
’XP’ – All gates are manifestly “experimentallypositive” maps.
’XPTP’ – All gates are manifestly “experimentallypositive” and tracepreserving maps.
’vSPAM’ – state preparation and measurement operations are valid.
’nothing’ – no contraction is performed.
dataset (DataSet, optional) – Dataset to use to determine whether a model is in the “experimentallypositive” (XP) space. Required only when contracting to XP or XPTP.
maxiter (int, optional) – Maximum number of iterations for iterative contraction routines.
tol (float, optional) – Tolerance for iterative contraction routines.
use_direct_cp (bool, optional) – Whether to use a faster directcontraction method for CP contraction. This method essentially transforms to the Choi matrix, truncates any negative eigenvalues to zero, then transforms back to a operation matrix.
method (string, optional) – The method used when contracting to XP and nondirectly to CP (i.e. use_direct_cp == False).
verbosity (int, optional) – How much detail to send to stdout.
 Returns
Model – The contracted model
 pygsti.algorithms._contract_to_xp(model, dataset, verbosity, method='NelderMead', maxiter=100000, tol=1e10)¶
 pygsti.algorithms._contract_to_cp(model, verbosity, method='NelderMead', maxiter=100000, tol=0.01)¶
 pygsti.algorithms._contract_to_cp_direct(model, verbosity, tp_also=False, maxiter=100000, tol=1e08)¶
 pygsti.algorithms._contract_to_tp(model, verbosity)¶
 pygsti.algorithms._contract_to_valid_spam(model, verbosity=0)¶
Contract the surface preparation and measurement operations of a Model to the space of valid quantum operations.
 Parameters
model (Model) – The model to contract
verbosity (int) – How much detail to send to stdout.
 Returns
Model – The contracted model
 class pygsti.algorithms._DummyProfiler¶
Bases:
object
A dummy profiler that doesn’t do anything.
A class which implements the same interface as Profiler but which doesn’t actually do any profiling (consists of stub functions).
 add_time(self, name, start_time, prefix=0)¶
Stub function that does nothing
 Parameters
name (string) – The name of the timer to add elapsed time into (if the name doesn’t exist, one is created and initialized to the elapsed time).
start_time (float) – The starting time used to compute the elapsed, i.e. the value time.time()start_time, which is added to the named timer.
prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.
 Returns
None
 add_count(self, name, inc=1, prefix=0)¶
Stub function that does nothing
 Parameters
name (string) – The name of the counter to add val into (if the name doesn’t exist, one is created and initialized to val).
inc (int, optional) – The increment (the value to add to the counter).
prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.
 Returns
None
 memory_check(self, name, printme=None, prefix=0)¶
Stub function that does nothing
 Parameters
name (string) – The name of the memory checkpoint. (Later, memory information can be organized by checkpoint name.)
printme (bool, optional) – Whether or not to print the memory usage during this function call (if None, the default, then the value of default_print_memcheck specified during Profiler construction is used).
prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.
 Returns
None
 class pygsti.algorithms.BuiltinBasis(name, dim_or_statespace, sparse=False)¶
Bases:
LazyBasis
A basis that is included within and integrated into pyGSTi.
Such bases may, in most cases be represented merely by its name. (In actuality, a dimension is also required, but this is often able to be inferred from context.)
 Parameters
name ({"pp", "gm", "std", "qt", "id", "cl", "sv"}) – Name of the basis to be created.
dim_or_statespace (int or StateSpace) – The dimension of the basis to be created or the state space for which a basis should be created. Note that when this is an integer it is the dimension of the vectors, which correspond to flattened elements in simple cases. Thus, a 1qubit basis would have dimension 2 in the statevector (name=”sv”) case and dimension 4 when constructing a densitymatrix basis (e.g. name=”pp”).
sparse (bool, optional) – Whether basis elements should be stored as SciPy CSR sparse matrices or dense numpy arrays (the default).
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 __hash__(self)¶
Return hash(self).
 _lazy_build_elements(self)¶
 _lazy_build_labels(self)¶
 _copy_with_toggled_sparsity(self)¶
 __eq__(self, other)¶
Return self==value.
 class pygsti.algorithms.VerbosityPrinter(verbosity=1, filename=None, comm=None, warnings=True, split=False, clear_file=True)¶
Bases:
object
Class responsible for logging things to stdout or a file.
Controls verbosity and can print progress bars. ex:
>>> VerbosityPrinter(1)
would construct a printer that printed out messages of level one or higher to the screen.
>>> VerbosityPrinter(3, 'output.txt')
would construct a printer that sends verbose output to a text file
The static function
create_printer()
will construct a printer from either an integer or an already existing printer. it is a static method of the VerbosityPrinter class, so it is called like so:>>> VerbosityPrinter.create_printer(2)
or
>>> VerbostityPrinter.create_printer(VerbosityPrinter(3, 'output.txt'))
printer.log('status')
would log ‘status’ if the printers verbosity was one or higher.printer.log('status2', 2)
would log ‘status2’ if the printer’s verbosity was two or higherprinter.error('something terrible happened')
would ALWAYS log ‘something terrible happened’.printer.warning('something worrisome happened')
would log if verbosity was one or higher  the same as a normal status.Both printer.error and printer.warning will prepend ‘ERROR: ‘ or ‘WARNING: ‘ to the message they are given. Optionally, printer.log() can also prepend ‘Status_n’ to the message, where n is the message level.
Logging of progress bars/iterations:
>>> with printer_instance.progress_logging(verbosity): >>> for i, item in enumerate(data): >>> printer.show_progress(i, len(data)) >>> printer.log(...)
will output either a progress bar or iteration statuses depending on the printer’s verbosity
 Parameters
verbosity (int) – How verbose the printer should be.
filename (str, optional) – Where to put output (If none, output goes to screen)
comm (mpi4py.MPI.Comm or ResourceAllocation, optional) – Restricts output if the program is running in parallel (By default, if the rank is 0, output is sent to screen, and otherwise sent to commfiles 1, 2, …
warnings (bool, optional) – Whether or not to print warnings
split (bool, optional) – Whether to split output between stdout and stderr as appropriate, or to combine the streams so everything is sent to stdout.
clear_file (bool, optional) – Whether or not filename should be cleared (overwritten) or simply appended to.
 _comm_path¶
relative path where comm files (outputs of nonroot ranks) are stored.
 Type
str
 _comm_file_name¶
root filename for comm files (outputs of nonroot ranks).
 Type
str
 _comm_file_ext¶
filename extension for comm files (outputs of nonroot ranks).
 Type
str
 _comm_path =¶
 _comm_file_name =¶
 _comm_file_ext = .txt¶
 _create_file(self, filename)¶
 _get_comm_file(self, comm_id)¶
 clone(self)¶
Instead of deepcopy, initialize a new printer object and feed it some select deepcopied members
 Returns
VerbosityPrinter
 static create_printer(verbosity, comm=None)¶
Function for converting between interfaces
 Parameters
verbosity (int or VerbosityPrinter object, required:) – object to build a printer from
comm (mpi4py.MPI.Comm object, optional) – Comm object to build printers with. !Will override!
 Returns
VerbosityPrinter – The printer object, constructed from either an integer or another printer
 __add__(self, other)¶
Increase the verbosity of a VerbosityPrinter
 __sub__(self, other)¶
Decrease the verbosity of a VerbosityPrinter
 __getstate__(self)¶
 __setstate__(self, state_dict)¶
 _append_to(self, filename, message)¶
 _put(self, message, flush=True, stderr=False)¶
 _record(self, typ, level, message)¶
 error(self, message)¶
Log an error to the screen/file
 Parameters
message (str) – the error message
 Returns
None
 warning(self, message)¶
Log a warning to the screen/file if verbosity > 1
 Parameters
message (str) – the warning message
 Returns
None
 log(self, message, message_level=None, indent_char=' ', show_statustype=False, do_indent=True, indent_offset=0, end='\n', flush=True)¶
Log a status message to screen/file.
Determines whether the message should be printed based on current verbosity setting, then sends the message to the appropriate output
 Parameters
message (str) – the message to print (or log)
message_level (int, optional) – the minimum verbosity level at which this level is printed.
indent_char (str, optional) – what constitutes an “indent” (messages at higher levels are indented more when do_indent=True).
show_statustype (bool, optional) – if True, prepend lines with “Status Level X” indicating the message_level.
do_indent (bool, optional) – whether messages at higher message levels should be indented. Note that if this is False it may be helpful to set show_statustype=True.
indent_offset (int, optional) – an additional number of indentations to add, on top of any due to the message level.
end (str, optional) – the character (or string) to end message lines with.
flush (bool, optional) – whether stdout should be flushed right after this message is printed (this avoids delays in onscreen output due to buffering).
 Returns
None
 _progress_bar(self, iteration, total, bar_length, num_decimals, fill_char, empty_char, prefix, suffix, indent)¶
 _verbose_iteration(self, iteration, total, prefix, suffix, verbose_messages, indent, end)¶
 __str__(self)¶
Return str(self).
 verbosity_env(self, level)¶
Create a temporary environment with a different verbosity level.
This is context manager, controlled using Python’s with statement:
>>> with printer.verbosity_env(2): printer.log('Message1') # printed at verbosity level 2 printer.log('Message2') # printed at verbosity level 2
 Parameters
level (int) – the verbosity level of the environment.
 progress_logging(self, message_level=1)¶
Context manager for logging progress bars/iterations.
(The printer will return to its normal, unrestricted state when the progress logging has finished)
 Parameters
message_level (int, optional) – progress messages will not be shown until the verbosity level reaches message_level.
 show_progress(self, iteration, total, bar_length=50, num_decimals=2, fill_char='#', empty_char='', prefix='Progress:', suffix='', verbose_messages=[], indent_char=' ', end='\n')¶
Displays a progress message (to be used within a progress_logging block).
 Parameters
iteration (int) – the 0based current iteration – the interation number this message is for.
total (int) – the total number of iterations expected.
bar_length (int, optional) – the length, in characters, of a textformat progress bar (only used when the verbosity level is exactly equal to the progress_logging message level.
num_decimals (int, optional) – number of places after the decimal point that are displayed in progress bar’s percentage complete.
fill_char (str, optional) – replaces ‘#’ as the barfilling character
empty_char (str, optional) – replaces ‘’ as the emptybar character
prefix (str, optional) – message in front of the bar
suffix (str, optional) – message after the bar
verbose_messages (list, optional) – A list of strings to display after an initial “Iter X of Y” line when the verbosity level is higher than the progress_logging message level and so more verbose messages are shown (and a progress bar is not). The elements of verbose_messages will occur, one per line, after the initial “Iter X of Y” line.
indent_char (str, optional) – what constitutes an “indentation”.
end (str, optional) – the character (or string) to end message lines with.
 Returns
None
 _end_progress(self)¶
 start_recording(self)¶
Begins recording the output (to memory).
Begins recording (in memory) a list of (type, verbosityLevel, message) tuples that is returned by the next call to :method:`stop_recording`.
 Returns
None
 is_recording(self)¶
Returns whether this VerbosityPrinter is currently recording.
 Returns
bool
 stop_recording(self)¶
Stops recording and returns recorded output.
Stops a “recording” started by :method:`start_recording` and returns the list of (type, verbosityLevel, message) tuples that have been recorded since then.
 Returns
list
 class pygsti.algorithms.DirectSumBasis(component_bases, name=None, longname=None)¶
Bases:
LazyBasis
A basis that is the direct sum of one or more “component” bases.
Elements of this basis are the union of the basis elements on each component, each embedded into a common blockdiagonal structure where each component occupies its own block. Thus, when there is more than one component, a DirectSumBasis is not a simple basis because the size of its elements is larger than the size of its vector space (which corresponds to just the diagonal blocks of its elements).
 Parameters
component_bases (iterable) – A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to :function:`Basis.cast`, e.g. (‘pp’,4).
name (str, optional) – The name of this basis. If None, the names of the component bases joined with “+” is used.
longname (str, optional) – A longer description of this basis. If None, then a long name is automatically generated.
 vector_elements¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Type
list
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 __hash__(self)¶
Return hash(self).
 _lazy_build_vector_elements(self)¶
 _lazy_build_elements(self)¶
 _lazy_build_labels(self)¶
 _copy_with_toggled_sparsity(self)¶
 __eq__(self, other)¶
Return self==value.
 property vector_elements(self)¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Returns
list
 property to_std_transform_matrix(self)¶
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.
 Returns
numpy array or scipy.sparse.lil_matrix – An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
 property to_elementstd_transform_matrix(self)¶
Get transformation matrix from this basis to the “element space”.
Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space”  that is, vectors in the same standard basis that the elements of this basis are expressed in.
 Returns
numpy array – An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
 create_equivalent(self, builtin_basis_name)¶
Create an equivalent basis with components of type builtin_basis_name.
Create a Basis that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name.
 Parameters
builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.
 Returns
DirectSumBasis
 create_simple_equivalent(self, builtin_basis_name=None)¶
Create a basis of type builtin_basis_name whose elements are compatible with this basis.
Create a simple basis and one without components (e.g. a
TensorProdBasis
, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_nameanalogue of the standard basis that this basis’s elements are expressed in. Parameters
builtin_basis_name (str, optional) – The name of the builtin basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and componentfree version of the same builtinbasis type.
 Returns
Basis
 class pygsti.algorithms._CircuitList(circuits, op_label_aliases=None, circuit_weights=None, name=None)¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
A unmutable list (a tuple) of
Circuit
objects and associated metadata. Parameters
circuits (list) – The list of circuits that constitutes the primary data held by this object.
op_label_aliases (dict, optional) – Dictionary of circuit metadata whose keys are operation label “aliases” and whose values are circuits corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined). e.g. op_label_aliases[‘Gx^3’] = pygsti.obj.Circuit([‘Gx’,’Gx’,’Gx’])
circuit_weights (numpy.ndarray, optional) – If not None, an array of percircuit weights (of length equal to the number of circuits) that are typically used to multiply the counts extracted for each circuit.
name (str, optional) – An optional name for this list, used for status messages.
 classmethod cast(cls, circuits)¶
Convert (if needed) an object into a
CircuitList
. Parameters
circuits (list or CircuitList) – The object to convert.
 Returns
CircuitList
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 __len__(self)¶
 __getitem__(self, index)¶
 __iter__(self)¶
 apply_aliases(self)¶
Applies any operationlabel aliases to this circuit list.
 Returns
list – A list of :class:`Circuit`s.
 truncate(self, circuits_to_keep)¶
Builds a new circuit list containing only a given subset.
This can be safer then just creating a new
CircuitList
because it preserves the aliases, etc., of this list. Parameters
circuits_to_keep (list or set) – The circuits to retain in the returned circuit list.
 Returns
CircuitList
 truncate_to_dataset(self, dataset)¶
Builds a new circuit list containing only those elements in dataset.
 Parameters
dataset (DataSet) – The dataset to check. Aliases are applied to the circuits in this circuit list before they are tested.
 Returns
CircuitList
 __hash__(self)¶
Return hash(self).
 __eq__(self, other)¶
Return self==value.
 __setstate__(self, state_dict)¶
 class pygsti.algorithms._ResourceAllocation(comm=None, mem_limit=None, profiler=None, distribute_method='default', allocated_memory=0)¶
Bases:
object
Describes available resources and how they should be allocated.
This includes the number of processors and amount of memory, as well as a strategy for how computations should be distributed among them.
 Parameters
comm (mpi4py.MPI.Comm, optional) – MPI communicator holding the number of available processors.
mem_limit (int, optional) – A rough perprocessor memory limit in bytes.
profiler (Profiler, optional) – A lightweight profiler object for tracking resource usage.
distribute_method (str, optional) – The name of a distribution strategy.
 classmethod cast(cls, arg)¶
Cast arg to a
ResourceAllocation
object.If arg already is a
ResourceAllocation
instance, it just returned. Otherwise this function attempts to create a new instance from arg. Parameters
arg (ResourceAllocation or dict) – An object that can be cast to a
ResourceAllocation
. Returns
ResourceAllocation
 build_hostcomms(self)¶
 property comm_rank(self)¶
A safe way to get self.comm.rank (0 if self.comm is None)
 property comm_size(self)¶
A safe way to get self.comm.size (1 if self.comm is None)
 property is_host_leader(self)¶
True if this processors is the rank0 “leader” of its host (node). False otherwise.
 host_comm_barrier(self)¶
Calls self.host_comm.barrier() when self.host_comm is not None.
This convenience function provides an oftenused barrier that follows code where a single “leader” processor modifies a memory block shared between all members of self.host_comm, and the other processors must wait until this modification is performed before proceeding with their own computations.
 Returns
None
 copy(self)¶
Copy this object.
 Returns
ResourceAllocation
 reset(self, allocated_memory=0)¶
Resets internal allocation counters to given values (defaults to zero).
 Parameters
allocated_memory (int64) – The value to set the memory allocation counter to.
 Returns
None
 add_tracked_memory(self, num_elements, dtype='d')¶
Adds nelements * itemsize bytes to the total amount of allocated memory being tracked.
If the total (tracked) memory exceeds self.mem_limit a
MemoryError
exception is raised. Parameters
num_elements (int) – The number of elements to track allocation of.
dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.
 Returns
None
 check_can_allocate_memory(self, num_elements, dtype='d')¶
Checks that allocating nelements doesn’t cause the memory limit to be exceeded.
This memory isn’t tracked  it’s just added to the current tracked memory and a
MemoryError
exception is raised if the result exceeds self.mem_limit. Parameters
num_elements (int) – The number of elements to track allocation of.
dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.
 Returns
None
 temporarily_track_memory(self, num_elements, dtype='d')¶
Temporarily adds nelements to tracked memory (a context manager).
A
MemoryError
exception is raised if the tracked memory exceeds self.mem_limit. Parameters
num_elements (int) – The number of elements to track allocation of.
dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.
 Returns
contextmanager
 gather_base(self, result, local, slice_of_global, unit_ralloc=None, all_gather=False)¶
Gather or allgather operation using local arrays and a unit resource allocation.
Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final tobe gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.
all_gather (bool, optional) – Whether the final result should be gathered on all the processors of this
ResourceAllocation
or just the root (rank 0) processor.
 Returns
None
 gather(self, result, local, slice_of_global, unit_ralloc=None)¶
Gather local arrays into a global result array potentially with a unit resource allocation.
Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final tobe gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.
The global array is only gathered on the root (rank 0) processor of this resource allocation.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, only needed on the root (rank 0) processor. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allgather(self, result, local, slice_of_global, unit_ralloc=None)¶
Allgather local arrays into global arrays on each processor, potentially using a unit resource allocation.
Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final tobe gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allreduce_sum(self, result, local, unit_ralloc=None)¶
Sum local arrays on different processors, potentially using a unit resource allocation.
Similar to a normal MPI reduce call (with MPI.SUM type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the sum, only processors with unit_ralloc.rank == 0 contribute to the sum. This handles the case where simply summing the local contributions from all processors would result in overcounting because of multiple processors hold the same logical result (summand).
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being summed. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allreduce_sum_simple(self, local, unit_ralloc=None)¶
A simplified sum over quantities on different processors that doesn’t use shared memory.
The shared memory usage of :method:`allreduce_sum` can be overkill when just summing a single scalar quantity. This method provides a way to easily sum a quantity across all the processors in this
ResourceAllocation
object using a unit resource allocation. Parameters
local (int or float) – The local (perprocessor) value to sum.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local value, so that only the unit_ralloc.rank == 0 processors will contribute to the sum. If None, then it is assumed that each processor computes a logically different local value.
 Returns
float or int – The sum of all local quantities, returned on all the processors.
 allreduce_min(self, result, local, unit_ralloc=None)¶
Take elementwise min of local arrays on different processors, potentially using a unit resource allocation.
Similar to a normal MPI reduce call (with MPI.MIN type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the min operation, only processors with unit_ralloc.rank == 0 contribute.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 allreduce_max(self, result, local, unit_ralloc=None)¶
Take elementwise max of local arrays on different processors, potentially using a unit resource allocation.
Similar to a normal MPI reduce call (with MPI.MAX type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the max operation, only processors with unit_ralloc.rank == 0 contribute.
 Parameters
result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intrahost communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.local (numpy.ndarray) – The locally computed quantity. This can be a sharedmemory array, but need not be.
unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.
 Returns
None
 bcast(self, value, root=0)¶
Broadcasts a value from the root processor/host to the others in this resource allocation.
This is similar to a usual MPI broadcast, except it takes advantage of shared memory when it is available. When shared memory is being used, i.e. when this
ResourceAllocation
object has a nontrivial interhost comm, then this routine places value in a shared memory buffer and uses the resource allocation’s interhost communicator to broadcast the result from the root host to all the other hosts using all the processor on the root host in parallel (all processors with the same intrahost rank participate in a MPI broadcast). Parameters
value (numpy.ndarray) – The value to broadcast. May be shared memory but doesn’t need to be. Only need to specify this on the rank root processor, other processors can provide any value for this argument (it’s unused).
root (int) – The rank of the processor whose value will be to broadcast.
 Returns
numpy.ndarray – The broadcast value, in a new, nonsharedmemory array.
 __getstate__(self)¶
 class pygsti.algorithms._CustomLMOptimizer(maxiter=100, maxfev=100, tol=1e06, fditer=0, first_fditer=0, damping_mode='identity', damping_basis='diagonal_values', damping_clip=None, use_acceleration=False, uphill_step_threshold=0.0, init_munu='auto', oob_check_interval=0, oob_action='reject', oob_check_mode=0, serial_solve_proc_threshold=100)¶
Bases:
Optimizer
A LevenbergMarquardt optimizer customized for GSTlike problems.
 Parameters
maxiter (int, optional) – The maximum number of (outer) interations.
maxfev (int, optional) – The maximum function evaluations.
tol (float or dict, optional) – The tolerance, specified as a single float or as a dict with keys {‘relx’, ‘relf’, ‘jac’, ‘maxdx’}. A single float sets the ‘relf’ and ‘jac’ elemments and leaves the others at their default values.
fditer (int optional) – Internally compute the Jacobian using a finitedifference method for the first fditer iterations. This is useful when the initial point lies at a special or singular point where the analytic Jacobian is misleading.
first_fditer (int, optional) – Number of finitedifference iterations applied to the first stage of the optimization (only). Unused.
damping_mode ({'identity', 'JTJ', 'invJTJ', 'adaptive'}) – How damping is applied. ‘identity’ means that the damping parameter mu multiplies the identity matrix. ‘JTJ’ means that mu multiplies the diagonal or singular values (depending on scaling_mode) of the JTJ (Fischer information and approx. hessaian) matrix, whereas ‘invJTJ’ means mu multiplies the reciprocals of these values instead. The ‘adaptive’ mode adaptively chooses a damping strategy.
damping_basis ({'diagonal_values', 'singular_values'}) – Whether the the diagonal or singular values of the JTJ matrix are used during damping. If ‘singular_values’ is selected, then a SVD of the Jacobian (J) matrix is performed and damping is performed in the basis of (right) singular vectors. If ‘diagonal_values’ is selected, the diagonal values of relevant matrices are used as a proxy for the the singular values (saving the cost of performing a SVD).
damping_clip (tuple, optional) – A 2tuple giving upper and lower bounds for the values that mu multiplies. If damping_mode == “identity” then this argument is ignored, as mu always multiplies a 1.0 on the diagonal if the identity matrix. If None, then no clipping is applied.
use_acceleration (bool, optional) – Whether to include a geodesic acceleration term as suggested in arXiv:1201.5885. This is supposed to increase the rate of convergence with very little overhead. In practice we’ve seen mixed results.
uphill_step_threshold (float, optional) – Allows uphill steps when taking two consecutive steps in nearly the same direction. The condition for accepting an uphill step is that (uphill_step_thresholdbeta)*new_objective < old_objective, where beta is the cosine of the angle between successive steps. If uphill_step_threshold == 0 then no uphill steps are allowed, otherwise it should take a value between 1.0 and 2.0, with 1.0 being the most permissive to uphill steps.
init_munu (tuple, optional) – If not None, a (mu, nu) tuple of 2 floats giving the initial values for mu and nu.
oob_check_interval (int, optional) – Every oob_check_interval outer iterations, the objective function (obj_fn) is called with a second argument ‘oob_check’, set to True. In this case, obj_fn can raise a ValueError exception to indicate that it is Out Of Bounds. If oob_check_interval is 0 then this check is never performed; if 1 then it is always performed.
oob_action ({"reject","stop"}) – What to do when the objective function indicates (by raising a ValueError as described above). “reject” means the step is rejected but the optimization proceeds; “stop” means the optimization stops and returns as converged at the last knowninbounds point.
oob_check_mode (int, optional) – An advanced option, expert use only. If 0 then the optimization is halted as soon as an attempt is made to evaluate the function out of bounds. If 1 then the optimization is halted only when a wouldbe accepted step is out of bounds.
serial_solve_proc_threshold (int optional) – When there are fewer than this many processors, the optimizer will solve linear systems serially, using SciPy on a single processor, rather than using a parallelized Gaussian Elimination (with partial pivoting) algorithm coded in Python. Since SciPy’s implementation is more efficient, it’s not worth using the parallel version until there are many processors to spread the work among.
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 run(self, objective, profiler, printer)¶
Perform the optimization.
 Parameters
objective (ObjectiveFunction) – The objective function to optimize.
profiler (Profiler) – A profiler to track resource usage.
printer (VerbosityPrinter) – printer to use for sending output to stdout.
 class pygsti.algorithms._Optimizer¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
An optimizer. Optimizes an objective function.
 pygsti.algorithms._dummy_profiler¶
 pygsti.algorithms.CUSTOMLM = True¶
 pygsti.algorithms.FLOATSIZE = 8¶
 pygsti.algorithms.run_lgst(dataset, prep_fiducials, effect_fiducials, target_model, op_labels=None, op_label_aliases=None, guess_model_for_gauge=None, svd_truncate_to=None, verbosity=0)¶
Performs Linearinversion Gate Set Tomography on the dataset.
 Parameters
dataset (DataSet) – The data used to generate the LGST estimates
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to specify which operation labels should be estimated, a guess for which gauge these estimates should be returned in.
op_labels (list, optional) – A list of which operation labels (or aliases) should be estimated. Overrides the operation labels in target_model. e.g. [‘Gi’,’Gx’,’Gy’,’Gx2’]
op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are circuits corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = pygsti.obj.Circuit([‘Gx’,’Gx’,’Gx’])
guess_model_for_gauge (Model, optional) – A model used to compute a gauge transformation that is applied to the LGST estimates before they are returned. This gauge transformation is computed such that if the estimated gates matched the model given, then the operation matrices would match, i.e. the gauge would be the same as the model supplied. Defaults to target_model.
svd_truncate_to (int, optional) – The Hilbert space dimension to truncate the operation matrices to using a SVD to keep only the largest svdToTruncateTo singular values of the I_tildle LGST matrix. Zero means no truncation. Defaults to dimension of target_model.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
Model – A model containing all of the estimated labels (or aliases)
 pygsti.algorithms._lgst_matrix_dims(model, prep_fiducials, effect_fiducials)¶
 pygsti.algorithms._construct_ab(prep_fiducials, effect_fiducials, model, dataset, op_label_aliases=None)¶
 pygsti.algorithms._construct_x_matrix(prep_fiducials, effect_fiducials, model, op_label_tuple, dataset, op_label_aliases=None)¶
 pygsti.algorithms._construct_a(effect_fiducials, model)¶
 pygsti.algorithms._construct_b(prep_fiducials, model)¶
 pygsti.algorithms._construct_target_ab(prep_fiducials, effect_fiducials, target_model)¶
 pygsti.algorithms.gram_rank_and_eigenvalues(dataset, prep_fiducials, effect_fiducials, target_model)¶
Returns the rank and singular values of the Gram matrix for a dataset.
 Parameters
dataset (DataSet) – The data used to populate the Gram matrix
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to make sense of circuit elements, and to compute the theoretical gram matrix eigenvalues (returned as svalues_target).
 Returns
rank (int) – the rank of the Gram matrix
svalues (numpy array) – the singular values of the Gram matrix
svalues_target (numpy array) – the corresponding singular values of the Gram matrix generated by target_model.
 pygsti.algorithms.run_gst_fit_simple(dataset, start_model, circuits, optimizer, objective_function_builder, resource_alloc, verbosity=0)¶
Performs core Gate Set Tomography function of model optimization.
Optimizes the parameters of start_model by minimizing the objective function built by objective_function_builder. Probabilities are computed by the model, and outcome counts are supplied by dataset.
 Parameters
dataset (DataSet) – The dataset to obtain counts from.
start_model (Model) – The Model used as a starting point for the leastsquares optimization.
circuits (list of (tuples or Circuits)) – Each tuple contains operation labels and specifies a circuit whose probabilities are considered when trying to leastsquaresfit the probabilities given in the dataset. e.g. [ (), (‘Gx’,), (‘Gx’,’Gy’) ]
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
objective_function_builder (ObjectiveFunctionBuilder) – Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”.
resource_alloc (ResourceAllocation) – A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
result (OptimizerResult) – the result of the optimization
model (Model) – the bestfit model.
 pygsti.algorithms.run_gst_fit(mdc_store, optimizer, objective_function_builder, verbosity=0)¶
Performs core Gate Set Tomography function of model optimization.
Optimizes the model to the data within mdc_store by minimizing the objective function built by objective_function_builder.
 Parameters
mdc_store (ModelDatasetCircuitsStore) – An object holding a model, data set, and set of circuits. This defines the model to be optimized, the data to fit to, and the circuits where predicted vs. observed comparisons should be made. This object also contains additional information specific to the given model, data set, and circuit list, doubling as a cache for increased performance. This information is also specific to a particular resource allocation, which affects how cached values stored.
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
objective_function_builder (ObjectiveFunctionBuilder) – Defines the objective function that is optimized. Can also be anything readily converted to an objective function builder, e.g. “logl”. If None, then mdc_store must itself be an alreadybuilt objective function.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
result (OptimizerResult) – the result of the optimization
objfn_store (MDCObjectiveFunction) – the objective function and store containing the bestfit model evaluated at the bestfit point.
 pygsti.algorithms.run_iterative_gst(dataset, start_model, circuit_lists, optimizer, iteration_objfn_builders, final_objfn_builders, resource_alloc, verbosity=0)¶
Performs Iterative Gate Set Tomography on the dataset.
 Parameters
dataset (DataSet) – The data used to generate MLGST gate estimates
start_model (Model) – The Model used as a starting point for the leastsquares optimization.
circuit_lists (list of lists of (tuples or Circuits)) – The ith element is a list of the circuits to be used in the ith iteration of the optimization. Each element of these lists is a circuit, specifed as either a Circuit object or as a tuple of operation labels (but all must be specified using the same type). e.g. [ [ (), (‘Gx’,) ], [ (), (‘Gx’,), (‘Gy’,) ], [ (), (‘Gx’,), (‘Gy’,), (‘Gx’,’Gy’) ] ]
optimizer (Optimizer or dict) – The optimizer to use, or a dictionary of optimizer parameters from which a default optimizer can be built.
iteration_objfn_builders (list) – List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on each iteration.
final_objfn_builders (list) – List of ObjectiveFunctionBuilder objects defining which objective functions should be optimizized (successively) on the final iteration.
resource_alloc (ResourceAllocation) – A resource allocation object containing information about how to divide computation amongst multiple processors and any memory limits that should be imposed.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
models (list of Models) – list whose ith element is the model corresponding to the results of the ith iteration.
optimums (list of OptimizerResults) – list whose ith element is the final optimizer result from that iteration.
final_objfn (MDSObjectiveFunction) – The final iteration’s objective function / store, which encapsulated the final objective function evaluated at the bestfit point (an “evaluated” modeldataSetcircuits store).
 pygsti.algorithms._do_runopt(objective, optimizer, printer)¶
Runs the core modeloptimization step within a GST routine by optimizing objective using optimizer.
This is factored out as a separate function because of the differences when running Taylorterm simtype calculations, which utilize this as a subroutine (see :function:`_do_term_runopt`).
 Parameters
objective (MDSObjectiveFunction) – A “modeldataset” objective function to optimize.
optimizer (Optimizer) – The optimizer to use.
printer (VerbosityPrinter) – An object for printing output.
 Returns
OptimizerResult
 pygsti.algorithms._do_term_runopt(objective, optimizer, printer)¶
Runs the core modeloptimization step for models using the Taylorterm (path integral) method of computing probabilities.
This routine serves the same purpose as :function:`_do_runopt`, but is more complex because an appropriate “path set” must be found, requiring a loop of model optimizations with fixed path sets until a sufficient “good” path set is obtained.
 Parameters
objective (MDSObjectiveFunction) – A “modeldataset” objective function to optimize.
optimizer (Optimizer) – The optimizer to use.
printer (VerbosityPrinter) – An object for printing output.
 Returns
OptimizerResult
 pygsti.algorithms.find_closest_unitary_opmx(operation_mx)¶
Find the closest (in fidelity) unitary superoperator to operation_mx.
Finds the closest operation matrix (by maximizing fidelity) to operation_mx that describes a unitary quantum gate.
 Parameters
operation_mx (numpy array) – The operation matrix to act on.
 Returns
numpy array – The resulting closest unitary operation matrix.
 class pygsti.algorithms._EigenvalueParamDenseOp(matrix, include_off_diags_in_degen_2_blocks=False, tp_constrained_and_unital=False, evotype='default', state_space=None)¶
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
A real operation matrix parameterized only by its eigenvalues.
These eigenvalues are assumed to be either real or to occur in conjugate pairs. Thus, the number of parameters is equal to the number of eigenvalues.
 Parameters
matrix (numpy array) – a square 2D numpy array that gives the raw operation matrix to paramterize. The shape of this array sets the dimension of the operation.
include_off_diags_in_degen_2_blocks (bool) – If True, include as parameters the (initially zero) offdiagonal elements in degenerate 2x2 blocks of the the diagonalized operation matrix (no offdiagonals are included in blocks larger than 2x2). This is an option specifically used in the intelligent fiducial pair reduction (IFPR) algorithm.
tp_constrained_and_unital (bool) – If True, assume the top row of the operation matrix is fixed to [1, 0, … 0] and should not be parameterized, and verify that the matrix is unital. In this case, “1” is always a fixed (notparamterized0 eigenvalue with eigenvector [1,0,…0] and if include_off_diags_in_degen_2_blocks is True any off diagonal elements lying on the top row are not parameterized as implied by the TP constraint.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 _construct_matrix(self)¶
Build the internal operation matrix using the current parameters.
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 pygsti.algorithms._remove_duplicates(l, index_to_test=None)¶
Remove duplicates from the a list and return the result.
 Parameters
l (iterable) – The list/set to remove duplicates from.
index_to_test (int, optional) – If not None, the index within the elements of l to test. For example, if all the elements of l contain 2 tuples (x,y) then set index_to_test == 1 to remove tuples with duplicate yvalues.
 Returns
list – the list after duplicates have been removed.
 pygsti.algorithms._nCr(n, r)¶
Number of combinations of r items out of a set of n. Equals n!/(r!(nr)!)
 pygsti.algorithms._random_combination(indices_tuple, r)¶
 Random selection from itertools.combinations(indices_tuple, r)
from http://docs.python.org/2/library/itertools.html#recipes
 pygsti.algorithms.find_sufficient_fiducial_pairs(target_model, prep_fiducials, meas_fiducials, germs, test_lengths=(256, 2048), prep_povm_tuples='first', tol=0.75, search_mode='sequential', n_random=100, seed=None, verbosity=0, test_pair_list=None, mem_limit=None, minimum_pairs=1)¶
Finds a (global) set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find a set of fiducial pairs that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). The test for amplification is performed using the two germpower lengths given by test_lengths, and tests whether the magnitudes of the Jacobian’s singular values scale linearly with the germpower length.
In the special case when test_pair_list is not None, the function tests the given set of fiducial pairs for amplificational completeness, and does not perform any search.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
test_lengths ((L1,L2) tuple of ints, optional) – A tuple of integers specifying the germpower lengths to use when checking for amplificational completeness.
prep_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
tol (float, optional) – The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
test_pair_list (list or None, optional) – If not None, a list of (prepfid_index,measfid_index) tuples of integers, specifying a list of fiducial pairs (indices are into prep_fiducials and meas_fiducials, respectively). These pairs are then tested for amplificational completeness and the number of amplified parameters is printed to stdout. (This is a special debugging functionality.)
mem_limit (int, optional) – A memory limit in bytes.
minimum_pairs (int, optional) – The minimium number of fiducial pairs to try (default == 1). Set this to integers larger than 1 to avoid trying pair sets that are known to be too small.
 Returns
list – A list of (prepfid_index,measfid_index) tuples of integers, specifying a list of fiducial pairs (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.find_sufficient_fiducial_pairs_per_germ(target_model, prep_fiducials, meas_fiducials, germs, pre_povm_tuples='first', search_mode='sequential', constrain_to_tp=True, n_random=100, seed=None, verbosity=0, mem_limit=None)¶
Finds a pergerm set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find sets of fiducial pairs, one set per germ, that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). For each germ, a fiducial pair set is found that amplifies all of the “parameters” (really linear combinations of them) that the particular germ amplifies.
To test whether a set of fiducial pairs satisfies this condition, the sum of projectors P_i = dot(J_i,J_i^T), where J_i is a matrix of the derivatives of each of the selected (prepFiducial+germ+effectFiducial) sequence probabilities with respect to the ith germ eigenvalue (or more generally, amplified parameter), is computed. If the fiducialpair set is sufficient, the rank of the resulting sum (an operator) will be equal to the total (maximal) number of parameters the germ can amplify.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence (per germ) before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
constrain_to_tp (bool, optional) – Whether or not to consider nonTP parameters the the germs amplify. If the fiducal pairs will be used in a GST estimation where the model is constrained to being tracepreserving (TP), this should be set to True.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
dict – A dictionary whose keys are the germ circuits and whose values are lists of (iRhoFid,iMeasFid) tuples of integers, each specifying the list of fiducial pairs for a particular germ (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.find_sufficient_fiducial_pairs_per_germ_power(target_model, prep_fiducials, meas_fiducials, germs, max_lengths, pre_povm_tuples='first', search_mode='sequential', constrain_to_tp=True, n_random=100, seed=None, verbosity=0, mem_limit=None)¶
Finds a pergerm set of fiducial pairs that are amplificationally complete.
A “standard” set of GST circuits consists of all circuits of the form:
statePrep + prepFiducial + germPower + measureFiducial + measurement
This set is typically overcomplete, and it is possible to restrict the (prepFiducial, measureFiducial) pairs to a subset of all the possible pairs given the separate prep_fiducials and meas_fiducials lists. This function attempts to find sets of fiducial pairs, one set per germ, that still amplify all of the model’s parameters (i.e. is “amplificationally complete”). For each germ, a fiducial pair set is found that amplifies all of the “parameters” (really linear combinations of them) that the particular germ amplifies.
To test whether a set of fiducial pairs satisfies this condition, the sum of projectors P_i = dot(J_i,J_i^T), where J_i is a matrix of the derivatives of each of the selected (prepFiducial+germ+effectFiducial) sequence probabilities with respect to the ith germ eigenvalue (or more generally, amplified parameter), is computed. If the fiducialpair set is sufficient, the rank of the resulting sum (an operator) will be equal to the total (maximal) number of parameters the germ can amplify.
 Parameters
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
max_lengths (list of int) – The germ powers (number of repetitions) to be used to amplify errors.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
search_mode ({"sequential","random"}, optional) – If “sequential”, then all potential fiducial pair sets of a given length are considered in sequence (per germ) before moving to sets of a larger size. This can take a long time when there are many possible fiducial pairs. If “random”, then only n_random randomly chosen fiducial pair sets are considered for each set size before the set is enlarged.
constrain_to_tp (bool, optional) – Whether or not to consider nonTP parameters the the germs amplify. If the fiducal pairs will be used in a GST estimation where the model is constrained to being tracepreserving (TP), this should be set to True.
n_random (int, optional) – The number of randompairsets to consider for a given set size.
seed (int, optional) – The seed to use for generating randompairsets.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
dict – A dictionary whose keys are the germ circuits and whose values are lists of (iRhoFid,iMeasFid) tuples of integers, each specifying the list of fiducial pairs for a particular germ (indices are into prep_fiducials and meas_fiducials).
 pygsti.algorithms.test_fiducial_pairs(fid_pairs, target_model, prep_fiducials, meas_fiducials, germs, test_lengths=(256, 2048), pre_povm_tuples='first', tol=0.75, verbosity=0, mem_limit=None)¶
Tests a set of global or pergerm fiducial pairs.
Determines how many model parameters (of target_model) are amplified by the fiducial pairs given by fid_pairs, which can be either a list of 2tuples (for globalFPR) or a dictionary (for pergerm FPR).
 Parameters
fid_pairs (list or dict) – Either a single list of fiducialindex pairs (2tuples) that is applied to every germ (global FPR) OR a pergerm dictionary of lists, each containing the fiducialindex pairs (2tuples) for that germ (for pergerm FPR).
target_model (Model) – The target model used to determine amplificational completeness.
prep_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective preparation.
meas_fiducials (list of Circuits) – Fiducial circuits used to construct an informationally complete effective measurement.
germs (list of Circuits) – The germ circuits that are repeated to amplify errors.
test_lengths ((L1,L2) tuple of ints, optional) – A tuple of integers specifying the germpower lengths to use when checking for amplificational completeness.
pre_povm_tuples (list or "first", optional) – A list of (prepLabel, povmLabel) tuples to consider when checking for completeness. Usually this should be left as the special (and default) value “first”, which considers the first prep and POVM contained in target_model.
tol (float, optional) – The tolerance for the fraction of the expected amplification that must be observed to call a parameter “amplified”.
verbosity (int, optional) – How much detail to print to stdout.
mem_limit (int, optional) – A memory limit in bytes.
 Returns
numAmplified (int)
 pygsti.algorithms._get_per_germ_fidpairs(prep_fiducials, meas_fiducials, pre_povm_tuples, gsGerm, mem_limit, printer, search_mode, seed, n_random)¶
 class pygsti.algorithms._ComplementPOVMEffect(identity, other_effects)¶
Bases:
pygsti.modelmembers.povms.conjugatedeffect.ConjugatedStatePOVMEffect
TODO: docstring A POVM effect vector that ensures that all the effects of a POVM sum to the identity.
This POVM effect vector is paramterized as I  sum(other_spam_vecs) where I is a (static) identity element and other_param_vecs is a list of other spam vectors in the same parent
POVM
. This only partially implements the modelmember interface (some methods such as to_vector and from_vector will thunk down to base class versions which raise NotImplementedError), as instances are meant to be contained within aPOVM
which takes care of vectorization. Parameters
identity (array_like or POVMEffect) – a 1D numpy array representing the static identity operation from which the sum of the other vectors is subtracted.
other_spamvecs (list of POVMEffects) – A list of the “other” parameterized POVM effect vectors which are subtracted from identity to compute the final value of this “complement” POVM effect vector.
 _construct_vector(self)¶
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 property num_params(self)¶
Get the number of independent parameters which specify this POVM effect vector.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Get the POVM effect vector parameters as an array of values.
 Returns
numpy array – The parameters as a 1D array with length num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the POVM effect vector using a 1D array of parameters.
 Parameters
v (numpy array) – The 1D vector of POVM effect vector parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this POVM effect vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this POVM effect vector.
Construct a matrix whose columns are the derivatives of the POVM effect vector with respect to a single param. Thus, each column is of length dimension and there is one column per POVM effect vector parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension, num_params)
 has_nonzero_hessian(self)¶
Whether this POVM effect vector has a nonzero Hessian with respect to its parameters.
 Returns
bool
 pygsti.algorithms.frobeniusdist_squared(a, b)¶
Returns the square of the frobenius distance between gate or density matrices.
This is given by :
sum( (A_ijB_ij)^2 )
 Parameters
a (numpy array) – First matrix.
b (numpy array) – Second matrix.
 Returns
float – The resulting frobenius distance.
 pygsti.algorithms.find_fiducials(target_model, omit_identity=True, eq_thresh=1e06, ops_to_omit=None, force_empty=True, max_fid_length=2, algorithm='grasp', algorithm_kwargs=None, verbosity=1)¶
Generate prep and measurement fiducials for a given target model.
 Parameters
target_model (Model) – The model you are aiming to implement.
omit_identity (bool, optional) – Whether to remove the identity gate from the set of gates with which fiducials are constructed. Identity gates do nothing to alter fiducials, and so should almost always be left out.
eq_thresh (float, optional) – Threshold for determining if a gate is the identity gate. If the square Frobenius distance between a given gate and the identity gate is less than this threshold, the gate is considered to be an identity gate and will be removed from the list of gates from which to construct fiducials if omit_identity is
True
.ops_to_omit (list of string, optional) – List of strings identifying gates in the model that should not be used in fiducials. Oftentimes this will include the identity gate, and may also include entangling gates if their fidelity is anticipated to be much worse than that of singlesystem gates.
force_empty (bool, optional (default is True)) – Whether or not to force all fiducial sets to contain the empty gate string as a fiducial.
max_fid_length (int, optional) – The maximum number of gates to include in a fiducial. The default is not guaranteed to work for arbitrary models (particularly for quantum systems larger than a single qubit).
algorithm ({'slack', 'grasp'}, optional) –
Specifies the algorithm to use to generate the fiducials. Current options are:
 ’slack’
See
_find_fiducials_integer_slack()
for more details. ’grasp’
Use GRASP to generate random greedy fiducial sets and then locally optimize them. See
_find_fiducials_grasp()
for more details.
algorithm_kwargs (dict) – Dictionary of
{'keyword': keyword_arg}
pairs providing keyword arguments for the specified algorithm function. See the documentation for functions referred to in the algorithm keyword documentation for what options are available for each algorithm.verbosity (int, optional) – How much detail to send to stdout.
 Returns
prepFidList (list of Circuits) – A list containing the circuits for the prep fiducials.
measFidList (list of Circuits) – A list containing the circuits for the measurement fiducials.
 pygsti.algorithms.xor(*args)¶
Implements logical xor function for arbitrary number of inputs.
 Parameters
args (boollikes) – All the boolean (or booleanlike) objects to be checked for xor satisfaction.
 Returns
output (bool) – True if and only if one and only one element of args is True and the rest are False. False otherwise.
 pygsti.algorithms.create_prep_mxs(model, prep_fid_list)¶
Make a list of matrices for the model preparation operations.
Makes a list of matrices, where each matrix corresponds to a single preparation operation in the model, and the column of each matrix is a fiducial acting on that state preparation.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
prep_fid_list (list of Circuits) – List of fiducial circuits for constructing an informationally complete state preparation.
 Returns
list – A list of matrices, each of shape (dim, len(prep_fid_list)) where dim is the dimension of model (4 for a single qubit). The length of this list is equal to the number of state preparations in model.
 pygsti.algorithms.create_meas_mxs(model, meas_fid_list)¶
Make a list of matrices for the model measurement operations.
Makes a list of matrices, where each matrix corresponds to a single measurement effect in the model, and the column of each matrix is the transpose of the measurement effect acting on a fiducial.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
meas_fid_list (list of Circuits) – List of fiducial circuits for constructing an informationally complete measurement.
 Returns
list – A list of matrices, each of shape (dim, len(meas_fid_list)) where dim is the dimension of model (4 for a single qubit). The length of this list is equal to the number of POVM effects in model.
 pygsti.algorithms.compute_composite_fiducial_score(model, fid_list, prep_or_meas, score_func='all', threshold=1000000.0, return_all=False, op_penalty=0.0, l1_penalty=0.0)¶
Compute a composite score for a fiducial list.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fid_list (list of Circuits) – List of fiducial circuits to test.
prep_or_meas (string ("prep" or "meas")) – Are we testing preparation or measurement fiducials?
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
return_all (bool, optional (default is False)) – Whether the spectrum should be returned along with the score.
op_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
.l1_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
.
 Returns
score (CompositeScore) – The score of the fiducials.
spectrum (numpy.array, optional) – The eigenvalues of the square of the absolute value of the score matrix.
 pygsti.algorithms.test_fiducial_list(model, fid_list, prep_or_meas, score_func='all', return_all=False, threshold=1000000.0, l1_penalty=0.0, op_penalty=0.0)¶
Tests a prep or measure fiducial list for informational completeness.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fid_list (list of Circuits) – List of fiducial circuits to test.
prep_or_meas (string ("prep" or "meas")) – Are we testing preparation or measurement fiducials?
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
return_all (bool, optional (default is False)) – If true, function returns reciprocals of eigenvalues of fiducial score matrix, and the score of the fiducial set as specified by score_func, in addition to a boolean specifying whether or not the fiducial set is informationally complete
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
l1_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
.op_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
.
 Returns
testResult (bool) – Whether or not the specified fiducial list is informationally complete for the provided model, to within the tolerance specified by threshold.
spectrum (array, optional) – The number of fiducials times the reciprocal of the spectrum of the score matrix. Only returned if return_all == True.
score (float, optional) – The score for the fiducial set; only returned if return_all == True.
 pygsti.algorithms.build_bitvec_mx(n, k)¶
Create an array of all lengthn and Hamming weight k binary vectors.
 Parameters
n (int) – The length of each bit string.
k (int) – The hamming weight of each bit string.
 Returns
numpy.ndarray – An array of shape (binom(n,k), n) whose rows are the sought binary vectors.
 pygsti.algorithms._find_fiducials_integer_slack(model, fid_list, prep_or_meas=None, initial_weights=None, score_func='all', max_iter=100, fixed_slack=None, slack_frac=None, return_all=False, force_empty=True, force_empty_score=1e+100, fixed_num=None, threshold=1000000.0, verbosity=1)¶
Find a locally optimal subset of the fiducials in fid_list.
Locally optimal here means that no single fiducial can be excluded without increasing the sum of the reciprocals of the singular values of the “score matrix” (the matrix whose columns are the fiducials acting on the preparation, or the transpose of the measurement acting on the fiducials), by more than a fixed or variable amount of “slack”, as specified by fixed_slack or slack_frac.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fid_list (list of Circuits) – List of all fiducials circuits to consider.
prep_or_meas ({'prep', 'meas'}) – Whether preparation or measturement fiducials are being selected.
initial_weights (listlike) – List or array of either booleans or (0 or 1) integers specifying which fiducials in fid_list comprise the initial fiduial set. If None, then starting point includes all fiducials.
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
max_iter (int, optional) – The maximum number of iterations before stopping.
fixed_slack (float, optional) – If not None, a floating point number which specifies that excluding a fiducial is allowed to increase the fiducial set score additively by fixed_slack. You must specify either fixed_slack or slack_frac.
slack_frac (float, optional) – If not None, a floating point number which specifies that excluding a fiducial is allowed to increase the fiducial set score multiplicatively by (1+slack_frac). You must specify either fixed_slack or slack_frac.
return_all (bool, optional) – If True, return the final “weights” vector and score dictionary in addition to the optimal fiducial list (see below).
force_empty (bool, optional (default is True)) –
Whether or not to force all fiducial sets to contain the empty gate string as a fiducial.
IMPORTANT: This only works if the first element of fid_list is the empty circuit.
force_empty_score (float, optional (default is 1e100)) – When force_empty is True, what score to assign any fiducial set that does not contain the empty circuit as a fiducial.
fixed_num (int, optional) – Require the output list of fiducials to contain exactly fixed_num elements.
threshold (float, optional (default is 1e6)) – Entire fiducial list is first scored before attempting to select fiducials; if score is above threshold, then fiducial selection will autofail. If final fiducial set selected is above threshold, then fiducial selection will print a warning, but return selected set.
verbosity (int, optional) – Integer >= 0 indicating the amount of detail to print.
 Returns
fiducial_list (list) – A list of the selected (optimized) fiducial circuits.
weights (list) – Only returned if return_all=True. The internal weights for each candidate germ.
score (dict) – Only returned if return_all=True. The internal dictionary mapping weights (as a tuple) to scores.
 pygsti.algorithms._find_fiducials_grasp(model, fids_list, prep_or_meas, alpha, iterations=5, score_func='all', op_penalty=0.0, l1_penalty=0.0, return_all=False, force_empty=True, threshold=1000000.0, seed=None, verbosity=0)¶
Use GRASP to find a highperforming set of fiducials.
 Parameters
model (Model) – The model (associates operation matrices with operation labels).
fids_list (list of Circuits) – List of fiducial circuits to test.
prep_or_meas (string ("prep" or "meas")) – Are we testing preparation or measurement fiducials?
alpha (float) – A number between 0 and 1 that roughly specifies a score threshold relative to the spread of scores that a germ must score better than in order to be included in the RCL. A value of 0 for alpha corresponds to a purely greedy algorithm (only the bestscoring element is included in the RCL), while a value of 1 for alpha will include all elements in the RCL.
iterations (int, optional) – Number of GRASP iterations.
score_func (str ('all' or 'worst'), optional (default is 'all')) – Sets the objective function for scoring a fiducial set. If ‘all’, score is (number of fiducials) * sum(1/Eigenvalues of score matrix). If ‘worst’, score is (number of fiducials) * 1/min(Eigenvalues of score matrix). Note: Choosing ‘worst’ corresponds to trying to make the optimizer make the “worst” direction (the one we are least sensitive to in HilbertSchmidt space) as minimally bad as possible. Choosing ‘all’ corresponds to trying to make the optimizer make us as sensitive as possible to all directions in HilbertSchmidt space. (Also note because we are using a simple integer program to choose fiducials, it is possible to get stuck in a local minimum, and choosing one or the other objective function can help avoid such minima in different circumstances.)
op_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the total number of gates in all fiducials that is added to
score.minor
.l1_penalty (float, optional (defailt is 0.0)) – Coefficient of a penalty linear in the number of fiducials that is added to
score.minor
.return_all (bool, optional (default is False)) – If true, function returns reciprocals of eigenvalues of fiducial score matrix, and the score of the fiducial set as specified by score_func, in addition to a boolean specifying whether or not the fiducial set is informationally complete
force_empty (bool, optional) – When True, the empty circuit must be a member of the chosen set.
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the fiducial set is rejected as informationally incomplete.
seed (int, optional) – The seed value used for each individual iteration.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
best_fiducials (list) – The bestscoring list of fiducial circuits.
initial_fiducials (list of lists) – Only returned if return_all=True. A list of the initial solution (a solution is a list of fiducial circuits) for each grasp iteration.
local_solutions (list of lists) – Only returned if return_all=True. A list of the best solution (a solution is a list of fiducial circuits) for each grasp iteration.
 class pygsti.algorithms._TrivialGaugeGroupElement(dim)¶
Bases:
GaugeGroupElement
Element of
TrivialGaugeGroup
 Parameters
dim (int) – The HilbertSchmidt space dimension of the gauge group.
 property transform_matrix(self)¶
The gaugetransform matrix.
 Returns
numpy.ndarray
 property transform_matrix_inverse(self)¶
The inverse of the gaugetransform matrix.
 Returns
numpy.ndarray
 deriv_wrt_params(self, wrt_filter=None)¶
Computes the derivative of the gauge group at this element.
That is, the derivative of a general element with respect to the gauge group’s parameters, evaluated at this element.
 Parameters
wrt_filter (list or numpy.ndarray, optional) – Indices of the gauge group parameters to differentiate with respect to. If None, differentiation is performed with respect to all the group’s parameters.
 Returns
numpy.ndarray
 to_vector(self)¶
Get the parameter vector corresponding to this transform.
 Returns
numpy.ndarray
 from_vector(self, v)¶
Reinitialize this GaugeGroupElement using the the parameter vector v.
 Parameters
v (numpy.ndarray) – A 1D array of length :method:`num_params`
 Returns
None
 property num_params(self)¶
Return the number of parameters (degrees of freedom) of this element.
 Returns
int
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 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, return_all=False, comm=None, verbosity=0, check_jac=False)¶
Optimize the gauge degrees of freedom of a model to that of a target.
 Parameters
model (Model) – The model to gaugeoptimize
target_model (Model) – The model to optimize to. The metric used for comparing models is given by gates_metric and spam_metric.
item_weights (dict, optional) – Dictionary of weighting factors for gates and spam operators. Keys can be gate, state preparation, or POVM effect, as well as the special values “spam” or “gates” which apply the given weighting to all spam operators or gates respectively. Values are floating point numbers. Values given for specific gates or spam operators take precedence over “gates” and “spam” values. The precise use of these weights depends on the model metric(s) being used.
cptp_penalty_factor (float, optional) – If greater than zero, the objective function also contains CPTP penalty terms which penalize nonCPTPness of the gates being optimized. This factor multiplies these CPTP penalty terms.
spam_penalty_factor (float, optional) – If greater than zero, the objective function also contains SPAM penalty terms which penalize nonpositiveness of the state preps being optimized. This factor multiplies these SPAM penalty terms.
gates_metric ({"frobenius", "fidelity", "tracedist"}, optional) – The metric used to compare gates within models. “frobenius” computes the normalized sqrt(sumofsquareddifferences), with weights multiplying the squared differences (see
Model.frobeniusdist()
). “fidelity” and “tracedist” sum the individual infidelities or trace distances of each gate, weighted by the weights.spam_metric ({"frobenius", "fidelity", "tracedist"}, optional) – The metric used to compare spam vectors within models. “frobenius” computes the normalized sqrt(sumofsquareddifferences), with weights multiplying the squared differences (see
Model.frobeniusdist()
). “fidelity” and “tracedist” sum the individual infidelities or trace distances of each “SPAM gate”, weighted by the weights.gauge_group (GaugeGroup, optional) – The gauge group which defines which gauge trasformations are optimized over. If None, then the model’s default gauge group is used.
method (string, optional) –
The method used to optimize the objective function. Can be any method known by scipy.optimize.minimize such as ‘BFGS’, ‘NelderMead’, ‘CG’, ‘LBFGSB’, or additionally:
’auto’ – ‘ls’ when allowed, otherwise ‘LBFGSB’
’ls’ – custom leastsquares optimizer.
’custom’ – custom CG that often works better than ‘CG’
’supersimplex’ – repeated application of ‘NelderMead’ to converge it
’basinhopping’ – scipy.optimize.basinhopping using LBFGSB as a local optimizer
’swarm’ – particle swarm global optimization algorithm
’evolve’ – evolutionary global optimization algorithm using DEAP
’brute’ – Experimental: scipy.optimize.brute using 4 points along each dimensions
maxiter (int, optional) – Maximum number of iterations for the gauge optimization.
maxfev (int, optional) – Maximum number of function evaluations for the gauge optimization. Defaults to maxiter.
tol (float, optional) – The tolerance for the gauge optimization.
oob_check_interval (int, optional) – If greater than zero, gauge transformations are allowed to fail (by raising any exception) to indicate an outofbounds condition that the gauge optimizer will avoid. If zero, then any gaugetransform failures just terminate the optimization.
return_all (bool, optional) – When True, return best “goodness” value and gauge matrix in addition to the gauge optimized model.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
verbosity (int, optional) – How much detail to send to stdout.
check_jac (bool) – When True, check least squares analytic jacobian against finite differences
 Returns
model if return_all == False
(goodnessMin, gaugeMx, model) if return_all == True – where goodnessMin is the minimum value of the goodness function (the best ‘goodness’) found, gaugeMx is the gauge matrix used to transform the model, and model is the final gaugetransformed model.
 pygsti.algorithms.gaugeopt_custom(model, objective_fn, gauge_group=None, method='LBFGSB', maxiter=100000, maxfev=None, tol=1e08, oob_check_interval=0, return_all=False, jacobian_fn=None, comm=None, verbosity=0)¶
Optimize the gauge of a model using a custom objective function.
 Parameters
model (Model) – The model to gaugeoptimize
objective_fn (function) – The function to be minimized. The function must take a single Model argument and return a float.
gauge_group (GaugeGroup, optional) – The gauge group which defines which gauge trasformations are optimized over. If None, then the model’s default gauge group is used.
method (string, optional) –
The method used to optimize the objective function. Can be any method known by scipy.optimize.minimize such as ‘BFGS’, ‘NelderMead’, ‘CG’, ‘LBFGSB’, or additionally:
’custom’ – custom CG that often works better than ‘CG’
’supersimplex’ – repeated application of ‘NelderMead’ to converge it
’basinhopping’ – scipy.optimize.basinhopping using LBFGSB as a local optimizer
’swarm’ – particle swarm global optimization algorithm
’evolve’ – evolutionary global optimization algorithm using DEAP
’brute’ – Experimental: scipy.optimize.brute using 4 points along each dimensions
maxiter (int, optional) – Maximum number of iterations for the gauge optimization.
maxfev (int, optional) – Maximum number of function evaluations for the gauge optimization. Defaults to maxiter.
tol (float, optional) – The tolerance for the gauge optimization.
oob_check_interval (int, optional) – If greater than zero, gauge transformations are allowed to fail (by raising any exception) to indicate an outofbounds condition that the gauge optimizer will avoid. If zero, then any gaugetransform failures just terminate the optimization.
return_all (bool, optional) – When True, return best “goodness” value and gauge matrix in addition to the gauge optimized model.
jacobian_fn (function, optional) – The jacobian of objective_fn. The function must take three parameters, 1) the untransformed Model, 2) the transformed Model, and 3) the GaugeGroupElement representing the transformation that brings the first argument into the second.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
verbosity (int, optional) – How much detail to send to stdout.
 Returns
model if return_all == False
(goodnessMin, gaugeMx, model) if return_all == True – where goodnessMin is the minimum value of the goodness function (the best ‘goodness’) found, gaugeMx is the gauge matrix used to transform the model, and model is the final gaugetransformed model.
 pygsti.algorithms._create_objective_fn(model, target_model, item_weights=None, cptp_penalty_factor=0, spam_penalty_factor=0, gates_metric='frobenius', spam_metric='frobenius', method=None, comm=None, check_jac=False)¶
Creates the objective function and jacobian (if available) for gaugeopt_to_target
 pygsti.algorithms._cptp_penalty_size(mdl)¶
Helper function  same as that in core.py.
 pygsti.algorithms._spam_penalty_size(mdl)¶
Helper function  same as that in core.py.
 pygsti.algorithms._cptp_penalty(mdl, prefactor, op_basis)¶
Helper function  CPTP penalty: (sum of tracenorms of gates), which in least squares optimization means returning an array of the sqrt(tracenorm) of each gate. This function is the same as that in core.py.
 Returns
numpy array – a (real) 1D array of length len(mdl.operations).
 pygsti.algorithms._spam_penalty(mdl, prefactor, op_basis)¶
Helper function  CPTP penalty: (sum of tracenorms of gates), which in least squares optimization means returning an array of the sqrt(tracenorm) of each gate. This function is the same as that in core.py.
 Returns
numpy array – a (real) 1D array of length _spam_penalty_size(mdl)
 pygsti.algorithms._cptp_penalty_jac_fill(cp_penalty_vec_grad_to_fill, mdl_pre, mdl_post, gauge_group_el, prefactor, op_basis, wrt_filter)¶
Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) Returns a (real) array of shape (len(mdl.operations), gauge_group_el.num_params).
 pygsti.algorithms._spam_penalty_jac_fill(spam_penalty_vec_grad_to_fill, mdl_pre, mdl_post, gauge_group_el, prefactor, op_basis, wrt_filter)¶
Helper function  jacobian of CPTP penalty (sum of tracenorms of gates) Returns a (real) array of shape (_spam_penalty_size(mdl), gauge_group_el.num_params).
 pygsti.algorithms.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)¶
Generate a germ set for doing GST with a given target model.
This function provides a streamlined interface to a variety of germ selection algorithms. It’s goal is to provide a method that typical users can run by simply providing a target model and leaving all other settings at their default values, while providing flexibility for users desiring more control to fine tune some of the general and algorithmspecific details.
Currently, to break troublesome degeneracies and provide some confidence that the chosen germ set is amplificationally complete (AC) for all models in a neighborhood of the target model (rather than only the target model), an ensemble of models with random unitary perturbations to their gates must be provided or generated.
 Parameters
target_model (Model or list of Model) – The model you are aiming to implement, or a list of models that are copies of the model you are trying to implement (either with or without random unitary perturbations applied to the models).
randomize (bool, optional) – Whether or not to add random unitary perturbations to the model(s) provided.
randomization_strength (float, optional) – The size of the random unitary perturbations applied to gates in the model. See
randomize_with_unitary()
for more details.num_gs_copies (int, optional) – The number of copies of the original model that should be used.
seed (int, optional) – Seed for generating random unitary perturbations to models. Also passed along to stochastic germselection algorithms.
candidate_germ_counts (dict, optional) – A dictionary of germ_length : count keyvalue pairs, specifying the germ “candidate list”  a list of potential germs to draw from. count is either an integer specifying the number of random germs considered at the given germ_length or the special values “all upto” that considers all of the of all nonequivalent germs of length up to the corresponding germ_length. If None, all germs of up to length 6 are used, the equivalent of {6: ‘all upto’}.
candidate_seed (int, optional) – A seed value used when randomly selecting candidate germs. For each germ length being randomly selected, the germ length is added to the value of candidate_seed to get the actual seed used.
force (str or list, optional) – A list of Circuits which must be included in the final germ set. If set to the special string “singletons” then all length1 strings will be included. Seting to None is the same as an empty list.
algorithm ({'greedy', 'grasp', 'slack'}, optional) –
Specifies the algorithm to use to generate the germ set. Current options are: ‘greedy’
Add germs oneatatime until the set is AC, picking the germ that improves the germset score by the largest amount at each step. See
find_germs_breadthfirst()
for more details. ’grasp’
Use GRASP to generate random greedy germ sets and then locally optimize them. See
find_germs_grasp()
for more details. ’slack’
From a initial set of germs, add or remove a germ at each step in an attempt to improve the germset score. Will allow moves that degrade the score in an attempt to escape local optima as long as the degredation is within some specified amount of “slack”. See
find_germs_integer_slack()
for more details.
algorithm_kwargs (dict) – Dictionary of
{'keyword': keyword_arg}
pairs providing keyword arguments for the specified algorithm function. See the documentation for functions referred to in the algorithm keyword documentation for what options are available for each algorithm.mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
profiler (Profiler, optional) – A profiler object used for to track timing and memory usage.
verbosity (int, optional) – The verbosity level of the
VerbosityPrinter
used to print log messages.
 Returns
list of Circuit – A list containing the germs making up the germ set.
 pygsti.algorithms.compute_germ_set_score(germs, target_model=None, neighborhood=None, neighborhood_size=5, randomization_strength=0.01, score_func='all', op_penalty=0.0, l1_penalty=0.0)¶
Calculate the score of a germ set with respect to a model.
More precisely, this function computes the maximum score (roughly equal to the number of amplified parameters) for a cloud of models. If target_model is given, it serves as the center of the cloud, otherwise the cloud must be supplied directly via neighborhood.
 Parameters
germs (list) – The germ set
target_model (Model, optional) – The target model, used to generate a neighborhood of randomized models.
neighborhood (list of Models, optional) – The “cloud” of models for which scores are computed. If not None, this overrides target_model, neighborhood_size, and randomization_strength.
neighborhood_size (int, optional) – Number of randomized models to construct around target_model.
randomization_strength (float, optional) – Strength of unitary randomizations, as passed to :method:`target_model.randomize_with_unitary`.
score_func ({'all', 'worst'}) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/input_array)
. If ‘worst’, score is1/min(input_array)
.op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
l1_penalty (float, optional) – Coefficient for a penalty linear in the number of germs.
 Returns
CompositeScore – The maximum score for germs, indicating how many parameters it amplifies.
 pygsti.algorithms._get_model_params(model_list)¶
Get the number of gates and gauge parameters of the models in a list.
Also verifies all models have the same number of gates and gauge parameters.
 Parameters
model_list (list of Model) – A list of models for which you want an AC germ set.
 Returns
reducedModelList (list of Model) – The original list of models with SPAM removed
numGaugeParams (int) – The number of nonSPAM gauge parameters for all models.
numNonGaugeParams (int) – The number of nonSPAM nongauge parameters for all models.
numOps (int) – The number of gates for all models.
 Raises
ValueError – If the number of gauge parameters or gates varies among the models.
 pygsti.algorithms._setup_model_list(model_list, randomize, randomization_strength, num_copies, seed)¶
Sets up a list of randomize models (helper function).
 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, num_gauge_params=None, op_penalty=0.0, germ_lengths=None, l1_penalty=0.0)¶
Compute the score for a germ set when it is not AC against a model.
Normally scores computed for germ sets against models for which they are not AC will simply be astronomically large. This is fine if AC is all you care about, but not so useful if you want to compare partial germ sets against one another to see which is closer to being AC. This function will see if the germ set is AC for the parameters corresponding to the largest N eigenvalues for increasing N until it finds a value of N for which the germ set is not AC or all the non gauge parameters are accounted for and report the value of N as well as the score. This allows partial germ set scores to be compared against oneanother sensibly, where a larger value of N always beats a smaller value of N, and ties in the value of N are broken by the score for that value of N.
 Parameters
score_fn (callable) – A function that takes as input a list of sorted eigenvalues and returns a score for the partial germ set based on those eigenvalues, with lower scores indicating better germ sets. Usually some flavor of
list_score()
.threshold_ac (float, optional) – Value which the score (before penalties are applied) must be lower than for the germ set to be considered AC.
init_n (int) – The number of largest eigenvalues to begin with checking.
partial_deriv_dagger_deriv (numpy.array, optional) – Array with three axes, where the first axis indexes individual germs within the partial germ set and the remaining axes index entries in the positive square of the Jacobian of each individual germ’s parameters with respect to the model parameters. If this array is not supplied it will need to be computed from germs_list and model, which will take longer, so it is recommended to precompute this array if this routine will be called multiple times.
model (Model, optional) – The model against which the germ set is to be scored. Not needed if partial_deriv_dagger_deriv is provided.
partial_germs_list (list of Circuit, optional) – The list of germs in the partial germ set to be evaluated. Not needed if partial_deriv_dagger_deriv (and germ_lengths when
op_penalty > 0
) are provided.eps (float, optional) – Used when calculating partial_deriv_dagger_deriv to determine if two eigenvalues are equal (see
_bulk_twirled_deriv()
for details). Not used if partial_deriv_dagger_deriv is provided.num_gauge_params (int) – The number of gauge parameters of the model. Not needed if model is provided.
op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths (numpy.array, optional) – The length of each germ. Not needed if op_penalty is
0.0
or partial_germs_list is provided.l1_penalty (float, optional) – Coefficient for a penalty linear in the number of germs.
 Returns
CompositeScore – The score for the germ set indicating how many parameters it amplifies and its numerical score restricted to those parameters.
 pygsti.algorithms._compute_bulk_twirled_ddd(model, germs_list, eps=1e06, check=False, germ_lengths=None, comm=None)¶
Calculate the positive squares of the germ Jacobians.
twirledDerivDaggerDeriv == array J.H*J contributions from each germ (J=Jacobian) indexed by (iGerm, iModelParam1, iModelParam2) size (nGerms, vec_model_dim, vec_model_dim)
 Parameters
model (Model) – The model defining the parameters to differentiate with respect to.
germs_list (list) – The germ set
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
germ_lengths (numpy.ndarray, optional) – A precomputed array of the length (depth) of each germ.
comm (mpi4py.MPI.Comm, optional) – When not
None
, an MPI communicator for distributing the computation across multiple processors.
 Returns
twirledDerivDaggerDeriv (numpy.ndarray) – A complex array of shape (len(germs), model.num_params, model.num_params).
 pygsti.algorithms._compute_twirled_ddd(model, germ, eps=1e06)¶
Calculate the positive squares of the germ Jacobian.
twirledDerivDaggerDeriv == array J.H*J contributions from germ (J=Jacobian) indexed by (iModelParam1, iModelParam2) size (vec_model_dim, vec_model_dim)
 Parameters
model (Model) – The model defining the parameters to differentiate with respect to.
germ (Circuit) – The (single) germ circuit to consider. J above is the twirled derivative of this circuit’s action (process matrix).
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
 Returns
numpy.ndarray
 pygsti.algorithms._germ_set_score_slack(weights, model_num, score_func, deriv_dagger_deriv_list, force_indices, force_score, n_gauge_params, op_penalty, germ_lengths, l1_penalty=0.01, score_dict=None)¶
Returns a germ set “score” in which smaller is better.
Also returns intentionally bad score (force_score) if weights is zero on any of the “forced” germs (i.e. at any index in forcedIndices). This function is included for use by
find_germs_integer_slack()
, but is not convenient for just computing the score of a germ set. For that, usecompute_germ_set_score()
. Parameters
weights (list) – The pergerm “selection weight”, indicating whether the germ is present in the selected germ set or not.
model_num (int) – index into deriv_dagger_deriv_list indicating which model (typically in a neighborhood) we’re computing scores for.
score_func ({'all', 'worst'}) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/input_array)
. If ‘worst’, score is1/min(input_array)
.deriv_dagger_deriv_list (numpy.ndarray) – Array of J.T * J contributions for each model.
force_indices (list of ints) – Indices marking the germs that must be in the final set (or else force_score will be returned).
force_score (float) – The score that is returned when any of the germs indexed by force_indices are not present (i.e. their weights are <= 0).
n_gauge_params (int) – The number of gauge (not amplifiable) parameters in the model.
op_penalty (float) – Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths (numpy.ndarray) – A precomputed array of the length (depth) of each germ.
l1_penalty (float) – Coefficient for a penalty linear in the number of germs.
score_dict (dict, optional) – A dictionary to cache the score valies for the given model_num and weights, i.e. score_dict[model_num, tuple(weights)] is set to the returned value.
 Returns
float
 pygsti.algorithms.randomize_model_list(model_list, randomization_strength, num_copies, seed=None)¶
Applies random unitary perturbations to a model or list of models.
If model_list is a length1 list, then num_copies determines how many randomizations to create. If model_list containes multiple models, then num_copies must be None and each model is randomized once to create the corresponding returned model.
 Parameters
model_list (Model or list) – A list of Model objects.
randomization_strength (float, optional) – Strength of unitary randomizations, as passed to :method:`Model.randomize_with_unitary`.
num_copies (int) – The number of random perturbations of model_list[0] to generate when len(model_list) == 1. A value of None will result in 1 copy. If len(model_list) > 1 then num_copies must be set to None.
seed (int, optional) – Starting seed for randomization. Successive randomizations receive successive seeds. None results in random seeds.
 Returns
list – A list of the randomized Models.
 pygsti.algorithms.test_germs_list_completeness(model_list, germs_list, score_func, threshold)¶
Check to see if the germs_list is amplificationally complete (AC).
Checks for AC with respect to all the Models in model_list, returning the index of the first Model for which it is not AC or 1 if it is AC for all Models.
 Parameters
model_list (list) – A list of models to test. Often this list is a neighborhood (“cloud”) of models around a model of interest.
germs_list (list) – A list of the germ :class:`Circuit`s (the “germ set”) to test for completeness.
score_func ({'all', 'worst'}) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/eigval_array)
. If ‘worst’, score is1/min(eigval_array)
.threshold (float, optional) – An eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when its reciprocal is greater than threshold. Also used for eigenvector degeneracy testing in twirling operation.
 Returns
int – The index of the first model in model_list to fail the amplficational completeness test.
 pygsti.algorithms._remove_spam_vectors(model)¶
Returns a copy of model with state preparations and effects removed.
 Parameters
model (Model) – The model to act on.
 Returns
Model
 pygsti.algorithms._num_non_spam_gauge_params(model)¶
Return the number of nongauge, nonSPAM parameters in model.
Equivalent to _remove_spam_vectors(model).num_gauge_params.
 Parameters
model (Model) –
model – The model to act on.
 Returns
int
 pygsti.algorithms._super_op_for_perfect_twirl(wrt, eps)¶
Return super operator for doing a perfect twirl with respect to wrt.
 pygsti.algorithms._sq_sing_vals_from_deriv(deriv, weights=None)¶
Calculate the squared singular values of the Jacobian of the germ set.
 Parameters
deriv (numpy.array) – Array of shape
(nGerms, flattened_op_dim, vec_model_dim)
. Each subarray corresponding to an individual germ is the Jacobian of the vectorized gate representation of that germ raised to some power with respect to the model parameters, normalized by dividing by the length of each germ after repetition.weights (numpy.array) – Array of length
nGerms
, giving the relative contributions of each individual germ’s Jacobian to the combined Jacobian (which is calculated as a convex combination of the individual Jacobians).
 Returns
numpy.array – The sorted squared singular values of the combined Jacobian of the germ set.
 pygsti.algorithms._twirled_deriv(model, circuit, eps=1e06)¶
Compute the “Twirled Derivative” of a circuit.
The twirled derivative is obtained by acting on the standard derivative of a circuit with the twirling superoperator.
 Parameters
model (Model object) – The Model which associates operation labels with operators.
circuit (Circuit object) – A twirled derivative of this circuit’s action (process matrix) is taken.
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
 Returns
numpy array – An array of shape (op_dim^2, num_model_params)
 pygsti.algorithms._bulk_twirled_deriv(model, circuits, eps=1e06, check=False, comm=None)¶
Compute the “Twirled Derivative” of a set of circuits.
The twirled derivative is obtained by acting on the standard derivative of a circuit with the twirling superoperator.
 Parameters
model (Model object) – The Model which associates operation labels with operators.
circuits (list of Circuit objects) – A twirled derivative of this circuit’s action (process matrix) is taken.
eps (float, optional) – Tolerance used for testing whether two eigenvectors are degenerate (i.e. abs(eval1  eval2) < eps ? )
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
 Returns
numpy array – An array of shape (num_simplified_circuits, op_dim^2, num_model_params)
 pygsti.algorithms.test_germ_set_finitel(model, germs_to_test, length, weights=None, return_spectrum=False, tol=1e06)¶
Test whether a set of germs is able to amplify all nongauge parameters.
 Parameters
model (Model) – The Model (associates operation matrices with operation labels).
germs_to_test (list of Circuits) – List of germ circuits to test for completeness.
length (int) – The finite length to use in amplification testing. Larger values take longer to compute but give more robust results.
weights (numpy array, optional) – A 1D array of weights with length equal len(germs_to_test), which multiply the contribution of each germ to the total jacobian matrix determining parameter amplification. If None, a uniform weighting of 1.0/len(germs_to_test) is applied.
return_spectrum (bool, optional) – If True, return the jacobian^T*jacobian spectrum in addition to the success flag.
tol (float, optional) – Tolerance: an eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when it is less than tol.
 Returns
success (bool) – Whether all nongauge parameters were amplified.
spectrum (numpy array) – Only returned when return_spectrum is
True
. Sorted array of eigenvalues (from small to large) of the jacobian^T * jacobian matrix used to determine parameter amplification.
 pygsti.algorithms.test_germ_set_infl(model, germs_to_test, score_func='all', weights=None, return_spectrum=False, threshold=1000000.0, check=False)¶
Test whether a set of germs is able to amplify all nongauge parameters.
 Parameters
model (Model) – The Model (associates operation matrices with operation labels).
germs_to_test (list of Circuit) – List of germ circuits to test for completeness.
score_func (string) – Label to indicate how a germ set is scored. See
list_score()
for details.weights (numpy array, optional) – A 1D array of weights with length equal len(germs_to_test), which multiply the contribution of each germ to the total jacobian matrix determining parameter amplification. If None, a uniform weighting of 1.0/len(germs_to_test) is applied.
return_spectrum (bool, optional) – If
True
, return the jacobian^T*jacobian spectrum in addition to the success flag.threshold (float, optional) – An eigenvalue of jacobian^T*jacobian is considered zero and thus a parameter unamplified when its reciprocal is greater than threshold. Also used for eigenvector degeneracy testing in twirling operation.
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
 Returns
success (bool) – Whether all nongauge parameters were amplified.
spectrum (numpy array) – Only returned when return_spectrum is
True
. Sorted array of eigenvalues (from small to large) of the jacobian^T * jacobian matrix used to determine parameter amplification.
 pygsti.algorithms.find_germs_depthfirst(model_list, germs_list, randomize=True, randomization_strength=0.001, num_copies=None, seed=0, op_penalty=0, score_func='all', tol=1e06, threshold=1000000.0, check=False, force='singletons', verbosity=0)¶
Greedy germ selection algorithm starting with 0 germs.
Tries to minimize the number of germs needed to achieve amplificational completeness (AC). Begins with 0 germs and adds the germ that increases the score used to check for AC by the largest amount at each step, stopping when the threshold for AC is achieved.
 Parameters
model_list (Model or list) – The model or list of `Model`s to select germs for.
germs_list (list of Circuit) – The list of germs to contruct a germ set from.
randomize (bool, optional) – Whether or not to randomize model_list (usually just a single Model) with small (see randomizationStrengh) unitary maps in order to avoid “accidental” symmetries which could allow for fewer germs but only for that particular model. Setting this to True will increase the run time by a factor equal to the numer of randomized copies (num_copies).
randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
.num_copies (int, optional) – The number of randomized models to create when only a single gate set is passed via model_list. Otherwise, num_copies must be set to None.
seed (int, optional) – Seed for generating random unitary perturbations to models.
op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
score_func ({'all', 'worst'}, optional) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/eigenvalues)
. If ‘worst’, score is1/min(eiganvalues)
.tol (float, optional) – Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate.threshold (float, optional) – Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
check (bool, optional) – Whether to perform internal checks (will slow down run time substantially).
force (list of Circuits) – A list of Circuit objects which must be included in the final germ set. If the special string “singletons” is given, then all of the single gates (length1 sequences) must be included.
verbosity (int, optional) – Level of detail printed to stdout.
 Returns
list – A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.find_germs_breadthfirst(model_list, germs_list, randomize=True, randomization_strength=0.001, num_copies=None, seed=0, op_penalty=0, score_func='all', tol=1e06, threshold=1000000.0, check=False, force='singletons', pretest=True, mem_limit=None, comm=None, profiler=None, verbosity=0)¶
Greedy algorithm starting with 0 germs.
Tries to minimize the number of germs needed to achieve amplificational completeness (AC). Begins with 0 germs and adds the germ that increases the score used to check for AC by the largest amount (for the model that currently has the lowest score) at each step, stopping when the threshold for AC is achieved. This strategy is something of a “breadthfirst” approach, in contrast to
find_germs_depthfirst()
, which only looks at the scores for one model at a time until that model achieves AC, then turning it’s attention to the remaining models. Parameters
model_list (Model or list) – The model or list of `Model`s to select germs for.
germs_list (list of Circuit) – The list of germs to contruct a germ set from.
randomize (bool, optional) – Whether or not to randomize model_list (usually just a single Model) with small (see randomizationStrengh) unitary maps in order to avoid “accidental” symmetries which could allow for fewer germs but only for that particular model. Setting this to True will increase the run time by a factor equal to the numer of randomized copies (num_copies).
randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
.num_copies (int, optional) – The number of randomized models to create when only a single gate set is passed via model_list. Otherwise, num_copies must be set to None.
seed (int, optional) – Seed for generating random unitary perturbations to models.
op_penalty (float, optional) – Coefficient for a penalty linear in the sum of the germ lengths.
score_func ({'all', 'worst'}, optional) – Sets the objective function for scoring the eigenvalues. If ‘all’, score is
sum(1/eigenvalues)
. If ‘worst’, score is1/min(eiganvalues)
.tol (float, optional) – Tolerance (eps arg) for
_compute_bulk_twirled_ddd()
, which sets the differece between eigenvalues below which they’re treated as degenerate.threshold (float, optional) – Value which the score (before penalties are applied) must be lower than for a germ set to be considered AC.
check (bool, optional) – Whether to perform internal checks (will slow down run time substantially).
force (list of Circuits) – A list of Circuit objects which must be included in the final germ set. If the special string “singletons” is given, then all of the single gates (length1 sequences) must be included.
pretest (boolean, optional) – Whether germ list should be initially checked for completeness.
mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.
profiler (Profiler, optional) – A profiler object used for to track timing and memory usage.
verbosity (int, optional) – Level of detail printed to stdout.
 Returns
list – A list of the builtup germ set (a list of
Circuit
objects).
 pygsti.algorithms.find_germs_integer_slack(model_list, germs_list, randomize=True, randomization_strength=0.001, num_copies=None, seed=0, l1_penalty=0.01, op_penalty=0, initial_weights=None, score_func='all', max_iter=100, fixed_slack=False, slack_frac=False, return_all=False, tol=1e06, check=False, force='singletons', force_score=1e+100, threshold=1000000.0, verbosity=1)¶
Find a locally optimal subset of the germs in germs_list.
Locally optimal here means that no single germ can be excluded without making the smallest nongauge eigenvalue of the Jacobian.H*Jacobian matrix smaller, i.e. less amplified, by more than a fixed or variable amount of “slack”, as specified by fixed_slack or slack_frac.
 Parameters
model_list (Model or list of Model) – The list of Models to be tested. To ensure that the returned germ set is amplficationally complete, it is a good idea to score potential germ sets against a collection (~510) of similar models. The user may specify a single Model and a number of unitarily close copies to be made (set by the kwarg num_copies), or the user may specify their own list of Models, each of which in turn may or may not be randomized (set by the kwarg randomize).
germs_list (list of Circuit) – List of all germ circuits to consider.
randomize (Bool, optional) – Whether or not the input Model(s) are first subject to unitary randomization. If
False
, the user should perform the unitary randomization themselves. Note: If the Model(s) are perfect (e.g.std1Q_XYI.target_model()
), then the germ selection output should not be trusted, due to accidental degeneracies in the Model. If the Model(s) include stochastic (nonunitary) error, then germ selection will fail, as we score amplificational completeness in the limit of infinite sequence length (so any stochastic noise will completely depolarize any sequence in that limit). Default isTrue
.randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. Default is1e3
.num_copies (int, optional) – The number of Model copies to be made of the input Model (prior to unitary randomization). If more than one Model is passed in, num_copies should be
None
. If only one Model is passed in and num_copies isNone
, no extra copies are made.seed (float, optional) – The starting seed used for unitary randomization. If multiple Models are to be randomized,
model_list[i]
is randomized withseed + i
. Default is 0.l1_penalty (float, optional) – How strong the penalty should be for increasing the germ set list by a single germ. Default is 1e2.
op_penalty (float, optional) – How strong the penalty should be for increasing a germ in the germ set list by a single gate. Default is 0.
initial_weights (listlike) – List or array of either booleans or (0 or 1) integers specifying which germs in germ_list comprise the initial germ set. If
None
, then starting point includes all germs.score_func (string) – Label to indicate how a germ set is scored. See
list_score()
for details.max_iter (int, optional) – The maximum number of iterations before giving up.
fixed_slack (float, optional) – If not
None
, a floating point number which specifies that excluding a germ is allowed to increase 1.0/smallestnongaugeeigenvalue by fixed_slack. You must specify either fixed_slack or slack_frac.slack_frac (float, optional) – If not
None
, a floating point number which specifies that excluding a germ is allowed to increase 1.0/smallestnongaugeeigenvalue by fixedFrac`*100 percent. You must specify *either* `fixed_slack or slack_frac.return_all (bool, optional) – If
True
, return the finalweights
vector and score dictionary in addition to the optimal germ list (see below).tol (float, optional) – Tolerance used for eigenvector degeneracy testing in twirling operation.
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
force (str or list, optional) – A list of Circuits which must be included in the final germ set. If set to the special string “singletons” then all length1 strings will be included. Seting to None is the same as an empty list.
force_score (float, optional (default is 1e100)) – When force designates a nonempty set of circuits, the score to assign any germ set that does not contain each and every required germ.
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the germ set is rejected as amplificationally incomplete.
verbosity (int, optional) – Integer >= 0 indicating the amount of detail to print.
See also
Model
,Circuit
 pygsti.algorithms._germ_set_score_grasp(germ_set, germs_list, twirled_deriv_dagger_deriv_list, non_ac_kwargs, init_n=1)¶
Score a germ set against a collection of models.
Calculate the score of the germ set with respect to each member of a collection of models and return the worst score among that collection.
 Parameters
germ_set (list of Circuit) – The set of germs to score.
germs_list (list of Circuit) – The list of all germs whose Jacobians are provided in twirled_deriv_dagger_deriv_list.
twirled_deriv_dagger_deriv_list (numpy.array) – Jacobians for all the germs in germs_list stored as a 3dimensional array, where the first index indexes the particular germ.
non_ac_kwargs (dict) – Dictionary containing further arguments to pass to
compute_composite_germ_set_score()
for the scoring of the germ set against individual models.init_n (int) – The number of eigenvalues to begin checking for amplificational completeness with respect to. Passed as an argument to
compute_composite_germ_set_score()
.
 Returns
CompositeScore – The worst score over all models of the germ set.
 pygsti.algorithms.find_germs_grasp(model_list, germs_list, alpha, randomize=True, randomization_strength=0.001, num_copies=None, seed=None, l1_penalty=0.01, op_penalty=0.0, score_func='all', tol=1e06, threshold=1000000.0, check=False, force='singletons', iterations=5, return_all=False, shuffle=False, verbosity=0)¶
Use GRASP to find a highperforming germ set.
 Parameters
model_list (Model or list of Model) – The list of Models to be tested. To ensure that the returned germ set is amplficationally complete, it is a good idea to score potential germ sets against a collection (~510) of similar models. The user may specify a single Model and a number of unitarily close copies to be made (set by the kwarg num_copies, or the user may specify their own list of Models, each of which in turn may or may not be randomized (set by the kwarg randomize).
germs_list (list of Circuit) – List of all germ circuits to consider.
alpha (float) – A number between 0 and 1 that roughly specifies a score theshold relative to the spread of scores that a germ must score better than in order to be included in the RCL. A value of 0 for alpha corresponds to a purely greedy algorithm (only the bestscoring germ set is included in the RCL), while a value of 1 for alpha will include all germs in the RCL. See
pygsti.algorithms.scoring.filter_composite_rcl()
for more details.randomize (Bool, optional) – Whether or not the input Model(s) are first subject to unitary randomization. If
False
, the user should perform the unitary randomization themselves. Note: If the Model(s) are perfect (e.g.std1Q_XYI.target_model()
), then the germ selection output should not be trusted, due to accidental degeneracies in the Model. If the Model(s) include stochastic (nonunitary) error, then germ selection will fail, as we score amplificational completeness in the limit of infinite sequence length (so any stochastic noise will completely depolarize any sequence in that limit).randomization_strength (float, optional) – The strength of the unitary noise used to randomize input Model(s); is passed to
randomize_with_unitary()
. Default is1e3
.num_copies (int, optional) – The number of Model copies to be made of the input Model (prior to unitary randomization). If more than one Model is passed in, num_copies should be
None
. If only one Model is passed in and num_copies isNone
, no extra copies are made.seed (float, optional) – The starting seed used for unitary randomization. If multiple Models are to be randomized,
model_list[i]
is randomized withseed + i
.l1_penalty (float, optional) – How strong the penalty should be for increasing the germ set list by a single germ. Used for choosing between outputs of various GRASP iterations.
op_penalty (float, optional) – How strong the penalty should be for increasing a germ in the germ set list by a single gate.
score_func (string) – Label to indicate how a germ set is scored. See
list_score()
for details.tol (float, optional) – Tolerance used for eigenvector degeneracy testing in twirling operation.
threshold (float, optional (default is 1e6)) – Specifies a maximum score for the score matrix, above which the germ set is rejected as amplificationally incomplete.
check (bool, optional) – Whether to perform internal consistency checks, at the expense of making the function slower.
force (str or list, optional) – A list of Circuits which must be included in the final germ set. If set to the special string “singletons” then all length1 strings will be included. Seting to None is the same as an empty list.
iterations (int, optional) – The number of GRASP iterations to perform.
return_all (bool, optional) – Flag set to tell the routine if it should return lists of all initial constructions and local optimizations in addition to the optimal solution (useful for diagnostic purposes or if you’re not sure what your finalScoreFn should really be).
shuffle (bool, optional) – Whether the neighborhood should be presented to the optimizer in a random order (important since currently the local optimizer updates the solution to the first better solution it finds in the neighborhood).
verbosity (int, optional) – Integer >= 0 indicating the amount of detail to print.
 Returns
finalGermList (list of Circuit) – Sublist of germs_list specifying the final, optimal set of germs.
 pygsti.algorithms._gram_rank_and_evals(dataset, prep_fiducials, effect_fiducials, target_model)¶
Returns the rank and singular values of the Gram matrix for a dataset.
 Parameters
dataset (DataSet) – The data used to populate the Gram matrix
prep_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective preparation.
effect_fiducials (list of Circuits) – Fiducial Circuits used to construct a informationally complete effective measurement.
target_model (Model) – A model used to make sense of circuit elements, and to compute the theoretical gram matrix eigenvalues (returned as svalues_target).
 Returns
rank (int) – the rank of the Gram matrix
svalues (numpy array) – the singular values of the Gram matrix
svalues_target (numpy array) – the corresponding singular values of the Gram matrix generated by target_model.
 pygsti.algorithms.max_gram_basis(op_labels, dataset, max_length=0)¶
Compute a maximal set of basis circuits for a Gram matrix.
That is, a maximal set of strings {S_i} such that the gate strings { S_i S_j } are all present in dataset. If max_length > 0, then restrict len(S_i) <= max_length.
 Parameters
op_labels (list or tuple) – the operation labels to use in Gram matrix basis strings
dataset (DataSet) – the dataset to use when constructing the Gram matrix
max_length (int, optional) – the maximum string length considered for Gram matrix basis elements. Defaults to 0 (no limit).
 Returns
list of tuples – where each tuple contains operation labels and specifies a single circuit.
 pygsti.algorithms.max_gram_rank_and_eigenvalues(dataset, target_model, max_basis_string_length=10, fixed_lists=None)¶
Compute the rank and singular values of a maximal Gram matrix.
That is, compute the rank and singular values of the Gram matrix computed using the basis: max_gram_basis(dataset.gate_labels(), dataset, max_basis_string_length).
 Parameters
dataset (DataSet) – the dataset to use when constructing the Gram matrix
target_model (Model) – A model used to make sense of circuits and for the construction of a theoretical gram matrix and spectrum.
max_basis_string_length (int, optional) – the maximum string length considered for Gram matrix basis elements. Defaults to 10.
fixed_lists ((prep_fiducials, effect_fiducials), optional) – 2tuple of
Circuit
lists, specifying the preparation and measurement fiducials to use when constructing the Gram matrix, and thereby bypassing the search for such lists.
 Returns
rank (integer)
singularvalues (numpy array)
targetsingularvalues (numpy array)
 pygsti.algorithms.create_mirror_circuit(circ, pspec, circ_type='clifford+zxzxz')¶
circ_type : clifford+zxzxz, cz(theta)+zxzxz