pygsti.drivers

pyGSTi High-Level Drivers Python Package

Submodules

Package Contents

Classes

ForwardSimulator

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

Functions

create_bootstrap_dataset(input_data_set, generation_method)

Creates a DataSet used for generating bootstrapped error bars.

create_bootstrap_models(num_models, input_data_set, ...)

Creates a series of "bootstrapped" Models.

gauge_optimize_models(gs_list, target_model[, ...])

Optimizes the "spam weight" parameter used when gauge optimizing a set of models.

create_explicit_model(processor_spec[, custom_gates, ...])

run_model_test(model_filename_or_object, ...[, ...])

Compares a Model's predictions to a DataSet using GST-like circuits.

run_linear_gst(data_filename_or_set, ...[, ...])

Perform Linear Gate Set Tomography (LGST).

run_long_sequence_gst(data_filename_or_set, ...[, ...])

Perform long-sequence GST (LSGST).

run_long_sequence_gst_base(data_filename_or_set, ...)

A more fundamental interface for performing end-to-end GST.

run_stdpractice_gst(data_filename_or_set, ...[, ...])

Perform end-to-end GST analysis using standard practices.

Attributes

ROBUST_SUFFIX_LIST

DEFAULT_BAD_FIT_THRESHOLD

pygsti.drivers.create_bootstrap_dataset(input_data_set, generation_method, input_model=None, seed=None, outcome_labels=None, verbosity=1)

Creates a DataSet used for generating bootstrapped error bars.

Parameters

input_data_setDataSet

The data set to use for generating the “bootstrapped” data set.

generation_method{ ‘nonparametric’, ‘parametric’ }

The type of dataset to generate. ‘parametric’ generates a DataSet with the same circuits and sample counts as input_data_set but using the probabilities in input_model (which must be provided). ‘nonparametric’ generates a DataSet with the same circuits and sample counts as input_data_set using the count frequencies of input_data_set as probabilities.

input_modelModel, optional

The model used to compute the probabilities for circuits when generation_method is set to ‘parametric’. If ‘nonparametric’ is selected, this argument must be set to None (the default).

seedint, optional

A seed value for numpy’s random number generator.

outcome_labelslist, optional

The list of outcome labels to include in the output dataset. If None are specified, defaults to the spam labels of input_data_set.

verbosityint, optional

How verbose the function output is. If 0, then printing is suppressed. If 1 (or greater), then printing is not suppressed.

Returns

DataSet

pygsti.drivers.create_bootstrap_models(num_models, input_data_set, generation_method, fiducial_prep, fiducial_measure, germs, max_lengths, input_model=None, target_model=None, start_seed=0, outcome_labels=None, lsgst_lists=None, return_data=False, verbosity=2)

Creates a series of “bootstrapped” Models.

Models are created from a single DataSet (and possibly Model) and are typically used for generating bootstrapped error bars. The resulting Models are obtained by performing MLGST on data generated by repeatedly calling create_bootstrap_dataset() with consecutive integer seed values.

Parameters

num_modelsint

The number of models to create.

input_data_setDataSet

The data set to use for generating the “bootstrapped” data set.

generation_method{ ‘nonparametric’, ‘parametric’ }

The type of data to generate. ‘parametric’ generates DataSets with the same circuits and sample counts as input_data_set but using the probabilities in input_model (which must be provided). ‘nonparametric’ generates DataSets with the same circuits and sample counts as input_data_set using the count frequencies of input_data_set as probabilities.

fiducial_preplist of Circuits

The state preparation fiducial circuits used by MLGST.

fiducial_measurelist of Circuits

The measurement fiducial circuits used by MLGST.

germslist of Circuits

The germ circuits used by MLGST.

max_lengthslist of ints

List of integers, one per MLGST 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.

input_modelModel, optional

The model used to compute the probabilities for circuits when generation_method is set to ‘parametric’. If ‘nonparametric’ is selected, this argument must be set to None (the default).

target_modelModel, optional

Mandatory model to use for as the target model for MLGST when generation_method is set to ‘nonparametric’. When ‘parametric’ is selected, this should be the ideal version of input_model.

start_seedint, optional

The initial seed value for numpy’s random number generator when generating data sets. For each succesive dataset (and model) that are generated, the seed is incremented by one.

outcome_labelslist, optional

The list of Outcome labels to include in the output dataset. If None are specified, defaults to the effect labels of input_data_set.

lsgst_listslist of circuit lists, optional

Provides explicit list of circuit lists to be used in analysis; to be given if the dataset uses “incomplete” or “reduced” sets of circuit. Default is None.

