pygsti.forwardsims

pyGSTi Forward Simulators Python Package

Submodules

Package Contents

Classes

CHPForwardSimulator

A WeakForwardSimulator returning probabilities with Scott Aaronson's CHP code

ForwardSimulator

A calculator of circuit outcome probability calculations and their derivatives w.r.t. model parameters.

SimpleMapForwardSimulator

A forward simulator that uses matrix-vector products to compute circuit outcome probabilities.

MapForwardSimulator

Computes circuit outcome probabilities using circuit layer maps that act on a state.

SimpleMatrixForwardSimulator

A forward simulator that uses matrix-matrix products to compute circuit outcome probabilities.

MatrixForwardSimulator

Computes circuit outcome probabilities by multiplying together circuit-layer process matrices.

TermForwardSimulator

A forward-simulation calculator that uses term-path-integration to compute probabilities.

WeakForwardSimulator

A calculator of circuit outcome probabilities from a "weak" forward simulator

class pygsti.forwardsims.CHPForwardSimulator(chpexe, shots, model=None)

Bases: pygsti.forwardsims.weakforwardsim.WeakForwardSimulator

A WeakForwardSimulator returning probabilities with Scott Aaronson’s CHP code

_compute_circuit_outcome_for_shot(self, circuit, resource_alloc, time=None)

Compute outcome for a single shot of a circuit.

Parameters
  • spc_circuit (SeparatePOVMCircuit) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’) generated by Circuit.expand_instruments_and_separate_povm()

  • resource_alloc (ResourceAlloc) – Currently not used

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

Returns

outcome_label (tuple) – An outcome label for the single shot sampled

_process_state(self, rho, file_handle)

Helper function to process state prep for CHP circuits.

Recursively handles TensorProd > Composed > Computational SPAMVec objects (e.g. those created by create_crosstalk_free_model).

Parameters
  • rho (State) – State vector to process

  • file_handle (TextIOWrapper) – Open file handle for dumping CHP strings

_process_povm(self, povm, povm_label, file_handle)

Helper function to process measurement for CHP circuits.

Recursively handles TensorProd > Composed > ComputationalBasis POVM objects (e.g. those created by create_crosstalk_free_model).

Parameters
  • povm (POVM) – Unmarginalized POVM to process

  • povm_label (Label) – POVM label, which may include StateSpaceLabels that result in POVM marginalization

  • file_handle (TextIOWrapper) – Open file handle for dumping CHP strings

class pygsti.forwardsims.ForwardSimulator(model=None)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

A calculator of circuit outcome probability calculations and their derivatives w.r.t. model parameters.

Some forward simulators may also be used to perform operation-product calculations.

This functionality exists in a class separate from Model to allow for additional model classes (e.g. ones which use entirely different – non-gate-local – parameterizations of operation matrices and SPAM vectors) access to these fundamental operations. It also allows for the easier addition of new forward simulators.

Note: a model holds or “contains” a forward simulator instance to perform its computations, and a forward simulator holds a reference to its parent model, so we need to make sure the forward simulator doesn’t serialize the model or we have a circular reference.

Parameters

model (Model, optional) – The model this forward simulator will use to compute circuit outcome probabilities.

classmethod cast(cls, obj, num_qubits=None)

num_qubits only used if obj == ‘auto’

classmethod _array_types_for_method(cls, method_name)
_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
__getstate__(self)
property model(self)
_set_evotype(self, evotype)

Called when the evotype being used (defined by the parent model) changes. evotype will be None when the current model is None

