pygsti.modelmembers.operations
Subpackage holding model operation objects.
Submodules
pygsti.modelmembers.operations.affineshiftop
pygsti.modelmembers.operations.composederrorgen
pygsti.modelmembers.operations.composedop
pygsti.modelmembers.operations.denseop
pygsti.modelmembers.operations.depolarizeop
pygsti.modelmembers.operations.eigpdenseop
pygsti.modelmembers.operations.embeddederrorgen
pygsti.modelmembers.operations.embeddedop
pygsti.modelmembers.operations.experrorgenop
pygsti.modelmembers.operations.fullarbitraryop
pygsti.modelmembers.operations.fullcptpop
pygsti.modelmembers.operations.fulltpop
pygsti.modelmembers.operations.fullunitaryop
pygsti.modelmembers.operations.identitypluserrorgenop
pygsti.modelmembers.operations.krausop
pygsti.modelmembers.operations.lindbladcoefficients
pygsti.modelmembers.operations.lindbladerrorgen
pygsti.modelmembers.operations.linearop
pygsti.modelmembers.operations.lpdenseop
pygsti.modelmembers.operations.opfactory
pygsti.modelmembers.operations.repeatedop
pygsti.modelmembers.operations.staticarbitraryop
pygsti.modelmembers.operations.staticcliffordop
pygsti.modelmembers.operations.staticstdop
pygsti.modelmembers.operations.staticunitaryop
pygsti.modelmembers.operations.stochasticop
Package Contents
Classes
A composition (sum!) of several Lindbladian exponent operators. 

An operation that is the composition of a number of maplike factors (possibly other LinearOperator). 

TODO: update docstring 

Adds a numpyarraymimicing interface onto an operation object. 

A depolarizing channel. 

A real operation matrix parameterized only by its eigenvalues. 

An error generator containing a single lower (or equal) dimensional operation within it. 

An operation containing a single lower (or equal) dimensional operation within it. 

An operation parameterized by the coefficients of an exponentiated sum of Lindbladlike terms. 

An operation consisting of the identity added to what would ordinarily be an error generator. 

An operation matrix that is fully parameterized. 

A tracepreserving operation matrix. 

An operation matrix that is fully parameterized. 

TODO: update docstring 

An Lindbladform error generator. 

An object encapsulating a particular way of parameterizing a LindbladErrorgen 

Base class for all operation representations 

An operation matrix parameterized such that each element depends only linearly on any parameter. 

An object that can generate "ondemand" operators (can be SPAM vecs, etc., as well) for a Model. 

A factory that embeds a given factory's action into a single, predefined set of target sectors. 

A factory that "ondemand" embeds a given factory or operation into any requested set of target sectors. 

A factory that composes a number of other factories and/or operations. 

An operation map that is the composition of a number of maplike factors (possibly other LinearOperator) 

An operation matrix that is completely fixed, or "static" (i.e. that posesses no parameters). 

A Clifford operation, represented via a symplectic matrix. 

An operation that is completely fixed, or "static" (i.e. that posesses no parameters) 

A unitary operation matrix that is completely fixed, or "static" (i.e. that posesses no parameters). 

A stochastic noise operation. 

An operation matrix that induces an affine shift. 
Functions

Computes a finitedifference Jacobian for a LinearOperator object. 

Computes a finitedifference Hessian for a LinearOperator object. 

TODO: docstring  note that op_type can be a list/tuple of types in order of precedence 



Decode an op type into the "canonical", more verbose op type. 

TODO: docstring 

Convert operation to a new type of parameterization. 

Checks the deriv_wrt_params method of a LinearOperator object. 

Optimize the parameters of op_to_optimize. 
 class pygsti.modelmembers.operations.ComposedErrorgen(errgens_to_compose, evotype='auto', state_space='auto')
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
A composition (sum!) of several Lindbladian exponent operators.
That is, a sum (not product) of other error generators.
Parameters
 errgens_to_composelist
List of LinearOperatorderived objects that are summed together (composed) to form this error generator.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype. The special value “auto” is equivalent to the evolution type of ops_to_compose[0] if there’s at least one operation being composed.
 state_spaceStateSpace or “auto”
State space of this error generator. Can be set to “auto” to take the state space from errgens_to_compose[0] if there’s at least one error generator being composed.
Initialize a new LinearOperator
 property parameter_labels
An array of labels (usually strings) describing this model member’s parameters.
 property num_params
Get the number of independent parameters which specify this error generator.
Returns
 int
the number of independent parameters.
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 coefficients(return_basis=False, logscale_nonham=False)
Constructs a dictionary of the Lindbladerrorgenerator coefficients of this error generator.
Note that these are not necessarily the parameter values, as these coefficients are generally functions of the parameters (so as to keep the coefficients positive, for instance).
Parameters
 return_basisbool
Whether to also return a
Basis
containing the elements with which the error generator terms were constructed. logscale_nonhambool, optional
Whether or not the nonhamiltonian error generator coefficients should be scaled so that the returned dict contains: (1  exp(d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by
error_rates()
.
Returns
 Ltermdictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Basis labels are integers starting at 0. Values are complex coefficients.
 basisBasis
A Basis mapping the basis labels used in the keys of Ltermdict to basis matrices.
 coefficient_labels()
The elementary errorgenerator labels corresponding to the elements of
coefficients_array()
.Returns
 tuple
A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 coefficients_array()
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by
coefficients()
, weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.Returns
 numpy.ndarray
A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this error generator.
 coefficients_array_deriv_wrt_params()
The jacobian of
coefficients_array()
with respect to this error generator’s parameters.Returns
 numpy.ndarray
A 2D array of shape (num_coeffs, num_params) where num_coeffs is the number of coefficients in the linear combination of standard error generators that is this error generator, and num_params is this error generator’s number of parameters.
 error_rates()
Constructs a dictionary of the error rates associated with this error generator.
These error rates pertaining to the channel formed by exponentiating this object.
The “error rate” for an individual Hamiltonian error is the angle about the “axis” (generalized in the multiqubit case) corresponding to a particular basis element, i.e. theta in the unitary channel U = exp(i * theta/2 * BasisElement).
The “error rate” for an individual Stochastic error is the contribution that basis element’s term would have to the error rate of a depolarization channel. For example, if the rate corresponding to the term (‘S’,’X’) is 0.01 this means that the coefficient of the rho > X*rho*Xrho error generator is set such that if this coefficient were used for all 3 (X,Y, and Z) terms the resulting depolarizing channel would have error rate 3*0.01 = 0.03.
Note that because error generator terms do not necessarily commute with one another, the sum of the returned error rates is not necessarily the error rate of the overall channel.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case.
 set_coefficients(lindblad_term_dict, action='update', logscale_nonham=False, truncate=True)
Sets the coefficients of terms in this error generator.
The dictionary lindblad_term_dict has tuplekeys describing the type of term and the basis elements used to construct it, e.g. (‘H’,’X’).
Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are the coefficients of these error generators, and should be real except for the 2basislabel case.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing errorgenerator coefficients.
 logscale_nonhambool, optional
Whether or not the values in lindblad_term_dict for nonhamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see
errorgen_coefficients()
) instead of raw coefficients. If True, then the nonhamiltonian coefficients are set to log(1  d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the functionset_error_rates()
. truncatebool, optional
Whether to truncate the projections onto the Lindblad terms in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given coefficients cannot be parameterized as specified.
Returns
None
 set_error_rates(lindblad_term_dict, action='update')
Sets the coeffcients of terms in this error generator.
Cofficients are set so that the contributions of the resulting channel’s error rate are given by the values in lindblad_term_dict. See
error_rates()
for more details.Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case, when they may be complex.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing error rates.
Returns
None
 deriv_wrt_params(wrt_filter=None)
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened error generator matrix with respect to a single operator parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
Parameters
 wrt_filterlist 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)
 hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this error generator with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension^2, num_params1, num_params2)
 append(*factors_to_add)
Add one or more factors to this operator.
Parameters
 *factors_to_addLinearOperator
One or multiple factor operators to add on at the end (summed last) of this operator.
Returns
None
 insert(insert_at, *factors_to_insert)
Insert one or more factors into this operator.
Parameters
 insert_atint
The index at which to insert factors_to_insert. The factor at this index and those after it are shifted back by len(factors_to_insert).
 *factors_to_insertLinearOperator
One or multiple factor operators to insert within this operator.
Returns
None
 remove(*factor_indices)
Remove one or more factors from this operator.
Parameters
 *factorop_indicesint
One or multiple factor indices to remove from this operator.
Returns
None
 to_sparse(on_space='minimal')
Return this error generator as a sparse matrix
Returns
scipy.sparse.csr_matrix
 to_dense(on_space='minimal')
Return this error generator as a dense matrix
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_vector()
Get the error generator parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this error generator.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get.
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
In this particular case any TP gauge transformation is possible, i.e. when s is an instance of TPGaugeGroupElement or corresponds to a TPlike transform matrix.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 class pygsti.modelmembers.operations.ComposedOp(ops_to_compose, evotype='auto', state_space='auto', allocated_to_parent=None)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
An operation that is the composition of a number of maplike factors (possibly other LinearOperator).
Parameters
 ops_to_composelist
List of LinearOperatorderived objects that are composed to form this operation map. Elements are composed with vectors in lefttoright ordering, maintaining the same convention as operation sequences in pyGSTi. Note that this is opposite from standard matrix multiplication order.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype. The special value “auto” is equivalent to the evolution type of ops_to_compose[0] if there’s at least one operation being composed.
 state_spaceStateSpace or “auto”
State space of this error generator. Can be set to “auto” to take the state space from errgens_to_compose[0] if there’s at least one error generator being composed.
Initialize a new LinearOperator
 property parameter_labels
An array of labels (usually strings) describing this model member’s parameters.
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 set_time(t)
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
Parameters
 tfloat
