pygsti.forwardsims
pyGSTi Forward Simulators Python Package
Submodules
pygsti.forwardsims.distforwardsim
pygsti.forwardsims.forwardsim
pygsti.forwardsims.mapforwardsim
pygsti.forwardsims.mapforwardsim_calc_generic
pygsti.forwardsims.matrixforwardsim
pygsti.forwardsims.successfailfwdsim
pygsti.forwardsims.termforwardsim
pygsti.forwardsims.termforwardsim_calc_generic
pygsti.forwardsims.weakforwardsim
Package Contents
Classes
A calculator of circuit outcome probability calculations and their derivatives w.r.t. model parameters. 

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

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

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

Computes circuit outcome probabilities by multiplying together circuitlayer process matrices. 

A forwardsimulation calculator that uses termpathintegration to compute probabilities. 

A calculator of circuit outcome probabilities from a "weak" forward simulator 
 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 operationproduct calculations.
This functionality exists in a class separate from Model to allow for additional model classes (e.g. ones which use entirely different – nongatelocal – 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
 modelModel, optional
The model this forward simulator will use to compute circuit outcome probabilities.
 property model
 Castable
 classmethod cast(obj: ForwardSimulator, num_qubits=None)
num_qubits only used if obj == ‘auto’
 probs(circuit, outcomes=None, time=None, resource_alloc=None)
Construct a dictionary containing the outcome probabilities for a single circuit.
Parameters
 circuitCircuit or tuple of operation labels
The sequence of operation labels specifying the circuit.
 outcomeslist 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 nonzero outcome probabilities will be reported.
 timefloat, optional
The start time at which circuit is evaluated.
 resource_allocResourceAllocation, optional
The resources available for computing circuit outcome probabilities.
Returns
 probsOutcomeLabelDict
A dictionary with keys equal to outcome labels and values equal to probabilities. If no target outcomes provided, only nonzero probabilities will be reported.
 dprobs(circuit, resource_alloc=None)
Construct a dictionary containing outcome probability derivatives for a single circuit.
Parameters
 circuitCircuit or tuple of operation labels
The sequence of operation labels specifying the circuit.
 resource_allocResourceAllocation, optional
The resources available for computing circuit outcome probability derivatives.
Returns
 dprobsOutcomeLabelDict
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(circuit, resource_alloc=None)
Construct a dictionary containing outcome probability Hessians for a single circuit.
Parameters
 circuitCircuit or tuple of operation labels
The sequence of operation labels specifying the circuit.
 resource_allocResourceAllocation, optional
The resources available for computing circuit outcome probability Hessians.
Returns
 hprobsOutcomeLabelDict
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(circuits, dataset=None, resource_alloc=None, array_types=(), derivative_dimensions=None, verbosity=0)
Constructs an circuitoutcomeprobabilityarray (COPA) layout for circuits and dataset.
Parameters
 circuitslist
The circuits whose outcome probabilities should be computed.
 datasetDataSet
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_allocResourceAllocation
A available resources and allocation information. These factors influence how the layout (evaluation strategy) is constructed.
 array_typestuple, optional
A tuple of stringvalued array types, as given by
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 derivativecontaining 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_dimensionstuple, optional
A tuple containing, optionally, the parameterspace dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This should have minimally 1 or 2 elements when array_types contains ‘ep’ or ‘epp’ types, respectively. If array_types contains either of these strings and derivative_dimensions is None on input then we automatically set derivative_dimensions based on self.model.
 verbosityint or VerbosityPrinter
Determines how much output to send to stdout. 0 means no output, higher integers mean more output.
Returns
CircuitOutcomeProbabilityArrayLayout
 bulk_probs(circuits, clip_to=None, resource_alloc=None, smartc=None)
Construct a dictionary containing the probabilities for an entire list of circuits.
Parameters
 circuitslist of Circuits
The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayout
object containing precomputed quantities that make this function run faster. clip_to2tuple, optional
(min,max) to clip return value if not None.
 resource_allocResourceAllocation, optional
A resource allocation object describing the available resources and a strategy for partitioning them.
 smartcSmartCache, optional
A cache object to cache & use previously cached values inside this function.
Returns
 probsdictionary
A dictionary such that probs[circuit] is an ordered dictionary of outcome probabilities whose keys are outcome labels.
 bulk_dprobs(circuits, resource_alloc=None, smartc=None)
Construct a dictionary containing the probability derivatives for an entire list of circuits.
Parameters
 circuitslist of Circuits
The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayout
object containing precomputed quantities that make this function run faster. resource_allocResourceAllocation, optional
A resource allocation object describing the available resources and a strategy for partitioning them.
 smartcSmartCache, optional
A cache object to cache & use previously cached values inside this function.
Returns
 dprobsdictionary
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(circuits, resource_alloc=None, smartc=None)
Construct a dictionary containing the probability Hessians for an entire list of circuits.
Parameters
 circuitslist of Circuits
The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayout
object containing precomputed quantities that make this function run faster. resource_allocResourceAllocation, optional
A resource allocation object describing the available resources and a strategy for partitioning them.
 smartcSmartCache, optional
A cache object to cache & use previously cached values inside this function.
Returns
 hprobsdictionary
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(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_fillnumpy ndarray
an alreadyallocated 1D numpy array of length equal to the total number of computed elements (i.e. len(layout)).
 layoutCircuitOutcomeProbabilityArrayLayout
A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout()
.
Returns
None
 bulk_fill_dprobs(array_to_fill, layout, pr_array_to_fill=None)
Compute the outcome probabilityderivatives 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_fillnumpy ndarray
an alreadyallocated 2D numpy array of shape (len(layout), Np), where Np is the number of model parameters being differentiated with respect to.
 layoutCircuitOutcomeProbabilityArrayLayout
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_fillnumpy array, optional
when not None, an alreadyallocated lengthlen(layout) numpy array that is filled with probabilities, just as in
bulk_fill_probs()
.
Returns
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 probabilityHessians 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_fillnumpy ndarray
an alreadyallocated 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).
 layoutCircuitOutcomeProbabilityArrayLayout
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_fillnumpy array, optional
when not None, an alreadyallocated lengthlen(layout) numpy array that is filled with probabilities, just as in
bulk_fill_probs()
. deriv1_array_to_fillnumpy array, optional
when not None, an alreadyallocated 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_fillnumpy array, optional
when not None, an alreadyallocated 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).
Returns
None
 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 colums (a “rectangle”) at once. For example, the Hessian of a function of many circuit probabilities can often be computed rectanglebyrectangle and without the need to ever store the entire Hessian at once.
