pygsti.objectivefns.wildcardbudget.PrimitiveOpsWildcardBudget#
- class PrimitiveOpsWildcardBudget(primitive_op_labels, start_budget=0.0, idle_name=None)#
Bases:
PrimitiveOpsWildcardBudgetBaseA wildcard budget containing one parameter per “primitive operation”.
A parameter’s absolute value gives the amount of “slack”, or “wildcard budget” that is allocated per that particular primitive operation.
Primitive operations are the components of circuit layers, and so the wildcard budget for a circuit is just the sum of the (abs vals of) the parameters corresponding to each primitive operation in the circuit.
- Parameters:
primitive_op_labels (iterable or dict) – A list of primitive-operation labels, e.g. Label(‘Gx’,(0,)), which give all the possible primitive ops (components of circuit layers) that will appear in circuits. Each one of these operations will be assigned it’s own independent element in the wildcard-vector. A dictionary can be given whose keys are Labels and whose values are 0-based parameter indices. In the non-dictionary case, each label gets it’s own parameter. Dictionaries allow multiple labels to be associated with the same wildcard budget parameter, e.g. {Label(‘Gx’,(0,)): 0, Label(‘Gy’,(0,)): 0}. If ‘SPAM’ is included as a primitive op, this value correspond to a uniform “SPAM budget” added to each circuit.
start_budget (float or dict, optional) – An initial value to set all the parameters to (if a float), or a dictionary mapping primitive operation labels to initial values.
Create a new PrimitiveOpsWildcardBudget.
- Parameters:
primitive_op_labels (iterable or dict) – A list of primitive-operation labels, e.g. Label(‘Gx’,(0,)), which give all the possible primitive ops (components of circuit layers) that will appear in circuits. Each one of these operations will be assigned it’s own independent element in the wildcard-vector. A dictionary can be given whose keys are Labels and whose values are 0-based parameter indices. In the non-dictionary case, each label gets it’s own parameter. Dictionaries allow multiple labels to be associated with the same wildcard budget parameter, e.g. {Label(‘Gx’,(0,)): 0, Label(‘Gy’,(0,)): 0}. If ‘SPAM’ is included as a primitive op, this value correspond to a uniform “SPAM budget” added to each circuit.
start_budget (float or dict, optional) – An initial value to set all the parameters to (if a float), or a dictionary mapping primitive operation labels to initial values.
idle_name (str, optional) – The gate name to be used for the 1-qubit idle gate. If not None, then circuit budgets are computed by considering layers of the circuit as being “padded” with 1-qubit idles gates on any empty lines.
Methods
__init__(primitive_op_labels[, ...])Create a new PrimitiveOpsWildcardBudget.
add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
budget_for(op_label)Retrieve the budget amount corresponding to primitive op op_label.
circuit_budget(circuit)Get the amount of wildcard budget, or "outcome-probability-slack" for circuit.
circuit_budgets(circuits[, precomp])Get the wildcard budgets for a list of circuits.
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(w_vec)Set the parameters of this wildcard budget.
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.
precompute_for_same_circuits(circuits)Compute a pre-computed quantity for speeding up circuit calculations.
precompute_for_same_probs_freqs(probs_in, ...)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, ...])slow_update_probs(probs_in, probs_out, ...)Updates probs_in to probs_out by applying this wildcard budget.
Serialize this object in a way that adheres to "niceness" rules of common text file formats.
Get the parameters of this wildcard budget.
update_probs(probs_in, probs_out, freqs, layout)Updates probs_in to probs_out by applying this wildcard budget.
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 dictionary of quantities describing this budget.
The number of parameters of this wildcard budget.
num_primitive_opswildcard_error_per_op- 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
- budget_for(op_label)#
Retrieve the budget amount corresponding to primitive op op_label.
This is just the absolute value of this wildcard budget’s parameter that corresponds to op_label.
- Parameters:
op_label (Label) – The operation label to extract a budget for.
- Return type:
float
- circuit_budget(circuit)#
Get the amount of wildcard budget, or “outcome-probability-slack” for circuit.
- Parameters:
circuit (Circuit) – the circuit to get the budget for.
- Return type:
float
- circuit_budgets(circuits, precomp=None)#
Get the wildcard budgets for a list of circuits.
- Parameters:
circuits (list) – The list of circuits to act on.
precomp (numpy.ndarray, optional) – A precomputed quantity that speeds up the computation of circuit budgets. Given by
precompute_for_same_circuits().
- 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
- 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(w_vec)#
Set the parameters of this wildcard budget.
- Parameters:
w_vec (numpy array) – A vector of parameter values.
- 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:
- 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:
- precompute_for_same_circuits(circuits)#
Compute a pre-computed quantity for speeding up circuit calculations.
This value can be passed to update_probs or circuit_budgets whenever this same circuits list is passed to update_probs to speed things up.
- Parameters:
circuits (list) – A list of
Circuitobjects.- Return type:
object
- 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
- slow_update_probs(probs_in, probs_out, freqs, layout, precomp=None)#
Updates probs_in to probs_out by applying this wildcard budget.
Update a set of circuit outcome probabilities, probs_in, into a corresponding set, probs_out, which uses the slack allotted to each outcome probability to match (as best as possible) the data frequencies in freqs. In particular, it computes this best-match in a way that maximizes the likelihood between probs_out and freqs. This method is the core function of a
WildcardBudget.- Parameters:
probs_in (numpy array) – The input probabilities, usually computed by a
Model.probs_out (numpy array) – The output probabilities: probs_in, adjusted according to the slack allowed by this wildcard budget, in order to maximize logl(probs_out, freqs). Note that probs_out may be the same array as probs_in for in-place updating.
freqs (numpy array) – An array of frequencies corresponding to each of the outcome probabilities in probs_in or probs_out.
layout (CircuitOutcomeProbabilityArrayLayout) – The layout for probs_in, probs_out, and freqs, specifying how array indices correspond to circuit outcomes, as well as the list of circuits.
precomp (numpy.ndarray, optional) – A precomputed quantity for speeding up this calculation.
- 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()#
Get the parameters of this wildcard budget.
- Return type:
numpy array
- update_probs(probs_in, probs_out, freqs, layout, precomp=None, probs_freqs_precomp=None, return_deriv=False)#
Updates probs_in to probs_out by applying this wildcard budget.
Update a set of circuit outcome probabilities, probs_in, into a corresponding set, probs_out, which uses the slack allotted to each outcome probability to match (as best as possible) the data frequencies in freqs. In particular, it computes this best-match in a way that maximizes the likelihood between probs_out and freqs. This method is the core function of a
WildcardBudget.- Parameters:
probs_in (numpy array) – The input probabilities, usually computed by a
Model.probs_out (numpy array) – The output probabilities: probs_in, adjusted according to the slack allowed by this wildcard budget, in order to maximize logl(probs_out, freqs). Note that probs_out may be the same array as probs_in for in-place updating.
freqs (numpy array) – An array of frequencies corresponding to each of the outcome probabilities in probs_in or probs_out.
layout (CircuitOutcomeProbabilityArrayLayout) – The layout for probs_in, probs_out, and freqs, specifying how array indices correspond to circuit outcomes, as well as the list of circuits.
precomp (numpy.ndarray, optional) – A precomputed quantity for speeding up this calculation.
probs_freqs_precomp (list, optional) – A precomputed list of quantities re-used when calling update_probs using the same probs_in, freqs, and layout. Generate by calling
precompute_for_same_probs_freqs().return_deriv (bool, optional) – When True, returns the derivative of each updated probability with respect to its circuit budget as a numpy array. Useful for internal methods.
- Return type:
None
- 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 description#
A dictionary of quantities describing this budget.
Return the contents of this budget in a dictionary containing (description, value) pairs for each element name.
- Returns:
Keys are primitive op labels and values are (description_string, value) tuples.
- Return type:
dict
- property num_params#
The number of parameters of this wildcard budget.
- Return type:
int