pygsti.forwardsims.termforwardsim

Defines the TermForwardSimulator calculator class

Module Contents

Classes

TermForwardSimulator

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

_TermPathSetBase

A set of error-term paths.

_AtomicTermPathSet

A path set, as specified for each atom of a TermCOPALayout.

TermPathSet

A path set for a split TermEvalTree.

class pygsti.forwardsims.termforwardsim.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.termforwardsim._TermPathSetBase(npaths, maxpaths, nfailed)

Bases: object

A set of error-term paths.

Each such path is comprised of a single “term” (usually a Taylor term of an error-generator expansion) for each gate operation or circuit layer (more generally, each factor within the product that evaluates to the probability).

A set of paths is specified by giving a path-magnitude threshold for each circuit in a COPA layout. All paths with magnitude less than this threshold are a part of the path set. The term magnitudes that determine a path magnitude are held in Term objects resulting from a Model at a particular parameter-space point. Representations of these term objects (actually just the “high-magnitude” ones, as determined by a different, term-magnitude, threshold) are also held within the path set.

Parameters
  • npaths (int) – The number of total paths.

  • maxpaths (int) – The maximum-allowed-paths limit that was in place when this path set was created.

  • nfailed (int) – The number of circuits that failed to meet the desired accuracy (path-magnitude gap) requirements.

property allowed_path_fraction(self)

The fraction of maximal allowed paths that are in this path set.

Returns

float

class pygsti.forwardsims.termforwardsim._AtomicTermPathSet(thresholds, highmag_termrep_cache, circuitsetup_cache, npaths, maxpaths, nfailed)

Bases: _TermPathSetBase

A path set, as specified for each atom of a TermCOPALayout.

Parameters
  • thresholds (dict) – A dictionary whose keys are circuits and values are path-magnitude thresholds. These thresholds store what

  • highmag_termrep_cache (dict) – A dictionary whose keys are gate or circuit-layer labels and whose values are internally-used “rep-cache” elements that each hold a list of the term representations for that gate having a “high” magnitude (magnitude above some threshold). This cache is an essential link between the path-magnitude thresholds in thresholds and the actual set of paths that are evaluated by processing layout_atom (e.g. updating this cache by re-computing term magnitudes at a new parameter-space point will also update the set of paths that are evaluated given the same set of thresholds).

  • circuitsetup_cache (dict) – A dictionary that caches per-circuit setup information and can be used to speed up multiple calls which use the same circuits.

  • npaths (int) – The number of total paths.

  • maxpaths (int) – The maximum-allowed-paths limit that was in place when this path set was created.

  • nfailed (int) – The number of circuits that failed to meet the desired accuracy (path-magnitude gap) requirements.

class pygsti.forwardsims.termforwardsim.TermPathSet(local_atom_pathsets, comm)

Bases: _TermPathSetBase

A path set for a split TermEvalTree.

Parameters
  • local_atom_pathsets (list) – A list of path sets for each of the local layout atom (i.e. the atoms assigned to the current processor).

  • comm (mpi4py.MPI.Comm) – When not None, an MPI communicator for distributing the computation across multiple processors.