pygsti.models.oplessmodel.OplessModel#

class OplessModel(state_space)#

Bases: Model

A model that does not have independent component operations.

OplessModel-derived classes often implement coarser models that predict the success or outcome probability of a circuit based on simple properties of the circuit and not detailed gate-level modeling.

Parameters:

state_space (StateSpace) – The state space of this model.

Methods

__init__(state_space)

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

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

bulk_probabilities(circuits[, clip_to, ...])

Construct a dictionary containing the probabilities for an entire list of circuits.

circuit_outcomes(circuit)

Get all the possible outcome labels produced by simulating this circuit.

complete_circuit(circuit)

Adds any implied preparation or measurement layers to circuit

compute_num_outcomes(circuit)

The number of outcomes of circuit, given by it's existing or implied POVM label.

copy()

Copy this model.

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.

from_vector(v[, close])

Sets this Model's operations based on parameter values v.

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.

probabilities(circuit[, outcomes, time])

Construct a dictionary containing the outcome probabilities of circuit.

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

set_parameter_bounds(index[, lower_bound, ...])

Set the bounds for a single model parameter.

set_parameter_label(index, label)

Set the label of a single model parameter.

to_nice_serialization()

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

to_vector()

Returns the model vectorized according to the optional parameters.

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

hyperparams

Dictionary of hyperparameters associated with this model

num_modeltest_params

The parameter count to use when testing this model against data.

num_params

The number of free parameters when vectorizing this model.

parameter_bounds

Upper and lower bounds on the values of each parameter, utilized by optimization routines

parameter_labels

A list of labels, usually of the form (op_label, string_description) describing this model's parameters.

parameter_labels_pretty

The list of parameter labels but formatted in a nice way.

state_space

State space labels

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

bulk_probabilities(circuits, clip_to=None, comm=None, mem_limit=None, smartc=None)#

Construct a dictionary containing the probabilities for an entire list of circuits.

Parameters:
  • circuits ((list of Circuits) or CircuitOutcomeProbabilityArrayLayout) – When a list, each element specifies a circuit to compute outcome probabilities for. A CircuitOutcomeProbabilityArrayLayout specifies the circuits along with an internal memory layout that reduces the time required by this function and can restrict the computed probabilities to those corresponding to only certain outcomes.

  • clip_to (2-tuple, optional) – (min,max) to clip return value if not None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors. Distribution is performed over subtrees of evalTree (if it is split).

  • mem_limit (int, optional) – A rough memory limit in bytes which is used to determine processor allocation.

  • smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.

Returns:

probs – A dictionary such that probs[opstr] is an ordered dictionary of (outcome, p) tuples, where outcome is a tuple of labels and p is the corresponding probability.

Return type:

dictionary

circuit_outcomes(circuit)#

Get all the possible outcome labels produced by simulating this circuit.

Parameters:

circuit (Circuit) – Circuit to get outcomes of.

Return type:

tuple

complete_circuit(circuit)#

Adds any implied preparation or measurement layers to circuit

Parameters:

circuit (Circuit) – Circuit to act on.

Returns:

Possibly the same object as circuit, if no additions are needed.

Return type:

Circuit

compute_num_outcomes(circuit)#

The number of outcomes of circuit, given by it’s existing or implied POVM label.

Parameters:

circuit (Circuit) – The circuit to simplify

Return type:

int

copy()#

Copy this model.

Returns:

a (deep) copy of this model.

Return type:

Model

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

from_vector(v, close=False)#

Sets this Model’s operations based on parameter values v.

Parameters:
  • v (numpy.ndarray) – A vector of parameters, with length equal to self.num_params.

  • close (bool, optional) – Set to True if v is close to the current parameter vector. This can make some operations more efficient.

Return type:

None

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

probabilities(circuit, outcomes=None, time=None)#

Construct a dictionary containing the outcome probabilities of circuit.

Parameters:
  • circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.

  • outcomes (list or tuple) – A sequence of outcomes, which can themselves be either tuples (to include intermediate measurements) or simple strings, e.g. ‘010’.

  • time (float, optional) – The start time at which circuit is evaluated.

Returns:

probs – A dictionary with keys equal to outcome labels and values equal to probabilities.

Return type:

OutcomeLabelDict

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

set_parameter_bounds(index, lower_bound=-inf, upper_bound=inf)#

Set the bounds for a single model parameter.

These limit the values the parameter can have during an optimization of the model.

Parameters:
  • index (int) – The index of the parameter whose bounds should be set.

  • lower_bound (float, optional) – The lower and upper bounds for the parameter. Can be set to the special numpy.inf (or -numpy.inf) values to effectively have no bound.

  • upper_bound (float, optional) – The lower and upper bounds for the parameter. Can be set to the special numpy.inf (or -numpy.inf) values to effectively have no bound.

Return type:

None

set_parameter_label(index, label)#

Set the label of a single model parameter.

Parameters:
  • index (int) – The index of the parameter whose label should be set.

  • label (object) – An object that serves to label this parameter. Often a string.

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

to_vector()#

Returns the model vectorized according to the optional parameters.

Returns:

The vectorized model parameters.

Return type:

numpy array

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

Dictionary of hyperparameters associated with this model

Return type:

dict

property num_modeltest_params: int#

The parameter count to use when testing this model against data.

Often times, this is the same as num_params(), but there are times when it can convenient or necessary to use a parameter count different than the actual number of parameters in this model.

property num_params#

The number of free parameters when vectorizing this model.

Returns:

the number of model parameters.

Return type:

int

property parameter_bounds#

Upper and lower bounds on the values of each parameter, utilized by optimization routines

property parameter_labels#

A list of labels, usually of the form (op_label, string_description) describing this model’s parameters.

property parameter_labels_pretty#

The list of parameter labels but formatted in a nice way.

In particular, tuples where the first element is an op label are made into a single string beginning with the string representation of the operation.

property state_space#

State space labels

Return type:

StateSpaceLabels