pygsti.modelmembers.operations.repeatedop.RepeatedOp#
- class RepeatedOp(op_to_repeat, num_repetitions, evotype='auto')#
Bases:
LinearOperatorAn operation map that is the composition of a number of map-like factors (possibly other LinearOperator)
- Parameters:
op_to_repeat (list) – A LinearOperator-derived object that is repeated some integer number of times to produce this operator.
num_repetitions (int) – the power to exponentiate op_to_exponentiate to.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype. The special value “auto” uses the evolutio ntype of op_to_repeat.
Initialize a new LinearOperator
Methods
__init__(op_to_repeat, num_repetitions[, ...])Initialize a new LinearOperator
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).
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.
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_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_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 operation 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.
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_dense(m)Set the dense-matrix value of this operation.
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.
Get the ModelMember-derived 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 operation 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 operation as a sparse matrix
Get the operation parameters as an array of values.
Update operation matrix O with inv(s) * O * 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_space- 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
- 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.
Constructs a matrix whose columns are the vectorized derivatives of the flattened operation matrix with respect to a single operation parameter. Thus, each column is of length op_dim^2 and there is one column per operation parameter. An empty 2D array in the StaticArbitraryOp case (num_params == 0).
- Parameters:
wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)
- Returns:
Array of derivatives with 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
- 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_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
- 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 operation with respect to its parameters.
This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.
- Parameters:
wrt_filter1 (list or numpy.ndarray) – List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)
wrt_filter2 (list or numpy.ndarray) – List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)
- Returns:
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:
- 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_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_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()#
Get the ModelMember-derived objects contained in this one.
- Return type:
list
- 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 operation as a dense matrix.
- Parameters:
on_space ({'minimal', 'Hilbert', 'HilbertSchmidt'}) – The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and 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 operation as a sparse matrix
- Return type:
scipy.sparse.csr_matrix
- Parameters:
on_space (Literal['minimal', 'Hilbert', 'HilbertSchmidt'])
- to_vector()#
Get the operation parameters as an array of values.
- Returns:
The operation parameters as a 1D array with length num_params().
- Return type:
numpy array
- transform_inplace(s)#
Update operation matrix O with inv(s) * O * s.
Generally, the transform function updates the parameters of the operation such that the resulting operation matrix is altered as described above. If such an update cannot be done (because the operation parameters do not allow for it), ValueError is raised.
In this particular case any transform of the appropriate dimension is possible, since all operation matrix elements are parameters.
- Parameters:
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.