pygsti.modelmembers.states.tensorprodstate.TensorProductState

Contents

pygsti.modelmembers.states.tensorprodstate.TensorProductState#

class TensorProductState(factors, state_space)#

Bases: State

A state vector that is a tensor-product of other state vectors.

Parameters:
  • factors (list of States) – a list of the component states to take the tensor product of.

  • state_space (StateSpace, optional) – The state space for this operation.

Initialize a new state Vector

Methods

__init__(factors, state_space)

Initialize a new state Vector

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

copy([parent, memo])

Copy this object.

depolarize(amount)

Depolarize this state vector by the given amount.

deriv_wrt_params([wrt_filter])

The element-wise derivative this state vector.

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 state vector using a 1D array of parameters.

gpindices_are_allocated(model[, memo])

Whether or not this model member's parameter indices are allocated within a potential parent model.

gpindices_as_array()

Returns gpindices as a numpy.ndarray of integers.

has_nonzero_hessian()

Whether this state vector has a non-zero Hessian with respect to its parameters.

hessian_wrt_params([wrt_filter1, wrt_filter2])

Construct the Hessian of this state vector 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.

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])

set_dense(vec)

Set the dense-vector value of this state vector.

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.

submembers()

Get the ModelMember-derived objects contained in this one.

taylor_order_terms(order[, ...])

Get the order-th order Taylor-expansion terms of this state vector.

taylor_order_terms_above_mag(order, ...)

Get the order-th order Taylor-expansion terms of this state vector that have magnitude above min_term_mag.

to_dense([on_space, scratch])

Return this state vector as a (dense) numpy array.

to_memoized_dict(mmg_memo)

Create a serializable dict with references to other objects in the memo.

to_nice_serialization()

Serialize this object in a way that adheres to "niceness" rules of common text file formats.

to_vector()

Get the state vector parameters as an array of values.

transform_inplace(s)

Update state preparation (column) vector V as inv(s) * V.

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

collection_name

dim

Return the dimension of this state (when viewed as a dense array)

dirty

Flag indicating whether this member's local parameters may have been updated without its parent's knowledge.

evotype

gpindices

The indices of this member's local parameters into the parent Model's parameter vector.

hilbert_schmidt_size

Return the number of independent elements in this state as a dense Hilbert-Schmidt super-ket.

num_params

Get the number of independent parameters which specify this state vector.

parameter_bounds

Upper and lower bounds on the values of each parameter, utilized by optimization routines

parameter_labels

An array of labels (usually strings) describing this model member's parameters.

parent

The parent of this object.

state_space

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 to write_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

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:

LinearOperator

depolarize(amount)#

Depolarize this state vector by the given amount.

Generally, the depolarize function updates the parameters of the State such that the resulting vector is depolarized. If such an update cannot be done (because the gate 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 gate. All but the first element of the spam vector (often corresponding to the identity element) are multiplied by amount (if a float) or the corresponding amount[i] (if a tuple).

Return type:

None

deriv_wrt_params(wrt_filter=None)#

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.

Parameters:

wrt_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, num_params)

Return type:

numpy array

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

ModelMember

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 state vector using a 1D array of parameters.

Parameters:
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_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 state vector has a non-zero Hessian with respect to its parameters.

Return type:

bool

hessian_wrt_params(wrt_filter1=None, wrt_filter2=None)#

Construct the Hessian of this state vector with respect to its parameters.

This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.

Parameters:
  • wrt_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, 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 state vector) 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 state vector’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:

  1. The sub-members are all un-allocated, i.e. their .parent model is None

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

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:

NicelySerializable

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:

NicelySerializable

preallocate_gpindices(parent, memo=None)#

Computes two key pieces of information for a model preparing to allocate this member.

These pieces of information are:

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

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

NicelySerializable

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

set_dense(vec)#

Set the dense-vector value of this state vector.

Attempts to modify this state vector’s parameters so that the raw state vector becomes vec. Will raise ValueError if this operation is not possible.

Parameters:

vec (array_like or State) – A numpy array representing a state vector, or a State object.

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 absolutely 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 Model object, 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

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

This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, meaning that it is a state preparation followed by or POVM effect preceded by actions on a density matrix rho of the form:

rho -> A rho B

The coefficients of these terms are typically polynomials of the State’s parameters, where the polynomial’s variable indices index the global parameters of the State’s parent (usually a Model) , not the State’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 RankOneTerm objects.

  • coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 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 state vector 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.

Parameters:
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • min_term_mag (float) – the minimum term magnitude.

Return type:

list

to_dense(on_space='minimal', scratch=None)#

Return this state vector as a (dense) numpy array.

The memory in scratch maybe used when it is not-None.

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.

  • scratch (numpy.ndarray, optional) – scratch space available for use.

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_vector()#

Get the state vector parameters as an array of values.

Returns:

The parameters as a 1D array with length num_params().

Return type:

numpy array

transform_inplace(s)#

Update state preparation (column) vector V as inv(s) * V.

Note that this is equivalent to state preparation vectors getting mapped: rho -> inv(s) * rho.

Generally, the transform function updates the parameters of the state vector such that the resulting vector is altered as described above. If such an update cannot be done (because the gate 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

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 dim#

Return the dimension of this state (when viewed as a dense array)

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 state as a dense Hilbert-Schmidt super-ket.

Return type:

int

property num_params#

Get the number of independent parameters which specify this state vector.

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 parent: Model | None#

The parent of this object.

Return type:

Model