Parameters
 layoutCircuitOutcomeProbabilityArrayLayout
A layout for generated arrays, describing what circuit outcome each element corresponds to. Usually given by a prior call to
create_layout()
. wrt_slices_listlist
A list of (rowSlice,colSlice) 2tuples, 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_12boolean, optional
If true, the generator computes a 2tuple: (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 3tuple (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]
 class pygsti.forwardsims.SimpleMapForwardSimulator(model=None)
Bases:
pygsti.forwardsims.forwardsim.ForwardSimulator
A forward simulator that uses matrixvector 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 aMapForwardSimulator
object, and is mainly useful as a reference implementation and check for other simulators.
 class pygsti.forwardsims.MapForwardSimulator(model=None, max_cache_size=0, num_atoms=None, processor_grid=None, param_blk_sizes=None, derivative_eps=1e07, hessian_eps=1e05)
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 finitedifferences, and the prefix tables construbed by
MapCOPALayout
layout object are used to avoid duplicating (some) computation.Parameters
 modelModel, 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_sizeint, 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_atomsint, optional
The number of atoms (subprefixtables) 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_gridtuple optional
Specifies how the total number of processors should be divided into a number of atomprocessors, 1stparameterderivprocessors, and 2ndparameterderivprocessors. 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_sizestuple, optional
The parameter block sizes along the first or first & second parameter dimensions  so this can be a 0, 1 or 2tuple 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.
 create_layout(circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimensions=None, verbosity=0)
Constructs an circuitoutcomeprobabilityarray (COPA) layout for a list of circuits.
Parameters
 circuitslist
The circuits whose outcome probabilities should be included in the layout.
 datasetDataSet
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_allocResourceAllocation
A available resources and allocation information. These factors influence how the layout (evaluation strategy) is constructed.
 array_typestuple, optional
A tuple of stringvalued array types. See
ForwardSimulator.create_layout()
. derivative_dimensionsint or tuple[int], optional
Optionally, the parameterspace dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be nonNone when array_types contains ‘ep’ or ‘epp’ types. If a tuple, then must be length 1.
 verbosityint or VerbosityPrinter
Determines how much output to send to stdout. 0 means no output, higher integers mean more output.
Returns
MapCOPALayout
 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_fillnumpy ndarray
an alreadyallocated 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
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 chi2 contributions.
 min_prob_clip_for_weightingfloat, optional
Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1p)) by clipping probability p values to lie within the interval [ min_prob_clip_for_weighting, 1min_prob_clip_for_weighting ].
 prob_clip_interval2tuple 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(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_fillnumpy ndarray
an alreadyallocated 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.
 layoutCircuitOutcomeProbabilityArrayLayout
A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
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 chi2 contributions.
 min_prob_clip_for_weightingfloat, optional
Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1p)) by clipping probability p values to lie within the interval [ min_prob_clip_for_weighting, 1min_prob_clip_for_weighting ].
 prob_clip_interval2tuple or None, optional
