pygsti.models.model

Defines the Model class and supporting functionality.

Module Contents

Classes

Model

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

OpModel

A Model that contains operators (i.e. "members"), having a container structure.

Attributes

MEMLIMIT_FOR_NONGAUGE_PARAMS

pygsti.models.model.MEMLIMIT_FOR_NONGAUGE_PARAMS = 'None'
class pygsti.models.model.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_spaceStateSpace

The state space of this model.

property state_space

State space labels

Returns

StateSpaceLabels

property hyperparams

Dictionary of hyperparameters associated with this model

Returns

dict

property num_params

The number of free parameters when vectorizing this model.

Returns
int

the number of model parameters.

property num_modeltest_params

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

Often times, this is the same as 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

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

property parameter_labels

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

property parameter_labels_pretty

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_bounds(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
indexint

The index of the paramter whose bounds should be set.

lower_bound, upper_boundfloat, 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

set_parameter_label(index, label)

Set the label of a single model parameter.

Parameters
indexint

The index of the paramter whose label should be set.

labelobject

An object that serves to label this parameter. Often a string.

Returns

None

to_vector()

Returns the model vectorized according to the optional parameters.

Returns
numpy array

The vectorized model parameters.

from_vector(v, close=False)

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

Parameters
vnumpy.ndarray

A vector of parameters, with length equal to self.num_params.

closebool, optional

Set to True if v is close to the current parameter vector. This can make some operations more efficient.

Returns

None

abstract probabilities(circuit, clip_to=None)

Construct a dictionary containing the outcome probabilities of circuit.

Parameters
circuitCircuit or tuple of operation labels

The sequence of operation labels specifying the circuit.

clip_to2-tuple, optional

(min,max) to clip probabilities to if not None.

Returns
probsdictionary

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

abstract bulk_probabilities(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_to2-tuple, optional

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

commmpi4py.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_limitint, optional

A rough memory limit in bytes which is used to determine processor allocation.

smartcSmartCache, optional

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

Returns
probsdictionary

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.

copy()

Copy this model.

Returns
Model

a (deep) copy of this model.

circuit_outcomes(circuit)

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

Parameters
circuitCircuit

Circuit to get outcomes of.

Returns

tuple

compute_num_outcomes(circuit)

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

Parameters
circuitCircuit

The circuit to simplify

Returns

int

complete_circuit(circuit)

Adds any implied preparation or measurement layers to circuit

Parameters
circuitCircuit

Circuit to act on.

Returns
Circuit

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

class pygsti.models.model.OpModel(state_space, basis, evotype, layer_rules, simulator='auto')

Bases: Model

A Model that contains operators (i.e. “members”), having a container structure.

These operators are independently (sort of) parameterized and can be thought to have dense representations (even if they’re not actually stored that way). This gives rise to the model having basis and evotype members.

Secondly, attached to an OpModel is the idea of “circuit simplification” whereby the operators (preps, operations, povms, instruments) within a circuit get simplified to things corresponding to a single outcome probability, i.e. pseudo-circuits containing just preps, operations, and POMV effects.

Thirdly, an OpModel is assumed to use a layer-by-layer evolution, and, because of circuit simplification process, the calculaton of circuit outcome probabilities has been pushed to a ForwardSimulator object which just deals with the forward simulation of simplified circuits. Furthermore, instead of relying on a static set of operations a forward simulator queries a LayerLizard for layer operations, making it possible to build up layer operations in an on-demand fashion from pieces within the model.

Parameters

state_spaceStateSpace

The state space for this model.

basisBasis

The basis used for the state space by dense operator representations.

evotypeEvotype or str, optional

The evolution type of this model, describing how states are represented. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

layer_rulesLayerRules

The “layer rules” used for constructing operators for circuit layers. This functionality is essential to using this model to simulate ciruits, and is typically supplied by derived classes.

simulatorForwardSimulator or {“auto”, “matrix”, “map”}

The forward simulator (or typ) that this model should use. “auto” tries to determine the best type automatically.

Creates a new OpModel. Rarely used except from derived classes __init__ functions.

property sim

Forward simulator for this model

property evotype

Evolution type

Returns

str

property basis

The basis used to represent dense (super)operators of this model

Returns

Basis

property dim

The dimension of the model.

This equals d when the gate (or, more generally, circuit-layer) matrices would have shape d x d and spam vectors would have shape d x 1 (if they were computed).

Returns
int

model dimension

property num_params

The number of free parameters when vectorizing this model.

Returns
int

the number of model parameters.

property param_interposer
property primitive_prep_labels
property primitive_povm_labels
property primitive_op_labels
property primitive_instrument_labels
print_parameters_by_op(max_depth=0)
collect_parameters(params_to_collect, new_param_label=None)

Updates this model’s parameters so that previously independent parameters are tied together.

The model’s parameterization is modified so that all of the parameters given by params_to_collect are replaced by a single parameter. The label of this single parameter may be given if desired.

Note that after this function is called the model’s parameter vector (i.e. the result of to_vector()) should be assumed to have a new format unrelated to the parameter vector before their adjustment. For example, you should not assume that un-modified parameters will retain their old indices.

Parameters
params_to_collectiterable

A list or tuple of parameter labels describing the parameters to collect. These should be a subset of the elements of self.parameter_labels or of self.parameter_labels_pretty, or integer indices into the model’s parameter vector. If empty, no parameter adjustment is performed.

new_param_labelobject, optional

The label for the new common parameter. If None, then the parameter label of the first collected parameter is used.

Returns

None

uncollect_parameters(param_to_uncollect)

Updates this model’s parameters so that a common paramter becomes independent parameters.

The model’s parameterization is modified so that each usage of the given parameter in the model’s parameterized operations is promoted to being a new independent parameter. The labels of the new parameters are set by the operations.

Note that after this function is called the model’s parameter vector (i.e. the result of to_vector()) should be assumed to have a new format unrelated to the parameter vector before their adjustment. For example, you should not assume that un-modified parameters will retain their old indices.

Parameters
param_to_uncollectint or object

A parameter label specifying the parameter to “uncollect”. This should be an element of self.parameter_labels or self.parameter_labels_pretty, or it may be an integer index into the model’s parameter vector.

Returns

None

to_vector()

Returns the model vectorized according to the optional parameters.

Returns
numpy array

The vectorized model parameters.

from_vector(v, close=False)

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

The inverse of to_vector.

Parameters
vnumpy.ndarray

A vector of parameters, with length equal to self.num_params.

closebool, optional

Set to True if v is close to the current parameter vector. This can make some operations more efficient.

Returns

None

circuit_outcomes(circuit)

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

Parameters
circuitCircuit

Circuit to get outcomes of.

Returns

tuple

split_circuit(circuit, erroron=('prep', 'povm'), split_prep=True, split_povm=True)

Splits a circuit into prep_layer + op_layers + povm_layer components.

If circuit does not contain a prep label or a povm label a default label is returned if one exists.

Parameters
circuitCircuit

A circuit, possibly beginning with a state preparation label and ending with a povm label.

errorontuple of {‘prep’,’povm’}

A ValueError is raised if a preparation or povm label cannot be resolved when ‘prep’ or ‘povm’ is included in ‘erroron’. Otherwise None is returned in place of unresolvable labels. An exception is when this model has no preps or povms, in which case None is always returned and errors are never raised, since in this case one usually doesn’t expect to use the Model to compute probabilities (e.g. in germ selection).

split_prepbool, optional

Whether to split off the state prep and return it as prep_label. If False, then the returned preparation label is always None, and is not removed from ops_only_circuit.

split_povmbool, optional

Whether to split off the POVM and return it as povm_label. If False, then the returned POVM label is always None, and is not removed from ops_only_circuit.

Returns

prep_label : str or None ops_only_circuit : Circuit povm_label : str or None

complete_circuit(circuit)

Adds any implied preparation or measurement layers to circuit

Converts circuit into a “complete circuit”, where the first (0-th) layer is a state preparation and the final layer is a measurement (POVM) layer.

Parameters
circuitCircuit

Circuit to act on.

Returns
Circuit

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

circuit_layer_operator(layerlbl, typ='auto')

Construct or retrieve the operation associated with a circuit layer.

Parameters
layerlblLabel

The circuit-layer label to construct an operation for.

typ{‘op’,’prep’,’povm’,’auto’}

The type of layer layerlbl refers to: ‘prep’ is for state preparation (only at the beginning of a circuit), ‘povm’ is for a measurement: a POVM or effect label (only at the end of a circuit), and ‘op’ is for all other “middle” circuit layers.

Returns

LinearOperator or State or POVM

circuit_operator(circuit)

Construct or retrieve the operation associated with a circuit.

Parameters
circuitCircuit

The circuit to construct an operation for. This circuit should not contain any state preparation or measurement layers.

Returns

LinearOperator

probabilities(circuit, outcomes=None, time=None)

Construct a dictionary containing the outcome probabilities of 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’.

timefloat, optional

The start time at which circuit is evaluated.

Returns
probsOutcomeLabelDict

A dictionary with keys equal to outcome labels and values equal to probabilities.

bulk_probabilities(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_to2-tuple, optional

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

commmpi4py.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_limitint, optional

A rough memory limit in bytes which is used to determine processor allocation.

datasetDataSet, optional

If not None, restrict what is computed to only those probabilities corresponding to non-zero counts (observed outcomes) in this data set.

smartcSmartCache, optional

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

Returns
probsdictionary

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.

copy()

Copy this model.

Returns
Model

a (deep) copy of this model.

abstract create_modelmember_graph()

Generate a ModelMemberGraph for the model.

Returns
ModelMemberGraph

A directed graph capturing dependencies among model members

print_modelmembers()

Print a summary of all the members within this model.

is_similar(other_model, rtol=1e-05, atol=1e-08)

Whether or not two Models have the same structure.

If True, then the two models are the same except for, perhaps, being at different parameter-space points (i.e. having different parameter vectors). Similar models, A and B, can be made equivalent (see is_equivalent()) by calling modelA.from_vector(modelB.to_vector()).

Parameters
other_model: Model

The model to compare against

rtolfloat, optional

Relative tolerance used to check if floating point values are “equal”, as passed to numpy.allclose.

atol: float, optional

Absolute tolerance used to check if floating point values are “equal”, as passed to numpy.allclose.

Returns

bool

is_equivalent(other_model, rtol=1e-05, atol=1e-08)

Whether or not two Models are equivalent to each other.

If True, then the two models have the same structure and the same parameters, so they are in all ways alike and will compute the same probabilities.

Parameters
other_model: Model

The model to compare against

rtolfloat, optional

Relative tolerance used to check if floating point (including parameter) values are “equal”, as passed to numpy.allclose.

atol: float, optional

Absolute tolerance used to check if floating point (including parameter) values are “equal”, as passed to numpy.allclose.

Returns

bool

setup_fogi(initial_gauge_basis, create_complete_basis_fn=None, op_label_abbrevs=None, reparameterize=False, reduce_to_model_space=True, dependent_fogi_action='drop', include_spam=True, primitive_op_labels=None)
fogi_errorgen_component_labels(include_fogv=False, typ='normal')
fogi_errorgen_components_array(include_fogv=False, normalized_elem_gens=True)
set_fogi_errorgen_components_array(components, include_fogv=False, normalized_elem_gens=True, truncate=False)
fogi_errorgen_vector(normalized_elem_gens=False)

Constructs a vector from all the error generator coefficients involved in the FOGI analysis of this model.

Parameters
normalized_elem_gensbool, optional

Whether or not coefficients correspond to elementary error generators constructed from normalized Pauli matrices or not.

Returns

numpy.ndarray

fogi_contribution(op_label, error_type='H', intrinsic_or_relational='intrinsic', target='all', hessian_for_errorbars=None)

Computes a contribution to the FOGI error on a single gate.

This method is used when partitioning the (FOGI) error on a gate in various ways, based on the error type, whether the error is intrinsic or relational, and the upon the error support.

Parameters
op_labelLabel

The operation to compute a contribution for.

error_type{‘H’, ‘S’, ‘fogi_total_error’, ‘fogi_infidelity’}

The type of errors to include in the partition. ‘H’ means Hamiltonian and ‘S’ means Pauli stochastic. There are two options for including both H and S errors: ‘fogi_total_error’ adds the Hamiltonian errors linearly with the Pauli tochastic errors, similar to the diamond distance; ‘fogi_infidelity’ adds the Hamiltonian errors in quadrature to the linear sum of Pauli stochastic errors, similar to the entanglement or average gate infidelity.

intrinsic_or_relational{“intrinsic”, “relational”, “all”}

Restrict to intrinsic or relational errors (or not, using “all”).

targettuple or “all”

A tuple of state space (qubit) labels to restrict to, e.g., (‘Q0’,’Q1’). Note that including multiple labels selects only those quantities that target all the labels. The special “all” value includes quantities on all targets (no restriction).

hessian_for_errorbarsnumpy.ndarray, optional

If not None, a hessian matrix for this model (with shape (Np, Np) where Np == self.num_params, the number of model paramters) that is used to compute and return 1-sigma error bars.

Returns
valuefloat

The value of the requested contribution.

errorbarfloat

The 1-sigma error bar, returned only if hessian_for_errorbars is given.