pygsti.protocols

Sub-package containing protocol objects and related inputs, data, and results

Submodules

Package Contents

Classes

_Circuit

A quantum circuit.

_FreeformDataSet

An association between Circuits and arbitrary data.

FreeformDataSimulator

Computes arbitrary functions of the state data simulator that also computes user-defined functions

ModelFreeformSimulator

A base class for data simulators that utilize models (probably most of them!).

_DummyProfiler

A dummy profiler that doesn't do anything.

_NicelySerializable

The base class for all "nicely serializable" objects in pyGSTi.

_Estimate

A class encapsulating the Model objects related to a single GST estimate up-to-gauge freedoms.

_ModelTest

A protocol that tests how well a model agrees with a given set of data.

_QubitProcessorSpec

The device specification for a one or more qubit quantum computer.

_Model

A predictive model for a Quantum Information Processor (QIP).

_GaugeGroup

A parameterized set (ideally a group) of gauge transformations.

_GaugeGroupElement

The element of a GaugeGroup, which represents a single gauge transformation.

_CircuitList

A unmutable list (a tuple) of Circuit objects and associated metadata.

_ResourceAllocation

Describes available resources and how they should be allocated.

HasProcessorSpec

Adds to an experiment design a processor_spec attribute

GateSetTomographyDesign

Minimal experiment design needed for GST

StandardGSTDesign

Standard GST experiment design consisting of germ-powers sandwiched between fiducials.

GSTInitialModel

Specification of a starting point for GST.

GSTBadFitOptions

Options for post-processing a GST fit that was unsatisfactory.

GSTObjFnBuilders

Holds the objective-function builders needed for long-sequence GST.

GSTGaugeOptSuite

Holds directives to perform one or more gauge optimizations on a model.

GateSetTomography

The core gate set tomography protocol, which optimizes a parameterized model to (best) fit a data set.

LinearGateSetTomography

The linear gate set tomography protocol.

StandardGST

The standard-practice GST protocol.

ModelEstimateResults

A results object that holds model estimates.

_DummyProfiler

A dummy profiler that doesn't do anything.

_ModelDatasetCircuitStore

Contains all the information that we'd like to persist when performing

_Estimate

A class encapsulating the Model objects related to a single GST estimate up-to-gauge freedoms.

_CircuitList

A unmutable list (a tuple) of Circuit objects and associated metadata.

_ResourceAllocation

Describes available resources and how they should be allocated.

ModelTest

A protocol that tests how well a model agrees with a given set of data.

_TreeNode

A base class for representing an object that lives "at" a filesystem directory.

_NamedDict

A dictionary that also holds category names and types.

Protocol

An analysis routine that is run on experimental data. A generalized notion of a QCVV protocol.

MultiPassProtocol

Runs a (contained) Protocol on all the passes of a multi-pass ProtocolData.

ProtocolRunner

Used to run :class:`Protocol`(s) on an entire tree of data

TreeRunner

Runs specific protocols on specific data-tree paths.

SimpleRunner

Runs a single protocol on every data node that has no sub-nodes (possibly separately for each pass).

DefaultRunner

Run the default protocol at each data-tree node.

ExperimentDesign

An experimental-design specification for one or more QCVV protocols.

CircuitListsDesign

Experiment design specification that is comprised of multiple circuit lists.

CombinedExperimentDesign

An experiment design that combines the specifications of one or more "sub-designs".

SimultaneousExperimentDesign

An experiment design whose circuits are the tensor-products of the circuits from one or more sub-designs.

FreeformDesign

Experiment design holding an arbitrary circuit list and meta data.

ProtocolData

Represents the experimental data needed to run one or more QCVV protocols.

ProtocolResults

Stores the results from running a QCVV protocol on data.

MultiPassResults

Holds the results of a single protocol on multiple "passes" (sets of data, typically taken at different times).

ProtocolResultsDir

Holds a dictionary of ProtocolResults objects.

ProtocolPostProcessor

Similar to a protocol, but runs on an existing ProtocolResults object.

DataSimulator

An analysis routine that is run on an experiment design to produce per-circuit data.

DataCountsSimulator

Simulates data counts for each circuit outcome, producing a simulated data set.

CliffordRBDesign

Experiment design for Clifford randomized benchmarking.

DirectRBDesign

Experiment design for Direct randomized benchmarking.

MirrorRBDesign

Experiment design for mirror randomized benchmarking.

RandomizedBenchmarking

The randomized benchmarking protocol.

RandomizedBenchmarkingResults

The results of running randomized benchmarking.

_RobustPhaseEstimation

Runs the non-adaptive RPE algorithm.

RobustPhaseEstimationDesign

Experimental design for robust phase estimation (RPE).

RobustPhaseEstimation

Robust phase estimation (RPE) protocol

RobustPhaseEstimationResults

Results from the RPE protocol

StabilityAnalysisDesign

Experimental design for stability analysis.

StabilityAnalysis

Stability Analysis protocol

StabilityAnalysisResults

Results from the stability analysis protocol.

_SuccessFailModel

An op-less model that always outputs 2 (success & failure) probabilities for each circuit.

ByDepthDesign

Experiment design that holds circuits organized by depth.

BenchmarkingDesign

Experiment design that holds benchmarking data.

PeriodicMirrorCircuitDesign

Experiment design for periodic mirror-circuit benchmarking.

SummaryStatistics

A protocol that can construct "summary" quantities from raw data.

ByDepthSummaryStatistics

A protocol that computes summary statistics for data organized into by-depth circuit lists.

SummaryStatisticsResults

Summary statistics computed for a set of data.

VBDataFrame

A class for storing a DataFrame that contains volumetric benchmarking data, and that

Functions

_load_pspec(processorspec_filename_or_obj)

_load_model(model_filename_or_obj)

_load_pspec_or_model(processorspec_or_model_filename_or_obj)

_load_fiducials_and_germs(prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, germ_list_or_filename)

_load_dataset(data_filename_or_set, comm, verbosity)

Loads a DataSet from the data_filename_or_set argument of functions in this module.

_add_gaugeopt_and_badfit(results, estlbl, target_model, gaugeopt_suite, unreliable_ops, badfit_options, optimizer, resource_alloc, printer)

_add_gauge_opt(results, base_est_label, gaugeopt_suite, starting_model, unreliable_ops, comm=None, verbosity=0)

Add a gauge optimization to an estimate.

_add_badfit_estimates(results, base_estimate_label, badfit_options, optimizer=None, resource_alloc=None, verbosity=0)

Add any and all "bad fit" estimates to results.

_compute_robust_scaling(scale_typ, objfn_cache, mdc_objfn)

Get the per-circuit data scaling ("weights") for a given type of robust-data-scaling.

_compute_wildcard_budget(objfn_cache, mdc_objfn, parameters, badfit_options, verbosity)

Create a wildcard budget for a model estimate.

_reoptimize_with_weights(mdc_objfn, circuit_weights_dict, optimizer, verbosity)

Re-optimize a model after data counts have been scaled by circuit weights.

_process_dataframe(df, pivot_valuename, pivot_value, drop_columns, preserve_order=False)

See to_dataframe docstrings for argument descriptions.

run_default_protocols(data, memlimit=None, comm=None)

Run the default protocols for the data-tree rooted at data.

_convert_nameddict_attributes(obj)

A helper function that converts the elements of the "_nameddict_attributes"

_calculate_summary_statistic(x, statistic, lower_cutoff=None)

Utility function that returns statistic(x), or the maximum

polarization_to_success_probability(p, n)

Inverse of success_probability_to_polarization.

success_probability_to_polarization(s, n)

Maps a success probablity s for an n-qubit circuit to

classify_circuit_shape(success_probabilities, total_counts, threshold, significance=0.05)

Utility function for computing "capability regions", as introduced in "Measuring the

Attributes

ROBUST_SUFFIX_LIST

DEFAULT_BAD_FIT_THRESHOLD

GSTDesign

GST

LGST

RB

RBResults

RPEDesign

RPE

RPEResults

class pygsti.protocols._Circuit(layer_labels=(), line_labels='auto', num_lines=None, editable=False, stringrep=None, name='', check=True, expand_subcircuits='default', occurrence=None, compilable_layer_indices=None)

Bases: object

A quantum circuit.

A Circuit represents a quantum circuit, consisting of state preparation, gates, and measurement operations. It is composed of some number of “lines”, typically one per qubit, and stores the operations on these lines as a sequence of Label objects, one per circuit layer, whose .sslbls members indicate which line(s) the label belongs on. When a circuit is created with ‘editable=True’, a rich set of operations may be used to construct the circuit in place, after which done_editing() should be called so that the Circuit can be properly hashed as needed.