(min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
 chi2_array_to_fillnumpy array, optional
when not None, an alreadyallocated lengthE numpy array that is filled with the percircuit chi2 contributions, just like in bulk_fill_timedep_chi2(…).
Returns
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 loglikelihood 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 alreadyallocated 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
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 loglikelihood. A penalty function replaces the true loglikelihood for probabilities that lie below this threshold so that the loglikelihood never becomes undefined (which improves optimizer performance).
 radiusfloat, optional
Specifies the severity of rounding used to “patch” the zerofrequency terms of the loglikelihood.
 prob_clip_interval2tuple 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(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”)loglikelihood 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_fillnumpy ndarray
an alreadyallocated 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.
 layoutCircuitOutcomeProbabilityArrayLayout
A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
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
a regularization parameter for the loglikelihood objective function.
 radiusfloat
a regularization parameter for the loglikelihood objective function.
 prob_clip_interval2tuple or None, optional
(min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
 logl_array_to_fillnumpy array, optional
when not None, an alreadyallocated lengthE numpy array that is filled with the percircuit logl contributions, just like in bulk_fill_timedep_loglpp(…) .
Returns
None
 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
 circuitCircuit or tuple of operation labels
The sequence of operation labels.
 scalebool, optional
When True, return a scaling factor (see below).
Returns
 productnumpy array
The product or scaled product of the operation matrices.
 scalefloat
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.
 class pygsti.forwardsims.SimpleMatrixForwardSimulator(model=None)
Bases:
pygsti.forwardsims.forwardsim.ForwardSimulator
A forward simulator that uses matrixmatrix 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 aMatrixForwardSimulator
object, and is mainly useful as a reference implementation and check for other simulators. 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
 circuitCircuit or tuple of operation labels
The sequence of operation labels.
 scalebool, optional
When True, return a scaling factor (see below).
Returns
 productnumpy array
The product or scaled product of the operation matrices.
 scalefloat
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.
 dproduct(circuit, flat=False, wrt_filter=None)
Compute the derivative of a specified sequence of operation labels.
Parameters
 circuitCircuit or tuple of operation labels
The sequence of operation labels.
 flatbool, optional
Affects the shape of the returned derivative array (see below).
 wrt_filterlist 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
 derivnumpy 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 ith 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 ith entry of the flattened product with respect to the jth model parameter.
 hproduct(circuit, flat=False, wrt_filter1=None, wrt_filter2=None)
Compute the hessian of a specified sequence of operation labels.
Parameters
 circuitCircuit or tuple of operation labels
The sequence of operation labels.
 flatbool, optional
Affects the shape of the returned derivative array (see below).
 wrt_filter1list 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 modelparameter index. This argument is used internally for distributing derivative calculations across multiple processors.
 wrt_filter2list 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 modelparameter index. This argument is used internally for distributing derivative calculations across multiple processors.
Returns
 hessiannumpy 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 jth then ith 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 ith entry of the flattened product with respect to the kth then kth model parameters.
 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 circuitlayer 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
 modelModel, 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_timestampbool, 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 timeindependent way, and the overall counts for each outcome are used. If support for intracircuit time dependence is needed, you must use a different forward simulator (e.g.
MapForwardSimulator
). num_atomsint, optional
The number of atoms (subevaluationtrees) 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_gridtuple optional
Specifies how the total number of processors should be divided into a number of atomprocessors, 1stparameterderivprocessors, and 2ndparameterderivprocessors. 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_sizestuple, optional
The parameter block sizes along the first or first & second parameter dimensions  so this can be a 0, 1 or 2tuple 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.
 create_layout(circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimensions=None, verbosity=0)
Constructs an circuitoutcomeprobabilityarray (COPA) layout for a list of circuits.
Parameters
 circuitslist
The circuits whose outcome probabilities should be included in the layout.
 datasetDataSet
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_allocResourceAllocation
A available resources and allocation information. These factors influence how the layout (evaluation strategy) is constructed.
 array_typestuple, optional
A tuple of stringvalued array types. See
ForwardSimulator.create_layout()
. derivative_dimensionsint or tuple[int], optional
Optionally, the parameterspace dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be nonNone when array_types contains ‘ep’ or ‘epp’ types. If a tuple, then must be length 1.
 verbosityint or VerbosityPrinter
Determines how much output to send to stdout. 0 means no output, higher integers mean more output.
Returns
MatrixCOPALayout
 bulk_product(circuits, scale=False, resource_alloc=None)
Compute the products of many circuits at once.
Parameters
 circuitslist of Circuits
The circuits to compute products for. These should not have any preparation or measurement layers.
 scalebool, optional
When True, return a scaling factor (see below).
 resource_allocResourceAllocation
Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.
Returns
 prodsnumpy 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).
 scaleValuesnumpy array
Only returned when scale == True. A lengthS array specifying the scaling that needs to be applied to the resulting products (final_product[i] = scaleValues[i] * prods[i]).
 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
 circuitslist of Circuits
The circuits to compute products for. These should not have any preparation or measurement layers.
 flatbool, optional
Affects the shape of the returned derivative array (see below).
 return_prodsbool, optional
when set to True, additionally return the probabilities.
 scalebool, optional
When True, return a scaling factor (see below).
 resource_allocResourceAllocation
Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.
 wrt_filterlist 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
 derivsnumpy 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 ith operation sequence product with respect to the jth 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 jth model parameter.
 productsnumpy array
Only returned when return_prods == True. An array of shape S x G x G; products[i] is the ith operation sequence product.
 scaleValsnumpy 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 ith operation sequence.
 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_fillnumpy ndarray
an alreadyallocated 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
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 chi2 contributions.
 min_prob_clip_for_weightingfloat, optional
Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1p)) by clipping probability p values to lie within the interval [ min_prob_clip_for_weighting, 1min_prob_clip_for_weighting ].
 prob_clip_interval2tuple 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(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_fillnumpy ndarray
an alreadyallocated 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.
 layoutCircuitOutcomeProbabilityArrayLayout
A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
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 chi2 contributions.
 min_prob_clip_for_weightingfloat, optional
Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1p)) by clipping probability p values to lie within the interval [ min_prob_clip_for_weighting, 1min_prob_clip_for_weighting ].
 prob_clip_interval2tuple or None, optional
