pygsti.models.localnoisemodel.LocalNoiseModel#
- class LocalNoiseModel(processor_spec, gatedict, prep_layers=None, povm_layers=None, evotype='default', simulator='auto', on_construction_error='raise', independent_gates=False, ensure_composed_gates=False, implicit_idle_mode='none')#
Bases:
ImplicitOpModelA n-qudit implicit model that allows for only local noise.
This model holds as building blocks individual noisy gates which are trivially embedded into circuit layers as requested.
- Parameters:
processor_spec (ProcessorSpec) – The processor specification to create a model for. This object specifies the gate names and unitaries for the processor, and their availability on the processor.
gatedict (dict) – A dictionary (an OrderedDict if you care about insertion order) that associates with gate names (e.g. “Gx”)
LinearOperator, numpy.ndarray objects. When the objects may act on fewer than the total number of qudits (determined by their dimension/shape) then they are repeatedly embedded into operation on the entire state space as specified by their availability within processor_spec. While the keys of this dictionary are usually string-type gate names, labels that include target qudits, e.g. (“Gx”,0), may be used to override the default behavior of embedding a reference or a copy of the gate associated with the same label minus the target qudits (e.g. “Gx”). Furthermore,OpFactoryobjects may be used in place of LinearOperator objects to allow the evaluation of labels with arguments.prep_layers (None or operator or dict or list) – The state preparateion operations as n-qudit layer operations. If None, then no state preparations will be present in the created model. If a dict, then the keys are labels and the values are layer operators. If a list, then the elements are layer operators and the labels will be assigned as “rhoX” where X is an integer starting at 0. If a single layer operation of type
Stateis given, then this is used as the sole prep and is assigned the label “rho0”.povm_layers (None or operator or dict or list) – The state preparateion operations as n-qudit layer operations. If None, then no POVMS will be present in the created model. If a dict, then the keys are labels and the values are layer operators. If a list, then the elements are layer operators and the labels will be assigned as “MX” where X is an integer starting at 0. If a single layer operation of type
POVMis given, then this is used as the sole POVM and is assigned the label “Mdefault”.evotype (Evotype or str, optional) – The evolution type of this model, describing how states are represented. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) –
The circuit simulator used to compute any requested probabilities, e.g. from
probs()orbulk_probs(). The default value of “auto” automatically selects the simulation type, and is usually what you want. Other special allowed values are:”matrix” : op_matrix-op_matrix products are computed and cached to get composite gates which can then quickly simulate a circuit for any preparation and outcome. High memory demand; best for a small number of (1 or 2) qubits.
”map” : op_matrix-state_vector products are repeatedly computed to simulate circuits. Slower for a small number of qubits, but faster and more memory efficient for higher numbers of qubits (3+).
on_construction_error ({'raise','warn',ignore'}) – What to do when the conversion from a value in gatedict to a
LinearOperatorof the type given by parameterization fails. Usually you’ll want to “raise” the error. In some cases, for example when converting as many gates as you can into parameterization=”clifford” gates, “warn” or even “ignore” may be useful.independent_gates (bool, optional) – Whether gates are allowed independent local noise or not. If False, then all gates with the same name (e.g. “Gx”) will have the same (local) noise (e.g. an overrotation by 1 degree), and the operation_bks[‘gates’] dictionary contains a single key per gate name. If True, then gates with the same name acting on different qudits may have different local noise, and so the operation_bks[‘gates’] dictionary contains a key for each gate available gate placement.
ensure_composed_gates (bool, optional) – If True then the elements of the operation_bks[‘gates’] will always be
ComposedOpobjects. The purpose of this is to facilitate modifying the gate operations after the model is created. If False, then the appropriately parameterized gate objects (often dense gates) are used directly.implicit_idle_mode ({'none', 'add_global', 'pad_1Q', 'only_global'}) – The way idle operations are added implicitly within the created model. “none” doesn’t add any “extra” idle operations when there is a layer that contains some gates but not gates on all the qubits. “add_global” adds the global idle operation, i.e., the operation for a global idle layer (zero gates - a completely empty layer), to every layer that is simulated, using the global idle as a background idle that always occurs regardless of the operation. “pad_1Q” applies the 1-qubit idle gate (if one exists) to all idling qubits within a circuit layer. “only_global” uses a global idle operation, if one exists, to simulate the completely empty layer but nothing else, i.e., this idle operation is not added to other layers as in “add_global”.
Creates a new OpModel. Rarely used except from derived classes __init__ functions. :param state_space: The state space for this model. :type state_space: StateSpace :param basis: The basis used for the state space by dense operator representations. :type basis: Basis :param evotype: The evolution type of this model, describing how states are
represented. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
- Parameters:
layer_rules (LayerRules) – The “layer rules” used for constructing operators for circuit layers. This functionality is essential to using this model to simulate circuits, and is typically supplied by derived classes.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) – The forward simulator (or typ) that this model should use. “auto” tries to determine the best type automatically.
Methods
__init__(processor_spec, gatedict[, ...])Creates a new OpModel. Rarely used except from derived classes __init__ functions. :param state_space: The state space for this model. :type state_space: StateSpace :param basis: The basis used for the state space by dense operator representations. :type basis: Basis :param evotype: The evolution type of this model, describing how states are represented. The special value "default" is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype. :type evotype: Evotype or str, optional :param layer_rules: The "layer rules" used for constructing operators for circuit layers. This functionality is essential to using this model to simulate circuits, and is typically supplied by derived classes. :type layer_rules: LayerRules :param simulator: The forward simulator (or typ) that this model should use. "auto" tries to determine the best type automatically. :type simulator: ForwardSimulator or {"auto", "matrix", "map"}.
add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
bulk_circuit_outcomes(circuits[, ...])Get all the possible outcome labels produced by simulating each of the circuits in this list of circuits.
Creates a list of dictionaries mapping from
SeparatePOVMCircuitobjects from expanding the instruments of this circuit.bulk_probabilities(circuits[, clip_to, ...])Construct a dictionary containing the probabilities for an entire list of circuits.
circuit_layer_operator(layerlbl[, typ])Construct or retrieve the operation associated with a circuit layer.
circuit_operator(circuit)Construct or retrieve the operation associated with a circuit.
circuit_outcomes(circuit)Get all the possible outcome labels produced by simulating this circuit.
circuit_parameter_dependence(circuits[, ...])Calculate the which model parameters each of the input circuits depends upon.
collect_parameters(params_to_collect[, ...])Updates this model's parameters so that previously independent parameters are tied together.
complete_circuit(circuit[, ...])Adds any implied preparation or measurement layers to circuit
complete_circuits(circuits[, ...])Adds any implied preparation or measurement layers to list of circuits.
Constructs a dictionary of the symplectic representations for all the Clifford gates in this model.
compute_num_outcomes(circuit)The number of outcomes of circuit, given by it's existing or implied POVM label.
copy()Copy this model.
Generate a ModelMemberGraph for the model.
create_processor_spec()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_coefficients([normalized_elem_gens])TODO: docstring - returns a nested dict containing all the error generator coefficients for all the operations in this model.
expand_instruments_and_separate_povm(circuit)Creates a dictionary of
SeparatePOVMCircuitobjects from expanding the instruments of this circuit.fogi_contribution(op_label[, error_type, ...])Computes a contribution to the FOGI error on a single gate.
fogi_errorgen_component_labels([...])fogi_errorgen_components_array([...])fogi_errorgen_vector([normalized_elem_gens])Constructs a vector from all the error generator coefficients involved in the FOGI analysis of this model.
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.
is_equivalent(other_model[, rtol, atol])Whether or not two Models are equivalent to each other.
is_similar(other_model[, rtol, atol])Whether or not two Models have the same structure.
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.
Print a summary of all the members within this model.
print_parameters_by_op([max_depth])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_fogi_errorgen_components_array(components)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.
set_parameter_value(index, val[, close])This method allows for updating the value of a single model parameter at the specified parameter index.
set_parameter_values(indices, values[, close])This method allows for updating the values of multiple model parameter at the specified parameter indices.
setup_fogi(initial_gauge_basis[, ...])split_circuit(circuit[, erroron, ...])Splits a circuit into prep_layer + op_layers + povm_layer components.
split_circuits(circuits[, erroron, ...])Splits a circuit into prep_layer + op_layers + povm_layer components.
Build an
ExplicitOpModelequivalent to this implicit model.Serialize this object in a way that adheres to "niceness" rules of common text file formats.
Returns the model vectorized according to the optional parameters.
uncollect_parameters(param_to_uncollect)Updates this model's parameters so that a common parameter becomes independent parameters.
write(path, **format_kwargs)Writes this object to a file.
write_to_mongodb(mongodb[, session, ...])Write this object to a MongoDB database.
Attributes
The basis used to represent dense (super)operators of this model
collection_nameThe dimension of the model.
Evolution type
Dictionary of hyperparameters associated with this model
The parameter count to use when testing this model against data.
The number of free parameters when vectorizing this model.
param_interposerUpper and lower bounds on the values of each parameter, utilized by optimization routines
A list of labels, usually of the form (op_label, string_description) describing this model's parameters.
The list of parameter labels but formatted in a nice way.
primitive_instrument_labelsprimitive_op_labelsprimitive_povm_labelsprimitive_prep_labelsForward simulator for this model
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 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
- bulk_circuit_outcomes(circuits, split_circuits=None, completed_circuits=None)#
Get all the possible outcome labels produced by simulating each of the circuits in this list of circuits.
- Parameters:
circuits (list of Circuits) – list of Circuits to get outcomes of.
split_circuits (list of tuples, optional (default None)) – If specified, this is a list of tuples for each circuit corresponding to the splitting of the circuit into the prep label, spam-free circuit, and povm label. This is the same format produced by the :meth:split_circuit(s) method, and so this option can allow for accelerating this method when that has previously been run. When using this kwarg only one of this or the complete_circuits kwargs should be used.
completed_circuits (list of Circuits, optional (default None)) – If specified, this is a list of completed circuits with prep and povm labels included. This is the format produced by the :meth:complete_circuit(s) method, and this can be used to accelerate this method call when that has been previously run. Should not be used in conjunction with split_circuits.
- Return type:
list of tuples corresponding to the possible outcomes for each circuit.
- bulk_expand_instruments_and_separate_povm(circuits, observed_outcomes_list=None, split_circuits=None, completed_circuits=None)#
Creates a list of dictionaries mapping from
SeparatePOVMCircuitobjects from expanding the instruments of this circuit.Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as
SeparatePOVMCircuitobjects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities.This function works similarly to expand_instruments_and_separate_povm, except it operates on an entire list of circuits at once, and provides additional kwargs to accelerate computation.
- Parameters:
circuit (Circuit) –
The circuit to expand, using necessary details regarding the expansion from this model, including:
default SPAM layers
definitions of instrument-containing layers
expansions of individual instruments and POVMs
observed_outcomes_list (list of iterables, optional (default None)) – If specified a list of iterables over the subset of outcomes empirically observed for each circuit.
split_circuits (list of tuples, optional (default None)) – If specified, this is a list of tuples for each circuit corresponding to the splitting of the circuit into the prep label, spam-free circuit, and povm label. This is the same format produced by the :meth:split_circuit(s) method, and so this option can allow for accelerating this method when that has previously been run. When using this kwarg only one of this or the complete_circuits kwargs should be used.
completed_circuits (list of Circuits, optional (default None)) – If specified, this is a list of completed circuits with prep and povm labels included. This is the format produced by the :meth:complete_circuit(s) method, and this can be used to accelerate this method call when that has been previously run. Should not be used in conjunction with split_circuits.
- Returns:
A list of dictionaries whose keys are
SeparatePOVMCircuitobjects and whose values are tuples of the outcome labels corresponding to each circuit, one per POVM effect held in the key.- Return type:
list of OrderedDicts
- 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
CircuitOutcomeProbabilityArrayLayoutspecifies 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.
dataset (DataSet, optional) – If not None, restrict what is computed to only those probabilities corresponding to non-zero counts (observed outcomes) in this data set.
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_layer_operator(layerlbl, typ='auto')#
Construct or retrieve the operation associated with a circuit layer.
- Parameters:
layerlbl (Label) – The circuit-layer label to construct an operation for.
typ ({'op','prep','povm','auto'}) – The type of layer layerlbl refers to: ‘prep’ is for state preparation (only at the beginning of a circuit), ‘povm’ is for a measurement: a POVM or effect label (only at the end of a circuit), and ‘op’ is for all other “middle” circuit layers.
- Return type:
LinearOperator or State or POVM
- circuit_operator(circuit)#
Construct or retrieve the operation associated with a circuit.
- Parameters:
circuit (Circuit) – The circuit to construct an operation for. This circuit should not contain any state preparation or measurement layers.
- Return type:
- 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 corresponding to the possible outcomes for circuit.
- circuit_parameter_dependence(circuits, return_param_circ_map=False)#
Calculate the which model parameters each of the input circuits depends upon. Return this result in the the form of a dictionary whose keys are circuits, and whose values are lists of parameters upon which that circuit depends. Optionally a reverse mapping from model parameters to the input circuits which depend on that parameter.
Note: This methods does not work with models using parameter interposers presently.
- Parameters:
circuits (list of Circuits) – List of circuits to determine parameter dependence for.
return_param_circ_map (bool, optional (default False)) – A flag indicating whether to return a reverse mapping from parameters to circuits depending on those parameters.
- Returns:
circuit_parameter_map (dict) – Dictionary with keys given by Circuits and values giving the list of model parameter indices upon which that circuit depends.
param_to_circuit_map (dict, optional) – Dictionary with keys given by model parameter indices, and values giving the list of input circuits dependent upon that parameter.
- collect_parameters(params_to_collect, new_param_label=None)#
Updates this model’s parameters so that previously independent parameters are tied together.
The model’s parameterization is modified so that all of the parameters given by params_to_collect are replaced by a single parameter. The label of this single parameter may be given if desired.
Note that after this function is called the model’s parameter vector (i.e. the result of to_vector()) should be assumed to have a new format unrelated to the parameter vector before their adjustment. For example, you should not assume that un-modified parameters will retain their old indices.
- Parameters:
params_to_collect (iterable) – A list or tuple of parameter labels describing the parameters to collect. These should be a subset of the elements of self.parameter_labels or of self.parameter_labels_pretty, or integer indices into the model’s parameter vector. If empty, no parameter adjustment is performed.
new_param_label (object, optional) – The label for the new common parameter. If None, then the parameter label of the first collected parameter is used.
- Return type:
None
- complete_circuit(circuit, prep_lbl_to_prepend=None, povm_lbl_to_append=None)#
Adds any implied preparation or measurement layers to circuit
Converts circuit into a “complete circuit”, where the first (0-th) layer is a state preparation and the final layer is a measurement (POVM) layer.
- Parameters:
circuit (Circuit) – Circuit to act on.
prep_lbl_to_prepend (Label, optional (default None)) – Optional user specified prep label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a prep label this argument will be ignored.
povm_lbl_to_append (Label, optional (default None)) – Optional user specified prep label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a prep label this argument will be ignored.
- Returns:
Possibly the same object as circuit, if no additions are needed.
- Return type:
- complete_circuits(circuits, prep_lbl_to_prepend=None, povm_lbl_to_append=None, return_split=False)#
Adds any implied preparation or measurement layers to list of circuits.
Converts circuit into a “complete circuit”, where the first (0-th) layer is a state preparation and the final layer is a measurement (POVM) layer.
- Parameters:
circuits (list of Circuit) – List of Circuit objects to act on.
prep_lbl_to_prepend (Label, optional (default None)) – Optional user specified prep label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a prep label this argument will be ignored.
povm_lbl_to_append (Label, optional (default None)) – Optional user specified povm label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a povm label this argument will be ignored.
return_split (bool, optional (default False)) – If True we additionally return a list of tuples of the form: (prep_label, no_spam_circuit, povm_label) for each circuit. This is of the same format returned by :meth:split_circuits when using the kwarg combination: erroron=(‘prep’, ‘povm’), split_prep=True, split_povm=True
- Returns:
Possibly the same object as circuit, if no additions are needed.
- Return type:
- compute_clifford_symplectic_reps(oplabel_filter=None)#
Constructs a dictionary of the symplectic representations for all the Clifford gates in this model.
Non-
StaticCliffordOpgates will be ignored and their entries omitted from the returned dictionary.- Parameters:
oplabel_filter (iterable, optional) – A list, tuple, or set of operation labels whose symplectic representations should be returned (if they exist).
- Returns:
keys are operation labels and/or just the root names of gates (without any state space indices/labels). Values are (symplectic_matrix, phase_vector) tuples.
- Return type:
dict
- 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
- create_modelmember_graph()#
Generate a ModelMemberGraph for the model.
- Returns:
A directed graph capturing dependencies among model members
- Return type:
- 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
- errorgen_coefficients(normalized_elem_gens=True)#
TODO: docstring - returns a nested dict containing all the error generator coefficients for all the operations in this model.
- expand_instruments_and_separate_povm(circuit, observed_outcomes=None)#
Creates a dictionary of
SeparatePOVMCircuitobjects from expanding the instruments of this circuit.Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as
SeparatePOVMCircuitobjects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities.- Parameters:
circuit (Circuit) –
The circuit to expand, using necessary details regarding the expansion from this model, including:
default SPAM layers
definitions of instrument-containing layers
expansions of individual instruments and POVMs
observed_outcomes (iterable, optional (default None)) – If specified an iterable over the subset of outcomes empirically observed for this circuit.
- Returns:
A dict whose keys are
SeparatePOVMCircuitobjects and whose values are tuples of the outcome labels corresponding to this circuit, one per POVM effect held in the key.- Return type:
OrderedDict
- fogi_contribution(op_label, error_type='H', intrinsic_or_relational='intrinsic', target='all', hessian_for_errorbars=None)#
Computes a contribution to the FOGI error on a single gate.
This method is used when partitioning the (FOGI) error on a gate in various ways, based on the error type, whether the error is intrinsic or relational, and the upon the error support.
- Parameters:
op_label (Label) – The operation to compute a contribution for.
error_type ({'H', 'S', 'fogi_total_error', 'fogi_infidelity'}) – The type of errors to include in the partition. ‘H’ means Hamiltonian and ‘S’ means Pauli stochastic. There are two options for including both H and S errors: ‘fogi_total_error’ adds the Hamiltonian errors linearly with the Pauli tochastic errors, similar to the diamond distance; ‘fogi_infidelity’ adds the Hamiltonian errors in quadrature to the linear sum of Pauli stochastic errors, similar to the entanglement or average gate infidelity.
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).
hessian_for_errorbars (numpy.ndarray, optional) – If not None, a hessian matrix for this model (with shape (Np, Np) where Np == self.num_params, the number of model parameters) that is used to compute and return 1-sigma error bars.
- Returns:
value (float) – The value of the requested contribution.
errorbar (float) – The 1-sigma error bar, returned only if hessian_for_errorbars is given.
- fogi_errorgen_vector(normalized_elem_gens=False)#
Constructs a vector from all the error generator coefficients involved in the FOGI analysis of this model.
- Parameters:
normalized_elem_gens (bool, optional) – Whether or not coefficients correspond to elementary error generators constructed from normalized Pauli matrices or not.
- Return type:
numpy.ndarray
- 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.
The inverse of to_vector.
- 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
- is_equivalent(other_model, rtol=1e-05, atol=1e-08)#
Whether or not two Models are equivalent to each other.
If True, then the two models have the same structure and the same parameters, so they are in all ways alike and will compute the same probabilities.
- Parameters:
other_model (Model) – The model to compare against
rtol (float, optional) – Relative tolerance used to check if floating point (including parameter) values are “equal”, as passed to numpy.allclose.
atol (float, optional) – Absolute tolerance used to check if floating point (including parameter) values are “equal”, as passed to numpy.allclose.
- Return type:
bool
- is_similar(other_model, rtol=1e-05, atol=1e-08)#
Whether or not two Models have the same structure.
If True, then the two models are the same except for, perhaps, being at different parameter-space points (i.e. having different parameter vectors). Similar models, A and B, can be made equivalent (see
is_equivalent()) by calling modelA.from_vector(modelB.to_vector()).- Parameters:
other_model (Model) – The model to compare against
rtol (float, optional) – Relative tolerance used to check if floating point values are “equal”, as passed to numpy.allclose.
atol (float, optional) – Absolute tolerance used to check if floating point values are “equal”, as passed to numpy.allclose.
- 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:
- 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:
- print_modelmembers()#
Print a summary of all the members within this model.
- 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:
- 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
- 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
- set_parameter_value(index, val, close=False)#
This method allows for updating the value of a single model parameter at the specified parameter index.
- Parameters:
index (int or tuple) – Index of the parameter value in the model’s parameter vector to update. If a tuple this instead indexes by the corresponding parameter label.
val (float) – Updated parameter value.
close (bool, optional) – Set to True if val is close to the current parameter vector. This can make some operations more efficient.
- Return type:
None
- set_parameter_values(indices, values, close=False)#
This method allows for updating the values of multiple model parameter at the specified parameter indices.
- Parameters:
indices (list of ints or tuples) – Indices of the parameter values in the model’s parameter vector to update. If tuples this instead indexes by the corresponding parameter label. Mixing integer indices and parameter label tuples is not supported. Note: In the event that the parameter labels vector for this model contains duplicates the update may only apply to the first instance.
values (list or tuple of floats) – Updated parameter values.
close (bool, optional) – Set to True if values are close to the current parameter vector. This can make some operations more efficient.
- Return type:
None
- split_circuit(circuit, erroron=('prep', 'povm'), split_prep=True, split_povm=True)#
Splits a circuit into prep_layer + op_layers + povm_layer components.
If circuit does not contain a prep label or a povm label a default label is returned if one exists.
- Parameters:
circuit (Circuit) – A circuit, possibly beginning with a state preparation label and ending with a povm label.
erroron (tuple of {'prep','povm'}) – A ValueError is raised if a preparation or povm label cannot be resolved when ‘prep’ or ‘povm’ is included in ‘erroron’. Otherwise None is returned in place of unresolvable labels. An exception is when this model has no preps or povms, in which case None is always returned and errors are never raised, since in this case one usually doesn’t expect to use the Model to compute probabilities (e.g. in germ selection).
split_prep (bool, optional) – Whether to split off the state prep and return it as prep_label. If False, then the returned preparation label is always None, and is not removed from ops_only_circuit.
split_povm (bool, optional) – Whether to split off the POVM and return it as povm_label. If False, then the returned POVM label is always None, and is not removed from ops_only_circuit.
- Returns:
prep_label (Label or None)
ops_only_circuit (Circuit)
povm_label (Label or None)
- split_circuits(circuits, erroron=('prep', 'povm'), split_prep=True, split_povm=True)#
Splits a circuit into prep_layer + op_layers + povm_layer components.
If circuit does not contain a prep label or a povm label a default label is returned if one exists.
- Parameters:
circuit (list of Circuit) – A list of circuits, possibly beginning with a state preparation label and ending with a povm label.
erroron (tuple of {'prep','povm'}) – A ValueError is raised if a preparation or povm label cannot be resolved when ‘prep’ or ‘povm’ is included in ‘erroron’. Otherwise None is returned in place of unresolvable labels. An exception is when this model has no preps or povms, in which case None is always returned and errors are never raised, since in this case one usually doesn’t expect to use the Model to compute probabilities (e.g. in germ selection).
split_prep (bool, optional) – Whether to split off the state prep and return it as prep_label. If False, then the returned preparation label is always None, and is not removed from ops_only_circuit.
split_povm (bool, optional) – Whether to split off the POVM and return it as povm_label. If False, then the returned POVM label is always None, and is not removed from ops_only_circuit.
- Returns:
list of tuples containing
prep_label (Label or None)
ops_only_circuit (Circuit)
povm_label (Label or None)
- to_explicit_model()#
Build an
ExplicitOpModelequivalent to this implicit model.Each primitive layer member stored in this model’s
prep_blks['layers'],povm_blks['layers'],operation_blks['layers'], andinstrument_blks['layers']dictionaries is copied into the returned model as an explicitly-stored member. The result therefore reproduces this model’s circuit-layer operators for any layer that this model builds by a direct lookup of these primitives – which is what report generation and other explicit-model-only code paths require.The members’ parameterizations are preserved: the actual
ModelMemberobjects are copied rather than densified, so a low-weight error-generator (Lindblad), TP, CPTP, etc. operation remains that type in the returned model. Parameter sharing between primitives (such as a single base gate embedded on several qubits in aindependent_gates=Falsemodel) is preserved as well, so the returned model should have the same number of parameters as this one.- Return type:
Notes
This function does not support ImplicitOpModel’s with factories.
- 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
- uncollect_parameters(param_to_uncollect)#
Updates this model’s parameters so that a common parameter becomes independent parameters.
The model’s parameterization is modified so that each usage of the given parameter in the model’s parameterized operations is promoted to being a new independent parameter. The labels of the new parameters are set by the operations.
Note that after this function is called the model’s parameter vector (i.e. the result of to_vector()) should be assumed to have a new format unrelated to the parameter vector before their adjustment. For example, you should not assume that un-modified parameters will retain their old indices.
- Parameters:
param_to_uncollect (int or object) – A parameter label specifying the parameter to “uncollect”. This should be an element of self.parameter_labels or self.parameter_labels_pretty, or it may be an integer index into the model’s parameter vector.
- 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 dim#
The dimension of the model.
This equals d when the gate (or, more generally, circuit-layer) matrices would have shape d x d and spam vectors would have shape d x 1 (if they were computed).
- Returns:
model dimension
- Return type:
int
- property evotype#
Evolution type
- Return type:
str
- property hyperparams#
Dictionary of hyperparameters associated with this model
- Return type:
dict
- property num_modeltest_params#
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.- Returns:
the number of model parameters.
- Return type:
int
- 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 sim#
Forward simulator for this model
- property state_space#
State space labels
- Return type:
StateSpaceLabels