pygsti.modelmembers.operations.lindbladerrorgen.LindbladErrorgen#
- class LindbladErrorgen(lindblad_coefficient_blocks, elementary_errorgen_basis='auto', mx_basis='pp', evotype='default', state_space=None)#
Bases:
LinearOperatorA class for representing noisy quantum operations using Lindblad error generators.
Initialize a LindbladErrorgen object.
- Parameters:
lindblad_coefficient_blocks (list of LindbladCoefficientBlock) – A list of Lindblad coefficient blocks that define the error generator.
lindblad_basis ({'auto', 'PP', 'std', 'gm', 'qt'} or Basis object, optional) – The basis used for Lindblad terms. If ‘auto’, the basis is inferred from the coefficient blocks. Default is ‘auto’.
mx_basis ({'std', 'gm', 'pp', 'qt'} or Basis object, optional) – The basis for this error generator’s linear mapping. Default is ‘pp’.
evotype ({"default", "densitymx", "svterm", "cterm"}, optional) – The evolution type of the error generator being constructed. Default is “default”.
state_space (StateSpace, optional) – The state space for the error generator. Default is None.
- Raises:
ValueError – If the provided evotype does not support any of the required representations for a LindbladErrorgen.
Methods
__init__(lindblad_coefficient_blocks[, ...])Initialize a LindbladErrorgen object.
acton(state[, on_space])Act with this operator upon state
add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
allocate_gpindices(starting_index, parent[, ...])Sets gpindices array for this object or any objects it contains (i.e. depends upon).
coefficient_labels([label_type])The elementary error-generator labels corresponding to the elements of
coefficients_array().Return a dictionary whose keys are error generator coefficients, as given by :method:`coefficient_labels`, and whose value are the weights that have been specified for those coefficients. Note that weight != rate! These weights are used in conjunction with certain penalty factor options available in the construction of objective functions for parameters estimation purposes, and are not generally used outside of that setting.
coefficients([return_basis, ...])Constructs a dictionary of the Lindblad-error-generator coefficients of this error generator.
The weighted coefficients of this error generator in terms of "standard" error generators.
The jacobian of
coefficients_array()with respect to this error generator's parameters.Static method that converts a matrix-like object to a 2D numpy array.
copy([parent, memo])Copy this object.
depolarize(amount)Depolarize this operation by the given amount.
deriv_wrt_params([wrt_filter])The element-wise derivative this operation.
diamonddist(other_op[, transform, inv_transform])Return the diamond distance between this operation and other_op.
dump(f[, format])Serializes and writes this object to a given output stream.
dumps([format])Serializes this object and returns it as a string.
error_rates([label_type])Constructs a dictionary of the error rates associated with this error generator.
frobeniusdist(other[, transform, inv_transform])Return the Frobenius norm of the difference between self and other, possibly after transformation by transform and/or inv_transform.
frobeniusdist_squared(other[, transform, ...])Return the squared Frobenius norm of the difference between self and other, possibly after transformation by transform and/or inv_transform.
from_elementary_errorgens(elementary_errorgens)Construct a new LindbladErrorgen instance instantiated using a dictionary of elementary error generator coefficients and rates.
from_error_generator(errgen_or_dim[, ...])Construct a new LindbladErrorgen instance instantiated using a dense numpy array or sparse scipy array representation.
from_error_generator_and_blocks(...[, ...])Creates a Lindblad-parameterized error generator from an operation and a set of `LindbladCoefficientBlock`s.
from_memoized_dict(mm_dict, serial_memo, ...)Deserialize a ModelMember object and relink submembers from a memo.
from_mongodb(mongodb, doc_id, **kwargs)Create and initialize an object from a MongoDB instance.
from_mongodb_doc(mongodb, collection_name, ...)Create and initialize an object from a MongoDB instance and pre-loaded primary document.
from_nice_serialization(state)Create and initialize an object from a "nice" serialization.
from_operation_matrix(op_matrix[, ...])Creates a Lindblad-parameterized error generator from an operation.
from_operation_matrix_and_blocks(op_matrix, ...)Creates a Lindblad-parameterized error generator from an operation and a set of `LindbladCoefficientBlock`s.
from_vector(v[, close, dirty_value])Initialize the operation using a vector of parameters.
gpindices_are_allocated(model[, memo])Whether or not this model member's parameter indices are allocated within a potential parent model.
Returns gpindices as a numpy.ndarray of integers.
Whether this operation has a non-zero Hessian with respect to its parameters.
hessian_wrt_params([wrt_filter1, wrt_filter2])Construct the Hessian of this error generator with respect to its parameters.
highmagnitude_terms(min_term_mag[, ...])Get terms with magnitude above min_term_mag.
init_gpindices([allocated_to_parent])Initializes this model member's parameter indices by allocating them to an "anticipated" parent model.
is_equivalent(other[, rtol, atol])Comparator returning whether two ModelMembers are equivalent.
is_similar(other[, rtol, atol])Comparator returning whether two ModelMembers are the same type and parameterization.
jtracedist(other_op[, transform, inv_transform])Return the Jamiolkowski trace distance between this operation and other_op.
load(f[, format])Load an object of this type, or a subclass of this type, from an input stream.
loads(s[, format])Load an object of this type, or a subclass of this type, from a string.
Returns an upper bound on the 1-norm for this error generator (viewed as a matrix).
preallocate_gpindices(parent[, memo])Computes two key pieces of information for a model preparing to allocate this member.
read(path[, format])Read an object of this type, or a subclass of this type, from a file.
relink_parent(parent)Sets the parent of this object without altering its gpindices.
remove_from_mongodb(mongodb, doc_id[, ...])Remove the documents corresponding to an instance of this class from a MongoDB database.
remove_me_from_mongodb(mongodb[, session, ...])residuals(other[, transform, inv_transform])rotate(amount[, mx_basis])Rotate this operation by the given amount.
set_coefficient_weights(weights)Set the weights for the error generator coefficients in this error generator using a dictionary whose keys are error generator coefficients, as given by :method:`coefficient_labels`, and whose value are the weights that have been specified for those coefficients. Note that weight != rate! These weights are used in conjunction with certain penalty factor options available in the construction of objective functions for parameters estimation purposes, and are not generally used outside of that setting.
set_coefficients(elementary_errorgens[, ...])Sets the coefficients of elementary error generator terms in this error generator.
set_dense(m)Set the dense-matrix value of this operation.
set_error_rates(elementary_errorgens[, action])Sets the coeffcients of elementary error generator terms in this error generator.
set_gpindices(gpindices, parent[, memo])Set the parent and indices into the parent's parameter vector that are used by this ModelMember object.
set_time(t)Sets the current time for a time-dependent operator.
shift_gpindices(above, amount[, ...])Shifts this member's gpindices by the given amount.
spam_transform_inplace(s, typ)Update operation matrix O with inv(s) * O OR O * s, depending on the value of typ.
Returns a sequence of any sub-ModelMember objects contained in this one.
taylor_order_terms(order[, ...])Get the order-th order Taylor-expansion terms of this operation.
taylor_order_terms_above_mag(order, ...)Get the order-th order Taylor-expansion terms of this operation that have magnitude above min_term_mag.
to_dense([on_space])Return this error generator as a dense matrix.
to_memoized_dict(mmg_memo)Create a serializable dict with references to other objects in the memo.
Serialize this object in a way that adheres to "niceness" rules of common text file formats.
to_sparse([on_space])Return the error generator as a sparse matrix.
Extract a vector of the underlying operation parameters from this operation.
Update error generator E with inv(s) * E * s,
unlink_parent([force])Remove the parent-link of this member.
write(path, **format_kwargs)Writes this object to a file.
write_to_mongodb(mongodb[, session, ...])Write this object to a MongoDB database.
Attributes
A string suitable for printing to a CHP input file after probabilistically selecting operation.
collection_nameReturn the dimension of this operation (when viewed as a dense matrix)
Flag indicating whether this member's local parameters may have been updated without its parent's knowledge.
evotypeThe indices of this member's local parameters into the parent Model's parameter vector.
Return the number of independent elements in this operation as a dense Hilbert-Schmidt superoperator.
Get the number of independent parameters which specify this operation.
Upper and lower bounds on the values of each parameter, utilized by optimization routines
An array of labels (usually strings) describing this model member's parameters.
The parent of this object.
shapestate_spaceGet the total (sum) of the magnitudes of all this operator's terms.
The derivative of the sum of all this operator's terms.
- acton(state, on_space='minimal')#
Act with this operator upon state
- add_mongodb_write_ops(write_ops, mongodb, overwrite_existing=False, **kwargs)#
Accumulate write and update operations for writing this object to a MongoDB database.
Similar to
write_to_mongodb()but collects write operations instead of actually executing any write operations on the database. This function may be preferred towrite_to_mongodb()when this object is being written as a part of a larger entity and executing write operations is saved until the end.As in
write_to_mongodb(), self.collection_name is the collection name and _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId- Parameters:
write_ops (WriteOpsByCollection) – An object that keeps track of pymongo write operations on a per-collection basis. This object accumulates write operations to be performed at some point in the future.
mongodb (pymongo.database.Database) – The MongoDB instance to write data to.
overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.
- Returns:
The identifier (_id value) of the main document that was written.
- Return type:
bson.objectid.ObjectId
- allocate_gpindices(starting_index, parent, memo=None, submembers_already_allocated=False)#
Sets gpindices array for this object or any objects it contains (i.e. depends upon).
Indices may be obtained from contained objects which have already been initialized (e.g. if a contained object is shared with other top-level objects), or given new indices starting with starting_index.
- Parameters:
starting_index (int) – The starting index for un-allocated parameters.
parent (Model or ModelMember) – The parent whose parameter array gpindices references.
memo (set, optional) – Used to prevent duplicate calls and self-referencing loops. If memo contains an object’s id (id(self)) then this routine will exit immediately.
submembers_already_allocated (bool, optional) – Whether submembers of this object are known to already have their parameter indices allocated to parent. Leave this as False unless you know what you’re doing.
- Returns:
num_new – The number of new allocated parameters (so the parent should mark as allocated parameter indices starting_index to starting_index + new_new).
- Return type:
int
- coefficient_labels(label_type='global')#
The elementary error-generator labels corresponding to the elements of
coefficients_array().- Parameters:
label_type (str, optional (default 'global')) – String specifying which type of ElementaryErrorgenLabel to use as the keys for the returned dictionary. Allowed options are ‘global’ for GlobalElementaryErrorgenLabel and ‘local’ for LocalElementaryErrorgenLabel.
- Returns:
elem_errorgens – list of ElementaryErrorgenLabel, which wrap the (termType, basisLabel1, <basisLabel2>) information for each coefficient. Where termType is “H” (Hamiltonian), “S” (Stochastic), “C”`(Correlation) or `”A” (Affine). Hamiltonian and S terms always have a single basis label while ‘C’ and ‘A’ terms have two.
- Return type:
dict
- coefficient_weights()#
Return a dictionary whose keys are error generator coefficients, as given by :method:`coefficient_labels`, and whose value are the weights that have been specified for those coefficients. Note that weight != rate! These weights are used in conjunction with certain penalty factor options available in the construction of objective functions for parameters estimation purposes, and are not generally used outside of that setting.
- coefficients(return_basis=False, logscale_nonham=False, label_type='global')#
Constructs a dictionary of the Lindblad-error-generator coefficients of this error generator.
Note that these are not necessarily the parameter values as those parameter value correspond to the internal representation utilized, which may be constructed to enforce positivity constraints, for instance.
- Parameters:
return_basis (bool) – Whether to also return a
Basiscontaining the elements with which the error generator terms were constructed.logscale_nonham (bool, optional) – Whether or not the non-hamiltonian error generator coefficients should be scaled so that the returned dict contains: (1 - exp(-d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by
error_rates().label_type (str, optional (default 'global')) – String specifying which type of ElementaryErrorgenLabel to use as the keys for the returned dictionary. Allowed options are ‘global’ for GlobalElementaryErrorgenLabel and ‘local’ for LocalElementaryErrorgenLabel.
- Returns:
elem_errorgens (dict) – Keys are instances of ElementaryErrorgenLabel, which wrap the (termType, basisLabel1, <basisLabel2>) information for each coefficient. Where termType is “H” (Hamiltonian), “S” (Stochastic), “C”`(Correlation) or `”A” (Affine). Hamiltonian and S terms always have a single basis label while ‘C’ and ‘A’ terms have two.
basis (Basis) – A Basis mapping the basis labels used in the keys of elem_errorgens to basis matrices.
- coefficients_array()#
The weighted coefficients of this error generator in terms of “standard” error generators.
Constructs a 1D array of all the coefficients returned by
coefficients(), weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.- Returns:
A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this error generator.
- Return type:
numpy.ndarray
- coefficients_array_deriv_wrt_params()#
The jacobian of
coefficients_array()with respect to this error generator’s parameters.- Returns:
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.
- Return type:
numpy.ndarray
- static convert_to_matrix(m)#
Static method that converts a matrix-like object to a 2D numpy array.
- Parameters:
m (array_like) – matrix-like object
- Return type:
numpy array
- copy(parent=None, memo=None)#
Copy this object.
- Parameters:
parent (Model, optional) – The parent of the returned copy.
- Returns:
A copy of this object.
- Return type:
- depolarize(amount)#
Depolarize this operation by the given amount.
Generally, the depolarize function updates the parameters of the operation such that the resulting operation matrix is depolarized. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
- Parameters:
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 non-identity basis elements) equal 1.0 - amount[i] (or just 1.0 - amount if amount is a float).
- Return type:
None
- deriv_wrt_params(wrt_filter=None)#
The element-wise 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:
Array of derivatives, shape == (dimension^2, num_params)
- Return type:
numpy array
- diamonddist(other_op, transform=None, inv_transform=None)#
Return the diamond distance between this operation and other_op.
Optionally, tansforming this operation first as O => inv_transform * O * transform.
- Parameters:
other_op (DenseOperator) – The operation to compare against.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
- Return type:
float
- dump(f, format='json', **format_kwargs)#
Serializes and writes this object to a given output stream.
- Parameters:
f (file-like) – A writable output stream.
format ({'json', 'repr'}) – The format to write.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
None
- dumps(format='json', **format_kwargs)#
Serializes this object and returns it as a string.
- Parameters:
format ({'json', 'repr'}) – The format to write.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
str
- error_rates(label_type='global')#
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 multi-qubit 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*X-rho 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.
- Parameters:
label_type (str, optional (default 'global')) – String specifying which type of ElementaryErrorgenLabel to use as the keys for the returned dictionary. Allowed options are ‘global’ for GlobalElementaryErrorgenLabel and ‘local’ for LocalElementaryErrorgenLabel.
- Returns:
elem_errorgens – Keys are instances of ElementaryErrorgenLabel, which wrap the (termType, basisLabel1, <basisLabel2>) information for each coefficient. Where termType is “H” (Hamiltonian), “S” (Stochastic), “C”`(Correlation) or `”A” (Affine). Hamiltonian and S terms always have a single basis label while ‘C’ and ‘A’ terms have two.
- Return type:
dict
- frobeniusdist(other, transform=None, inv_transform=None)#
Return the Frobenius norm of the difference between self and other, possibly after transformation by transform and/or inv_transform.
- Parameters:
other (ModelMember)
transform (OperatorLike | None)
inv_transform (OperatorLike | None)
- Return type:
floating
- frobeniusdist_squared(other, transform=None, inv_transform=None)#
Return the squared Frobenius norm of the difference between self and other, possibly after transformation by transform and/or inv_transform.
- Parameters:
other (ModelMember)
transform (OperatorLike | None)
inv_transform (OperatorLike | None)
- Return type:
floating
- classmethod from_elementary_errorgens(elementary_errorgens, parameterization='auto', elementary_errorgen_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)#
Construct a new LindbladErrorgen instance instantiated using a dictionary of elementary error generator coefficients and rates.
- Parameters:
elementary_errorgens (dict) – A dictionary whose keys are `ElementaryErrogenLabel`s and whose values are corresponding error generator rates.
parameterization (LindbladParameterization or str castable to LindbladParameterization, optional (default ‘auto’)) –
Either an instance of LindbladParameterization or a string castable to a valid LindbladParameterization. This object specifies the internal parameterizations and coefficient blocks required for storing the data associated with this error generator and requisite for enforcing appropriate constraints. See documentation of LindbladParameterization for more details, but common examples include:
’auto’: A minimal parameterization is inferred based on the contents of elementary_errorgens. See the minimal_from_elementary_errorgens method of LindbladParameterization for more.
’CPTPLND’: A CPTP-constrained error generator parameterization
’GLND’: General Lindbladian, a non-CP (but still TP) constrained parameterization
’H’: A Hamiltonian-only parameterization (no ‘S’, ‘C’, or ‘A’ terms)
’H+S’: A Hamiltonian + Stochastic only parameterization (no ‘C’ or ‘A’ terms).
See aforementioned documentation for more details.
elementary_errorgen_basis (str or 'Basis', optional (default 'PP')) – The basis is used to construct the elementary error generator basis elements. Should be compatible with the basis element subscripts labeling the coefficients in elementary_errorgens. Most commonly ‘PP’, the unnormalized Pauli-product basis.
mx_basis (str or Basis object) – The basis in which to return matrix representation of the constructed error generator. E.g. ‘pp’, ‘gm’, ‘std’, etc…
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 error generator cannot be realized by the specified parameterization.
evotype (str or Evotype, optional (default ‘default’)) – The evolution type of the error generator being constructed. When specifying ‘default’ the evotype is automatically inferred/chosen. “densitymx” means usual Lioville density-matrix-vector propagation via matrix-vector products. “svterm” denotes state-vector term- based evolution (action of operation is obtained by evaluating the rank-1 terms up to some order). “cterm” is similar but uses Clifford operation action on stabilizer states.
state_space (StateSpace or castable to StateSpace) – The state space upon which this error generator acts.
- Return type:
LindbladErrorgen
- classmethod from_error_generator(errgen_or_dim, parameterization='CPTPLND', elementary_errorgen_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)#
Construct a new LindbladErrorgen instance instantiated using a dense numpy array or sparse scipy array representation.
- Parameters:
errgen_or_dim (numpy array or SciPy sparse matrix or int) – A square 2D array that gives the full error generator, or an integer specifying the dimension of an empty (all-zeros) 2D array to construct.
parameterization (LindbladParameterization or str castable to LindbladParameterization, optional (default ‘auto’)) –
Either an instance of LindbladParameterization or a string castable to a valid LindbladParameterization. This object specifies the internal parameterizations and coefficient blocks required for storing the data associated with this error generator and requisite for enforcing appropriate constraints. See documentation of LindbladParameterization for more details, but common examples include:
’auto’: A minimal parameterization is inferred based on the contents of elementary_errorgens. See the minimal_from_elementary_errorgens method of LindbladParameterization for more.
’CPTPLND’: A CPTP-constrained error generator parameterization
’GLND’: General Lindbladian, a non-CP (but still TP) constrained parameterization
’H’: A Hamiltonian-only parameterization (no ‘S’, ‘C’, or ‘A’ terms)
’H+S’: A Hamiltonian + Stochastic only parameterization (no ‘C’ or ‘A’ terms).
See aforementioned documentation for more details.
elementary_errorgen_basis (str or 'Basis', optional (default 'PP')) – The basis is used to construct the elementary error generator basis elements. Should be compatible with the basis element subscripts labeling the coefficients in elementary_errorgens. Most commonly ‘PP’, the unnormalized Pauli-product basis.
mx_basis (str or Basis object) – The basis in which to return matrix representation of the constructed error generator. E.g. ‘pp’, ‘gm’, ‘std’, etc…
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 error generator cannot be realized by the specified parameterization.
evotype (str or Evotype, optional (default ‘default’)) – The evolution type of the error generator being constructed. When specifying ‘default’ the evotype is automatically inferred/chosen. “densitymx” means usual Lioville density-matrix-vector propagation via matrix-vector products. “svterm” denotes state-vector term- based evolution (action of operation is obtained by evaluating the rank-1 terms up to some order). “cterm” is similar but uses Clifford operation action on stabilizer states.
state_space (StateSpace, optional (default None)) – StateSpace object to use in construction of this LindbladErrorgen. If None we use the function pygsti.baseobjs.statespace.default_space_for_dim to infer the correct state space from the dimensions of the passed in error generator.
- Return type:
LindbladErrorgen
- classmethod from_error_generator_and_blocks(errgen_or_dim, lindblad_coefficient_blocks, elementary_errorgen_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)#
Creates a Lindblad-parameterized error generator from an operation and a set of `LindbladCoefficientBlock`s.
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 by subsequently projecting this constructed error generator onto the specified LindbladCoefficientBlock`s. Note that since these blocks are user specified this projection may not be complete. E.g. passing in a general operation consisting of non-trivial ‘H’, ‘S’, ‘C’ and ‘A’ generators together with a single `LindbladCoefficientBlock for storing ‘H’ terms will result in an ‘H’-only generator.
- Parameters:
errgen_or_dim (numpy array or SciPy sparse matrix or int) – A square 2D array that gives the full error generator, or an integer specifying the dimension of an empty (all-zeros) 2D array to construct.
lindblad_coefficient_blocks (list of LindbladCoefficientBlocks) – List of LindbladCoefficientBlocks for storing the input error generator data given the projections onto these blocks.
elementary_errorgen_basis (str or 'Basis', optional (default 'PP')) – The basis is used to construct the elementary error generator basis elements. Should be compatible with the basis element subscripts labeling the coefficients in elementary_errorgens. Most commonly ‘PP’, the unnormalized Pauli-product basis.
mx_basis (str or Basis object) – The basis in which to return matrix representation of the constructed error generator. E.g. ‘pp’, ‘gm’, ‘std’, etc…
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 error generator cannot be realized by the specified parameterization.
evotype (str or Evotype, optional (default ‘default’)) – The evolution type of the error generator being constructed. When specifying ‘default’ the evotype is automatically inferred/chosen. “densitymx” means usual Lioville density-matrix-vector propagation via matrix-vector products. “svterm” denotes state-vector term- based evolution (action of operation is obtained by evaluating the rank-1 terms up to some order). “cterm” is similar but uses Clifford operation action on stabilizer states.
state_space (StateSpace, optional (default None)) – StateSpace object to use in construction of this LindbladErrorgen. If None we use the function pygsti.baseobjs.statespace.default_space_for_dim to infer the correct state space from the dimensions of the passed in error generator.
- Return type:
LindbladErrorgen
- classmethod from_memoized_dict(mm_dict, serial_memo, parent_model)#
Deserialize a ModelMember object and relink submembers from a memo.
- Parameters:
mm_dict (dict) – A dict representation of this ModelMember ready for deserialization This must have at least the following fields: module, class, submembers, state_space, evotype
serial_memo (dict) – Keys are serialize_ids and values are ModelMembers. This is NOT the same as other memos in ModelMember, (e.g. copy(), allocate_gpindices(), etc.). This is similar but not the same as mmg_memo in to_memoized_dict(), as we do not need to build a ModelMemberGraph for deserialization.
parent_model (Model) – The parent model that being build that will eventually hold this ModelMember object. It’s important to set this so that the Model considers the set gpindices valid and doesn’t just wipe them out when cleaning its parameter vector.
- Returns:
An initialized object
- Return type:
- classmethod from_mongodb(mongodb, doc_id, **kwargs)#
Create and initialize an object from a MongoDB instance.
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to load from.
doc_id (bson.objecctid.ObjectId or dict) – The object ID or filter used to find a single object ID within the database. This document is loaded from the collection given by the collection_name attribute of this class.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _create_obj_from_doc_and_mongodb method is allowed here.
- Return type:
object
- classmethod from_mongodb_doc(mongodb, collection_name, doc, **kwargs)#
Create and initialize an object from a MongoDB instance and pre-loaded primary document.
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to load from.
collection_name (str) – The collection name within mongodb that doc was loaded from. This is needed for the sole purpose of setting the created (returned) object’s database “coordinates”.
doc (dict) – The already-retrieved main document for the object being loaded. This takes the place of giving an identifier for this object.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _create_obj_from_doc_and_mongodb method is allowed here.
- Return type:
object
- classmethod from_nice_serialization(state)#
Create and initialize an object from a “nice” serialization.
A “nice” serialization here means one created by a prior call to to_nice_serialization using this class or a subclass of it. Nice serializations adhere to additional rules (e.g. that dictionary keys must be strings) that make them amenable to common file formats (e.g. JSON).
The state argument is typically a dictionary containing ‘module’ and ‘state’ keys specifying the type of object that should be created. This type must be this class or a subclass of it.
- Parameters:
state (object) – An object, usually a dictionary, representing the object to de-serialize.
- Return type:
object
- classmethod from_operation_matrix(op_matrix, parameterization='CPTPLND', elementary_errorgen_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)#
Creates a Lindblad-parameterized error generator from an operation.
Here “operation” means the exponentiated error generator, so this method essentially takes the matrix log of op_matrix and constructs an error generator from this using
from_error_generator().- Parameters:
op_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.
parameterization (LindbladParameterization or str castable to LindbladParameterization, optional (default ‘auto’)) –
Either an instance of LindbladParameterization or a string castable to a valid LindbladParameterization. This object specifies the internal parameterizations and coefficient blocks required for storing the data associated with this error generator and requisite for enforcing appropriate constraints. See documentation of LindbladParameterization for more details, but common examples include:
’auto’: A minimal parameterization is inferred based on the contents of elementary_errorgens. See the minimal_from_elementary_errorgens method of LindbladParameterization for more.
’CPTPLND’: A CPTP-constrained error generator parameterization
’GLND’: General Lindbladian, a non-CP (but still TP) constrained parameterization
’H’: A Hamiltonian-only parameterization (no ‘S’, ‘C’, or ‘A’ terms)
’H+S’: A Hamiltonian + Stochastic only parameterization (no ‘C’ or ‘A’ terms).
See aforementioned documentation for more details.
elementary_errorgen_basis (str or 'Basis', optional (default 'PP')) – The basis is used to construct the elementary error generator basis elements. Should be compatible with the basis element subscripts labeling the coefficients in elementary_errorgens. Most commonly ‘PP’, the unnormalized Pauli-product basis.
mx_basis (str or Basis object) – The basis in which to return matrix representation of the constructed error generator. E.g. ‘pp’, ‘gm’, ‘std’, etc…
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 error generator cannot be realized by the specified parameterization.
evotype (str or Evotype, optional (default ‘default’)) – The evolution type of the error generator being constructed. When specifying ‘default’ the evotype is automatically inferred/chosen. “densitymx” means usual Lioville density-matrix-vector propagation via matrix-vector products. “svterm” denotes state-vector term- based evolution (action of operation is obtained by evaluating the rank-1 terms up to some order). “cterm” is similar but uses Clifford operation action on stabilizer states.
state_space (StateSpace or castable to StateSpace) – The state space upon which this error generator acts.
- Return type:
LindbladErrorgen
- classmethod from_operation_matrix_and_blocks(op_matrix, lindblad_coefficient_blocks, elementary_errorgen_basis='PP', mx_basis='pp', truncate=True, evotype='default', state_space=None)#
Creates a Lindblad-parameterized error generator from an operation and a set of `LindbladCoefficientBlock`s.
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 by subsequently projecting this constructed error generator onto the specified LindbladCoefficientBlock`s. Note that since these blocks are user specified this projection may not be complete. E.g. passing in a general operation consisting of non-trivial ‘H’, ‘S’, ‘C’ and ‘A’ generators together with a single `LindbladCoefficientBlock for storing ‘H’ terms will result in an ‘H’-only 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.
lindblad_coefficient_blocks (list of LindbladCoefficientBlocks) – List of LindbladCoefficientBlocks for storing the input error generator data given the projections onto these blocks.
elementary_errorgen_basis (str or 'Basis', optional (default 'PP')) – The basis is used to construct the elementary error generator basis elements. Should be compatible with the basis element subscripts labeling the coefficients in elementary_errorgens. Most commonly ‘PP’, the unnormalized Pauli-product basis.
mx_basis (str or Basis object) – The basis in which to return matrix representation of the constructed error generator. E.g. ‘pp’, ‘gm’, ‘std’, etc…
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 error generator cannot be realized by the specified parameterization.
evotype (str or Evotype, optional (default ‘default’)) – The evolution type of the error generator being constructed. When specifying ‘default’ the evotype is automatically inferred/chosen. “densitymx” means usual Lioville density-matrix-vector propagation via matrix-vector products. “svterm” denotes state-vector term- based evolution (action of operation is obtained by evaluating the rank-1 terms up to some order). “cterm” is similar but uses Clifford operation action on stabilizer states.
state_space (StateSpace or castable to StateSpace) – The state space upon which this error generator acts.
- Return type:
LindbladErrorgen
- from_vector(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.
- Return type:
None
- gpindices_are_allocated(model, memo=None)#
Whether or not this model member’s parameter indices are allocated within a potential parent model.
This is used to infer when the model member needs to have its parameter indices reallocated (by its parent model).
- Parameters:
model (Model) – Test for parameter allocation with respect to this model.
memo (dict, optional) – Used to prevent duplicate calls and self-referencing loops. If memo contains an object’s id (id(self)) then this routine will exit immediately with a cached value.
- Returns:
True if this member’s .gpindices and those of its sub-members are not None and refer to parameter indices of model.
- Return type:
bool
- gpindices_as_array()#
Returns gpindices as a numpy.ndarray of integers.
The underlying .gpindices attribute itself can be None, a slice, or an integer array. If gpindices is None, an empty array is returned.
- Return type:
numpy.ndarray
- has_nonzero_hessian()#
Whether this operation has a non-zero Hessian with respect to its parameters.
(i.e. whether it only depends linearly on its parameters or not)
- Return type:
bool
- hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)#
Construct the Hessian of this error generator with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
- Parameters:
wrt_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:
Hessian with shape (dimension^2, num_params1, num_params2)
- Return type:
numpy array
- highmagnitude_terms(min_term_mag, force_firstorder=True, max_taylor_order=3, max_polynomial_vars=100)#
Get terms with magnitude above min_term_mag.
Get the terms (from a Taylor expansion of this operator) that have magnitude above min_term_mag (the magnitude of a term is taken to be the absolute value of its coefficient), considering only those terms up to some maximum Taylor expansion order, max_taylor_order.
Note that this function also sets the magnitudes of the returned terms (by calling term.set_magnitude(…)) based on the current values of this operator’s parameters. This is an essential step to using these terms in pruned-path-integral 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 first-order Taylor-series terms, even if they have magnitudes smaller than min_term_mag. This behavior is needed for using GST with pruned-term 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 Taylor-order 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 high-magnitude terms that were found. These terms are sorted in descending order by term-magnitude.
first_order_indices (list) – A list of the indices into highmag_terms that mark which of these terms are first-order Taylor terms (useful when we’re forcing these terms to always be present).
- init_gpindices(allocated_to_parent=None)#
Initializes this model member’s parameter indices by allocating them to an “anticipated” parent model.
Objects with submembers often rely on having valid .gpindices and .subm_rpindices attributes, but these aren’t set until the object is allocated to a parent model. This method initializes these attributes in the best way possible before receiving the actual parent model. Typically model members (containing sub-members) are build in two ways:
The sub-members are all un-allocated, i.e. their .parent model is None
The sub-members are all allocated to the same parent model.
This method computes an “anticipated parent” model as the common parent of all the submembers (if one exists) or None, and calls
allocate_gpindices()using this parent model and a starting index of 0. This has the desired behavior in the two cases above. In case 1, parameter indices are set (allocated) but the parent is set to None, so that the to-be parent model will see this member as being unallocated. In case 2, the parent model, if it is the anticipated one, will see that this member’s indices are already allocated to it, and won’t need to re-allocate them.
- is_equivalent(other, rtol=1e-05, atol=1e-08)#
Comparator returning whether two ModelMembers are equivalent.
This uses is_similar for type checking and NumPy allclose for parameter checking, so is unlikely to be needed to overload.
Note that this only checks for NUMERICAL equivalence, not whether the objects are the same.
- Parameters:
other (ModelMember) – ModelMember to compare to
rtol (float) – Relative tolerance for floating point comparisons (passed to numpy.isclose)
atol (float) – Absolute tolerance for floating point comparisons (passed to numpy.isclose)
- Returns:
True if structure AND parameter vectors match
- Return type:
bool
- is_similar(other, rtol=1e-05, atol=1e-08)#
Comparator returning whether two ModelMembers are the same type and parameterization.
ModelMembers with internal parameterization information (e.g. LindbladErrorgen) should overload this function to account for that.
- Parameters:
other (ModelMember) – ModelMember to compare to
rtol (float) – Relative tolerance for floating point comparisons (passed to numpy.isclose)
atol (float) – Absolute tolerance for floating point comparisons (passed to numpy.isclose)
- Returns:
True if structure (all but parameter values) matches
- Return type:
bool
- jtracedist(other_op, transform=None, inv_transform=None)#
Return the Jamiolkowski trace distance between this operation and other_op.
Optionally, tansforming this operation first as O => inv_transform * O * transform.
- Parameters:
other_op (DenseOperator) – The operation to compare against.
transform (numpy.ndarray, optional) – Transformation matrix.
inv_transform (numpy.ndarray, optional) – Inverse of transform.
- Return type:
float
- classmethod load(f, format='json')#
Load an object of this type, or a subclass of this type, from an input stream.
- Parameters:
f (file-like) – An open input stream to read from.
format ({'json'}) – The format of the input stream data.
- Return type:
- classmethod loads(s, format='json')#
Load an object of this type, or a subclass of this type, from a string.
- Parameters:
s (str) – The serialized object.
format ({'json'}) – The format of the string data.
- Return type:
- onenorm_upperbound()#
Returns an upper bound on the 1-norm for this error generator (viewed as a matrix).
- Return type:
float
- preallocate_gpindices(parent, memo=None)#
Computes two key pieces of information for a model preparing to allocate this member.
These pieces of information are:
the total number of new parameters that would need to be allocated to parent in order to have all this model member’s parameters allocated to parent.
the largest parameter index from all the parameters already allocated to parent. This is useful for providing an ideal insertion point for the new parameters, once the model has made space for them.
Note that this function does not update this model member’s .gpindces or other attributes at all - it just serves as a pre-allocation probe so that the allocating model knows how much space in its parameter vector is needed/ requested by this perhaps-not-fully-allocated member.
- Parameters:
parent (Model) – The model that parameter allocation is being considered with respect to.
memo (set, optional) – Used to prevent duplicate calls and self-referencing loops. If memo contains an object’s id (id(self)) then this routine will exit immediately..
- Returns:
num_new_params (int) – the number of parameters that aren’t currently allocated to parent
max_index (int) – the maximum index of the parameters currently allocated to parent
- classmethod read(path, format=None)#
Read an object of this type, or a subclass of this type, from a file.
- Parameters:
path (str or Path or file-like) – The filename to open or an already open input stream.
format ({'json', None}) – The format of the file. If None this is determined automatically by the filename extension of a given path.
- Return type:
- relink_parent(parent)#
Sets the parent of this object without altering its gpindices.
This operation is appropriate to do when “re-linking” a parent with its children after the parent and child have been serialized. (the parent is not saved in serialization - see ModelChild.__getstate__ – and so must be manually re-linked upon de-serialization).
In addition to setting the parent of this object, this method sets the parent of any objects this object contains (i.e. depends upon) - much like allocate_gpindices. To ensure a valid parent is not overwritten, the existing parent must be None prior to this call.
- Parameters:
parent (Model) – The model to (re-)set as the parent of this member.
- Return type:
None
- classmethod remove_from_mongodb(mongodb, doc_id, collection_name=None, session=None, recursive='default')#
Remove the documents corresponding to an instance of this class from a MongoDB database.
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to remove documents from.
doc_id (bson.objectid.ObjectId) – The identifier of the root document stored in the database.
collection_name (str, optional) – the MongoDB collection within mongodb where the main document resides. If None, then <this_class>.collection_name is used (which is usually what you want).
session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.
recursive (RecursiveRemovalSpecification, optional) – An object that filters the type of documents that are removed. Used when working with inter-related experiment designs, data, and results objects to only remove the types of documents you know aren’t being shared with other documents.
- Return type:
None
- rotate(amount, mx_basis='gm')#
Rotate this operation by the given amount.
Generally, the rotate function updates the parameters of the operation such that the resulting operation matrix is rotated. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
- Parameters:
amount (tuple of floats, optional) – Specifies the rotation “coefficients” along each of the non-identity Pauli-product 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 non-identity un-normalized Pauli operators.
mx_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).
- Return type:
None
- set_coefficient_weights(weights)#
Set the weights for the error generator coefficients in this error generator using a dictionary whose keys are error generator coefficients, as given by :method:`coefficient_labels`, and whose value are the weights that have been specified for those coefficients. Note that weight != rate! These weights are used in conjunction with certain penalty factor options available in the construction of objective functions for parameters estimation purposes, and are not generally used outside of that setting.
- Parameters:
weights (dict) – A dictionary where keys are coefficient labels and values are the corresponding weights to set.
- set_coefficients(elementary_errorgens, action='update', logscale_nonham=False, truncate=True)#
Sets the coefficients of elementary error generator terms in this error generator.
The dictionary elementary_errorgens has keys which are ElementaryErrorgenLabel`s describing the type of term and the basis elements used to construct it, e.g. `(‘H’,’X’), together with the corresponding rates.
- Parameters:
elementary_errorgens (dict) – Dictionary whose keys are instances of ElementaryErrorgenLabel, which wrap the (termType, basisLabel1, <basisLabel2>) information for each coefficient, and whose values are corresponding error generator rates for each coefficient. Where termType is “H” (Hamiltonian), “S” (Stochastic), “C”`(Correlation) or `”A” (Affine). Hamiltonian and S terms always have a single basis label while ‘C’ and ‘A’ terms have two.
action ({"update","add","reset"}) – How the values in lindblad_term_dict should be combined with existing error-generator coefficients.
logscale_nonham (bool, optional) – Whether or not the values in lindblad_term_dict for non-hamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see
errorgen_coefficients()) instead of raw coefficients. If True, then the non-hamiltonian coefficients are set to -log(1 - d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the functionset_error_rates().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.
- Return type:
None
- set_dense(m)#
Set the dense-matrix 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.
- Return type:
None
- set_error_rates(elementary_errorgens, action='update')#
Sets the coeffcients of elementary error generator 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 elementary_errorgens. See
error_rates()for more details.- Parameters:
elementary_errorgens (dict) – Dictionary whose keys are instances of ElementaryErrorgenLabel, which wrap the (termType, basisLabel1, <basisLabel2>) information for each coefficient, and whose values are corresponding error generator rates for each coefficient. Where termType is “H” (Hamiltonian), “S” (Stochastic), “C”`(Correlation) or `”A” (Affine). Hamiltonian and S terms always have a single basis label while ‘C’ and ‘A’ terms have two.
action ({"update","add","reset"}) – How the values in lindblad_term_dict should be combined with existing error-generator coefficients.
action – How the values in lindblad_term_dict should be combined with existing error rates.
- Return type:
None
- set_gpindices(gpindices, parent, memo=None)#
Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.
- Parameters:
gpindices (slice or integer ndarray) – The indices of this objects parameters in its parent’s array.
parent (Model) – The parent whose parameter array gpindices references.
memo (set, optional) – A set keeping track of the object ids that have had their indices set in a root set_gpindices call. Used to prevent duplicate calls and self-referencing loops. If memo contains an object’s id (id(self)) then this routine will exit immediately.
- Return type:
None
- set_time(t)#
Sets the current time for a time-dependent operator.
For time-independent operators (the default), this function does nothing.
- Parameters:
t (float) – The current time.
- Return type:
None
- shift_gpindices(above, amount, parent_filter=None, memo=None)#
Shifts this member’s gpindices by the given amount.
Usually called by the parent model when it shifts parameter indices around in its parameter vector.
- Parameters:
above (int) – The “insertion point” within the range of indices. All indices greater than or equal to this index are shifted.
amount (int) – The amount to shift indices greater than or equal to above by.
parent_filter (Model or None) – If a
Modelobject, then only those members with indices allocated to this model will be shifted. It usually makes sense to specify this argument, supplying the parent model whose parameter vector is being shifted.memo (set, optional) – A set keeping track of the object ids that have had their indices set in a root set_gpindices call. Used to prevent duplicate calls and self-referencing loops. If memo contains an object’s id (id(self)) then this routine will exit immediately.
- Return type:
None
- spam_transform_inplace(s, typ)#
Update operation matrix O with inv(s) * O OR O * s, depending on the value of typ.
This functions as transform_inplace(…) but is used when this operation is used as a part of a SPAM vector. When typ == “prep”, the spam vector is assumed to be rho = dot(self, <spamvec>), which transforms as rho -> inv(s) * rho, so self -> inv(s) * self. When typ == “effect”, e.dag = dot(e.dag, self) (note that self is NOT self.dag here), and e.dag -> e.dag * s so that self -> self * s.
- Parameters:
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).
- Return type:
None
- submembers()#
Returns a sequence of any sub-ModelMember objects contained in this one.
Sub-members are processed by other
ModelMembermethods (e.g. unlink_parent and set_gpindices) as though the parent object is just a container for these sub-members and has no parameters of its own. Member objects that contain other members and possess their own independent parameters should implement the appropriate ModelMember functions (usually just allocate_gpindices, using the base implementation as a reference).- Return type:
list or tuple
- taylor_order_terms(order, max_polynomial_vars=100, return_coeff_polys=False)#
Get the order-th order Taylor-expansion terms of this operation.
This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, 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 locally-indexed (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
RankOneTermobjects.coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2-tuple formed by concatenating together the output of
Polynomial.compact().
- taylor_order_terms_above_mag(order, max_polynomial_vars, min_term_mag)#
Get the order-th order Taylor-expansion terms of this operation that have magnitude above min_term_mag.
This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls
taylor_order_terms()internally, so that all the terms at order order are typically cached for future calls.The coefficients of these terms are typically polynomials of the operation’s parameters, where the polynomial’s variable indices index the global parameters of the operation’s parent (usually a
Model), not the operation’s local parameter array (i.e. that returned from to_vector).- Parameters:
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:
A list of
Rank1Termobjects.- Return type:
list
- to_dense(on_space='minimal')#
Return this error generator as a dense matrix.
- Parameters:
on_space ({'minimal', 'Hilbert', 'HilbertSchmidt'}) – The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and super-bra/super-ket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.
- Return type:
numpy.ndarray
- to_memoized_dict(mmg_memo)#
Create a serializable dict with references to other objects in the memo.
- Parameters:
mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).
- Returns:
mm_dict – 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.
- Return type:
dict
- to_nice_serialization()#
Serialize this object in a way that adheres to “niceness” rules of common text file formats.
- Returns:
Usually a dictionary representing the serialized object, but may also be another native Python type, e.g. a string or list.
- Return type:
object
- to_sparse(on_space='minimal')#
Return the error generator as a sparse matrix.
- Return type:
scipy.sparse.csr_matrix
- Parameters:
on_space (Literal['minimal', 'Hilbert', 'HilbertSchmidt'])
- to_vector()#
Extract a vector of the underlying operation parameters from this operation.
- Returns:
a 1D numpy array with length == num_params().
- Return type:
numpy array
- transform_inplace(s)#
Update error generator E with inv(s) * E * s,
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
- Parameters:
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
- Return type:
None
- unlink_parent(force=False)#
Remove the parent-link of this member.
Called when at least one reference (via key) to this object is being disassociated with parent. If all references are to this object are now gone, set parent to None, invalidating any gpindices.
- Parameters:
force (bool, optional) –
If True, then resets parent to None, effectively de-allocating the model member’s parameters from the parent model, even if the parent still contains references to it. If False, the parent is only set to None when its parent contains no reference to it.
Passed through to unlink_parent calls for submembers of this model member.
- Return type:
None
- write(path, **format_kwargs)#
Writes this object to a file.
- Parameters:
path (str or Path) – The name of the file that is written.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
None
- write_to_mongodb(mongodb, session=None, overwrite_existing=False, **kwargs)#
Write this object to a MongoDB database.
The collection name used is self.collection_name, and the _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to write data to.
session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.
overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.
- Returns:
The identifier (_id value) of the main document that was written.
- Return type:
bson.objectid.ObjectId
- property chp_str#
A string suitable for printing to a CHP input file after probabilistically selecting operation.
- Returns:
s – String of CHP code
- Return type:
str
- property dim#
Return the dimension of this operation (when viewed as a dense matrix)
- Return type:
int
- property dirty: bool#
Flag indicating whether this member’s local parameters may have been updated without its parent’s knowledge.
- property gpindices#
The indices of this member’s local parameters into the parent Model’s parameter vector.
- Return type:
slice or numpy.ndarray
- property hilbert_schmidt_size#
Return the number of independent elements in this operation as a dense Hilbert-Schmidt superoperator.
- Return type:
int
- property num_params#
Get the number of independent parameters which specify this operation.
- Returns:
the number of independent parameters.
- Return type:
int
- property parameter_bounds: ndarray | None#
Upper and lower bounds on the values of each parameter, utilized by optimization routines
- property parameter_labels#
An array of labels (usually strings) describing this model member’s parameters.
- property total_term_magnitude#
Get the total (sum) of the magnitudes of all this operator’s terms.
The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolute-coefficients of all the Taylor terms (at all orders!) you get from expanding this operator in a Taylor series.
- Return type:
float
- property total_term_magnitude_deriv#
The derivative of the sum of all this operator’s terms.
Computes the derivative of the total (sum) of the magnitudes of all this operator’s terms with respect to the operators (local) parameters.
- Returns:
An array of length self.num_params
- Return type:
numpy array