(min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
 chi2_array_to_fillnumpy array, optional
when not None, an alreadyallocated lengthE numpy array that is filled with the percircuit chi2 contributions, just like in bulk_fill_timedep_chi2(…).
Returns
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 loglikelihood 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 alreadyallocated 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
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 loglikelihood. A penalty function replaces the true loglikelihood for probabilities that lie below this threshold so that the loglikelihood never becomes undefined (which improves optimizer performance).
 radiusfloat, optional
Specifies the severity of rounding used to “patch” the zerofrequency terms of the loglikelihood.
 prob_clip_interval2tuple 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(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”)loglikelihood 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_fillnumpy ndarray
an alreadyallocated 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.
 layoutCircuitOutcomeProbabilityArrayLayout
A layout for array_to_fill, describing what circuit outcome each element corresponds to. Usually given by a prior call to
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
a regularization parameter for the loglikelihood objective function.
 radiusfloat
a regularization parameter for the loglikelihood objective function.
 prob_clip_interval2tuple or None, optional
(min,max) values used to clip the predicted probabilities to. If None, no clipping is performed.
 logl_array_to_fillnumpy array, optional
when not None, an alreadyallocated lengthE numpy array that is filled with the percircuit 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 forwardsimulation calculator that uses termpathintegration to compute probabilities.
Parameters
 modelModel, 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{“taylororder”, “pruned”, “direct”}
Overall method used to compute (approximate) circuit probabilities. The “taylororder” mode includes all taylorexpansion terms up to a fixed and predefined 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_orderint
The maximum order of errorrate terms to include in probability computations. When polynomials are computed, the maximum Taylor order to compute polynomials to.
 desired_perrfloat, optional
The desired maximumerror when computing probabilities.. Path sets are selected (heuristically) to target this error, within the bounds set by max_order, etc.
 allowed_perrfloat, optional
The allowed maximumerror 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_magfloat, 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_outcomeint, 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 pathmagnitude gap (the maximum  achieved sumofpathmagnitudes, 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 pathmagnitude gap multiplied by a scaling factor is greater than allowed_perr. This scaling factor is equal to the computed probability divided by the achieved sumofpathmagnitudes 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 pathmagnitude gap.  “meanscaled” : a path set is deemed insufficient when, the mean of all the scaled (as above) pathmagnitude 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_stagesint, optional
The maximum number of “stage”, i.e. recomputations of a path set, are allowed before giving up.
 path_fraction_thresholdfloat, optional
When greater than this fraction of the total available paths (set by other constraints) are considered, no further recompuation of the path set will occur, as it is expected to give little improvement.
 oob_check_intervalint, optional
The optimizer will check whether the computed probabilities have sufficiently small error every oob_check_interval (outer) optimizer iteration.
 cachedict, optional
A dictionary of precomputed 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 aCircuit
. 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_atomsint, optional
The number of atoms (subtables) 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_gridtuple optional
Specifies how the total number of processors should be divided into a number of atomprocessors, 1stparameterderivprocessors, and 2ndparameterderivprocessors. 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_sizestuple, optional
The parameter block sizes along the first or first & second parameter dimensions  so this can be a 0, 1 or 2tuple 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.
 create_layout(circuits, dataset=None, resource_alloc=None, array_types=('E',), derivative_dimension=None, verbosity=0)
Constructs an circuitoutcomeprobabilityarray (COPA) layout for a list of circuits.
Parameters
 circuitslist
The circuits whose outcome probabilities should be included in the layout.
 datasetDataSet
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_allocResourceAllocation
A available resources and allocation information. These factors influence how the layout (evaluation strategy) is constructed.
 array_typestuple, optional
A tuple of stringvalued array types. See
ForwardSimulator.create_layout()
. derivative_dimensionint, optional
Optionally, the parameterspace dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This must be nonNone when array_types contains ‘ep’ or ‘epp’ types.
 verbosityint or VerbosityPrinter
Determines how much output to send to stdout. 0 means no output, higher integers mean more output.
Returns
TermCOPALayout
 find_minimal_paths_set(layout, exit_after_this_many_failures=0)
Find a good, i.e. minimal, path set for the current modelparameter space point.
Parameters
 layoutTermCOPALayout
The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.
 exit_after_this_many_failuresint, optional
If > 0, give up after this many circuits fail to meet the desired accuracy criteria. This shortcircuits doomed attempts to find a good path set so they don’t take too long.
Returns
TermPathSet
 bulk_test_if_paths_are_sufficient(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 (percircuti) pathmagnitude thresholds (stored in the evaluation tree) and the current parameterspace point (also reflected in the terms cached in the evaluation tree).
Parameters
 layoutTermCOPALayout
The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.
 probsnumpy.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 pathmagnitude gap.
 verbosityint or VerbosityPrinter, optional
An integer verbosity level or printer object for displaying messages.
Returns
bool
 bulk_sopm_gaps(layout)
Compute an element array sumofpathmagnitude gaps (the difference between maximum and achieved).
These values are computed for the current set of paths contained in eval_tree.
Parameters
 layoutTermCOPALayout
The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.
Returns
 numpy.ndarray
An array containing the percircuitoutcome sumofpathmagnitude gaps.
 bulk_sopm_gaps_jacobian(layout)
Compute the jacobian of the the output of
bulk_sopm_gaps()
.Parameters
 layoutTermCOPALayout
The layout specifiying the quantities (circuit outcome probabilities) to be computed, and related information.
 resource_allocResourceAllocation, optional
Available resources for this computation. Includes the number of processors (MPI comm) and memory limit.
Returns
 numpy.ndarray
An numberofelements by numberofmodelparameters array containing the jacobian of the sumofpathmagnitude gaps.
 class pygsti.forwardsims.WeakForwardSimulator(shots, model=None, base_seed=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.
Construct a new WeakForwardSimulator object.
Parameters
 shots: int
Number of times to run each circuit to obtain an approximate probability
 modelModel
Optional parent Model to be stored with the Simulator
 base_seed: int, optional
Base seed for RNG of probabilitic operations during circuit simulation. Incremented for every shot such that deterministic seeding behavior can be carried out with both serial or MPI execution. If not provided, falls back to using time.time() to get a valid seed.
 bulk_probs(circuits, clip_to=None, resource_alloc=None, smartc=None)
Construct a dictionary containing the probabilities for an entire list of circuits.
Parameters
 circuitslist of Circuits
The list of circuits. May also be a
CircuitOutcomeProbabilityArrayLayout
object containing precomputed quantities that make this function run faster. clip_to2tuple, optional
(min,max) to clip return value if not None.
 resource_allocResourceAllocation, optional
A resource allocation object describing the available resources and a strategy for partitioning them.
 smartcSmartCache, optional
A cache object to cache & use previously cached values inside this function.
Returns
 probsdictionary
A dictionary such that probs[circuit] is an ordered dictionary of outcome probabilities whose keys are outcome labels.