pygsti.models.fogistore.FirstOrderGaugeInvariantStore#

class FirstOrderGaugeInvariantStore(primitive_op_labels, gauge_space, elem_errorgen_labels_by_op, op_errorgen_indices, fogi_directions, fogi_metadata, dependent_dir_indices, fogv_directions, allop_gauge_action, gauge_space_directions, norm_order='auto', dependent_fogi_action='drop')#

Bases: NicelySerializable

An object that computes and stores the first-order-gauge-invariant quantities of a model.

Currently, it is only compatible with ExplicitOpModel objects.

Parameters:
  • primitive_op_labels (tuple of Label) – Labels describing the gate set operations

  • gauge_space (ErrorgenSpace) – Special way of intersecting the gauge spaces of all ops, see the beginning of from_gauge_action_matrices() for a more detailed description.

  • elem_errorgen_labels_by_op (dict of Label keys with GlobalElementaryErrorgenLabel or GlobalElementaryErrorgenLabel values) – Elementary error generator labels for every operation in the gate set

  • op_errorgen_indices (dict of Label keys with Slices values) – Specifies which indices from the error generator space labels correspond to which operation. For example, these allows us to index accordingly into the rows of allop_gauge_action which contain all error generators from every operation stacked on top of each other.

  • fogi_directions (numpy array) – Array where each column is a FOGI direction, the rows represent the modelmember parameters from which they were derived (typically elementary error generators)

  • fogi_metadata (list of dictionaries) –

    Entry number k of this list contains metadata information about fogi quantity k (column k of fogi_directions). It is organized as a dictionary with the following entries:

    • ’name’ (str) : Label describing the FOGI quantity

    • ’abbrev’ (str) : An abbreviated version of the label above TODO: more details

    • ’r’ (float)constant that allows us to convert between the gauge-space-normalized

      FOGI direction to the errgen-space-normalized version of it. fogi_dir = r * dot(M, epsilon) = r * dot(inv_diff_gauge_action, int_vec)

    • ’gaugespace_dir’ (numpy array)A corresponding gauge direction TODO: more details on their relationship

      to FOGI quantities

    • ’opset’ (list of Label)The set of model member operations that are affected by the corresponding FOGI

      quantity

    • ’raw’ (str) : Another version of ‘name’ without abbreviations

  • dependent_dir_indices (list of int) – Specifies the indices of a set of FOGI quantities which, if removed, the remaining FOGI quantities are linearly independent.

  • fogv_directions (numpy array) – A list of gauge directions that span the gauge space of the target gate set

  • allop_gauge_action (lil_matrix) – Stands for “All operations gauge action”. It is a restricted version of each operation’s gauge_action stacked together. Ignores elemgens that are not included in the common gauge space. The common gauge space is the intersection of all the individual gauge spaces. TODO: I believe this is done to remove the “trivial”/”meta” gauge from SPAM operations. We should verify this and if so, include it in this docstring

  • gauge_space_directions (numpy array) – Contains, when applicable, a gauge-space direction that correspondings to the FOGI quantity in fogi_directions. Such a gauge-space direction exists for relational FOGI quantities, where the FOGI quantity is constructed by taking the difference of a gauge-space action (given by the gauge-space direction) on two operations (or sets of operations). TODO: How does one know the corresponding fogi direction? each one of these is computed from fogv_directions.

  • norm_order (str or int) – Defines the order of the norm to normalize FOGI directions. It should be 1 for normalizing ‘S’ quantities and 2 for ‘H’, so ‘auto’ utilizes intelligence.

  • dependent_fogi_action ('drop' or 'mark') – If ‘drop’, all linearly dependent FOGI directions are not returned, resulting in a linearly independent set of quantities. If ‘mark’ linearly dependent FOGI directions are kept and marked by dependent_dir_indices.

Methods

__init__(primitive_op_labels, gauge_space, ...)

add_mongodb_write_ops(write_ops, mongodb[, ...])

Accumulate write and update operations for writing this object to a MongoDB database.

create_binned_fogi_infos([tol])

