pygsti.modelmembers.operations.opfactory.EmbeddedOpFactory

pygsti.modelmembers.operations.opfactory.EmbeddedOpFactory#

class EmbeddedOpFactory(state_space, target_labels, factory_to_embed)#

Bases: OpFactory

A factory that embeds a given factory’s action into a single, pre-defined set of target sectors.

Parameters:
  • state_space (StateSpace) – The state space of this factory, describing the space of these that the operations produced by this factory act upon.

  • target_labels (list of strs) – The labels contained in state_space_labels which demarcate the portions of the state space acted on by the operations produced by factory_to_embed (the “contained” factory).

  • factory_to_embed (OpFactory) – The factory object that is to be contained within this factory, and that specifies the only non-trivial action of the operations this factory produces.

Initialize a new ModelMember

Methods

__init__(state_space, target_labels, ...)

Initialize a new ModelMember

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.

create_object([args, sslbls])

Create the object that implements the operation associated with the given args and sslbls.

create_op([args, sslbls])

Create the operation associated with the given args and sslbls.

create_simplified_op([args, sslbls, item_lbl])

Create the simplified operation associated with the given args, sslbls, and item_lbl.

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 this OpFactory using a vector of its 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.

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_gpindices(gpindices, parent[, memo])

Set the parent and indices into the parent's parameter vector that are used by this ModelMember object.

shift_gpindices(above, amount[, ...])

Shifts this member's gpindices by the given amount.

submembers()

Get the ModelMember-derived objects contained in this one.

to_dense()

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

Extract a vector of the underlying gate parameters from this OpFactory.

transform_inplace(s)

Update OpFactory so that created ops O are additionally transformed as 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

collection_name

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.

num_params

Get the number of independent parameters which specify this OpFactory.

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

create_object(args=None, sslbls=None)#

Create the object that implements the operation associated with the given args and sslbls.

Note to developers The difference beween this method and create_op() is that this method just creates the foundational object without needing to setup its parameter indices (a technical detail which connects the created object with the originating factory’s parameters). The base-class create_op method calls create_object and then performs some additional setup on the returned object before returning it itself. Thus, unless you have a reason for implementing create_op it’s often more convenient and robust to implement this function.

Parameters:
  • args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.

  • sslbls (list or tuple) – The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).

Returns:

Can be any type of operation, e.g. a LinearOperator, SPAMVec, Instrument, or POVM, depending on the label requested.

Return type:

ModelMember

create_op(args=None, sslbls=None)#

Create the operation associated with the given args and sslbls.

Parameters:
  • args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.

  • sslbls (list or tuple) – The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).

Returns:

Can be any type of operation, e.g. a LinearOperator, State, Instrument, or POVM, depending on the label requested.

Return type:

ModelMember

create_simplified_op(args=None, sslbls=None, item_lbl=None)#

Create the simplified operation associated with the given args, sslbls, and item_lbl.

Similar to as create_op(), but returns a simplified operation (i.e. not a POVM or Instrument). In addition, the item_lbl argument must be used for POVMs and Instruments, as these need to know which (simple) member of themselves to return (this machinery still needs work).

That is, if create_op returns something like a POVM or an Instrument, this method returns a single effect or instrument-member operation (a single linear-operator or SPAM vector).

Parameters:
  • args (list or tuple) – The arguments for the operation to be created. None means no arguments were supplied.

  • sslbls (list or tuple) – The list of state space labels the created operator should act on. If None, then these labels are unspecified and should be irrelevant to the construction of the operator (which typically, in this case, has some fixed dimension and no noition of state space labels).

  • item_lbl (str, optional) – Effect or instrument-member label (index) for factories that create POVMs or instruments, respectively.

Returns:

Can be any type of siple operation, e.g. a LinearOperator or SPAMVec, depending on the label requested.

Return type:

ModelMember

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 this OpFactory using a vector of its parameters.

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

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

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

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

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

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

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

Extract a vector of the underlying gate parameters from this OpFactory.

Returns:

a 1D numpy array with length == num_params().

Return type:

numpy array

transform_inplace(s)#

Update OpFactory so that created ops O are additionally transformed as inv(s) * O * s.

Parameters:

s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.

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

Get the number of independent parameters which specify this OpFactory.

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