return_databool

Whether generated data sets should be returned in addition to models.

verbosityint

Level of detail printed to stdout.

Returns

modelslist

The list of generated Model objects.

datalist

The list of generated DataSet objects, only returned when return_data == True.

pygsti.drivers.gauge_optimize_models(gs_list, target_model, gate_metric='frobenius', spam_metric='frobenius', plot=True)

Optimizes the “spam weight” parameter used when gauge optimizing a set of models.

This function gauge optimizes multiple times using a range of spam weights and takes the one the minimizes the average spam error multiplied by the average gate error (with respect to a target model).

Parameters

gs_listlist

The list of Model objects to gauge optimize (simultaneously).

target_modelModel

The model to compare the gauge-optimized gates with, and also to gauge-optimize them to.

gate_metric{ “frobenius”, “fidelity”, “tracedist” }, optional

The metric used within the gauge optimization to determing error in the gates.

spam_metric{ “frobenius”, “fidelity”, “tracedist” }, optional

The metric used within the gauge optimization to determing error in the state preparation and measurement.

plotbool, optional

Whether to create a plot of the model-target discrepancy as a function of spam weight (figure displayed interactively).

Returns

list

The list of Models gauge-optimized using the best spamWeight.

pygsti.drivers.create_explicit_model(processor_spec, custom_gates=None, depolarization_strengths=None, stochastic_error_probs=None, lindblad_error_coeffs=None, depolarization_parameterization='depolarize', stochastic_parameterization='stochastic', lindblad_parameterization='auto', evotype='default', simulator='auto', ideal_gate_type='auto', ideal_spam_type='computational', embed_gates=False, basis='pp')
class pygsti.drivers.ForwardSimulator(model=None)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

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

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

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

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

Parameters

modelModel, optional

The model this forward simulator will use to compute circuit outcome probabilities.

property model
Castable
classmethod cast(obj: ForwardSimulator, num_qubits=None)

num_qubits only used if obj == ‘auto’

probs(circuit, outcomes=None, time=None, resource_alloc=None)

Construct a dictionary containing the outcome probabilities for a single circuit.

Parameters
circuitCircuit or tuple of operation labels

The sequence of operation labels specifying the circuit.

outcomeslist or tuple

A sequence of outcomes, which can themselves be either tuples (to include intermediate measurements) or simple strings, e.g. ‘010’. If None, only non-zero outcome probabilities will be reported.

timefloat, optional

The start time at which circuit is evaluated.

resource_allocResourceAllocation, optional

The resources available for computing circuit outcome probabilities.

Returns
probsOutcomeLabelDict

A dictionary with keys equal to outcome labels and values equal to probabilities. If no target outcomes provided, only non-zero probabilities will be reported.

dprobs(circuit, resource_alloc=None)

Construct a dictionary containing outcome probability derivatives for a single circuit.

Parameters
circuitCircuit or tuple of operation labels

The sequence of operation labels specifying the circuit.

resource_allocResourceAllocation, optional

The resources available for computing circuit outcome probability derivatives.

Returns
dprobsOutcomeLabelDict

A dictionary with keys equal to outcome labels and values equal to an array containing the (partial) derivatives of the outcome probability with respect to all model parameters.

hprobs(circuit, resource_alloc=None)

Construct a dictionary containing outcome probability Hessians for a single circuit.

Parameters
circuitCircuit or tuple of operation labels

The sequence of operation labels specifying the circuit.

resource_allocResourceAllocation, optional

The resources available for computing circuit outcome probability Hessians.

Returns
hprobsOutcomeLabelDict

A dictionary with keys equal to outcome labels and values equal to a 2D array that is the Hessian matrix for the corresponding outcome probability (with respect to all model parameters).

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

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

Parameters
circuitslist

The circuits whose outcome probabilities should be computed.

datasetDataSet

The source of data counts that will be compared to the circuit outcome probabilities. The computed outcome probabilities are limited to those with counts present in dataset.

resource_allocResourceAllocation

A available resources and allocation information. These factors influence how the layout (evaluation strategy) is constructed.

array_typestuple, optional

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

derivative_dimensionstuple, optional

A tuple containing, optionally, the parameter-space dimension used when taking first and second derivatives with respect to the cirucit outcome probabilities. This should have minimally 1 or 2 elements when array_types contains ‘ep’ or ‘epp’ types, respectively. If array_types contains either of these strings and derivative_dimensions is None on input then we automatically set derivative_dimensions based on self.model.

verbosityint or VerbosityPrinter