The current time.
Returns
None
 set_gpindices(gpindices, parent, memo=None)
Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.
Parameters
 gpindicesslice or integer ndarray
The indices of this objects parameters in its parent’s array.
 parentModel or ModelMember
The parent whose parameter array gpindices references.
 memodict, optional
A memo dict used to avoid circular references.
Returns
None
 append(*factorops_to_add)
Add one or more factors to this operator.
Parameters
 *factors_to_addLinearOperator
One or multiple factor operators to add on at the end (evaluated last) of this operator.
Returns
None
 insert(insert_at, *factorops_to_insert)
Insert one or more factors into this operator.
Parameters
 insert_atint
The index at which to insert factorops_to_insert. The factor at this index and those after it are shifted back by len(factorops_to_insert).
 *factors_to_insertLinearOperator
One or multiple factor operators to insert within this operator.
Returns
None
 remove(*factorop_indices)
Remove one or more factors from this operator.
Parameters
 *factorop_indicesint
One or multiple factor indices to remove from this operator.
Returns
None
 to_sparse(on_space='minimal')
Return the operation as a sparse matrix
Returns
scipy.sparse.csr_matrix
 to_dense(on_space='minimal')
Return this operation as a dense matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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 with shape (dimension^2, num_params)
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get.
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 taylor_order_terms_above_mag(order, max_polynomial_vars, min_term_mag)
Get the orderth order Taylorexpansion terms of this operation that have magnitude above min_term_mag.
This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls
taylor_order_terms()
internally, so that all the terms at order order are typically cached for future calls.The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get (and filter).
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 min_term_magfloat
the minimum term magnitude.
Returns
 list
A list of
Rank1Term
objects.
 has_nonzero_hessian()
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
 transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
In this particular case any TP gauge transformation is possible, i.e. when s is an instance of TPGaugeGroupElement or corresponds to a TPlike transform matrix.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 errorgen_coefficients(return_basis=False, logscale_nonham=False)
Constructs a dictionary of the Lindbladerrorgenerator coefficients of this operation.
Note that these are not necessarily the parameter values, as these coefficients are generally functions of the parameters (so as to keep the coefficients positive, for instance).
Parameters
 return_basisbool, optional
