pygsti.baseobjs.basis.TensorProdBasis#
- class TensorProdBasis(component_bases, name=None, longname=None)#
Bases:
LazyBasisA Basis that is the tensor product of one or more “component” bases.
The elements of a TensorProdBasis consist of all tensor products of component basis elements (respecting the order given). The components of a TensorProdBasis must be simple bases so that kronecker products can be used to produce the parent basis’s elements.
A TensorProdBasis is a “simple” basis in that its flattened elements do correspond to its vectors.
- Parameters:
component_bases (iterable) – A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to
Basis.cast(), e.g. (‘pp’, 4).name (str, optional) – The name of this basis. If None, the names of the component bases joined with “*” is used.
longname (str, optional) – A longer description of this basis. If None, then a long name is automatically generated.
Create a new TensorProdBasis whose elements are the tensor products of the elements of a set of “component” bases.
- Parameters:
component_bases (iterable) – A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to
Basis.cast(), e.g. (‘pp’, 4).name (str, optional) – The name of this basis. If None, the names of the component bases joined with “*” is used.
longname (str, optional) – A longer description of this basis. If None, then a long name is automatically generated.
Methods
__init__(component_bases[, name, longname])Create a new TensorProdBasis whose elements are the tensor products of the elements of a set of "component" bases.
add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
cast(arg[, dim, sparse])cast_from_arrays(arrays[, dim, sparse])cast_from_basis(basis[, dim, sparse])cast_from_name_and_dims(name, dim[, sparse])cast_from_name_and_statespace(name, state_space)copy()Make a copy of this Basis object.
create_equivalent(builtin_basis_name)Create an equivalent basis with components of type builtin_basis_name.
create_simple_equivalent([builtin_basis_name])Create a basis of type builtin_basis_name whose elements are compatible with this basis.
create_transform_matrix(to_basis)Get the matrix that transforms a vector from this basis to to_basis.
dump(f[, format])Serializes and writes this object to a given output stream.
dumps([format])Serializes this object and returns it as a string.
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.
is_compatible_with_state_space(state_space)Checks whether this basis is compatible with a given state space.
Whether this is a complete basis, i.e. this basis's vectors span the entire space that they live in.
is_equivalent(other[, sparseness_must_match])Tests whether this basis is equal to another basis, optionally ignoring sparseness.
is_hermitian()Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.
The negative of
is_complete(), effectively "is_incomplete".Whether the flattened-element vector space is the same space as the space this basis's vectors belong to.
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.
read(path[, format])Read an object of this type, or a subclass of this type, from a file.
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, ...])reverse_transform_matrix(from_basis)Get the matrix that transforms a vector from from_basis to this basis.
Serialize this object in a way that adheres to "niceness" rules of common text file formats.
with_sparsity(desired_sparsity)Returns either this basis or a copy of it with the desired sparsity.
write(path, **format_kwargs)Writes this object to a file.
write_to_mongodb(mongodb[, session, ...])Write this object to a MongoDB database.
Attributes
collection_nameA list of the component bases.
The dimension of the vector space this basis fully or partially spans.
The basis elements (sometimes different from the vectors)
A dictionary mapping labels to the index in self.elements that holds that label's basis element.
A dictionary mapping basis element labels to the elements themselves
The number of element dimensions, i.e. len(self.elshape).
The shape of each element.
The total element size, i.e. product(self.elshape).
True if the first element of this basis is proportional to the identity matrix, False otherwise.
Get transformation matrix from "element space" to this basis.
Retrieve the matrix that transforms vectors from the standard basis to this basis.
True if this basis designates a proper subspace of Hilbert space as "computational."
The basis labels
The number of elements (or vector-elements) in the basis.
Get transformation matrix from this basis to the "element space".
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis's dimension.
The "vectors" of this basis, always 1D (sparse or dense) arrays.
- 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
- create_equivalent(builtin_basis_name)#
Create an equivalent basis with components of type builtin_basis_name.
Create a Basis that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name.
- Parameters:
builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.
- Return type:
- create_simple_equivalent(builtin_basis_name=None)#
Create a basis of type builtin_basis_name whose elements are compatible with this basis.
Create a simple basis and one without components (e.g. a
TensorProdBasis, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_name-analogue of the standard basis that this basis’s elements are expressed in.- Parameters:
builtin_basis_name (str, optional) – The name of the built-in basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and component-free version of the same builtin-basis type.
- Return type:
- create_transform_matrix(to_basis)#
Get the matrix that transforms a vector from this basis to to_basis.
- Parameters:
to_basis (Basis or string) – The basis to transform to or a built-in basis name. In the latter case, a basis to transform to is built with the same structure as this basis but with all components constructed from the given name.
- Return type:
numpy.ndarray (even if basis is sparse)
- 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
- 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
- is_compatible_with_state_space(state_space)#
Checks whether this basis is compatible with a given state space.
- Parameters:
state_space (StateSpace) – the state space to check.
- Return type:
bool
- is_complete()#
Whether this is a complete basis, i.e. this basis’s vectors span the entire space that they live in.
- Return type:
bool
- is_equivalent(other, sparseness_must_match=True)#
Tests whether this basis is equal to another basis, optionally ignoring sparseness.
- Parameters:
other (Basis or str) – The basis to compare with.
sparseness_must_match (bool, optional) – If False then comparison ignores differing sparseness, and this function returns True when the two bases are equal except for their .sparse values.
- Return type:
bool
- is_normalized()#
Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.
Available only to bases whose elements are matrices for now.
- Return type:
bool
- is_partial()#
The negative of
is_complete(), effectively “is_incomplete”.- Return type:
bool
- is_simple()#
Whether the flattened-element vector space is the same space as the space this basis’s vectors belong to.
- 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:
- 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:
- 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:
- 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
- reverse_transform_matrix(from_basis)#
Get the matrix that transforms a vector from from_basis to this basis.
The reverse of
create_transform_matrix().- Parameters:
from_basis (Basis or string) – The basis to transform from or a built-in basis name. In the latter case, a basis to transform from is built with the same structure as this basis but with all components constructed from the given name.
- Return type:
numpy.ndarray (even if basis is sparse)
- 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
- with_sparsity(desired_sparsity)#
Returns either this basis or a copy of it with the desired sparsity.
If this basis has the desired sparsity it is simply returned. If not, this basis is copied to one that does.
- Parameters:
desired_sparsity (bool) – The sparsity (True for sparse elements, False for dense elements) that is desired.
- Return type:
- 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 component_bases#
A list of the component bases.
- property dim#
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
- property elements#
The basis elements (sometimes different from the vectors)
- Return type:
numpy.ndarray
- property elindlookup: dict#
A dictionary mapping labels to the index in self.elements that holds that label’s basis element.
- Return type:
dict
- property ellookup#
A dictionary mapping basis element labels to the elements themselves
- Return type:
dict
- property elndim#
The number of element dimensions, i.e. len(self.elshape)
- Return type:
int
- property elshape#
The shape of each element. Typically either a length-1 or length-2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim, ) (or (dim, 1) in the sparse case).
- property elsize#
The total element size, i.e. product(self.elshape)
- Return type:
int
- property first_element_is_identity#
True if the first element of this basis is proportional to the identity matrix, False otherwise.
- property from_elementstd_transform_matrix#
Get transformation matrix from “element space” to this basis.
Get the matrix that transforms vectors in the “element space” - that is, vectors in the same standard basis that the elements of this basis are expressed in - to vectors in this basis (with length equal to the dim of this basis).
- Returns:
An array of shape (size, element_dim) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
- Return type:
numpy array
- property from_std_transform_matrix#
Retrieve the matrix that transforms vectors from the standard basis to this basis.
- Returns:
An array of shape (size, dim) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
- Return type:
numpy array or scipy sparse matrix
- property implies_leakage_modeling: bool | None#
True if this basis designates a proper subspace of Hilbert space as “computational.”
A basis implies leakage modeling when all three of the following hold:
It has an identity-candidate label: a label matching
^(?:I|C\[I+\])+$, i.e. any concatenation of ‘I’ characters and ‘C[I…I]’ groups (see _EYE_LABEL_REGEX). When several labels qualify, the one containing the most ‘I’ characters is used. This is how the basis names the element that plays the role of “identity on the computational subspace”: ordinary bases like ‘pp’ and ‘gm’ have exactly one such label (‘I’, ‘II’, …), leakage bases use the ‘C[I…I]’ convention, and tensor products concatenate per-factor segments (e.g. ‘IC[I]’ for pp ⊗ l2p1).The element carrying that label is proportional to a real orthogonal projector E. This is what makes “the computational subspace” well defined: we take C = range(E). An element that is not (proportional to) a projector doesn’t single out a subspace, so no leakage interpretation is possible; the probe below fails and we return False.
rank(E) is strictly less than the Hilbert-space dimension, i.e. C is a proper subspace of H. When E is proportional to the full identity (as in ‘pp’ or ‘gm’), there is no leakage level to model, and this property is False even though condition 2 holds.
Example: the built-in ‘l2p1’ basis (a qutrit basis, “leakage-2-plus-1”) has an element labeled ‘C[I]’ proportional to diag(1, 1, 0). That element is a rank-2 projector on a 3-dimensional Hilbert space, so
Basis.cast('l2p1', 9)implies leakage modeling with C spanned by the first two levels. By contrast, ‘gm’ of the same dimension has identity-candidate ‘I’ with element proportional to diag(1, 1, 1) — a full-rank projector — so it does not.Conditions 2 and 3 are checked by calling
matrixtools.induced_projector()as a probe: it returns the projector onto range(E) if the labeled element is proportional to a real orthogonal projector, and we treat a probe failure as “no leakage modeling” rather than an error.See
pygsti.leakage.corefor the functions this property drives (computational_effect, computational_superkets, computational_projector).
- property labels#
The basis labels
- Return type:
list
- property size#
The number of elements (or vector-elements) in the basis.
- property to_elementstd_transform_matrix#
Get transformation matrix from this basis to the “element space”.
Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space” - that is, vectors in the same standard basis that the elements of this basis are expressed in.
- Returns:
An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
- Return type:
numpy array
- property to_std_transform_matrix#
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.
- Returns:
An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
- Return type:
numpy array or scipy.sparse.lil_matrix
- property vector_elements#
The “vectors” of this basis, always 1D (sparse or dense) arrays.
- Returns:
A list of 1D arrays.
- Return type:
list