Determines how much output to send to stdout. 0 means no output, higher integers mean more output.

Returns

CircuitOutcomeProbabilityArrayLayout

bulk_probs(circuits, clip_to=None, resource_alloc=None, smartc=None)

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

Parameters
circuitslist of Circuits

The list of circuits. May also be a CircuitOutcomeProbabilityArrayLayout object containing pre-computed quantities that make this function run faster.

clip_to2-tuple, optional

(min,max) to clip return value if not None.

resource_allocResourceAllocation, optional

A resource allocation object describing the available resources and a strategy for partitioning them.

smartcSmartCache, optional

A cache object to cache & use previously cached values inside this function.

Returns
probsdictionary

A dictionary such that probs[circuit] is an ordered dictionary of outcome probabilities whose keys are outcome labels.

bulk_dprobs(circuits, resource_alloc=None, smartc=None)

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

Parameters
circuitslist of Circuits

The list of circuits. May also be a CircuitOutcomeProbabilityArrayLayout object containing pre-computed quantities that make this function run faster.

resource_allocResourceAllocation, optional

A resource allocation object describing the available resources and a strategy for partitioning them.

smartcSmartCache, optional

A cache object to cache & use previously cached values inside this function.

Returns
dprobsdictionary

A dictionary such that dprobs[circuit] is an ordered dictionary of derivative arrays (one element per differentiated parameter) whose keys are outcome labels

bulk_hprobs(circuits, resource_alloc=None, smartc=None)

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

Parameters
circuitslist of Circuits

The list of circuits. May also be a CircuitOutcomeProbabilityArrayLayout object containing pre-computed quantities that make this function run faster.

resource_allocResourceAllocation, optional

A resource allocation object describing the available resources and a strategy for partitioning them.

smartcSmartCache, optional

A cache object to cache & use previously cached values inside this function.

Returns
hprobsdictionary

A dictionary such that hprobs[circuit] is an ordered dictionary of Hessian arrays (a square matrix with one row/column per differentiated parameter) whose keys are outcome labels

bulk_fill_probs(array_to_fill, layout)

Compute the outcome probabilities for a list circuits.

This routine fills a 1D array, array_to_fill with circuit outcome probabilities as dictated by a CircuitOutcomeProbabilityArrayLayout (“COPA layout”) object, which is usually specifically tailored for efficiency.

The array_to_fill array must have length equal to the number of elements in layout, and the meanings of each element are given by layout.

Parameters
array_to_fillnumpy ndarray

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

layoutCircuitOutcomeProbabilityArrayLayout

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

Returns

None

bulk_fill_dprobs(array_to_fill, layout, pr_array_to_fill=None)

Compute the outcome probability-derivatives for an entire tree of circuits.

This routine fills a 2D array, array_to_fill with circuit outcome probabilities as dictated by a CircuitOutcomeProbabilityArrayLayout (“COPA layout”) object, which is usually specifically tailored for efficiency.

The array_to_fill array must have length equal to the number of elements in layout, and the meanings of each element are given by layout.

Parameters
array_to_fillnumpy ndarray

an already-allocated 2D numpy array of shape (len(layout), Np), where Np is the number of model parameters being differentiated with respect to.

layoutCircuitOutcomeProbabilityArrayLayout

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

pr_mx_to_fillnumpy array, optional

when not None, an already-allocated length-len(layout) numpy array that is filled with probabilities, just as in bulk_fill_probs().

Returns

None

bulk_fill_hprobs(array_to_fill, layout, pr_array_to_fill=None, deriv1_array_to_fill=None, deriv2_array_to_fill=None)

Compute the outcome probability-Hessians for an entire list of circuits.

Similar to bulk_fill_probs(…), but fills a 3D array with the Hessians for each circuit outcome probability.

Parameters
array_to_fillnumpy ndarray

an already-allocated numpy array of shape (len(layout),M1,M2) where M1 and M2 are the number of selected model parameters (by wrt_filter1 and wrt_filter2).

layoutCircuitOutcomeProbabilityArrayLayout

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

pr_mx_to_fillnumpy array, optional

when not None, an already-allocated length-len(layout) numpy array that is filled with probabilities, just as in bulk_fill_probs().

deriv1_array_to_fillnumpy array, optional

when not None, an already-allocated numpy array of shape (len(layout),M1) that is filled with probability derivatives, similar to bulk_fill_dprobs() (see array_to_fill for a definition of M1).

deriv2_array_to_fillnumpy array, optional

when not None, an already-allocated numpy array of shape (len(layout),M2) that is filled with probability derivatives, similar to bulk_fill_dprobs() (see array_to_fill for a definition of M2).