Parameters
  • layer_labels (iterable of Labels or str) –

    This argument provides a list of the layer labels specifying the state preparations, gates, and measurements for the circuit. This argument can also be a Circuit or a string, in which case it is parsed as a text-formatted circuit. Internally this will eventually be converted to a list of Label objects, one per layer, but it may be specified using anything that can be readily converted to a Label objects. For example, any of the following are allowed:

    • [‘Gx’,’Gx’] : X gate on each of 2 layers

    • `[Label(‘Gx’),Label(‘Gx’)] : same as above

    • [(‘Gx’,0),(‘Gy’,0)] : X then Y on qubit 0 (2 layers)

    • [[(‘Gx’,0),(‘Gx’,1)],[(‘Gy’,0),(‘Gy’,1)]] : parallel X then Y on qubits 0 & 1

  • line_labels (iterable, optional) – The (string valued) label for each circuit line. If ‘auto’, then line_labels is taken to be the list of all state-space labels present within layer_labels. If there are no such labels (e.g. if layer_labels contains just gate names like (‘Gx’,’Gy’)), then the special value ‘*’ is used as a single line label.

  • num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines-1.

  • editable (bool, optional) – Whether the created Circuit is created in able to be modified. If True, then you should call done_editing() once the circuit is completely assembled, as this makes the circuit read-only and allows it to be hashed.

  • stringrep (string, optional) – A string representation for the circuit. If None (the default), then this will be generated automatically when needed. One reason you’d want to specify this is if you know of a nice compact string representation that you’d rather use, e.g. “Gx^4” instead of the automatically generated “GxGxGxGx”. If you want to initialize a Circuit entirely from a string representation you can either specify the string in as layer_labels or set layer_labels to None and stringrep to any valid (one-line) circuit string.

  • name (str, optional) – A name for this circuit (useful if/when used as a block within larger circuits).

  • check (bool, optional) – Whether stringrep should be checked against layer_labels to ensure they are consistent, and whether the labels in layer_labels are a subset of line_labels. The only reason you’d want to set this to False is if you’re absolutely sure stringrep and line_labels are consistent and want to save computation time.

  • expand_subcircuits (bool or "default") – If “default”, then the value of Circuit.default_expand_subcircuits is used. If True, then any sub-circuits (e.g. anything exponentiated like “(GxGy)^4”) will be expanded when it is stored within the created Circuit. If False, then such sub-circuits will be left as-is. It’s typically more robust to expand sub-circuits as this facilitates comparison (e.g. so “GxGx” == “Gx^2”), but in cases when you have massive exponents (e.g. “Gx^8192”) it may improve performance to set expand_subcircuits=False.

  • occurrence (hashable, optional) – A value to set as the “occurrence id” for this circuit. This value doesn’t affect the circuit an any way except by affecting it’s hashing and equivalence testing. Circuits with different occurrence ids are not equivalent. Occurrence values effectively allow multiple copies of the same ciruit to be stored in a dictionary or DataSet.

  • compilable_layer_indices (tuple, optional) – The circuit-layer indices that may be internally altered (but retaining the same target operation) and/or combined with the following circuit layer by a hardware compiler.when executing this circuit. Layers that are not “compilable” are effectively followed by a barrier which prevents the hardward compiler from restructuring the circuit across the layer boundary.

default_expand_subcircuits

By default, expand sub-circuit labels.

Type

bool

line_labels

The line labels (often qubit labels) of this circuit.

Type

tuple

layertup

This Circuit’s layers as a standard Python tuple of layer Labels.

Type

tuple

tup

This Circuit as a standard Python tuple of layer Labels and line labels.

Type

tuple

str

The Python string representation of this Circuit.

Type

str

default_expand_subcircuits = True
classmethod cast(cls, obj)

Convert obj into a Circuit.

Parameters

obj (object) – Object to convert

Returns

Circuit

classmethod from_tuple(cls, tup)

Creates a Circuit from a tuple

Parameters

tup (tuple) – The tuple to convert.

Returns

Circuit

classmethod _fastinit(cls, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)
_bare_init(self, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)
to_label(self, nreps=1)

Construct and return this entire circuit as a CircuitLabel.

Note: occurrence-id information is not stored in a circuit label, so circuits that differ only in their occurence_id will return circuit labels that are equal.

Parameters

nreps (int, optional) – The number of times this circuit will be repeated (CircuitLabels support exponentiation and you can specify this here).

Returns

CircuitLabel

property line_labels(self)

The line labels (often qubit labels) of this circuit.

property name(self)

The name of this circuit.

Note: the name is not a part of the hashed value. The name is used to name the CircuitLabel returned from :method:`to_label`.

property occurrence(self)

The occurrence id of this circuit.

property layertup(self)

This Circuit’s layers as a standard Python tuple of layer Labels.

Returns

tuple

property tup(self)

This Circuit as a standard Python tuple of layer Labels and line labels.

Returns

tuple

property compilable_layer_indices(self)

Tuple of the layer indices corresponding to “compilable” layers.

property compilable_by_layer(self)

Boolean array indicating whether each layer is “compilable” or not.

property str(self)

The Python string representation of this Circuit.

Returns

str

property layerstr(self)

Just the string representation of the circuit layers (no ‘@<line_labels>’ suffix)

property linesstr(self)

Just the string representation of the circuit’s line labels (the ‘@<line_labels>’ suffix)

_labels_lines_str(self)

Split the string representation up into layer-labels & line-labels parts

__hash__(self)

Return hash(self).

__len__(self)
__iter__(self)
__contains__(self, x)

Note: this is not covered by __iter__ for case of contained CircuitLabels

__radd__(self, x)
__add__(self, x)
repeat(self, ntimes, expand='default')

Repeat this circuit ntimes times.

Parameters
  • ntimes (int) – Number of repetitions.

  • expand (bool or "default", optional) – When False, the returned circuit will contain a CircuitLabel encapsulating the repetitions without explicitly storing them. When True, the returned circuit will be expanded into the ntimes repetitions. “default” means to use the value in the class variable Circuit.default_expand_subcircuits.

__mul__(self, x)
__pow__(self, x)
__eq__(self, x)

Return self==value.

__lt__(self, x)

Return self<value.

__gt__(self, x)

Return self>value.

property num_lines(self)

The number of lines in this circuit.

Returns

int

copy(self, editable='auto')

Returns a copy of the circuit.

Parameters

editable ({True,False,"auto"}) – Whether returned copy is editable. If “auto” is given, then the copy is editable if and only if this Circuit is.

Returns

Circuit

clear(self)

Removes all the gates in a circuit (preserving the number of lines).

Returns

None

_proc_layers_arg(self, layers)

Pre-process the layers argument used by many methods

_proc_lines_arg(self, lines)

Pre-process the lines argument used by many methods

_proc_key_arg(self, key)

Pre-process the key argument used by many methods

_layer_components(self, ilayer)

Get the components of the ilayer-th layer as a list/tuple.

_remove_layer_component(self, ilayer, indx)

Removes the indx-th component from the ilayer-th layer

_append_layer_component(self, ilayer, val)

Add val to the ilayer-th layer

_replace_layer_component(self, ilayer, indx, val)
extract_labels(self, layers=None, lines=None, strict=True)

Get a subregion - a “rectangle” - of this Circuit.

This can be used to select multiple layers and/or lines of this Circuit. The strict argument controls whether gates need to be entirely within the given rectangle or can be intersecting it. If layers is a single integer then a Label is returned (representing a layer or a part of a layer), otherwise a Circuit is returned.

Parameters
  • layers (int, slice, or list/tuple of ints) – Which layers to select (the horizontal dimension of the selection rectangle). Layers are always selected by index, and this argument can be a single (integer) index - in which case a Label is returned - or multiple indices as given by a slice or list - in which case a Circuit is returned. Note that, even though we speak of a “rectangle”, layer indices do not need to be contiguous. The special value None selects all layers.

  • lines (str/int, slice, or list/tuple of strs/ints) – Which lines to select (the vertical dimension of the selection rectangle). Lines are selected by their line-labels (elements of the circuit’s .line_labels property), which can be strings and/or integers. A single or multiple line-labels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to select multiple of them. Note that line-labels do not need to be contiguous. The special value None selects all lines.

  • strict (bool, optional) – When True, only gates lying completely within the selected region are included in the return value. If a gate straddles the region boundary (e.g. if we select just line 1 and the circuit contains “Gcnot:1:2”) then it is silently not-included in the returned label or circuit. If False, then gates which straddle the region boundary are included. Note that this may result in a Label or Circuit containing more line labels than where requested in the call to extract_labels(…)..

Returns

Label or Circuit – The requested portion of this circuit, given as a Label if layers is a single integer and as a Circuit otherwise. Note: if you want a Circuit when only selecting one layer, set layers to a slice or tuple containing just a single index.

set_labels(self, lbls, layers=None, lines=None)

Write lbls to the block defined by the layers and lines arguments.

Note that lbls can be anything interpretable as a Label or list of labels.

Parameters
  • lbls (Label, list/tuple of Labels, or Circuit) – When layers is a single integer, lbls should be a single “layer label” of type Label. Otherwise, lbls should be a list or tuple of Label objects with length equal to the number of layers being set. A Circuit may also be used in this case.

  • layers (int, slice, or list/tuple of ints) – Which layers to set (the horizontal dimension of the destination rectangle). Layers are always selected by index, and this argument can be a single (integer) index or multiple indices as given by a slice or list. Note that these indices do not need to be contiguous. The special value None stands for all layers.

  • lines (str/int, slice, or list/tuple of strs/ints) – Which lines to set (the vertical dimension of the destination rectangle). Lines are selected by their line-labels, which can be strings and/or integers. A single or multiple line-labels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to specify multiple of them. The line-labels do not need to be contiguous. The special value None stands for all lines, and in this case new lines will be created if there are new state-space labels in lbls (when lines is not None an error is raised instead).

Returns

None

insert_idling_layers(self, insert_before, num_to_insert, lines=None)

Inserts into this circuit one or more idling (blank) layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • num_to_insert (int) – The number of new layers to insert.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

Circuit

insert_idling_layers_inplace(self, insert_before, num_to_insert, lines=None)

Inserts into this circuit one or more idling (blank) layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • num_to_insert (int) – The number of new layers to insert.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

None

_append_idling_layers_inplace(self, num_to_insert, lines=None)

Adds one or more idling (blank) layers to the end of this circuit.

By default, complete layer(s) are appended. The lines argument allows you to add partial layers (on only a subset of the lines).

Parameters
  • num_to_insert (int) – The number of new layers to append.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

None

insert_labels_into_layers(self, lbls, layer_to_insert_before, lines=None)

Inserts into this circuit the contents of lbls into new full or partial layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.

Returns

Circuit

insert_labels_into_layers_inplace(self, lbls, layer_to_insert_before, lines=None)

Inserts into this circuit the contents of lbls into new full or partial layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.

Returns

None

insert_idling_lines(self, insert_before, line_labels)

Insert one or more idling (blank) lines into this circuit.

Parameters
  • insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.

  • line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

Circuit

insert_idling_lines_inplace(self, insert_before, line_labels)

Insert one or more idling (blank) lines into this circuit.

Parameters
  • insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.

  • line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

None

_append_idling_lines(self, line_labels)

Add one or more idling (blank) lines onto the bottom of this circuit.

Parameters

line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

None

insert_labels_as_lines_inplace(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')

Inserts into this circuit the contents of lbls into new lines.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.

Returns

None

insert_labels_as_lines(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')

Inserts into this circuit the contents of lbls into new lines.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.

Returns

None

_append_labels_as_lines(self, lbls, layer_to_insert_before=None, line_labels='auto')

Adds the contents of lbls as new lines at the bottom of this circuit.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to append as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being added. If “auto”, then these are inferred from lbls.

Returns

None

_clear_labels(self, layers, lines, clear_straddlers=False)

remove all labels in a block given by layers and lines Note: layers & lines must be lists/tuples of values; they can’t be slices or single vals

clear_labels(self, layers=None, lines=None, clear_straddlers=False)

Removes all the gates within the given circuit region. Does not reduce the number of layers or lines.

Parameters
  • layers (int, slice, or list/tuple of ints) – Defines the horizontal dimension of the region to clear. See :method:`extract_labels` for details.

  • lines (str/int, slice, or list/tuple of strs/ints) – Defines the vertical dimension of the region to clear. See :method:`extract_labels` for details.

  • clear_straddlers (bool, optional) – Whether or not gates which straddle cleared and non-cleared lines should be cleared. If False and straddling gates exist, an error will be raised.

Returns

None

delete_layers(self, layers=None)

Deletes one or more layers from the circuit.

Parameters

layers (int, slice, or list/tuple of ints) – The layer index or indices to delete. See :method:`extract_labels` for details.

Returns

None

delete_lines(self, lines, delete_straddlers=False)

Deletes one or more lines from the circuit.

Parameters
  • lines (str/int, slice, or list/tuple of strs/ints) – The line label(s) to delete. See :method:`extract_labels` for details.

  • delete_straddlers (bool, optional) – Whether or not gates which straddle deleted and non-deleted lines should be removed. If False and straddling gates exist, an error will be raised.

Returns

None

__getitem__(self, key)
__setitem__(self, key, val)
__delitem__(self, key)
to_pythonstr(self, op_labels)

Convert this circuit to an “encoded” python string.

In the returned string each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This can be useful for processing operation sequences using python’s string tools (regex in particular).

Parameters

op_labels (tuple) – An iterable containing at least all the layer-Labels that appear in this Circuit, and which will be mapped to alphabet characters, beginning with ‘A’.

Returns

string – The converted operation sequence.

Examples

(‘Gx’,’Gx’,’Gy’,’Gx’) => “AABA”

classmethod from_pythonstr(cls, python_string, op_labels)

Decode an “encoded string” into a Circuit.

Create a Circuit from a python string where each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This performs the inverse of :method:`to_pythonstr`.

Parameters
  • python_string (string) – string whose individual characters correspond to the operation labels of a operation sequence.

  • op_labels (tuple) – tuple containing all the operation labels that will be mapped from alphabet characters, beginning with ‘A’.

Returns

Circuit

Examples

“AABA” => (‘Gx’,’Gx’,’Gy’,’Gx’)

serialize(self)

Serialize the parallel gate operations of this Circuit.

Construct a new Circuit whereby all layers containing multiple gates are converted to separate single-gate layers, effectively putting each elementary gate operation into its own layer. Ordering is dictated by the ordering of the compound layer labels.

Returns

Circuit

parallelize(self, can_break_labels=True, adjacent_only=False)

Compress a circuit’s gates by performing them in parallel.

Construct a circuit with the same underlying labels as this one, but with as many gates performed in parallel as possible (with some restrictions - see the Parameters section below). Generally, gates are moved as far left (toward the start) of the circuit as possible.

Parameters
  • can_break_labels (bool, optional) – Whether compound (parallel-gate) labels in this Circuit can be separated during the parallelization process. For example, if can_break_labels=True then “Gx:0[Gy:0Gy:1]” => “[Gx:0Gy:1]Gy:0” whereas if can_break_labels=False the result would remain “Gx:0[Gy:0Gy:1]” because [Gy:0Gy:1] cannot be separated.

  • adjacent_only (bool, optional) – It True, then operation labels are only allowed to move into an adjacent label, that is, they cannot move “through” other operation labels. For example, if adjacent_only=True then “Gx:0Gy:0Gy:1” => “Gx:0[Gy:0Gy:1]” whereas if adjacent_only=False the result would be “[Gx:0Gy:1]Gy:0. Setting this to True is sometimes useful if you want to parallelize a serial string in such a way that subsequently calling .serialize() will give you back the original string.

Returns

Circuit

expand_subcircuits_inplace(self)

Expands all CircuitLabel labels within this circuit.

This operation is done in place and so can only be performed on an editable Circuit.

Returns

None

expand_subcircuits(self)

Returns a new circuit with CircuitLabel labels expanded.

Returns

Circuit

factorize_repetitions_inplace(self)

Attempt to replace repeated sub-circuits with CircuitLabel objects.

More or less the reverse of :method:`expand_subcircuits`, this method attempts to collapse repetitions of the same labels into single CircuitLabel labels within this circuit.

This operation is done in place and so can only be performed on an editable Circuit.

Returns

None

insert_layer(self, circuit_layer, j)

Inserts a single layer into a circuit.

The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.

Parameters
  • circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.

  • j (int) – The layer index (depth) at which to insert the circuit_layer.

Returns

Circuit

insert_layer_inplace(self, circuit_layer, j)

Inserts a single layer into a circuit.

The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.

Parameters
  • circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.

  • j (int) – The layer index (depth) at which to insert the circuit_layer.

Returns

None

insert_circuit(self, circuit, j)

Inserts a circuit into this circuit.

The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all non-idling qubits must be a subset of the labels of this circuit.

Parameters
  • circuit (Circuit) – The circuit to be inserted.

  • j (int) – The layer index (depth) at which to insert the circuit.

Returns

Circuit

insert_circuit_inplace(self, circuit, j)

Inserts a circuit into this circuit.

The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all non-idling qubits must be a subset of the labels of this circuit.

Parameters
  • circuit (Circuit) – The circuit to be inserted.

  • j (int) – The layer index (depth) at which to insert the circuit.

Returns

None

append_circuit(self, circuit)

Append a circuit to the end of this circuit.

This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be appended.

Returns

Circuit

append_circuit_inplace(self, circuit)

Append a circuit to the end of this circuit.

This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be appended.

Returns

None

prefix_circuit(self, circuit)

Prefix a circuit to the beginning of this circuit.

This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be prefixed.

Returns

Circuit

prefix_circuit_inplace(self, circuit)

Prefix a circuit to the beginning of this circuit.

This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be prefixed.

Returns

None

tensor_circuit_inplace(self, circuit, line_order=None)

The tensor product of this circuit and circuit.

That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.

Parameters
  • circuit (A Circuit object) – The circuit to be tensored.

  • line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.

Returns

None

tensor_circuit(self, circuit, line_order=None)

The tensor product of this circuit and circuit.

That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.

Parameters
  • circuit (A Circuit object) – The circuit to be tensored.

  • line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.

Returns

Circuit

replace_layer_with_circuit_inplace(self, circuit, j)

Replaces the j-th layer of this circuit with circuit.

Parameters
  • circuit (Circuit) – The circuit to insert

  • j (int) – The layer index to replace.

Returns

None

replace_layer_with_circuit(self, circuit, j)

Replaces the j-th layer of this circuit with circuit.

Parameters
  • circuit (Circuit) – The circuit to insert

  • j (int) – The layer index to replace.

Returns

Circuit

replace_gatename_inplace(self, old_gatename, new_gatename)

Changes the name of a gate throughout this Circuit.

Note that the name is only a part of the label identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.

Parameters
  • old_gatename (str) – The gate name to replace.

  • new_gatename (str) – The name to replace old_gatename with.

Returns

None

replace_gatename(self, old_gatename, new_gatename)

Returns a copy of this Circuit except that old_gatename is changed to new_gatename.

Note that the “name” is only a part of the “label” identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.

Parameters
  • old_gatename (str) – The gate name to replace.

  • new_gatename (str) – The name to replace old_gatename with.

Returns

Circuit

replace_gatename_with_idle_inplace(self, gatename)

Treats a given gatename as an idle gate throughout this Circuit.

This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.

Parameters

gatename (str) – The gate name to replace.

Returns

None

replace_gatename_with_idle(self, gatename)

Returns a copy of this Circuit with a given gatename treated as an idle gate.

This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.

Parameters

gatename (str) – The gate name to replace.

Returns

Circuit

replace_layer(self, old_layer, new_layer)

Returns a copy of this Circuit except that old_layer is changed to new_layer.

Parameters
  • old_layer (str or Label) – The layer to find.

  • new_layer (str or Label) – The layer to replace found layers with.

Returns

Circuit

replace_layers_with_aliases(self, alias_dict)

Performs a find and replace using layer aliases.

Returns a copy of this Circuit except that it’s layers that match keys of alias_dict are replaced with the corresponding values.

Parameters

alias_dict (dict) – A dictionary whose keys are layer Labels (or equivalent tuples or strings), and whose values are Circuits.

Returns

Circuit

change_gate_library(self, compilation, allowed_filter=None, allow_unchanged_gates=False, depth_compression=True, one_q_gate_relations=None)

Re-express a circuit over a different model.

Parameters
  • compilation (dict or CompilationLibrary.) –

    If a dictionary, the keys are some or all of the gates that appear in the circuit, and the values are replacement circuits that are normally compilations for each of these gates (if they are not, the action of the circuit will be changed). The circuits need not be on all of the qubits, and need only satisfy the requirements of the insert_circuit method. There must be a key for every gate except the self.identity gate, unless allow_unchanged_gates is False. In that case, gate that aren’t a key in this dictionary are left unchanged.

    If a CompilationLibrary, this will be queried via the retrieve_compilation_of() method to find compilations for all of the gates in the circuit. So this CompilationLibrary must contain or be able to auto-generate compilations for the requested gates, except when allow_unchanged_gates is True. In that case, gates that a compilation is not returned for are left unchanged.

  • allowed_filter (dict or set, optional) – Specifies which gates are allowed to be used when generating compilations from compilation. Can only be not None if compilation is a CompilationLibrary. If a dict, keys must be gate names (like “Gcnot”) and values QubitGraph objects indicating where that gate (if it’s present in the library) may be used. If a set, then it specifies a set of qubits and any gate in the current library that is confined within that set is allowed. If None, then all gates within the library are allowed.

  • allow_unchanged_gates (bool, optional) – Whether to allow some gates to remain unchanged, and therefore to be absent from compilation. When True such gates are left alone; when False an error is raised if any such gates are encountered.

  • depth_compression (bool, optional) – Whether to perform depth compression after changing the gate library. If one_q_gate_relations is None this will only remove idle layers and compress the circuit by moving everything as far forward as is possible without knowledge of the action of any gates other than self.identity. See the depth_compression method for more details. Under most circumstances this should be true; if it is False changing gate library will often result in a massive increase in circuit depth.

  • one_q_gate_relations (dict, optional) – Gate relations for the one-qubit gates in the new gate library, that are used in the depth compression, to cancel / combine gates. E.g., one key-value pair might be (‘Gh’,’Gh’) : ‘I’, to signify that two Hadamards c ompose to the idle gate ‘Gi’. See the depth_compression() method for more details.

Returns

None

map_names_inplace(self, mapper)

The names of all of the simple labels are updated in-place according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing gate name values and whose values are the new names (strings) or a function which takes a single (existing name) argument and returns a new name.

Returns

None

map_state_space_labels_inplace(self, mapper)

The labels of all of the lines (wires/qubits) are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing line-label) argument and returns a new line-label.

Returns

None

map_state_space_labels(self, mapper)

Creates a new Circuit whose line labels are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing line-label) argument and returns a new line-label.

Returns

Circuit

reorder_lines_inplace(self, order)

Reorders the lines (wires/qubits) of the circuit.

Note that the ordering of the lines is unimportant for most purposes.

Parameters

order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.

Returns

None

reorder_lines(self, order)

Reorders the lines (wires/qubits) of the circuit.

Note that the ordering of the lines is unimportant for most purposes.

Parameters

order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.

Returns

Circuit

_is_line_idling(self, line_label, idle_layer_labels=None)

Whether the line in question is idling in every circuit layer.

Parameters
  • line_label (str or int) – The label of the line (i.e., “wire” or qubit).

  • idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

bool – True if the line is idling. False otherwise.

idling_lines(self, idle_layer_labels=None)

Returns the line labels corresponding to idling lines.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

tuple

delete_idling_lines_inplace(self, idle_layer_labels=None)

Removes from this circuit all lines that are idling at every layer.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

None

delete_idling_lines(self, idle_layer_labels=None)

Removes from this circuit all lines that are idling at every layer.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

Circuit

replace_with_idling_line_inplace(self, line_label, clear_straddlers=True)

Converts the specified line to an idling line, by removing all its gates.

If there are any multi-qubit gates acting on this line, this function will raise an error when clear_straddlers=False.

Parameters
  • line_label (str or int) – The label of the line to convert to an idling line.

  • clear_straddlers (bool, optional) – Whether or not gates which straddle the line_label should also be cleared. If False and straddling gates exist, an error will be raised.

Returns

None

reverse_inplace(self)

Reverses the order of the circuit.

Returns

None

_combine_one_q_gates_inplace(self, one_q_gate_relations)

Compresses sequences of 1-qubit gates in the circuit, using the provided gate relations.

One of the steps of the depth_compression() method, and in most cases that method will be more useful.

Parameters

one_q_gate_relations (dict) –

Keys that are pairs of strings, corresponding to 1-qubit gate names, with values that are a single string, also corresponding to a 1-qubit gate name. Whenever a 1-qubit gate with name name1 is followed in the circuit by a 1-qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 -> name3 and name2 -> self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1-qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1-qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) -> name12, (name12,name3) -> name123 etc then the entire sequence of 1-qubit gates will be compressed into a single possibly non-idle 1-qubit gate followed by idle gates in place of the previous 1-qubit gates. Note that None can be used as name3 to signify that the result is the identity (no gate labels).

If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and auto-generated) one_q_gate_relations.

Note that this function will not compress sequences of 1-qubit gates that cannot be compressed by independently inspecting sequential non-idle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) -> Gypi, even though the sequence is the identity).

Returns

bool – False if the circuit is unchanged, and True otherwise.

_shift_gates_forward_inplace(self)

Shift all gates forward (left) as far as is possible.

This operation is performed without any knowledge of what any of the gates are. One of the steps of :method:`depth_compression()`.

Returns

bool – False if the circuit is unchanged, and True otherwise.

delete_idle_layers_inplace(self)

Deletes all layers in this circuit that contain no gate operations.

One of the steps of the depth_compression() method.

Returns

bool – False if the circuit is unchanged, and True otherwise.

compress_depth_inplace(self, one_q_gate_relations=None, verbosity=0)

Compresses the depth of this circuit using very simple re-write rules.

  1. If one_q_gate_relations is provided, all sequences of 1-qubit gates in the circuit are compressed as far as is possible using only the pair-wise combination rules provided by this dict (see below).

  2. All gates are shifted forwarded as far as is possible without any knowledge of what any of the gates are.

  3. All idle-only layers are deleted.

Parameters
  • one_q_gate_relations (dict) –

    Keys that are pairs of strings, corresponding to 1-qubit gate names, with values that are a single string, also corresponding to a 1-qubit gate name. Whenever a 1-qubit gate with name name1 is followed in the circuit by a 1-qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 -> name3 and name2 -> self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1-qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1-qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) -> name12, (name12,name3) -> name123 etc then the entire sequence of 1-qubit gates will be compressed into a single possibly non-idle 1-qubit gate followed by idle gates in place of the previous 1-qubit gates.

    If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and auto-generated) one_q_gate_relations.

    Note that this function will not compress sequences of 1-qubit gates that cannot be compressed by independently inspecting sequential non-idle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) -> Gypi, even though the sequence is the identity).

  • verbosity (int, optional) – If > 0, information about the depth compression is printed to screen.

Returns

None

layer(self, j)

Returns a tuple of the components, i.e. the (non-identity) gates, in the layer at depth j.

These are the .components of the Label returned by indexing this Circuit (using square brackets) with j, i.e. this returns this_circuit[j].components.

Parameters

j (int) – The index (depth) of the layer to be returned

Returns

tuple

layer_label(self, j)

Returns the layer, as a Label, at depth j.

This label contains as components all the (non-identity) gates in the layer..

Parameters

j (int) – The index (depth) of the layer to be returned

Returns

Label

layer_with_idles(self, j, idle_gate_name='I')

Returns a tuple of the components of the layer at depth j, with idle_gate_name at empty circuit locations.

This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.

Parameters
  • j (int) – The index (depth) of the layer to be returned

  • idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a Label.

Returns

tuple

layer_label_with_idles(self, j, idle_gate_name='I')

Returns the layer, as a Label, at depth j, with idle_gate_name at empty circuit locations.

This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.

Parameters
  • j (int) – The index (depth) of the layer to be returned

  • idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a Label.

Returns

Label

property num_layers(self)

The number of circuit layers.

In simple circuits, this is the same as the depth (given by :method:`depth`). For circuits containing sub-circuit blocks, this gives the number of top-level layers in this circuit.

Returns

int

property depth(self)

The circuit depth.

This is the number of layers in simple circuits. For circuits containing sub-circuit blocks, this includes the full depth of these blocks. If you just want the number of top-level layers, use :method:`num_layers`.

Returns

int

property width(self)

The circuit width.

This is the number of qubits on which the circuit acts. This includes qubits that only idle, but are included as part of the circuit according to self.line_labels.

Returns

int

property size(self)

Returns the circuit size.

This is the sum of the sizes of all the gates in the circuit. A gate that acts on n-qubits has a size of n, with the exception of the idle which has a size of 0. Hence, the circuit is given by: size = depth * num_lines - num_1Q_idles.

Returns

int

property duration(self)
two_q_gate_count(self)

The number of two-qubit gates in the circuit.

(Note that this cannot distinguish between “true” 2-qubit gates and gate that have been defined to act on two qubits but that represent some tensor-product gate.)

Returns

int

num_nq_gates(self, nq)

The number of nq-qubit gates in the circuit.

(Note that this cannot distinguish between “true” nq-qubit gates and gate that have been defined to act on nq qubits but that represent some tensor-product gate.)

Parameters

nq (int) – The qubit-count of the gates to count. For example, if nq == 3, this function returns the number of 3-qubit gates.

Returns

int

property num_multiq_gates(self)

The number of multi-qubit (2+ qubits) gates in the circuit.

(Note that this cannot distinguish between “true” multi-qubit gates and gate that have been defined to act on more than one qubit but that represent some tensor-product gate.)

Returns

int

_togrid(self, identity_name)

return a list-of-lists rep?

__str__(self)

A text rendering of the circuit.

__repr__(self)

Return repr(self).

format_display_str(self, width=80)

Formats a string for displaying this circuit suject to a maximum width.

Parameters

width (int, optional) – The maximum width in characters. If the circuit is longer than this width it is wrapped using multiple lines (like a musical score).

Returns

str

_print_labelinfo(self)

A useful debug routine for printing the internal label structure of a circuit

abstract _write_q_circuit_tex(self, filename)

Writes a LaTeX file for rendering this circuit nicely.

Creates a file containing LaTex that will display this circuit using the Qcircuit.tex LaTex import (compiling the LaTex requires that you have the Qcircuit.tex file).

Parameters

filename (str) – The file to write the LaTex into. Should end with ‘.tex’

Returns

None

convert_to_cirq(self, qubit_conversion, wait_duration=None, gatename_conversion=None, idle_gate_name='Gi')

Converts this circuit to a Cirq circuit.

Parameters
  • qubit_conversion (dict) – Mapping from qubit labels (e.g. integers) to Cirq qubit objects.

  • wait_duration (cirq.Duration, optional) – If no gatename_conversion dict is given, the idle operation is not converted to a gate. If wait_diration is specified and gatename_conversion is not specified, then the idle operation will be converted to a cirq.WaitGate with the specified duration.

  • gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the Cirq gates that will appear in the Cirq circuit. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard Cirq names will be implemented.

  • idle_gate_name (str, optional) – Name to use for idle gates. Defaults to ‘Gi’

Returns

A Cirq Circuit object.

convert_to_quil(self, num_qubits=None, gatename_conversion=None, qubit_conversion=None, readout_conversion=None, block_between_layers=True, block_idles=True, gate_declarations=None)

Converts this circuit to a quil string.

Parameters
  • num_qubits (int, optional) – The number of qubits for the quil file. If None, then this is assumed to equal the number of line labels in this circuit.

  • gatename_conversion (dict, optional) – A dictionary mapping gate names contained in this circuit to the corresponding gate names used in the rendered quil. If None, a standard set of conversions is used (see :function:`standard_gatenames_quil_conversions`).

  • qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the quil output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).

  • readout_conversion (dict, optional) – If not None, a dictionary converting the qubit labels mapped through qubit_conversion to the bit labels for readot. E.g. Suppose only qubit 2 (on Rigetti hardware) is in use. Then the pyGSTi string will have only one qubit (labeled 0); it will get remapped to 2 via qubit_conversion={0:2}. At the end of the quil circuit, readout should go recorded in bit 0, so readout_conversion = {0:0}. (That is, qubit with pyGSTi label 0 gets read to Rigetti bit 0, even though that qubit has Rigetti label 2.)

  • block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such “pragma” blocks can be important for QCVV testing, as this can help reduce the “behind-the-scenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.

  • block_idles (bool, optional) – In the special case of global idle gates, pragma-block barriers are inserted even when block_between_layers=False. Set block_idles=False to disable this behavior, whcih typically results in global idle gates being removed by the compiler.

  • gate_declarations (dict, optional) – If not None, a dictionary that provides unitary maps for particular gates that are not already in the quil syntax.

Returns

str – A quil string.

convert_to_openqasm(self, num_qubits=None, standard_gates_version='u3', gatename_conversion=None, qubit_conversion=None, block_between_layers=True, block_between_gates=False, gateargs_map=None)

Converts this circuit to an openqasm string.

Parameters
  • num_qubits (int, optional) – The number of qubits for the openqasm file. If None, then this is assumed to equal the number of line labels in this circuit.

  • version (string, optional) – Either ‘u3’ or ‘x-sx-rz’. Specifies the naming convention for the QASM gates. With ‘u3’, all single-qubit gates are specified in terms of the ‘u3’ gate, used by IBM and QisKit until ~2021 (see the qasm_u3 function). With ‘x-sx-rz’, all single-gates are specified in terms of ‘x’ (an x pi rotation), ‘sx’ (an x pi/2 rotation) and ‘rz’ (a parameterized rotation around z by an angle theta).

  • gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the gatenames that will appear in the openqasm output. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard openqasm names will be implemented.

  • qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the openqasm output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).

  • block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such barriers can be important for QCVV testing, as this can help reduce the “behind-the-scenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.

  • gateargs_map (dict, optional) – If not None, a dict that maps strings (representing pyGSTi standard gate names) to functions that map the parameters of a pyGSTi gate to a string to be combined with the QASM name to specify the specific gate, in QASM. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gzr’, ‘Gczr, etc) or none of the gates are parameterized, this dictionary need not be specified, and an automatic conversion to the standard openqasm format will be implemented.

Returns

str – An openqasm string.

simulate(self, model, return_all_outcomes=False)

Compute the outcome probabilities of this Circuit using model as a model for the gates.

The order of the outcome strings (e.g., ‘0100’) is w.r.t. to the ordering of the qubits in the circuit. That is, the ith element of the outcome string corresponds to the qubit with label self.line_labels[i].

Parameters
  • model (Model) – A description of the gate and SPAM operations corresponding to the labels stored in this Circuit. If this model is over more qubits than the circuit, the output will be the probabilities for the qubits in the circuit marginalized, if possible over the other qubits. But, the simulation is over the full set of qubits in the model, and so the time taken for the simulation scales with the number of qubits in the model. For models where “spectator” qubits do not affect the qubits in this circuit (such as with perfect gates), more efficient simulations will be obtained by first creating a model only over the qubits in this circuit.

  • return_all_outcomes (bool, optional) – Whether to include outcomes in the returned dictionary that have zero probability. When False, the threshold for discarding an outcome as z ero probability is 10^-12.

Returns

probs (dictionary) – A dictionary with keys equal to all (return_all_outcomes is True) or possibly only some (return_all_outcomes is False) of the possible outcomes, and values that are float probabilities.

done_editing(self)

Make this circuit read-only, so that it can be hashed (e.g. used as a dictionary key).

This is done automatically when attempting to hash a Circuit for the first time, so there’s calling this function can usually be skipped (but it’s good for code clarity).

Returns

None

expand_instruments_and_separate_povm(self, model, observed_outcomes=None)

Creates a dictionary of SeparatePOVMCircuit objects from expanding the instruments of this circuit.

Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as SeparatePOVMCircuit objects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities.

Parameters

model (Model) –

The model used to provide necessary details regarding the expansion, including:

  • default SPAM layers

  • definitions of instrument-containing layers

  • expansions of individual instruments and POVMs

Returns

OrderedDict – A dict whose keys are SeparatePOVMCircuit objects and whose values are tuples of the outcome labels corresponding to this circuit, one per POVM effect held in the key.

class pygsti.protocols._FreeformDataSet(circuits=None, circuit_indices=None)

Bases: object

An association between Circuits and arbitrary data.

Parameters
  • circuits (list of (tuples or Circuits), optional) – Each element is a tuple of operation labels or a Circuit object. Indices for these strings are assumed to ascend from 0. These indices must correspond to the time series of spam-label indices (above). Only specify this argument OR circuit_indices, not both.

  • circuit_indices (ordered dictionary, optional) – An OrderedDict with keys equal to circuits (tuples of operation labels) and values equal to integer indices associating a row/element of counts with the circuit. Only specify this argument OR circuits, not both.

to_dataframe(self, pivot_valuename=None, pivot_value='Value', drop_columns=False)

Create a Pandas dataframe with the data from this free-form dataset.

Parameters
  • pivot_valuename (str, optional) – If not None, the resulting dataframe is pivoted using pivot_valuename as the column whose values name the pivoted table’s column names. If None and pivot_value is not None,`”ValueName”` is used.

  • pivot_value (str, optional) – If not None, the resulting dataframe is pivoted such that values of the pivot_value column are rearranged into new columns whose names are given by the values of the pivot_valuename column. If None and pivot_valuename is not None,`”Value”` is used.

  • drop_columns (bool or list, optional) – A list of column names to drop (prior to performing any pivot). If True appears in this list or is given directly, then all constant-valued columns are dropped as well. No columns are dropped when drop_columns == False.

Returns

pandas.DataFrame

__iter__(self)
__len__(self)
__contains__(self, circuit)

Test whether data set contains a given circuit.

Parameters

circuit (tuple or Circuit) – A tuple of operation labels or a Circuit instance which specifies the the circuit to check for.

Returns

bool – whether circuit was found.

__hash__(self)

Return hash(self).

__getitem__(self, circuit)
__setitem__(self, circuit, info_dict)
__delitem__(self, circuit)
keys(self)

Returns the circuits used as keys of this DataSet.

Returns

list – A list of Circuit objects which index the data counts within this data set.

items(self)

Iterator over (circuit, info_dict) pairs.

Returns

Iterator

values(self)

Iterator over info-dicts for each circuit.

Returns

Iterator

copy(self)

Make a copy of this FreeformDataSet.

Returns

DataSet

class pygsti.protocols.FreeformDataSimulator

Bases: pygsti.protocols.protocol.DataSimulator

Computes arbitrary functions of the state data simulator that also computes user-defined functions of the final states.

abstract compute_freeform_data(self, circuit)

Computes the simulated free-form data for a single circuit.

Parameters

circuit (Circuit) – The circuit to compute data for.

Returns

dict

run(self, edesign, memlimit=None, comm=None)

Run this data simulator on an experiment design.

Parameters
  • edesign (ExperimentDesign) – The input experiment design.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this data simulator in parallel.

Returns

ProtocolData

apply_fn(self, series)
apply(self, df)

Apply this data simulator to a data frame having a Circuit column.

Parameters

df (pandas.DataFrame) – The data frame to apply to.

Returns

pandas.DataFrame

class pygsti.protocols.ModelFreeformSimulator(models)

Bases: FreeformDataSimulator

A base class for data simulators that utilize models (probably most of them!).

Holds a dictionary of models and provides basic functionality for computing probabilities, final states, and process matrices corresponding to circuits which make implementing :method:`compute_freeform_data` easier.

Parameters

models (dict) – A dictionary whose keys are string labels and values are Model objects, specifying the models used to compute “simluated” data.

compute_process_matrix(self, model, circuit, include_final_state=False, include_probabilities=False)
compute_process_matrices(self, circuit, include_final_state=False, include_probabilities=False)
compute_final_state(self, model, circuit, include_probabilities=False)
compute_final_states(self, circuit, include_probabilities=False)
compute_circuit_probabilities(self, model, circuit)
compute_probabilities(self, circuit, include_probabilities=False)
class pygsti.protocols._DummyProfiler

Bases: object

A dummy profiler that doesn’t do anything.

A class which implements the same interface as Profiler but which doesn’t actually do any profiling (consists of stub functions).

add_time(self, name, start_time, prefix=0)

Stub function that does nothing

Parameters
  • name (string) – The name of the timer to add elapsed time into (if the name doesn’t exist, one is created and initialized to the elapsed time).

  • start_time (float) – The starting time used to compute the elapsed, i.e. the value time.time()-start_time, which is added to the named timer.

  • prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.

Returns

None

add_count(self, name, inc=1, prefix=0)

Stub function that does nothing

Parameters
  • name (string) – The name of the counter to add val into (if the name doesn’t exist, one is created and initialized to val).

  • inc (int, optional) – The increment (the value to add to the counter).

  • prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.

Returns

None

memory_check(self, name, printme=None, prefix=0)

Stub function that does nothing

Parameters
  • name (string) – The name of the memory checkpoint. (Later, memory information can be organized by checkpoint name.)

  • printme (bool, optional) – Whether or not to print the memory usage during this function call (if None, the default, then the value of default_print_memcheck specified during Profiler construction is used).

  • prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.

Returns

None

class pygsti.protocols._NicelySerializable

Bases: object

The base class for all “nicely serializable” objects in pyGSTi.

A “nicely serializable” object can be converted to and created from a native Python object (like a string or dict) that contains only other native Python objects. In addition, there are constraints on the makeup of these objects so that they can be easily serialized to standard text-based formats, e.g. JSON. For example, dictionary keys must be strings, and the list vs. tuple distinction cannot be assumed to be preserved during serialization.

classmethod read(cls, path, format=None)

Read an object of this type, or a subclass of this type, from a file.

Parameters
  • path (str or Path or file-like) – The filename to open or an already open input stream.

  • format ({'json', None}) – The format of the file. If None this is determined automatically by the filename extension of a given path.

Returns

NicelySerializable

classmethod load(cls, f, format='json')

Load an object of this type, or a subclass of this type, from an input stream.

Parameters
  • f (file-like) – An open input stream to read from.

  • format ({'json'}) – The format of the input stream data.

Returns

NicelySerializable

classmethod loads(cls, s, format='json')

Load an object of this type, or a subclass of this type, from a string.

Parameters
  • s (str) – The serialized object.

  • format ({'json'}) – The format of the string data.

Returns

NicelySerializable

classmethod from_nice_serialization(cls, state)

Create and initialize an object from a “nice” serialization.

A “nice” serialization here means one created by a prior call to to_nice_serialization using this class or a subclass of it. Nice serializations adhere to additional rules (e.g. that dictionary keys must be strings) that make them amenable to common file formats (e.g. JSON).

The state argument is typically a dictionary containing ‘module’ and ‘state’ keys specifying the type of object that should be created. This type must be this class or a subclass of it.

Parameters

state (object) – An object, usually a dictionary, representing the object to de-serialize.

Returns

object

to_nice_serialization(self)

Serialize this object in a way that adheres to “niceness” rules of common text file formats.

Returns

object – Usually a dictionary representing the serialized object, but may also be another native Python type, e.g. a string or list.

write(self, path, **format_kwargs)

Writes this object to a file.

Parameters
  • path (str or Path) – The name of the file that is written.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

None

dump(self, f, format='json', **format_kwargs)

Serializes and writes this object to a given output stream.

Parameters
  • f (file-like) – A writable output stream.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

None

dumps(self, format='json', **format_kwargs)

Serializes this object and returns it as a string.

Parameters
  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

str

_dump_or_dumps(self, f, format='json', **format_kwargs)

Serializes and writes this object to a given output stream.

Parameters
  • f (file-like) – A writable output stream. If None, then object is written as a string and returned.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

str or None – If f is None, then the serialized object as a string is returned. Otherwise, None is returned.

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
classmethod _state_class(cls, state, check_is_subclass=True)

Returns the class specified by the given state dictionary

classmethod _check_compatible_nice_state(cls, state)
classmethod _encodemx(cls, mx)
classmethod _decodemx(cls, mx)
classmethod _encodevalue(cls, val)
classmethod _decodevalue(cls, val)
class pygsti.protocols._Estimate(parent, models=None, parameters=None, extra_parameters=None)

Bases: object

A class encapsulating the Model objects related to a single GST estimate up-to-gauge freedoms.

Thus, this class holds the “iteration” Model`s leading up to a final `Model, and then different gauge optimizations of the final set.

Parameters
  • parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.

  • models (dict, optional) – A dictionary of models to included in this estimate

  • parameters (dict, optional) – A dictionary of parameters associated with how these models were obtained.

classmethod from_dir(cls, dirname, quick_load=False)

Initialize a new Protocol object from dirname.

quick_loadbool, optional

Setting this to True skips the loading of components that may take a long time to load.

Parameters
  • dirname (str) – The directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load.

Returns

Protocol

classmethod create_gst_estimate(cls, parent, target_model=None, seed_model=None, models_by_iter=None, parameters=None)

Initialize an empty Estimate object.

Parameters
  • parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.

  • target_model (Model) – The target model used when optimizing the objective.

  • seed_model (Model) – The initial model used to seed the iterative part of the objective optimization. Typically this is obtained via LGST.

  • models_by_iter (list of Models) – The estimated model at each GST iteration. Typically these are the estimated models before any gauge optimization is performed.

  • parameters (dict) – A dictionary of parameters associated with how these models were obtained.

Returns

Estimate

property parameters(self)
property goparameters(self)
write(self, dirname)

Write this protocol to a directory.

Parameters

dirname (str) – The directory name to write. This directory will be created if needed, and the files in an existing directory will be overwritten.

Returns

None

retrieve_start_model(self, goparams)

Returns the starting model for the gauge optimization given by goparams.

This has a particular (and perhaps singular) use for deciding whether the gauge-optimized model for one estimate can be simply copied to another estimate, without actually re-gauge-optimizing.

Parameters

goparams (dict or list) – A dictionary of gauge-optimization parameters, just as in add_gaugeoptimized().

Returns

Model

add_gaugeoptimized(self, goparams, model=None, label=None, comm=None, verbosity=None)

Adds a gauge-optimized Model (computing it if needed) to this object.

Parameters
  • goparams (dict or list) – A dictionary of gauge-optimization parameters, typically arguments to gaugeopt_to_target(), specifying how the gauge optimization was (or should be) performed. When model is None (and this function computes the model internally) the keys and values of this dictionary must correspond to allowed arguments of gaugeopt_to_target(). By default, gaugeopt_to_target()’s first two arguments, the Model to optimize and the target, are taken to be self.models[‘final iteration estimate’] and self.models[‘target’]. This argument can also be a list of such parameter dictionaries, which specifies a multi-stage gauge- optimization whereby the output of one stage is the input of the next.

  • model (Model, optional) – The gauge-optimized model to store. If None, then this model is computed by calling gaugeopt_to_target() with the contents of goparams as arguments as described above.

  • label (str, optional) – A label for this gauge-optimized model, used as the key in this object’s models and goparameters member dictionaries. If None, then the next available “go<X>”, where <X> is a non-negative integer, is used as the label.

  • comm (mpi4py.MPI.Comm, optional) – A default MPI communicator to use when one is not specified as the ‘comm’ element of/within goparams.

  • verbosity (int, optional) – An integer specifying the level of detail printed to stdout during the calculations performed in this function. If not None, this value will override any verbosity values set within goparams.

Returns

None

add_confidence_region_factory(self, model_label='final iteration estimate', circuits_label='final')

Creates a new confidence region factory.

An instance of ConfidenceRegionFactory serves to create confidence intervals and regions in reports and elsewhere. This function creates such a factory, which is specific to a given Model (given by this object’s .models[model_label] ) and circuit list (given by the parent Results’s .circuit_lists[gastrings_label] list).

Parameters
  • model_label (str, optional) – The label of a Model held within this Estimate.

  • circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.

Returns

ConfidenceRegionFactory – The newly created factory (also cached internally) and accessible via the create_confidence_region_factory() method.

has_confidence_region_factory(self, model_label='final iteration estimate', circuits_label='final')

Checks whether a confidence region factory for the given model and circuit list labels exists.

Parameters
  • model_label (str, optional) – The label of a Model held within this Estimate.

  • circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.

Returns

bool

create_confidence_region_factory(self, model_label='final iteration estimate', circuits_label='final', create_if_needed=False)

Retrieves a confidence region factory for the given model and circuit list labels.

For more information about confidence region factories, see add_confidence_region_factory().

Parameters
  • model_label (str, optional) – The label of a Model held within this Estimate.

  • circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.

  • create_if_needed (bool, optional) – If True, a new confidence region factory will be created if none exists. Otherwise a KeyError is raised when the requested factory doesn’t exist.

Returns

ConfidenceRegionFactory

gauge_propagate_confidence_region_factory(self, to_model_label, from_model_label='final iteration estimate', circuits_label='final', eps=0.001, verbosity=0)

Propagates a confidence region among gauge-equivalent models.

More specifically, this function propagates an existing “reference” confidence region for a Model “G0” to a new confidence region for a gauge-equivalent model “G1”.

When successful, a new confidence region factory is created for the .models[to_model_label] Model and circuits_label gate string list from the existing factory for .models[from_model_label].

Parameters
  • to_model_label (str) – The key into this Estimate object’s models and goparameters dictionaries that identifies the final gauge-optimized result to create a factory for. This gauge optimization must have begun at “from” reference model, i.e., models[from_model_label] must equal (by frobeinus distance) goparameters[to_model_label][‘model’].

  • from_model_label (str, optional) – The key into this Estimate object’s models dictionary that identifies the reference model.

  • circuits_label (str, optional) – The key of the circuit list (within the parent Results’s .circuit_lists dictionary) that identifies the circuit list used by the old (&new) confidence region factories.

  • eps (float, optional) – A small offset used for constructing finite-difference derivatives. Usually the default value is fine.

  • verbosity (int, optional) – A non-negative integer indicating the amount of detail to print to stdout.

Returns

ConfidenceRegionFactory – Note: this region is also stored internally and as such the return value of this function can often be ignored.

create_effective_dataset(self, return_submxs=False)

Generate a DataSet containing the effective counts as dictated by the “weights” parameter.

An estimate’s self.parameters[‘weights’] value specifies a dictionary of circuits weights, which modify (typically reduce) the counts given in its (parent’s) data set.

This function rescales the actual data contained in this Estimate’s parent ModelEstimteResults object according to the estimate’s “weights” parameter. The scaled data set is returned, along with (optionall) a list-of-lists of matrices containing the scaling values which can be easily plotted via a ColorBoxPlot.

Parameters

return_submxs (boolean) – If true, also return a list-of-lists of matrices containing the scaling values, as described above.

Returns

  • ds (DataSet) – The “effective” (scaled) data set.

  • subMxs (list-of-lists) – Only returned if return_submxs == True. Contains the scale values (see above).

final_mdc_store(self, resource_alloc=None, array_types=('e', 'ep'))

The final (not intermediate) model-dataset-circuit storage object (MDC store) for this estimate.

This object is created and cached as needed, and combined the final model, data set, and circuit list for this estimate.

Parameters
  • resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store. This can just be left as None unless multiple processors are being utilized. Note that this argument is only used when a MDC store needs to be created – if this estimate has already created one then this argument is ignored.

  • array_types (tuple) – A tuple of array types passed to the MDC store constructor (if a new MDC store needs to be created). These affect how memory is allocated within the MDC store object and can enable (or disable) the use of certain MDC store functionality later on (e.g. the use of Jacobian or Hessian quantities).

Returns

ModelDatasetCircuitsStore

final_objective_fn(self, resource_alloc=None)

The final (not intermediate) objective function object for this estimate.

This object is created and cached as needed, and is the evaluated (and sometimes optimized) objective function associated with this estimate. Often this is a log-likelihood or chi-squared function, or a close variant.

Parameters

resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store underlying the objective function. This can just be left as None unless multiple processors are being utilized. Note that this argument is only used when an underlying MDC store needs to be created – if this estimate has already created a MDC store then this argument is ignored.

Returns

MDCObjectiveFunction

final_objective_fn_cache(self, resource_alloc=None)

The final (not intermediate) serializable (“cached”) objective function object for this estimate.

This is an explicitly serializable version of the final objective function, useful because is often doesn’t need be constructed. To become serializable, however, the objective function is stripped of any MPI comm or multi-processor information (since this may be different between loading and saving). This makes the cached objective function convenient for fast calls/usages of the objective function.

Parameters

resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store underlying the objective function. This can just be left as None unless multiple processors are being utilized - and in this case the cached objective function doesn’t even benefit from these processors (but calls to :method:`final_objective_fn` will return an objective function setup for multiple processors). Note that this argument is only used when there is no existing cached objective function and an underlying MDC store needs to be created.

Returns

CachedObjectiveFunction

misfit_sigma(self, resource_alloc=None)

Returns the number of standard deviations (sigma) of model violation.

Parameters

resource_alloc (ResourceAllocation, optional) – What resources are available for this computation.

Returns

float

view(self, gaugeopt_keys, parent=None)

Creates a shallow copy of this Results object containing only the given gauge-optimization keys.

Parameters
  • gaugeopt_keys (str or list, optional) – Either a single string-value gauge-optimization key or a list of such keys. If None, then all gauge-optimization keys are retained.

  • parent (Results, optional) – The parent Results object of the view. If None, then the current Estimate’s parent is used.

Returns

Estimate

copy(self)

Creates a copy of this Estimate object.

Returns

Estimate

__str__(self)

Return str(self).

__getstate__(self)
__setstate__(self, state_dict)
set_parent(self, parent)

Sets the parent object of this estimate.

This is used, for instance, to re-establish parent-child links after loading objects from disk.

Parameters

parent (ModelEstimateResults) – This object’s parent.

Returns

None

class pygsti.protocols._ModelTest(model_to_test, target_model=None, gaugeopt_suite=None, objfn_builder=None, badfit_options=None, set_trivial_gauge_group=True, verbosity=2, name=None)

Bases: pygsti.protocols.protocol.Protocol

A protocol that tests how well a model agrees with a given set of data.

Parameters
  • model_to_test (Model) – The model to compare with data when :method:`run` is called.

  • target_model (Model, optional) – The ideal or desired model of perfect operations. It is often useful to bundle this together with model_to_test so that comparison metrics can be easily computed.

  • gaugeopt_suite (GSTGaugeOptSuite, optional) – Specifies which gauge optimizations to perform on each estimate. Can also be any object that can be cast to a GSTGaugeOptSuite object, such as a string or list of strings (see below) specifying built-in sets of gauge optimizations. This object also optionally stores an alternate target model for gauge optimization. This model is used as the “target” for gauge- optimization (only), and is useful when you want to gauge optimize toward something other than the ideal target gates.

  • objfn_builder (ObjectiveFunctionBuilder) – The objective function (builder) that is used to compare the model to data, i.e. the objective function that defines this model test.

  • badfit_options (GSTBadFitOptions) – Options specifing what constitutes a “bad fit” (or “failed test”) and what additional actions to take if and when this occurs.

  • set_trivial_gauge_group (bool, optional) – A convenience flag that updates the default gauge group of model_to_test to the trivial gauge group before performing the test, so that no actual gauge optimization is performed (even if gaugeopt_suite is non-None).

  • verbosity (int, optional) – Level of detail printed to stdout.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

classmethod create_objective_builder(cls, obj)

Creates objective function builders from obj that are commonly used in model tests.

Parameters

obj (object) – If obj is already an ObjectiveFunctionBuilder it is used directly. A dictionary is assumed to hold arguments of :method:`ObjectiveFunctionBuilder.simple`. A list or tuple is assumed to hold positional arguments of :method:`ObjectiveFunctionBuilder.__init__`.

Returns

ObjectiveFunctionBuilder

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

ModelEstimateResults

class pygsti.protocols._QubitProcessorSpec(num_qubits, gate_names, nonstd_gate_unitaries=None, availability=None, geometry=None, qubit_labels=None, nonstd_gate_symplecticreps=None, aux_info=None)

Bases: ProcessorSpec

The device specification for a one or more qubit quantum computer.

This is objected is geared towards multi-qubit devices; many of the contained structures are superfluous in the case of a single qubit.

Parameters
  • num_qubits (int) – The number of qubits in the device.

  • gate_names (list of strings) –

    The names of gates in the device. This may include standard gate names known by pyGSTi (see below) or names which appear in the nonstd_gate_unitaries argument. The set of standard gate names includes, but is not limited to:

    • ’Gi’ : the 1Q idle operation

    • ’Gx’,’Gy’,’Gz’ : 1-qubit pi/2 rotations

    • ’Gxpi’,’Gypi’,’Gzpi’ : 1-qubit pi rotations

    • ’Gh’ : Hadamard

    • ’Gp’ : phase or S-gate (i.e., ((1,0),(0,i)))

    • ’Gcphase’,’Gcnot’,’Gswap’ : standard 2-qubit gates

    Alternative names can be used for all or any of these gates, but then they must be explicitly defined in the nonstd_gate_unitaries dictionary. Including any standard names in nonstd_gate_unitaries overrides the default (builtin) unitary with the one supplied.

  • nonstd_gate_unitaries (dictionary of numpy arrays) – A dictionary with keys that are gate names (strings) and values that are numpy arrays specifying quantum gates in terms of unitary matrices. This is an additional “lookup” database of unitaries - to add a gate to this QubitProcessorSpec its names still needs to appear in the gate_names list. This dictionary’s values specify additional (target) native gates that can be implemented in the device as unitaries acting on ordinary pure-state-vectors, in the standard computationl basis. These unitaries need not, and often should not, be unitaries acting on all of the qubits. E.g., a CNOT gate is specified by a key that is the desired name for CNOT, and a value that is the standard 4 x 4 complex matrix for CNOT. All gate names must start with ‘G’. As an advanced behavior, a unitary-matrix-returning function which takes a single argument - a tuple of label arguments - may be given instead of a single matrix to create an operation factory which allows continuously-parameterized gates. This function must also return an empty/dummy unitary when None is given as it’s argument.

  • availability (dict, optional) – A dictionary whose keys are some subset of the keys (which are gate names) nonstd_gate_unitaries and the strings (which are gate names) in gate_names and whose values are lists of qubit-label-tuples. Each qubit-label-tuple must have length equal to the number of qubits the corresponding gate acts upon, and causes that gate to be available to act on the specified qubits. Instead of a list of tuples, values of availability may take the special values “all-permutations” and “all-combinations”, which as their names imply, equate to all possible permutations and combinations of the appropriate number of qubit labels (deterined by the gate’s dimension). If a gate name is not present in availability, the default is “all-permutations”. So, the availability of a gate only needs to be specified when it cannot act in every valid way on the qubits (e.g., the device does not have all-to-all connectivity).

  • geometry ({"line","ring","grid","torus"} or QubitGraph, optional) – The type of connectivity among the qubits, specifying a graph used to define neighbor relationships. Alternatively, a QubitGraph object with qubit_labels as the node labels may be passed directly. This argument is only used as a convenient way of specifying gate availability (edge connections are used for gates whose availability is unspecified by availability or whose value there is “all-edges”).

  • qubit_labels (list or tuple, optional) – The labels (integers or strings) of the qubits. If None, then the integers starting with zero are used.

  • nonstd_gate_symplecticreps (dict, optional) – A dictionary similar to nonstd_gate_unitaries that supplies, instead of a unitary matrix, the symplectic representation of a Clifford operations, given as a 2-tuple of numpy arrays.

  • aux_info (dict, optional) – Any additional information that should be attached to this processor spec.

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
property num_qubits(self)

The number of qubits.

property primitive_op_labels(self)

All the primitive operation labels derived from the gate names and availabilities

gate_num_qubits(self, gate_name)

The number of qubits that a given gate acts upon.

Parameters

gate_name (str) – The name of the gate.

Returns

int

resolved_availability(self, gate_name, tuple_or_function='auto')

The availability of a given gate, resolved as either a tuple of sslbl-tuples or a function.

This function does more than just access the availability attribute, as this may hold special values like “all-edges”. It takes the value of self.availability[gate_name] and resolves and converts it into the desired format: either a tuple of state-space labels or a function with a single state-space-labels-tuple argument.

Parameters
  • gate_name (str) – The gate name to get the availability of.

  • tuple_or_function ({'tuple', 'function', 'auto'}) – The type of object to return. ‘tuple’ means a tuple of state space label tuples, e.g. ((0,1), (1,2)). ‘function’ means a function that takes a single state space label tuple argument and returns True or False to indicate whether the gate is available on the given target labels. If ‘auto’ is given, then either a tuple or function is returned - whichever is more computationally convenient.

Returns

tuple or function

_resolve_availability(self, avail_entry, gate_nqubits, tuple_or_function='auto')
is_available(self, gate_label)

Check whether a gate at a given location is available.

Parameters

gate_label (Label) – The gate name and target labels to check availability of.

Returns

bool

available_gatenames(self, sslbls)

List all the gate names that are available within a set of state space labels.

This function finds all the gate names that are available for at least a subset of sslbls.

Parameters

sslbls (tuple) – The state space labels to find availability within.

Returns

tuple of strings – A tuple of gate names (strings).

available_gatelabels(self, gate_name, sslbls)

List all the gate labels that are available for gate_name on at least a subset of sslbls.

Parameters
  • gate_name (str) – The gate name.

  • sslbls (tuple) – The state space labels to find availability within.

Returns

tuple of Labels – The available gate labels (all with name gate_name).

force_recompute_gate_relationships(self)

Invalidates LRU caches for all compute_* methods of this object, forcing them to recompute their values.

The compute_* methods of this processor spec compute various relationships and properties of its gates. These routines can be computationally intensive, and so their values are cached for performance. If the gates of a processor spec changes and its compute_* methods are used, force_recompute_gate_relationships should be called.

compute_clifford_symplectic_reps(self, gatename_filter=None)

Constructs a dictionary of the symplectic representations for all the Clifford gates in this processor spec.

Parameters

gatename_filter (iterable, optional) – A list, tuple, or set of gate names whose symplectic representations should be returned (if they exist).

Returns

dict – keys are gate names, values are (symplectic_matrix, phase_vector) tuples.

compute_one_qubit_gate_relations(self)

Computes the basic pair-wise relationships relationships between the gates.

1. It multiplies all possible combinations of two 1-qubit gates together, from the full model available to in this device. If the two gates multiple to another 1-qubit gate from this set of gates this is recorded in the dictionary self.oneQgate_relations. If the 1-qubit gate with name name1 followed by the 1-qubit gate with name name2 multiple (up to phase) to the gate with name3, then self.oneQgate_relations[name1,`name2`] = name3.

2. If the inverse of any 1-qubit gate is contained in the model, this is recorded in the dictionary self.gate_inverse.

Returns

  • gate_relations (dict) – Keys are (gatename1, gatename2) and values are either the gate name of the product of the two gates or None, signifying the identity.

  • gate_inverses (dict) – Keys and values are gate names, mapping a gate name to its inverse gate (if one exists).

compute_multiqubit_inversion_relations(self)

Computes the inverses of multi-qubit (>1 qubit) gates.

Finds whether any of the multi-qubit gates in this device also have their inverse in the model. That is, if the unitaries for the multi-qubit gate with name name1 followed by the multi-qubit gate (of the same dimension) with name name2 multiple (up to phase) to the identity, then gate_inverse[name1] = name2 and gate_inverse[name2] = name1

1-qubit gates are not computed by this method, as they are be computed by the method :method:`compute_one_qubit_gate_relations`.

Returns

gate_inverse (dict) – Keys and values are gate names, mapping a gate name to its inverse gate (if one exists).

compute_clifford_ops_on_qubits(self)

Constructs a dictionary mapping tuples of state space labels to the clifford operations available on them.

Returns

dict – A dictionary with keys that are state space label tuples and values that are lists of gate labels, giving the available Clifford gates on those target labels.

compute_ops_on_qubits(self)

Constructs a dictionary mapping tuples of state space labels to the operations available on them.

Returns

dict – A dictionary with keys that are state space label tuples and values that are lists of gate labels, giving the available gates on those target labels.

compute_clifford_2Q_connectivity(self)

Constructs a graph encoding the connectivity between qubits via 2-qubit Clifford gates.

Returns

QubitGraph – A graph with nodes equal to the qubit labels and edges present whenever there is a 2-qubit Clifford gate between the vertex qubits.

compute_2Q_connectivity(self)

Constructs a graph encoding the connectivity between qubits via 2-qubit gates.

Returns

QubitGraph – A graph with nodes equal to the qubit labels and edges present whenever there is a 2-qubit gate between the vertex qubits.

subset(self, gate_names_to_include='all', qubit_labels_to_keep='all')

Construct a smaller processor specification by keeping only a select set of gates from this processor spec.

Parameters

gate_names_to_include (list or tuple or set) – The gate names that should be included in the returned processor spec.

Returns

QubitProcessorSpec

map_qubit_labels(self, mapper)

Creates a new QubitProcessorSpec whose qubit labels are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.qubit_labels values and whose value are the new labels, or a function which takes a single (existing qubit-label) argument and returns a new qubit label.

Returns

QubitProcessorSpec

property idle_gate_names(self)

The gate names that correspond to idle operations.

property global_idle_gate_name(self)

The (first) gate name that corresponds to a global idle operation.

property global_idle_layer_label(self)

Similar to global_idle_gate_name but include the appropriate sslbls (either None or all the qubits)

class pygsti.protocols._Model(state_space)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

A predictive model for a Quantum Information Processor (QIP).

The main function of a Model object is to compute the outcome probabilities of Circuit objects based on the action of the model’s ideal operations plus (potentially) noise which makes the outcome probabilities deviate from the perfect ones.

Parameters

state_space (StateSpace) – The state space of this model.

_to_nice_serialization(self)
property state_space(self)

State space labels

Returns

StateSpaceLabels

property hyperparams(self)

Dictionary of hyperparameters associated with this model

Returns

dict

property num_params(self)

The number of free parameters when vectorizing this model.

Returns

int – the number of model parameters.

property num_modeltest_params(self)

The parameter count to use when testing this model against data.

Often times, this is the same as :method:`num_params`, but there are times when it can convenient or necessary to use a parameter count different than the actual number of parameters in this model.

Returns

int – the number of model parameters.

property parameter_bounds(self)

Upper and lower bounds on the values of each parameter, utilized by optimization routines

set_parameter_bounds(self, index, lower_bound=- _np.inf, upper_bound=_np.inf)

Set the bounds for a single model parameter.

These limit the values the parameter can have during an optimization of the model.

Parameters
  • index (int) – The index of the paramter whose bounds should be set.

  • lower_bound (float, optional) – The lower and upper bounds for the parameter. Can be set to the special numpy.inf (or -numpy.inf) values to effectively have no bound.

  • upper_bound (float, optional) – The lower and upper bounds for the parameter. Can be set to the special numpy.inf (or -numpy.inf) values to effectively have no bound.

Returns

None

property parameter_labels(self)

A list of labels, usually of the form (op_label, string_description) describing this model’s parameters.

property parameter_labels_pretty(self)

The list of parameter labels but formatted in a nice way.

In particular, tuples where the first element is an op label are made into a single string beginning with the string representation of the operation.

set_parameter_label(self, index, label)

Set the label of a single model parameter.

Parameters
  • index (int) – The index of the paramter whose label should be set.

  • label (object) – An object that serves to label this parameter. Often a string.

Returns

None

to_vector(self)

Returns the model vectorized according to the optional parameters.

Returns

numpy array – The vectorized model parameters.

from_vector(self, v, close=False)

Sets this Model’s operations based on parameter values v.

Parameters
  • v (numpy.ndarray) – A vector of parameters, with length equal to self.num_params.

  • close (bool, optional) – Set to True if v is close to the current parameter vector. This can make some operations more efficient.

Returns

None

abstract probabilities(self, circuit, clip_to=None)

Construct a dictionary containing the outcome probabilities of circuit.

Parameters
  • circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.

  • clip_to (2-tuple, optional) – (min,max) to clip probabilities to if not None.

Returns

probs (dictionary) – A dictionary such that probs[SL] = pr(SL,circuit,clip_to) for each spam label (string) SL.

abstract bulk_probabilities(self, circuits, clip_to=None, comm=None, mem_limit=None, smartc=None)

Construct a dictionary containing the probabilities for an entire list of circuits.

Parameters
  • circuits ((list of Circuits) or CircuitOutcomeProbabilityArrayLayout) – When a list, each element specifies a circuit to compute outcome probabilities for. A CircuitOutcomeProbabilityArrayLayout specifies the circuits along with an internal memory layout that reduces the time required by this function and can restrict the computed probabilities to those corresponding to only certain outcomes.

  • clip_to (2-tuple, optional) – (min,max) to clip return value if not None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors. Distribution is performed over subtrees of evalTree (if it is split).

  • mem_limit (int, optional) – A rough memory limit in bytes which is used to determine processor allocation.

  • smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.

Returns

probs (dictionary) – A dictionary such that probs[opstr] is an ordered dictionary of (outcome, p) tuples, where outcome is a tuple of labels and p is the corresponding probability.

_init_copy(self, copy_into, memo)

Copies any “tricky” member of this model into copy_into, before deep copying everything else within a .copy() operation.

_post_copy(self, copy_into, memo)

Called after all other copying is done, to perform “linking” between the new model (copy_into) and its members.

copy(self)

Copy this model.

Returns

Model – a (deep) copy of this model.

__str__(self)

Return str(self).

__hash__(self)

Return hash(self).

circuit_outcomes(self, circuit)

Get all the possible outcome labels produced by simulating this circuit.

Parameters

circuit (Circuit) – Circuit to get outcomes of.

Returns

tuple

compute_num_outcomes(self, circuit)

The number of outcomes of circuit, given by it’s existing or implied POVM label.

Parameters

circuit (Circuit) – The circuit to simplify

Returns

int

complete_circuit(self, circuit)

Adds any implied preparation or measurement layers to circuit

Parameters

circuit (Circuit) – Circuit to act on.

Returns

Circuit – Possibly the same object as circuit, if no additions are needed.

class pygsti.protocols._GaugeGroup(name)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

A parameterized set (ideally a group) of gauge transformations.

Specifies the “optimization space” explored by gauge optimization algorithms. This base class is used to define the common interface of all types of gauge “groups” (even though they need not be groups in the mathematical sense).

Parameters

name (str) – A name for this group - used for reporting what type of gauge optimization was performed.

property num_params(self)

Return the number of parameters (degrees of freedom) of this gauge group..

Returns

int

compute_element(self, param_vec)

Retrieve the element of this group corresponding to param_vec

Parameters

param_vec (numpy.ndarray) – A 1D array of length :method:`num_params`.

Returns

GaugeGroupElement

property initial_params(self)

Return a good (or standard) starting parameter vector, used to initialize a gauge optimization.

Returns

numpy.ndarray – A 1D array of length :method:`num_params`.

class pygsti.protocols._GaugeGroupElement

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

The element of a GaugeGroup, which represents a single gauge transformation.

property transform_matrix(self)

The gauge-transform matrix.

Returns

numpy.ndarray

property transform_matrix_inverse(self)

The inverse of the gauge-transform matrix.

Returns

numpy.ndarray

deriv_wrt_params(self, wrt_filter=None)

Computes the derivative of the gauge group at this element.

That is, the derivative of a general element with respect to the gauge group’s parameters, evaluated at this element.

Parameters

wrt_filter (list or numpy.ndarray, optional) – Indices of the gauge group parameters to differentiate with respect to. If None, differentiation is performed with respect to all the group’s parameters.

Returns

numpy.ndarray

to_vector(self)

Get the parameter vector corresponding to this transform.

Returns

numpy.ndarray

from_vector(self, v)

Reinitialize this GaugeGroupElement using the the parameter vector v.

Parameters

v (numpy.ndarray) – A 1D array of length :method:`num_params`

Returns

None

property num_params(self)

Return the number of parameters of this gauge group element.

(This is equivalent to the number of parameters of the parent gauge group.)

Returns

int

inverse(self)

Creates a gauge group element that performs the inverse of this element.

Returns

InverseGaugeGroupElement

class pygsti.protocols._CircuitList(circuits, op_label_aliases=None, circuit_weights=None, name=None)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

A unmutable list (a tuple) of Circuit objects and associated metadata.

Parameters
  • circuits (list) – The list of circuits that constitutes the primary data held by this object.

  • op_label_aliases (dict, optional) – Dictionary of circuit meta-data whose keys are operation label “aliases” and whose values are circuits corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined). e.g. op_label_aliases[‘Gx^3’] = pygsti.obj.Circuit([‘Gx’,’Gx’,’Gx’])

  • circuit_weights (numpy.ndarray, optional) – If not None, an array of per-circuit weights (of length equal to the number of circuits) that are typically used to multiply the counts extracted for each circuit.

  • name (str, optional) – An optional name for this list, used for status messages.

classmethod cast(cls, circuits)

Convert (if needed) an object into a CircuitList.

Parameters

circuits (list or CircuitList) – The object to convert.

Returns

CircuitList

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
__len__(self)
__getitem__(self, index)
__iter__(self)
apply_aliases(self)

Applies any operation-label aliases to this circuit list.

Returns

list – A list of :class:`Circuit`s.

truncate(self, circuits_to_keep)

Builds a new circuit list containing only a given subset.

This can be safer then just creating a new CircuitList because it preserves the aliases, etc., of this list.

Parameters

circuits_to_keep (list or set) – The circuits to retain in the returned circuit list.

Returns

CircuitList

truncate_to_dataset(self, dataset)

Builds a new circuit list containing only those elements in dataset.

Parameters

dataset (DataSet) – The dataset to check. Aliases are applied to the circuits in this circuit list before they are tested.

Returns

CircuitList

__hash__(self)

Return hash(self).

__eq__(self, other)

Return self==value.

__setstate__(self, state_dict)
class pygsti.protocols._ResourceAllocation(comm=None, mem_limit=None, profiler=None, distribute_method='default', allocated_memory=0)

Bases: object

Describes available resources and how they should be allocated.

This includes the number of processors and amount of memory, as well as a strategy for how computations should be distributed among them.

Parameters
  • comm (mpi4py.MPI.Comm, optional) – MPI communicator holding the number of available processors.

  • mem_limit (int, optional) – A rough per-processor memory limit in bytes.

  • profiler (Profiler, optional) – A lightweight profiler object for tracking resource usage.

  • distribute_method (str, optional) – The name of a distribution strategy.

classmethod cast(cls, arg)

Cast arg to a ResourceAllocation object.

If arg already is a ResourceAllocation instance, it just returned. Otherwise this function attempts to create a new instance from arg.

Parameters

arg (ResourceAllocation or dict) – An object that can be cast to a ResourceAllocation.

Returns

ResourceAllocation

build_hostcomms(self)
property comm_rank(self)

A safe way to get self.comm.rank (0 if self.comm is None)

property comm_size(self)

A safe way to get self.comm.size (1 if self.comm is None)

property is_host_leader(self)

True if this processors is the rank-0 “leader” of its host (node). False otherwise.

host_comm_barrier(self)

Calls self.host_comm.barrier() when self.host_comm is not None.

This convenience function provides an often-used barrier that follows code where a single “leader” processor modifies a memory block shared between all members of self.host_comm, and the other processors must wait until this modification is performed before proceeding with their own computations.

Returns

None

copy(self)

Copy this object.

Returns

ResourceAllocation

reset(self, allocated_memory=0)

Resets internal allocation counters to given values (defaults to zero).

Parameters

allocated_memory (int64) – The value to set the memory allocation counter to.

Returns

None

add_tracked_memory(self, num_elements, dtype='d')

Adds nelements * itemsize bytes to the total amount of allocated memory being tracked.

If the total (tracked) memory exceeds self.mem_limit a MemoryError exception is raised.

Parameters
  • num_elements (int) – The number of elements to track allocation of.

  • dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.

Returns

None

check_can_allocate_memory(self, num_elements, dtype='d')

Checks that allocating nelements doesn’t cause the memory limit to be exceeded.

This memory isn’t tracked - it’s just added to the current tracked memory and a MemoryError exception is raised if the result exceeds self.mem_limit.

Parameters
  • num_elements (int) – The number of elements to track allocation of.

  • dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.

Returns

None

temporarily_track_memory(self, num_elements, dtype='d')

Temporarily adds nelements to tracked memory (a context manager).

A MemoryError exception is raised if the tracked memory exceeds self.mem_limit.

Parameters
  • num_elements (int) – The number of elements to track allocation of.

  • dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.

Returns

contextmanager

gather_base(self, result, local, slice_of_global, unit_ralloc=None, all_gather=False)

Gather or all-gather operation using local arrays and a unit resource allocation.

Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final to-be gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.

  • all_gather (bool, optional) – Whether the final result should be gathered on all the processors of this ResourceAllocation or just the root (rank 0) processor.

Returns

None

gather(self, result, local, slice_of_global, unit_ralloc=None)

Gather local arrays into a global result array potentially with a unit resource allocation.

Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final to-be gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.

The global array is only gathered on the root (rank 0) processor of this resource allocation.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, only needed on the root (rank 0) processor. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allgather(self, result, local, slice_of_global, unit_ralloc=None)

All-gather local arrays into global arrays on each processor, potentially using a unit resource allocation.

Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final to-be gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allreduce_sum(self, result, local, unit_ralloc=None)

Sum local arrays on different processors, potentially using a unit resource allocation.

Similar to a normal MPI reduce call (with MPI.SUM type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the sum, only processors with unit_ralloc.rank == 0 contribute to the sum. This handles the case where simply summing the local contributions from all processors would result in over-counting because of multiple processors hold the same logical result (summand).

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being summed. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allreduce_sum_simple(self, local, unit_ralloc=None)

A simplified sum over quantities on different processors that doesn’t use shared memory.

The shared memory usage of :method:`allreduce_sum` can be overkill when just summing a single scalar quantity. This method provides a way to easily sum a quantity across all the processors in this ResourceAllocation object using a unit resource allocation.

Parameters
  • local (int or float) – The local (per-processor) value to sum.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local value, so that only the unit_ralloc.rank == 0 processors will contribute to the sum. If None, then it is assumed that each processor computes a logically different local value.

Returns

float or int – The sum of all local quantities, returned on all the processors.

allreduce_min(self, result, local, unit_ralloc=None)

Take elementwise min of local arrays on different processors, potentially using a unit resource allocation.

Similar to a normal MPI reduce call (with MPI.MIN type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the min operation, only processors with unit_ralloc.rank == 0 contribute.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allreduce_max(self, result, local, unit_ralloc=None)

Take elementwise max of local arrays on different processors, potentially using a unit resource allocation.

Similar to a normal MPI reduce call (with MPI.MAX type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the max operation, only processors with unit_ralloc.rank == 0 contribute.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.

Returns

None

bcast(self, value, root=0)

Broadcasts a value from the root processor/host to the others in this resource allocation.

This is similar to a usual MPI broadcast, except it takes advantage of shared memory when it is available. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, then this routine places value in a shared memory buffer and uses the resource allocation’s inter-host communicator to broadcast the result from the root host to all the other hosts using all the processor on the root host in parallel (all processors with the same intra-host rank participate in a MPI broadcast).

Parameters
  • value (numpy.ndarray) – The value to broadcast. May be shared memory but doesn’t need to be. Only need to specify this on the rank root processor, other processors can provide any value for this argument (it’s unused).

  • root (int) – The rank of the processor whose value will be to broadcast.

Returns

numpy.ndarray – The broadcast value, in a new, non-shared-memory array.

__getstate__(self)
pygsti.protocols.ROBUST_SUFFIX_LIST = ['.robust', '.Robust', '.robust+', '.Robust+']
pygsti.protocols.DEFAULT_BAD_FIT_THRESHOLD = 2.0
class pygsti.protocols.HasProcessorSpec(processorspec_filename_or_obj)

Bases: object

Adds to an experiment design a processor_spec attribute

Parameters

processorspec_filename_or_obj (QubitProcessorSpec or str) – The processor API used by this experiment design.

create_target_model(self, gate_type='auto', prep_type='auto', povm_type='auto')

Create a target model for this experiment design.

An explicit model is created based on the processor spec. If a different type of model is needed, consider creating the model manually via the construction functions in the pygsti.models.modelconstruction module using this experiment design’s .processor_spec attribute.

Parameters
  • gate_type (str, optional) – The type of gate objects to create. Currently “auto” is the same as “static”.

  • prep_type (str, optional) – The type of state preparation objects to create. “auto” selects a type based on the value of gate_type.

  • povm_type (str, optional) – The type of POVM objects to create. “auto” selects a type based on the value of gate_type.

Returns

Model

class pygsti.protocols.GateSetTomographyDesign(processorspec_filename_or_obj, circuit_lists, all_circuits_needing_data=None, qubit_labels=None, nested=False, remove_duplicates=True)

Bases: pygsti.protocols.protocol.CircuitListsDesign, HasProcessorSpec

Minimal experiment design needed for GST

Parameters
  • processorspec_filename_or_obj (QubitProcessorSpec or str) – The processor API used by this experiment design.

  • circuit_lists (list) – Per-GST-iteration circuit lists, giving the circuits to run at each GST iteration (typically these correspond to different maximum-lengths).

  • all_circuits_needing_data (list, optional) – A list of all the circuits in circuit_lists typically with duplicates removed.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

  • nested (bool, optional) – Whether the elements of circuit_lists are nested, e.g. whether circuit_lists[i] is a subset of circuit_lists[i+1]. This is useful to know because certain operations can be more efficient when it is known that the lists are nested.

  • remove_duplicates (bool, optional) – Whether to remove duplicates when automatically creating all the circuits that need data (this argument isn’t used when all_circuits_needing_data is given).

class pygsti.protocols.StandardGSTDesign(processorspec_filename_or_obj, prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, germ_list_or_filename, max_lengths, germ_length_limits=None, fiducial_pairs=None, keep_fraction=1, keep_seed=None, include_lgst=True, nest=True, circuit_rules=None, op_label_aliases=None, dscheck=None, action_if_missing='raise', qubit_labels=None, verbosity=0, add_default_protocol=False)

Bases: GateSetTomographyDesign

Standard GST experiment design consisting of germ-powers sandwiched between fiducials.

Parameters
  • processorspec_filename_or_obj (QubitProcessorSpec or str) – The processor API used by this experiment design.

  • prep_fiducial_list_or_filename (list or str) – A list of preparation fiducial :class:`Circuit`s or the path to a filename containing them.

  • meas_fiducial_list_or_filename (list or str) – A list of measurement fiducial :class:`Circuit`s or the path to a filename containing them.

  • germ_list_or_filename (list or str) – A list of germ :class:`Circuit`s or the path to a filename containing them.

  • max_lengths (list) – List of integers, one per LSGST iteration, which set truncation lengths for repeated germ strings. The list of circuits for the i-th LSGST iteration includes the repeated germs truncated to the L-values up to and including the i-th one.

  • germ_length_limits (dict, optional) – A dictionary limiting the max-length values used for specific germs. Keys are germ sequences and values are integers. For example, if this argument is {(‘Gx’,): 4} and max_length_list = [1,2,4,8,16], then the germ (‘Gx’,) is only repeated using max-lengths of 1, 2, and 4 (whereas other germs use all the values in max_length_list).

  • fiducial_pairs (list of 2-tuples or dict, optional) – Specifies a subset of all fiducial string pairs (prepStr, effectStr) to be used in the circuit lists. If a list, each element of fid_pairs is a (iPrepStr, iEffectStr) 2-tuple of integers, each indexing a string within prep_strs and effect_strs, respectively, so that prepStr = prep_strs[iPrepStr] and effectStr = effect_strs[iEffectStr]. If a dictionary, keys are germs (elements of germ_list) and values are lists of 2-tuples specifying the pairs to use for that germ.

  • keep_fraction (float, optional) – The fraction of fiducial pairs selected for each germ-power base string. The default includes all fiducial pairs. Note that for each germ-power the selected pairs are different random sets of all possible pairs (unlike fid_pairs, which specifies the same fiducial pairs for all same-germ base strings). If fid_pairs is used in conjuction with keep_fraction, the pairs specified by fid_pairs are always selected, and any additional pairs are randomly selected.

  • keep_seed (int, optional) – The seed used for random fiducial pair selection (only relevant when keep_fraction < 1).

  • include_lgst (boolean, optional) – If true, then the starting list (only applicable when nest == True) is the list of LGST strings rather than the empty list. This means that when nest == True, the LGST sequences will be included in all the lists.

  • nest (boolean, optional) – If True, the GST circuit lists are “nested”, meaning that each successive list of circuits contains all the gate strings found in previous lists (and usually some additional new ones). If False, then the returned circuit list for maximum length == L contains only those circuits specified in the description above, and not those for previous values of L.

  • circuit_rules (list, optional) – A list of (find,replace) 2-tuples which specify circuit-label replacement rules. Both find and replace are tuples of operation labels (or Circuit objects).

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. This information is stored within the returned circuit structures. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • dscheck (DataSet, optional) – A data set which filters the circuits used for GST. When a standard-GST circuit is missing from this DataSet, action is taken according to action_if_missing.

  • action_if_missing ({"raise","drop"}, optional) – The action to take when a desired circuit is missing from dscheck (only relevant when dscheck is not None). “raise” causes a ValueError to be raised; “drop” causes the missing sequences to be dropped from the returned set.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

  • verbosity (int, optional) – The level of output to print to stdout.

  • add_default_protocol (bool, optional) – Whether a default StandardGST protocol should be added to this experiment design. Setting this to True makes it easy to analyze the data (after it’s gathered) corresponding to this design via a DefaultRunner.

copy_with_maxlengths(self, max_lengths, germ_length_limits=None, dscheck=None, action_if_missing='raise', verbosity=0)

Copies this GST experiment design to one with the same data except a different set of maximum lengths.

Parameters
  • max_lengths_to_keep (list) – A list of the maximum lengths that should be present in the returned experiment design.

  • germ_length_limits (dict, optional) – A dictionary limiting the max-length values to keep for specific germs. Keys are germ sequences and values are integers. If None, then the current length limits are used.

  • dscheck (DataSet, optional) – A data set which filters the circuits used for GST. When a standard-GST circuit is missing from this DataSet, action is taken according to action_if_missing.

  • action_if_missing ({"raise","drop"}, optional) – The action to take when a desired circuit is missing from dscheck (only relevant when dscheck is not None). “raise” causes a ValueError to be raised; “drop” causes the missing sequences to be dropped from the returned set.

  • -------

  • StandardGSTDesign

class pygsti.protocols.GSTInitialModel(model=None, target_model=None, starting_point=None, depolarize_start=0, randomize_start=0, lgst_gaugeopt_tol=1e-06, contract_start_to_cptp=False)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

Specification of a starting point for GST.

Parameters
  • model (Model, optional) – The model to start at, given explicitly.

  • starting_point ({"target", "User-supplied-Model", "LGST", "LGST-if-possible"}, optional) – The starting point type. If None, then defaults to “User-supplied-Model” if model is given, otherwise to “target”.

  • depolarize_start (float, optional) – Amount to depolarize the starting model just prior to running GST.

  • randomize_start (float, optional) – Amount to randomly kick the starting model just prior to running GST.

  • lgst_gaugeopt_tol (float, optional) – Gauge-optimization tolerance for the post-LGST gauge optimization that is performed when starting_point == “LGST” or possibly when “starting_point == “LGST-if-possible”.

  • contract_start_to_cptp (bool, optional) – Whether the Model should be forced (“contracted”) to being CPTP just prior to running GST.

classmethod cast(cls, obj)

Cast obj to a GSTInitialModel object.

Parameters

obj (object) – object to cast. Can be a GSTInitialModel (naturally) or a Model.

Returns

GSTInitialModel

retrieve_model(self, edesign, gaugeopt_target, dataset, comm)

Retrieve the starting-point Model used to seed a long-sequence GST run.

Parameters
  • edesign (ExperimentDesign) – The experiment design containing the circuits being used, the qubit labels, and (possibly) a target model (for use when starting_point == “target”) and fiducial circuits (for LGST).

  • gaugeopt_target (Model) – The gauge-optimization target, i.e. distance to this model is the objective function within the post-LGST gauge-optimization step.

  • dataset (DataSet) – Data used to execute LGST when needed.

  • comm (mpi4py.MPI.Comm) – A MPI communicator to divide workload amoung multiple processors.

Returns

Model

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
class pygsti.protocols.GSTBadFitOptions(threshold=DEFAULT_BAD_FIT_THRESHOLD, actions=(), wildcard_budget_includes_spam=True, wildcard_L1_weights=None, wildcard_primitive_op_labels=None, wildcard_initial_budget=None, wildcard_methods=('neldermead',), wildcard_inadmissable_action='print')

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

Options for post-processing a GST fit that was unsatisfactory.

Parameters
  • threshold (float, optional) – A threshold, given in number-of-standard-deviations, below which a GST fit is considered satisfactory (and no “bad-fit” processing is needed).

  • actions (tuple, optional) – Actions to take when a GST fit is unsatisfactory.

  • wildcard_budget_includes_spam (bool, optional) – Include a SPAM budget within the wildcard budget used to process the “wildcard” action.

classmethod cast(cls, obj)

Cast obj to a GSTBadFitOptions object.

Parameters

obj (object) – Object to cast. Can be a GSTBadFitOptions (naturally) or a dictionary of constructor arguments.

Returns

GSTBadFitOptions

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
class pygsti.protocols.GSTObjFnBuilders(iteration_builders, final_builders=())

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

Holds the objective-function builders needed for long-sequence GST.

Parameters
  • iteration_builders (list or tuple) – A list of ObjectiveFunctionBuilder objects used (sequentially) on each GST iteration.

  • final_builders (list or tuple, optional) – A list of ObjectiveFunctionBuilder objects used (sequentially) on the final GST iteration.

classmethod cast(cls, obj)

Cast obj to a GSTObjFnBuilders object.

Parameters

obj (object) – Object to cast. Can be a GSTObjFnBuilders (naturally), a dictionary of :method:`create_from` arguments (or None), or a list or tuple of the (iteration_builders, final_builders) constructor arguments.

Returns

GSTObjFnBuilders

classmethod create_from(cls, objective='logl', freq_weighted_chi2=False, always_perform_mle=False, only_perform_mle=False)

Creates a common GSTObjFnBuilders object from several arguments.

Parameters
  • objective ({'logl', 'chi2'}, optional) – Whether to create builders for maximum-likelihood or minimum-chi-squared GST.

  • freq_weighted_chi2 (bool, optional) – Whether chi-squared objectives use frequency-weighting. If you’re not sure what this is, leave it as False.

  • always_perform_mle (bool, optional) – Perform a ML-GST step on each iteration (usually this is only done for the final iteration).

  • only_perform_mle (bool, optional) – Only perform a ML-GST step on each iteration, i.e. do not perform any chi2 minimization to “seed” the ML-GST step.

Returns

GSTObjFnBuilders

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
class pygsti.protocols.GSTGaugeOptSuite(gaugeopt_suite_names=None, gaugeopt_argument_dicts=None, gaugeopt_target=None)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

Holds directives to perform one or more gauge optimizations on a model.

Usually this gauge optimization is done after fitting a parameterized model to data (e.g. after GST), as the data cannot (by definition) prefer any particular gauge choice.

Parameters
  • gaugeopt_suite_names (str or list of strs, optional) –

    Names one or more gauge optimization suites to perform. A string or list of strings (see below) specifies built-in sets of gauge optimizations. The built-in suites are:

    • ”single” : performs only a single “best guess” gauge optimization.

    • ”varySpam” : varies spam weight and toggles SPAM penalty (0 or 1).

    • ”varySpamWt” : varies spam weight but no SPAM penalty.

    • ”varyValidSpamWt” : varies spam weight with SPAM penalty == 1.

    • ”toggleValidSpam” : toggles spame penalty (0 or 1); fixed SPAM wt.

    • ”unreliable2Q” : adds branch to a spam suite that weights 2Q gates less

    • ”none” : no gauge optimizations are performed.

  • gaugeopt_argument_dicts (dict, optional) – A dictionary whose string-valued keys label different gauge optimizations (e.g. within a resulting Estimate object). Each corresponding value can be either a dictionary of arguments to gaugeopt_to_target() or a list of such dictionaries which then describe the different stages of a multi-stage gauge optimization.

  • gaugeopt_target (Model, optional) – If not None, a model to be used as the “target” for gauge- optimization (only). This argument is useful when you want to gauge optimize toward something other than the ideal target gates given by the target model, which are used as the default when gaugeopt_target is None.

classmethod cast(cls, obj)
is_empty(self)

Whether this suite is completely empty, i.e., contains NO gauge optimization instructions.

This is a useful check before constructing quantities needed by gauge optimization, e.g. a target model, which can just be skipped when no gauge optimization will be performed.

Returns

bool

to_dictionary(self, model, unreliable_ops=(), verbosity=0)

Converts this gauge optimization suite into a raw dictionary of dictionaries.

Constructs a dictionary of gauge-optimization parameter dictionaries based on “gauge optimization suite” name(s).

This essentially renders the gauge-optimization directives within this object in an “expanded” form for either running gauge optimization (e.g. within a :method:`GateSetTomography.run` call) or for constructing the would-be gauge optimization call arguments so they can be slightly modeified before passing them in as the actual gauge-optimization suite used in an analysis (the resulting dictionary can be used to initialize a new GSTGaugeOptSuite object via the gaugeopt_argument_dicts argument.

Parameters
  • model (Model) – A model which specifies the dimension (i.e. parameterization) of the gauge-optimization and the basis. Typically the model that is optimized or the ideal model using the same parameterization and having the correct default-gauge-group as the model that is optimized.

  • unreliable_ops (tuple, optional) – A tuple of gate (or circuit-layer) labels that count as “unreliable operations”. Typically these are the multi-qubit (2-qubit) gates.

  • verbosity (int) – The verbosity to attach to the various gauge optimization parameter dictionaries.

Returns

dict – A dictionary whose keys are the labels of the different gauge optimizations to perform and whose values are the corresponding dictionaries of arguments to gaugeopt_to_target() (or lists of such dictionaries for a multi-stage gauge optimization).

_update_gaugeopt_dict_from_suitename(self, gaugeopt_suite_dict, root_lbl, suite_name, model, unreliable_ops, printer)
__getstate__(self)
_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
class pygsti.protocols.GateSetTomography(initial_model=None, gaugeopt_suite='stdgaugeopt', objfn_builders=None, optimizer=None, badfit_options=None, verbosity=2, name=None)

Bases: pygsti.protocols.protocol.Protocol

The core gate set tomography protocol, which optimizes a parameterized model to (best) fit a data set.

Parameters
  • initial_model (Model or GSTInitialModel, optional) – The starting-point Model.

  • gaugeopt_suite (GSTGaugeOptSuite, optional) – Specifies which gauge optimizations to perform on each estimate. Can also be any object that can be cast to a GSTGaugeOptSuite object, such as a string or list of strings (see below) specifying built-in sets of gauge optimizations. This object also optionally stores an alternate target model for gauge optimization. This model is used as the “target” for gauge- optimization (only), and is useful when you want to gauge optimize toward something other than the ideal target gates.

  • objfn_builders (GSTObjFnBuilders, optional) – The objective function(s) to optimize. Can also be anything that can be cast to a GSTObjFnBuilders object.

  • optimizer (Optimizer, optional) – The optimizer to use. Can also be anything that can be cast to a Optimizer.

  • badfit_options (GSTBadFitOptions, optional) – Options specifying what post-processing actions should be performed if the GST fit is unsatisfactory. Can also be anything that can be cast to a GSTBadFitOptions object.

  • verbosity (int, optional) – The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

ModelEstimateResults

class pygsti.protocols.LinearGateSetTomography(target_model=None, gaugeopt_suite='stdgaugeopt', badfit_options=None, verbosity=2, name=None)

Bases: pygsti.protocols.protocol.Protocol

The linear gate set tomography protocol.

Parameters
  • target_model (Model, optional) – The target (ideal) model.

  • gaugeopt_suite (GSTGaugeOptSuite, optional) – Specifies which gauge optimizations to perform on each estimate. Can also be any object that can be cast to a GSTGaugeOptSuite object, such as a string or list of strings (see below) specifying built-in sets of gauge optimizations. This object also optionally stores an alternate target model for gauge optimization. This model is used as the “target” for gauge- optimization (only), and is useful when you want to gauge optimize toward something other than the ideal target gates.

  • badfit_options (GSTBadFitOptions, optional) – Options specifying what post-processing actions should be performed if the LGST fit is unsatisfactory. Can also be anything that can be cast to a GSTBadFitOptions object.

  • verbosity (int, optional) – The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

check_if_runnable(self, data)

Raises a ValueError if LGST cannot be run on data

Parameters

data (ProtocolData) – The experimental data to test for LGST-compatibility.

Returns

None

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

ModelEstimateResults

class pygsti.protocols.StandardGST(modes='full TP,CPTP,Target', gaugeopt_suite='stdgaugeopt', models_to_test=None, objfn_builders=None, optimizer=None, badfit_options=None, verbosity=2, name=None)

Bases: pygsti.protocols.protocol.Protocol

The standard-practice GST protocol.

Parameters
  • modes (str, optional) –

    A comma-separated list of modes which dictate what types of analyses are performed. Currently, these correspond to different types of parameterizations/constraints to apply to the estimated model. The default value is usually fine. Allowed values are:

    • ”full” : full (completely unconstrained)

    • ”TP” : TP-constrained

    • ”CPTP” : Lindbladian CPTP-constrained

    • ”H+S” : Only Hamiltonian + Stochastic errors allowed (CPTP)

    • ”S” : Only Stochastic errors allowed (CPTP)

    • ”Target” : use the target (ideal) gates as the estimate

    • <model> : any key in the models_to_test argument

  • gaugeopt_suite (GSTGaugeOptSuite, optional) – Specifies which gauge optimizations to perform on each estimate. Can also be any object that can be cast to a GSTGaugeOptSuite object, such as a string or list of strings (see below) specifying built-in sets of gauge optimizations. This object also optionally stores an alternate target model for gauge optimization. This model is used as the “target” for gauge- optimization (only), and is useful when you want to gauge optimize toward something other than the ideal target gates.

  • models_to_test (dict, optional) – A dictionary of Model objects representing (gate-set) models to test against the data. These Models are essentially hypotheses for which (if any) model generated the data. The keys of this dictionary can (and must, to actually test the models) be used within the comma- separate list given by the modes argument.

  • objfn_builders (GSTObjFnBuilders, optional) – The objective function(s) to optimize. Can also be anything that can be cast to a GSTObjFnBuilders object. Applies to all modes.

  • optimizer (Optimizer, optional) – The optimizer to use. Can also be anything that can be case to a Optimizer. Applies to all modes.

  • badfit_options (GSTBadFitOptions, optional) – Options specifying what post-processing actions should be performed if the GST fit is unsatisfactory. Can also be anything that can be cast to a GSTBadFitOptions object. Applies to all modes.

  • verbosity (int, optional) – The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

ProtocolResults

pygsti.protocols._load_pspec(processorspec_filename_or_obj)
pygsti.protocols._load_model(model_filename_or_obj)
pygsti.protocols._load_pspec_or_model(processorspec_or_model_filename_or_obj)
pygsti.protocols._load_fiducials_and_germs(prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, germ_list_or_filename)
pygsti.protocols._load_dataset(data_filename_or_set, comm, verbosity)

Loads a DataSet from the data_filename_or_set argument of functions in this module.

pygsti.protocols._add_gaugeopt_and_badfit(results, estlbl, target_model, gaugeopt_suite, unreliable_ops, badfit_options, optimizer, resource_alloc, printer)
pygsti.protocols._add_gauge_opt(results, base_est_label, gaugeopt_suite, starting_model, unreliable_ops, comm=None, verbosity=0)

Add a gauge optimization to an estimate.

Parameters
  • results (ModelEstimateResults) – The parent results of the estimate to add a gauge optimization to. The estimate is specified via results and base_est_label rather than just passing an Estimate directly so that related (e.g. bad-fit) estimates can also be updated.

  • base_est_label (str) – The key within results.estimates of the primary Estimate to update.

  • gaugeopt_suite (GSTGaugeOptSuite, optional) – Specifies which gauge optimizations to perform on each estimate. Can also be any object that can be cast to a GSTGaugeOptSuite object, such as a string or list of strings (see below) specifying built-in sets of gauge optimizations. This object also optionally stores an alternate target model for gauge optimization. This model specifies the ideal gates and the default gauge group to optimize over (this should be set prior to calling this function).

  • starting_model (Model) – The starting model of the GST or GST-like protocol. This communicates the parameterization that is available to gauge optimize over, and helps interpret gauge-optimization-suite names (e.g. “stdgaugeopt” produces different steps based on the parameterization of starting_model).

  • unreliable_ops (tuple, optional) – A tuple of gate (or circuit-layer) labels that count as “unreliable operations”. Typically these are the multi-qubit (2-qubit) gates.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run computations in parallel.

  • verbosity (int, optional) – The level of detail printed to stdout.

Returns

None

pygsti.protocols._add_badfit_estimates(results, base_estimate_label, badfit_options, optimizer=None, resource_alloc=None, verbosity=0)

Add any and all “bad fit” estimates to results.

Parameters
  • results (ModelEstimateResults) – The results to add bad-fit estimates to.

  • base_estimate_label (str) – The primary estimate label to base bad-fit additions off of.

  • badfit_options (GSTBadFitOptions) – The options specifing what constitutes a “bad fit” and what actions to take when one occurs.

  • optimizer (Optimizer) – The optimizer to perform re-optimization, if any is needed.

  • resource_alloc (ResourceAllocation, optional) – What resources are available and how they should be distributed.

  • verbosity (int, optional) – Level of detail printed to stdout.

Returns

None

pygsti.protocols._compute_robust_scaling(scale_typ, objfn_cache, mdc_objfn)

Get the per-circuit data scaling (“weights”) for a given type of robust-data-scaling. TODO: update docstring

Parameters
  • scale_typ ({'robust', 'robust+', 'Robust', 'Robust+'}) – The type of robust scaling. Captial vs. lowercase “R” doesn’t matter to this function (it indicates whether a post-scaling re-optimization is performed elsewhere). The “+” postfix distinguishes a “version 1” scaling (no “+”), where we drastically scale down weights of especially bad sequences, from a “version 2” scaling (“+”), where we additionaly rescale all the circuit data to achieve the desired chi2 distribution of per-circuit goodness-of-fit values without reordering these values.

  • model (Model) – The final model fit.

  • ds (DataSet) – The data set to compare to the model predictions.

  • circuit_list (list) – A list of the :class:`Circuit`s whose data should be compared.

  • parameters (dict) – Various parameters of the estimate at hand.

  • comm (mpi4py.MPI.Comm, optional) – An MPI communicator used to run this computation in parallel.

  • mem_limit (int, optional) – A rough per-processor memory limit in bytes.

Returns

dict – A dictionary of circuit weights. Keys are cirrcuits and values are scaling factors that should be applied to the data counts for that circuit. Omitted circuits should not be scaled.

pygsti.protocols._compute_wildcard_budget(objfn_cache, mdc_objfn, parameters, badfit_options, verbosity)

Create a wildcard budget for a model estimate. TODO: update docstring

Parameters
  • model (Model) – The model to add a wildcard budget to.

  • ds (DataSet) – The data the model predictions are being compared with.

  • circuits_to_use (list) – The circuits whose data are compared.

  • parameters (dict) – Various parameters of the estimate at hand.

  • badfit_options (GSTBadFitOptions, optional) – Options specifying what post-processing actions should be performed when a fit is unsatisfactory. Contains detailed parameters for wildcard budget creation.

  • comm (mpi4py.MPI.Comm, optional) – An MPI communicator used to run this computation in parallel.

  • mem_limit (int, optional) – A rough per-processor memory limit in bytes.

  • verbosity (int, optional) – Level of detail printed to stdout.

Returns

PrimitiveOpsWildcardBudget

pygsti.protocols._reoptimize_with_weights(mdc_objfn, circuit_weights_dict, optimizer, verbosity)

Re-optimize a model after data counts have been scaled by circuit weights. TODO: update docstring

Parameters
  • model (Model) – The model to re-optimize.

  • ds (DataSet) – The data set to compare againts.

  • circuit_list (list) – The circuits for which data and predictions should be compared.

  • circuit_weights_dict (dict) – A dictionary of circuit weights, such as that returned by :function:`_compute_robust_scaling`, giving the data-count scaling factors.

  • objfn_builder (ObjectiveFunctionBuilder) – The objective function (builder) that represents the final stage of optimization. This defines what objective function is minimized in this re-optimization.

  • optimizer (Optimizer) – The optimizer to use.

  • resource_alloc (ResourceAllocation, optional) – What resources are available and how they should be distributed.

  • verbosity (int, optional) – Level of detail printed to stdout.

Returns

Model – The re-optimized model, potentially the same object as model.

class pygsti.protocols.ModelEstimateResults(data, protocol_instance, init_circuits=True)

Bases: pygsti.protocols.protocol.ProtocolResults

A results object that holds model estimates.

Parameters
  • data (ProtocolData) – The experimental data these results are generated from.

  • protocol_instance (Protocol) – The protocol that generated these results.

  • init_circuits (bool, optional) – Whether self.circuit_lists should be initialized or not. (In special cases, this can be disabled for speed.)

dataset

The underlying data set.

Type

DataSet

classmethod from_dir(cls, dirname, name, preloaded_data=None, quick_load=False)

Initialize a new ModelEstimateResults object from dirname / results / name.

Parameters
  • dirname (str) – The root directory name (under which there is are ‘edesign’, ‘data’, and ‘results’ subdirectories).

  • name (str) – The sub-directory name of the particular results object to load (there can be multiple under a given root dirname). This is the name of a subdirectory of dirname / results.

  • preloaded_data (ProtocolData, optional) – In the case that the ProtocolData object for dirname is already loaded, it can be passed in here. Otherwise leave this as None and it will be loaded.

  • quick_load (bool, optional) – Setting this to True skips the loading of data and experiment-design components that may take a long time to load. This can be useful all the information of interest lies only within the results object.

Returns

ModelEstimateResults

_create_circuit_lists(self, edesign)
property dataset(self)

The underlying data set.

to_nameddict(self)

Convert these results into nested NamedDict objects.

Returns

NamedDict

add_estimates(self, results, estimates_to_add=None)

Add some or all of the estimates from results to this Results object.

Parameters
  • results (Results) – The object to import estimates from. Note that this object must contain the same data set and gate sequence information as the importing object or an error is raised.

  • estimates_to_add (list, optional) – A list of estimate keys to import from results. If None, then all the estimates contained in results are imported.

Returns

None

rename_estimate(self, old_name, new_name)

Rename an estimate in this Results object.

Ordering of estimates is not changed.

Parameters
  • old_name (str) – The labels of the estimate to be renamed

  • new_name (str) – The new name for the estimate.

Returns

None

add_estimate(self, estimate, estimate_key='default')

Add a set of Model estimates to this Results object.

Parameters
  • estimate (Estimate) – The estimate to add.

  • estimate_key (str, optional) – The key or label used to identify this estimate.

Returns

None

add_model_test(self, target_model, themodel, estimate_key='test', gaugeopt_keys='auto')

Add a new model-test (i.e. non-optimized) estimate to this Results object.

Parameters
  • target_model (Model) – The target model used for comparison to the model.

  • themodel (Model) – The “model” model whose fit to the data and distance from target_model are assessed.

  • estimate_key (str, optional) – The key or label used to identify this estimate.

  • gaugeopt_keys (list, optional) – A list of gauge-optimization keys to add to the estimate. All of these keys will correspond to trivial gauge optimizations, as the model model is assumed to be fixed and to have no gauge degrees of freedom. The special value “auto” creates gauge-optimized estimates for all the gauge optimization labels currently in this Results object.

Returns

None

view(self, estimate_keys, gaugeopt_keys=None)

Creates a shallow copy of this Results object containing only the given estimate.

This function an also filter based on gauge-optimization keys, only keeping a subset of those available.

Parameters
  • estimate_keys (str or list) – Either a single string-value estimate key or a list of such keys.

  • gaugeopt_keys (str or list, optional) – Either a single string-value gauge-optimization key or a list of such keys. If None, then all gauge-optimization keys are retained.

Returns

Results

copy(self)

Creates a copy of this ModelEstimateResults object.

Returns

ModelEstimateResults

__setstate__(self, state_dict)
__str__(self)

Return str(self).

pygsti.protocols.GSTDesign
pygsti.protocols.GST
pygsti.protocols.LGST
class pygsti.protocols._DummyProfiler

Bases: object

A dummy profiler that doesn’t do anything.

A class which implements the same interface as Profiler but which doesn’t actually do any profiling (consists of stub functions).

add_time(self, name, start_time, prefix=0)

Stub function that does nothing

Parameters
  • name (string) – The name of the timer to add elapsed time into (if the name doesn’t exist, one is created and initialized to the elapsed time).

  • start_time (float) – The starting time used to compute the elapsed, i.e. the value time.time()-start_time, which is added to the named timer.

  • prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.

Returns

None

add_count(self, name, inc=1, prefix=0)

Stub function that does nothing

Parameters
  • name (string) – The name of the counter to add val into (if the name doesn’t exist, one is created and initialized to val).

  • inc (int, optional) – The increment (the value to add to the counter).

  • prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.

Returns

None

memory_check(self, name, printme=None, prefix=0)

Stub function that does nothing

Parameters
  • name (string) – The name of the memory checkpoint. (Later, memory information can be organized by checkpoint name.)

  • printme (bool, optional) – Whether or not to print the memory usage during this function call (if None, the default, then the value of default_print_memcheck specified during Profiler construction is used).

  • prefix (int, optional) – Prefix to the timer name the current stack depth and this number of function names, starting with the current function and moving the call stack. When zero, no prefix is added. For example, with prefix == 1, “Total” might map to ” 3: myFunc: Total”.

Returns

None

class pygsti.protocols._ModelDatasetCircuitStore(model, dataset, circuits=None, resource_alloc=None, array_types=(), precomp_layout=None, verbosity=0)

Bases: object

Contains all the information that we’d like to persist when performing (multiple) evaluations of the same circuits using the same model and data set. For instance, the evaluation of mubltiple (different) objective functions.

This class holds only quantities that do not depend on the contained model’s parameters. See EvaluatedObjectiveFunction for a class (TODO??) that holds the values of an objective function at a certain parameter-space point.

property opBasis(self)
num_data_params(self)

The number of degrees of freedom in the data used by this objective function.

Returns

int

add_omitted_freqs(self, printer=None, force=False)

Detect omitted frequences (assumed to be 0) so we can compute objective fn correctly

add_count_vectors(self, force=False)

Ensure this store contains count and total-count vectors.

class pygsti.protocols._Estimate(parent, models=None, parameters=None, extra_parameters=None)

Bases: object

A class encapsulating the Model objects related to a single GST estimate up-to-gauge freedoms.

Thus, this class holds the “iteration” Model`s leading up to a final `Model, and then different gauge optimizations of the final set.

Parameters
  • parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.

  • models (dict, optional) – A dictionary of models to included in this estimate

  • parameters (dict, optional) – A dictionary of parameters associated with how these models were obtained.

classmethod from_dir(cls, dirname, quick_load=False)

Initialize a new Protocol object from dirname.

quick_loadbool, optional

Setting this to True skips the loading of components that may take a long time to load.

Parameters
  • dirname (str) – The directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load.

Returns

Protocol

classmethod create_gst_estimate(cls, parent, target_model=None, seed_model=None, models_by_iter=None, parameters=None)

Initialize an empty Estimate object.

Parameters
  • parent (Results) – The parent Results object containing the dataset and circuit structure used for this Estimate.

  • target_model (Model) – The target model used when optimizing the objective.

  • seed_model (Model) – The initial model used to seed the iterative part of the objective optimization. Typically this is obtained via LGST.

  • models_by_iter (list of Models) – The estimated model at each GST iteration. Typically these are the estimated models before any gauge optimization is performed.

  • parameters (dict) – A dictionary of parameters associated with how these models were obtained.

Returns

Estimate

property parameters(self)
property goparameters(self)
write(self, dirname)

Write this protocol to a directory.

Parameters

dirname (str) – The directory name to write. This directory will be created if needed, and the files in an existing directory will be overwritten.

Returns

None

retrieve_start_model(self, goparams)

Returns the starting model for the gauge optimization given by goparams.

This has a particular (and perhaps singular) use for deciding whether the gauge-optimized model for one estimate can be simply copied to another estimate, without actually re-gauge-optimizing.

Parameters

goparams (dict or list) – A dictionary of gauge-optimization parameters, just as in add_gaugeoptimized().

Returns

Model

add_gaugeoptimized(self, goparams, model=None, label=None, comm=None, verbosity=None)

Adds a gauge-optimized Model (computing it if needed) to this object.

Parameters
  • goparams (dict or list) – A dictionary of gauge-optimization parameters, typically arguments to gaugeopt_to_target(), specifying how the gauge optimization was (or should be) performed. When model is None (and this function computes the model internally) the keys and values of this dictionary must correspond to allowed arguments of gaugeopt_to_target(). By default, gaugeopt_to_target()’s first two arguments, the Model to optimize and the target, are taken to be self.models[‘final iteration estimate’] and self.models[‘target’]. This argument can also be a list of such parameter dictionaries, which specifies a multi-stage gauge- optimization whereby the output of one stage is the input of the next.

  • model (Model, optional) – The gauge-optimized model to store. If None, then this model is computed by calling gaugeopt_to_target() with the contents of goparams as arguments as described above.

  • label (str, optional) – A label for this gauge-optimized model, used as the key in this object’s models and goparameters member dictionaries. If None, then the next available “go<X>”, where <X> is a non-negative integer, is used as the label.

  • comm (mpi4py.MPI.Comm, optional) – A default MPI communicator to use when one is not specified as the ‘comm’ element of/within goparams.

  • verbosity (int, optional) – An integer specifying the level of detail printed to stdout during the calculations performed in this function. If not None, this value will override any verbosity values set within goparams.

Returns

None

add_confidence_region_factory(self, model_label='final iteration estimate', circuits_label='final')

Creates a new confidence region factory.

An instance of ConfidenceRegionFactory serves to create confidence intervals and regions in reports and elsewhere. This function creates such a factory, which is specific to a given Model (given by this object’s .models[model_label] ) and circuit list (given by the parent Results’s .circuit_lists[gastrings_label] list).

Parameters
  • model_label (str, optional) – The label of a Model held within this Estimate.

  • circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.

Returns

ConfidenceRegionFactory – The newly created factory (also cached internally) and accessible via the create_confidence_region_factory() method.

has_confidence_region_factory(self, model_label='final iteration estimate', circuits_label='final')

Checks whether a confidence region factory for the given model and circuit list labels exists.

Parameters
  • model_label (str, optional) – The label of a Model held within this Estimate.

  • circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.

Returns

bool

create_confidence_region_factory(self, model_label='final iteration estimate', circuits_label='final', create_if_needed=False)

Retrieves a confidence region factory for the given model and circuit list labels.

For more information about confidence region factories, see add_confidence_region_factory().

Parameters
  • model_label (str, optional) – The label of a Model held within this Estimate.

  • circuits_label (str, optional) – The label of a circuit list within this estimate’s parent Results object.

  • create_if_needed (bool, optional) – If True, a new confidence region factory will be created if none exists. Otherwise a KeyError is raised when the requested factory doesn’t exist.

Returns

ConfidenceRegionFactory

gauge_propagate_confidence_region_factory(self, to_model_label, from_model_label='final iteration estimate', circuits_label='final', eps=0.001, verbosity=0)

Propagates a confidence region among gauge-equivalent models.

More specifically, this function propagates an existing “reference” confidence region for a Model “G0” to a new confidence region for a gauge-equivalent model “G1”.

When successful, a new confidence region factory is created for the .models[to_model_label] Model and circuits_label gate string list from the existing factory for .models[from_model_label].

Parameters
  • to_model_label (str) – The key into this Estimate object’s models and goparameters dictionaries that identifies the final gauge-optimized result to create a factory for. This gauge optimization must have begun at “from” reference model, i.e., models[from_model_label] must equal (by frobeinus distance) goparameters[to_model_label][‘model’].

  • from_model_label (str, optional) – The key into this Estimate object’s models dictionary that identifies the reference model.

  • circuits_label (str, optional) – The key of the circuit list (within the parent Results’s .circuit_lists dictionary) that identifies the circuit list used by the old (&new) confidence region factories.

  • eps (float, optional) – A small offset used for constructing finite-difference derivatives. Usually the default value is fine.

  • verbosity (int, optional) – A non-negative integer indicating the amount of detail to print to stdout.

Returns

ConfidenceRegionFactory – Note: this region is also stored internally and as such the return value of this function can often be ignored.

create_effective_dataset(self, return_submxs=False)

Generate a DataSet containing the effective counts as dictated by the “weights” parameter.

An estimate’s self.parameters[‘weights’] value specifies a dictionary of circuits weights, which modify (typically reduce) the counts given in its (parent’s) data set.

This function rescales the actual data contained in this Estimate’s parent ModelEstimteResults object according to the estimate’s “weights” parameter. The scaled data set is returned, along with (optionall) a list-of-lists of matrices containing the scaling values which can be easily plotted via a ColorBoxPlot.

Parameters

return_submxs (boolean) – If true, also return a list-of-lists of matrices containing the scaling values, as described above.

Returns

  • ds (DataSet) – The “effective” (scaled) data set.

  • subMxs (list-of-lists) – Only returned if return_submxs == True. Contains the scale values (see above).

final_mdc_store(self, resource_alloc=None, array_types=('e', 'ep'))

The final (not intermediate) model-dataset-circuit storage object (MDC store) for this estimate.

This object is created and cached as needed, and combined the final model, data set, and circuit list for this estimate.

Parameters
  • resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store. This can just be left as None unless multiple processors are being utilized. Note that this argument is only used when a MDC store needs to be created – if this estimate has already created one then this argument is ignored.

  • array_types (tuple) – A tuple of array types passed to the MDC store constructor (if a new MDC store needs to be created). These affect how memory is allocated within the MDC store object and can enable (or disable) the use of certain MDC store functionality later on (e.g. the use of Jacobian or Hessian quantities).

Returns

ModelDatasetCircuitsStore

final_objective_fn(self, resource_alloc=None)

The final (not intermediate) objective function object for this estimate.

This object is created and cached as needed, and is the evaluated (and sometimes optimized) objective function associated with this estimate. Often this is a log-likelihood or chi-squared function, or a close variant.

Parameters

resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store underlying the objective function. This can just be left as None unless multiple processors are being utilized. Note that this argument is only used when an underlying MDC store needs to be created – if this estimate has already created a MDC store then this argument is ignored.

Returns

MDCObjectiveFunction

final_objective_fn_cache(self, resource_alloc=None)

The final (not intermediate) serializable (“cached”) objective function object for this estimate.

This is an explicitly serializable version of the final objective function, useful because is often doesn’t need be constructed. To become serializable, however, the objective function is stripped of any MPI comm or multi-processor information (since this may be different between loading and saving). This makes the cached objective function convenient for fast calls/usages of the objective function.

Parameters

resource_alloc (ResourceAllocation) – The resource allocation object used to create the MDC store underlying the objective function. This can just be left as None unless multiple processors are being utilized - and in this case the cached objective function doesn’t even benefit from these processors (but calls to :method:`final_objective_fn` will return an objective function setup for multiple processors). Note that this argument is only used when there is no existing cached objective function and an underlying MDC store needs to be created.

Returns

CachedObjectiveFunction

misfit_sigma(self, resource_alloc=None)

Returns the number of standard deviations (sigma) of model violation.

Parameters

resource_alloc (ResourceAllocation, optional) – What resources are available for this computation.

Returns

float

view(self, gaugeopt_keys, parent=None)

Creates a shallow copy of this Results object containing only the given gauge-optimization keys.

Parameters
  • gaugeopt_keys (str or list, optional) – Either a single string-value gauge-optimization key or a list of such keys. If None, then all gauge-optimization keys are retained.

  • parent (Results, optional) – The parent Results object of the view. If None, then the current Estimate’s parent is used.

Returns

Estimate

copy(self)

Creates a copy of this Estimate object.

Returns

Estimate

__str__(self)

Return str(self).

__getstate__(self)
__setstate__(self, state_dict)
set_parent(self, parent)

Sets the parent object of this estimate.

This is used, for instance, to re-establish parent-child links after loading objects from disk.

Parameters

parent (ModelEstimateResults) – This object’s parent.

Returns

None

class pygsti.protocols._CircuitList(circuits, op_label_aliases=None, circuit_weights=None, name=None)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

A unmutable list (a tuple) of Circuit objects and associated metadata.

Parameters
  • circuits (list) – The list of circuits that constitutes the primary data held by this object.

  • op_label_aliases (dict, optional) – Dictionary of circuit meta-data whose keys are operation label “aliases” and whose values are circuits corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined). e.g. op_label_aliases[‘Gx^3’] = pygsti.obj.Circuit([‘Gx’,’Gx’,’Gx’])

  • circuit_weights (numpy.ndarray, optional) – If not None, an array of per-circuit weights (of length equal to the number of circuits) that are typically used to multiply the counts extracted for each circuit.

  • name (str, optional) – An optional name for this list, used for status messages.

classmethod cast(cls, circuits)

Convert (if needed) an object into a CircuitList.

Parameters

circuits (list or CircuitList) – The object to convert.

Returns

CircuitList

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
__len__(self)
__getitem__(self, index)
__iter__(self)
apply_aliases(self)

Applies any operation-label aliases to this circuit list.

Returns

list – A list of :class:`Circuit`s.

truncate(self, circuits_to_keep)

Builds a new circuit list containing only a given subset.

This can be safer then just creating a new CircuitList because it preserves the aliases, etc., of this list.

Parameters

circuits_to_keep (list or set) – The circuits to retain in the returned circuit list.

Returns

CircuitList

truncate_to_dataset(self, dataset)

Builds a new circuit list containing only those elements in dataset.

Parameters

dataset (DataSet) – The dataset to check. Aliases are applied to the circuits in this circuit list before they are tested.

Returns

CircuitList

__hash__(self)

Return hash(self).

__eq__(self, other)

Return self==value.

__setstate__(self, state_dict)
class pygsti.protocols._ResourceAllocation(comm=None, mem_limit=None, profiler=None, distribute_method='default', allocated_memory=0)

Bases: object

Describes available resources and how they should be allocated.

This includes the number of processors and amount of memory, as well as a strategy for how computations should be distributed among them.

Parameters
  • comm (mpi4py.MPI.Comm, optional) – MPI communicator holding the number of available processors.

  • mem_limit (int, optional) – A rough per-processor memory limit in bytes.

  • profiler (Profiler, optional) – A lightweight profiler object for tracking resource usage.

  • distribute_method (str, optional) – The name of a distribution strategy.

classmethod cast(cls, arg)

Cast arg to a ResourceAllocation object.

If arg already is a ResourceAllocation instance, it just returned. Otherwise this function attempts to create a new instance from arg.

Parameters

arg (ResourceAllocation or dict) – An object that can be cast to a ResourceAllocation.

Returns

ResourceAllocation

build_hostcomms(self)
property comm_rank(self)

A safe way to get self.comm.rank (0 if self.comm is None)

property comm_size(self)

A safe way to get self.comm.size (1 if self.comm is None)

property is_host_leader(self)

True if this processors is the rank-0 “leader” of its host (node). False otherwise.

host_comm_barrier(self)

Calls self.host_comm.barrier() when self.host_comm is not None.

This convenience function provides an often-used barrier that follows code where a single “leader” processor modifies a memory block shared between all members of self.host_comm, and the other processors must wait until this modification is performed before proceeding with their own computations.

Returns

None

copy(self)

Copy this object.

Returns

ResourceAllocation

reset(self, allocated_memory=0)

Resets internal allocation counters to given values (defaults to zero).

Parameters

allocated_memory (int64) – The value to set the memory allocation counter to.

Returns

None

add_tracked_memory(self, num_elements, dtype='d')

Adds nelements * itemsize bytes to the total amount of allocated memory being tracked.

If the total (tracked) memory exceeds self.mem_limit a MemoryError exception is raised.

Parameters
  • num_elements (int) – The number of elements to track allocation of.

  • dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.

Returns

None

check_can_allocate_memory(self, num_elements, dtype='d')

Checks that allocating nelements doesn’t cause the memory limit to be exceeded.

This memory isn’t tracked - it’s just added to the current tracked memory and a MemoryError exception is raised if the result exceeds self.mem_limit.

Parameters
  • num_elements (int) – The number of elements to track allocation of.

  • dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.

Returns

None

temporarily_track_memory(self, num_elements, dtype='d')

Temporarily adds nelements to tracked memory (a context manager).

A MemoryError exception is raised if the tracked memory exceeds self.mem_limit.

Parameters
  • num_elements (int) – The number of elements to track allocation of.

  • dtype (numpy.dtype, optional) – The type of elements, needed to compute the number of bytes per element.

Returns

contextmanager

gather_base(self, result, local, slice_of_global, unit_ralloc=None, all_gather=False)

Gather or all-gather operation using local arrays and a unit resource allocation.

Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final to-be gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.

  • all_gather (bool, optional) – Whether the final result should be gathered on all the processors of this ResourceAllocation or just the root (rank 0) processor.

Returns

None

gather(self, result, local, slice_of_global, unit_ralloc=None)

Gather local arrays into a global result array potentially with a unit resource allocation.

Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final to-be gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.

The global array is only gathered on the root (rank 0) processor of this resource allocation.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, only needed on the root (rank 0) processor. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allgather(self, result, local, slice_of_global, unit_ralloc=None)

All-gather local arrays into global arrays on each processor, potentially using a unit resource allocation.

Similar to a normal MPI gather call, but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array, i.e., slice of the final to-be gathered array. So, when gathering the result, only processors with unit_ralloc.rank == 0 need to contribute to the gather operation.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by having multiple smaller gather operations in parallel instead of one large gather.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • slice_of_global (slice or numpy.ndarray) – The slice of result that local constitutes, i.e., in the end result[slice_of_global] = local. This may be a Python slice or a NumPy array of indices.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the gather operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allreduce_sum(self, result, local, unit_ralloc=None)

Sum local arrays on different processors, potentially using a unit resource allocation.

Similar to a normal MPI reduce call (with MPI.SUM type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the sum, only processors with unit_ralloc.rank == 0 contribute to the sum. This handles the case where simply summing the local contributions from all processors would result in over-counting because of multiple processors hold the same logical result (summand).

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being summed. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allreduce_sum_simple(self, local, unit_ralloc=None)

A simplified sum over quantities on different processors that doesn’t use shared memory.

The shared memory usage of :method:`allreduce_sum` can be overkill when just summing a single scalar quantity. This method provides a way to easily sum a quantity across all the processors in this ResourceAllocation object using a unit resource allocation.

Parameters
  • local (int or float) – The local (per-processor) value to sum.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local value, so that only the unit_ralloc.rank == 0 processors will contribute to the sum. If None, then it is assumed that each processor computes a logically different local value.

Returns

float or int – The sum of all local quantities, returned on all the processors.

allreduce_min(self, result, local, unit_ralloc=None)

Take elementwise min of local arrays on different processors, potentially using a unit resource allocation.

Similar to a normal MPI reduce call (with MPI.MIN type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the min operation, only processors with unit_ralloc.rank == 0 contribute.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.

Returns

None

allreduce_max(self, result, local, unit_ralloc=None)

Take elementwise max of local arrays on different processors, potentially using a unit resource allocation.

Similar to a normal MPI reduce call (with MPI.MAX type), but more easily integrates with a hierarchy of processor divisions, or nested comms, by taking a unit_ralloc argument. This is essentially another comm that specifies the groups of processors that have all computed the same local array. So, when performing the max operation, only processors with unit_ralloc.rank == 0 contribute.

Parameters
  • result (numpy.ndarray, possibly shared) – The destination “global” array, with the same shape as all the local arrays being operated on. This can be any shape (including any number of dimensions). When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, this array must be allocated as a shared array using this ralloc or a larger so that result is shared between all the processors for this resource allocation’s intra-host communicator. This allows a speedup when shared memory is used by distributing computation of result over each host’s processors and performing these sums in parallel.

  • local (numpy.ndarray) – The locally computed quantity. This can be a shared-memory array, but need not be.

  • unit_ralloc (ResourceAllocation, optional) – A resource allocation (essentially a comm) for the group of processors that all compute the same local result, so that only the unit_ralloc.rank == 0 processors will contribute to the sum operation. If None, then it is assumed that all processors compute different local results.

Returns

None

bcast(self, value, root=0)

Broadcasts a value from the root processor/host to the others in this resource allocation.

This is similar to a usual MPI broadcast, except it takes advantage of shared memory when it is available. When shared memory is being used, i.e. when this ResourceAllocation object has a nontrivial inter-host comm, then this routine places value in a shared memory buffer and uses the resource allocation’s inter-host communicator to broadcast the result from the root host to all the other hosts using all the processor on the root host in parallel (all processors with the same intra-host rank participate in a MPI broadcast).

Parameters
  • value (numpy.ndarray) – The value to broadcast. May be shared memory but doesn’t need to be. Only need to specify this on the rank root processor, other processors can provide any value for this argument (it’s unused).

  • root (int) – The rank of the processor whose value will be to broadcast.

Returns

numpy.ndarray – The broadcast value, in a new, non-shared-memory array.

__getstate__(self)
class pygsti.protocols.ModelTest(model_to_test, target_model=None, gaugeopt_suite=None, objfn_builder=None, badfit_options=None, set_trivial_gauge_group=True, verbosity=2, name=None)

Bases: pygsti.protocols.protocol.Protocol

A protocol that tests how well a model agrees with a given set of data.

Parameters
  • model_to_test (Model) – The model to compare with data when :method:`run` is called.

  • target_model (Model, optional) – The ideal or desired model of perfect operations. It is often useful to bundle this together with model_to_test so that comparison metrics can be easily computed.

  • gaugeopt_suite (GSTGaugeOptSuite, optional) – Specifies which gauge optimizations to perform on each estimate. Can also be any object that can be cast to a GSTGaugeOptSuite object, such as a string or list of strings (see below) specifying built-in sets of gauge optimizations. This object also optionally stores an alternate target model for gauge optimization. This model is used as the “target” for gauge- optimization (only), and is useful when you want to gauge optimize toward something other than the ideal target gates.

  • objfn_builder (ObjectiveFunctionBuilder) – The objective function (builder) that is used to compare the model to data, i.e. the objective function that defines this model test.

  • badfit_options (GSTBadFitOptions) – Options specifing what constitutes a “bad fit” (or “failed test”) and what additional actions to take if and when this occurs.

  • set_trivial_gauge_group (bool, optional) – A convenience flag that updates the default gauge group of model_to_test to the trivial gauge group before performing the test, so that no actual gauge optimization is performed (even if gaugeopt_suite is non-None).

  • verbosity (int, optional) – Level of detail printed to stdout.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

classmethod create_objective_builder(cls, obj)

Creates objective function builders from obj that are commonly used in model tests.

Parameters

obj (object) – If obj is already an ObjectiveFunctionBuilder it is used directly. A dictionary is assumed to hold arguments of :method:`ObjectiveFunctionBuilder.simple`. A list or tuple is assumed to hold positional arguments of :method:`ObjectiveFunctionBuilder.__init__`.

Returns

ObjectiveFunctionBuilder

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

ModelEstimateResults

class pygsti.protocols._TreeNode(possible_child_name_dirs, child_values=None)

Bases: object

A base class for representing an object that lives “at” a filesystem directory.

Parameters
  • possible_child_name_dirs (dict) – A dictionary with string keys and values that maps possible child names (keys of this TreeNode) to directory names (where those keys are stored).

  • child_values (dict, optional) – A dictionary of child values (may be other TreeNode objects).

abstract classmethod from_dir(cls, dirname, parent=None, name=None)

Load a TreeNode from the data rooted at dirname.

Parameters
  • dirname (str or Path) – The directory path to load from.

  • parent (TreeNode, optional) – This node’s parent node, if it’s already loaded.

  • name (immutable, optional) – The name of this node, usually a string or tuple. Almost always the key within parent that refers to the loaded node (this can be different from the directory name).

_init_children(self, dirname, meta_subdir=None, **kwargs)
keys(self)

An iterator over the keys (child names) of this tree node.

__contains__(self, key)
__len__(self)
items(self)

An iterator over the (child_name, child_node) pairs of this node.

__getitem__(self, key)
abstract _create_childval(self, key)
underlying_tree_paths(self)

Dictionary paths leading to data objects/nodes beneath this one.

Returns

list – A list of tuples, each specifying the tree traversal to a child node. The first tuple is the empty tuple, referring to this (root) node.

view(self, keys_to_keep)

Get a “view” of this tree node that only has a subset of this node’s children.

Parameters

keys_to_keep (iterable) – A sequence of key names to keep.

Returns

TreeNode

prune_tree(self, paths, paths_are_sorted=False)

Prune the tree rooted here to include only the given paths, discarding all other leaves & branches.

Parameters
  • paths (list) – A list of tuples specifying the paths to keep.

  • paths_are_sorted (bool, optional) – Whether paths is sorted (lexographically). Setting this to True will save a little time.

Returns

TreeNode – A view of this node and its descendants where unwanted children have been removed.

abstract write(self, dirname, parent=None)

Write this tree node to a directory.

Parameters
  • dirname (str or Path) – Directory to write to.

  • parent (TreeNode, optional) – This node’s parent.

Returns

None

_write_children(self, dirname, write_subdir_json=True)

Writes this node’s children to directories beneath dirname.

Each child node is written to a sub-directory named according to the sub-directory names associated with the child names (keys) of this node.

Parameters
  • dirname (str or Path) – The root directory to write to.

  • write_subdir_json (bool, optional) – If True, a dirname/edesign/subdirs.json file is written that contains child name information, i.e. the map between directory names and child names (it is useful to not requires these be the same, and sometimes it’s useful to name children with a tuple rather than just a string).

Returns

None

class pygsti.protocols._NamedDict(keyname=None, keytype=None, valname=None, valtype=None, items=())

Bases: dict, pygsti.baseobjs.nicelyserializable.NicelySerializable

A dictionary that also holds category names and types.

This dict-derived class holds a catgory name applicable to its keys, and key and value type names indicating the types of its keys and values.

The main purpose of this class is to utilize its :method:`to_dataframe` method.

Parameters
  • keyname (str, optional) – A category name for the keys of this dict. For example, if the dict contained the keys “dog” and “cat”, this might be “animals”. This becomes a column header if this dict is converted to a data frame.

  • keytype ({"float", "int", "category", None}, optional) – The key-type, in correspondence with different pandas series types.

  • valname (str, optional) – A category name for the keys of this dict. This becomse a column header if this dict is converted to a data frame.

  • valtype ({"float", "int", "category", None}, optional) – The value-type, in correspondence with different pandas series types.

  • items (list or dict, optional) – Initial items, used in serialization.

classmethod create_nested(cls, key_val_type_list, inner)

Creates a nested NamedDict.

Parameters
  • key_val_type_list (list) – A list of (key, value, type) tuples, one per nesting layer.

  • inner (various) – The value that will be set to the inner-most nested dictionary’s value, supplying any additional layers of nesting (if inner is a NamedDict) or the value contained in all of the nested layers.

__reduce__(self)

Helper for pickle.

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
to_dataframe(self)

Render this dict as a pandas data frame.

Returns

pandas.DataFrame

_add_to_columns(self, columns, seriestypes, row_prefix)
pygsti.protocols._process_dataframe(df, pivot_valuename, pivot_value, drop_columns, preserve_order=False)

See to_dataframe docstrings for argument descriptions.

class pygsti.protocols.Protocol(name=None)

Bases: object

An analysis routine that is run on experimental data. A generalized notion of a QCVV protocol.

A Protocol object represents things like, but not strictly limited to, QCVV protocols. This class is essentially a serializable run function that takes as input a ProtocolData object and returns a ProtocolResults object. This function describes the working of the “protocol”.

Parameters

name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

classmethod from_dir(cls, dirname, quick_load=False)

Initialize a new Protocol object from dirname.

quick_loadbool, optional

Setting this to True skips the loading of components that may take a long time to load.

Parameters
  • dirname (str) – The directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load.

Returns

Protocol

abstract run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

ProtocolResults

write(self, dirname)

Write this protocol to a directory.

Parameters

dirname (str) – The directory name to write. This directory will be created if needed, and the files in an existing directory will be overwritten.

Returns

None

setup_nameddict(self, final_dict)

Initializes a set of nested NamedDict dictionaries describing this protocol.

This function is used by ProtocolResults objects when they’re creating nested dictionaries of their contents. This function returns a set of nested, single (key,val)-pair named-dictionaries which describe the particular attributes of this Protocol object named within its self._nameddict_attributes tuple. The final nested dictionary is set to be final_dict, which allows additional result quantities to easily be added.

Parameters

final_dict (NamedDict) – the final-level (innermost-nested) NamedDict in the returned nested dictionary.

Returns

NamedDict

_init_unserialized_attributes(self)

Initialize anything that isn’t serialized based on the things that are serialized. Usually this means initializing things with auxfile_type == ‘none’ that aren’t separately serialized.

class pygsti.protocols.MultiPassProtocol(protocol, name=None)

Bases: Protocol

Runs a (contained) Protocol on all the passes of a multi-pass ProtocolData.

A simple protocol that runs a “sub-protocol” on the passes of a ProtocolData containing a MultiDataSet. The sub-protocol therefore doesn’t need to know how to deal with multiple data passes. Instances of this class essentially act as wrappers around other protocols enabling them to handle multi-pass data.

Parameters
  • protocol (Protocol) – The protocol to run on each pass.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

MultiPassResults

class pygsti.protocols.ProtocolRunner

Bases: object

Used to run :class:`Protocol`(s) on an entire tree of data

This class provides a way of combining multiple calls to :method:`Protocol.run`, potentially running multiple protocols on different data. From the outside, a ProtocolRunner object behaves similarly, and can often be used interchangably, with a Protocol object. It posesses a run method that takes a ProtocolData as input and returns a ProtocolResultsDir that can contain multiple ProtocolResults objects within it.

abstract run(self, data, memlimit=None, comm=None)

Run all the protocols specified by this protocol-runner on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol-runner in parallel.

Returns

ProtocolResultsDir

class pygsti.protocols.TreeRunner(protocol_dict)

Bases: ProtocolRunner

Runs specific protocols on specific data-tree paths.

Parameters

protocol_dict (dict) – A dictionary of Protocol objects whose keys are paths (tuples of strings) specifying where in the data-tree that protocol should be run.

run(self, data, memlimit=None, comm=None)

Run all the protocols specified by this protocol-runner on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol-runner in parallel.

Returns

ProtocolResultsDir

class pygsti.protocols.SimpleRunner(protocol, protocol_can_handle_multipass_data=False, edesign_type='all')

Bases: ProtocolRunner

Runs a single protocol on every data node that has no sub-nodes (possibly separately for each pass).

Parameters
  • protocol (Protocol) – The protocol to run.

  • protocol_can_handle_multipass_data (bool, optional) – Whether protocol is able to process multi-pass data, or if MultiPassProtocol objects should be created implicitly.

  • edesign_type (type or 'all') – Only run protocol on leaves with this type. (If ‘all’, then no filtering is performed.)

run(self, data, memlimit=None, comm=None)

Run all the protocols specified by this protocol-runner on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol-runner in parallel.

Returns

ProtocolResultsDir

class pygsti.protocols.DefaultRunner(run_passes_separately=False)

Bases: ProtocolRunner

Run the default protocol at each data-tree node.

(Default protocols are given within ExperimentDesign objects.)

Parameters

run_passes_separately (bool, optional) – If True, then when multi-pass data is encountered it is split into passes before handing it off to the protocols. Set this to True when the default protocols being run expect single-pass data.

run(self, data, memlimit=None, comm=None)

Run all the protocols specified by this protocol-runner on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol-runner in parallel.

Returns

ProtocolResultsDir

class pygsti.protocols.ExperimentDesign(circuits=None, qubit_labels=None, children=None, children_dirs=None)

Bases: pygsti.protocols.treenode.TreeNode

An experimental-design specification for one or more QCVV protocols.

The quantities needed to define the experiments required to run a Protocol. Minimally, a ExperimentDesign object holds a list of Circuit`s that need to be run.  Typically, a :class:`ExperimentDesign object also contains information used to interpret these circuits, either by describing how they are constructed from smaller pieces or how they are drawn from a distribution.

It’s important to note that a ExperimentDesign does not contain all the inputs needed to run any particular QCVV protocol (e.g. there may be additional parameters specified when creating a Protocol object, and it may be the case that the data described by a single ExperimentDesign can be used by muliple protocols). Rather, a ExperimentDesign specifies what is necessary to acquire and interpret the data needed for one or more QCVV protocols.

Parameters
  • circuits (list of Circuits, optional) – A list of the circuits needing data. If None, then the list is empty.

  • qubit_labels (tuple or "multiple", optional) – The qubits that this experiment design applies to. These should also be the line labels of circuits. If None, the concatenation of the qubit labels of any child experiment designs is used, or, if there are no child designs, the line labels of the first circuit is used. The special “multiple” value means that different circuits act on different qubit lines.

  • children (dict, optional) – A dictionary of whose values are child ExperimentDesign objects and whose keys are the names used to identify them in a “path”.

  • children_dirs (dict, optional) – A dictionary whose values are directory names and keys are child names (the same as the keys of children). If None, then the keys of children must be strings and are used as directory names. Directory names are used when saving the object (via :method:`write`).

  • child_category (str, optional) – The category that describes the children of this object. This is used as a heading for the keys of children.

classmethod from_dir(cls, dirname, parent=None, name=None, quick_load=False)

Initialize a new ExperimentDesign object from dirname.

Parameters
  • dirname (str) – The root directory name (under which there is a ‘edesign’ subdirectory).

  • parent (ExperimentDesign, optional) – The parent design object, if there is one. Primarily used internally - if in doubt, leave this as None.

  • name (str, optional) – The sub-name of the design object being loaded, i.e. the key of this data object beneath parent. Only used when parent is not None.

  • quick_load (bool, optional) – Setting this to True skips the loading of the potentially long circuit lists. This can be useful when loading takes a long time and all the information of interest lies elsewhere, e.g. in an encompassing results object.

Returns

ExperimentDesign

classmethod from_edesign(cls, edesign)

Create an ExperimentDesign out of an existing experiment design.

Parameters

edesign (ExperimentDesign) – The experiment design to convert (use as a base).

Returns

ExperimentDesign

_auto_dirname(self, child_key)

A helper function to generate a default directory name base off of a sub-name key

set_actual_circuits_executed(self, actual_circuits)

Sets a list of circuits that will actually be executed.

This list must be parallel, and corresponding circuits must be logically equivalent, to those in self.all_circuits_needing_data. For example, when the circuits in this design are run simultaneously with other circuits, the circuits in this design may need to be padded with idles.

Parameters

actual_circuits (list) – A list of Circuit objects that must be the same length as self.all_circuits_needing_data.

Returns

None

add_default_protocol(self, default_protocol_instance)

Add a “default” protocol to this experiment design.

Default protocols are a way of designating protocols you mean to run on the the data corresponding to an experiment design before that data has been taken. Use a DefaultRunner object to run (all) the default protocols of the experiment designs within a ProtocolData object.

Note that default protocols are indexed by their names, and so when adding multiple default protocols they need to have distinct names (usually given to the protocol when it is constructed).

Parameters

default_protocol_instance (Protocol) – The protocol to add. This protocol’s name is used to index it.

Returns

None

truncate_to_circuits(self, circuits_to_keep)

Builds a new experiment design containing only the specified circuits.

Parameters

circuits_to_keep (list) – A list of the circuits to keep.

Returns

ExperimentDesign

truncate_to_available_data(self, dataset)

Builds a new experiment design containing only those circuits present in dataset.

Parameters

dataset (DataSet) – The dataset to filter based upon.

Returns

ExperimentDesign

truncate_to_design(self, other_design)

Truncates this experiment design by only keeping the circuits also in other_design

Parameters

other_design (ExperimentDesign) – The experiment design to compare with.

Returns

ExperimentDesign – The truncated experiment design.

_truncate_to_circuits_inplace(self, circuits_to_keep)
_truncate_to_design_inplace(self, other_design)
_truncate_to_available_data_inplace(self, dataset)
write(self, dirname=None, parent=None)

Write this experiment design to a directory.

Parameters
  • dirname (str) – The root directory to write into. This directory will have an ‘edesign’ subdirectory, which will be created if needed and overwritten if present. If None, then the path this object was loaded from is used (if this object wasn’t loaded from disk, an error is raised).

  • parent (ExperimentDesign, optional) – The parent experiment design, when a parent is writing this design as a sub-experiment-design. Otherwise leave as None.

Returns

None

setup_nameddict(self, final_dict)

Initializes a set of nested NamedDict dictionaries describing this design.

This function is used by ProtocolResults objects when they’re creating nested dictionaries of their contents. This function returns a set of nested, single (key,val)-pair named-dictionaries which describe the particular attributes of this ExperimentDesign object named within its self._nameddict_attributes tuple. The final nested dictionary is set to be final_dict, which allows additional result quantities to easily be added.

Parameters

final_dict (NamedDict) – the final-level (innermost-nested) NamedDict in the returned nested dictionary.

Returns

NamedDict

abstract _create_subdata(self, subdata_name, dataset)

Creates a ProtocolData object for a sub-experiment-design.

Specifically, this creates the object for the sub-experiment-design given by subdata_name starting from dataset as the data for this experiment design. This is used internally by ProtocolData objects, and shouldn’t need to be used by external users.

Parameters
  • subdata_name (immutable) – The child (node) name of the sub-experiment design to create data for.

  • dataset (DataSet) – The data for this experiment design.

Returns

ProtocolData

promote_to_combined(self, name='**0')

Promote this experiment design to be a combined experiment design.

Wraps this experiment design in a new CombinedExperimentDesign whose only sub-design is this one, and returns the combined design.

Parameters

name (str, optional) – The sub-design-name of this experiment design within the created combined experiment design.

Returns

CombinedExperimentDesign

promote_to_simultaneous(self)

Promote this experiment design to be a simultaneous experiment design.

Wraps this experiment design in a new SimultaneousExperimentDesign whose only sub-design is this one, and returns the simultaneous design.

Returns

SimultaneousExperimentDesign

class pygsti.protocols.CircuitListsDesign(circuit_lists, all_circuits_needing_data=None, qubit_labels=None, nested=False, remove_duplicates=True)

Bases: ExperimentDesign

Experiment design specification that is comprised of multiple circuit lists.

Parameters
  • circuit_lists (list) – A list whose elements are themselves lists of Circuit objects, specifying the data that needs to be taken.

  • all_circuits_needing_data (list, optional) – A list of all the circuits needing data. By default, This is just the concatenation of the elements of circuit_lists with duplicates removed. The only reason to specify this separately is if you happen to have this list lying around.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

  • nested (bool, optional) – Whether the elements of circuit_lists are nested, e.g. whether circuit_lists[i] is a subset of circuit_lists[i+1]. This is useful to know because certain operations can be more efficient when it is known that the lists are nested.

  • remove_duplicates (bool, optional) – Whether to remove duplicates when automatically creating all the circuits that need data (this argument isn’t used when all_circuits_needing_data is given).

classmethod from_edesign(cls, edesign)

Create a CircuitListsDesign out of an existing experiment design.

If edesign already is a circuit lists experiment design, it will just be returned (not a copy of it).

Parameters

edesign (ExperimentDesign) – The experiment design to convert (use as a base).

Returns

CircuitListsDesign

truncate_to_lists(self, list_indices_to_keep)

Truncates this experiment design by only keeping a subset of its circuit lists.

Parameters

list_indices_to_keep (iterable) – A list of the (integer) list indices to keep.

Returns

CircuitListsDesign – The truncated experiment design.

_truncate_to_circuits_inplace(self, circuits_to_keep)
_truncate_to_design_inplace(self, other_design)
_truncate_to_available_data_inplace(self, dataset)
class pygsti.protocols.CombinedExperimentDesign(sub_designs, all_circuits=None, qubit_labels=None, sub_design_dirs=None, interleave=False)

Bases: ExperimentDesign

An experiment design that combines the specifications of one or more “sub-designs”.

The sub-designs are preserved as children under the CombinedExperimentDesign instance, creating a “data-tree” structure. The CombinedExperimentDesign object itself simply merges all of the circuit lists.

Parameters
  • sub_designs (dict or list) – A dictionary of other ExperimentDesign objects whose keys are names for each sub-edesign (used for directories and to index the sub-edesigns from this experiment design). If a list is given instead, a default names of the form “**<number>” are used.

  • all_circuits (list, optional) – A list of Circuit`s, specifying all the circuits needing data.  This can include additional circuits that are not in any of `sub_designs. By default, the union of all the circuits in the sub-designs is used.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

  • sub_design_dirs (dict, optional) – A dictionary whose values are directory names and keys are sub-edesign names (the same as the keys of sub_designs). If None, then the keys of sub_designs must be strings and are used as directory names. Directory names are used when saving the object (via :method:`write`).

  • interleave (bool, optional) – Whether the circuits of the sub_designs should be interleaved to form the circuit ordering of this experiment design.

classmethod from_edesign(cls, edesign, name)

Create a combined experiment design out of an existing experiment design.

This makes edesign the one and only member of a new combined experiment design, even in edesign is already a CombinedExperimentDesign.

Parameters
  • edesign (ExperimentDesign) – The experiment design to convert (use as a base).

  • name (str) – The sub-name of edesign within the returned combined experiment design.

Returns

CombinedExperimentDesign

_create_subdata(self, sub_name, dataset)

Creates a ProtocolData object for a sub-experiment-design.

Specifically, this creates the object for the sub-experiment-design given by subdata_name starting from dataset as the data for this experiment design. This is used internally by ProtocolData objects, and shouldn’t need to be used by external users.

Parameters
  • sub_name (immutable) – The child (node) name of the sub-experiment design to create data for.

  • dataset (DataSet) – The data for this experiment design.

Returns

ProtocolData

__setitem__(self, key, val)
class pygsti.protocols.SimultaneousExperimentDesign(edesigns, tensored_circuits=None, qubit_labels=None)

Bases: ExperimentDesign

An experiment design whose circuits are the tensor-products of the circuits from one or more sub-designs.

The sub-ExperimentDesign objects must act on disjoint sets of qubits. The sub-designs are preserved as children under the SimultaneousExperimentDesign instance, creating a “data-tree” structure.

Parameters
  • edesigns (list) – A list of ExperimentDesign objects whose circuits are to occur simultaneously.

  • tensored_circuits (list, optional) – A list of all the circuits for this experiment design. By default, these are the circuits of those in edesigns tensored together. Typically this is left as the default.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the concatenated qubit labels of edesigns are used (this is usually what you want).

  • category (str, optional) – The category name for the qubit-label-tuples correspoding to the elements of edesigns.

classmethod from_edesign(cls, edesign)

Create a simultaneous experiment design out of an existing experiment design.

This makes edesign the one and only member of a new simultanieous experiment design, even in edesign is already a SimultaneousExperimentDesign.

Parameters

edesign (ExperimentDesign) – The experiment design to convert (use as a base).

Returns

SimultaneousExperimentDesign

_create_subdata(self, qubit_labels, dataset)

Creates a ProtocolData object for a sub-experiment-design.

Specifically, this creates the object for the sub-experiment-design given by subdata_name starting from dataset as the data for this experiment design. This is used internally by ProtocolData objects, and shouldn’t need to be used by external users.

Parameters
  • qubit_labels (tuple) – The child (node) label of the sub-experiment design to create data for.

  • dataset (DataSet) – The data for this experiment design.

Returns

ProtocolData

class pygsti.protocols.FreeformDesign(circuits, qubit_labels=None)

Bases: ExperimentDesign

Experiment design holding an arbitrary circuit list and meta data.

Parameters
  • circuits (list or dict) – A list of the circuits needing data. If None, then the list is empty.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

classmethod from_dataframe(cls, df, qubit_labels=None)

Create a FreeformDesign from a pandas dataframe.

Parameters
  • df (pandas.Dataframe) – A dataframe containing a “Circuit” column and possibly others.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

Returns

FreeformDesign

classmethod from_edesign(cls, edesign)

Create a FreeformDesign out of an existing experiment design.

If edesign already is a free-form experiment design, it will just be returned (not a copy of it).

Parameters

edesign (ExperimentDesign) – The experiment design to convert (use as a base).

Returns

FreeformDesign

_truncate_to_circuits_inplace(self, circuits_to_keep)
to_dataframe(self, pivot_valuename=None, pivot_value='Value', drop_columns=False)
class pygsti.protocols.ProtocolData(edesign, dataset=None, cache=None)

Bases: pygsti.protocols.treenode.TreeNode

Represents the experimental data needed to run one or more QCVV protocols.

This class contains a ProtocolIput, which describes a set of circuits, and a DataSet (or MultiDataSet) that holds data for these circuits. These members correspond to the .edesign and .dataset attributes.

Parameters
  • edesign (ExperimentDesign) – The experiment design describing what circuits this object contains data for. If None, then an unstructured ExperimentDesign is created containing the circuits present in dataset.

  • dataset (DataSet or MultiDataSet, optional) – The data counts themselves.

  • cache (dict, optional) – A cache of values which holds values derived only from the experiment design and data in this object.

passes

A dictionary of the data on a per-pass basis (works even it there’s just one pass).

Type

dict

classmethod from_dir(cls, dirname, parent=None, name=None, quick_load=False)

Initialize a new ProtocolData object from dirname.

Parameters
  • dirname (str) – The root directory name (under which there are ‘edesign’ and ‘data’ subdirectories).

  • parent (ProtocolData, optional) – The parent data object, if there is one. This is needed for sub-data objects which reference/inherit their parent’s dataset. Primarily used internally - if in doubt, leave this as None.

  • name (str, optional) – The sub-name of the design object being loaded, i.e. the key of this data object beneath parent. Only used when parent is not None.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time, e.g. the actual raw data set(s). This can be useful when loading takes a long time and all the information of interest lies elsewhere, e.g. in an encompassing results object.

Returns

ProtocolData

__getstate__(self)
__setstate__(self, state_dict)
_create_childval(self, key)

Create the value for key on demand.

copy(self)

Make a copy of this object.

Returns

ProtocolData

property passes(self)

A dictionary of the data on a per-pass basis (works even it there’s just one pass).

Returns

dict

is_multipass(self)

Whether this protocol data contains multiple passes.

More accurately, whether the .dataset of this object is a MultiDataSet.

Returns

bool

prune_tree(self, paths, paths_are_sorted=False)

Prune the tree rooted here to include only the given paths, discarding all else.

Returns a new ProtocolData object with a subset of the data-tree paths contained under this one.

Parameters
  • paths (list) – A list of the paths to keep. Each path is a tuple of keys, delineating a path in the data-tree.

  • paths_are_sorted (bool, optional) – Whether paths has already been sorted lexographically.

Returns

ProtocolData

write(self, dirname=None, parent=None)

Write this protocol data to a directory.

Parameters
  • dirname (str) – The root directory to write into. This directory will have ‘edesign’ and ‘data’ subdirectories, which will be created if needed and overwritten if present. If None, then the path this object was loaded from is used (if this object wasn’t loaded from disk, an error is raised).

  • parent (ProtocolData, optional) – The parent protocol data, when a parent is writing this data as a sub-protocol-data object. Otherwise leave as None.

Returns

None

setup_nameddict(self, final_dict)

Initializes a set of nested NamedDict dictionaries describing this data.

This function is used by ProtocolResults objects when they’re creating nested dictionaries of their contents. The final nested dictionary is set to be final_dict, which allows additional result quantities to easily be added.

Parameters

final_dict (NamedDict) – the final-level (innermost-nested) NamedDict in the returned nested dictionary.

Returns

NamedDict

to_dataframe(self, pivot_valuename=None, pivot_value=None, drop_columns=False)

Create a Pandas dataframe with this data.

Parameters
  • pivot_valuename (str, optional) – If not None, the resulting dataframe is pivoted using pivot_valuename as the column whose values name the pivoted table’s column names. If None and pivot_value is not None,`”ValueName”` is used.

  • pivot_value (str, optional) – If not None, the resulting dataframe is pivoted such that values of the pivot_value column are rearranged into new columns whose names are given by the values of the pivot_valuename column. If None and pivot_valuename is not None,`”Value”` is used.

  • drop_columns (bool or list, optional) – A list of column names to drop (prior to performing any pivot). If True appears in this list or is given directly, then all constant-valued columns are dropped as well. No columns are dropped when drop_columns == False.

Returns

pandas.DataFrame

class pygsti.protocols.ProtocolResults(data, protocol_instance)

Bases: object

Stores the results from running a QCVV protocol on data.

A ProtocolResults object Contains a ProtocolData object and stores the results of running a Protcocol on this data.

Parameters
  • data (ProtocolData) – The input data from which these results are derived.

  • protocol_instance (Protocol) – The protocol that created these results.

classmethod from_dir(cls, dirname, name, preloaded_data=None, quick_load=False)

Initialize a new ProtocolResults object from dirname / results / name.

Parameters
  • dirname (str) – The root directory name (under which there is are ‘edesign’, ‘data’, and ‘results’ subdirectories).

  • name (str) – The sub-directory name of the particular results object to load (there can be multiple under a given root dirname). This is the name of a subdirectory of dirname / results.

  • preloaded_data (ProtocolData, optional) – In the case that the ProtocolData object for dirname is already loaded, it can be passed in here. Otherwise leave this as None and it will be loaded.

  • quick_load (bool, optional) – Setting this to True skips the loading of data and experiment-design components that may take a long time to load. This can be useful all the information of interest lies only within the results object.

Returns

ProtocolResults

classmethod _from_dir_partial(cls, dirname, quick_load=False, load_protocol=False)

Internal method for loading only the results-specific data, and not the data member. This method may be used independently by derived ProtocolResults objecsts which contain multiple sub-results (e.g. MultiPassResults)

write(self, dirname=None, data_already_written=False)

Write these protocol results to a directory.

Parameters
  • dirname (str) – The root directory to write into. This directory will have ‘edesign’, ‘data’, and ‘results/<myname>’ subdirectories, which will path be created if needed and overwritten if present. If None, then the this object was loaded from is used (if this object wasn’t loaded from disk, an error is raised).

  • data_already_written (bool, optional) – Set this to True if you’re sure the .data ProtocolData object within this results object has already been written to dirname. Leaving this as the default is a safe option.

Returns

None

_write_partial(self, results_dir, write_protocol=False)

Internal method used to write the results-specific data to a directory. This method does not write the object’s data member, which must be serialized separately.

to_nameddict(self)

Convert these results into nested NamedDict objects.

Returns

NamedDict

_my_attributes_as_nameddict(self)
to_dataframe(self, pivot_valuename=None, pivot_value=None, drop_columns=False)

Convert these results into Pandas dataframe.

Parameters
  • pivot_valuename (str, optional) – If not None, the resulting dataframe is pivoted using pivot_valuename as the column whose values name the pivoted table’s column names. If None and pivot_value is not None,`”ValueName”` is used.

  • pivot_value (str, optional) – If not None, the resulting dataframe is pivoted such that values of the pivot_value column are rearranged into new columns whose names are given by the values of the pivot_valuename column. If None and pivot_valuename is not None,`”Value”` is used.

  • drop_columns (bool or list, optional) – A list of column names to drop (prior to performing any pivot). If True appears in this list or is given directly, then all constant-valued columns are dropped as well. No columns are dropped when drop_columns == False.

Returns

DataFrame

__str__(self)

Return str(self).

class pygsti.protocols.MultiPassResults(data, protocol_instance)

Bases: ProtocolResults

Holds the results of a single protocol on multiple “passes” (sets of data, typically taken at different times).

The results of each pass are held as a separate ProtcolResults object within the .passes attribute.

Parameters
  • data (ProtocolData) – The input data from which these results are derived.

  • protocol_instance (Protocol) – The protocol that created these results.

classmethod from_dir(cls, dirname, name, preloaded_data=None, quick_load=False)

Initialize a new MultiPassResults object from dirname / results / name.

Parameters
  • dirname (str) – The root directory name (under which there is are ‘edesign’, ‘data’, and ‘results’ subdirectories).

  • name (str) – The sub-directory name of the particular results object to load (there can be multiple under a given root dirname). This is the name of a subdirectory of dirname / results.

  • preloaded_data (ProtocolData, optional) – In the case that the ProtocolData object for dirname is already loaded, it can be passed in here. Otherwise leave this as None and it will be loaded.

  • quick_load (bool, optional) – Setting this to True skips the loading of data and experiment-design components that may take a long time to load. This can be useful all the information of interest lies only within the results object.

Returns

ProtocolResults

to_nameddict(self)

Create a NamedDict of the results within this object.

Returns

NamedDict

copy(self)

Make a copy of this object.

Returns

MultiPassResults

class pygsti.protocols.ProtocolResultsDir(data, protocol_results=None, children=None)

Bases: pygsti.protocols.treenode.TreeNode

Holds a dictionary of ProtocolResults objects.

It contains a ProtocolData object and is rooted at the_model corresponding node of the data-tree. It contains links to child-ProtocolResultsDir objects representing sub-directories.

This container object holds two things: 1. A .for_protocol dictionary of ProtocolResults corresponding

to different protocols (keys are protocol names).

  1. Child ProtocolResultsDir objects, obtained by indexing this object directly using the name of the sub-directory.

Parameters
  • data (ProtocolData) – The data from which all the Results objects in this ProtocolResultsDir are derived.

  • protocol_results (ProtocolResults, optional) – An initial (single) results object to add. The name of the results object is used as its key within the .for_protocol dictionary. If None, then an empty results directory is created.

  • children (dict, optional) – A dictionary of the ProtocolResultsDir objects that are sub-directories beneath this one. If None, then children are automatically created based upon the tree given by data. (To avoid creating any children, you can pass an empty dict here.)

classmethod from_dir(cls, dirname, parent=None, name=None, preloaded_data=None, quick_load=False)

Initialize a new ProtocolResultsDir object from dirname.

Parameters
  • dirname (str) – The root directory name (under which there are ‘edesign’ and ‘data’, and possibly ‘results’, subdirectories).

  • parent (ProtocolResultsDir, optional) – The parent results-directory object that is loading the returned object as a sub-results. This is used internally when loading a ProtocolResultsDir that represents a node of the data-tree with children.

  • name (str, optional) – The name of this result within parent. This is only used when parent is not None.

  • preloaded_data (ProtocolData, optional) – In the case that the ProtocolData object for dirname is already loaded, it can be passed in here. Otherwise leave this as None and it will be loaded.

  • quick_load (bool, optional) – Setting this to True skips the loading of data and experiment-design components that may take a long time to load. This can be useful all the information of interest lies only within the contained results objects.

Returns

ProtcolResultsDir

_create_childval(self, key)

Create the value for key on demand.

write(self, dirname=None, parent=None)

Write this “protocol results directory” to a directory.

Parameters
  • dirname (str) – The root directory to write into. This directory will have ‘edesign’, ‘data’, and ‘results’ subdirectories, which will be created if needed and overwritten if present. If None, then the path this object was loaded from is used (if this object wasn’t loaded from disk, an error is raised).

  • parent (ProtocolResultsDir, optional) – The parent protocol results directory, when a parent is writing this results dir as a sub-results-dir. Otherwise leave as None.

Returns

None

_result_namedicts_on_this_node(self)
_addto_bypath_nameddict(self, dest, path)
to_nameddict(self)

Convert the results in this object into nested NamedDict objects.

Returns

NamedDict

to_dataframe(self, pivot_valuename=None, pivot_value=None, drop_columns=False)

Convert these results into Pandas dataframe.

Parameters
  • pivot_valuename (str, optional) – If not None, the resulting dataframe is pivoted using pivot_valuename as the column whose values name the pivoted table’s column names. If None and pivot_value is not None,`”ValueName”` is used.

  • pivot_value (str, optional) – If not None, the resulting dataframe is pivoted such that values of the pivot_value column are rearranged into new columns whose names are given by the values of the pivot_valuename column. If None and pivot_valuename is not None,`”Value”` is used.

  • drop_columns (bool or list, optional) – A list of column names to drop (prior to performing any pivot). If True appears in this list or is given directly, then all constant-valued columns are dropped as well. No columns are dropped when drop_columns == False.

Returns

DataFrame

__str__(self)

Return str(self).

pygsti.protocols.run_default_protocols(data, memlimit=None, comm=None)

Run the default protocols for the data-tree rooted at data.

Parameters
  • data (ProtocolData) – the data to run default protocols on.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run the protocols in parallel.

Returns

ProtocolResultsDir

class pygsti.protocols.ProtocolPostProcessor(name)

Bases: object

Similar to a protocol, but runs on an existing ProtocolResults object.

Running a ProtocolPostProcessor produces a new (or updated) ProtocolResults object.

Parameters

name (str) – The name of this post-processor.

classmethod from_dir(cls, dirname, quick_load=False)

Initialize a new ProtocolPostProcessor object from dirname.

Parameters
  • dirname (str) – The directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load.

Returns

ProtocolPostProcessor

_init_unserialized_attributes(self)
abstract run(self, results, memlimit=None, comm=None)

Run this post-processor on results.

Parameters
  • results (ProtocolResults) – The input results.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this post-processor in parallel.

Returns

ProtocolResults

write(self, dirname)

Write this protocol post-processor to a directory.

Parameters

dirname (str) – The directory to write into.

Returns

None

class pygsti.protocols.DataSimulator

Bases: object

An analysis routine that is run on an experiment design to produce per-circuit data.

A DataSimulator fundamentally simulates a model to create data, taking an ExperimentDesign as input and producing a ProtocolData object as output.

The produced data may consist of data counts for some/all of the circuit outcomes, and thus result in a ProtocolData containsing a normal DataSet. Alternatively, a data simulator may compute arbitrary quantities to be associated with the circuits, resulting in a ProtocolData containsing a normal FreeformDataSet.

abstract run(self, edesign, memlimit=None, comm=None)

Run this data simulator on an experiment design.

Parameters
  • edesign (ExperimentDesign) – The input experiment design.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this data simulator in parallel.

Returns

ProtocolData

class pygsti.protocols.DataCountsSimulator(model, num_samples=1000, sample_error='multinomial', seed=None, rand_state=None, alias_dict=None, collision_action='aggregate', record_zero_counts=True, times=None)

Bases: DataSimulator

Simulates data counts for each circuit outcome, producing a simulated data set.

This object can also be used to compute the outcome probabilities for each circuit outcome instead of sampled counts by setting sample_error=”none”.

Parameters
  • model (Model) – The model to simulate.

  • num_samples (int or list of ints or None, optional) – The simulated number of samples for each circuit. This only has effect when sample_error == "binomial" or "multinomial". If an integer, all circuits have this number of total samples. If a list, integer elements specify the number of samples for the corresponding circuit. If None, then model_or_dataset must be a DataSet, and total counts are taken from it (on a per-circuit basis).

  • sample_error (string, optional) –

    What type of sample error is included in the counts. Can be:

    • ”none” - no sample error: counts are floating point numbers such that the exact probabilty can be found by the ratio of count / total.

    • ”clip” - no sample error, but clip probabilities to [0,1] so, e.g., counts are always positive.

    • ”round” - same as “clip”, except counts are rounded to the nearest integer.

    • ”binomial” - the number of counts is taken from a binomial distribution. Distribution has parameters p = (clipped) probability of the circuit and n = number of samples. This can only be used when there are exactly two SPAM labels in model_or_dataset.

    • ”multinomial” - counts are taken from a multinomial distribution. Distribution has parameters p_k = (clipped) probability of the gate string using the k-th SPAM label and n = number of samples.

  • seed (int, optional) – If not None, a seed for numpy’s random number generator, which is used to sample from the binomial or multinomial distribution.

  • rand_state (numpy.random.RandomState) – A RandomState object to generate samples from. Can be useful to set instead of seed if you want reproducible distribution samples across multiple random function calls but you don’t want to bother with manually incrementing seeds between those calls.

  • alias_dict (dict, optional) – A dictionary mapping single operation labels into tuples of one or more other operation labels which translate the given circuits before values are computed using model_or_dataset. The resulting Dataset, however, contains the un-translated circuits as keys.

  • collision_action ({"aggregate", "keepseparate"}) – Determines how duplicate circuits are handled by the resulting DataSet. Please see the constructor documentation for DataSet.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • times (iterable, optional) – When not None, a list of time-stamps at which data should be sampled. num_samples samples will be simulated at each time value, meaning that each circuit in circuit_list will be evaluated with the given time value as its start time.

run(self, edesign, memlimit=None, comm=None)

Run this data simulator on an experiment design.

Parameters
  • edesign (ExperimentDesign) – The input experiment design.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this data simulator in parallel.

Returns

ProtocolData

pygsti.protocols._convert_nameddict_attributes(obj)

A helper function that converts the elements of the “_nameddict_attributes” attribute of several classes to the (key, value, type) array expected by :method:`NamedDict.create_nested`.

class pygsti.protocols.CliffordRBDesign(pspec, clifford_compilations, depths, circuits_per_depth, qubit_labels=None, randomizeout=False, interleaved_circuit=None, citerations=20, compilerargs=(), descriptor='A Clifford RB experiment', add_default_protocol=False, seed=None, verbosity=1, num_processes=1)

Bases: pygsti.protocols.vb.BenchmarkingDesign

Experiment design for Clifford randomized benchmarking.

This encapsulates a “Clifford randomized benchmarking” (CRB) experiment. CRB is the RB protocol defined in “Scalable and robust randomized benchmarking of quantum processes”, Magesan et al. PRL 106 180504 (2011). The circuits created by this function will respect the connectivity and gate-set of the device encoded by pspec (see the QubitProcessorSpec object docstring for how to construct the relevant pspec for a device).

Note that this function uses the convention that a depth “l” CRB circuit consists of “l”+2 Clifford gates before compilation.

Parameters
  • pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the CRB experiment is being generated for, which defines the “native” gate-set and the connectivity of the device. The returned CRB circuits will be over the gates in pspec, and will respect the connectivity encoded by pspec.

  • clifford_compilations (dict) – A dictionary with the potential keys ‘absolute’ and ‘paulieq’ and corresponding CompilationRules values. These compilation rules specify how to compile the “native” gates of pspec into Clifford gates.

  • depths (list of ints) – The “CRB depths” of the circuit; a list of integers >= 0. The CRB length is the number of Cliffords in the circuit - 2 before each Clifford is compiled into the native gate-set.

  • circuits_per_depth (int) – The number of (possibly) different CRB circuits sampled at each length.

  • qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuits are to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant. If desired, a circuit that explicitly idles on the other qubits can be obtained by using methods of the Circuit object.

  • randomizeout (bool, optional) – If False, the ideal output of the circuits (the “success” or “survival” outcome) is always the all-zeros bit string. This is probably considered to be the “standard” in CRB. If True, the ideal output a circuit is randomized to a uniformly random bit-string. This setting is useful for, e.g., detecting leakage/loss/measurement-bias etc.

  • citerations (int, optional) – Some of the Clifford compilation algorithms in pyGSTi (including the default algorithm) are randomized, and the lowest-cost circuit is chosen from all the circuit generated in the iterations of the algorithm. This is the number of iterations used. The time required to generate a CRB circuit is linear in citerations * (CRB length + 2). Lower-depth / lower 2-qubit gate count compilations of the Cliffords are important in order to successfully implement CRB on more qubits.

  • compilerargs (list, optional) –

    A list of arguments that are handed to compile_clifford() function, which includes all the optional arguments of compile_clifford() after the iterations option (set by citerations). In order, this list should be values for:

    • algorithmstr. A string that specifies the compilation algorithm. The default in

      compile_clifford() will always be whatever we consider to be the ‘best’ all-round algorith,

    • aargs : list. A list of optional arguments for the particular compilation algorithm.

    • costfunction’str’ or function. The cost-function from which the “best” compilation

      for a Clifford is chosen from all citerations compilations. The default costs a circuit as 10x the num. of 2-qubit gates in the circuit + 1x the depth of the circuit.

    • prefixpaulis : bool. Whether to prefix or append the Paulis on each Clifford.

    • paulirandomizebool. Whether to follow each layer in the Clifford circuit with a

      random Pauli on each qubit (compiled into native gates). I.e., if this is True the native gates are Pauli-randomized. When True, this prevents any coherent errors adding (on average) inside the layers of each compiled Clifford, at the cost of increased circuit depth. Defaults to False.

    For more information on these options, see the compile_clifford() docstring.

  • descriptor (str, optional) – A string describing the experiment generated, which will be stored in the returned dictionary.

  • add_default_protocol (bool, optional) – Whether to add a default RB protocol to the experiment design, which can be run later (once data is taken) by using a DefaultProtocolRunner object.

  • seed (int, optional) – A seed to initialize the random number generator used for creating random clifford circuits.

  • verbosity (int, optional) – If > 0 the number of circuits generated so far is shown.

classmethod from_existing_circuits(cls, circuits_and_idealouts_by_depth, qubit_labels=None, randomizeout=False, citerations=20, compilerargs=(), interleaved_circuit=None, descriptor='A Clifford RB experiment', add_default_protocol=False)

Create a CliffordRBDesign from an existing set of sampled RB circuits.

This function serves as an alternative to the usual method of creating a Clifford RB experiment design by sampling a number of circuits randomly. This function takes a list of previously-sampled random circuits and does not sampling internally.

Parameters
  • circuits_and_idealouts_by_depth (dict) – A dictionary whose keys are integer depths and whose values are lists of (circuit, ideal_outcome) 2-tuples giving each RB circuit and its ideal (correct) outcome.

  • qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuits are to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant. If desired, a circuit that explicitly idles on the other qubits can be obtained by using methods of the Circuit object.

  • randomizeout (bool, optional) – If False, the ideal output of the circuits (the “success” or “survival” outcome) is always the all-zeros bit string. This is probably considered to be the “standard” in CRB. If True, the ideal output a circuit is randomized to a uniformly random bit-string. This setting is useful for, e.g., detecting leakage/loss/measurement-bias etc.

  • citerations (int, optional) – Some of the Clifford compilation algorithms in pyGSTi (including the default algorithm) are randomized, and the lowest-cost circuit is chosen from all the circuit generated in the iterations of the algorithm. This is the number of iterations used. The time required to generate a CRB circuit is linear in citerations * (CRB length + 2). Lower-depth / lower 2-qubit gate count compilations of the Cliffords are important in order to successfully implement CRB on more qubits.

  • compilerargs (list, optional) –

    A list of arguments that are handed to compile_clifford() function, which includes all the optional arguments of compile_clifford() after the iterations option (set by citerations). In order, this list should be values for:

    • algorithmstr. A string that specifies the compilation algorithm. The default in

      compile_clifford() will always be whatever we consider to be the ‘best’ all-round algorith,

    • aargs : list. A list of optional arguments for the particular compilation algorithm.

    • costfunction’str’ or function. The cost-function from which the “best” compilation

      for a Clifford is chosen from all citerations compilations. The default costs a circuit as 10x the num. of 2-qubit gates in the circuit + 1x the depth of the circuit.

    • prefixpaulis : bool. Whether to prefix or append the Paulis on each Clifford.

    • paulirandomizebool. Whether to follow each layer in the Clifford circuit with a

      random Pauli on each qubit (compiled into native gates). I.e., if this is True the native gates are Pauli-randomized. When True, this prevents any coherent errors adding (on average) inside the layers of each compiled Clifford, at the cost of increased circuit depth. Defaults to False.

    For more information on these options, see the compile_clifford() docstring.

  • descriptor (str, optional) – A string describing the experiment generated, which will be stored in the returned dictionary.

  • add_default_protocol (bool, optional) – Whether to add a default RB protocol to the experiment design, which can be run later (once data is taken) by using a DefaultProtocolRunner object.

Returns

CliffordRBDesign

_init_foundation(self, depths, circuit_lists, ideal_outs, circuits_per_depth, qubit_labels, randomizeout, citerations, compilerargs, descriptor, add_default_protocol, interleaved_circuit)
class pygsti.protocols.DirectRBDesign(pspec, clifford_compilations, depths, circuits_per_depth, qubit_labels=None, sampler='edgegrab', samplerargs=[0.25], addlocal=False, lsargs=(), randomizeout=False, cliffordtwirl=True, conditionaltwirl=True, citerations=20, compilerargs=(), partitioned=False, descriptor='A DRB experiment', add_default_protocol=False, seed=None, verbosity=1, num_processes=1)

Bases: pygsti.protocols.vb.BenchmarkingDesign

Experiment design for Direct randomized benchmarking.

This encapsulates a “direct randomized benchmarking” (DRB) experiments. DRB was a protocol introduced in arXiv:1807.07975 (2018).

An n-qubit DRB circuit consists of (1) a circuit the prepares a uniformly random stabilizer state; (2) a length-l circuit (specified by length) consisting of circuit layers sampled according to some user-specified distribution (specified by sampler), (3) a circuit that maps the output of the preceeding circuit to a computational basis state. See arXiv:1807.07975 (2018) for further details.

Parameters
  • pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the circuit is being sampled for, which defines the “native” gate-set and the connectivity of the device. The returned DRB circuit will be over the gates in pspec, and will respect the connectivity encoded by pspec. Note that pspec is always handed to the sampler, as the first argument of the sampler function (this is only of importance when not using an in-built sampler for the “core” of the DRB circuit). Unless qubit_labels is not None, the circuit is sampled over all the qubits in pspec.

  • clifford_compilations (dict) – A dictionary with the potential keys ‘absolute’ and ‘paulieq’ and corresponding CompilationRules values. These compilation rules specify how to compile the “native” gates of pspec into Clifford gates.

  • depths (int) – The set of “direct RB depths” for the circuits. The DRB depths must be integers >= 0. Unless addlocal is True, the DRB length is the depth of the “core” random circuit, sampled according to sampler, specified in step (2) above. If addlocal is True, each layer in the “core” circuit sampled according to “sampler` is followed by a layer of 1-qubit gates, with sampling specified by lsargs (and the first layer is proceeded by a layer of 1-qubit gates), and so the circuit of step (2) is length 2*`length` + 1.

  • circuits_per_depth (int) – The number of (possibly) different DRB circuits sampled at each length.

  • qubit_labels (list, optional) – If not None, a list of the qubits to sample the circuit for. This is a subset of pspec.qubit_labels. If None, the circuit is sampled to act on all the qubits in pspec.

  • sampler (str or function, optional) –

    If a string, this should be one of:

    {‘edgegrab’, pairingQs’, ‘Qelimination’, ‘co2Qgates’, ‘local’}.

    Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by_* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid form of sampling for n-qubit DRB, but is not explicitly forbidden in this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful in-built sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.

  • samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec, the second argument is qubit_labels, and samplerargs lists the remaining arguments handed to the sampler. This is not optional for some choices of sampler.

  • addlocal (bool, optional) – Whether to follow each layer in the “core” circuits, sampled according to sampler with a layer of 1-qubit gates.

  • lsargs (list, optional) – Only used if addlocal is True. A list of optional arguments handed to the 1Q gate layer sampler circuit_layer_by_oneQgate(). Specifies how to sample 1Q-gate layers.

  • randomizeout (bool, optional) – If False, the ideal output of the circuits (the “success” or “survival” outcome) is the all-zeros bit string. If True, the ideal output of each circuit is randomized to a uniformly random bit-string. This setting is useful for, e.g., detecting leakage/loss/measurement-bias etc.

  • cliffordtwirl (bool, optional) – Wether to begin the circuits with a sequence that generates a random stabilizer state. For standard DRB this should be set to True. There are a variety of reasons why it is better to have this set to True.

  • conditionaltwirl (bool, optional) – DRB only requires that the initial/final sequences of step (1) and (3) create/measure a uniformly random / particular stabilizer state, rather than implement a particular unitary. step (1) and (3) can be achieved by implementing a uniformly random Clifford gate and the unique inversion Clifford, respectively. This is implemented if conditionaltwirl is False. However, steps (1) and (3) can be implemented much more efficiently than this: the sequences of (1) and (3) only need to map a particular input state to a particular output state, if conditionaltwirl is True this more efficient option is chosen – this is option corresponds to “standard” DRB. (the term “conditional” refers to the fact that in this case we essentially implementing a particular Clifford conditional on a known input).

  • citerations (int, optional) – Some of the stabilizer state / Clifford compilation algorithms in pyGSTi (including the default algorithms) are randomized, and the lowest-cost circuit is chosen from all the circuits generated in the iterations of the algorithm. This is the number of iterations used. The time required to generate a DRB circuit is linear in citerations. Lower-depth / lower 2-qubit gate count compilations of steps (1) and (3) are important in order to successfully implement DRB on as many qubits as possible.

  • compilerargs (list, optional) – A list of arguments that are handed to the compile_stabilier_state/measurement()functions (or the compile_clifford() function if conditionaltwirl `is False). This includes all the optional arguments of these functions *after* the `iterations option (set by citerations). For most purposes the default options will be suitable (or at least near-optimal from the compilation methods in-built into pyGSTi). See the docstrings of these functions for more information.

  • partitioned (bool, optional) – If False, each circuit is returned as a single full circuit. If True, each circuit is returned as a list of three circuits consisting of: (1) the stabilizer-prep circuit, (2) the core random circuit, (3) the pre-measurement circuit. In that case the full circuit is obtained by appended (2) to (1) and then (3) to (1).

  • descriptor (str, optional) – A description of the experiment being generated. Stored in the output dictionary.

  • add_default_protocol (bool, optional) – Whether to add a default RB protocol to the experiment design, which can be run later (once data is taken) by using a DefaultProtocolRunner object.

  • seed (int, optional) – A seed to initialize the random number generator used for creating random clifford circuits.

  • verbosity (int, optional) – If > 0 the number of circuits generated so far is shown.

classmethod from_existing_circuits(cls, circuits_and_idealouts_by_depth, qubit_labels=None, sampler='edgegrab', samplerargs=[0.25], addlocal=False, lsargs=(), randomizeout=False, cliffordtwirl=True, conditionaltwirl=True, citerations=20, compilerargs=(), partitioned=False, descriptor='A DRB experiment', add_default_protocol=False)

Create a DirectRBDesign from an existing set of sampled RB circuits.

This function serves as an alternative to the usual method of creating a direct RB experiment design by sampling a number of circuits randomly. This function takes a list of previously-sampled random circuits and does not sampling internally.

Parameters
  • circuits_and_idealouts_by_depth (dict) – A dictionary whose keys are integer depths and whose values are lists of (circuit, ideal_outcome) 2-tuples giving each RB circuit and its ideal (correct) outcome.

  • qubit_labels (list, optional) – If not None, a list of the qubits to sample the circuit for. This is a subset of pspec.qubit_labels. If None, the circuit is sampled to act on all the qubits in pspec.

  • sampler (str or function, optional) –

    If a string, this should be one of:

    {‘edgegrab’, pairingQs’, ‘Qelimination’, ‘co2Qgates’, ‘local’}.

    Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by_* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid form of sampling for n-qubit DRB, but is not explicitly forbidden in this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful in-built sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.

  • samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec, the second argument is qubit_labels, and samplerargs lists the remaining arguments handed to the sampler. This is not optional for some choices of sampler.

  • addlocal (bool, optional) – Whether to follow each layer in the “core” circuits, sampled according to sampler with a layer of 1-qubit gates.

  • lsargs (list, optional) – Only used if addlocal is True. A list of optional arguments handed to the 1Q gate layer sampler circuit_layer_by_oneQgate(). Specifies how to sample 1Q-gate layers.

  • randomizeout (bool, optional) – If False, the ideal output of the circuits (the “success” or “survival” outcome) is the all-zeros bit string. If True, the ideal output of each circuit is randomized to a uniformly random bit-string. This setting is useful for, e.g., detecting leakage/loss/measurement-bias etc.

  • cliffordtwirl (bool, optional) – Wether to begin the circuits with a sequence that generates a random stabilizer state. For standard DRB this should be set to True. There are a variety of reasons why it is better to have this set to True.

  • conditionaltwirl (bool, optional) – DRB only requires that the initial/final sequences of step (1) and (3) create/measure a uniformly random / particular stabilizer state, rather than implement a particular unitary. step (1) and (3) can be achieved by implementing a uniformly random Clifford gate and the unique inversion Clifford, respectively. This is implemented if conditionaltwirl is False. However, steps (1) and (3) can be implemented much more efficiently than this: the sequences of (1) and (3) only need to map a particular input state to a particular output state, if conditionaltwirl is True this more efficient option is chosen – this is option corresponds to “standard” DRB. (the term “conditional” refers to the fact that in this case we essentially implementing a particular Clifford conditional on a known input).

  • citerations (int, optional) – Some of the stabilizer state / Clifford compilation algorithms in pyGSTi (including the default algorithms) are randomized, and the lowest-cost circuit is chosen from all the circuits generated in the iterations of the algorithm. This is the number of iterations used. The time required to generate a DRB circuit is linear in citerations. Lower-depth / lower 2-qubit gate count compilations of steps (1) and (3) are important in order to successfully implement DRB on as many qubits as possible.

  • compilerargs (list, optional) – A list of arguments that are handed to the compile_stabilier_state/measurement()functions (or the compile_clifford() function if conditionaltwirl `is False). This includes all the optional arguments of these functions *after* the `iterations option (set by citerations). For most purposes the default options will be suitable (or at least near-optimal from the compilation methods in-built into pyGSTi). See the docstrings of these functions for more information.

  • partitioned (bool, optional) – If False, each circuit is returned as a single full circuit. If True, each circuit is returned as a list of three circuits consisting of: (1) the stabilizer-prep circuit, (2) the core random circuit, (3) the pre-measurement circuit. In that case the full circuit is obtained by appended (2) to (1) and then (3) to (1).

  • descriptor (str, optional) – A description of the experiment being generated. Stored in the output dictionary.

  • add_default_protocol (bool, optional) – Whether to add a default RB protocol to the experiment design, which can be run later (once data is taken) by using a DefaultProtocolRunner object.

Returns

DirectRBDesign

_init_foundation(self, depths, circuit_lists, ideal_outs, circuits_per_depth, qubit_labels, sampler, samplerargs, addlocal, lsargs, randomizeout, cliffordtwirl, conditionaltwirl, citerations, compilerargs, partitioned, descriptor, add_default_protocol)
class pygsti.protocols.MirrorRBDesign(pspec, depths, circuits_per_depth, qubit_labels=None, circuit_type='clifford', clifford_compilations=None, sampler='edgegrab', samplerargs=(0.25,), localclifford=True, paulirandomize=True, descriptor='A mirror RB experiment', add_default_protocol=False, seed=None, num_processes=1, verbosity=1)

Bases: pygsti.protocols.vb.BenchmarkingDesign

Experiment design for mirror randomized benchmarking.

Encapsulates a “mirror randomized benchmarking” (MRB) experiment, for the case of Clifford gates and with the option of Pauli randomization and local Clifford twirling. To implement mirror RB it is necessary for U^(-1) to in the gate set for every gate U in the gate set.

THIS METHOD IS IN DEVELOPEMENT. DO NOT EXPECT THAT THIS FUNCTION WILL BEHAVE THE SAME IN FUTURE RELEASES OF PYGSTI!

Parameters
  • pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the experiment is being generated for. The pspec is always handed to the sampler, as the first argument of the sampler function.

  • clifford_compilations (dict) – A dictionary with the potential keys ‘absolute’ and ‘paulieq’ and corresponding CompilationRules values. These compilation rules specify how to compile the “native” gates of pspec into Clifford gates.

  • depths (list of ints) –

    The “mirror RB depths” of the circuits, which is closely related to the circuit depth. A MRB length must be an even integer, and can be zero.

    • If localclifford and paulirandomize are False, the depth of a sampled circuit = the MRB length. The first length/2 layers are all sampled independently according to the sampler specified by sampler. The remaining half of the circuit is the “inversion” circuit that is determined by the first half.

    • If paulirandomize is True and localclifford is False, the depth of a circuit is 2*length+1 with odd-indexed layers sampled according to the sampler specified by `sampler, and the the zeroth layer + the even-indexed layers consisting of random 1-qubit Pauli gates.

    • If paulirandomize and localclifford are True, the depth of a circuit is 2*length+1 + X where X is a random variable (between 0 and normally <= ~12-16) that accounts for the depth from the layer of random 1-qubit Cliffords at the start and end of the circuit.

    • If paulirandomize is False and localclifford is True, the depth of a circuit is length + X where X is a random variable (between 0 and normally <= ~12-16) that accounts for the depth from the layer of random 1-qubit Cliffords at the start and end of the circuit.

  • circuits_per_depth (int) – The number of (possibly) different MRB circuits sampled at each length.

  • qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuit is to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant.

  • sampler (str or function, optional) – If a string, this should be one of: {‘edgegrab’, ‘Qelimination’, ‘co2Qgates’, ‘local’}. Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid option for n-qubit MRB – it results in sim. 1-qubit MRB – but it is not explicitly forbidden by this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful in-built sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.

  • samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec and samplerargs lists the remaining arguments handed to the sampler.

  • localclifford (bool, optional) – Whether to start the circuit with uniformly random 1-qubit Cliffords and all of the qubits (compiled into the native gates of the device).

  • paulirandomize (bool, optional) – Whether to have uniformly random Pauli operators on all of the qubits before and after all of the layers in the “out” and “back” random circuits. At length 0 there is a single layer of random Pauli operators (in between two layers of 1-qubit Clifford gates if localclifford is True); at length l there are 2l+1 Pauli layers as there are

  • descriptor (str, optional) – A string describing the generated experiment. Stored in the returned dictionary.

  • add_default_protocol (bool, optional) – Whether to add a default RB protocol to the experiment design, which can be run later (once data is taken) by using a DefaultProtocolRunner object.

classmethod from_existing_circuits(cls, circuits_and_idealouts_by_depth, qubit_labels=None, circuit_type='clifford', sampler='edgegrab', samplerargs=(0.25,), localclifford=True, paulirandomize=True, descriptor='A mirror RB experiment', add_default_protocol=False)

Create a MirrorRBDesign from an existing set of sampled RB circuits.

This function serves as an alternative to the usual method of creating a mirror RB experiment design by sampling a number of circuits randomly. This function takes a list of previously-sampled random circuits and does not sampling internally.

Parameters

circuits_and_idealouts_by_depth (dict) – A dictionary whose keys are integer depths and whose values are lists of (circuit, ideal_outcome) 2-tuples giving each RB circuit and its ideal (correct) outcome.

See init docstring for details on all other parameters.

Returns

MirrorRBDesign

_init_foundation(self, depths, circuit_lists, ideal_outs, circuits_per_depth, qubit_labels, circuit_type, sampler, samplerargs, localclifford, paulirandomize, descriptor, add_default_protocol)
class pygsti.protocols.RandomizedBenchmarking(datatype='success_probabilities', defaultfit='full', asymptote='std', rtype='EI', seed=(0.8, 0.95), bootstrap_samples=200, depths='all', square_mean_root=False, name=None)

Bases: pygsti.protocols.vb.SummaryStatistics

The randomized benchmarking protocol.

This same analysis protocol is used for Clifford, Direct and Mirror RB. The standard Mirror RB analysis is obtained by setting datatype = adjusted_success_probabilities.

Parameters
  • datatype ('success_probabilities' or 'adjusted_success_probabilities', optional) – The type of summary data to extract, average, and the fit to an exponential decay. If ‘success_probabilities’ then the summary data for a circuit is the frequency that the target bitstring is observed, i.e., the success probability of the circuit. If ‘adjusted_success_probabilties’ then the summary data for a circuit is S = sum_{k = 0}^n (-1/2)^k h_k where h_k is the frequency at which the output bitstring is a Hamming distance of k from the target bitstring, and n is the number of qubits. This datatype is used in Mirror RB, but can also be used in Clifford and Direct RB.

  • defaultfit ('A-fixed' or 'full') – The summary data is fit to A + Bp^m with A fixed and with A as a fit parameter. If ‘A-fixed’ then the default results displayed are those from fitting with A fixed, and if ‘full’ then the default results displayed are those where A is a fit parameter.

  • asymptote ('std' or float, optional) – The summary data is fit to A + Bp^m with A fixed and with A has a fit parameter, with the default results returned set by defaultfit. This argument specifies the value used when ‘A’ is fixed. If left as ‘std’, then ‘A’ defaults to 1/2^n if datatype is success_probabilities and to 1/4^n if datatype is adjusted_success_probabilities.

  • rtype ('EI' or 'AGI', optional) – The RB error rate definition convention. ‘EI’ results in RB error rates that are associated with the entanglement infidelity, which is the error probability with stochastic Pauli errors. ‘AGI’ results in RB error rates that are associated with the average gate infidelity.

  • seed (list, optional) – Seeds for the fit of B and p (A is seeded to the asymptote defined by asympote).

  • bootstrap_samples (float, optional) – The number of samples for generating bootstrapped error bars.

  • depths (list or 'all') – If not ‘all’, a list of depths to use (data at other depths is discarded).

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

RandomizedBenchmarkingResults

class pygsti.protocols.RandomizedBenchmarkingResults(data, protocol_instance, fits, depths, defaultfit)

Bases: pygsti.protocols.protocol.ProtocolResults

The results of running randomized benchmarking.

Parameters
  • data (ProtocolData) – The experimental data these results are generated from.

  • protocol_instance (Protocol) – The protocol that generated these results.

  • fits (dict) – A dictionary of RB fit parameters.

  • depths (list or tuple) – A sequence of the depths used in the RB experiment. The x-values of the RB fit curve.

  • defaultfit (str) – The default key within fits to plot when calling :method:`plot`.

plot(self, fitkey=None, decay=True, success_probabilities=True, size=(8, 5), ylim=None, xlim=None, legend=True, title=None, figpath=None)

Plots RB data and, optionally, a fitted exponential decay.

Parameters
  • fitkey (dict key, optional) – The key of the self.fits dictionary to plot the fit for. If None, will look for a ‘full’ key (the key for a full fit to A + Bp^m if the standard analysis functions are used) and plot this if possible. It otherwise checks that there is only one key in the dict and defaults to this. If there are multiple keys and none of them are ‘full’, fitkey must be specified when decay is True.

  • decay (bool, optional) – Whether to plot a fit, or just the data.

  • success_probabilities (bool, optional) – Whether to plot the success probabilities distribution, as a violin plot. (as well as the average success probabilities at each length).

  • size (tuple, optional) – The figure size

  • ylim (tuple, optional) – The y-axis range.

  • xlim (tuple, optional) – The x-axis range.

  • legend (bool, optional) – Whether to show a legend.

  • title (str, optional) – A title to put on the figure.

  • figpath (str, optional) – If specified, the figure is saved with this filename.

Returns

None

pygsti.protocols.RB
pygsti.protocols.RBResults
class pygsti.protocols._RobustPhaseEstimation(q)

Bases: object

Runs the non-adaptive RPE algorithm.

Runs the non-adaptive RPE algorithm using a dictionary of measurement results, Q.raw_angles, containing the angles calculated from the probabilities:

P^{γ’γ}_{Nₖs} = |<γ' y| U^Nₖ |γ x>|² = |<γ' x| U^Nₖ |-γ y>|² = (1 ± sin(θ))/2 P^{γ'γ}_{Nₖc} = |<γ' x| U^Nₖ |γ x>|² = |<γ' y| U^Nₖ | γ y>|² = (1 ± cos(θ))/2

Expect measured[Nₖ] = θ.

Overview:

At each generation, use the previous estimated angle to select the 2π/L window (of which the measurements cannot distinguish).

Returns an result object. theta is the estimated angle, angle_estimates are the estimates from each generation.

Parameters

q (<TODO typ>) – <TODO description>

theta_n(self, n)

Returns the equivalence class of the measurement Θ.

By definition, Θ is equivalent when any integer multiple of 2π/N is added to it.

Parameters

n (int) – The RPE ‘N’ parameter, used to determine the equivalence class.

Returns

float

class pygsti.protocols.RobustPhaseEstimationDesign(gate, req_lengths, sin_prep, sin_meas, sin_outcomes_pos, sin_outcomes_neg, cos_prep, cos_meas, cos_outcomes_pos, cos_outcomes_neg, *, qubit_labels=None, req_counts=None)

Bases: pygsti.protocols.protocol.CircuitListsDesign

Experimental design for robust phase estimation (RPE).

Produces an Experiment Design to test the phase that develops on a target gate, by applying it req_lengths times to a states prepared by sin_prep and cos_prep circuits, and then measured in the computational basis after (respective) action by sin_meas and cos_meas circuits. outcomes_pos and outcomes_neg determine which of those computational basis states count towards each of the probabilities

P^{γ’γ}_{Ns} = |<γ' y| U^N |γ x>|² = |<γ' x| U^N |-γ y>|² = (1 ± sin(θ))/2 P^{γ'γ}_{Nc} = |<γ' x| U^N |γ x>|² = |<γ' y| U^N | γ y>|² = (1 ± cos(θ))/2

(Computational basis state measurements in neither of these sets are silently dropped.)

In the above, the +x refers to the |E_0> + |E_1> combination of eigenstates of U, not of computational basis states. For instance, if U is rotation in the X basis, then cos_prep and cos_meas could be simply the identity:

|± U> = |0> ± |1>

where |±U> are the eigenstates of U, so that, in the notation of the above,

|+x> = |+U> + |-U> = |0>

The circuit would then calculate

P^+_{Nc} = |<+x| U^N | +x>|²

provided that cos_outcomes_pos = [0] and cos_outcomes_neg = [1].

Parameters
  • gate (<TODO typ>) – <TODO description>

  • req_lengths (<TODO typ>) – <TODO description>

  • sin_prep (<TODO typ>) – <TODO description>

  • sin_meas (<TODO typ>) – <TODO description>

  • sin_outcomes_pos (<TODO typ>) – <TODO description>

  • sin_outcomes_neg (<TODO typ>) – <TODO description>

  • cos_prep (<TODO typ>) – <TODO description>

  • cos_meas (<TODO typ>) – <TODO description>

  • cos_outcomes_pos (<TODO typ>) – <TODO description>

  • cos_outcomes_neg (<TODO typ>) – <TODO description>

class pygsti.protocols.RobustPhaseEstimation(name=None)

Bases: pygsti.protocols.protocol.Protocol

Robust phase estimation (RPE) protocol

_parse_row(self, row, outcomes_pos, outcomes_neg)
parse_dataset(self, design, dataset)

<TODO summary>

Parameters
  • design (<TODO typ>) – <TODO description>

  • dataset (<TODO typ>) – <TODO description>

compute_raw_angles(self, measured)

Determine the raw angles from the count data.

This corresponds to the angle of U^N, i.e., it is N times the phase of U.

Parameters

measured (<TODO typ>) – <TODO description>

Returns

<TODO typ>

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

RobustPhaseEstimationResults

class pygsti.protocols.RobustPhaseEstimationResults(data, protocol_instance, angle_estimates)

Bases: pygsti.protocols.protocol.ProtocolResults

Results from the RPE protocol

Parameters
  • data (<TODO typ>) – <TODO description>

  • protocol_instance (<TODO typ>) – <TODO description>

  • angle_estimates (<TODO typ>) – <TODO description>

angle_estimate

<TODO description>

Type

<TODO typ>

measured_counts

<TODO description>

Type

<TODO typ>

raw_angles

<TODO description>

Type

<TODO typ>

property angle_estimate(self)

<TODO summary>

property measured_counts(self)

<TODO summary>

property raw_angles(self)

<TODO summary>

pygsti.protocols.RPEDesign
pygsti.protocols.RPE
pygsti.protocols.RPEResults
class pygsti.protocols.StabilityAnalysisDesign(circuits, qubit_labels=None)

Bases: pygsti.protocols.protocol.ExperimentDesign

Experimental design for stability analysis.

Parameters
  • circuits (list) – The list of circuits to perform the stability analysis on. These can be anything.

  • qubit_labels (tuple or "multiple", optional) – The qubits that this experiment design applies to. These should also be the line labels of circuits.

class pygsti.protocols.StabilityAnalysis(significance=0.05, transform='auto', marginalize='auto', mergeoutcomes=None, constnumtimes='auto', ids=False, frequencies='auto', freqpointers={}, freqstest=None, tests='auto', inclass_correction={}, betweenclass_weighting='auto', estimator='auto', modelselector=None, verbosity=1, name=None)

Bases: pygsti.protocols.protocol.Protocol

Stability Analysis protocol

Parameters
  • ds (DataSet or MultiDataSet) – A DataSet containing time-series data to be analyzed for signs of instability.

  • significance (float, optional) – The global significance level. With defaults for all other inputs (a wide range of non-default options), the family-wise error rate of the set of all hypothesis tests performed is controlled to this value.

  • transform (str, optional) –

    The type of transform to use in the spectral analysis. Options are:

    • ’auto’: An attempt is made to choose the best transform given the “meta-data” of the data,

      e.g., the variability in the time-step between data points. For beginners, ‘auto’ is the best option. If you are familiar with the underlying methods, the meta-data of the input, and the relative merits of the different transform, then it is probably better to choose this yourself – as the auto-selection is not hugely sophisticated.

    • ’dct’The Type-II Discrete Cosine Transform (with an orthogonal normalization). This is

      the only tested option, and it is our recommended option when the data is approximately equally-spaced, i.e., the time-step between each “click” for each circuit is almost a constant. (the DCT transform implicitly assumes that this time-step is exactly constant)

    • ’dft’The discrete Fourier transform (with an orthogonal normalization). *** This is an

      experimental feature, and the results are unreliable with this transform ***

    • ’lsp’The Lomb-Scargle periodogram. *** This is an experimental feature, and the code is

      untested with this transform ***

  • marginalize (str or bool, optional) – True, False or ‘auto’. Whether or not to marginalize multi-qubit data, to look for instability in the marginalized probability distribution over the two outcomes for each qubit. Cannot be set to True if mergeoutcomes is not None.

  • mergeoutcomes (None or Dict, optional) – If not None, a dictionary of outcome-merging dictionaries. Each dictionary contained as a value of mergeoutcomes is used to create a new DataSet, where the values have been merged according to that dictionary (see the aggregate_dataset_outcomes() function inside datasetconstructions.py). The corresponding key is used as the key for that DataSet, when it is stored in a MultiDataSet, and the instability analysis is implemented on each DataSet. This is a more general data coarse-grainin option than marginalize.

  • constnumtimes (str or bool, optional) – True, False or ‘auto’. If True then data is discarded from the end of the “clickstream” for each circuit until all circuits have the same length clickstream, i.e., the same number of data aquisition times. If ‘auto’ then it is set to True or False depending on the meta-data of the data and the type of transform being used.

  • ids (True or False, optional) – Whether the multiple DataSets should be treat as generated from independent random variables. If the input is a DataSet and marginalize is False and mergeoutcomes is None then this input is irrelevant: there is only ever one DataSet being analyzed. But in general multiple DataSets are concurrently analyzed. This is irrelevant for independent analyses of the DataSets, but the analysis is capable of also implementing a joint analysis of the DataSets. This joint analysis is only valid on the assumption of independent DataSets, and so this analysis will not be permitted unless ids is set to True. Note that the set of N marginalized data from N-qubit circuits are generally not independent – even if the circuits contain no 2-qubit gates then crosstalk can causes dependencies. However, as long as the dependencies are weak then settings this to True is likely ok.

  • frequencies ('auto' or list, optional) –

    The frequencies that the power spectra are calculated for. If ‘auto’ these are automatically determined from the meta-data of the time-series data (e.g., using the mean time between data points) and the transform being used. If not ‘auto’, then a list of lists, where each list is a set of frequencies that are the frequencies corresponding to one or more power spectra. The frequencies that should be paired to a given power spectrum are specified by freqpointers.

    These frequencies (whether automatically calculated or explicitly input) have a fundmentally different meaning depending on whether the transform is time-stamp aware (here, the LSP) or not (here, the DCT and DFT).

    Time-stamp aware transforms take the frequencies to calculate powers at as an input, so the specified frequencies are, explicitly, the frequencies associated with the powers. The task of choosing the frequencies amounts to picking the best set of frequencies at which to interogate the true probability trajectory for components. As there are complex factors involved in this choice that the code has no way of knowing, sometimes it is best to choose them yourself. E.g., if different frequencies are used for different circuits it isn’t possible to (meaningfully) averaging power spectra across circuits, but this might be preferable if the time-step is sufficiently different between different circuits – it depends on your aims.

    For time-stamp unaware transforms, these frequencies should be the frequencies that, given that we’re implementing the, e.g., DCT, the generated power spectrum is implicitly with respect to. In the case of data on a fixed time-grid, i.e., equally spaced data, then there is a precise set of frequencies implicit in the transform (which will be accurately extracted with frequencies set to auto). Otherwise, these frequencies are explicitly at least slightly ad hoc, and choosing these frequencies amounts to choosing those frequencies that “best” approximate the properties being interogatted with fitting each, e.g., DCT basis function to the (timestamp-free) data. The ‘auto’ option bases there frequencies solely on the mean time step and the number of times, and is a decent option when the time stamps are roughly equally spaced for each circuit.

    These frequencies should be in units of 1/t where ‘t’ is the unit of the time stamps.

  • freqpointers (dict, optional) – Specifies which frequencies correspond to which power spectra. The keys are power spectra labels, and the values are integers that point to the index of frequencies (a list of lists) that the relevant frquencies are found at. Whenever a power spectra is not included in freqpointers then this defaults to 0. So if frequencies is specified and is a list containing a single list (of frequencies) then freqpointers can be left as the empty dictionary.

  • freqstest (None or list, optional) – If not not None, a list of the frequency indices at which to test the powers. Leave as None to perform comprehensive testing of the power spectra.

  • tests ('auto' or tuple, optional) –

    Specifies the set of hypothesis tests to perform. If ‘auto’ then an set of tests is automatically chosen. This set of tests will be suitable for most purposes, but sometimes it is useful to override this. If a tuple, the elements are “test classes”, that specifies a set of hypothesis tests to run, and each test class is itself specified by a tuple. The tests specified by each test class in this tuple are all implemented. A test class is a tuple containing some subset of ‘dataset’, ‘circuit’ and ‘outcome’, which specifies a set of power spectra. Specifically, a power spectra has been calculated for the clickstream for every combination of eachinput DataSet (e.g., there are multiple DataSets if there has been marginalization of multi-qubit data), each Circuit in the DataSet, and each possible outcome in the DataSet. For each of “dataset”, “circuit” and “outcome” not included in a tuple defining a test class, the coresponding “axis” of the 3-dimensional array of spectra is averaged over, and these spectra are then tested. So the tuple () specifies the “test class” whereby we test the power spectrum obtained by averaging all power spectra; the tuple (‘dataset’,’circuit’) specifies the “test class” whereby we average only over outcomes, obtaining a single power spectrum for each DataSet and Circuit combination, which we test.

    The default option for “tests” is appropriate for most circumstances, and it consists of (), (‘dataset’) and (‘dataset’, ‘circuit’) with duplicates removed (e.g., if there is a single DataSet then () is equivalent to (‘dataset’)).

  • inclass_correction (dict, optional) – A dictionary with keys ‘dataset’, ‘circuit’, ‘outcome’ and ‘spectrum’, and values that specify the type of multi-test correction used to account for the multiple tests being implemented. This specifies how the statistically significance is maintained within the tests implemented in a single “test class”.

  • betweenclass_weighting ('auto' or dict, optional) – The weighting to use to maintain statistical significance between the different classes of test being implemented. If ‘auto’ then a standard Bonferroni correction is used.

  • estimator (str, optional) –

    The name of the estimator to use. This is the method used to estimate the parameters of a parameterized model for each probability trajectory, after that parameterized model has been selected with the model selection methods. Allowed values are:

    • ’auto’. The estimation method is chosen automatically, default to the fast method that is also

      reasonably reliable.

    • ’filter’. Performs a type of signal filtering: implements the transform used for generating power

      spectra (e.g., the DCT), sets the amplitudes to zero for all freuquencies that the model selection has not included in the model, inverts the transform, and then performs some minor post-processing to guarantee probabilities within [0, 1]. This method is less statically well-founded than ‘mle’, but it is faster and typically gives similar results. This method is not an option for non-invertable transforms, such as the Lomb-Scargle periodogram.

    • ’mle’. Implements maximum likelihood estimation, on the parameterized model chosen by the model

      selection. The most statistically well-founded option, but can be slower than ‘filter’ and relies on numerical optimization.

  • modelselector (tuple, optional) – The model selection method. If not None, a “test class” tuple, specifying which test results to use to decide which frequencies are significant for each circuit, to then construct a parameterized model for each probability trajectory. This can be typically set to None, and it will be chosen automatically. But if you wish to use specific test results for the model selection then this should be set.

  • verbosity (int, optional) – The amount of print-to-screen

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

run(self, data, memlimit=None, comm=None)

Run this protocol on data.

Parameters
  • data (ProtocolData) – The input data.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

Returns

StabilityAnalysisResults

class pygsti.protocols.StabilityAnalysisResults(data, protocol_instance, stabilityanalyzer)

Bases: pygsti.protocols.protocol.ProtocolResults

Results from the stability analysis protocol.

NOTE Currently, this object just wraps a pygsti.extras.drift.StabilityAnalyzer object, which historically performed stability analysis. In the future, this object will likely take over the function of StabilityAnalyzer.

Parameters
  • data (ProtocolData) – The experimental data these results are generated from.

  • protocol_instance (Protocol) – The protocol that generated these results.

  • stabilityanalyzer (pygsti.extras.drift.StabilityAnalyzer) – An object holding the stability analysis results. This will likely be updated in the future.

__getattr__(self, attr)
class pygsti.protocols._SuccessFailModel(state_space, use_cache=False)

Bases: OplessModel

An op-less model that always outputs 2 (success & failure) probabilities for each circuit.

Parameters
  • state_space (StateSpace) – The state space of this model.

  • use_cache (bool, optional) – Whether a cache should be used to increase performance.

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
property sim(self)

Forward simulator for this model

_post_copy(self, copy_into, memo)

Called after all other copying is done, to perform “linking” between the new model (copy_into) and its members.

circuit_outcomes(self, circuit)

Get all the possible outcome labels produced by simulating this circuit.

Parameters

circuit (Circuit) – Circuit to get outcomes of.

Returns

tuple

abstract _success_prob(self, circuit, cache)
_success_dprob(self, circuit, param_slice, cache)

Derived classes can override this. Default implemntation is to use finite difference.

probabilities(self, circuit, outcomes=None, time=None)

Construct a dictionary containing the outcome probabilities of circuit.

Parameters
  • circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.

  • outcomes (list or tuple) – A sequence of outcomes, which can themselves be either tuples (to include intermediate measurements) or simple strings, e.g. ‘010’.

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

Returns

probs (OutcomeLabelDict) – A dictionary with keys equal to outcome labels and values equal to probabilities.

bulk_probabilities(self, circuits, clip_to=None, comm=None, mem_limit=None, smartc=None)

Construct a dictionary containing the probabilities for an entire list of circuits.

Parameters
  • circuits ((list of Circuits) or CircuitOutcomeProbabilityArrayLayout) – When a list, each element specifies a circuit to compute outcome probabilities for. A CircuitOutcomeProbabilityArrayLayout specifies the circuits along with an internal memory layout that reduces the time required by this function and can restrict the computed probabilities to those corresponding to only certain outcomes.

  • clip_to (2-tuple, optional) – (min,max) to clip return value if not None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors. Distribution is performed over subtrees of evalTree (if it is split).

  • mem_limit (int, optional) – A rough memory limit in bytes which is used to determine processor allocation.

  • smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.

Returns

probs (dictionary) – A dictionary such that probs[opstr] is an ordered dictionary of (outcome, p) tuples, where outcome is a tuple of labels and p is the corresponding probability.

class pygsti.protocols.ByDepthDesign(depths, circuit_lists, qubit_labels=None, remove_duplicates=True)

Bases: pygsti.protocols.protocol.CircuitListsDesign

Experiment design that holds circuits organized by depth.

Parameters
  • depths (list or tuple) – A sequence of integers specifying the circuit depth associated with each element of circuit_lists.

  • circuit_lists (list or tuple) – The circuits to include in this experiment design. Each element is a list of Circuits specifying the circuits at the corresponding depth.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

  • remove_duplicates (bool, optional) – Whether to remove duplicates when automatically creating all the circuits that need data.

class pygsti.protocols.BenchmarkingDesign(depths, circuit_lists, ideal_outs, qubit_labels=None, remove_duplicates=False)

Bases: ByDepthDesign

Experiment design that holds benchmarking data.

By “benchmarking data” we mean definite-outcome circuits organized by depth along with their corresponding ideal outcomes.

Parameters
  • depths (list or tuple) – A sequence of integers specifying the circuit depth associated with each element of circuit_lists.

  • circuit_lists (list or tuple) – The circuits to include in this experiment design. Each element is a list of Circuits specifying the circuits at the corresponding depth.

  • ideal_outs (list or tuple) – The ideal circuit outcomes corresponding to the circuits in circuit_lists. Each element of ideal_outs is a list (with the same length as the corresponding circuits_lists element) of outcome labels.

  • qubit_labels (tuple, optional) – The qubits that this experiment design applies to. If None, the line labels of the first circuit is used.

  • remove_duplicates (bool, optional) – Whether to remove duplicates when automatically creating all the circuits that need data.

class pygsti.protocols.PeriodicMirrorCircuitDesign(pspec, depths, circuits_per_depth, qubit_labels=None, clifford_compilations=None, sampler='edgegrab', samplerargs=(0.125,), localclifford=True, paulirandomize=True, fixed_versus_depth=False, descriptor='A random germ mirror circuit experiment')

Bases: BenchmarkingDesign

Experiment design for periodic mirror-circuit benchmarking.

THIS METHOD IS IN DEVELOPEMENT. DO NOT EXPECT THAT THIS FUNCTION WILL BEHAVE THE SAME IN FUTURE RELEASES OF PYGSTI! THE DOCSTRINGS SHOULD ALSO NOT BE TRUSTED – MANY (MAYBE ALL) OF THEM ARE COPIED FROM THE MIRRORBDESIGN OBJECT AND SO SOME BITS ARE WRONG OR NOT APPLICABLE.

Parameters
  • pspec (QubitProcessorSpec) – The QubitProcessorSpec for the device that the experiment is being generated for. The pspec is always handed to the sampler, as the first argument of the sampler function.

  • depths (list of ints) –

    The “mirror RB depths” of the circuits, which is closely related to the circuit depth. A MRB length must be an even integer, and can be zero.

    • If localclifford and paulirandomize are False, the depth of a sampled circuit = the MRB length. The first length/2 layers are all sampled independently according to the sampler specified by sampler. The remaining half of the circuit is the “inversion” circuit that is determined by the first half.

    • If paulirandomize is True and localclifford is False, the depth of a circuit is 2*length+1 with odd-indexed layers sampled according to the sampler specified by `sampler, and the the zeroth layer + the even-indexed layers consisting of random 1-qubit Pauli gates.

    • If paulirandomize and localclifford are True, the depth of a circuit is 2*length+1 + X where X is a random variable (between 0 and normally <= ~12-16) that accounts for the depth from the layer of random 1-qubit Cliffords at the start and end of the circuit.

    • If paulirandomize is False and localclifford is True, the depth of a circuit is length + X where X is a random variable (between 0 and normally <= ~12-16) that accounts for the depth from the layer of random 1-qubit Cliffords at the start and end of the circuit.

  • circuits_per_depth (int) – The number of (possibly) different MRB circuits sampled at each length.

  • qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuit is to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant.

  • sampler (str or function, optional) – If a string, this should be one of: {‘pairingQs’, ‘Qelimination’, ‘co2Qgates’, ‘local’}. Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid option for n-qubit MRB – it results in sim. 1-qubit MRB – but it is not explicitly forbidden by this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful in-built sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.

  • samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec and samplerargs lists the remaining arguments handed to the sampler.

  • localclifford (bool, optional) – Whether to start the circuit with uniformly random 1-qubit Cliffords and all of the qubits (compiled into the native gates of the device).

  • paulirandomize (bool, optional) – Whether to have uniformly random Pauli operators on all of the qubits before and after all of the layers in the “out” and “back” random circuits. At length 0 there is a single layer of random Pauli operators (in between two layers of 1-qubit Clifford gates if localclifford is True); at length l there are 2l+1 Pauli layers as there are

  • fixed_versus_depth (bool, optional) – <TODO description>

  • descriptor (str, optional) – A string describing the generated experiment. Stored in the returned dictionary.

classmethod from_existing_circuits(cls, circuits_and_idealouts_by_depth, qubit_labels=None, sampler='edgegrab', samplerargs=(0.125,), localclifford=True, paulirandomize=True, fixed_versus_depth=False, descriptor='A random germ mirror circuit experiment')

Create a PeriodicMirrorCircuitDesign from an existing set of sampled RB circuits.

This function serves as an alternative to the usual method of creating a mirror RB experiment design by sampling a number of circuits randomly. This function takes a list of previously-sampled random circuits and does not sampling internally.

Parameters
  • circuits_and_idealouts_by_depth (dict) – A dictionary whose keys are integer depths and whose values are lists of (circuit, ideal_outcome) 2-tuples giving each RB circuit and its ideal (correct) outcome.

  • qubit_labels (list, optional) – If not None, a list of the qubits that the RB circuit is to be sampled for. This should be all or a subset of the qubits in the device specified by the QubitProcessorSpec pspec. If None, it is assumed that the RB circuit should be over all the qubits. Note that the ordering of this list is the order of the ``wires’’ in the returned circuit, but is otherwise irrelevant.

  • sampler (str or function, optional) – If a string, this should be one of: {‘pairingQs’, ‘Qelimination’, ‘co2Qgates’, ‘local’}. Except for ‘local’, this corresponds to sampling layers according to the sampling function in rb.sampler named circuit_layer_by* (with * replaced by ‘sampler’). For ‘local’, this corresponds to sampling according to rb.sampler.circuit_layer_of_oneQgates [which is not a valid option for n-qubit MRB – it results in sim. 1-qubit MRB – but it is not explicitly forbidden by this function]. If sampler is a function, it should be a function that takes as the first argument a QubitProcessorSpec, and returns a random circuit layer as a list of gate Label objects. Note that the default ‘Qelimination’ is not necessarily the most useful in-built sampler, but it is the only sampler that requires no parameters beyond the QubitProcessorSpec and works for arbitrary connectivity devices. See the docstrings for each of these samplers for more information.

  • samplerargs (list, optional) – A list of arguments that are handed to the sampler function, specified by sampler. The first argument handed to the sampler is pspec and samplerargs lists the remaining arguments handed to the sampler.

  • localclifford (bool, optional) – Whether to start the circuit with uniformly random 1-qubit Cliffords and all of the qubits (compiled into the native gates of the device).

  • paulirandomize (bool, optional) – Whether to have uniformly random Pauli operators on all of the qubits before and after all of the layers in the “out” and “back” random circuits. At length 0 there is a single layer of random Pauli operators (in between two layers of 1-qubit Clifford gates if localclifford is True); at length l there are 2l+1 Pauli layers as there are

  • fixed_versus_depth (bool, optional) – <TODO description>

  • descriptor (str, optional) – A string describing the generated experiment. Stored in the returned dictionary.

Returns

PeriodicMirrorCircuitDesign

_init_foundation(self, depths, circuit_lists, ideal_outs, circuits_per_depth, qubit_labels, sampler, samplerargs, localclifford, paulirandomize, fixed_versus_depth, descriptor)
class pygsti.protocols.SummaryStatistics(name)

Bases: pygsti.protocols.protocol.Protocol

A protocol that can construct “summary” quantities from raw data.

Parameters

name (str) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

summary_statistics

Static list of the categories of summary information this protocol can compute.

Type

tuple

circuit_statistics

Static list of the categories of circuit information this protocol can compute.

Type

tuple

summary_statistics = ['success_counts', 'total_counts', 'hamming_distance_counts', 'success_probabilities',...
circuit_statistics = ['two_q_gate_count', 'depth', 'idealout', 'circuit_index', 'width']
_compute_summary_statistics(self, data)

Computes all summary statistics for the given data.

Parameters

data (ProtocolData) – The data to operate on.

Returns

NamedDict

_compute_circuit_statistics(self, data)

Computes all circuit statistics for the given data.

Parameters

data (ProtocolData) – The data to operate on.

Returns

NamedDict

_compute_predicted_probs(self, data, model)

Compute the predicted success probabilities of model given data.

Parameters
Returns

NamedDict

_compute_dict(self, data, component_names, compute_fn, for_passes='all')

Executes a computation function row-by-row on the data in data and packages the results.

Parameters
  • data (ProtocolData) – The data.

  • component_names (list or tuple) – A sequence of string-valued component names which must be the keys of the dictionary returned by compute_fn.

  • compute_fn (function) – A function that computes values for each item in component_names for each row of data. This function should have signature: compute_fn(icirc : int, circ : Circuit, dsrow : _DataSetRow, idealout : OutcomeLabel) and should return a dictionary whose keys are the same as component_names.

  • for_passes ({'all', 'none', 'first'}) – UNUSED. What passes within data values are computed for.

Returns

NamedDict – A nested dictionary with indices: component-name, depth, circuit-index (the last level is a list, not a dict).

_create_depthwidth_dict(self, depths, widths, fillfn, seriestype)

Create a nested NamedDict with depht and width indices.

Parameters
  • depths (list or tuple) – The (integer) depths to use.

  • widths (list or tuple) – The (integer) widths to use.

  • fillfn (function) – A function with no arguments that is called to return a default value for each (depth, width).

  • seriestype ({"float", "int"}) – The type of values held by this nested dict.

Returns

NamedDict

_add_bootstrap_qtys(self, data_cache, num_qtys, finitecounts=True)

Adds bootstrapped “summary data”.

The bootstrap is over both the finite counts of each circuit and over the circuits at each length.

Note: only adds quantities if they’re needed.

Parameters
  • data_cache (dict) – A cache of already-existing bootstraps.

  • num_qtys (int, optional) – The number of bootstrapped data to construct.

  • finitecounts (bool, optional) – Whether finite counts should be used, i.e. whether the bootstrap samples include finite sample error with the same number of counts as the sampled data, or whether they have no finite sample error (just probabilities).

Returns

None

class pygsti.protocols.ByDepthSummaryStatistics(depths='all', statistics_to_compute=('polarization',), names_to_compute=None, custom_data_src=None, name=None)

Bases: SummaryStatistics

A protocol that computes summary statistics for data organized into by-depth circuit lists.

Parameters
  • depths (list or "all", optional) – A sequence of the depths to compute summary statistics for or the special “all” value which means “all the depths in the data”. If data being processed does not contain a given value in depths, it is just ignored.

  • statistics_to_compute (tuple, optional) – A sequence of the statistic names to compute. Allowed names are: ‘success_counts’, ‘total_counts’, ‘hamming_distance_counts’, ‘success_probabilities’, ‘polarization’, ‘adjusted_success_probabilities’, ‘two_q_gate_count’, ‘depth’, ‘idealout’, ‘circuit_index’, and ‘width’.

  • names_to_compute (tuple, optional) – A sequence of user-defined names for the statistics in statistics_to_compute. If None, then the statistic names themselves are used. These names are the column names produced by calling to_dataframe on this protocol’s results, so can be useful to name the computed statistics differently from the statistic name itself to distinguish it from the same statistic run on other data, when you want to combine data frames generated from multiple ProtocolData objects.

  • custom_data_src (SuccessFailModel, optional) – An alternate source of the data counts used to compute the desired summary statistics. Currently this can only be a SuccessFailModel.

  • name (str, optional) – The name of this protocol, also used to (by default) name the results produced by this protocol. If None, the class name will be used.

_get_statistic_per_depth(self, statistic, data)
run(self, data, memlimit=None, comm=None, dscomparator=None)

Run this protocol on data.

Parameters
  • results (ProtocolResults or ProtocolResultsDir) – The input results.

  • memlimit (int, optional) – A rough per-processor memory limit in bytes.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to run this protocol in parallel.

  • dscomparator (DataComparator) – Special additional comparator object for comparing data sets.

Returns

SummaryStatisticsResults

class pygsti.protocols.SummaryStatisticsResults(data, protocol_instance)

Bases: pygsti.protocols.protocol.ProtocolResults

Summary statistics computed for a set of data.

Usually the result of running a SummaryStatistics (or derived) protocol.

Parameters
  • data (ProtocolData) – The experimental data these results are generated from.

  • protocol_instance (Protocol) – The protocol that generated these results.

_my_attributes_as_nameddict(self)

Overrides base class behavior so elements of self.statistics form top-level NamedDict

pygsti.protocols._calculate_summary_statistic(x, statistic, lower_cutoff=None)

Utility function that returns statistic(x), or the maximum of statistic(x) and lower_cutoff if lower_cutoff is not None.

pygsti.protocols.polarization_to_success_probability(p, n)

Inverse of success_probability_to_polarization.

pygsti.protocols.success_probability_to_polarization(s, n)

Maps a success probablity s for an n-qubit circuit to the polarization, defined by p = (s - 1/2^n)/(1 - 1/2^n)

pygsti.protocols.classify_circuit_shape(success_probabilities, total_counts, threshold, significance=0.05)

Utility function for computing “capability regions”, as introduced in “Measuring the Capabilities of Quantum Computers” arXiv:2008.11294.

Returns an integer that classifies the input list of success probabilities (SPs) as either

– “success”: all SPs above the specified threshold, specified by the int 2. – “indeterminate”: some SPs are above and some are below the threshold, specified by the int 1. – “fail”: all SPs are below the threshold, specified by the int 0.

This classification is based on a hypothesis test whereby the null hypothesis is “success” or “fail”. That is, the set of success probabilities are designated to be “indeterminate” only if there is statistically significant evidence that at least one success probabilities is above the threshold, and at least one is below. The details of this hypothesis testing are given in the Section 8.B.5 in the Supplement of arXiv:2008.11294.

Parameters
  • success_probabilities (list) – List of success probabilities, should all be in [0,1].

  • total_counts (list) – The number of samples from which the success probabilities where computed.

  • threshold (float) – The threshold for designating a success probability as “success”.

  • significance (float, optional) – The statistical significance for the hypothesis test.

Returns

  • int in (2, 1, 0), corresponding to (“success”, “indeterminate”, “fail”) classifications.

  • If the SPs list is length 0 then NaN is returned, and if it contains only NaN elements then

  • 0 is returned. Otherwise, all NaN elements are ignored.

class pygsti.protocols.VBDataFrame(df, x_axis='Depth', y_axis='Width', x_values=None, y_values=None, edesign=None)

Bases: object

A class for storing a DataFrame that contains volumetric benchmarking data, and that has methods for manipulating that data and creating volumetric-benchmarking-like plots.

select_column_value(self, column_label, column_value)

Filters the dataframe, by discarding all rows of the dataframe for which the column labelled column_label does not have column_value.

Parameters
  • column_label (string) – The label of the column whose value is to be filtered on.

  • column_value (varied) – The value of the column.

Returns

VBDataFrame – A new VBDataFrame that has had the filtering applied to its dataframe.

filter_data(self, column_label, metric='polarization', statistic='mean', indep_x=True, threshold=1 / _np.e, verbosity=0)

Filters the dataframe, by selecting the “best” value at each (x, y) (typically corresponding to circuit shape) for the column specified by column_label. Returns a VBDataFrame whose data that contains only one value for the column labelled by column_label for each (x, y).

Parameters
  • column_label (string) – The label of the column whose “best” value at each circuit shape is to be selected. For example, this could be “Qubits”, to select only the data for the best qubit subset at each circuit shape.

  • metric (string, optional) – The data to be used as the figure-of-merit for performance at each (x, y). Must be a column of the dataframe.

  • statistics (string, optional) – The statistic to apply to the data specified by metric the data at (x, y) into a scalar. Allowed values are: - ‘max’ - ‘min’ - ‘mean’

  • indep_x (bool, optional) – If True, then an independent value, for the column, is selected at each (x, y) value. If False, then the same value for the column is selected for every x value for a given y.

  • threshold (float, optional.) – Does nothing if indep_x is True. If indep_x is False, then ‘metric’ and ‘statistic’ are not enough to uniquely decide which column value is best. In this case, the value is chosen that, for each y in (x,y), maximizes the x value at which the figure-of-merit (as specified by the metric and statistic) drops below the threshold. If there are multiple values that drop below the threshold at the same x (or the figure-of-merit never drops below the threshold for multiple values), then value with the larger figure-of-merit at that x is chosen.

Returns

VBDataFrame – A new VBDataFrame that has had the filtering applied to its dataframe.

vb_data(self, metric='polarization', statistic='mean', lower_cutoff=0.0, no_data_action='discard')

Converts the data into a dictionary, for plotting in a volumetric benchmarking plot. For each (x, y) value (as specified by the axes of this VBDataFrame, and typically circuit shape), pools all of the data specified by metric with that (x, y) and computes the statistic on that data defined by statistic.

Parameters
  • metric (string, optional) – The type of data. Must be a column of the dataframe.

  • statistics (string, optional) –

    The statistic on the data to be computed at each value of (x, y). Options are:

    • ’max’: the maximum

    • ’min’: the minimum.

    • ’mean’: the mean.

    • ’monotonic_max’: the maximum of all the data with (x, y) values that are that large or larger

    • ’monotonic_min’: the minimum of all the data with (x, y) values that are that small or smaller

  • values. (All these options ignore nan) –

  • lower_cutoff (float, optional) – The value to cutoff the statistic at: takes the maximum of the calculated static and this value.

  • no_data_action (string, optional) –

    Sets what to do when there is no data, or only NaN data, at an (x, y) value: - If ‘discard’ then when there is no data, or only NaN data, for an (x,y) value then this (x,y)

    value will not be a key in the returned dictionary

    • If ‘nan’ then when there is no data, or only NaN data, for an (x,y) value then this (x,y) value will be a key in the returned dictionary and its value will be NaN.

    • If ‘min’ then when there is no data, or only NaN data, for an (x,y) value then this (x,y) value will be a key in the returned dictionary and its value will be the minimal value allowed for this statistic, as specified by lower_cutoff.

Returns

dict – A dictionary where the keys are (x,y) tuples (typically circuit shapes) and the values are the VB data at that (x, y).

capability_regions(self, metric='polarization', threshold=1 / _np.e, significance=0.05, monotonic=True, nan_data_action='discard')

Computes a “capability region” from the data, as introduced in “Measuring the Capabilities of Quantum Computers” arXiv:2008.11294. Classifies each (x,y) value (as specified by the x and y axes of the VBDataFrame, which are typically width and depth) as either “success” (the int 2), “indeterminate” (the int 1), “fail” (the int 0), or “no data” (NaN).

Parameters
  • metric (string, optional) – The type of data. Must be ‘polarization’ or ‘success_probability’, and this must be a column in the dataframe.

  • threshold (float, optional) – The threshold for “success”.

  • significance (float, optional) – The statistical significance for the hypothesis tests that are used to classify each circuit shape.

  • monotonic (bool, optional) – If True, makes the region monotonic, i,e, if (x’,y’) > (x,y) then the classification for (x’,y’) is less/worse than for (x,y).

  • no_data_action (string, optional) – If ‘discard’ then when there is no data, for an (x,y) value then this (x,y) value will not be a key in the returned dictionary. Otherwise the value will be NaN.

Returns

dict – A dictionary where the keys are (x,y) tuples (typically circuit shapes) and the values are in (2, 1, 0, NaN).