abstract _compute_circuit_outcome_probabilities(self, array_to_fill, circuit, outcomes, resource_alloc, time=None)
abstract _compute_sparse_circuit_outcome_probabilities(self, circuit, resource_alloc, time=None)
abstract _compute_circuit_outcome_probability_derivatives(self, array_to_fill, circuit, outcomes, param_slice, resource_alloc)
probs(self, 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 (OutcomeLabelDict) – 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.

dprobs(self, 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 (OutcomeLabelDict) – 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.

hprobs(self, 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 (OutcomeLabelDict) – 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).

create_layout(self, circuits, dataset=None, resource_alloc=None, array_types=(), derivative_dimensions=None, verbosity=0)

Constructs an circuit-outcome-probability-array (COPA) layout for circuits and dataset.

Parameters
  • circuits (list) – The circuits whose outcome probabilities should be computed.

  • 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, as given by :method:`CircuitOutcomeProbabilityArrayLayout.allocate_local_array`. These types determine what types of arrays we anticipate computing using this layout (and forward simulator). These are used to check available memory against the limit (if it exists) within resource_alloc. The array types also determine the number of derivatives that this layout is able to compute. So, for example, if you ever want to compute derivatives or Hessians of element arrays then array_types must contain at least one ‘ep’ or ‘epp’ type, respectively or the layout will not allocate needed intermediate storage for derivative-containing types. If you don’t care about accurate memory limits, use (‘e’,) when you only ever compute probabilities and never their derivatives, and (‘e’,’ep’) or (‘e’,’ep’,’epp’) if you need to compute Jacobians or Hessians too.

  • derivative_dimensions (tuple, optional) – A tuple containing, optionally, the parameter-space dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be have minimally 1 or 2 elements when array_types contains ‘ep’ or ‘epp’ types, respectively.

  • verbosity (int or VerbosityPrinter) – Determines how much output to send to stdout. 0 means no output, higher integers mean more output.

Returns

CircuitOutcomeProbabilityArrayLayout

bulk_probs(self, 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 CircuitOutcomeProbabilityArrayLayout object 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 (dictionary) – A dictionary such that probs[circuit] is an ordered dictionary of outcome probabilities whose keys are outcome labels.

bulk_dprobs(self, 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 CircuitOutcomeProbabilityArrayLayout object 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 (dictionary) – A dictionary such that dprobs[circuit] is an ordered dictionary of derivative arrays (one element per differentiated parameter) whose keys are outcome labels

bulk_hprobs(self, 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 CircuitOutcomeProbabilityArrayLayout object 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 (dictionary) – 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

bulk_fill_probs(self, 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 :method:`create_layout`.

Returns

None

_bulk_fill_probs(self, array_to_fill, layout)
_bulk_fill_probs_block(self, array_to_fill, layout)
_bulk_fill_probs_at_times(self, array_to_fill, layout, times)
_bulk_fill_probs_block_at_times(self, array_to_fill, layout, times)
bulk_fill_dprobs(self, 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 :method:`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 :method:`bulk_fill_probs`.

Returns

None

_bulk_fill_dprobs(self, array_to_fill, layout, pr_array_to_fill)
_bulk_fill_dprobs_block(self, array_to_fill, dest_param_slice, layout, param_slice)
bulk_fill_hprobs(self, 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 :method:`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 :method:`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 :method:`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 :method:`bulk_fill_dprobs` (see array_to_fill for a definition of M2).

Returns

None

_bulk_fill_hprobs(self, array_to_fill, layout, pr_array_to_fill, deriv1_array_to_fill, deriv2_array_to_fill)
_bulk_fill_hprobs_block(self, array_to_fill, dest_param_slice1, dest_param_slice2, layout, param_slice1, param_slice2)
iter_hprobs_by_rectangle(self, 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 colums (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 :method:`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

rectangle_generator – 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]

_iter_hprobs_by_rectangle(self, layout, wrt_slices_list, return_dprobs_12)
__str__(self)

Return str(self).

class pygsti.forwardsims.SimpleMapForwardSimulator(model=None)

Bases: pygsti.forwardsims.forwardsim.ForwardSimulator

A forward simulator that uses matrix-vector products to compute circuit outcome probabilities.

This is “simple” in that it adds a minimal implementation to its ForwardSimulator base class. Because of this, it lacks some of the efficiency of a MapForwardSimulator object, and is mainly useful as a reference implementation and check for other simulators.

_compute_circuit_outcome_probabilities(self, array_to_fill, circuit, outcomes, resource_alloc, time=None)
_set_evotype(self, evotype)

Called when the evotype being used (defined by the parent model) changes. evotype will be None when the current model is None

__getstate__(self)
class pygsti.forwardsims.MapForwardSimulator(model=None, max_cache_size=0, num_atoms=None, processor_grid=None, param_blk_sizes=None)

Bases: pygsti.forwardsims.distforwardsim.DistributableForwardSimulator, SimpleMapForwardSimulator

Computes circuit outcome probabilities using circuit layer maps that act on a state.

Interfaces with a model via its circuit_layer_operator method and applies the resulting operators in order to propagate states and finally compute outcome probabilities. Derivatives are computed using finite-differences, and the prefix tables construbed by MapCOPALayout layout object are used to avoid duplicating (some) computation.

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.

  • max_cache_size (int, optional) – The maximum number of “prefix” quantum states that may be cached for performance (within the layout). If None, there is no limit to how large the cache may be.

  • num_atoms (int, optional) – The number of atoms (sub-prefix-tables) to use when creating the layout (i.e. when calling :method:`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.

classmethod _array_types_for_method(cls, method_name)
_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
copy(self)

Return a shallow copy of this MapForwardSimulator

Returns

MapForwardSimulator

create_layout(self, circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimension=None, verbosity=0)

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 :method:`ForwardSimulator.create_layout`.

  • derivative_dimension (int, optional) – Optionally, the parameter-space dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be non-None when array_types contains ‘ep’ or ‘epp’ types.

  • verbosity (int or VerbosityPrinter) – Determines how much output to send to stdout. 0 means no output, higher integers mean more output.

Returns

MapCOPALayout

_bulk_fill_probs_atom(self, array_to_fill, layout_atom, resource_alloc)
_bulk_fill_dprobs_atom(self, array_to_fill, dest_param_slice, layout_atom, param_slice, resource_alloc)
_bulk_fill_hprobs_atom(self, array_to_fill, dest_param_slice1, dest_param_slice2, layout_atom, param_slice1, param_slice2, resource_alloc)
_mapfill_hprobs_atom(self, array_to_fill, dest_indices, dest_param_indices1, dest_param_indices2, layout_atom, param_indices1, param_indices2, resource_alloc)

Helper function for populating hessian values by block.

bulk_fill_timedep_chi2(self, 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 :method:`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.

Returns

None

bulk_fill_timedep_dchi2(self, 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 :method:`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 :method:`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(…).

Returns

None

bulk_fill_timedep_loglpp(self, 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_fillnumpy ndarray

an already-allocated 1D numpy array of length equal to the total number of computed elements (i.e. layout.num_elements)

layoutCircuitOutcomeProbabilityArrayLayout

A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to :method:`create_layout`.

ds_circuitslist 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_outcomeslist 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.

datasetDataSet

the data set used to compute the logl contributions.

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

radiusfloat, optional

Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

prob_clip_interval2-tuple or None, optional

(min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.

Returns
None
bulk_fill_timedep_dloglpp(self, 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 :method:`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 :method:`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(…).

Returns

None

class pygsti.forwardsims.SimpleMatrixForwardSimulator(model=None)

Bases: pygsti.forwardsims.forwardsim.ForwardSimulator

A forward simulator that uses matrix-matrix products to compute circuit outcome probabilities.

This is “simple” in that it adds a minimal implementation to its ForwardSimulator base class. Because of this, it lacks some of the efficiency of a MatrixForwardSimulator object, and is mainly useful as a reference implementation and check for other simulators.

product(self, 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.

_rho_es_from_spam_tuples(self, rholabel, elabels)
_process_wrt_filter(self, wrt_filter, obj)

Helper function for doperation and hoperation below: pulls out pieces of a wrt_filter argument relevant for a single object (gate or spam vec)

_doperation(self, op_label, flat=False, wrt_filter=None)

Return the derivative of a length-1 (single-gate) sequence

_hoperation(self, op_label, flat=False, wrt_filter1=None, wrt_filter2=None)

Return the hessian of a length-1 (single-gate) sequence

dproduct(self, 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 (numpy array) –

  • 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.

hproduct(self, 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 (numpy array) –

  • 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.

_compute_circuit_outcome_probabilities(self, array_to_fill, circuit, outcomes, resource_alloc, time=None)

Compute probabilities of a multiple “outcomes” for a single circuit.

The outcomes correspond to circuit sandwiched between rholabel (a state preparation) and the multiple effect labels in elabels.

Parameters
  • rholabel (Label) – The state preparation label.

  • elabels (list) – A list of Label objects giving the simplified effect labels.

  • circuit (Circuit or tuple) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’)

  • use_scaling (bool, optional) – Whether to use a post-scaled product internally. If False, this routine will run slightly faster, but with a chance that the product will overflow and the subsequent trace operation will yield nan as the returned probability.

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

Returns

numpy.ndarray – An array of floating-point probabilities, corresponding to the elements of elabels.

class pygsti.forwardsims.MatrixForwardSimulator(model=None, distribute_by_timestamp=False, num_atoms=None, processor_grid=None, param_blk_sizes=None)

Bases: pygsti.forwardsims.distforwardsim.DistributableForwardSimulator, SimpleMatrixForwardSimulator

Computes 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 MatrixCOPALayout layout 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 infomation (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 :method:`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.

classmethod _array_types_for_method(cls, method_name)
_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
copy(self)

Return a shallow copy of this MatrixForwardSimulator

Returns

MatrixForwardSimulator

_compute_product_cache(self, layout_atom_tree, resource_alloc)

Computes an array of operation sequence products (process matrices).

Note: will not parallelize computation: parallelization should be done at a higher level.

_compute_dproduct_cache(self, layout_atom_tree, prod_cache, scale_cache, resource_alloc=None, wrt_slice=None, profiler=None)

Computes a tree of product derivatives in a linear cache space. Will use derivative columns to parallelize computation.

_compute_hproduct_cache(self, layout_atom_tree, prod_cache, d_prod_cache1, d_prod_cache2, scale_cache, resource_alloc=None, wrt_slice1=None, wrt_slice2=None)

Computes a tree of product 2nd derivatives in a linear cache space. Will use derivative rows and columns to parallelize computation.

create_layout(self, circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimension=None, verbosity=0)

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 :method:`ForwardSimulator.create_layout`.

  • derivative_dimension (int, optional) – Optionally, the parameter-space dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be non-None when array_types contains ‘ep’ or ‘epp’ types.

  • verbosity (int or VerbosityPrinter) – Determines how much output to send to stdout. 0 means no output, higher integers mean more output.

Returns

MatrixCOPALayout

_scale_exp(self, scale_exps)
_rho_e_from_spam_tuple(self, spam_tuple)
_probs_from_rho_e(self, rho, e, gs, scale_vals)
_dprobs_from_rho_e(self, spam_tuple, rho, e, gs, d_gs, scale_vals, wrt_slice=None)
_hprobs_from_rho_e(self, spam_tuple, rho, e, gs, d_gs1, d_gs2, h_gs, scale_vals, wrt_slice1=None, wrt_slice2=None)
_bulk_fill_probs_atom(self, array_to_fill, layout_atom, resource_alloc)
_bulk_fill_dprobs_atom(self, array_to_fill, dest_param_slice, layout_atom, param_slice, resource_alloc)
_bulk_fill_hprobs_atom(self, array_to_fill, dest_param_slice1, dest_param_slice2, layout_atom, param_slice1, param_slice2, resource_alloc)
bulk_product(self, 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]).

bulk_dproduct(self, 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.

_ds_quantities(self, timestamp, ds_cache, layout, dataset, TIMETOL=1e-06)
_bulk_fill_timedep_objfn(self, raw_objective, array_to_fill, layout, ds_circuits, num_total_outcomes, dataset, ds_cache=None)
_bulk_fill_timedep_dobjfn(self, raw_objective, array_to_fill, layout, ds_circuits, num_total_outcomes, dataset, ds_cache=None)
bulk_fill_timedep_chi2(self, 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 :method:`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.

Returns

None

bulk_fill_timedep_dchi2(self, 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 :method:`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 :method:`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(…).

Returns

None

bulk_fill_timedep_loglpp(self, 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_fillnumpy ndarray

an already-allocated 1D numpy array of length equal to the total number of computed elements (i.e. layout.num_elements)

layoutCircuitOutcomeProbabilityArrayLayout

A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to :method:`create_layout`.

ds_circuitslist 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_outcomeslist 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.

datasetDataSet

the data set used to compute the logl contributions.

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

radiusfloat, optional

Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

prob_clip_interval2-tuple or None, optional

(min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.

Returns
None
bulk_fill_timedep_dloglpp(self, 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 :method:`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 :method:`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(…).

Returns

None

class pygsti.forwardsims.TermForwardSimulator(model=None, mode='pruned', max_order=3, desired_perr=0.01, allowed_perr=0.1, min_term_mag=None, max_paths_per_outcome=1000, perr_heuristic='none', max_term_stages=5, path_fraction_threshold=0.9, oob_check_interval=10, cache=None, num_atoms=None, processor_grid=None, param_blk_sizes=None)

Bases: pygsti.forwardsims.distforwardsim.DistributableForwardSimulator

A forward-simulation calculator that uses term-path-integration to compute probabilities.

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.

  • mode ({"taylor-order", "pruned", "direct"}) – Overall method used to compute (approximate) circuit probabilities. The “taylor-order” mode includes all taylor-expansion terms up to a fixed and pre-defined order, fixing a single “path set” at the outset. The “pruned” mode selects a path set based on a heuristic (sometimes a true upper bound) calculation of the error in the approximate probabilities. This method effectively “prunes” the paths to meet a fixed desired accuracy. The “direct” method is still under development. Its intention is to perform path integrals directly without the use of polynomial computation and caching. Initial testing showed the direct method to be much slower for common QCVV tasks, making it less urgent to complete.

  • max_order (int) – The maximum order of error-rate terms to include in probability computations. When polynomials are computed, the maximum Taylor order to compute polynomials to.

  • desired_perr (float, optional) – The desired maximum-error when computing probabilities.. Path sets are selected (heuristically) to target this error, within the bounds set by max_order, etc.

  • allowed_perr (float, optional) – The allowed maximum-error when computing probabilities. When rigorous bounds cannot guarantee that probabilities are correct to within this error, additional paths are added to the path set.

  • min_term_mag (float, optional) – Terms with magnitudes less than this value will be ignored, i.e. not considered candidates for inclusion in paths. If this number is too low, the number of possible paths to consder may be very large, impacting performance. If too high, then not enough paths will be considered to achieve an accurate result. By default this value is set automatically based on the desired error and max_paths_per_outcome. Only adjust this if you know what you’re doing.

  • max_paths_per_outcome (int, optional) – The maximum number of paths that can be used (summed) to compute a single outcome probability.

  • perr_heuristic ({"none", "scaled", "meanscaled"}) – Which heuristic (if any) to use when deciding whether a given path set is sufficient given the allowed error (allowed_perr). - “none”: This is the strictest setting, and is absence of any heuristic. if the path-magnitude gap (the maximum - achieved sum-of-path-magnitudes, a rigorous upper bound on the approximation error for a circuit outcome probability) is greater than allowed_perr for any circuit, the path set is deemed insufficient. - “scaled”: a path set is deemed insufficient when, for any circuit, the path-magnitude gap multiplied by a scaling factor is greater than allowed_perr. This scaling factor is equal to the computed probability divided by the achieved sum-of-path-magnitudes and is always less than 1. This scaling is essentially the ratio of the sum of the path amplitudes without and with an absolute value, and tries to quantify and offset the degree of pessimism in the computed path-magnitude gap. - “meanscaled” : a path set is deemed insufficient when, the mean of all the scaled (as above) path-magnitude gaps is greater than allowed_perr. The mean here is thus over the circuit outcomes. This heuristic is even more permissive of potentially bad path sets than “scaled”, as it allows badly approximated circuits to be offset by well approximated ones.

  • max_term_stages (int, optional) – The maximum number of “stage”, i.e. re-computations of a path set, are allowed before giving up.

  • path_fraction_threshold (float, optional) – When greater than this fraction of the total available paths (set by other constraints) are considered, no further re-compuation of the path set will occur, as it is expected to give little improvement.

  • oob_check_interval (int, optional) – The optimizer will check whether the computed probabilities have sufficiently small error every oob_check_interval (outer) optimizer iteration.

  • cache (dict, optional) – A dictionary of pre-computed compact polynomial objects. Keys are (max_order, rholabel, elabel, circuit) tuples, where max_order is an integer, rholabel and elabel are Label objects, and circuit is a Circuit. Computed values are added to any dictionary that is supplied, so supplying an empty dictionary and using this calculator will cause the dictionary to be filled with values.

  • num_atoms (int, optional) – The number of atoms (sub-tables) to use when creating the layout (i.e. when calling :method:`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.

classmethod _array_types_for_method(cls, method_name)
_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
_set_evotype(self, evotype)

Called when the evotype being used (defined by the parent model) changes. evotype will be None when the current model is None

__getstate__(self)
copy(self)

Return a shallow copy of this TermForwardSimulator.

Returns

TermForwardSimulator

create_layout(self, circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimension=None, verbosity=0)

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 :method:`ForwardSimulator.create_layout`.

  • derivative_dimension (int, optional) – Optionally, the parameter-space dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be non-None when array_types contains ‘ep’ or ‘epp’ types.

  • verbosity (int or VerbosityPrinter) – Determines how much output to send to stdout. 0 means no output, higher integers mean more output.

Returns

TermCOPALayout

_bulk_fill_probs_atom(self, array_to_fill, layout_atom, resource_alloc)
_bulk_fill_dprobs_atom(self, array_to_fill, dest_param_slice, layout_atom, param_slice, resource_alloc)
_bulk_fill_hprobs_atom(self, array_to_fill, dest_param_slice1, dest_param_slice2, layout_atom, param_slice1, param_slice2, resource_alloc)
_compute_pruned_pathmag_threshold(self, rholabel, elabels, circuit, polynomial_vindices_per_int, repcache, circuitsetup_cache, resource_alloc, threshold_guess=None)

Finds a good path-magnitude threshold for circuit at the current parameter-space point.

Parameters
  • rholabel (Label) – The state preparation label.

  • elabels (list) – A list of Label objects giving the simplified effect labels.

  • circuit (Circuit or tuple) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’)

  • polynomial_vindices_per_int (int) – The number of variable indices that can fit into a single platform-width integer (can be computed from number of model params, but passed in for performance).

  • repcache (dict, optional) – Dictionaries used to cache operator representations to speed up future calls to this function that would use the same set of operations.

  • circuitsetup_cache (dict) – A cache holding specialized elements that store and eliminate the need to recompute per-circuit information.

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

  • threshold_guess (float, optional) – A guess estimate of a good path-magnitude threshold.

Returns

  • npaths (int) – The number of paths found. (total over all circuit outcomes)

  • threshold (float) – The final path-magnitude threshold used.

  • target_sopm (float) – The target (desired) sum-of-path-magnitudes. (summed over all circuit outcomes)

  • achieved_sopm (float) – The achieved sum-of-path-magnitudes. (summed over all circuit outcomes)

_find_minimal_paths_set_atom(self, layout_atom, resource_alloc, exit_after_this_many_failures=0)

Find the minimal (smallest) path set that achieves the desired accuracy conditions.

Parameters
  • layout_atom (_TermCOPALayoutAtom) – The probability array layout containing the circuits to find a path-set for.

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

  • exit_after_this_many_failures (int, optional) – If > 0, give up after this many circuits fail to meet the desired accuracy criteria. This short-circuits doomed attempts to find a good path set so they don’t take too long.

Returns

TermPathSetAtom

find_minimal_paths_set(self, layout, exit_after_this_many_failures=0)

Find a good, i.e. minimal, path set for the current model-parameter space point.

Parameters
  • layout (TermCOPALayout) – The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.

  • exit_after_this_many_failures (int, optional) – If > 0, give up after this many circuits fail to meet the desired accuracy criteria. This short-circuits doomed attempts to find a good path set so they don’t take too long.

Returns

TermPathSet

_circuit_achieved_and_max_sopm(self, rholabel, elabels, circuit, repcache, threshold)

Computes the achieved and maximum sum-of-path-magnitudes for circuit.

Parameters
  • rholabel (Label) – The state preparation label.

  • elabels (list) – A list of Label objects giving the simplified effect labels.

  • circuit (Circuit or tuple) – A tuple-like object of simplified gates.

  • repcache (dict, optional) – Dictionaries used to cache operator representations to speed up future calls to this function that would use the same set of operations.

  • threshold (float) – path-magnitude threshold. Only sum path magnitudes above or equal to this threshold.

Returns

  • achieved_sopm (float) – The achieved sum-of-path-magnitudes. (summed over all circuit outcomes)

  • max_sopm (float) – The maximum possible sum-of-path-magnitudes. (summed over all circuit outcomes)

_achieved_and_max_sopm_atom(self, layout_atom)

Compute the achieved and maximum possible sum-of-path-magnitudes for a single layout atom.

This gives a sense of how accurately the current path set is able to compute probabilities.

Parameters

layout_atom (_TermCOPALayoutAtom) – The probability array layout specifying the circuits and outcomes.

Returns

numpy.ndarray

_bulk_fill_achieved_and_max_sopm(self, achieved_sopm, max_sopm, layout)

Compute element arrays of achieved and maximum-possible sum-of-path-magnitudes.

These values are computed for the current set of paths contained in eval_tree.

Parameters
  • achieved_sopm (numpy.ndarray) – An array containing the per-circuit-outcome achieved sum-of-path-magnitudes.

  • max_sopm (numpy.ndarray) – An array containing the per-circuit-outcome maximum sum-of-path-magnitudes.

  • layout (TermCOPALayout) – The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.

Returns

None

bulk_test_if_paths_are_sufficient(self, layout, probs, verbosity=0)

Determine whether layout’s current path set (perhaps heuristically) achieves the desired accuracy.

The current path set is determined by the current (per-circuti) path-magnitude thresholds (stored in the evaluation tree) and the current parameter-space point (also reflected in the terms cached in the evaluation tree).

Parameters
  • layout (TermCOPALayout) – The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.

  • probs (numpy.ndarray) – The element array of (approximate) circuit outcome probabilities. This is needed because some heuristics take into account an probability’s value when computing an acceptable path-magnitude gap.

  • verbosity (int or VerbosityPrinter, optional) – An integer verbosity level or printer object for displaying messages.

Returns

bool

bulk_sopm_gaps(self, layout)

Compute an element array sum-of-path-magnitude gaps (the difference between maximum and achieved).

These values are computed for the current set of paths contained in eval_tree.

Parameters

layout (TermCOPALayout) – The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.

Returns

numpy.ndarray – An array containing the per-circuit-outcome sum-of-path-magnitude gaps.

_achieved_and_max_sopm_jacobian_atom(self, layout_atom)

Compute the jacobian of the achieved and maximum possible sum-of-path-magnitudes for a single layout atom.

Parameters

layout_atom (_TermCOPALayoutAtom) – The probability array layout specifying the circuits and outcomes.

Returns

  • achieved_sopm_jacobian (numpy.ndarray) – The jacobian of the achieved sum-of-path-magnitudes.

  • max_sopm_jacobian (numpy.ndarray) – The jacobian of the maximum possible sum-of-path-magnitudes.

_sopm_gaps_jacobian_atom(self, layout_atom)

Compute the jacobian of the (maximum-possible - achieved) sum-of-path-magnitudes for a single layout atom.

Parameters

layout_atom (_TermCOPALayoutAtom) – The probability array layout.

Returns

numpy.ndarray – The jacobian of the sum-of-path-magnitudes gap.

bulk_sopm_gaps_jacobian(self, layout)

Compute the jacobian of the the output of :method:`bulk_sopm_gaps`.

Parameters
  • layout (TermCOPALayout) – The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.

  • resource_alloc (ResourceAllocation, optional) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

Returns

numpy.ndarray – An number-of-elements by number-of-model-parameters array containing the jacobian of the sum-of-path-magnitude gaps.

_prs_as_pruned_polynomial_reps(self, threshold, rholabel, elabels, circuit, polynomial_vindices_per_int, repcache, circuitsetup_cache, resource_alloc, mode='normal')

Computes polynomial-representations of circuit-outcome probabilities.

In particular, the circuit-outcomes under consideration share the same state preparation and differ only in their POVM effects. Employs a truncated or pruned path-integral approach, as opposed to just including everything up to some Taylor order as in :method:`_prs_as_polynomials`.

Parameters
  • threshold (float) – The path-magnitude threshold. Only include (sum) paths whose magnitudes are greater than or equal to this threshold.

  • rholabel (Label) – The state preparation label.

  • elabels (list) – A list of Label objects giving the simplified effect labels.

  • circuit (Circuit or tuple) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’)

  • polynomial_vindices_per_int (int) – The number of variable indices that can fit into a single platform-width integer (can be computed from number of model params, but passed in for performance).

  • repcache (dict, optional) – Dictionaries used to cache operator representations to speed up future calls to this function that would use the same set of operations.

  • circuitsetup_cache (dict) – A cache holding specialized elements that store and eliminate the need to recompute per-circuit information.

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

  • mode ({"normal", "achieved_sopm"}) – Controls whether polynomials are actually computed (“normal”) or whether only the achieved sum-of-path-magnitudes is computed (“achieved_sopm”). The latter mode is useful when a threshold is being tested but not committed to, as computing only the achieved sum-of-path-magnitudes is significantly faster.

Returns

list – A list of PolynomialRep objects. These polynomial represetations are essentially bare-bones polynomials stored efficiently for performance. (To get a full Polynomial object, use :classmethod:`Polynomial.from_rep`.)

_select_paths_set_atom(self, layout_atom, pathset, resource_alloc)

Selects (makes “current”) a path set and computes polynomials the new set for a single layout atom.

This routine updates the information held in layout_atom. After this call, layout_atom.pathset == pathset.

Parameters
  • layout_atom (_TermCOPALayoutAtom) – The probability array layout whose path-set is being set.

  • pathset (PathSet) – The path set to select.

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

Returns

None

_prs_as_polynomials(self, rholabel, elabels, circuit, polynomial_vindices_per_int, resource_alloc, fastmode=True)

Computes polynomial-representations of circuit-outcome probabilities.

In particular, the circuit-outcomes under consideration share the same state preparation and differ only in their POVM effects.

Parameters
  • rholabel (Label) – The state preparation label.

  • elabels (list) – A list of Label objects giving the simplified effect labels.

  • circuit (Circuit or tuple) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’)

  • polynomial_vindices_per_int (int) – The number of variable indices that can fit into a single platform-width integer (can be computed from number of model params, but passed in for performance).

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

  • fastmode (bool, optional) – Whether to use a faster and slightly more memory-hungry implementation for computing the polynomial terms. (Usually best to leave this as True).

Returns

list – A list of Polynomial objects.

_prs_as_compact_polynomials(self, rholabel, elabels, circuit, polynomial_vindices_per_int, resource_alloc)

Compute compact-form polynomials of the outcome probabilities for circuit.

Note that these outcomes are defined as having the same state preparation and different POVM effects.

Parameters
  • rholabel (Label) – The state preparation label.

  • elabels (list) – A list of Label objects giving the simplified effect labels.

  • circuit (Circuit or tuple) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’)

  • polynomial_vindices_per_int (int) – The number of variable indices that can fit into a single platform-width integer (can be computed from number of model params, but passed in for performance).

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

Returns

list – A list of Polynomial objects.

_cache_p_polynomials(self, layout_atom, resource_alloc, polynomial_vindices_per_int)

Compute and cache the compact-form polynomials that evaluate the probabilities of a single layout atom.

These polynomials corresponding to all this tree’s operation sequences sandwiched between each state preparation and effect. The result is cached to speed up subsequent calls.

Parameters
  • layout_atom (_TermCOPALayoutAtom) – The probability array layout containing the circuits to compute polynomials for.

  • resource_alloc (ResourceAllocation) – Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.

  • polynomial_vindices_per_int (int) – The number of variable indices that can fit into a single platform-width integer (can be computed from number of model params, but passed in for performance).

Returns

None

select_paths_set(self, layout, path_set)

Selects (makes “current”) a path set and computes polynomials the new set.

Parameters
  • layout (TermCOPALayout) – The layout whose path-set should be set.

  • path_set (PathSet) – The path set to select.

Returns

None

_prepare_layout(self, layout, polynomial_vindices_per_int)

Performs preparatory work for computing circuit outcome probabilities.

Finds a good path set that meets (if possible) the accuracy requirements and computes needed polynomials.

Parameters
  • layout (TermCOPALayout) – The layout to prepare.

  • polynomial_vindices_per_int (int) – The number of variable indices that can fit into a single platform-width integer (can be computed from number of model params, but passed in for performance).

Returns

None

class pygsti.forwardsims.WeakForwardSimulator(shots, model=None)

Bases: pygsti.forwardsims.forwardsim.ForwardSimulator

A calculator of circuit outcome probabilities from a “weak” forward simulator (i.e. probabilites taken as average frequencies over a number of “shots”).

Due to their ability to only sample outcome probabilities, WeakForwardSimulators rely heavily on implementing the _compute_sparse_circuit_outcome_probabilities function of ForwardSimulators.

abstract _compute_circuit_outcome_for_shot(self, spc_circuit, resource_alloc, time=None)

Compute outcome for a single shot of a circuit.

Parameters
  • spc_circuit (SeparatePOVMCircuit) – A tuple-like object of simplified gates (e.g. may include instrument elements like ‘Imyinst_0’) generated by Circuit.expand_instruments_and_separate_povm()

  • resource_alloc (ResourceAlloc) – Currently not used

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

Returns

outcome_label (tuple) – An outcome label for the single shot sampled

_compute_sparse_circuit_outcome_probabilities(self, circuit, resource_alloc, time=None)
_compute_circuit_outcome_probabilities(self, array_to_fill, circuit, outcomes, resource_alloc, time=None)
bulk_probs(self, 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 CircuitOutcomeProbabilityArrayLayout object 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 (dictionary) – A dictionary such that probs[circuit] is an ordered dictionary of outcome probabilities whose keys are outcome labels.