Returns

None

iter_hprobs_by_rectangle(layout, wrt_slices_list, return_dprobs_12=False)

Iterates over the 2nd derivatives of a layout’s circuit probabilities one rectangle at a time.

This routine can be useful when memory constraints make constructing the entire Hessian at once impractical, and as it only computes a subset of the Hessian’s rows and colums (a “rectangle”) at once. For example, the Hessian of a function of many circuit probabilities can often be computed rectangle-by-rectangle and without the need to ever store the entire Hessian at once.

Parameters
layoutCircuitOutcomeProbabilityArrayLayout

A layout for generated arrays, describing what circuit outcome each element corresponds to. Usually given by a prior call to create_layout().

wrt_slices_listlist

A list of (rowSlice,colSlice) 2-tuples, each of which specify a “rectangle” of the Hessian to compute. Iterating over the output of this function iterates over these computed rectangles, in the order given by wrt_slices_list. rowSlice and colSlice must by Python slice objects.

return_dprobs_12boolean, optional

If true, the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability generated by the sequence and spam label indexed by iOpStr and iSpamLabel. d12 has the same dimensions as the Hessian, and turns out to be useful when computing the Hessian of functions of the probabilities.

Returns
rectangle_generator

A generator which, when iterated, yields the 3-tuple (rowSlice, colSlice, hprobs) or (rowSlice, colSlice, hprobs, dprobs12) (the latter if return_dprobs_12 == True). rowSlice and colSlice are slices directly from wrt_slices_list. hprobs and dprobs12 are arrays of shape E x B x B’, where:

  • E is the length of layout elements

  • B is the number of parameter rows (the length of rowSlice)

  • B’ is the number of parameter columns (the length of colSlice)

If mx, dp1, and dp2 are the outputs of bulk_fill_hprobs() (i.e. args mx_to_fill, deriv1_mx_to_fill, and deriv2_mx_to_fill), then:

  • hprobs == mx[:,rowSlice,colSlice]

  • dprobs12 == dp1[:,rowSlice,None] * dp2[:,None,colSlice]

pygsti.drivers.ROBUST_SUFFIX_LIST = ['.robust', '.Robust', '.robust+', '.Robust+']
pygsti.drivers.DEFAULT_BAD_FIT_THRESHOLD = 2.0
pygsti.drivers.run_model_test(model_filename_or_object, data_filename_or_set, processorspec_filename_or_object, prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, germs_list_or_filename, max_lengths, gauge_opt_params=None, advanced_options=None, comm=None, mem_limit=None, output_pkl=None, verbosity=2, checkpoint=None, checkpoint_path=None, disable_checkpointing=False, simulator: pygsti.forwardsims.ForwardSimulator.Castable | None = None)

Compares a Model’s predictions to a DataSet using GST-like circuits.

This routine tests a Model model against a DataSet using a specific set of structured, GST-like circuits (given by fiducials, max_lengths and germs). In particular, circuits are constructed by repeating germ strings an integer number of times such that the length of the repeated germ is less than or equal to the maximum length set in max_lengths. Each string thus constructed is sandwiched between all pairs of (preparation, measurement) fiducial sequences.

model_filename_or_object is used directly (without any optimization) as the the model estimate at each maximum-length “iteration”. The model is given a trivial default_gauge_group so that it is not altered during any gauge optimization step.

A ModelEstimateResults object is returned, which encapsulates the model estimate and related parameters, and can be used with report-generation routines.

Parameters

model_filename_or_objectModel or string

The model model, specified either directly or by the filename of a model file (text format).

data_filename_or_setDataSet or string

The data set object to use for the analysis, specified either directly or by the filename of a dataset file (assumed to be a pickled DataSet if extension is ‘pkl’ otherwise assumed to be in pyGSTi’s text format).

processorspec_filename_or_objectProcessorSpec or string

A specification of the processor this model test is to be run on, given either directly or by the filename of a processor-spec file (text format). The processor specification contains basic interface-level information about the processor being tested, e.g., its state space and available gates.

prep_fiducial_list_or_filename(list of Circuits) or string

The state preparation fiducial circuits, specified either directly or by the filename of a circuit list file (text format).

meas_fiducial_list_or_filename(list of Circuits) or string or None

The measurement fiducial circuits, specified either directly or by the filename of a circuit list file (text format). If None, then use the same strings as specified by prep_fiducial_list_or_filename.

germs_list_or_filename(list of Circuits) or string