Whether to also return a
Basis
containing the elements with which the error generator terms were constructed. logscale_nonhambool, optional
Whether or not the nonhamiltonian error generator coefficients should be scaled so that the returned dict contains: (1  exp(d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by
error_rates()
.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Basis labels are integers starting at 0. Values are complex coefficients.
 basisBasis
A Basis mapping the basis labels used in the keys of lindblad_term_dict to basis matrices.
 errorgen_coefficient_labels()
The elementary errorgenerator labels corresponding to the elements of
errorgen_coefficients_array()
.Returns
 tuple
A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 errorgen_coefficients_array()
The weighted coefficients of this operation’s error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by
errorgen_coefficients()
, weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.Returns
 numpy.ndarray
A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this operation’s error generator.
 errorgen_coefficients_array_deriv_wrt_params()
The jacobian of
errogen_coefficients_array()
with respect to this operation’s parameters.Returns
 numpy.ndarray
A 2D array of shape (num_coeffs, num_params) where num_coeffs is the number of coefficients of this operation’s error generator and num_params is this operation’s number of parameters.
 error_rates()
Constructs a dictionary of the error rates associated with this operation.
The “error rate” for an individual Hamiltonian error is the angle about the “axis” (generalized in the multiqubit case) corresponding to a particular basis element, i.e. theta in the unitary channel U = exp(i * theta/2 * BasisElement).
The “error rate” for an individual Stochastic error is the contribution that basis element’s term would have to the error rate of a depolarization channel. For example, if the rate corresponding to the term (‘S’,’X’) is 0.01 this means that the coefficient of the rho > X*rho*Xrho error generator is set such that if this coefficient were used for all 3 (X,Y, and Z) terms the resulting depolarizing channel would have error rate 3*0.01 = 0.03.
Note that because error generator terms do not necessarily commute with one another, the sum of the returned error rates is not necessarily the error rate of the overall channel.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case.
 set_errorgen_coefficients(lindblad_term_dict, action='update', logscale_nonham=False, truncate=True)
Sets the coefficients of terms in the error generator of this operation.
The dictionary lindblad_term_dict has tuplekeys describing the type of term and the basis elements used to construct it, e.g. (‘H’,’X’).
Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are the coefficients of these error generators, and should be real except for the 2basislabel case.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing errorgenerator coefficients.
 logscale_nonhambool, optional
Whether or not the values in lindblad_term_dict for nonhamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see
errorgen_coefficients()
) instead of raw coefficients. If True, then the nonhamiltonian coefficients are set to log(1  d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the functionset_error_rates()
. truncatebool, optional
Whether to allow adjustment of the errogen coefficients in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given coefficients cannot be set as specified.
Returns
None
 set_error_rates(lindblad_term_dict, action='update')
Sets the coeffcients of terms in the error generator of this operation.
Values are set so that the contributions of the resulting channel’s error rate are given by the values in lindblad_term_dict. See
error_rates()
for more details.Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case, when they may be complex.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing error rates.
Returns
None
 class pygsti.modelmembers.operations.DenseOperator(mx, basis, evotype, state_space=None)
Bases:
DenseOperatorInterface
,pygsti.modelmembers.operations.krausop.KrausOperatorInterface
,pygsti.modelmembers.operations.linearop.LinearOperator
TODO: update docstring An operator that behaves like a dense superoperator matrix.
This class is the common base class for more specific dense operators.
Parameters
 mxnumpy.ndarray
The operation as a dense process matrix.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Attributes
 basenumpy.ndarray
Direct access to the underlying process matrix data.
Initialize a new LinearOperator
 property kraus_operators
A list of this operation’s Kraus operators as numpy arrays.
 classmethod from_kraus_operators(kraus_operators, basis='pp', evotype='default', state_space=None)
Create an operation by specifying its Kraus operators.
Parameters
 kraus_operatorslist
A list of numpy arrays, each of which specifyies a Kraus operator.
 basisstr or Basis, optional
The basis in which the created operator’s superoperator representation is in.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 to_dense(on_space='minimal')
Return the dense array used to represent this operation within its evolution type.
Note: for efficiency, this doesn’t copy the underlying data, so the caller should copy this data before modifying it.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.DenseOperatorInterface
Bases:
object
Adds a numpyarraymimicing interface onto an operation object.
 to_array()
Return the array used to identify this operation within its range of possible values.
For instance, if the operation is a unitary operation, this returns a unitary matrix regardless of the evolution type. The related
to_dense()
method, in contrast, returns the dense representation of the operation, which varies by evolution type.Note: for efficiency, this doesn’t copy the underlying data, so the caller should copy this data before modifying it.
Returns
numpy.ndarray
 to_sparse(on_space='minimal')
Return the operation as a sparse matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
scipy.sparse.csr_matrix
 class pygsti.modelmembers.operations.DepolarizeOp(state_space, basis='PP', evotype='default', initial_rate=0, seed_or_state=None)
Bases:
pygsti.modelmembers.operations.stochasticop.StochasticNoiseOp
A depolarizing channel.
Parameters
 state_spaceStateSpace, optional
The state space for this operation.
 basisBasis or {‘pp’,’gm’,’qt’}, optional
The basis to use, defining the “principle axes” along which there is stochastic noise. While strictly unnecessary since all complete bases yield the same operator, this affects the underlying
StochasticNoiseOp
and so is given as an option to the user. evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 initial_ratefloat, optional
the initial error rate.
 seed_or_statefloat or RandomState, optional
Random seed for RandomState (or directly provided RandomState) for sampling stochastic superoperators with the ‘chp’ evotype.
Initialize a new LinearOperator
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.EigenvalueParamDenseOp(matrix, include_off_diags_in_degen_blocks=False, tp_constrained_and_unital=False, basis=None, 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
 matrixnumpy 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_blocksbool or int
If True, include as parameters the (initially zero) offdiagonal elements in degenerate blocks of the the diagonalized operation matrix. If an integer, no offdiagonals are included in blocks larger than n x n, where n == include_off_diags_in_degen_blocks. This is an option specifically used in the pergermpower fiducial pair reduction (FPR) algorithm.
 tp_constrained_and_unitalbool
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 (notparamterized) eigenvalue with eigenvector [1,…0] and if include_off_diags_in_degen_blocks is True any off diagonal elements lying on the top row are not parameterized as implied by the TP constraint.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 to_memoized_dict(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.
 to_vector()
Extract a vector of the underlying operation parameters from this operation.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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)
 class pygsti.modelmembers.operations.EmbeddedErrorgen(state_space, target_labels, errgen_to_embed)
Bases:
pygsti.modelmembers.operations.embeddedop.EmbeddedOp
An error generator containing a single lower (or equal) dimensional operation within it.
An EmbeddedErrorGen acts as the null map (zero) on all of its domain except the subspace of its contained error generator, where it acts as the contained item does.
Parameters
 state_spaceStateSpace
Specifies the density matrix space upon which this operation acts.
 target_labelslist of strs
The labels contained in state_space which demarcate the portions of the state space acted on by errgen_to_embed (the “contained” error generator).
 errgen_to_embedLinearOperator
The error generator object that is to be contained within this error generator, and that specifies the only nontrivial action of the EmbeddedErrorgen.
Initialize a new LinearOperator
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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
 coefficients(return_basis=False, logscale_nonham=False)
Constructs a dictionary of the Lindbladerrorgenerator coefficients of this operation.
Note that these are not necessarily the parameter values, as these coefficients are generally functions of the parameters (so as to keep the coefficients positive, for instance).
Parameters
 return_basisbool
Whether to also return a
Basis
containing the elements with which the error generator terms were constructed. logscale_nonhambool, optional
Whether or not the nonhamiltonian error generator coefficients should be scaled so that the returned dict contains: (1  exp(d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by
error_rates()
.
Returns
 Ltermdictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Basis labels are integers starting at 0. Values are complex coefficients.
 basisBasis
A Basis mapping the basis labels used in the keys of Ltermdict to basis matrices.
 coefficient_labels()
The elementary errorgenerator labels corresponding to the elements of
coefficients_array()
.Returns
 tuple
A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 coefficients_array()
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by
coefficients()
, weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.Returns
 numpy.ndarray
A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this error generator.
 coefficients_array_deriv_wrt_params()
The jacobian of
coefficients_array()
with respect to this error generator’s parameters.Returns
 numpy.ndarray
A 2D array of shape (num_coeffs, num_params) where num_coeffs is the number of coefficients in the linear combination of standard error generators that is this error generator, and num_params is this error generator’s number of parameters.
 error_rates()
Constructs a dictionary of the error rates associated with this error generator.
These error rates pertain to the channel formed by exponentiating this object.
The “error rate” for an individual Hamiltonian error is the angle about the “axis” (generalized in the multiqubit case) corresponding to a particular basis element, i.e. theta in the unitary channel U = exp(i * theta/2 * BasisElement).
The “error rate” for an individual Stochastic error is the contribution that basis element’s term would have to the error rate of a depolarization channel. For example, if the rate corresponding to the term (‘S’,’X’) is 0.01 this means that the coefficient of the rho > X*rho*Xrho error generator is set such that if this coefficient were used for all 3 (X,Y, and Z) terms the resulting depolarizing channel would have error rate 3*0.01 = 0.03.
Note that because error generator terms do not necessarily commute with one another, the sum of the returned error rates is not necessarily the error rate of the overall channel.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case.
 set_coefficients(lindblad_term_dict, action='update', logscale_nonham=False, truncate=True)
Sets the coefficients of terms in this error generator.
The dictionary lindblad_term_dict has tuplekeys describing the type of term and the basis elements used to construct it, e.g. (‘H’,’X’).
Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are the coefficients of these error generators, and should be real except for the 2basislabel case.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing errorgenerator coefficients.
 logscale_nonhambool, optional
Whether or not the values in lindblad_term_dict for nonhamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see
errorgen_coefficients()
) instead of raw coefficients. If True, then the nonhamiltonian coefficients are set to log(1  d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the functionset_error_rates()
. truncatebool, optional
Whether to truncate the projections onto the Lindblad terms in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given coefficients cannot be parameterized as specified.
Returns
None
 set_error_rates(lindblad_term_dict, action='update')
Sets the coeffcients of terms in this error generator.
Coefficients are set so that the contributions of the resulting channel’s error rate are given by the values in lindblad_term_dict. See
error_rates()
for more details.Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case, when they may be complex.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing error rates.
Returns
None
 deriv_wrt_params(wrt_filter=None)
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened error generator matrix with respect to a single operator parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
Parameters
 wrt_filterlist 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)
 hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this error generator with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension^2, num_params1, num_params2)
 class pygsti.modelmembers.operations.EmbeddedOp(state_space, target_labels, operation_to_embed, allocated_to_parent=None)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
An operation containing a single lower (or equal) dimensional operation within it.
An EmbeddedOp acts as the identity on all of its domain except the subspace of its contained operation, where it acts as the contained operation does.
Parameters
 state_spaceStateSpace
Specifies the density matrix space upon which this operation acts.
 target_labelslist of strs
The labels contained in state_space which demarcate the portions of the state space acted on by operation_to_embed (the “contained” operation).
 operation_to_embedLinearOperator
The operation object that is to be contained within this operation, and that specifies the only nontrivial action of the EmbeddedOp.
Initialize a new LinearOperator
 property parameter_labels
An array of labels (usually strings) describing this model member’s parameters.
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 set_time(t)
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
Parameters
 tfloat
The current time.
Returns
None
 to_sparse(on_space='minimal')
Return the operation as a sparse matrix
Returns
scipy.sparse.csr_matrix
 to_dense(on_space='minimal')
Return the operation as a dense matrix
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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 with shape (dimension^2, num_params)
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get.
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 taylor_order_terms_above_mag(order, max_polynomial_vars, min_term_mag)
Get the orderth order Taylorexpansion terms of this operation that have magnitude above min_term_mag.
This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls
taylor_order_terms()
internally, so that all the terms at order order are typically cached for future calls.The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get (and filter).
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 min_term_magfloat
the minimum term magnitude.
Returns
 list
A list of
Rank1Term
objects.
 abstract transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
In this particular case any TP gauge transformation is possible, i.e. when s is an instance of TPGaugeGroupElement or corresponds to a TPlike transform matrix.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 errorgen_coefficients(return_basis=False, logscale_nonham=False)
Constructs a dictionary of the Lindbladerrorgenerator coefficients of this operation.
Note that these are not necessarily the parameter values, as these coefficients are generally functions of the parameters (so as to keep the coefficients positive, for instance).
Parameters
 return_basisbool, optional
Whether to also return a
Basis
containing the elements with which the error generator terms were constructed. logscale_nonhambool, optional
Whether or not the nonhamiltonian error generator coefficients should be scaled so that the returned dict contains: (1  exp(d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by
error_rates()
.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Basis labels are integers starting at 0. Values are complex coefficients.
 basisBasis
A Basis mapping the basis labels used in the keys of lindblad_term_dict to basis matrices.
 errorgen_coefficient_labels()
The elementary errorgenerator labels corresponding to the elements of
errorgen_coefficients_array()
.Returns
 tuple
A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 errorgen_coefficients_array()
The weighted coefficients of this operation’s error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by
errorgen_coefficients()
, weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.Returns
 numpy.ndarray
A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this operation’s error generator.
 errorgen_coefficients_array_deriv_wrt_params()
The jacobian of
errogen_coefficients_array()
with respect to this operation’s parameters.Returns
 numpy.ndarray
A 2D array of shape (num_coeffs, num_params) where num_coeffs is the number of coefficients of this operation’s error generator and num_params is this operation’s number of parameters.
 error_rates()
Constructs a dictionary of the error rates associated with this operation.
The “error rate” for an individual Hamiltonian error is the angle about the “axis” (generalized in the multiqubit case) corresponding to a particular basis element, i.e. theta in the unitary channel U = exp(i * theta/2 * BasisElement).
The “error rate” for an individual Stochastic error is the contribution that basis element’s term would have to the error rate of a depolarization channel. For example, if the rate corresponding to the term (‘S’,’X’) is 0.01 this means that the coefficient of the rho > X*rho*Xrho error generator is set such that if this coefficient were used for all 3 (X,Y, and Z) terms the resulting depolarizing channel would have error rate 3*0.01 = 0.03.
Note that because error generator terms do not necessarily commute with one another, the sum of the returned error rates is not necessarily the error rate of the overall channel.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case.
 set_errorgen_coefficients(lindblad_term_dict, action='update', logscale_nonham=False, truncate=True)
Sets the coefficients of terms in the error generator of this operation.
The dictionary lindblad_term_dict has tuplekeys describing the type of term and the basis elements used to construct it, e.g. (‘H’,’X’).
Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are the coefficients of these error generators, and should be real except for the 2basislabel case.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing errorgenerator coefficients.
 logscale_nonhambool, optional
Whether or not the values in lindblad_term_dict for nonhamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see
errorgen_coefficients()
) instead of raw coefficients. If True, then the nonhamiltonian coefficients are set to log(1  d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the functionset_error_rates()
. truncatebool, optional
Whether to allow adjustment of the errogen coefficients in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given coefficients cannot be set as specified.
Returns
None
 set_error_rates(lindblad_term_dict, action='update')
Sets the coeffcients of terms in the error generator of this operation.
Values are set so that the contributions of the resulting channel’s error rate are given by the values in lindblad_term_dict. See
error_rates()
for more details.Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case, when they may be complex.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing error rates.
Returns
None
 depolarize(amount)
Depolarize this operation by the given amount.
Generally, the depolarize function updates the parameters of the operation such that the resulting operation matrix is depolarized. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 amountfloat or tuple
The amount to depolarize by. If a tuple, it must have length equal to one less than the dimension of the operation. In standard bases, depolarization corresponds to multiplying the operation matrix by a diagonal matrix whose first diagonal element (corresponding to the identity) equals 1.0 and whose subsequent elements (corresponding to nonidentity basis elements) equal 1.0  amount[i] (or just 1.0  amount if amount is a float).
Returns
None
 rotate(amount, mx_basis='gm')
Rotate this operation by the given amount.
Generally, the rotate function updates the parameters of the operation such that the resulting operation matrix is rotated. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 amounttuple of floats, optional
Specifies the rotation “coefficients” along each of the nonidentity Pauliproduct axes. The operation’s matrix G is composed with a rotation operation R (so G > dot(R, G) ) where R is the unitary superoperator corresponding to the unitary operator U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) ). Here Pauli_k ranges over all of the nonidentity unnormalized Pauli operators.
 mx_basis{‘std’, ‘gm’, ‘pp’, ‘qt’} or Basis object
The source and destination basis, respectively. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
Returns
None
 has_nonzero_hessian()
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
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.ExpErrorgenOp(errorgen)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
,pygsti.modelmembers.errorgencontainer.ErrorGeneratorContainer
An operation parameterized by the coefficients of an exponentiated sum of Lindbladlike terms. TODO: update docstring!
The exponentiated terms give the operation’s action.
Parameters
 errorgenLinearOperator
The error generator for this operator. That is, the L if this operator is exp(L).
Initialize a new LinearOperator
 property parameter_labels
An array of labels (usually strings) describing this model member’s parameters.
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 set_gpindices(gpindices, parent, memo=None)
Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.
Parameters
 gpindicesslice or integer ndarray
The indices of this objects parameters in its parent’s array.
 parentModel or ModelMember
The parent whose parameter array gpindices references.
 memodict, optional
A memo dict used to avoid circular references.
Returns
None
 to_sparse(on_space='minimal')
Return the operation as a sparse matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
scipy.sparse.csr_matrix
 deriv_wrt_params(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_filterlist 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()
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
 hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this operation with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension^2, num_params1, num_params2)
 to_vector()
Extract a vector of the underlying operation parameters from this operation.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve. max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 taylor_order_terms_above_mag(order, max_polynomial_vars, min_term_mag)
Get the orderth order Taylorexpansion terms of this operation that have magnitude above min_term_mag.
This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls
taylor_order_terms()
internally, so that all the terms at order order are typically cached for future calls.The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get (and filter).
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 min_term_magfloat
the minimum term magnitude.
Returns
 list
A list of
Rank1Term
objects.
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes mx. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 spam_transform_inplace(s, typ)
Update operation matrix O with inv(s) * O OR O * s, depending on the value of typ.
This functions as transform_inplace(…) but is used when this operation is used as a part of a SPAM vector. When typ == “prep”, the spam vector is assumed to be rho = dot(self, <spamvec>), which transforms as rho > inv(s) * rho, so self > inv(s) * self. When typ == “effect”, e.dag = dot(e.dag, self) (note that self is NOT self.dag here), and e.dag > e.dag * s so that self > self * s.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 typ{ ‘prep’, ‘effect’ }
Which type of SPAM vector is being transformed (see above).
Returns
None
 class pygsti.modelmembers.operations.IdentityPlusErrorgenOp(errorgen)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
,pygsti.modelmembers.errorgencontainer.ErrorGeneratorContainer
An operation consisting of the identity added to what would ordinarily be an error generator.
This is the firstorder expansion, exp(L) = 1 + L, and yields a CPTP map whenever L is a valid Lindbladian.
Parameters
 errorgenLinearOperator
The error generator for this operator.
Initialize a new LinearOperator
 property parameter_labels
An array of labels (usually strings) describing this model member’s parameters.
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 set_gpindices(gpindices, parent, memo=None)
Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.
Parameters
 gpindicesslice or integer ndarray
The indices of this objects parameters in its parent’s array.
 parentModel or ModelMember
The parent whose parameter array gpindices references.
 memodict, optional
A memo dict used to avoid circular references.
Returns
None
 to_sparse(on_space='minimal')
Return the operation as a sparse matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
scipy.sparse.csr_matrix
 deriv_wrt_params(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_filterlist 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()
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
 hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this operation with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension^2, num_params1, num_params2)
 to_vector()
Extract a vector of the underlying operation parameters from this operation.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve. max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 taylor_order_terms_above_mag(order, max_polynomial_vars, min_term_mag)
Get the orderth order Taylorexpansion terms of this operation that have magnitude above min_term_mag.
This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls
taylor_order_terms()
internally, so that all the terms at order order are typically cached for future calls.The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get (and filter).
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 min_term_magfloat
the minimum term magnitude.
Returns
 list
A list of
Rank1Term
objects.
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes mx. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 abstract transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 abstract spam_transform_inplace(s, typ)
Update operation matrix O with inv(s) * O OR O * s, depending on the value of typ.
This functions as transform_inplace(…) but is used when this operation is used as a part of a SPAM vector. When typ == “prep”, the spam vector is assumed to be rho = dot(self, <spamvec>), which transforms as rho > inv(s) * rho, so self > inv(s) * self. When typ == “effect”, e.dag = dot(e.dag, self) (note that self is NOT self.dag here), and e.dag > e.dag * s so that self > self * s.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 typ{ ‘prep’, ‘effect’ }
Which type of SPAM vector is being transformed (see above).
Returns
None
 class pygsti.modelmembers.operations.FullArbitraryOp(m, basis=None, evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
An operation matrix that is fully parameterized.
That is, each element of the operation matrix is an independent parameter.
Parameters
 marray_like or LinearOperator
a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes mx. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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 with shape (dimension^2, num_params)
 class pygsti.modelmembers.operations.FullTPOp(m, basis=None, evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
A tracepreserving operation matrix.
An operation matrix that is fully parameterized except for the first row, which is frozen to be [1 0 … 0] so that the action of the operation, when interpreted in the Pauli or GellMann basis, is trace preserving (TP).
Parameters
 marray_like or LinearOperator
a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Attributes
 basenumpy.ndarray
Direct access to the underlying process matrix data.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes mx. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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 with shape (dimension^2, num_params)
 class pygsti.modelmembers.operations.FullUnitaryOp(m, basis='pp', evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseUnitaryOperator
An operation matrix that is fully parameterized.
That is, each element of the operation matrix is an independent parameter.
Parameters
 marray_like or LinearOperator
a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
 basisBasis or {‘pp’,’gm’,’std’}, optional
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes mx. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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 with shape (dimension^2, num_params)
 has_nonzero_hessian()
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
 transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 spam_transform_inplace(s, typ)
Update operation matrix O with inv(s) * O OR O * s, depending on the value of typ.
This functions as transform_inplace(…) but is used when this Lindbladparameterized operation is used as a part of a SPAM vector. When typ == “prep”, the spam vector is assumed to be rho = dot(self, <spamvec>), which transforms as rho > inv(s) * rho, so self > inv(s) * self. When typ == “effect”, e.dag = dot(e.dag, self) (not that self is NOT self.dag here), and e.dag > e.dag * s so that self > self * s.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 typ{ ‘prep’, ‘effect’ }
Which type of SPAM vector is being transformed (see above).
Returns
None
 class pygsti.modelmembers.operations.FullCPTPOp(choi_mx, basis, evotype, state_space=None, truncate=False)
Bases:
pygsti.modelmembers.operations.krausop.KrausOperatorInterface
,pygsti.modelmembers.operations.linearop.LinearOperator
TODO: update docstring An operator that is constrained to be CPTP.
This operation is parameterized by (normalized) elements of the Cholesky decomposition of the quantum channel’s Choi matrix.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this state vector.
Returns
 int
the number of independent parameters.
 classmethod from_superop_matrix(superop_mx, basis, evotype, state_space=None, truncate=False)
 to_dense(on_space='minimal')
Return the dense array used to represent this operation within its evolution type.
Note: for efficiency, this doesn’t copy the underlying data, so the caller should copy this data before modifying it.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_vector()
Get the state vector parameters as an array of values.
Returns
 numpy array
The parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the state vector using a 1D array of parameters.
Parameters
 vnumpy array
The 1D vector of state vector parameters. Length must == num_params()
 closebool, optional
Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
 dirty_valuebool, 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
 abstract deriv_wrt_params(wrt_filter=None)
The elementwise derivative this state vector.
Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.
Parameters
 wrt_filterlist 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()
Whether this state vector has a nonzero Hessian with respect to its parameters.
Returns
bool
 abstract hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this state vector with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension, num_params1, num_params2)
 class pygsti.modelmembers.operations.LindbladErrorgen(lindblad_coefficient_blocks, lindblad_basis='auto', mx_basis='pp', evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
An Lindbladform error generator.
This error generator consisting of terms that, with appropriate constraints ensurse that the resulting (after exponentiation) operation/layer operation is CPTP. These terms can be divided into “Hamiltonian”type terms, which map rho > i[H,rho] and “nonHamiltonian”/”other”type terms, which map rho > A rho B + 0.5*(ABrho + rhoAB).
Parameters
 dimint
The HilbertSchmidt (superoperator) dimension, which will be the dimension of the created operator.
 lindblad_term_dictdict
A dictionary specifying which Linblad terms are present in the parameteriztion. Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType can be “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples with 1 basis label indicate a diagonal term, and are the only types of terms allowed when nonham_mode != “all”. Otherwise, Stochastic term tuples can include 2 basis labels to specify “offdiagonal” nonHamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients.
 basisBasis, optional
A basis mapping the labels used in the keys of lindblad_term_dict to basis matrices (e.g. numpy arrays or Scipy sparse matrices).
 param_mode{“unconstrained”, “cptp”, “depol”, “reldepol”}
Describes how the Lindblad coefficients/projections relate to the error generator’s parameter values. Allowed values are: “unconstrained” (coeffs are independent unconstrained parameters), “cptp” (independent parameters but constrained so map is CPTP), “reldepol” (all nonHam. diagonal coeffs take the same value), “depol” (same as “reldepol” but coeffs must be positive)
 nonham_mode{“diagonal”, “diag_affine”, “all”}
Which nonHamiltonian Lindblad projections are potentially nonzero. Allowed values are: “diagonal” (only the diagonal Lind. coeffs.), “diag_affine” (diagonal coefficients + affine projections), and “all” (the entire matrix of coefficients is allowed).
 truncatebool, optional
Whether to truncate the projections onto the Lindblad terms in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given dictionary of Lindblad terms doesn’t conform to the constrains.
 mx_basis{‘std’, ‘gm’, ‘pp’, ‘qt’} or Basis object
The basis for this error generator’s linear mapping. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
 evotype{“densitymx”,”svterm”,”cterm”}
The evolution type of the error generator being constructed. “densitymx” means the usual Lioville densitymatrixvector propagation via matrixvector products. “svterm” denotes statevector termbased evolution (action of operation is obtained by evaluating the rank1 terms up to some order). “cterm” is similar but uses Clifford operation action on stabilizer states.
Initialize a new LinearOperator
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 classmethod from_operation_matrix_and_blocks(op_matrix, lindblad_coefficient_blocks, lindblad_basis='auto', mx_basis='pp', truncate=True, evotype='default', state_space=None)
 classmethod from_operation_matrix(op_matrix, parameterization='CPTP', lindblad_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)
Creates a Lindbladparameterized error generator from an operation.
Here “operation” means the exponentiated error generator, so this method essentially takes the matrix log of op_matrix and constructs an error generator from this using
from_error_generator()
.Parameters
 op_matrixnumpy array or SciPy sparse matrix
a square 2D array that gives the raw operation matrix, assumed to be in the mx_basis basis, to parameterize. The shape of this array sets the dimension of the operation. If None, then it is assumed equal to unitary_postfactor (which cannot also be None). The quantity op_matrix inv(unitary_postfactor) is parameterized via projection onto the Lindblad terms.
 ham_basis{‘std’, ‘gm’, ‘pp’, ‘qt’}, list of matrices, or Basis object
The basis is used to construct the Hamiltoniantype lindblad error Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.
 nonham_basis{‘std’, ‘gm’, ‘pp’, ‘qt’}, list of matrices, or Basis object
The basis is used to construct the nonHamiltonian (generalized Stochastictype) lindblad error Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.
 param_mode{“unconstrained”, “cptp”, “depol”, “reldepol”}
Describes how the Lindblad coefficients/projections relate to the operation’s parameter values. Allowed values are: “unconstrained” (coeffs are independent unconstrained parameters), “cptp” (independent parameters but constrained so map is CPTP), “reldepol” (all nonHam. diagonal coeffs take the same value), “depol” (same as “reldepol” but coeffs must be positive)
 nonham_mode{“diagonal”, “diag_affine”, “all”}
Which nonHamiltonian Lindblad projections are potentially nonzero. Allowed values are: “diagonal” (only the diagonal Lind. coeffs.), “diag_affine” (diagonal coefficients + affine projections), and “all” (the entire matrix of coefficients is allowed).
 truncatebool, optional
Whether to truncate the projections onto the Lindblad terms in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given operation cannot be realized by the specified set of Lindblad projections.
 mx_basis{‘std’, ‘gm’, ‘pp’, ‘qt’} or Basis object
The source and destination basis, respectively. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space : TODO docstring
Returns
LindbladOp
 classmethod from_error_generator(errgen_or_dim, parameterization='CPTP', lindblad_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)
TODO: docstring  take from nowprivate version below Note: errogen_or_dim can be an integer => zero errgen
 classmethod from_error_generator_and_blocks(errgen_or_dim, lindblad_coefficient_blocks, lindblad_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)
TODO: docstring  take from nowprivate version below Note: errogen_or_dim can be an integer => zero errgen
 classmethod from_elementary_errorgens(elementary_errorgens, parameterization='auto', elementary_errorgen_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)
TODO: docstring
 to_dense(on_space='minimal')
Return this error generator as a dense matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_sparse(on_space='minimal')
Return the error generator as a sparse matrix.
Returns
scipy.sparse.csr_matrix
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get.
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 to_vector()
Extract a vector of the underlying operation parameters from this operation.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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
 coefficients(return_basis=False, logscale_nonham=False)
TODO: docstring Constructs a dictionary of the Lindbladerrorgenerator coefficients of this error generator.
Note that these are not necessarily the parameter values, as these coefficients are generally functions of the parameters (so as to keep the coefficients positive, for instance).
Parameters
 return_basisbool
Whether to also return a
Basis
containing the elements with which the error generator terms were constructed. logscale_nonhambool, optional
Whether or not the nonhamiltonian error generator coefficients should be scaled so that the returned dict contains: (1  exp(d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by
error_rates()
.
Returns
 Ltermdictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Basis labels are integers starting at 0. Values are complex coefficients.
 basisBasis
A Basis mapping the basis labels used in the keys of Ltermdict to basis matrices.
 coefficient_labels()
The elementary errorgenerator labels corresponding to the elements of
coefficients_array()
.Returns
 tuple
A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 coefficients_array()
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by
coefficients()
, weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.Returns
 numpy.ndarray
A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this error generator.
 coefficients_array_deriv_wrt_params()
The jacobian of
coefficients_array()
with respect to this error generator’s parameters.Returns
 numpy.ndarray
A 2D array of shape (num_coeffs, num_params) where num_coeffs is the number of coefficients in the linear combination of standard error generators that is this error generator, and num_params is this error generator’s number of parameters.
 error_rates()
Constructs a dictionary of the error rates associated with this error generator.
The error rates pertain to the channel formed by exponentiating this object.
The “error rate” for an individual Hamiltonian error is the angle about the “axis” (generalized in the multiqubit case) corresponding to a particular basis element, i.e. theta in the unitary channel U = exp(i * theta/2 * BasisElement).
The “error rate” for an individual Stochastic error is the contribution that basis element’s term would have to the error rate of a depolarization channel. For example, if the rate corresponding to the term (‘S’,’X’) is 0.01 this means that the coefficient of the rho > X*rho*Xrho error generator is set such that if this coefficient were used for all 3 (X,Y, and Z) terms the resulting depolarizing channel would have error rate 3*0.01 = 0.03.
Note that because error generator terms do not necessarily commute with one another, the sum of the returned error rates is not necessarily the error rate of the overall channel.
Returns
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case.
 set_coefficients(elementary_errorgens, action='update', logscale_nonham=False, truncate=True)
Sets the coefficients of elementary error generator terms in this error generator.
TODO: docstring update The dictionary lindblad_term_dict has tuplekeys describing the type of term and the basis elements used to construct it, e.g. (‘H’,’X’).
Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are the coefficients of these error generators, and should be real except for the 2basislabel case.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing errorgenerator coefficients.
 logscale_nonhambool, optional
Whether or not the values in lindblad_term_dict for nonhamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see
errorgen_coefficients()
) instead of raw coefficients. If True, then the nonhamiltonian coefficients are set to log(1  d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the functionset_error_rates()
. truncatebool, optional
Whether to truncate the projections onto the Lindblad terms in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given coefficients cannot be parameterized as specified.
Returns
None
 set_error_rates(elementary_errorgens, action='update')
Sets the coeffcients of elementary error generator terms in this error generator.
TODO: update docstring Coefficients are set so that the contributions of the resulting channel’s error rate are given by the values in lindblad_term_dict. See
error_rates()
for more details.Parameters
 lindblad_term_dictdict
Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify offdiagonal nonHamiltonian Lindblad terms. Values are real error rates except for the 2basislabel case, when they may be complex.
 action{“update”,”add”,”reset”}
How the values in lindblad_term_dict should be combined with existing error rates.
Returns
None
 coefficient_weights(weights)
TODO: docstring
 set_coefficient_weights(weights)
TODO: docstring
 transform_inplace(s)
Update error generator E with inv(s) * E * s,
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 deriv_wrt_params(wrt_filter=None)
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened error generator matrix with respect to a single operator parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
Parameters
 wrt_filterlist 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)
 hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this error generator with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension^2, num_params1, num_params2)
 onenorm_upperbound()
Returns an upper bound on the 1norm for this error generator (viewed as a matrix).
Returns
float
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.LindbladParameterization(block_types, param_modes, abbrev=None, meta=None)
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
An object encapsulating a particular way of parameterizing a LindbladErrorgen
A LindbladParameterization is a highlevel parameterizationtype (e.g. “H+S”) that contains two “modes”  one describing the number (and structure) of the nonHamiltonian Lindblad coefficients (nonham_mode’) and one describing how the Lindblad coefficients are converted to/from parameters (`param_mode).
Parameters
 nonham_modestr
The “nonHamiltonian mode” describes which nonHamiltonian Lindblad coefficients are stored in a LindbladOp, and is one of “diagonal” (only the diagonal elements of the full coefficient matrix as a 1D array), “diag_affine” (a 2byd array of the diagonal coefficients on top of the affine projections), or “all” (the entire coefficient matrix).
 param_modestr
The “parameter mode” describes how the Lindblad coefficients/projections are converted into parameter values. This can be: “unconstrained” (coefficients are independent unconstrained parameters), “cptp” (independent parameters but constrained so map is CPTP), “depol” (all nonHam. diagonal coeffs are the same, positive value), or “reldepol” (same as “depol” but no positivity constraint).
 ham_params_allowed, nonham_params_allowedbool
Whether or not Hamiltonian and nonHamiltonian parameters are allowed.
 classmethod minimal_from_elementary_errorgens(errs)
Helper function giving minimal Lindblad parameterization needed for specified errors.
Parameters
 errsdict
Error dictionary with keys as (termType, basisLabel) tuples, where termType can be “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine), and basisLabel is a string of I, X, Y, or Z to describe a Pauli basis element appropriate for the gate (i.e. having the same number of letters as there are qubits in the gate). For example, you could specify a 0.01radian Zrotation error and 0.05 rate of Pauli stochastic X errors on a 1qubit gate by using the error dictionary: {(‘H’,’Z’): 0.01, (‘S’,’X’): 0.05}.
Returns
 parameterizationstr
Parameterization string for constructing Lindblad error generators.
 class pygsti.modelmembers.operations.LinearOperator(rep, evotype)
Bases:
pygsti.modelmembers.modelmember.ModelMember
Base class for all operation representations
Parameters
 repobject
A representation object containing the core data for this operator.
 evotypeEvotype
The evolution type.
Attributes
 sizeint
Return the number of independent elements in this operation (when viewed as a dense array)
 dirtybool
Whether this object has been modified in a way that could have affected its parameters. A parent
OpModel
uses this information to know when it needs to refresh it’s modelwide parameter vector.
Initialize a new LinearOperator
 property hilbert_schmidt_size
Return the number of independent elements in this operation as a dense HilbertSchmidt superoperator.
Returns
int
 property chp_str
A string suitable for printing to a CHP input file after probabilistically selecting operation.
Returns
 sstr
String of CHP code
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes mx. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 set_time(t)
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
Parameters
 tfloat
The current time.
Returns
None
 abstract to_dense(on_space='minimal')
Return this operation as a dense matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 acton(state, on_space='minimal')
Act with this operator upon state
Parameters
 stateState
The state to act on
Returns
 State
The output state
 abstract to_sparse(on_space='minimal')
Return this operation as a sparse matrix.
Returns
scipy.sparse.csr_matrix
 abstract taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get.
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 highmagnitude_terms(min_term_mag, force_firstorder=True, max_taylor_order=3, max_polynomial_vars=100)
Get terms with magnitude above min_term_mag.
Get the terms (from a Taylor expansion of this operator) that have magnitude above min_term_mag (the magnitude of a term is taken to be the absolute value of its coefficient), considering only those terms up to some maximum Taylor expansion order, max_taylor_order.
Note that this function also sets the magnitudes of the returned terms (by calling term.set_magnitude(…)) based on the current values of this operator’s parameters. This is an essential step to using these terms in prunedpathintegral calculations later on.
Parameters
 min_term_magfloat
the threshold for term magnitudes: only terms with magnitudes above this value are returned.
 force_firstorderbool, optional
if True, then always return all the firstorder Taylorseries terms, even if they have magnitudes smaller than min_term_mag. This behavior is needed for using GST with prunedterm calculations, as we may begin with a guess model that has no error (all terms have zero magnitude!) and still need to compute a meaningful jacobian at this point.
 max_taylor_orderint, optional
the maximum Taylororder to consider when checking whether term magnitudes exceed min_term_mag.
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
Returns
 highmag_termslist
A list of the highmagnitude terms that were found. These terms are sorted in descending order by termmagnitude.
 first_order_indiceslist
A list of the indices into highmag_terms that mark which of these terms are firstorder Taylor terms (useful when we’re forcing these terms to always be present).
 taylor_order_terms_above_mag(order, max_polynomial_vars, min_term_mag)
Get the orderth order Taylorexpansion terms of this operation that have magnitude above min_term_mag.
This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls
taylor_order_terms()
internally, so that all the terms at order order are typically cached for future calls.The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
The order of terms to get (and filter).
 max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 min_term_magfloat
the minimum term magnitude.
Returns
 list
A list of
Rank1Term
objects.
 frobeniusdist_squared(other_op, transform=None, inv_transform=None)
Return the squared frobenius difference between this operation and other_op
Optionally transforms this operation first using matrices transform and inv_transform. Specifically, this operation gets transfomed as: O => inv_transform * O * transform before comparison with other_op.
Parameters
 other_opDenseOperator
The other operation.
 transformnumpy.ndarray, optional
Transformation matrix.
 inv_transformnumpy.ndarray, optional
Inverse of transform.
Returns
float
 frobeniusdist(other_op, transform=None, inv_transform=None)
Return the frobenius distance between this operation and other_op.
Optionally transforms this operation first using matrices transform and inv_transform. Specifically, this operation gets transfomed as: O => inv_transform * O * transform before comparison with other_op.
Parameters
 other_opDenseOperator
The other operation.
 transformnumpy.ndarray, optional
Transformation matrix.
 inv_transformnumpy.ndarray, optional
Inverse of transform.
Returns
float
 residuals(other_op, transform=None, inv_transform=None)
The perelement difference between this DenseOperator and other_op.
Optionally, tansforming this operation first as O => inv_transform * O * transform.
Parameters
 other_opDenseOperator
The operation to compare against.
 transformnumpy.ndarray, optional
Transformation matrix.
 inv_transformnumpy.ndarray, optional
Inverse of transform.
Returns
 numpy.ndarray
A 1Darray of size equal to that of the flattened operation matrix.
 jtracedist(other_op, transform=None, inv_transform=None)
Return the Jamiolkowski trace distance between this operation and other_op.
Optionally, tansforming this operation first as O => inv_transform * O * transform.
Parameters
 other_opDenseOperator
The operation to compare against.
 transformnumpy.ndarray, optional
Transformation matrix.
 inv_transformnumpy.ndarray, optional
Inverse of transform.
Returns
float
 diamonddist(other_op, transform=None, inv_transform=None)
Return the diamond distance between this operation and other_op.
Optionally, tansforming this operation first as O => inv_transform * O * transform.
Parameters
 other_opDenseOperator
The operation to compare against.
 transformnumpy.ndarray, optional
Transformation matrix.
 inv_transformnumpy.ndarray, optional
Inverse of transform.
Returns
float
 transform_inplace(s)
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
In this particular case any transform of the appropriate dimension is possible, since all operation matrix elements are parameters.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
Returns
None
 spam_transform_inplace(s, typ)
Update operation matrix O with inv(s) * O OR O * s, depending on the value of typ.
This functions as transform_inplace(…) but is used when this operation is used as a part of a SPAM vector. When typ == “prep”, the spam vector is assumed to be rho = dot(self, <spamvec>), which transforms as rho > inv(s) * rho, so self > inv(s) * self. When typ == “effect”, e.dag = dot(e.dag, self) (note that self is NOT self.dag here), and e.dag > e.dag * s so that self > self * s.
Parameters
 sGaugeGroupElement
A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 typ{ ‘prep’, ‘effect’ }
Which type of SPAM vector is being transformed (see above).
Returns
None
 depolarize(amount)
Depolarize this operation by the given amount.
Generally, the depolarize function updates the parameters of the operation such that the resulting operation matrix is depolarized. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 amountfloat or tuple
The amount to depolarize by. If a tuple, it must have length equal to one less than the dimension of the operation. In standard bases, depolarization corresponds to multiplying the operation matrix by a diagonal matrix whose first diagonal element (corresponding to the identity) equals 1.0 and whose subsequent elements (corresponding to nonidentity basis elements) equal 1.0  amount[i] (or just 1.0  amount if amount is a float).
Returns
None
 rotate(amount, mx_basis='gm')
Rotate this operation by the given amount.
Generally, the rotate function updates the parameters of the operation such that the resulting operation matrix is rotated. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
Parameters
 amounttuple of floats, optional
Specifies the rotation “coefficients” along each of the nonidentity Pauliproduct axes. The operation’s matrix G is composed with a rotation operation R (so G > dot(R, G) ) where R is the unitary superoperator corresponding to the unitary operator U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) ). Here Pauli_k ranges over all of the nonidentity unnormalized Pauli operators.
 mx_basis{‘std’, ‘gm’, ‘pp’, ‘qt’} or Basis object
The source and destination basis, respectively. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
Returns
None
 deriv_wrt_params(wrt_filter=None)
The elementwise derivative this operation.
Constructs 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. An empty 2D array in the StaticArbitraryOp case (num_params == 0).
Parameters
 wrt_filterlist 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 with shape (dimension^2, num_params)
 has_nonzero_hessian()
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
 hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)
Construct the Hessian of this operation with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
Parameters
 wrt_filter1list or numpy.ndarray
List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
 wrt_filter2list or numpy.ndarray
List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
Returns
 numpy array
Hessian with shape (dimension^2, num_params1, num_params2)
 pygsti.modelmembers.operations.finite_difference_deriv_wrt_params(operation, wrt_filter, eps=1e07)
Computes a finitedifference Jacobian for a LinearOperator object.
The returned value is a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter, matching the format expected from the operation’s deriv_wrt_params method.
Parameters
 operationLinearOperator
The operation object to compute a Jacobian for.
 wrt_filterlist or numpy.ndarray
List of parameter indices to filter the result by (as though derivative is only taken with respect to these parameters).
 epsfloat, optional
The finite difference step to use.
Returns
 numpy.ndarray
An M by N matrix where M is the number of operation elements and N is the number of operation parameters.
 pygsti.modelmembers.operations.finite_difference_hessian_wrt_params(operation, wrt_filter1, wrt_filter2, eps=0.0001)
Computes a finitedifference Hessian for a LinearOperator object.
The returned value is a tensor whose leading dimension corresponds to the elements of the flattened operation matrix, and whose remaining two dimensions correspond to derivatives with respect to the operations parameters (potentially filtered). This matches the format expected from the operation’s hessian_wrt_params method.
Parameters
 operationLinearOperator
The operation object to compute a Hessian for.
 wrt_filter1list or numpy.ndarray
List of parameter indices to filter the result by (as though the 1st derivative is only taken with respect to these parameters).
 wrt_filter2list or numpy.ndarray
List of parameter indices to filter the result by (as though the 2nd derivative is only taken with respect to these parameters).
 epsfloat, optional
The finite difference step to use.
Returns
 numpy.ndarray
An M by N1 by N2 tensor where M is the number of operation elements and N1 and N2 are numbers of operation parameters.
 class pygsti.modelmembers.operations.LinearlyParamArbitraryOp(base_matrix, parameter_array, parameter_to_base_indices_map, left_transform=None, right_transform=None, real=False, basis=None, evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
An operation matrix parameterized such that each element depends only linearly on any parameter.
Parameters
 basematrixnumpy array
a square 2D numpy array that acts as the starting point when constructin the operation’s matrix. The shape of this array sets the dimension of the operation.
 parameter_arraynumpy array
a 1D numpy array that holds the all the parameters for this operation. The shape of this array sets is what is returned by value_dimension(…).
 parameter_to_base_indices_mapdict
A dictionary with keys == index of a parameter (i.e. in parameter_array) and values == list of 2tuples indexing potentially multiple operation matrix coordinates which should be set equal to this parameter.
 left_transformnumpy array or None, optional
A 2D array of the same shape as basematrix which leftmultiplies the base matrix after parameters have been evaluated. Defaults to no transform_inplace.
 right_transformnumpy array or None, optional
A 2D array of the same shape as basematrix which rightmultiplies the base matrix after parameters have been evaluated. Defaults to no transform_inplace.
 realbool, optional
Whether or not the resulting operation matrix, after all parameter evaluation and left & right transforms have been performed, should be real. If True, ValueError will be raised if the matrix contains any complex or imaginary elements.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 to_memoized_dict(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.
 to_vector()
Extract a vector of the underlying operation parameters from this operation.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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)
 class pygsti.modelmembers.operations.OpFactory(state_space, evotype)
Bases:
pygsti.modelmembers.modelmember.ModelMember
An object that can generate “ondemand” operators (can be SPAM vecs, etc., as well) for a Model.
It is assigned certain parameter indices (it’s a ModelMember), which definie the block of indices it may assign to its created operations.
The central method of an OpFactory object is the create_op method, which creates an operation that is associated with a given label. This is very similar to a LayerLizard’s function, though a LayerLizard has detailed knowledge and access to a Model’s internals whereas an OpFactory is meant to create a selfcontained class of operators (e.g. continuously parameterized gates or ondemand embedding).
This class just provides a skeleton for an operation factory  derived classes add the actual code for creating custom objects.
Parameters
 state_spaceStateSpace
The statespace of the operation(s) this factory builds.
 evotypeEvotype
The evolution type of the operation(s) this factory builds.
Initialize a new ModelMember
 abstract create_object(args=None, sslbls=None)
Create the object that implements the operation associated with the given args and sslbls.
Note to developers The difference beween this method and
create_op()
is that this method just creates the foundational object without needing to setup its parameter indices (a technical detail which connects the created object with the originating factory’s parameters). The baseclass create_op method calls create_object and then performs some additional setup on the returned object before returning it itself. Thus, unless you have a reason for implementing create_op it’s often more convenient and robust to implement this function.Parameters
 argslist or tuple
The arguments for the operation to be created. None means no arguments were supplied.
 sslblslist or tuple
The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).
Returns
 ModelMember
Can be any type of operation, e.g. a LinearOperator, SPAMVec, Instrument, or POVM, depending on the label requested.
 create_op(args=None, sslbls=None)
Create the operation associated with the given args and sslbls.
Parameters
 argslist or tuple
The arguments for the operation to be created. None means no arguments were supplied.
 sslblslist or tuple
The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).
Returns
 ModelMember
Can be any type of operation, e.g. a LinearOperator, SPAMVec, Instrument, or POVM, depending on the label requested.
 create_simplified_op(args=None, sslbls=None, item_lbl=None)
Create the simplified operation associated with the given args, sslbls, and item_lbl.
Similar to as
create_op()
, but returns a simplified operation (i.e. not a POVM or Instrument). In addition, the item_lbl argument must be used for POVMs and Instruments, as these need to know which (simple) member of themselves to return (this machinery still needs work).That is, if create_op returns something like a POVM or an Instrument, this method returns a single effect or instrumentmember operation (a single linearoperator or SPAM vector).
Parameters
 argslist or tuple
The arguments for the operation to be created. None means no arguments were supplied.
 sslblslist or tuple
The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).
 item_lblstr, optional
Effect or instrumentmember label (index) for factories that create POVMs or instruments, respectively.
Returns
 ModelMember
Can be any type of siple operation, e.g. a LinearOperator or SPAMVec, depending on the label requested.
 class pygsti.modelmembers.operations.EmbeddedOpFactory(state_space, target_labels, factory_to_embed)
Bases:
OpFactory
A factory that embeds a given factory’s action into a single, predefined set of target sectors.
Parameters
 state_spaceStateSpace
The state space of this factory, describing the space of these that the operations produced by this factory act upon.
 target_labelslist of strs
The labels contained in state_space_labels which demarcate the portions of the state space acted on by the operations produced by factory_to_embed (the “contained” factory).
 factory_to_embedOpFactory
The factory object that is to be contained within this factory, and that specifies the only nontrivial action of the operations this factory produces.
Initialize a new ModelMember
 property num_params
Get the number of independent parameters which specify this OpFactory.
Returns
 int
the number of independent parameters.
 to_memoized_dict(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.
 create_op(args=None, sslbls=None)
Create the operation associated with the given args and sslbls.
Parameters
 argslist or tuple
The arguments for the operation to be created. None means no arguments were supplied.
 sslblslist or tuple
The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).
Returns
 ModelMember
Can be any type of operation, e.g. a LinearOperator, State, Instrument, or POVM, depending on the label requested.
 to_vector()
Extract a vector of the underlying gate parameters from this OpFactory.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize this OpFactory using a vector of its parameters.
Parameters
 vnumpy array
The 1D vector of gate parameters. Length must == num_params().
 closebool, optional
Whether v is close to this factory’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
 dirty_valuebool, 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
 class pygsti.modelmembers.operations.EmbeddingOpFactory(state_space, factory_or_op_to_embed, num_target_labels=None, allowed_sslbls_fn=None)
Bases:
OpFactory
A factory that “ondemand” embeds a given factory or operation into any requested set of target sectors.
This is similar to an EmbeddedOpFactory except in this case how the “contained” operation/factory is embedded is not determined at creation time: the sslbls argument of
create_op()
is used instead.Parameters
 state_spaceStateSpace
The state space of this factory, describing the space of these that the operations produced by this factory act upon.
 factory_or_op_to_embedLinearOperator or OpFactory
The factory or operation object that is to be contained within this factory. If a linear operator, this same operator (not a copy) is embedded however is requested. If a factory, then this object’s create_op method is called with any args that are passed to the embeddingfactory’s create_op method, but the sslbls are always set to None (as they are processed by the embedding
 num_target_labelsint, optional
If not None, the number of target labels that should be expected (usually equal to the number of qubits the contained gate acts upon). If None, then the length of the sslbls passed to this factory’s create_op method is not checked at all.
 allowed_sslbls_fncallable, optional
A boolean function that takes a single sslbls argument specifying the statespace labels for which the factory has been asked to embed factory_or_op_to_embed. If the function returns True then the embedding is allowed, if False then an error is raised.
Initialize a new ModelMember
 property num_params
Get the number of independent parameters which specify this OpFactory.
Returns
 int
the number of independent parameters.
 to_memoized_dict(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.
 create_op(args=None, sslbls=None)
Create the operation associated with the given args and sslbls.
Parameters
 argslist or tuple
The arguments for the operation to be created. None means no arguments were supplied.
 sslblslist or tuple
The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).
Returns
 ModelMember
Can be any type of operation, e.g. a LinearOperator, State, Instrument, or POVM, depending on the label requested.
 to_vector()
Extract a vector of the underlying gate parameters from this OpFactory.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize this OpFactory using a vector of its parameters.
Parameters
 vnumpy array
The 1D vector of gate parameters. Length must == num_params().
 closebool, optional
Whether v is close to this factory’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
 dirty_valuebool, 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
 class pygsti.modelmembers.operations.ComposedOpFactory(factories_or_ops_to_compose, state_space='auto', evotype='auto', dense=False)
Bases:
OpFactory
A factory that composes a number of other factories and/or operations.
Label arguments are passed unaltered through this factory to any component factories.
Parameters
 factories_or_ops_to_composelist
List of LinearOperator or OpFactoryderived objects that are composed to form this factory. There should be at least one factory among this list, otherwise there’s no need for a factory. Elements are composed with vectors in lefttoright ordering, maintaining the same convention as operation sequences in pyGSTi. Note that this is opposite from standard matrix multiplication order.
 state_spaceStateSpace or “auto”
States space of the operations produced by this factory. Can be set to “auto” to take the state space from factories_or_ops_to_compose[0] if there’s at least one factory or operator being composed.
 evotype{“densitymx”,”statevec”,”stabilizer”,”svterm”,”cterm”,”auto”}
The evolution type of this factory. Can be set to “auto” to take the evolution type of factories_or_ops_to_compose[0] if there’s at least one factory or operator being composed.
 densebool, optional
Whether dense composed operations (ops which hold their entire superoperator) should be created. (Currently UNUSED  leave as default).
Initialize a new ModelMember
 property num_params
Get the number of independent parameters which specify this factory.
Returns
 int
the number of independent parameters.
 create_op(args=None, sslbls=None)
Create the operation associated with the given args and sslbls.
Parameters
 argslist or tuple
The arguments for the operation to be created. None means no arguments were supplied.
 sslblslist or tuple
The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).
Returns
 ModelMember
Can be any type of operation, e.g. a LinearOperator, State, Instrument, or POVM, depending on the label requested.
 to_vector()
Get the parameters as an array of values.
Returns
 numpy array
The parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize this factory using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of gate parameters. Length must == num_params()
 closebool, optional
Whether v is close to this factory’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
 dirty_valuebool, 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
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.RepeatedOp(op_to_repeat, num_repetitions, evotype='auto')
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
An operation map that is the composition of a number of maplike factors (possibly other LinearOperator)
Parameters
 op_to_repeatlist
A LinearOperatorderived object that is repeated some integer number of times to produce this operator.
 num_repetitionsint
the power to exponentiate op_to_exponentiate to.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype. The special value “auto” uses the evolutio ntype of op_to_repeat.
Initialize a new LinearOperator
 property parameter_labels
An array of labels (usually strings) describing this model member’s parameters.
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 set_time(t)
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
Parameters
 tfloat
The current time.
Returns
None
 to_sparse(on_space='minimal')
Return the operation as a sparse matrix
Returns
scipy.sparse.csr_matrix
 to_dense(on_space='minimal')
Return this operation as a dense matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(wrt_filter=None)
The elementwise derivative this operation.
Constructs 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. An empty 2D array in the StaticArbitraryOp case (num_params == 0).
Parameters
 wrt_filterlist 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 with shape (dimension^2, num_params)
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.StaticArbitraryOp(m, basis=None, evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
,pygsti.modelmembers.errorgencontainer.NoErrorGeneratorInterface
An operation matrix that is completely fixed, or “static” (i.e. that posesses no parameters).
Parameters
 marray_like or LinearOperator
a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 class pygsti.modelmembers.operations.StaticCliffordOp(unitary, symplecticrep=None, basis='pp', evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
,pygsti.modelmembers.errorgencontainer.NoErrorGeneratorInterface
A Clifford operation, represented via a symplectic matrix.
Parameters
 unitarynumpy.ndarray
The unitary action of the clifford operation.
 symplecticreptuple, optional
A (symplectic matrix, phase vector) 2tuple specifying the pre computed symplectic representation of unitary. If None, then this representation is computed automatically from unitary.
 basisBasis or {‘pp’,’gm’,’std’}, optional
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
 evotypeEvotype or str
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property smatrix
 property svector
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve. max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 to_dense(on_space='minimal')
Return the dense array used to represent this operation within its evolution type.
Note: for efficiency, this doesn’t copy the underlying data, so the caller should copy this data before modifying it.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.StaticStandardOp(name, basis='pp', evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
,pygsti.modelmembers.errorgencontainer.NoErrorGeneratorInterface
An operation that is completely fixed, or “static” (i.e. that posesses no parameters) that can be constructed from “standard” gate names (as defined in pygsti.tools.internalgates).
Parameters
 namestr
Standard gate name
 basisBasis or {‘pp’,’gm’,’std’}, optional
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 to_dense(on_space='minimal')
Return the dense array used to represent this operation within its evolution type.
Note: for efficiency, this doesn’t copy the underlying data, so the caller should copy this data before modifying it.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve. max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.StaticUnitaryOp(m, basis='pp', evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseUnitaryOperator
,pygsti.modelmembers.errorgencontainer.NoErrorGeneratorInterface
A unitary operation matrix that is completely fixed, or “static” (i.e. that posesses no parameters).
Parameters
 marray_like or LinearOperator
a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
 basisBasis or {‘pp’,’gm’,’std’}, optional
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Initialize a new LinearOperator
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve. max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 class pygsti.modelmembers.operations.StochasticNoiseOp(state_space, stochastic_basis='PP', basis='pp', evotype='default', initial_rates=None, seed_or_state=None)
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
,pygsti.modelmembers.operations.krausop.KrausOperatorInterface
A stochastic noise operation.
Implements the stochastic noise map: rho > (1sum(p_i))rho + sum_(i>0) p_i * B_i * rho * B_i^dagger where p_i > 0 and sum(p_i) < 1, and B_i is basis where B_0 is the identity.
In the case of the ‘chp’ evotype, the B_i element is returned with probability p_i, such that the outcome distribution matches the aforementioned stochastic noise map when considered over many samples.
Parameters
 state_spaceStateSpace, optional
The state space for this operation.
 basisBasis or {‘pp’,’gm’,’qt’}, optional
The basis to use, defining the “principle axes” along which there is stochastic noise. We assume that the first element of basis is the identity.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 initial_rateslist or array
if not None, a list of basis.size1 initial error rates along each of the directions corresponding to each basis element. If None, then all initial rates are zero.
 seed_or_statefloat or RandomState, optional
Random seed for RandomState (or directly provided RandomState) for sampling stochastic superoperators with the ‘chp’ evotype.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 property total_term_magnitude
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolutecoefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
Returns
float
 property total_term_magnitude_deriv
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
Returns
 numpy array
An array of length self.num_params
 property kraus_operators
A list of this operation’s Kraus operators as numpy arrays.
 to_dense(on_space='minimal')
Return this operation as a dense matrix.
Parameters
 on_space{‘minimal’, ‘Hilbert’, ‘HilbertSchmidt’}
The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and superbra/superket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
Returns
numpy.ndarray
 to_vector()
Extract a vector of the underlying operation parameters from this operation.
Returns
 numpy array
a 1D numpy array with length == num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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
 taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)
Get the orderth order Taylorexpansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank1”, meaning that its action on a density matrix rho can be written:
rho > A rho B
The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model
), not the operation’s local parameter array (i.e. that returned from to_vector).Parameters
 orderint
Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve. max_polynomial_varsint, optional
maximum number of variables the created polynomials can have.
 return_coeff_polysbool
Whether a parallel list of locallyindexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.
Returns
 termslist
A list of
RankOneTerm
objects. coefficientslist
Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2tuple formed by concatenating together the output of
Polynomial.compact()
.
 set_kraus_operators(kraus_operators)
Set the parameters of this operation by specifying its Kraus operators.
Parameters
 kraus_operatorslist
A list of numpy arrays, each of which specifies a Kraus operator.
Returns
None
 to_memoized_dict(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.
 class pygsti.modelmembers.operations.AffineShiftOp(m, basis=None, evotype='default', state_space=None)
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
An operation matrix that induces an affine shift.
An operation matrix with ones on the diagonal and nonzero values in the first columns.
Meant to work in the Pauli basis for now.
Parameters
 marray_like or LinearOperator
a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
 basisBasis or {‘pp’,’gm’,’std’} or None
The basis used to construct the HilbertSchmidt space representation of this state as a superoperator. If None, certain functionality, such as access to Kraus operators, will be unavailable.
 evotypeEvotype or str, optional
The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
 state_spaceStateSpace, optional
The state space for this operation. If None a default state space with the appropriate number of qubits is used.
Attributes
 basenumpy.ndarray
Direct access to the underlying process matrix data.
Initialize a new LinearOperator
 property num_params
Get the number of independent parameters which specify this operation.
Returns
 int
the number of independent parameters.
 set_dense(m)
Set the densematrix value of this operation.
Attempts to modify operation parameters so that the specified raw operation matrix becomes m. Will raise ValueError if this operation is not possible.
Parameters
 marray_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
None
 to_vector()
Get the operation parameters as an array of values.
Returns
 numpy array
The operation parameters as a 1D array with length num_params().
 from_vector(v, close=False, dirty_value=True)
Initialize the operation using a vector of parameters.
Parameters
 vnumpy array
The 1D vector of operation parameters. Length must == num_params()
 closebool, 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_valuebool, 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(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_filterlist 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 with shape (dimension^2, num_params)
 pygsti.modelmembers.operations.create_from_unitary_mx(unitary_mx, op_type, basis='pp', stdname=None, evotype='default', state_space=None)
TODO: docstring  note that op_type can be a list/tuple of types in order of precedence
 pygsti.modelmembers.operations.create_from_superop_mx(superop_mx, op_type, basis='pp', stdname=None, evotype='default', state_space=None)
 pygsti.modelmembers.operations.verbose_type_from_op_type(op_type)
Decode an op type into the “canonical”, more verbose op type.
Parameters:
 op_type: str or list of str
Operation parameterization type (or list of preferences)
Returns
 povm_type_preferences: tuple of str
POVM parameterization types
 pygsti.modelmembers.operations.convert_errorgen(errorgen, to_type, basis, flatten_structure=False)
TODO: docstring
 pygsti.modelmembers.operations.convert(operation, to_type, basis, ideal_operation=None, flatten_structure=False, cptp_truncation_tol=1e06)
Convert operation to a new type of parameterization.
This potentially creates a new LinearOperator object, and Raises ValueError for invalid conversions.
Parameters
 operationLinearOperator
LinearOperator to convert
 to_type{“full”,”full TP”,”static”,”static unitary”,”clifford”,LINDBLAD}
The type of parameterizaton to convert to. “LINDBLAD” is a placeholder for the various Lindblad parameterization types. See
Model.set_all_parameterizations()
for more details. basis{‘std’, ‘gm’, ‘pp’, ‘qt’} or Basis object
The basis for operation. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
 ideal_operationLinearOperator or “identity”, optional
The ideal (usually unitary) version of operation, potentially used when converting to an errorgenerator type. The special value “identity” can be used to indicate that the ideal operation is the identity.
 flatten_structurebool, optional
When False, the submembers of composed and embedded operations are separately converted, leaving the original operation’s structure unchanged. When True, composed and embedded operations are “flattened” into a single operation of the requested to_type.
 cptp_truncation_tolfloat, optional (default 1e6)
Tolerance used for conversion to CPTP parameterizations. When converting to CPTP models negative eigenvalues of the choi matrix representation of a superoperator are truncated, which can result in a change in the PTM for that operator. This tolerance indicates the maximum amount of truncation induced deviation from the original operations (measured by frobenius distance) we’re willing to accept without marking the conversion as failed.
Returns
 LinearOperator
The converted operation, usually a distinct object from the operation object passed as input.
 pygsti.modelmembers.operations.check_deriv_wrt_params(operation, deriv_to_check=None, wrt_filter=None, eps=1e07)
Checks the deriv_wrt_params method of a LinearOperator object.
This routine is meant to be used as an aid in testing and debugging operation classes by comparing the finitedifference Jacobian that should be returned by operation.deriv_wrt_params with the one that actually is. A ValueError is raised if the two do not match.
Parameters
 operationLinearOperator
The operation object to test.
 deriv_to_checknumpy.ndarray or None, optional
If not None, the Jacobian to compare against the finite difference result. If None, operation.deriv_wrt_parms() is used. Setting this argument can be useful when the function is called within a LinearOperator class’s deriv_wrt_params() method itself as a part of testing.
 wrt_filterlist or numpy.ndarray
List of parameter indices to filter the result by (as though derivative is only taken with respect to these parameters).
 epsfloat, optional
The finite difference step to use.
Returns
None
 pygsti.modelmembers.operations.optimize_operation(op_to_optimize, target_op)
Optimize the parameters of op_to_optimize.
Optimization is performed so that the the resulting operation matrix is as close as possible to target_op’s matrix.
This is trivial for the case of FullArbitraryOp instances, but for other types of parameterization this involves an iterative optimization over all the parameters of op_to_optimize.
Parameters
 op_to_optimizeLinearOperator
The operation to optimize. This object gets altered.
 target_opLinearOperator
The operation whose matrix is used as the target.
Returns
None