pygsti.modelmembers.operations
¶
Subpackage holding model operation objects.
Submodules¶
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.fulltpop
pygsti.modelmembers.operations.fullunitaryop
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`s). 

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 matrix that is fully parameterized. 

A tracepreserving operation matrix. 

An operation matrix that is fully parameterized. 

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`s) 

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

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_compose (list) – List of LinearOperatorderived objects that are summed together (composed) to form this error generator.
evotype (Evotype 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_space (StateSpace 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.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 coefficients(self, 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_basis (bool) – Whether to also return a
Basis
containing the elements with which the error generator terms were constructed.logscale_nonham (bool, 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 :method:`error_rates`.
 Returns
Ltermdict (dict) – 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.
basis (Basis) – A Basis mapping the basis labels used in the keys of Ltermdict to basis matrices.
 coefficient_labels(self)¶
The elementary errorgenerator labels corresponding to the elements of :method:`coefficients_array`.
 Returns
tuple – A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 coefficients_array(self)¶
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by :method:`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(self)¶
The jacobian of :method:`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(self)¶
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_dict (dict) – 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(self, 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_dict (dict) – 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_nonham (bool, 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 :method:`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 function :method:`set_error_rates`.
truncate (bool, 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(self, 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 :method:`error_rates` for more details.
 Parameters
lindblad_term_dict (dict) – 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(self, 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_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 hessian_wrt_params(self, 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_filter1 (list 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_filter2 (list 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)
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 append(self, *factors_to_add)¶
Add one or more factors to this operator.
 Parameters
*factors_to_add (LinearOperator) – One or multiple factor operators to add on at the end (summed last) of this operator.
 Returns
None
 insert(self, insert_at, *factors_to_insert)¶
Insert one or more factors into this operator.
 Parameters
insert_at (int) – 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_insert (LinearOperator) – One or multiple factor operators to insert within this operator.
 Returns
None
 remove(self, *factor_indices)¶
Remove one or more factors from this operator.
 Parameters
*factorop_indices (int) – One or multiple factor indices to remove from this operator.
 Returns
None
 to_sparse(self, on_space='minimal')¶
Return this error generator as a sparse matrix
 Returns
scipy.sparse.csr_matrix
 to_dense(self, 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
 property parameter_labels(self)¶
An array of labels (usually strings) describing this model member’s parameters.
 property num_params(self)¶
Get the number of independent parameters which specify this error generator.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 taylor_order_terms(self, 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
order (int) – The order of terms to get.
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 property total_term_magnitude(self)¶
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(self)¶
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
 transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 onenorm_upperbound(self)¶
Returns an upper bound on the 1norm for this error generator (viewed as a matrix).
 Returns
float
 __str__(self)¶
Return string representation
 class pygsti.modelmembers.operations.ComposedOp(ops_to_compose, evotype='auto', state_space='auto')¶
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
An operation that is the composition of a number of maplike factors (possibly other `LinearOperator`s).
 Parameters
ops_to_compose (list) – 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.
evotype (Evotype 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_space (StateSpace 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.
 _update_denserep(self)¶
Performs additional update for the case when we use a dense underlying representation.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 set_time(self, t)¶
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
 Parameters
t (float) – The current time.
 Returns
None
 set_gpindices(self, gpindices, parent, memo=None)¶
Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.
 Parameters
gpindices (slice or integer ndarray) – The indices of this objects parameters in its parent’s array.
parent (Model or ModelMember) – The parent whose parameter array gpindices references.
memo (dict, optional) – A memo dict used to avoid circular references.
 Returns
None
 append(self, *factorops_to_add)¶
Add one or more factors to this operator.
 Parameters
*factors_to_add (LinearOperator) – One or multiple factor operators to add on at the end (evaluated last) of this operator.
 Returns
None
 insert(self, insert_at, *factorops_to_insert)¶
Insert one or more factors into this operator.
 Parameters
insert_at (int) – 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_insert (LinearOperator) – One or multiple factor operators to insert within this operator.
 Returns
None
 remove(self, *factorop_indices)¶
Remove one or more factors from this operator.
 Parameters
*factorop_indices (int) – One or multiple factor indices to remove from this operator.
 Returns
None
 to_sparse(self, on_space='minimal')¶
Return the operation as a sparse matrix
 Returns
scipy.sparse.csr_matrix
 to_dense(self, 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
 property parameter_labels(self)¶
An array of labels (usually strings) describing this model member’s parameters.
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 taylor_order_terms(self, 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
order (int) – The order of terms to get.
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 _compute_taylor_order_terms(self, order, max_polynomial_vars, gpindices_array)¶
 taylor_order_terms_above_mag(self, 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 :method:`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
order (int) – The order of terms to get (and filter).
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
min_term_mag (float) – the minimum term magnitude.
 Returns
list – A list of
Rank1Term
objects.
 property total_term_magnitude(self)¶
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(self)¶
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
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 errorgen_coefficients(self, 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_basis (bool, optional) – Whether to also return a
Basis
containing the elements with which the error generator terms were constructed.logscale_nonham (bool, 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 :method:`error_rates`.
 Returns
lindblad_term_dict (dict) – 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.
basis (Basis) – A Basis mapping the basis labels used in the keys of lindblad_term_dict to basis matrices.
 errorgen_coefficient_labels(self)¶
The elementary errorgenerator labels corresponding to the elements of :method:`errorgen_coefficients_array`.
 Returns
tuple – A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 errorgen_coefficients_array(self)¶
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 :method:`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(self)¶
The jacobian of :method:`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(self)¶
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_dict (dict) – 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(self, 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_dict (dict) – 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_nonham (bool, 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 :method:`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 function :method:`set_error_rates`.
truncate (bool, 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(self, 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 :method:`error_rates` for more details.
 Parameters
lindblad_term_dict (dict) – 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
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 __str__(self)¶
Return string representation
 class pygsti.modelmembers.operations.DenseOperator(mx, evotype, state_space=None)¶
Bases:
DenseOperatorInterface
,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
mx (numpy.ndarray) – The operation as a dense process matrix.
evotype (Evotype or str) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 base¶
Direct access to the underlying process matrix data.
 Type
numpy.ndarray
 property _ptr(self)¶
 _ptr_has_changed(self)¶
Derived classes should override this function to handle rep updates when the _ptr property is changed.
 to_dense(self, 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(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 class pygsti.modelmembers.operations.DenseOperatorInterface¶
Bases:
object
Adds a numpyarraymimicing interface onto an operation object.
 property _ptr(self)¶
 _ptr_has_changed(self)¶
Derived classes should override this function to handle rep updates when the _ptr property is changed.
 to_array(self)¶
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 :method:`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(self, 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
 __copy__(self)¶
 __deepcopy__(self, memo)¶
 __getitem__(self, key)¶
 __getslice__(self, i, j)¶
 __setitem__(self, key, val)¶
 __getattr__(self, attr)¶
 __str__(self)¶
Return str(self).
 __pos__(self)¶
 __neg__(self)¶
 __abs__(self)¶
 __add__(self, x)¶
 __radd__(self, x)¶
 __sub__(self, x)¶
 __rsub__(self, x)¶
 __mul__(self, x)¶
 __rmul__(self, x)¶
 __truediv__(self, x)¶
 __rtruediv__(self, x)¶
 __floordiv__(self, x)¶
 __rfloordiv__(self, x)¶
 __pow__(self, x)¶
 __eq__(self, x)¶
Return self==value.
 __len__(self)¶
 __int__(self)¶
 __long__(self)¶
 __float__(self)¶
 __complex__(self)¶
 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_space (StateSpace, optional) – The state space for this operation.
basis (Basis 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.evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
initial_rate (float, optional) – the initial error rate.
seed_or_state (float or RandomState, optional) – Random seed for RandomState (or directly provided RandomState) for sampling stochastic superoperators with the ‘chp’ evotype.
 _rates_to_params(self, rates)¶
Note: requires rates to all be the same
 _params_to_rates(self, params)¶
 _get_rate_poly_dicts(self)¶
Return a list of dicts, one per rate, expressing the rate as a polynomial of the local parameters (tuple keys of dicts <=> poly terms, e.g. (1,1) <=> x1^2)
 property total_term_magnitude_deriv(self)¶
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(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 __str__(self)¶
Return str(self).
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 class pygsti.modelmembers.operations.EigenvalueParamDenseOp(matrix, include_off_diags_in_degen_2_blocks=False, tp_constrained_and_unital=False, evotype='default', state_space=None)¶
Bases:
pygsti.modelmembers.operations.denseop.DenseOperator
A real operation matrix parameterized only by its eigenvalues.
These eigenvalues are assumed to be either real or to occur in conjugate pairs. Thus, the number of parameters is equal to the number of eigenvalues.
 Parameters
matrix (numpy array) – a square 2D numpy array that gives the raw operation matrix to paramterize. The shape of this array sets the dimension of the operation.
include_off_diags_in_degen_2_blocks (bool) – If True, include as parameters the (initially zero) offdiagonal elements in degenerate 2x2 blocks of the the diagonalized operation matrix (no offdiagonals are included in blocks larger than 2x2). This is an option specifically used in the intelligent fiducial pair reduction (IFPR) algorithm.
tp_constrained_and_unital (bool) – If True, assume the top row of the operation matrix is fixed to [1, 0, … 0] and should not be parameterized, and verify that the matrix is unital. In this case, “1” is always a fixed (notparamterized0 eigenvalue with eigenvector [1,0,…0] and if include_off_diags_in_degen_2_blocks is True any off diagonal elements lying on the top row are not parameterized as implied by the TP constraint.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 _construct_matrix(self)¶
Build the internal operation matrix using the current parameters.
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 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_space (StateSpace) – Specifies the density matrix space upon which this operation acts.
target_labels (list 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_embed (LinearOperator) – The error generator object that is to be contained within this error generator, and that specifies the only nontrivial action of the EmbeddedErrorgen.
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 coefficients(self, 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_basis (bool) – Whether to also return a
Basis
containing the elements with which the error generator terms were constructed.logscale_nonham (bool, 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 :method:`error_rates`.
 Returns
Ltermdict (dict) – 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.
basis (Basis) – A Basis mapping the basis labels used in the keys of Ltermdict to basis matrices.
 coefficient_labels(self)¶
The elementary errorgenerator labels corresponding to the elements of :method:`coefficients_array`.
 Returns
tuple – A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 coefficients_array(self)¶
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by :method:`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(self)¶
The jacobian of :method:`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(self)¶
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_dict (dict) – 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(self, 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_dict (dict) – 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_nonham (bool, 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 :method:`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 function :method:`set_error_rates`.
truncate (bool, 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(self, 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 :method:`error_rates` for more details.
 Parameters
lindblad_term_dict (dict) – 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(self, 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_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 hessian_wrt_params(self, 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_filter1 (list 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_filter2 (list 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(self)¶
Returns an upper bound on the 1norm for this error generator (viewed as a matrix).
 Returns
float
 __str__(self)¶
Return string representation
 class pygsti.modelmembers.operations.EmbeddedOp(state_space, target_labels, operation_to_embed)¶
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_space (StateSpace) – Specifies the density matrix space upon which this operation acts.
target_labels (list 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_embed (LinearOperator) – The operation object that is to be contained within this operation, and that specifies the only nontrivial action of the EmbeddedOp.
 _update_denserep(self)¶
Performs additional update for the case when we use a dense underlying representation.
 __getstate__(self)¶
Don’t pickle parent
 __setstate__(self, d)¶
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 set_time(self, t)¶
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
 Parameters
t (float) – The current time.
 Returns
None
 _iter_matrix_elements_precalc(self, on_space)¶
 _iter_matrix_elements(self, on_space, rel_to_block=False)¶
Iterates of (op_i,op_j,embedded_op_i,embedded_op_j) tuples giving mapping between nonzero elements of operation matrix and elements of the embedded operation matrix
 to_sparse(self, on_space='minimal')¶
Return the operation as a sparse matrix
 Returns
scipy.sparse.csr_matrix
 to_dense(self, 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
 property parameter_labels(self)¶
An array of labels (usually strings) describing this model member’s parameters.
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 taylor_order_terms(self, 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
order (int) – The order of terms to get.
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 taylor_order_terms_above_mag(self, 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 :method:`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
order (int) – The order of terms to get (and filter).
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
min_term_mag (float) – the minimum term magnitude.
 Returns
list – A list of
Rank1Term
objects.
 property total_term_magnitude(self)¶
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(self)¶
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
 abstract transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 errorgen_coefficients(self, 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_basis (bool, optional) – Whether to also return a
Basis
containing the elements with which the error generator terms were constructed.logscale_nonham (bool, 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 :method:`error_rates`.
 Returns
lindblad_term_dict (dict) – 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.
basis (Basis) – A Basis mapping the basis labels used in the keys of lindblad_term_dict to basis matrices.
 errorgen_coefficients_array(self)¶
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 :method:`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(self)¶
The jacobian of :method:`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(self)¶
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_dict (dict) – 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(self, 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_dict (dict) – 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_nonham (bool, 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 :method:`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 function :method:`set_error_rates`.
truncate (bool, 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(self, 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 :method:`error_rates` for more details.
 Parameters
lindblad_term_dict (dict) – 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(self, 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
amount (float 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(self, 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
amount (tuple 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(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 __str__(self)¶
Return string representation
 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
errorgen (LinearOperator) – The error generator for this operator. That is, the L if this operator is exp(L).
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 _update_rep(self, close=False)¶
Updates self._rep as needed after parameters have changed.
 set_gpindices(self, gpindices, parent, memo=None)¶
Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.
 Parameters
gpindices (slice or integer ndarray) – The indices of this objects parameters in its parent’s array.
parent (Model or ModelMember) – The parent whose parameter array gpindices references.
memo (dict, optional) – A memo dict used to avoid circular references.
 Returns
None
 to_dense(self, on_space='minimal')¶
Return this operation as a dense matrix.
 Returns
numpy.ndarray
 to_sparse(self, 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(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 hessian_wrt_params(self, 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_filter1 (list 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_filter2 (list 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)
 property parameter_labels(self)¶
An array of labels (usually strings) describing this model member’s parameters.
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 taylor_order_terms(self, 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
order (int) – Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve.max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 _compute_taylor_order_terms(self, order, max_polynomial_vars)¶
 taylor_order_terms_above_mag(self, 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 :method:`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
order (int) – The order of terms to get (and filter).
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
min_term_mag (float) – the minimum term magnitude.
 Returns
list – A list of
Rank1Term
objects.
 property total_term_magnitude(self)¶
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(self)¶
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
 transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 spam_transform_inplace(self, 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
s (GaugeGroupElement) – 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
 __str__(self)¶
Return str(self).
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 class pygsti.modelmembers.operations.FullArbitraryOp(m, 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
m (array_like or LinearOperator) – a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 set_dense(self, 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
m (array_like or LinearOperator) – An array of shape (dim, dim) or LinearOperator representing the operation action.
 Returns
None
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 class pygsti.modelmembers.operations.FullTPOp(m, 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
m (array_like or LinearOperator) – a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 base¶
Direct access to the underlying process matrix data.
 Type
numpy.ndarray
 property _ptr(self)¶
The underlying dense process matrix.
 set_dense(self, 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
m (array_like or LinearOperator) – An array of shape (dim, dim) or LinearOperator representing the operation action.
 Returns
None
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 class pygsti.modelmembers.operations.FullUnitaryOp(m, basis='pp', 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
m (array_like or LinearOperator) – a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 set_dense(self, 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
m (array_like or LinearOperator) – An array of shape (dim, dim) or LinearOperator representing the operation action.
 Returns
None
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 class pygsti.modelmembers.operations.LindbladErrorgen(lindblad_term_dict, parameterization='auto', lindblad_basis='pp', mx_basis='pp', truncate=True, 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
dim (int) – The HilbertSchmidt (superoperator) dimension, which will be the dimension of the created operator.
lindblad_term_dict (dict) – 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.
basis (Basis, 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).
truncate (bool, 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.
 _generators_cache¶
 classmethod from_operation_matrix(cls, 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 :method:`from_error_generator`.
 Parameters
op_matrix (numpy 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).
truncate (bool, 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).
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (TODO docstring) –
 Returns
LindbladOp
 classmethod from_error_generator(cls, 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(cls, errgen, parameterization='CPTP', ham_basis='pp', nonham_basis='pp', mx_basis='pp', truncate=True, evotype='default', state_space=None)¶
Create a Lindbladform error generator from an error generator matrix and a basis.
The basis specifies how to decompose (project) the error generator.
 Parameters
errgen (numpy array or SciPy sparse matrix) – a square 2D array that gives the full error generator. The shape of this array sets the dimension of the operator. The projections of this quantity onto the ham_basis and nonham_basis are closely related to the parameters of the error generator (they may not be exactly equal if, e.g cptp=True).
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 nonHamiltoniantype 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).
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).
truncate (bool, 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 errgen cannot be realized by the specified set of Lindblad projections.
evotype ({"densitymx","svterm","cterm"}) – The evolution type of the error generator being constructed. “densitymx” means usual Lioville densitymatrixvector propagation via matrixvector products. “svterm” denotes statevector term based 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.
state_space (TODO docstring) –
 Returns
LindbladErrorgen
 _init_generators(self, dim)¶
 _init_terms(self, lindblad_term_dict, basis, dim, max_polynomial_vars)¶
 _set_params_from_matrix(self, errgen, truncate)¶
Sets self.paramvals based on errgen
 _update_rep(self)¶
Updates self._rep, which contains a representation of this error generator as either a dense or sparse matrix. This routine essentially builds the error generator matrix using the current parameters and updates self._rep accordingly (by rewriting its data).
 to_dense(self, 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(self, on_space='minimal')¶
Return the error generator as a sparse matrix.
 Returns
scipy.sparse.csr_matrix
 taylor_order_terms(self, 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
order (int) – The order of terms to get.
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 property total_term_magnitude(self)¶
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(self)¶
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(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 coefficients(self, 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_basis (bool) – Whether to also return a
Basis
containing the elements with which the error generator terms were constructed.logscale_nonham (bool, 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 :method:`error_rates`.
 Returns
Ltermdict (dict) – 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.
basis (Basis) – A Basis mapping the basis labels used in the keys of Ltermdict to basis matrices.
 coefficient_labels(self)¶
The elementary errorgenerator labels corresponding to the elements of :method:`coefficients_array`.
 Returns
tuple – A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.
 coefficients_array(self)¶
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by :method:`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(self)¶
The jacobian of :method:`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(self)¶
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_dict (dict) – 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(self, 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_dict (dict) – 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_nonham (bool, 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 :method:`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 function :method:`set_error_rates`.
truncate (bool, 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(self, 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 :method:`error_rates` for more details.
 Parameters
lindblad_term_dict (dict) – 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(self, weights)¶
TODO: docstring
 set_coefficient_weights(self, weights)¶
TODO: docstring
 transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 _d_hdp(self)¶
 _d_odp(self)¶
 _d2_odp2(self)¶
 deriv_wrt_params(self, 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_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 hessian_wrt_params(self, 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_filter1 (list 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_filter2 (list 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(self)¶
Returns an upper bound on the 1norm for this error generator (viewed as a matrix).
 Returns
float
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 __str__(self)¶
Return str(self).
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 class pygsti.modelmembers.operations.LindbladParameterization(nonham_mode, param_mode, ham_params_allowed, nonham_params_allowed, abbrev=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_mode (str) – 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_mode (str) – 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 (bool) – Whether or not Hamiltonian and nonHamiltonian parameters are allowed.
nonham_params_allowed (bool) – Whether or not Hamiltonian and nonHamiltonian parameters are allowed.
 classmethod from_lindblad_terms(cls, errs)¶
Helper function giving minimal Lindblad parameterization needed for specified errors.
 Parameters
errs (dict) – 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
parameterization (str) – Parameterization string for constructing Lindblad error generators.
 classmethod cast(cls, obj)¶
Converts a string into a LindbladParameterization object if necessary.
 Parameters
obj (str or LindbladParameterization) – The object to convert.
 Returns
LindbladParameterization
 __hash__(self)¶
Return hash(self).
 __eq__(self, other)¶
Return self==value.
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 __str__(self)¶
Return str(self).
 class pygsti.modelmembers.operations.LinearOperator(rep, evotype)¶
Bases:
pygsti.modelmembers.modelmember.ModelMember
Base class for all operation representations
 Parameters
rep (object) – A representation object containing the core data for this operator.
evotype (Evotype) – The evolution type.
 size¶
Return the number of independent elements in this operation (when viewed as a dense array)
 Type
int
 dirty¶
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. Type
bool
 property dim(self)¶
Return the dimension of this operation (when viewed as a dense matrix)
 Returns
int
 property size(self)¶
Return the number of independent elements in this operation (when viewed as a dense array)
 Returns
int
 set_dense(self, 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
m (array_like or LinearOperator) – An array of shape (dim, dim) or LinearOperator representing the operation action.
 Returns
None
 set_time(self, t)¶
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
 Parameters
t (float) – The current time.
 Returns
None
 abstract to_dense(self, 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(self, state, on_space='minimal')¶
Act with this operator upon state
 Parameters
state (State) – The state to act on
 Returns
State – The output state
 abstract to_sparse(self, on_space='minimal')¶
Return this operation as a sparse matrix.
 Returns
scipy.sparse.csr_matrix
 abstract taylor_order_terms(self, 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
order (int) – The order of terms to get.
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 highmagnitude_terms(self, 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_mag (float) – the threshold for term magnitudes: only terms with magnitudes above this value are returned.
force_firstorder (bool, 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_order (int, optional) – the maximum Taylororder to consider when checking whether term magnitudes exceed min_term_mag.
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
 Returns
highmag_terms (list) – A list of the highmagnitude terms that were found. These terms are sorted in descending order by termmagnitude.
first_order_indices (list) – 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(self, 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 :method:`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
order (int) – The order of terms to get (and filter).
max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
min_term_mag (float) – the minimum term magnitude.
 Returns
list – A list of
Rank1Term
objects.
 frobeniusdist_squared(self, 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_op (DenseOperator) – The other operation.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
 Returns
float
 frobeniusdist(self, 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_op (DenseOperator) – The other operation.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
 Returns
float
 residuals(self, 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_op (DenseOperator) – The operation to compare against.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
 Returns
numpy.ndarray – A 1Darray of size equal to that of the flattened operation matrix.
 jtracedist(self, 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_op (DenseOperator) – The operation to compare against.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
 Returns
float
 diamonddist(self, 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_op (DenseOperator) – The operation to compare against.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
 Returns
float
 transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 depolarize(self, 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
amount (float 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(self, 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
amount (tuple 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(self, 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_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 hessian_wrt_params(self, 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_filter1 (list 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_filter2 (list 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)
 __setstate__(self, state)¶
 static convert_to_matrix(m)¶
Static method that converts a matrixlike object to a 2D numpy array.
 Parameters
m (array_like) – matrixlike object
 Returns
numpy array
 property chp_str(self)¶
A string suitable for printing to a CHP input file after probabilistically selecting operation.
 Returns
s (str) – String of CHP code
 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
operation (LinearOperator) – The operation object to compute a Jacobian for.
wrt_filter (list or numpy.ndarray) – List of parameter indices to filter the result by (as though derivative is only taken with respect to these parameters).
eps (float, 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
operation (LinearOperator) – The operation object to compute a Hessian for.
wrt_filter1 (list 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_filter2 (list 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).
eps (float, 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, 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
basematrix (numpy 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_array (numpy 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_map (dict) – 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_transform (numpy 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_transform (numpy 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.
real (bool, 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.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 _construct_matrix(self)¶
Build the internal operation matrix using the current parameters.
 _construct_param_to_base_indices_map(self)¶
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
Construct a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter.
 Parameters
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives, shape == (dimension^2, num_params)
 has_nonzero_hessian(self)¶
Whether this operation has a nonzero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
 Returns
bool
 __str__(self)¶
Return str(self).
 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_space (StateSpace) – The statespace of the operation(s) this factory builds.
evotype (Evotype) – The evolution type of the operation(s) this factory builds.
 abstract create_object(self, 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 :method:`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
args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.
sslbls (list 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(self, args=None, sslbls=None)¶
Create the operation associated with the given args and sslbls.
 Parameters
args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.
sslbls (list 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(self, args=None, sslbls=None, item_lbl=None)¶
Create the simplified operation associated with the given args, sslbls, and item_lbl.
Similar to as :method:`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
args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.
sslbls (list 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_lbl (str, 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.
 abstract transform_inplace(self, s)¶
Update OpFactory so that created ops O are additionally transformed as inv(s) * O * s.
 Parameters
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 __str__(self)¶
Return str(self).
 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_space (StateSpace) – The state space of this factory, describing the space of these that the operations produced by this factory act upon.
target_labels (list 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_embed (OpFactory) – The factory object that is to be contained within this factory, and that specifies the only nontrivial action of the operations this factory produces.
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 create_op(self, args=None, sslbls=None)¶
Create the operation associated with the given args and sslbls.
 Parameters
args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.
sslbls (list 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.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 property num_params(self)¶
Get the number of independent parameters which specify this OpFactory.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying gate parameters from this OpFactory.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize this OpFactory using a vector of its parameters.
 Parameters
v (numpy array) – The 1D vector of gate parameters. Length must == num_params().
close (bool, 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_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 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 :method:`create_op` is used instead.
 Parameters
state_space (StateSpace) – The state space of this factory, describing the space of these that the operations produced by this factory act upon.
factory_or_op_to_embed (LinearOperator 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_labels (int, 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_fn (callable, 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.
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 create_op(self, args=None, sslbls=None)¶
Create the operation associated with the given args and sslbls.
 Parameters
args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.
sslbls (list 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.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 property num_params(self)¶
Get the number of independent parameters which specify this OpFactory.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying gate parameters from this OpFactory.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize this OpFactory using a vector of its parameters.
 Parameters
v (numpy array) – The 1D vector of gate parameters. Length must == num_params().
close (bool, 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_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 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_compose (list) – 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_space (StateSpace 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.
dense (bool, optional) – Whether dense composed operations (ops which hold their entire
 create_op(self, args=None, sslbls=None)¶
Create the operation associated with the given args and sslbls.
 Parameters
args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.
sslbls (list 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.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 property num_params(self)¶
Get the number of independent parameters which specify this factory.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Get the parameters as an array of values.
 Returns
numpy array – The parameters as a 1D array with length num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize this factory using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of gate parameters. Length must == num_params()
close (bool, 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_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 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`s)
 Parameters
op_to_repeat (list) – A LinearOperatorderived object that is repeated some integer number of times to produce this operator.
num_repetitions (int) – the power to exponentiate op_to_exponentiate to.
evotype (Evotype 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.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 set_time(self, t)¶
Sets the current time for a timedependent operator.
For timeindependent operators (the default), this function does nothing.
 Parameters
t (float) – The current time.
 Returns
None
 to_sparse(self, on_space='minimal')¶
Return the operation as a sparse matrix
 Returns
scipy.sparse.csr_matrix
 to_dense(self, 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
 property parameter_labels(self)¶
An array of labels (usually strings) describing this model member’s parameters.
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
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(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 deriv_wrt_params(self, wrt_filter=None)¶
The elementwise derivative this operation.
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_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
 Returns
numpy array – Array of derivatives with shape (dimension^2, num_params)
 to_memoized_dict(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 __str__(self)¶
Return string representation
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 class pygsti.modelmembers.operations.StaticArbitraryOp(m, 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
m (array_like or LinearOperator) – a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 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
unitary (numpy.ndarray) – The unitary action of the clifford operation.
symplecticrep (tuple, 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.
basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
evotype (Evotype or str) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 __str__(self)¶
Return string representation
 property smatrix(self)¶
 property svector(self)¶
 taylor_order_terms(self, 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
order (int) – Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve.max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 property total_term_magnitude(self)¶
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(self)¶
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(self, 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(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 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
name (str) – Standard gate name
basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 to_dense(self, 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(self, 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
order (int) – Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve.max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 property total_term_magnitude(self)¶
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(self)¶
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(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 __str__(self)¶
Return str(self).
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 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
m (array_like or LinearOperator) – a square 2D arraylike or LinearOperator object representing the operation action. The shape of m sets the dimension of the operation.
basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the HilbertSchmidt space representation of this state as a superoperator.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.
 taylor_order_terms(self, 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
order (int) – Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve.max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 property total_term_magnitude(self)¶
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(self)¶
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
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 class pygsti.modelmembers.operations.StochasticNoiseOp(state_space, basis='pp', evotype='default', initial_rates=None, seed_or_state=None)¶
Bases:
pygsti.modelmembers.operations.linearop.LinearOperator
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_space (StateSpace, optional) – The state space for this operation.
basis (Basis 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.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
initial_rates (list 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_state (float or RandomState, optional) – Random seed for RandomState (or directly provided RandomState) for sampling stochastic superoperators with the ‘chp’ evotype.
 _update_rep(self)¶
 _rates_to_params(self, rates)¶
 _params_to_rates(self, params)¶
 _get_rate_poly_dicts(self)¶
Return a list of dicts, one per rate, expressing the rate as a polynomial of the local parameters (tuple keys of dicts <=> poly terms, e.g. (1,1) <=> x1^2)
 to_dense(self, 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
 property num_params(self)¶
Get the number of independent parameters which specify this operation.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying operation parameters from this operation.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the operation using a vector of parameters.
 Parameters
v (numpy array) – The 1D vector of operation parameters. Length must == num_params()
close (bool, optional) – Whether v is close to this operation’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.
dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.
 Returns
None
 taylor_order_terms(self, 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
order (int) – Which order terms (in a Taylor expansion of this
LindbladOp
) to retrieve.max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.
return_coeff_polys (bool) – 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
terms (list) – A list of
RankOneTerm
objects.coefficients (list) – 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 :method:`Polynomial.compact`.
 property total_term_magnitude(self)¶
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(self)¶
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(self, mmg_memo)¶
Create a serializable dict with references to other objects in the memo.
 Parameters
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
 Returns
mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:
module, class, submembers, params, state_space, evotype
Additional fields may be added by derived classes.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 __str__(self)¶
Return str(self).
 _oneline_contents(self)¶
Summarizes the contents of this object in a single line. Does not summarize submembers.
 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.
 pygsti.modelmembers.operations.convert(operation, to_type, basis, extra=None)¶
Convert operation to a new type of parameterization.
This potentially creates a new LinearOperator object, and Raises ValueError for invalid conversions.
 Parameters
operation (LinearOperator) – 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 :method:`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).
extra (object, optional) – Additional information for conversion.
 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
operation (LinearOperator) – The operation object to test.
deriv_to_check (numpy.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_filter (list or numpy.ndarray) – List of parameter indices to filter the result by (as though derivative is only taken with respect to these parameters).
eps (float, 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_optimize (LinearOperator) – The operation to optimize. This object gets altered.
target_op (LinearOperator) – The operation whose matrix is used as the target.
 Returns
None