The germ circuits, specified either directly or by the filename of a circuit list file (text format).

max_lengthslist of ints

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.

gauge_opt_paramsdict, optional

A dictionary of arguments to gaugeopt_to_target(), specifying how the final gauge optimization should be performed. The keys and values of this dictionary may correspond to any of the arguments of gaugeopt_to_target() except for the first model argument, which is specified internally. The target_model argument, can be set, but is specified internally when it isn’t. If None, then the dictionary {‘item_weights’: {‘gates’:1.0, ‘spam’:0.001}} is used. If False, then then no gauge optimization is performed.

advanced_optionsdict, optional

Specifies advanced options most of which deal with numerical details of the objective function or expert-level functionality.

commmpi4py.MPI.Comm, optional

When not None, an MPI communicator for distributing the computation across multiple processors.

mem_limitint or None, optional

A rough memory limit in bytes which restricts the amount of memory used (per core when run on multi-CPUs).

output_pklstr or file, optional

If not None, a file(name) to pickle.dump the returned Results object to (only the rank 0 process performs the dump when comm is not None).

verbosityint, optional

The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation.

checkpointModelTestCheckpoint, optional (default None)

If specified use a previously generated checkpoint object to restart or warm start this run part way through.

checkpoint_pathstr, optional (default None)

A string for the path/name to use for writing intermediate checkpoint files to disk. Format is {path}/{name}, without inclusion of the json file extension. This {path}/{name} combination will have the latest completed iteration number appended to it before writing it to disk. If none, the value of {name} will be set to the name of the protocol being run.

disable_checkpointingbool, optional (default False)

When set to True checkpoint objects will not be constructed and written to disk during the course of this protocol. It is strongly recommended that this be kept set to False without good reason to disable the checkpoints.

simulatorForwardSimulator.Castable or None
Ignored if None. If not None, then we call

fwdsim = ForwardSimulator.cast(simulator),

and we set the .sim attribute of every Model we encounter to fwdsim.

Returns

Results

pygsti.drivers.run_linear_gst(data_filename_or_set, target_model_filename_or_object, prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, gauge_opt_params=None, advanced_options=None, comm=None, mem_limit=None, output_pkl=None, verbosity=2)

Perform Linear Gate Set Tomography (LGST).

This function differs from the lower level run_lgst() function in that it may perform a post-LGST gauge optimization and this routine returns a Results object containing the LGST estimate.

Overall, this is a high-level driver routine which can be used similarly to run_long_sequence_gst() whereas run_lgst is a low-level routine used when building your own algorithms.

Parameters

data_filename_or_setDataSet or string

The data set object to use for the analysis, specified either directly or by the filename of a dataset file (assumed to be a pickled DataSet if extension is ‘pkl’ otherwise assumed to be in pyGSTi’s text format).

target_model_filename_or_objectModel or string

The target model specifying the gates and SPAM elements that LGST is to be run on, given either directly or by the filename of a model file (text format).

prep_fiducial_list_or_filename(list of Circuits) or string

The state preparation fiducial circuits, specified either directly or by the filename of a circuit list file (text format).

meas_fiducial_list_or_filename(list of Circuits) or string or None

The measurement fiducial circuits, specified either directly or by the filename of a circuit list file (text format). If None, then use the same strings as specified by prep_fiducial_list_or_filename.

gauge_opt_paramsdict, optional

A dictionary of arguments to gaugeopt_to_target(), specifying how the final gauge optimization should be performed. The keys and values of this dictionary may correspond to any of the arguments of gaugeopt_to_target() except for the first model argument, which is specified internally. The target_model argument, can be set, but is specified internally when it isn’t. If None, then the dictionary {‘item_weights’: {‘gates’:1.0, ‘spam’:0.001}} is used. If False, then then no gauge optimization is performed.

advanced_optionsdict, optional

Specifies advanced options most of which deal with numerical details of the objective function or expert-level functionality. See run_long_sequence_gst().

commmpi4py.MPI.Comm, optional

When not None, an MPI communicator for distributing the computation across multiple processors. In this LGST case, this is just the gauge optimization.

mem_limitint or None, optional

A rough memory limit in bytes which restricts the amount of memory used (per core when run on multi-CPUs).

output_pklstr or file, optional

If not None, a file(name) to pickle.dump the returned Results object to (only the rank 0 process performs the dump when comm is not None).

verbosityint, optional

The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation.

Returns

Results

