pygsti.baseobjs.basis.Basis#

class Basis(name, longname, real, sparse)#

Bases: NicelySerializable

An ordered set of labeled matrices/vectors.

The base class for basis objects. A basis in pyGSTi is an abstract notion of a set of labeled elements, or “vectors”. Each basis has a certain size, and has .elements, .labels, and .ellookup members, the latter being a dictionary mapping of labels to elements.

An important point to note that isn’t immediately intuitive is that while Basis object holds elements (in its .elements property) these are not the same as its vectors (given by the object’s vector_elements property). Often times, in what we term a “simple” basis, the you just flatten an element to get the corresponding vector-element. This works for bases where the elements are either vectors (where flattening does nothing) and matrices. By storing elements as distinct from vector_elements, the Basis can capture additional structure of the elements (such as viewing them as matrices) that can be helpful for their display and interpretation. The elements are also sometimes referred to as the “natural elements” because they represent how to display the element in a natural way. A non-simple basis occurs when vector_elements need to be stored as elements in a larger “embedded” way so that these elements can be displayed and interpreted naturally.

A second important note is that there is assumed to be some underlying “standard” basis underneath all the bases in pyGSTi. The elements in a Basis are always written in this standard basis. In the case of the “std”-named basis in pyGSTi, these elements are just the trivial vector or matrix units, so one can rightly view the “std” pyGSTi basis as the “standard” basis for a that particular dimension.

The arguments below describe the basic properties of all basis objects in pyGSTi. It is important to remember that the vector_elements of a basis are different from its elements (see the Basis docstring), and that dim refers to the vector elements whereas elshape refers to the elements.

For example, consider a 2-element Basis containing the I and X Pauli matrices. The size of this basis is 2, as there are two elements (and two vector elements). Since vector elements are the length-4 flattened Pauli matrices, the dimension (dim) is 4. Since the elements are 2x2 Pauli matrices, the elshape is (2, 2).

As another example consider a basis which spans all the diagonal 2x2 matrices. The elements of this basis are the two matrix units with a 1 in the (0, 0) or (1, 1) location. The vector elements, however, are the length-2 [1, 0] and [0, 1] vectors obtained by extracting just the diagonal entries from each basis element. Thus, for this basis, size=2, dim=2, and elshape=(2, 2) - so the dimension is not just the product of elshape entries (equivalently, elsize).

Parameters:
  • name (string) – The name of the basis. This can be anything, but is usually short and abbreviated. There are several types of bases built into pyGSTi that can be constructed by this name.

  • longname (string) – A more descriptive name for the basis.

  • real (bool) – Elements and vector elements are always allowed to have complex entries. This argument indicates whether the coefficients in the expression of an arbitrary vector in this basis must be real. For example, if real=True, then when pyGSTi transforms a vector in some other basis to a vector in this basis, it will demand that the values of that vector (i.e. the coefficients which multiply this basis’s elements to obtain a vector in the “standard” basis) are real.

  • sparse (bool) – Whether the elements of .elements for this Basis are stored (when they are stored at all) as sparse matrices or vectors.

dim#

The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.

Type:

int

size#

The number of elements (or vector-elements) in the basis.

Type:

int

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

Type:

int

elndim#

The number of element dimensions, i.e. len(self.elshape)

Type:

int

elsize#

The total element size, i.e. product(self.elshape)

Type:

int

vector_elements#

The “vectors” of this basis, always 1D (sparse or dense) arrays.

Type:

list

Methods

__init__(name, longname, real, sparse)

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.

is_complete()

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

is_normalized()

Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.

is_partial()

The negative of is_complete(), effectively "is_incomplete".

is_simple()

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.

to_nice_serialization()

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_name

dim

The dimension of the vector space this basis fully or partially spans.

elndim

The number of element dimensions, i.e. len(self.elshape).

elshape

The shape of each element.

elsize

The total element size, i.e. product(self.elshape).

first_element_is_identity

True if the first element of this basis is proportional to the identity matrix, False otherwise.

from_elementstd_transform_matrix

Get transformation matrix from "element space" to this basis.

from_std_transform_matrix

Retrieve the matrix that transforms vectors from the standard basis to this basis.

implies_leakage_modeling

True if this basis designates a proper subspace of Hilbert space as "computational."

size

The number of elements (or vector-elements) in the basis.

to_elementstd_transform_matrix

Get transformation matrix from this basis to the "element space".

to_std_transform_matrix

Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis's dimension.

vector_elements

The "vectors" of this basis, always 1D (sparse or dense) arrays.

labels

elements

ellookup

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

copy()#

Make a copy of this Basis object.

Return type:

Basis

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:

Basis

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:

Basis

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:

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

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

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:

Basis

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#

The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.

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:

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

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

  3. 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.core for the functions this property drives (computational_effect, computational_superkets, computational_projector).

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