pygsti.forwardsims.matrixforwardsim.MatrixForwardSimulator#
- class MatrixForwardSimulator(model=None, distribute_by_timestamp=False, num_atoms=None, processor_grid=None, param_blk_sizes=None)#
Bases:
DistributableForwardSimulator,SimpleMatrixForwardSimulatorComputes circuit outcome probabilities by multiplying together circuit-layer process matrices.
Interfaces with a model via its circuit_layer_operator method and extracts a dense matrix representation of operators by calling their to_dense method. An “evaluation tree” that composes all of the circuits using pairwise “joins” is constructed by a
MatrixCOPALayoutlayout object, and this tree then directs pairwise multiplications of process matrices to compute circuit outcome probabilities. Derivatives are computed analytically, using operators’ deriv_wrt_params methods.- Parameters:
model (Model, optional) – The parent model of this simulator. It’s fine if this is None at first, but it will need to be set (by assigning self.model before using this simulator.
distribute_by_timestamp (bool, optional) – When True, treat the data as time dependent, and distribute the computation of outcome probabilitiesby assigning groups of processors to the distinct time stamps within the dataset. This means of distribution be used only when the circuits themselves contain no time delay information (all circuit layer durations are 0), as operators are cached at the “start” time of each circuit, i.e., the timestamp in the data set. If False, then the data is treated in a time-independent way, and the overall counts for each outcome are used. If support for intra-circuit time dependence is needed, you must use a different forward simulator (e.g.
MapForwardSimulator).num_atoms (int, optional) – The number of atoms (sub-evaluation-trees) to use when creating the layout (i.e. when calling
create_layout()). This determines how many units the element (circuit outcome probability) dimension is divided into, and doesn’t have to correclate with the number of processors. When multiple processors are used, if num_atoms is less than the number of processors then num_atoms should divide the number of processors evenly, so that num_atoms // num_procs groups of processors can be used to divide the computation over parameter dimensions.processor_grid (tuple optional) – Specifies how the total number of processors should be divided into a number of atom-processors, 1st-parameter-deriv-processors, and 2nd-parameter-deriv-processors. Each level of specification is optional, so this can be a 1-, 2-, or 3- tuple of integers (or None). Multiplying the elements of processor_grid together should give at most the total number of processors.
param_blk_sizes (tuple, optional) – The parameter block sizes along the first or first & second parameter dimensions - so this can be a 0-, 1- or 2-tuple of integers or None values. A block size of None means that there should be no division into blocks, and that each block processor computes all of its parameter indices at once.
Methods
__init__([model, distribute_by_timestamp, ...])add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
bulk_dprobs(circuits[, resource_alloc, smartc])Construct a dictionary containing the probability derivatives for an entire list of circuits.
bulk_dproduct(circuits[, flat, ...])Compute the derivative of a many operation sequences at once.
bulk_fill_dprobs(array_to_fill, layout[, ...])Compute the outcome probability-derivatives for an entire tree of circuits.
bulk_fill_hprobs(array_to_fill, layout[, ...])Compute the outcome probability-Hessians for an entire list of circuits.
bulk_fill_probs(array_to_fill, layout)Compute the outcome probabilities for a list circuits.
bulk_fill_timedep_chi2(array_to_fill, ...[, ...])Compute the chi2 contributions for an entire tree of circuits, allowing for time dependent operations.
bulk_fill_timedep_dchi2(array_to_fill, ...)Compute the chi2 jacobian contributions for an entire tree of circuits, allowing for time dependent operations.
bulk_fill_timedep_dloglpp(array_to_fill, ...)Compute the ("poisson picture")log-likelihood jacobian contributions for an entire tree of circuits.
bulk_fill_timedep_loglpp(array_to_fill, ...)Compute the log-likelihood contributions (within the "poisson picture") for an entire tree of circuits.
bulk_hprobs(circuits[, resource_alloc, smartc])Construct a dictionary containing the probability Hessians for an entire list of circuits.
bulk_probs(circuits[, clip_to, ...])Construct a dictionary containing the probabilities for an entire list of circuits.
bulk_product(circuits[, scale, resource_alloc])Compute the products of many circuits at once.
cast(obj[, num_qubits])num_qubits only used if obj == 'auto'
copy([keep_model_attached])Return a shallow copy of this MatrixForwardSimulator
create_copa_layout_circuit_cache(circuits, model)Helper function for pre-computing/pre-processing circuits structures used in matrix layout creation.
create_layout(circuits[, dataset, ...])Constructs an circuit-outcome-probability-array (COPA) layout for a list of circuits.
dprobs(circuit[, resource_alloc])Construct a dictionary containing outcome probability derivatives for a single circuit.
dproduct(circuit[, flat, wrt_filter])Compute the derivative of a specified sequence of operation labels.
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.
hprobs(circuit[, resource_alloc])Construct a dictionary containing outcome probability Hessians for a single circuit.
hproduct(circuit[, flat, wrt_filter1, ...])Compute the hessian of a specified sequence of operation labels.
iter_hprobs_by_rectangle(layout, wrt_slices_list)Iterates over the 2nd derivatives of a layout's circuit probabilities one rectangle at a time.
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.
probs(circuit[, outcomes, time, resource_alloc])Construct a dictionary containing the outcome probabilities for a single circuit.
product(circuit[, scale])Compute the product of a specified sequence of operation labels.
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, ...])Serialize this object in a way that adheres to "niceness" rules of common text file formats.
write(path, **format_kwargs)Writes this object to a file.
write_to_mongodb(mongodb[, session, ...])Write this object to a MongoDB database.
Attributes
Castablealias of
ForwardSimulator|Callable[[],ForwardSimulator] |Literal['map'] |Literal['matrix'] |Literal['auto']collection_namemodel- 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_dprobs(circuits, resource_alloc=None, smartc=None)#
Construct a dictionary containing the probability derivatives for an entire list of circuits.
- Parameters:
circuits (list of Circuits) – The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayoutobject containing pre-computed quantities that make this function run faster.resource_alloc (ResourceAllocation, optional) – A resource allocation object describing the available resources and a strategy for partitioning them.
smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.
- Returns:
dprobs – A dictionary such that dprobs[circuit] is an ordered dictionary of derivative arrays (one element per differentiated parameter) whose keys are outcome labels
- Return type:
dictionary
- bulk_dproduct(circuits, flat=False, return_prods=False, scale=False, resource_alloc=None, wrt_filter=None)#
Compute the derivative of a many operation sequences at once.
- Parameters:
circuits (list of Circuits) – The circuits to compute products for. These should not have any preparation or measurement layers.
flat (bool, optional) – Affects the shape of the returned derivative array (see below).
return_prods (bool, optional) – when set to True, additionally return the probabilities.
scale (bool, optional) – When True, return a scaling factor (see below).
resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.
wrt_filter (list of ints, optional) – If not None, a list of integers specifying which gate parameters to include in the derivative. Each element is an index into an array of gate parameters ordered by concatenating each gate’s parameters (in the order specified by the model). This argument is used internally for distributing derivative calculations across multiple processors.
- Returns:
derivs (numpy array) –
if flat == False, an array of shape S x M x G x G, where: - S == len(circuits) - M == the length of the vectorized model - G == the linear dimension of a operation matrix (G x G operation matrices) and derivs[i,j,k,l] holds the derivative of the (k,l)-th entry of the i-th operation sequence product with respect to the j-th model parameter.
if flat == True, an array of shape S*N x M where: - N == the number of entries in a single flattened gate (ordering same as numpy.flatten), - S,M == as above, and deriv[i,j] holds the derivative of the (i % G^2)-th entry of the (i / G^2)-th flattened operation sequence product with respect to the j-th model parameter.
products (numpy array) – Only returned when return_prods == True. An array of shape S x G x G; products[i] is the i-th operation sequence product.
scaleVals (numpy array) – Only returned when scale == True. An array of shape S such that scaleVals[i] contains the multiplicative scaling needed for the derivatives and/or products for the i-th operation sequence.
- bulk_fill_dprobs(array_to_fill, layout, pr_array_to_fill=None)#
Compute the outcome probability-derivatives for an entire tree of circuits.
This routine fills a 2D array, array_to_fill with circuit outcome probabilities as dictated by a
CircuitOutcomeProbabilityArrayLayout(“COPA layout”) object, which is usually specifically tailored for efficiency.The array_to_fill array must have length equal to the number of elements in layout, and the meanings of each element are given by layout.
- Parameters:
array_to_fill (numpy ndarray) – an already-allocated 2D numpy array of shape (len(layout), Np), where Np is the number of model parameters being differentiated with respect to.
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().pr_mx_to_fill (numpy array, optional) – when not None, an already-allocated length-len(layout) numpy array that is filled with probabilities, just as in
bulk_fill_probs().
- Return type:
None
- bulk_fill_hprobs(array_to_fill, layout, pr_array_to_fill=None, deriv1_array_to_fill=None, deriv2_array_to_fill=None)#
Compute the outcome probability-Hessians for an entire list of circuits.
Similar to bulk_fill_probs(…), but fills a 3D array with the Hessians for each circuit outcome probability.
- Parameters:
array_to_fill (numpy ndarray) – an already-allocated numpy array of shape (len(layout),M1,M2) where M1 and M2 are the number of selected model parameters (by wrt_filter1 and wrt_filter2).
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().pr_mx_to_fill (numpy array, optional) – when not None, an already-allocated length-len(layout) numpy array that is filled with probabilities, just as in
bulk_fill_probs().deriv1_array_to_fill (numpy array, optional) – when not None, an already-allocated numpy array of shape (len(layout),M1) that is filled with probability derivatives, similar to
bulk_fill_dprobs()(see array_to_fill for a definition of M1).deriv2_array_to_fill (numpy array, optional) – when not None, an already-allocated numpy array of shape (len(layout),M2) that is filled with probability derivatives, similar to
bulk_fill_dprobs()(see array_to_fill for a definition of M2).
- Return type:
None
- bulk_fill_probs(array_to_fill, layout)#
Compute the outcome probabilities for a list circuits.
This routine fills a 1D array, array_to_fill with circuit outcome probabilities as dictated by a
CircuitOutcomeProbabilityArrayLayout(“COPA layout”) object, which is usually specifically tailored for efficiency.The array_to_fill array must have length equal to the number of elements in layout, and the meanings of each element are given by layout.
- Parameters:
array_to_fill (numpy ndarray) – an already-allocated 1D numpy array of length equal to the total number of computed elements (i.e. len(layout)).
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().
- Return type:
None
- bulk_fill_timedep_chi2(array_to_fill, layout, ds_circuits, num_total_outcomes, dataset, min_prob_clip_for_weighting, prob_clip_interval, ds_cache=None)#
Compute the chi2 contributions for an entire tree of circuits, allowing for time dependent operations.
Computation is performed by summing together the contributions for each time the circuit is run, as given by the timestamps in dataset.
- Parameters:
array_to_fill (numpy ndarray) – an already-allocated 1D numpy array of length equal to the total number of computed elements (i.e. layout.num_elements)
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().ds_circuits (list of Circuits) – the circuits to use as they should be queried from dataset (see below). This is typically the same list of circuits used to construct layout potentially with some aliases applied.
num_total_outcomes (list or array) – a list of the total number of possible outcomes for each circuit (so len(num_total_outcomes) == len(ds_circuits_to_use)). This is needed for handling sparse data, where dataset may not contain counts for all the possible outcomes of each circuit.
dataset (DataSet) – the data set used to compute the chi2 contributions.
min_prob_clip_for_weighting (float, optional) – Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1-p)) by clipping probability p values to lie within the interval [ min_prob_clip_for_weighting, 1-min_prob_clip_for_weighting ].
prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
- Return type:
None
- bulk_fill_timedep_dchi2(array_to_fill, layout, ds_circuits, num_total_outcomes, dataset, min_prob_clip_for_weighting, prob_clip_interval, chi2_array_to_fill=None, ds_cache=None)#
Compute the chi2 jacobian contributions for an entire tree of circuits, allowing for time dependent operations.
Similar to
bulk_fill_timedep_chi2()but compute the jacobian of the summed chi2 contributions for each circuit with respect to the model’s parameters.- Parameters:
array_to_fill (numpy ndarray) – an already-allocated ExM numpy array where E is the total number of computed elements (i.e. layout.num_elements) and M is the number of model parameters.
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().ds_circuits (list of Circuits) – the circuits to use as they should be queried from dataset (see below). This is typically the same list of circuits used to construct layout potentially with some aliases applied.
num_total_outcomes (list or array) – a list of the total number of possible outcomes for each circuit (so len(num_total_outcomes) == len(ds_circuits_to_use)). This is needed for handling sparse data, where dataset may not contain counts for all the possible outcomes of each circuit.
dataset (DataSet) – the data set used to compute the chi2 contributions.
min_prob_clip_for_weighting (float, optional) – Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1-p)) by clipping probability p values to lie within the interval [ min_prob_clip_for_weighting, 1-min_prob_clip_for_weighting ].
prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
chi2_array_to_fill (numpy array, optional) – when not None, an already-allocated length-E numpy array that is filled with the per-circuit chi2 contributions, just like in bulk_fill_timedep_chi2(…).
- Return type:
None
- bulk_fill_timedep_dloglpp(array_to_fill, layout, ds_circuits, num_total_outcomes, dataset, min_prob_clip, radius, prob_clip_interval, logl_array_to_fill=None, ds_cache=None)#
Compute the (“poisson picture”)log-likelihood jacobian contributions for an entire tree of circuits.
Similar to
bulk_fill_timedep_loglpp()but compute the jacobian of the summed logl (in posison picture) contributions for each circuit with respect to the model’s parameters.- Parameters:
array_to_fill (numpy ndarray) – an already-allocated ExM numpy array where E is the total number of computed elements (i.e. layout.num_elements) and M is the number of model parameters.
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().ds_circuits (list of Circuits) – the circuits to use as they should be queried from dataset (see below). This is typically the same list of circuits used to construct layout potentially with some aliases applied.
num_total_outcomes (list or array) – a list of the total number of possible outcomes for each circuit (so len(num_total_outcomes) == len(ds_circuits_to_use)). This is needed for handling sparse data, where dataset may not contain counts for all the possible outcomes of each circuit.
dataset (DataSet) – the data set used to compute the logl contributions.
min_prob_clip (float) – a regularization parameter for the log-likelihood objective function.
radius (float) – a regularization parameter for the log-likelihood objective function.
prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
logl_array_to_fill (numpy array, optional) – when not None, an already-allocated length-E numpy array that is filled with the per-circuit logl contributions, just like in bulk_fill_timedep_loglpp(…).
- Return type:
None
- bulk_fill_timedep_loglpp(array_to_fill, layout, ds_circuits, num_total_outcomes, dataset, min_prob_clip, radius, prob_clip_interval, ds_cache=None)#
Compute the log-likelihood contributions (within the “poisson picture”) for an entire tree of circuits.
Computation is performed by summing together the contributions for each time the circuit is run, as given by the timestamps in dataset.
- Parameters:
array_to_fill (numpy ndarray) – an already-allocated 1D numpy array of length equal to the total number of computed elements (i.e. layout.num_elements)
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().ds_circuits (list of Circuits) – the circuits to use as they should be queried from dataset (see below). This is typically the same list of circuits used to construct layout potentially with some aliases applied.
num_total_outcomes (list or array) – a list of the total number of possible outcomes for each circuit (so len(num_total_outcomes) == len(ds_circuits_to_use)). This is needed for handling sparse data, where dataset may not contain counts for all the possible outcomes of each circuit.
dataset (DataSet) – the data set used to compute the logl contributions.
min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).
radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.
prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
- Return type:
None
- bulk_hprobs(circuits, resource_alloc=None, smartc=None)#
Construct a dictionary containing the probability Hessians for an entire list of circuits.
- Parameters:
circuits (list of Circuits) – The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayoutobject containing pre-computed quantities that make this function run faster.resource_alloc (ResourceAllocation, optional) – A resource allocation object describing the available resources and a strategy for partitioning them.
smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.
- Returns:
hprobs – A dictionary such that hprobs[circuit] is an ordered dictionary of Hessian arrays (a square matrix with one row/column per differentiated parameter) whose keys are outcome labels
- Return type:
dictionary
- bulk_probs(circuits, clip_to=None, resource_alloc=None, smartc=None)#
Construct a dictionary containing the probabilities for an entire list of circuits.
- Parameters:
circuits (list of Circuits) – The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayoutobject containing pre-computed quantities that make this function run faster.clip_to (2-tuple, optional) – (min,max) to clip return value if not None.
resource_alloc (ResourceAllocation, optional) – A resource allocation object describing the available resources and a strategy for partitioning them.
smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.
- Returns:
probs – A dictionary such that probs[circuit] is an ordered dictionary of outcome probabilities whose keys are outcome labels.
- Return type:
dictionary
- bulk_product(circuits, scale=False, resource_alloc=None)#
Compute the products of many circuits at once.
- Parameters:
circuits (list of Circuits) – The circuits to compute products for. These should not have any preparation or measurement layers.
scale (bool, optional) – When True, return a scaling factor (see below).
resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.
- Returns:
prods (numpy array) – Array of shape S x G x G, where: - S == the number of operation sequences - G == the linear dimension of a operation matrix (G x G operation matrices).
scaleValues (numpy array) – Only returned when scale == True. A length-S array specifying the scaling that needs to be applied to the resulting products (final_product[i] = scaleValues[i] * prods[i]).
- classmethod cast(obj, num_qubits=None)#
num_qubits only used if obj == ‘auto’
- Parameters:
obj (ForwardSimulator | Callable[[], ForwardSimulator] | Literal['map'] | ~typing.Literal['matrix'] | ~typing.Literal['auto'])
- copy(keep_model_attached=True)#
Return a shallow copy of this MatrixForwardSimulator
- Return type:
- static create_copa_layout_circuit_cache(circuits, model, dataset=None)#
Helper function for pre-computing/pre-processing circuits structures used in matrix layout creation.
- create_layout(circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimensions=None, verbosity=0, layout_creation_circuit_cache=None)#
Constructs an circuit-outcome-probability-array (COPA) layout for a list of circuits.
- Parameters:
circuits (list) – The circuits whose outcome probabilities should be included in the layout.
dataset (DataSet) – The source of data counts that will be compared to the circuit outcome probabilities. The computed outcome probabilities are limited to those with counts present in dataset.
resource_alloc (ResourceAllocation) – A available resources and allocation information. These factors influence how the layout (evaluation strategy) is constructed.
array_types (tuple, optional) – A tuple of string-valued array types. See
ForwardSimulator.create_layout().derivative_dimensions (int or tuple[int], optional) – Optionally, the parameter-space dimension used when taking first and second derivatives with respect to the circuit outcome probabilities. This must be non-None when array_types contains ‘ep’ or ‘epp’ types. If a tuple, then must be length 1.
verbosity (int or VerbosityPrinter) – Determines how much output to send to stdout. 0 means no output, higher integers mean more output.
layout_creation_circuit_cache (dict, optional (default None)) – A precomputed dictionary serving as a cache for completed circuits. I.e. circuits with prep labels and POVM labels appended. Along with other useful pre-computed circuit structures used in layout creation.
- Return type:
- dprobs(circuit, resource_alloc=None)#
Construct a dictionary containing outcome probability derivatives for a single circuit.
- Parameters:
circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.
resource_alloc (ResourceAllocation, optional) – The resources available for computing circuit outcome probability derivatives.
- Returns:
dprobs – A dictionary with keys equal to outcome labels and values equal to an array containing the (partial) derivatives of the outcome probability with respect to all model parameters.
- Return type:
- dproduct(circuit, flat=False, wrt_filter=None)#
Compute the derivative of a specified sequence of operation labels.
- Parameters:
circuit (Circuit or tuple of operation labels) – The sequence of operation labels.
flat (bool, optional) – Affects the shape of the returned derivative array (see below).
wrt_filter (list of ints, optional) – If not None, a list of integers specifying which gate parameters to include in the derivative. Each element is an index into an array of gate parameters ordered by concatenating each gate’s parameters (in the order specified by the model). This argument is used internally for distributing derivative calculations across multiple processors.
- Returns:
deriv –
if flat == False, a M x G x G array, where:
M == length of the vectorized model (number of model parameters)
G == the linear dimension of a operation matrix (G x G operation matrices).
and deriv[i,j,k] holds the derivative of the (j,k)-th entry of the product with respect to the i-th model parameter.
if flat == True, a N x M array, where:
N == the number of entries in a single flattened gate (ordering as numpy.flatten)
M == length of the vectorized model (number of model parameters)
and deriv[i,j] holds the derivative of the i-th entry of the flattened product with respect to the j-th model parameter.
- Return type:
numpy array
- 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
- hprobs(circuit, resource_alloc=None)#
Construct a dictionary containing outcome probability Hessians for a single circuit.
- Parameters:
circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.
resource_alloc (ResourceAllocation, optional) – The resources available for computing circuit outcome probability Hessians.
- Returns:
hprobs – A dictionary with keys equal to outcome labels and values equal to a 2D array that is the Hessian matrix for the corresponding outcome probability (with respect to all model parameters).
- Return type:
- hproduct(circuit, flat=False, wrt_filter1=None, wrt_filter2=None)#
Compute the hessian of a specified sequence of operation labels.
- Parameters:
circuit (Circuit or tuple of operation labels) – The sequence of operation labels.
flat (bool, optional) – Affects the shape of the returned derivative array (see below).
wrt_filter1 (list of ints, optional) – If not None, a list of integers specifying which parameters to differentiate with respect to in the first (row) derivative operations. Each element is an model-parameter index. This argument is used internally for distributing derivative calculations across multiple processors.
wrt_filter2 (list of ints, optional) – If not None, a list of integers specifying which parameters to differentiate with respect to in the second (col) derivative operations. Each element is an model-parameter index. This argument is used internally for distributing derivative calculations across multiple processors.
- Returns:
hessian –
if flat == False, a M x M x G x G numpy array, where:
M == length of the vectorized model (number of model parameters)
G == the linear dimension of a operation matrix (G x G operation matrices).
and hessian[i,j,k,l] holds the derivative of the (k,l)-th entry of the product with respect to the j-th then i-th model parameters.
if flat == True, a N x M x M numpy array, where:
N == the number of entries in a single flattened gate (ordered as numpy.flatten)
M == length of the vectorized model (number of model parameters)
and hessian[i,j,k] holds the derivative of the i-th entry of the flattened product with respect to the k-th then k-th model parameters.
- Return type:
numpy array
- iter_hprobs_by_rectangle(layout, wrt_slices_list, return_dprobs_12=False)#
Iterates over the 2nd derivatives of a layout’s circuit probabilities one rectangle at a time.
This routine can be useful when memory constraints make constructing the entire Hessian at once impractical, and as it only computes a subset of the Hessian’s rows and columns (a “rectangle”) at once. For example, the Hessian of a function of many circuit probabilities can often be computed rectangle-by-rectangle and without the need to ever store the entire Hessian at once.
- Parameters:
layout (CircuitOutcomeProbabilityArrayLayout) – A layout for generated arrays, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout().wrt_slices_list (list) – A list of (rowSlice,colSlice) 2-tuples, each of which specify a “rectangle” of the Hessian to compute. Iterating over the output of this function iterates over these computed rectangles, in the order given by wrt_slices_list. rowSlice and colSlice must by Python slice objects.
return_dprobs_12 (boolean, optional) – If true, the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability generated by the sequence and spam label indexed by iOpStr and iSpamLabel. d12 has the same dimensions as the Hessian, and turns out to be useful when computing the Hessian of functions of the probabilities.
- Returns:
A generator which, when iterated, yields the 3-tuple (rowSlice, colSlice, hprobs) or (rowSlice, colSlice, hprobs, dprobs12) (the latter if return_dprobs_12 == True). rowSlice and colSlice are slices directly from wrt_slices_list. hprobs and dprobs12 are arrays of shape E x B x B’, where:
E is the length of layout elements
B is the number of parameter rows (the length of rowSlice)
B’ is the number of parameter columns (the length of colSlice)
If mx, dp1, and dp2 are the outputs of
bulk_fill_hprobs()(i.e. args mx_to_fill, deriv1_mx_to_fill, and deriv2_mx_to_fill), then:hprobs == mx[:,rowSlice,colSlice]
dprobs12 == dp1[:,rowSlice,None] * dp2[:,None,colSlice]
- Return type:
rectangle_generator
- 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:
- probs(circuit, outcomes=None, time=None, resource_alloc=None)#
Construct a dictionary containing the outcome probabilities for a single 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’. If None, only non-zero outcome probabilities will be reported.
time (float, optional) – The start time at which circuit is evaluated.
resource_alloc (ResourceAllocation, optional) – The resources available for computing circuit outcome probabilities.
- Returns:
probs – A dictionary with keys equal to outcome labels and values equal to probabilities. If no target outcomes provided, only non-zero probabilities will be reported.
- Return type:
- product(circuit, scale=False)#
Compute the product of a specified sequence of operation labels.
Note: LinearOperator matrices are multiplied in the reversed order of the tuple. That is, the first element of circuit can be thought of as the first gate operation performed, which is on the far right of the product of matrices.
- Parameters:
circuit (Circuit or tuple of operation labels) – The sequence of operation labels.
scale (bool, optional) – When True, return a scaling factor (see below).
- Returns:
product (numpy array) – The product or scaled product of the operation matrices.
scale (float) – Only returned when scale == True, in which case the actual product == product * scale. The purpose of this is to allow a trace or other linear operation to be done prior to the scaling.
- 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
- to_nice_serialization()#
Serialize this object in a way that adheres to “niceness” rules of common text file formats.
- Returns:
Usually a dictionary representing the serialized object, but may also be another native Python type, e.g. a string or list.
- Return type:
object
- write(path, **format_kwargs)#
Writes this object to a file.
- Parameters:
path (str or Path) – The name of the file that is written.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
None
- write_to_mongodb(mongodb, session=None, overwrite_existing=False, **kwargs)#
Write this object to a MongoDB database.
The collection name used is self.collection_name, and the _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to write data to.
session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.
overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.
- Returns:
The identifier (_id value) of the main document that was written.
- Return type:
bson.objectid.ObjectId