pygsti.drivers.run_long_sequence_gst(data_filename_or_set, target_model_filename_or_object, prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, germs_list_or_filename, max_lengths, gauge_opt_params=None, advanced_options=None, comm=None, mem_limit=None, output_pkl=None, verbosity=2, checkpoint=None, checkpoint_path=None, disable_checkpointing=False, simulator: pygsti.forwardsims.ForwardSimulator.Castable | None = None)

Perform long-sequence GST (LSGST).

This analysis fits a model (target_model_filename_or_object) to data (data_filename_or_set) using the outcomes from periodic GST circuits constructed by repeating germ strings an integer number of times such that the length of the repeated germ is less than or equal to the maximum length set in max_lengths. When LGST is applicable (i.e. for explicit models with full or TP parameterizations), the LGST estimate of the gates is computed, gauge optimized, and used as a starting seed for the remaining optimizations.

LSGST iterates len(max_lengths) times, optimizing the chi2 using successively larger sets of circuits. On the i-th iteration, the repeated germs sequences limited by max_lengths[i] are included in the growing set of circuits used by LSGST. The final iteration maximizes the log-likelihood.

Once computed, the model estimates are optionally gauge optimized as directed by gauge_opt_params. A ModelEstimateResults object is returned, which encapsulates the input and outputs of this GST analysis, and can generate final end-user output such as reports and presentations.

Parameters

data_filename_or_setDataSet or string

The data set object to use for the analysis, specified either directly or by the filename of a dataset file (assumed to be a pickled DataSet if extension is ‘pkl’ otherwise assumed to be in pyGSTi’s text format).

target_model_filename_or_objectModel or string

The target model, specified either directly or by the filename of a model file (text format).

prep_fiducial_list_or_filename(list of Circuits) or string

The state preparation fiducial circuits, specified either directly or by the filename of a circuit list file (text format).

meas_fiducial_list_or_filename(list of Circuits) or string or None

The measurement fiducial circuits, specified either directly or by the filename of a circuit list file (text format). If None, then use the same strings as specified by prep_fiducial_list_or_filename.

germs_list_or_filename(list of Circuits) or string

The germ circuits, specified either directly or by the filename of a circuit list file (text format).

max_lengthslist of ints

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.

gauge_opt_paramsdict, optional

A dictionary of arguments to gaugeopt_to_target(), specifying how the final gauge optimization should be performed. The keys and values of this dictionary may correspond to any of the arguments of gaugeopt_to_target() except for the first model argument, which is specified internally. The target_model argument, can be set, but is specified internally when it isn’t. If None, then the dictionary {‘item_weights’: {‘gates’:1.0, ‘spam’:0.001}} is used. If False, then then no gauge optimization is performed.

advanced_optionsdict, optional