Creates an 'info' dictionary for each FOGI quantity and places it within a nested dictionary structure by the operators involved, the types of error generators, and the qubits acted upon (a.k.a.

create_elementary_errorgen_space(...)

Construct a matrix whose column space spans the given list of elementary error generators.

create_fogi_aggregate_single_op_space(op_label)

Construct a matrix with columns spanning a particular FOGI subspace for a single operation.

create_fogi_aggregate_space([op_set, ...])

Construct a matrix with columns equal to the FOGI directions within the specified categories.

dump(f[, format])

Serializes and writes this object to a given output stream.

dumps([format])

Serializes this object and returns it as a string.

errorgen_vec_to_fogi_components_array(...)

errorgen_vec_to_fogv_components_array(...)

errorgen_vec_to_opcoeffs(errorgen_vec)

find_nice_fogiv_directions()

fogi_components_array_to_errorgen_vec(...)

fogi_components_array_to_opcoeffs(...)

fogi_errorgen_direction_labels([typ])

typ can be 'raw' or 'abbrev' too

fogiv_components_array_to_errorgen_vec(...)

fogiv_components_array_to_opcoeffs(...)

fogv_components_array_to_errorgen_vec(...)

fogv_components_array_to_opcoeffs(...)

fogv_errorgen_direction_labels([typ])

from_gauge_action_matrices(...[, ...])

Receives the matrices describing the individual gauge action of each operation within the gate set, and massages them into appropriate from to be fed into construct_fogi_quantities() which finds FOGI quantities for the corresponding gate set.

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.

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.

merge_binned_fogi_infos(binned_fogi_infos, ...)

Merge together multiple FOGI-info dictionaries created by create_binned_fogi_infos().

opcoeffs_to_fogi_components_array(op_coeffs)

opcoeffs_to_fogiv_components_array(op_coeffs)

opcoeffs_to_fogv_components_array(op_coeffs)

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

to_nice_serialization()

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

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

errorgen_space_dim

gauge_space_dim

num_fogi_directions

num_fogv_directions

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

create_binned_fogi_infos(tol=1e-05)#

Creates an ‘info’ dictionary for each FOGI quantity and places it within a nested dictionary structure by the operators involved, the types of error generators, and the qubits acted upon (a.k.a. the “target” qubits). TODO: docstring

Return type:

dict

create_elementary_errorgen_space(op_elem_errgen_labels)#

Construct a matrix whose column space spans the given list of elementary error generators.

Parameters:

op_elem_errgen_labels (iterable) – A list of (operation_label, elementary_error_generator_label) tuples, where operation_label is one of the primitive operation labels in self.primitive_op_labels and elementary_error_generator_label is a GlobalElementaryErrorgenLabel object.

Returns:

A two-dimensional array of shape (self.errorgen_space_dim, len(op_elem_errgen_labels)). Columns correspond to elements of op_elem_errgen_labels and the rowspace is the full elementary error generator space of this FOGI analysis.

Return type:

numpy.ndarray

create_fogi_aggregate_single_op_space(op_label, errorgen_type='H', intrinsic_or_relational='intrinsic', target='all')#

Construct a matrix with columns spanning a particular FOGI subspace for a single operation.

This is a subspace of the full error-generator space of this FOGI analysis, and projecting a model’s error-generator vector onto this space can be used to obtain the contribution of a desired subset of the op_label’s errors.

Parameters:
  • op_label (Label or str) – The operation to construct a subspace for. This should be an element of self.primitive_op_labels.

  • errorgen_type ({"H", "S", "all"}) – Potentially restrict to the subspace containing just Hamiltonian (H) or Pauli stochastic (S) errors. “all” imposes no restriction.

  • intrinsic_or_relational ({"intrinsic", "relational", "all"}) – Restrict to intrinsic or relational errors (or not, using “all”).

  • target (tuple or "all") – A tuple of state space (qubit) labels to restrict to, e.g., (‘Q0’,’Q1’). Note that including multiple labels selects only those quantities that target all the labels. The special “all” value includes quantities on all targets (no restriction).

Returns:

A two-dimensional array with self.errorgen_space_dim rows and a number of columns dependent on the dimension of the selected subspace.

Return type:

numpy.ndarray

create_fogi_aggregate_space(op_set='all', errorgen_types='all', target='all')#

Construct a matrix with columns equal to the FOGI directions within the specified categories.

Projecting a model’s error-generator vector onto such a space can be used to obtain the contribution of a desired subset of the model’s errors.

Parameters:
  • op_set (tuple or "all") – Restrict to (intrinsic) FOGI quantities of a single operation, given as a 1-tuple, e.g. ((‘Gxpi2’,0),) or relational error between multiple operations, e.g., ((‘Gxpi2’,0), (‘Gypi2’,0)). The special “all” value includes quantities on all operations (no restriction).

  • errorgen_types (tuple of {"H", "S"} or "all") – Restrict to FOGI quantities containing elementary error generators of the given type(s). Note that a tuple with multiple types only selects FOGI quantities containing all the give types (e.g., (‘H’,’S’) will not match quantities composed of solely Hamiltonian-type generators). The special “all” value includes quantities of all types (no restriction).

  • target (tuple or "all") – A tuple of state space (qubit) labels to restrict to, e.g., (‘Q0’,’Q1’). Note that including multiple labels selects only those quantities that target all the labels. The special “all” value includes quantities on all targets (no restriction).

Returns:

A two-dimensional array with self.errorgen_space_dim rows and a number of columns dependent on the number of FOGI quantities matching the argument criteria.

Return type:

numpy.ndarray

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

fogi_errorgen_direction_labels(typ='normal')#

typ can be ‘raw’ or ‘abbrev’ too

classmethod from_gauge_action_matrices(gauge_action_matrices_by_op, gauge_action_gauge_spaces_by_op, errorgen_coefficient_labels_by_op, op_label_abbrevs=None, dependent_fogi_action='drop', norm_order='auto')#

Receives the matrices describing the individual gauge action of each operation within the gate set, and massages them into appropriate from to be fed into construct_fogi_quantities() which finds FOGI quantities for the corresponding gate set. Additionally, gauge space vectors are computed, and gauge directions that “correspond” to FOGI quantities are identified. With all of this, a FOGIStore object is created and returned.

Parameters:
  • gauge_action_matrices_by_op (dict of Label keys and numpy array values) – Gauge action of the primitive operator described by Label. For SPAM, “gauge action” matrix is just the identity on the relevant space of gauge transformations. For gates, it is K - UKU^dag where K is a gauge generator, and U is the ideal gate.

  • gauge_action_gauge_spaces_by_op (dict of Label keys and numpy array values) – “Formatted” gauge spaces corresponding to each gauge action from gauge_action_matrices_by_op. This formatting occurs in model.py:_format_gauge_action_matrix() TODO: More details

  • errorgen_coefficient_labels_by_op (dict of Label keys and list of Label values) – If indexed by an operation Label, this variable returns a list of error generator labels that identify every row of their corresponding gauge action matrix in gauge_action_matrices_by_op

  • op_label_abbrevs (dict of Label keys with str values) – The user is able to fill the values of this dictionary with any strings to represent the operations in the gate set. typically used to choose shorter names to avoid FOGI names that are too long/complicated to read.

norm_order : int or ‘auto’ (Defaults to ‘auto’)

Defines the order of the norm to normalize FOGI directions. It should be 1 for normalizing ‘S’ quantities and 2 for ‘H’, so ‘auto’ utilizes intelligence.

dependent_fogi_action : ‘drop’ or ‘mark’ (Defaults to ‘drop’)

If ‘drop’, all linearly dependent FOGI directions are not returned, resulting in a linearly independent set of quantities. If ‘mark’ linearly dependent FOGI directions are kept and marked by dependent_dir_indices.

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

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 merge_binned_fogi_infos(binned_fogi_infos, index_offsets)#

Merge together multiple FOGI-info dictionaries created by create_binned_fogi_infos().

Parameters:
  • binned_fogi_infos (list) – A list of FOGI-info dictionaries.

  • index_offsets (list) – A list of length len(binned_fogi_infos) that gives the offset into an assumed-to-exist corresponding vector of components for all the FOGI infos.

Returns:

The merged dictionary

Return type:

dict

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

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

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