pygsti.protocols.estimate.Estimate#
- class Estimate(parent, models=None, parameters=None, extra_parameters=None)#
Bases:
MongoSerializableA class encapsulating the Model objects related to a single GST estimate up-to-gauge freedoms.
Thus, this class holds the “iteration” Model`s leading up to a final `Model, and then different gauge optimizations of the final set.
- Parameters:
parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.
models (dict, optional) – A dictionary of models to included in this estimate
parameters (dict, optional) – A dictionary of parameters associated with how these models were obtained.
Initialize an empty Estimate object.
- Parameters:
parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.
models (dict, optional) – A dictionary of models to included in this estimate
parameters (dict, optional) – A dictionary of parameters associated with how these models were obtained.
Methods
__init__(parent[, models, parameters, ...])Initialize an empty Estimate object.
add_confidence_region_factory([model_label, ...])Creates a new confidence region factory.
add_gaugeoptimized(goparams[, model, label, ...])Adds a gauge-optimized Model (computing it if needed) to this object.
add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
copy()Creates a copy of this Estimate object.
Retrieves a confidence region factory for the given model and circuit list labels.
create_effective_dataset([return_submxs])Generate a DataSet containing the effective counts as dictated by the "weights" parameter.
create_gst_estimate(parent[, target_model, ...])Initialize an empty Estimate object.
final_mdc_store([resource_alloc, array_types])The final (not intermediate) model-dataset-circuit storage object (MDC store) for this estimate.
final_objective_fn([resource_alloc])The final (not intermediate) objective function object for this estimate.
final_objective_fn_cache([resource_alloc])The final (not intermediate) serializable ("cached") objective function object for this estimate.
from_dir(dirname[, quick_load])Initialize a new Protocol object from dirname.
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.
Propagates a confidence region among gauge-equivalent models.
has_confidence_region_factory([model_label, ...])Checks whether a confidence region factory for the given model and circuit list labels exists.
misfit_sigma([resource_alloc])Returns the number of standard deviations (sigma) of model violation.
remove_from_mongodb(mongodb_collection, doc_id)Remove an Estimate from a MongoDB database.
remove_me_from_mongodb(mongodb[, session, ...])retrieve_start_model(goparams)Returns the starting model for the gauge optimization given by goparams.
set_parent(parent)Sets the parent object of this estimate.
view(gaugeopt_keys[, parent])Creates a shallow copy of this Results object containing only the given gauge-optimization keys.
write(dirname)Write this protocol to a directory.
write_to_mongodb(mongodb[, session, ...])Write this object to a MongoDB database.
Attributes
collection_namegoparametersparameters- add_confidence_region_factory(model_label='final iteration estimate', circuits_label='final')#
Creates a new confidence region factory.
An instance of
ConfidenceRegionFactoryserves to create confidence intervals and regions in reports and elsewhere. This function creates such a factory, which is specific to a given Model (given by this object’s .models[model_label] ) and circuit list (given by the parent Results’s .circuit_lists[gastrings_label] list).- Parameters:
model_label (str, optional) – The label of a Model held within this Estimate.
circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.
- Returns:
The newly created factory (also cached internally) and accessible via the
create_confidence_region_factory()method.- Return type:
- add_gaugeoptimized(goparams, model=None, label=None, comm=None, verbosity=None)#
Adds a gauge-optimized Model (computing it if needed) to this object.
- Parameters:
goparams (dict or list) – A dictionary of gauge-optimization parameters, typically arguments to
gaugeopt_to_target(), specifying how the gauge optimization was (or should be) performed. When model is None (and this function computes the model internally) the keys and values of this dictionary must correspond to allowed arguments ofgaugeopt_to_target(). By default,gaugeopt_to_target()’s first two arguments, the Model to optimize and the target, are taken to be self.models[‘final iteration estimate’] and self.models[‘target’]. This argument can also be a list of such parameter dictionaries, which specifies a multi-stage gauge- optimization whereby the output of one stage is the input of the next.model (Model, optional) – The gauge-optimized model to store. If None, then this model is computed by calling
gaugeopt_to_target()with the contents of goparams as arguments as described above.label (str, optional) – A label for this gauge-optimized model, used as the key in this object’s models and goparameters member dictionaries. If None, then the next available “go<X>”, where <X> is a non-negative integer, is used as the label.
comm (mpi4py.MPI.Comm, optional) – A default MPI communicator to use when one is not specified as the ‘comm’ element of/within goparams.
verbosity (int, optional) – An integer specifying the level of detail printed to stdout during the calculations performed in this function. If not None, this value will override any verbosity values set within goparams.
- Return type:
None
- 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_confidence_region_factory(model_label='final iteration estimate', circuits_label='final', create_if_needed=False)#
Retrieves a confidence region factory for the given model and circuit list labels.
For more information about confidence region factories, see
add_confidence_region_factory().- Parameters:
model_label (str, optional) – The label of a Model held within this Estimate.
circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.
create_if_needed (bool, optional) – If True, a new confidence region factory will be created if none exists. Otherwise a KeyError is raised when the requested factory doesn’t exist.
- Return type:
- create_effective_dataset(return_submxs=False)#
Generate a DataSet containing the effective counts as dictated by the “weights” parameter.
An estimate’s self.parameters[‘weights’] value specifies a dictionary of circuits weights, which modify (typically reduce) the counts given in its (parent’s) data set.
This function rescales the actual data contained in this Estimate’s parent
ModelEstimteResultsobject according to the estimate’s “weights” parameter. The scaled data set is returned, along with (optional) a list-of-lists of matrices containing the scaling values which can be easily plotted via a ColorBoxPlot.- Parameters:
return_submxs (boolean) – If true, also return a list-of-lists of matrices containing the scaling values, as described above.
- Returns:
ds (DataSet) – The “effective” (scaled) data set.
subMxs (list-of-lists) – Only returned if return_submxs == True. Contains the scale values (see above).
- classmethod create_gst_estimate(parent, target_model=None, seed_model=None, models_by_iter=None, parameters=None)#
Initialize an empty Estimate object.
- Parameters:
parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.
target_model (Model) – The target model used when optimizing the objective.
seed_model (Model) – The initial model used to seed the iterative part of the objective optimization. Typically this is obtained via LGST.
models_by_iter (list of Models) – The estimated model at each GST iteration. Typically these are the estimated models before any gauge optimization is performed.
parameters (dict) – A dictionary of parameters associated with how these models were obtained.
- Return type:
- final_mdc_store(resource_alloc=None, array_types=('e', 'ep'))#
The final (not intermediate) model-dataset-circuit storage object (MDC store) for this estimate.
This object is created and cached as needed, and combined the final model, data set, and circuit list for this estimate.
- Parameters:
resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store. This can just be left as None unless multiple processors are being utilized. Note that this argument is only used when a MDC store needs to be created – if this estimate has already created one then this argument is ignored.
array_types (tuple) – A tuple of array types passed to the MDC store constructor (if a new MDC store needs to be created). These affect how memory is allocated within the MDC store object and can enable (or disable) the use of certain MDC store functionality later on (e.g. the use of Jacobian or Hessian quantities).
- Return type:
- final_objective_fn(resource_alloc=None)#
The final (not intermediate) objective function object for this estimate.
This object is created and cached as needed, and is the evaluated (and sometimes optimized) objective function associated with this estimate. Often this is a log-likelihood or chi-squared function, or a close variant.
- Parameters:
resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store underlying the objective function. This can just be left as None unless multiple processors are being utilized. Note that this argument is only used when an underlying MDC store needs to be created – if this estimate has already created a MDC store then this argument is ignored.
- Return type:
- final_objective_fn_cache(resource_alloc=None)#
The final (not intermediate) serializable (“cached”) objective function object for this estimate.
This is an explicitly serializable version of the final objective function, useful because is often doesn’t need be constructed. To become serializable, however, the objective function is stripped of any MPI comm or multi-processor information (since this may be different between loading and saving). This makes the cached objective function convenient for fast calls/usages of the objective function.
- Parameters:
resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store underlying the objective function. This can just be left as None unless multiple processors are being utilized - and in this case the cached objective function doesn’t even benefit from these processors (but calls to
final_objective_fn()will return an objective function setup for multiple processors). Note that this argument is only used when there is no existing cached objective function and an underlying MDC store needs to be created.- Return type:
- classmethod from_dir(dirname, quick_load=False)#
Initialize a new Protocol object from dirname.
- quick_loadbool, optional
Setting this to True skips the loading of components that may take a long time to load.
- Parameters:
dirname (str) – The directory name.
quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load.
- Return type:
- 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
- gauge_propagate_confidence_region_factory(to_model_label, from_model_label='final iteration estimate', circuits_label='final', eps=0.001, verbosity=0)#
Propagates a confidence region among gauge-equivalent models.
More specifically, this function propagates an existing “reference” confidence region for a Model “G0” to a new confidence region for a gauge-equivalent model “G1”.
When successful, a new confidence region factory is created for the .models[to_model_label] Model and circuits_label gate string list from the existing factory for .models[from_model_label].
- Parameters:
to_model_label (str) – The key into this Estimate object’s models and goparameters dictionaries that identifies the final gauge-optimized result to create a factory for. This gauge optimization must have begun at “from” reference model, i.e., models[from_model_label] must equal (by frobeinus distance) goparameters[to_model_label][‘model’].
from_model_label (str, optional) – The key into this Estimate object’s models dictionary that identifies the reference model.
circuits_label (str, optional) – The key of the circuit list (within the parent Results’s .circuit_lists dictionary) that identifies the circuit list used by the old (&new) confidence region factories.
eps (float, optional) – A small offset used for constructing finite-difference derivatives. Usually the default value is fine.
verbosity (int, optional) – A non-negative integer indicating the amount of detail to print to stdout.
- Returns:
Note: this region is also stored internally and as such the return value of this function can often be ignored.
- Return type:
- has_confidence_region_factory(model_label='final iteration estimate', circuits_label='final')#
Checks whether a confidence region factory for the given model and circuit list labels exists.
- Parameters:
model_label (str, optional) – The label of a Model held within this Estimate.
circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.
- Return type:
bool
- misfit_sigma(resource_alloc=None)#
Returns the number of standard deviations (sigma) of model violation.
- Parameters:
resource_alloc (ResourceAllocation, optional) – What resources are available for this computation.
- Return type:
float
- classmethod remove_from_mongodb(mongodb_collection, doc_id, session=None)#
Remove an Estimate from a MongoDB database.
- Returns:
True if the specified experiment design was removed, False if it didn’t exist.
- Return type:
bool
- retrieve_start_model(goparams)#
Returns the starting model for the gauge optimization given by goparams.
This has a particular (and perhaps singular) use for deciding whether the gauge-optimized model for one estimate can be simply copied to another estimate, without actually re-gauge-optimizing.
- Parameters:
goparams (dict or list) – A dictionary of gauge-optimization parameters, just as in
add_gaugeoptimized().- Return type:
- set_parent(parent)#
Sets the parent object of this estimate.
This is used, for instance, to re-establish parent-child links after loading objects from disk.
- Parameters:
parent (ModelEstimateResults) – This object’s parent.
- Return type:
None
- view(gaugeopt_keys, parent=None)#
Creates a shallow copy of this Results object containing only the given gauge-optimization keys.
- Parameters:
gaugeopt_keys (str or list, optional) – Either a single string-value gauge-optimization key or a list of such keys. If None, then all gauge-optimization keys are retained.
parent (Results, optional) – The parent Results object of the view. If None, then the current Estimate’s parent is used.
- Return type:
- write(dirname)#
Write this protocol to a directory.
- Parameters:
dirname (str) – The directory name to write. This directory will be created if needed, and the files in an existing directory will be overwritten.
- 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