Specifies advanced options most of which deal with numerical details of the objective function or expert-level functionality. The allowed keys and values include: - objective = {‘chi2’, ‘logl’} - op_labels = list of strings - circuit_weights = dict or None - starting_point = “LGST-if-possible” (default), “LGST”, or “target” - depolarize_start = float (default == 0) - randomize_start = float (default == 0) - contract_start_to_cptp = True / False (default) - cptpPenaltyFactor = float (default = 0) - tolerance = float or dict w/’relx’,’relf’,’f’,’jac’,’maxdx’ keys - max_iterations = int - finitediff_iterations = int - min_prob_clip = float - min_prob_clip_for_weighting = float (default == 1e-4) - prob_clip_interval = tuple (default == (-1e6,1e6) - radius = float (default == 1e-4) - use_freq_weighted_chi2 = True / False (default) - XX nested_circuit_lists = True (default) / False - XX include_lgst = True / False (default is True) - distribute_method = “default”, “circuits” or “deriv” - profile = int (default == 1) - check = True / False (default) - XX op_label_aliases = dict (default = None) - always_perform_mle = bool (default = False) - only_perform_mle = bool (default = False) - XX truncScheme = “whole germ powers” (default) or “truncated germ powers” or “length as exponent” - appendTo = Results (default = None) - estimateLabel = str (default = “default”) - XX missingDataAction = {‘drop’,’raise’} (default = ‘drop’) - XX string_manipulation_rules = list of (find,replace) tuples - germ_length_limits = dict of form {germ: maxlength} - record_output = bool (default = True) - timeDependent = bool (default = False)

commmpi4py.MPI.Comm, optional

When not None, an MPI communicator for distributing the computation across multiple processors.

mem_limitint or None, optional

A rough memory limit in bytes which restricts the amount of memory used (per core when run on multi-CPUs).

output_pklstr or file, optional

If not None, a file(name) to pickle.dump the returned Results object to (only the rank 0 process performs the dump when comm is not None).

verbosityint, optional

The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation. - 0 – prints nothing - 1 – shows progress bar for entire iterative GST - 2 – show summary details about each individual iteration - 3 – also shows outer iterations of LM algorithm - 4 – also shows inner iterations of LM algorithm - 5 – also shows detailed info from within jacobian and objective function calls.

checkpointGateSetTomographyCheckpoint, optional (default None)

If specified use a previously generated checkpoint object to restart or warm start this run part way through.

checkpoint_pathstr, optional (default None)

A string for the path/name to use for writing intermediate checkpoint files to disk. Format is {path}/{name}, without inclusion of the json file extension. This {path}/{name} combination will have the latest completed iteration number appended to it before writing it to disk. If none, the value of {name} will be set to the name of the protocol being run.

disable_checkpointingbool, optional (default False)

When set to True checkpoint objects will not be constructed and written to disk during the course of this protocol. It is strongly recommended that this be kept set to False without good reason to disable the checkpoints.

simulatorForwardSimulator.Castable or None
Ignored if None. If not None, then we call

fwdsim = ForwardSimulator.cast(simulator),

and we set the .sim attribute of every Model we encounter to fwdsim.

Returns

Results

pygsti.drivers.run_long_sequence_gst_base(data_filename_or_set, target_model_filename_or_object, lsgst_lists, gauge_opt_params=None, advanced_options=None, comm=None, mem_limit=None, output_pkl=None, verbosity=2, checkpoint=None, checkpoint_path=None, disable_checkpointing=False, simulator: pygsti.forwardsims.ForwardSimulator.Castable | None = None)

A more fundamental interface for performing end-to-end GST.

Similar to run_long_sequence_gst() except this function takes lsgst_lists, a list of either raw circuit lists or of PlaquetteGridCircuitStructure objects to define which circuits are used on each GST iteration.

Parameters

data_filename_or_setDataSet or string

The data set object to use for the analysis, specified either directly or by the filename of a dataset file (assumed to be a pickled DataSet if extension is ‘pkl’ otherwise assumed to be in pyGSTi’s text format).

target_model_filename_or_objectModel or string

The target model, specified either directly or by the filename of a model file (text format).

lsgst_listslist of lists or PlaquetteGridCircuitStructure(s)

An explicit list of either the raw circuit lists to be used in the analysis or of PlaquetteGridCircuitStructure objects, which additionally contain the structure of a set of circuits. A single PlaquetteGridCircuitStructure object can also be given, which is equivalent to passing a list of successive L-value truncations of this object (e.g. if the object has Ls = [1,2,4] then this is like passing a list of three PlaquetteGridCircuitStructure objects w/truncations [1], [1,2], and [1,2,4]).

gauge_opt_paramsdict, optional

A dictionary of arguments to gaugeopt_to_target(), specifying how the final gauge optimization should be performed. The keys and values of this dictionary may correspond to any of the arguments of gaugeopt_to_target() except for the first model argument, which is specified internally. The target_model argument, can be set, but is specified internally when it isn’t. If None, then the dictionary {‘item_weights’: {‘gates’:1.0, ‘spam’:0.001}} is used. If False, then then no gauge optimization is performed.

advanced_optionsdict, optional

Specifies advanced options most of which deal with numerical details of the objective function or expert-level functionality. See run_long_sequence_gst() for a list of the allowed keys, with the exception “nested_circuit_lists”, “op_label_aliases”, “include_lgst”, and “truncScheme”.

commmpi4py.MPI.Comm, optional

When not None, an MPI communicator for distributing the computation across multiple processors.

mem_limitint or None, optional

A rough memory limit in bytes which restricts the amount of memory used (per core when run on multi-CPUs).

output_pklstr or file, optional

If not None, a file(name) to pickle.dump the returned Results object to (only the rank 0 process performs the dump when comm is not None).

verbosityint, optional

The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation. - 0 – prints nothing - 1 – shows progress bar for entire iterative GST - 2 – show summary details about each individual iteration - 3 – also shows outer iterations of LM algorithm - 4 – also shows inner iterations of LM algorithm - 5 – also shows detailed info from within jacobian and objective function calls.

checkpointGateSetTomographyCheckpoint, optional (default None)

If specified use a previously generated checkpoint object to restart or warm start this run part way through.

checkpoint_pathstr, optional (default None)

A string for the path/name to use for writing intermediate checkpoint files to disk. Format is {path}/{name}, without inclusion of the json file extension. This {path}/{name} combination will have the latest completed iteration number appended to it before writing it to disk. If none, the value of {name} will be set to the name of the protocol being run.

disable_checkpointingbool, optional (default False)

When set to True checkpoint objects will not be constructed and written to disk during the course of this protocol. It is strongly recommended that this be kept set to False without good reason to disable the checkpoints.

simulatorForwardSimulator.Castable or None
Ignored if None. If not None, then we call

fwdsim = ForwardSimulator.cast(simulator),

and we set the .sim attribute of every Model we encounter to fwdsim.

Returns

Results

pygsti.drivers.run_stdpractice_gst(data_filename_or_set, target_model_filename_or_object, prep_fiducial_list_or_filename, meas_fiducial_list_or_filename, germs_list_or_filename, max_lengths, modes=('full TP', 'CPTPLND', 'Target'), gaugeopt_suite='stdgaugeopt', gaugeopt_target=None, models_to_test=None, comm=None, mem_limit=None, advanced_options=None, output_pkl=None, verbosity=2, checkpoint=None, checkpoint_path=None, disable_checkpointing=False, simulator: pygsti.forwardsims.ForwardSimulator.Castable | None = None)

Perform end-to-end GST analysis using standard practices.

This routines is an even higher-level driver than run_long_sequence_gst(). It performs bottled, typically-useful, runs of long sequence GST on a dataset. This essentially boils down to running run_long_sequence_gst() one or more times using different model parameterizations, and performing commonly-useful gauge optimizations, based only on the high-level modes argument.

Parameters

data_filename_or_setDataSet or string

The data set object to use for the analysis, specified either directly or by the filename of a dataset file (assumed to be a pickled DataSet if extension is ‘pkl’ otherwise assumed to be in pyGSTi’s text format).

target_model_filename_or_objectModel or string

A specification of the target model that GST is to be run on, given either directly or by the filename of a model (text format).

prep_fiducial_list_or_filename(list of Circuits) or string

The state preparation fiducial circuits, specified either directly or by the filename of a circuit list file (text format).

meas_fiducial_list_or_filename(list of Circuits) or string or None

The measurement fiducial circuits, specified either directly or by the filename of a circuit list file (text format). If None, then use the same strings as specified by prep_fiducial_list_or_filename.

germs_list_or_filename(list of Circuits) or string

The germ circuits, specified either directly or by the filename of a circuit list file (text format).

max_lengthslist of ints

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.

modesiterable of strs, optional (default (‘full TP’,’CPTPLND’,’Target’)

An iterable strings corresponding to 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_suitestr or list or dict, optional

Specifies which gauge optimizations to perform on each estimate. A string or list of strings (see below) specifies built-in sets of gauge optimizations, otherwise gaugeopt_suite should be a dictionary of gauge-optimization parameter dictionaries, as specified by the gauge_opt_params argument of run_long_sequence_gst(). The key names of gaugeopt_suite then label the gauge optimizations within the resuling Estimate objects. 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_targetModel, 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 target_model_filename_or_object, which are used as the default when gaugeopt_target is None.

models_to_testdict, 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.

commmpi4py.MPI.Comm, optional

When not None, an MPI communicator for distributing the computation across multiple processors.

mem_limitint or None, optional

A rough memory limit in bytes which restricts the amount of memory used (per core when run on multi-CPUs).

advanced_optionsdict, optional

Specifies advanced options most of which deal with numerical details of the objective function or expert-level functionality. See run_long_sequence_gst() for a list of the allowed keys for each such dictionary.

output_pklstr or file, optional

If not None, a file(name) to pickle.dump the returned Results object to (only the rank 0 process performs the dump when comm is not None).

verbosityint, optional

The ‘verbosity’ option is an integer specifying the level of detail printed to stdout during the calculation.

checkpointStandardGSTCheckpoint, optional (default None)

If specified use a previously generated checkpoint object to restart or warm start this run part way through.

checkpoint_pathstr, optional (default None)

A string for the path/name to use for writing intermediate checkpoint files to disk. Format is {path}/{name}, without inclusion of the json file extension. This {path}/{name} combination will have the latest completed iteration number appended to it before writing it to disk. If none, the value of {name} will be set to the name of the protocol being run.

disable_checkpointingbool, optional (default False)

When set to True checkpoint objects will not be constructed and written to disk during the course of this protocol. It is strongly recommended that this be kept set to False without good reason to disable the checkpoints.

simulatorForwardSimulator.Castable or None
Ignored if None. If not None, then we call

fwdsim = ForwardSimulator.cast(simulator),

and we set the .sim attribute of every Model we encounter to fwdsim.

Returns

Results