pygsti.modelmembers.operations.lindbladerrorgen
¶
The LindbladErrorgen class and supporting functionality.
Module Contents¶
Classes¶
An Lindbladform error generator. 

An object encapsulating a particular way of parameterizing a LindbladErrorgen 
Attributes¶
 pygsti.modelmembers.operations.lindbladerrorgen.IMAG_TOL = 1e07¶
 class pygsti.modelmembers.operations.lindbladerrorgen.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.lindbladerrorgen.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).