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.

Functions

_default_param_bounds(num_params)

Construct an array to hold parameter bounds that starts with no bounds (all bounds +-inf)

_param_bounds_are_nontrivial(param_bounds)

Checks whether a parameter-bounds array holds any actual bounds, or if all are just +-inf

Attributes

MEMLIMIT_FOR_NONGAUGE_PARAMS

pygsti.models.model.MEMLIMIT_FOR_NONGAUGE_PARAMS
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_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.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_space (StateSpace) – The state space for this model.

  • basis (Basis) – The basis used for the state space by dense operator representations.

  • evotype (Evotype 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_rules (LayerRules) – 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.

  • simulator (ForwardSimulator or {"auto", "matrix", "map"}) – The forward simulator (or typ) that this model should use. “auto” tries to determine the best type automatically.

_pcheck = False
__setstate__(self, state_dict)
property sim(self)

Forward simulator for this model

property evotype(self)

Evolution type

Returns

str

property basis(self)

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

Returns

Basis

_set_state_space(self, lbls, basis='pp')

Sets labels for the components of the Hilbert space upon which the gates of this Model act.

Parameters
  • lbls (list or tuple or StateSpaceLabels object) – A list of state-space labels (can be strings or integers), e.g. [‘Q0’,’Q1’] or a StateSpaceLabels object.

  • basis (Basis or str) – A Basis object or a basis name (like “pp”), specifying the basis used to interpret the operators in this Model. If a Basis object, then its dimensions must match those of lbls.

Returns

None

property dim(self)

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(self)

The number of free parameters when vectorizing this model.

Returns

int – the number of model parameters.

abstract _iter_parameterized_objs(self)
_check_paramvec(self, debug=False)
_clean_paramvec(self)

Updates _paramvec corresponding to any “dirty” elements, which may have been modified without out knowing, leaving _paramvec out of sync with the element’s internal data. It may be necessary to resolve conflicts where multiple dirty elements want different values for a single parameter. This method is used as a safety net that tries to insure _paramvec & Model elements are consistent before their use.

_mark_for_rebuild(self, modified_obj=None)
_print_gpindices(self, max_depth=100)
print_parameters_by_op(self, max_depth=0)
collect_parameters(self, 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_collect (iterable) – 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_label (object, 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(self, 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_uncollect (int 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

_rebuild_paramvec(self)

Resizes self._paramvec and updates gpindices & parent members as needed, and will initialize new elements of _paramvec, but does NOT change existing elements of _paramvec (use _update_paramvec for this)

_init_virtual_obj(self, obj)

Initializes a “virtual object” - an object (e.g. LinearOperator) that could be a member of the Model but won’t be, as it’s just built for temporary use (e.g. the parallel action of several “base” gates). As such we need to fully initialize its parent and gpindices members so it knows it belongs to this Model BUT it’s not allowed to add any new parameters (they’d just be temporary). It’s also assumed that virtual objects don’t need to be to/from-vectored as there are already enough real (non-virtual) gates/spamvecs/etc. to accomplish this.

_obj_refcount(self, obj)

Number of references to obj contained within this Model

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.

The inverse of to_vector.

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

property param_interposer(self)
_model_paramvec_to_ops_paramvec(self, v)
_ops_paramvec_to_model_paramvec(self, w)
_ops_paramlbls_to_model_paramlbls(self, w)
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

split_circuit(self, 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
  • circuit (Circuit) – A circuit, possibly beginning with a state preparation label and ending with a povm label.

  • erroron (tuple 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_prep (bool, 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_povm (bool, 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(self, 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

circuit (Circuit) – Circuit to act on.

Returns

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

property _primitive_prep_label_dict(self)
property _primitive_povm_labels_dict(self)
property _primitive_op_labels_dict(self)
property _primitive_instrument_labels_dict(self)
property primitive_prep_labels(self)
property primitive_povm_labels(self)
property primitive_op_labels(self)
property primitive_instrument_labels(self)
_is_primitive_prep_layer_lbl(self, lbl)

Whether lbl is a valid state prep label (returns boolean)

Parameters

lbl (Label) – The label to test.

Returns

bool

_is_primitive_povm_layer_lbl(self, lbl)

Whether lbl is a valid POVM label (returns boolean)

Parameters

lbl (Label) – The label to test.

Returns

bool

_is_primitive_op_layer_lbl(self, lbl)

Whether lbl is a valid operation label (returns boolean)

Parameters

lbl (Label) – The label to test.

Returns

bool

_is_primitive_instrument_layer_lbl(self, lbl)

Whether lbl is a valid instrument label (returns boolean)

Parameters

lbl (Label) – The label to test.

Returns

bool

_has_instruments(self)

Useful for short-circuiting circuit expansion

_default_primitive_prep_layer_lbl(self)

Gets the default state prep label.

This is often used when a circuit is specified without a preparation layer. Returns None if there is no default and one must be specified.

Returns

Label or None

_default_primitive_povm_layer_lbl(self, sslbls)

Gets the default POVM label.

This is often used when a circuit is specified without an ending POVM layer. Returns None if there is no default and one must be specified.

Parameters

sslbls (tuple or None) – The state space labels being measured, and for which a default POVM is desired.

Returns

Label or None

_has_primitive_preps(self)

Whether this model contains any state preparations.

Returns

bool

_has_primitive_povms(self)

Whether this model contains any POVMs (measurements).

Returns

bool

abstract _effect_labels_for_povm(self, povm_lbl)

Gets the effect labels corresponding to the possible outcomes of POVM label povm_lbl.

Parameters

povm_lbl (Label) – POVM label.

Returns

list – A list of strings which label the POVM outcomes.

abstract _member_labels_for_instrument(self, inst_lbl)

Get the member labels corresponding to the possible outcomes of the instrument labeled by inst_lbl.

Parameters

inst_lbl (Label) – Instrument label.

Returns

list – A list of strings which label the instrument members.

circuit_layer_operator(self, layerlbl, typ='auto')

Construct or retrieve the operation associated with a circuit layer.

Parameters
  • layerlbl (Label) – 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_layer_operator(self, layerlbl, typ)
circuit_operator(self, circuit)

Construct or retrieve the operation associated with a circuit.

Parameters

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

Returns

LinearOperator

_reinit_opcaches(self)

Called when parameter vector structure changes and self._opcaches should be cleared & re-initialized

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.

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

  • 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.

abstract create_modelmember_graph(self)

Generate a ModelMemberGraph for the model.

Returns

ModelMemberGraph – A directed graph capturing dependencies among model members

print_modelmembers(self)

Print a summary of all the members within this model.

is_similar(self, 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 :method:`is_equivalent`) by calling modelA.from_vector(modelB.to_vector()).

Parameters
  • other_model (Model) – The model to compare against

  • rtol (float, 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(self, 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

  • rtol (float, 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

pygsti.models.model._default_param_bounds(num_params)

Construct an array to hold parameter bounds that starts with no bounds (all bounds +-inf)

pygsti.models.model._param_bounds_are_nontrivial(param_bounds)

Checks whether a parameter-bounds array holds any actual bounds, or if all are just +-inf