pygsti.models

pyGSTi Models Python Package

Submodules

Package Contents

Classes

CloudNoiseModel

A n-qudit model using a low-weight and geometrically local error model with a common "global idle" operation.

ExplicitOpModel

Encapsulates a set of gate, state preparation, and POVM effect operations.

ImplicitOpModel

A model that stores the building blocks for layer operations and build circuit-layer operations on-demand.

LocalNoiseModel

A n-qudit implicit model that allows for only local noise.

Model

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

OplessModel

A model that does not have independent component operations.

SuccessFailModel

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

Instrument

A generalized quantum instrument.

Functions

create_spam_vector(vec_expr, state_space, basis)

Build a rho or E vector from an expression.

create_identity_vec(basis)

Build a the identity vector for a given space and basis.

create_operation(op_expr, state_space[, basis, ...])

Build an operation object from an expression.

create_explicit_model_from_expressions(state_space, ...)

Build a new ExplicitOpModel given lists of labels and expressions.

create_explicit_alias_model(mdl_primitives, alias_dict)

Creates a model by applying aliases to an existing model.

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

create_crosstalk_free_model(processor_spec[, ...])

Create a n-qudit "crosstalk-free" model.

create_cloud_crosstalk_model(processor_spec[, ...])

Create a n-qudit "cloud-crosstalk" model.

create_cloud_crosstalk_model_from_hops_and_weights(...)

Create a "cloud crosstalk" model based on maximum error weights and hops along the processor's qudit graph.

create_qutrit_model(error_scale[, x_angle, y_angle, ...])

Constructs a standard qutrit Model.

Attributes

sqrt2

id2x2

sigmax

sigmay

sigmaz

class pygsti.models.CloudNoiseModel(processor_spec, gatedict, prep_layers=None, povm_layers=None, build_cloudnoise_fn=None, build_cloudkey_fn=None, simulator='map', evotype='default', errcomp_type='gates', implicit_idle_mode='none', verbosity=0)

Bases: pygsti.models.implicitmodel.ImplicitOpModel

A n-qudit model using a low-weight and geometrically local error model with a common “global idle” operation.

Parameters

processor_specProcessorSpec

The processor specification to create a model for. This object specifies the gate names and unitaries for the processor, and their availability on the processor.

gatedictdict

A dictionary (an OrderedDict if you care about insertion order) that associates with string-type gate names (e.g. “Gx”) LinearOperator, numpy.ndarray, or OpFactory objects. When the objects may act on fewer than the total number of qudits (determined by their dimension/shape) then they are repeatedly embedded into operation on the entire state space as specified by their availability within processor_spec. These operations represent the ideal target operations, and thus, any LinearOperator or OpFactory objects must be static, i.e., have zero parameters.

prep_layers, povm_layersNone or operator or dict or list, optional

The SPAM operations as n-qudit layer operations. If None, then no preps (or POVMs) are created. If a dict, then the keys are labels and the values are layer operators. If a list, then the elements are layer operators and the labels will be assigned as “rhoX” and “MX” where X is an integer starting at 0. If a single layer operation is given, then this is used as the sole prep or POVM and is assigned the label “rho0” or “Mdefault” respectively.

build_cloudnoise_fnfunction, optional

A function which takes a single Label as an argument and returns the cloud-noise operation for that primitive layer operation. Note that if errcomp_type=”gates” the returned operator should be a superoperator whereas if errcomp_type=”errorgens” then the returned operator should be an error generator (not yet exponentiated).

build_cloudkey_fnfunction, optional

An function which takes a single Label as an argument and returns a “cloud key” for that primitive layer. The “cloud” is the set of qudits that the error (the operator returned from build_cloudnoise_fn) touches – and the “key” returned from this function is meant to identify that cloud. This is used to keep track of which primitive layer-labels correspond to the same cloud - e.g. the cloud-key for (“Gx”,2) and (“Gy”,2) might be the same and could be processed together when selecing sequences that amplify the parameters in the cloud-noise operations for these two labels. The return value should be something hashable with the property that two noise which act on the same qudits should have the same cloud key.

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

The circuit simulator used to compute any requested probabilities, e.g. from probs() or bulk_probs(). The default value of “auto” automatically selects the simulation type, and is usually what you want. Other special allowed values are:

  • “matrix” : op_matrix-op_matrix products are computed and cached to get composite gates which can then quickly simulate a circuit for any preparation and outcome. High memory demand; best for a small number of (1 or 2) qubits.

  • “map” : op_matrix-state_vector products are repeatedly computed to simulate circuits. Slower for a small number of qubits, but faster and more memory efficient for higher numbers of qubits (3+).

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.

errcomp_type{“gates”,”errorgens”}

How errors are composed when creating layer operations in the created model. “gates” means that the errors on multiple gates in a single layer are composed as separate and subsequent processes. Specifically, the layer operation has the form Composed(target,idleErr,cloudErr) where target is a composition of all the ideal gate operations in the layer, idleErr is idle error (.operation_blks[‘layers’][‘globalIdle’]), and cloudErr is the composition (ordered as layer-label) of cloud- noise contributions, i.e. a map that acts as the product of exponentiated error-generator matrices. “errorgens” means that layer operations have the form Composed(target, error) where target is as above and error results from composing the idle and cloud-noise error generators, i.e. a map that acts as the exponentiated sum of error generators (ordering is irrelevant in this case).

implicit_idle_mode{‘none’, ‘add_global’, ‘pad_1Q’, ‘only_global’}

The way idle operations are added implicitly within the created model. “none” doesn’t add any “extra” idle operations when there is a layer that contains some gates but not gates on all the qubits. “add_global” adds the global idle operation, i.e., the operation for a global idle layer (zero gates - a completely empty layer), to every layer that is simulated, using the global idle as a background idle that always occurs regardless of the operation. “pad_1Q” applies the 1-qubit idle gate (if one exists) to all idling qubits within a circuit layer. “only_global” uses a global idle operation, if one exists, to simulate the completely empty layer but nothing else, i.e., this idle operation is not added to other layers as in “add_global”.

verbosityint, optional

An integer >= 0 dictating how must output to send to stdout.

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

property clouds

Returns the set of cloud-sets used when creating sequences which amplify the parameters of this model.

Returns

dict

create_processor_spec()
errorgen_coefficients(normalized_elem_gens=True)

TODO: docstring - returns a nested dict containing all the error generator coefficients for all the operations in this model.

class pygsti.models.ExplicitOpModel(state_space, basis='pp', default_gate_type='full', default_prep_type='auto', default_povm_type='auto', default_instrument_type='auto', prep_prefix='rho', effect_prefix='E', gate_prefix='G', povm_prefix='M', instrument_prefix='I', simulator='auto', evotype='default')

Bases: pygsti.models.model.OpModel

Encapsulates a set of gate, state preparation, and POVM effect operations.

An ExplictOpModel stores a set of labeled LinearOperator objects and provides dictionary-like access to their matrices. State preparation and POVM effect operations are represented as column vectors.

Parameters

state_spaceStateSpace

The state space for this model.

basis{“pp”,”gm”,”qt”,”std”,”sv”} or Basis, optional

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

default_param{“full”, “TP”, “CPTP”, etc.}, optional

Specifies the default gate and SPAM vector parameterization type. Can be any value allowed by set_all_parameterizations(), which also gives a description of each parameterization type.

prep_prefix: string, optional

Key prefixe for state preparations, allowing the model to determing what type of object a key corresponds to.

effect_prefixstring, optional

Key prefix for POVM effects, allowing the model to determing what type of object a key corresponds to.

gate_prefixstring, optional

Key prefix for gates, allowing the model to determing what type of object a key corresponds to.

povm_prefixstring, optional

Key prefix for POVMs, allowing the model to determing what type of object a key corresponds to.

instrument_prefixstring, optional

Key prefix for instruments, allowing the model to determing what type of object a key corresponds to.

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

The circuit simulator used to compute any requested probabilities, e.g. from probs() or bulk_probs(). The default value of “auto” automatically selects the simulation type, and is usually what you want. Other special allowed values are:

  • “matrix” : op_matrix-op_matrix products are computed and cached to get composite gates which can then quickly simulate a circuit for any preparation and outcome. High memory demand; best for a small number of (1 or 2) qubits.

  • “map” : op_matrix-state_vector products are repeatedly computed to simulate circuits. Slower for a small number of qubits, but faster and more memory efficient for higher numbers of qubits (3+).

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.

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

property default_gauge_group

Gets the default gauge group for performing gauge transformations on this Model.

Returns

GaugeGroup

property prep

The unique state preparation in this model, if one exists.

If not, a ValueError is raised.

Returns

State

property effects

The effect vectors from the unique POVM in this model, if one exists.

If not, a ValueError is raised.

Returns

list of POVMEffects

property num_elements

Return the number of total operation matrix and spam vector elements in this model.

This is in general different from the number of parameters in the model, which are the number of free variables used to generate all of the matrix and vector elements.

Returns
int

the number of model elements.

property num_nongauge_params

Return the number of non-gauge parameters in this model.

Returns
int

the number of non-gauge model parameters.

property num_gauge_params

Return the number of gauge parameters in this model.

Returns
int

the number of gauge model parameters.

convert_members_inplace(to_type, categories_to_convert='all', labels_to_convert='all', ideal_model=None, flatten_structure=False, set_default_gauge_group=False, cptp_truncation_tol=1e-06)

TODO: docstring – like set_all_parameterizations but doesn’t set default gauge group by default

set_default_gauge_group_for_member_type(member_type)

TODO: docstring

set_all_parameterizations(gate_type, prep_type='auto', povm_type='auto', instrument_type='auto', ideal_model=None, cptp_truncation_tol=1e-06)

Convert all gates, states, and POVMs to a specific parameterization type.

Parameters
parameterization_typestring

The gate, state, and POVM parameterization type. Allowed values are (where ‘*’ means “ terms” and “ clifford terms” evolution-type suffixes are allowed):

  • “full” : each gate / state / POVM effect element is an independent parameter

  • “TP” : Trace-Preserving gates and state preps

  • “static” : no parameters

  • “static unitary” : no parameters; convert superops to unitaries

  • “clifford” : no parameters; convert unitaries to Clifford symplecitics.

  • “GLND*” : General unconstrained Lindbladian

  • “CPTP*” : Completely-Positive-Trace-Preserving

  • “H+S+A*” : Hamiltoian, Pauli-Stochastic, and Affine errors

  • “H+S*” : Hamiltonian and Pauli-Stochastic errors

  • “S+A*” : Pauli-Stochastic and Affine errors

  • “S*” : Pauli-Stochastic errors

  • “H+D+A*” : Hamiltoian, Depolarization, and Affine errors

  • “H+D*” : Hamiltonian and Depolarization errors

  • “D+A*” : Depolarization and Affine errors

  • “D*” : Depolarization errors

  • Any of the above with “S” replaced with “s” or “D” replaced with “d”. This removes the CPTP constraint on the gates and SPAM operations (and as such is seldom used).

ideal_modelModel, optional

This may specify an ideal model of unitary gates and pure state vectors to be used as the ideal operation of each gate/SPAM operation, which is particularly useful as target for CPTP-based conversions.

cptp_truncation_tolfloat, optional (default 1e-6)

Tolerance used for conversion to CPTP parameterizations. When converting to CPTP models negative eigenvalues of the choi matrix representation of a superoperator are truncated, which can result in a change in the PTM for that operator. This tolerance indicates the maximum amount of truncation induced deviation from the original operations (measured by frobenius distance) we’re willing to accept without marking the conversion as failed.

Returns

None

deriv_wrt_params()

The element-wise derivative of all this models’ operations.

Constructs a matrix whose columns are the vectorized derivatives of all the model’s raw matrix and vector elements (placed in a vector) with respect to each single model parameter.

Thus, each column has length equal to the number of elements in the model, and there are num_params() columns. In the case of a “fully parameterized model” (i.e. all operation matrices and SPAM vectors are fully parameterized) then the resulting matrix will be the (square) identity matrix.

Returns
numpy array

2D array of derivatives.

compute_nongauge_and_gauge_spaces(item_weights=None, non_gauge_mix_mx=None)

TODO: docstring

compute_nongauge_projector(item_weights=None, non_gauge_mix_mx=None)

Construct a projector onto the non-gauge parameter space.

Useful for isolating the gauge degrees of freedom from the non-gauge degrees of freedom.

Parameters
item_weightsdict, optional

Dictionary of weighting factors for individual gates and spam operators. Keys can be gate, state preparation, POVM effect, spam labels, or the special strings “gates” or “spam” whic represent the entire set of gate or SPAM operators, respectively. Values are floating point numbers. These weights define the metric used to compute the non-gauge space, orthogonal the gauge space, that is projected onto.

non_gauge_mix_mxnumpy array, optional

An array of shape (n_non_gauge_params,n_gauge_params) specifying how to mix the non-gauge degrees of freedom into the gauge degrees of freedom that are projected out by the returned object. This argument essentially sets the off-diagonal block of the metric used for orthogonality in the “gauge + non-gauge” space. It is for advanced usage and typically left as None (the default).

Returns
numpy array

The projection operator as a N x N matrix, where N is the number of parameters (obtained via num_params()). This projector acts on parameter-space, and has rank equal to the number of non-gauge degrees of freedom.

transform_inplace(s)

Gauge transform this model.

Update each of the operation matrices G in this model with inv(s) * G * s, each rhoVec with inv(s) * rhoVec, and each EVec with EVec * s

Parameters
sGaugeGroupElement

A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.

Returns

None

frobeniusdist(other_model, transform_mx=None, item_weights=None, normalize=True)

Compute the weighted frobenius norm of the difference between this model and other_model.

Differences in each corresponding gate matrix and spam vector element are squared, weighted (using item_weights as applicable), then summed. The value returned is the square root of this sum, or the square root of this sum divided by the number of summands if normalize == True.

Parameters
other_modelModel

the other model to difference against.

transform_mxnumpy array, optional

if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

item_weightsdict, optional

Dictionary of weighting factors for individual gates and spam operators. Weights are applied multiplicatively to the squared differences, i.e., (before the final square root is taken). Keys can be gate, state preparation, POVM effect, or spam labels, as well as the two special labels “gates” and “spam” which apply to all of the gate or SPAM elements, respectively (but are overridden by specific element values). Values are floating point numbers. By default, all weights are 1.0.

normalizebool, optional

if True (the default), the sum of weighted squared-differences is divided by the weighted number of differences before the final square root is taken. If False, the division is not performed.

Returns

float

residuals(other_model, transform_mx=None, item_weights=None)

Compute the weighted residuals between two models.

Residuals are the differences in corresponding operation matrix and spam vector elements.

Parameters
other_modelModel

the other model to difference against.

transform_mxnumpy array, optional

if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

item_weightsdict, optional

Dictionary of weighting factors for individual gates and spam operators. Weights applied such that they act multiplicatively on the squared differences, so that the residuals themselves are scaled by the square roots of these weights. Keys can be gate, state preparation, POVM effect, or spam labels, as well as the two special labels “gates” and “spam” which apply to all of the gate or SPAM elements, respectively (but are overridden by specific element values). Values are floating point numbers. By default, all weights are 1.0.

Returns
residualsnumpy.ndarray

A 1D array of residuals (differences w.r.t. other)

nSummandsint

The (weighted) number of elements accounted for by the residuals.

jtracedist(other_model, transform_mx=None, include_spam=True)

Compute the Jamiolkowski trace distance between this model and other_model.

This is defined as the maximum of the trace distances between each corresponding gate, including spam gates.

Parameters
other_modelModel

the other model to difference against.

transform_mxnumpy array, optional

if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

include_spambool, optional

Whether to add to the max-trace-distance the frobenius distances between corresponding SPAM operations.

Returns

float

diamonddist(other_model, transform_mx=None, include_spam=True)

Compute the diamond-norm distance between this model and other_model.

This is defined as the maximum of the diamond-norm distances between each corresponding gate, including spam gates.

Parameters
other_modelModel

the other model to difference against.

transform_mxnumpy array, optional

if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

include_spambool, optional

Whether to add to the max-diamond-distance the frobenius distances between corresponding SPAM operations.

Returns

float

strdiff(other_model, metric='frobenius')

Return a string describing the distances between this model and other_model.

The returned string displays differences between each corresponding gate, state prep, and POVM effect.

Parameters
other_modelModel

the other model to difference against.

metric{‘frobenius’, ‘infidelity’, ‘diamond’}

Which distance metric to use.

Returns

str

all_objects()

Iterate over all of the (label, operator object) entities in this model.

This iterator runs over all state preparations, POVMS, operations, and instruments.

depolarize(op_noise=None, spam_noise=None, max_op_noise=None, max_spam_noise=None, seed=None)

Apply depolarization uniformly or randomly to this model’s gate and/or SPAM elements.

The result is returned without modifying the original (this) model. You must specify either op_noise or max_op_noise (for the amount of gate depolarization), and either spam_noise or max_spam_noise (for spam depolarization).

Parameters
op_noisefloat, optional
apply depolarizing noise of strength 1-op_noise to all gates in

the model. (Multiplies each assumed-Pauli-basis operation matrix by the diagonal matrix with (1.0-op_noise) along all the diagonal elements except the first (the identity).

spam_noisefloat, optional

apply depolarizing noise of strength 1-spam_noise to all SPAM opeations (state and POVM effects) in the model. (Multiplies the non-identity part of each assumed-Pauli-basis state preparation vector and measurement vector by (1.0-spam_noise)).

max_op_noisefloat, optional

specified instead of op_noise; apply a random depolarization with maximum strength 1-max_op_noise to each gate in the model.

max_spam_noisefloat, optional

specified instead of spam_noise; apply a random depolarization with maximum strength 1-max_spam_noise to each state preparation and POVM in the model.

seedint, optional

if not None, seed numpy’s random number generator with this value before generating random depolarizations.

Returns
Model

the depolarized Model

rotate(rotate=None, max_rotate=None, seed=None)

Apply a rotation uniformly or randomly to this model.

Uniformly means the same rotation applied to each gate and randomly means different random rotations are applied to each gate of this model. The result is returned without modifying the original (this) model.

You must specify either rotate or max_rotate. This method currently only works on n-qubit models.

Parameters
rotatetuple of floats, optional

If you specify the rotate argument, then the same rotation operation is applied to each gate. That is, each gate’s matrix G is composed with a rotation operation R (so G -> dot(R, G) ) where R is the unitary superoperator corresponding to the unitary operator U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) ). Here Pauli_k ranges over all of the non-identity un-normalized Pauli operators (e.g. {X,Y,Z} for 1 qubit, {IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, ZZ} for 2 qubits).

max_rotatefloat, optional

If max_rotate is specified (instead of rotate), then pyGSTi randomly generates a different rotate tuple, and applies the corresponding rotation, to each gate in this Model. Each component of each tuple is drawn uniformly from [0, max_rotate).

seedint, optional

if not None, seed numpy’s random number generator with this value before generating random depolarizations.

Returns
Model

the rotated Model

randomize_with_unitary(scale, seed=None, rand_state=None)

Create a new model with random unitary perturbations.

Apply a random unitary to each element of a model, and return the result, without modifying the original (this) model. This method works on Model as long as the dimension is a perfect square.

Parameters
scalefloat

maximum element magnitude in the generator of each random unitary transform.

seedint, optional

if not None, seed numpy’s random number generator with this value before generating random depolarizations.

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

Returns
Model

the randomized Model

increase_dimension(new_dimension)

Enlarge the dimension of this model.

Enlarge the spam vectors and operation matrices of model to a specified dimension, and return the resulting inflated model. Spam vectors are zero-padded and operation matrices are padded with 1’s on the diagonal and zeros on the off-diagonal (effectively padded by identity operation).

Parameters
new_dimensionint

the dimension of the returned model. That is, the returned model will have rho and E vectors that have shape (new_dimension,1) and operation matrices with shape (new_dimension,new_dimension)

Returns
Model

the increased-dimension Model

kick(absmag=1.0, bias=0, seed=None)

“Kick” this model by adding to each gate a random matrix.

The random matrices have values uniformly distributed in the interval [bias-absmag,bias+absmag].

Parameters
absmagfloat, optional

The maximum magnitude of the entries in the “kick” matrix relative to bias.

biasfloat, optional

The bias of the entries in the “kick” matrix.

seedint, optional

if not None, seed numpy’s random number generator with this value before generating random depolarizations.

Returns
Model

the kicked model.

compute_clifford_symplectic_reps(oplabel_filter=None)

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

Non-StaticCliffordOp gates will be ignored and their entries omitted from the returned dictionary.

Parameters
oplabel_filteriterable, optional

A list, tuple, or set of operation labels whose symplectic representations should be returned (if they exist).

Returns
dict

keys are operation labels and/or just the root names of gates (without any state space indices/labels). Values are (symplectic_matrix, phase_vector) tuples.

print_info()

Print to stdout relevant information about this model.

This information includes the Choi matrices and their eigenvalues.

Returns

None

create_processor_spec(qudit_labels='auto')

Create a processor specification from this model with the given qudit labels.

Currently this only works for models on qudits.

Parameters
qudit_labelstuple or “auto”, optional

A tuple of qudit labels, e.g. (‘Q0’, ‘Q1’) or (0, 1). “auto” uses the labels in this model’s state space labels.

Returns

QuditProcessorSpec or QubitProcessorSpec

create_modelmember_graph()

Generate a ModelMemberGraph for the model.

Returns
ModelMemberGraph

A directed graph capturing dependencies among model members

errorgen_coefficients(normalized_elem_gens=True)

TODO: docstring - returns a nested dict containing all the error generator coefficients for all the operations in this model.

class pygsti.models.ImplicitOpModel(state_space, layer_rules, basis='pp', simulator='auto', evotype='densitymx')

Bases: pygsti.models.model.OpModel

A model that stores the building blocks for layer operations and build circuit-layer operations on-demand.

An ImplicitOpModel represents a flexible QIP model whereby only the building blocks for layer operations are stored, and custom layer-lizard logic is used to construct layer operations from these blocks on an on-demand basis.

Parameters

state_spaceStateSpace

The state space for this model.

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.

basisBasis

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

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

The circuit simulator used to compute any requested probabilities, e.g. from probs() or

evotype{“densitymx”, “statevec”, “stabilizer”, “svterm”, “cterm”}

The evolution type of this model, describing how states are represented, allowing compatibility checks with (super)operator objects.

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

compute_clifford_symplectic_reps(oplabel_filter=None)

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

Non-StaticCliffordOp gates will be ignored and their entries omitted from the returned dictionary.

Parameters
oplabel_filteriterable, optional

A list, tuple, or set of operation labels whose symplectic representations should be returned (if they exist).

Returns
dict

keys are operation labels and/or just the root names of gates (without any state space indices/labels). Values are (symplectic_matrix, phase_vector) tuples.

create_modelmember_graph()

Generate a ModelMemberGraph for the model.

Returns
ModelMemberGraph

A directed graph capturing dependencies among model members

class pygsti.models.LocalNoiseModel(processor_spec, gatedict, prep_layers=None, povm_layers=None, evotype='default', simulator='auto', on_construction_error='raise', independent_gates=False, ensure_composed_gates=False, implicit_idle_mode='none')

Bases: pygsti.models.implicitmodel.ImplicitOpModel

A n-qudit implicit model that allows for only local noise.

This model holds as building blocks individual noisy gates which are trivially embedded into circuit layers as requested.

Parameters

processor_specProcessorSpec

The processor specification to create a model for. This object specifies the gate names and unitaries for the processor, and their availability on the processor.

gatedictdict

A dictionary (an OrderedDict if you care about insertion order) that associates with gate names (e.g. “Gx”) LinearOperator, numpy.ndarray objects. When the objects may act on fewer than the total number of qudits (determined by their dimension/shape) then they are repeatedly embedded into operation on the entire state space as specified by their availability within processor_spec. While the keys of this dictionary are usually string-type gate names, labels that include target qudits, e.g. (“Gx”,0), may be used to override the default behavior of embedding a reference or a copy of the gate associated with the same label minus the target qudits (e.g. “Gx”). Furthermore, OpFactory objects may be used in place of LinearOperator objects to allow the evaluation of labels with arguments.

prep_layersNone or operator or dict or list

The state preparateion operations as n-qudit layer operations. If None, then no state preparations will be present in the created model. If a dict, then the keys are labels and the values are layer operators. If a list, then the elements are layer operators and the labels will be assigned as “rhoX” where X is an integer starting at 0. If a single layer operation of type State is given, then this is used as the sole prep and is assigned the label “rho0”.

povm_layersNone or operator or dict or list

The state preparateion operations as n-qudit layer operations. If None, then no POVMS will be present in the created model. If a dict, then the keys are labels and the values are layer operators. If a list, then the elements are layer operators and the labels will be assigned as “MX” where X is an integer starting at 0. If a single layer operation of type POVM is given, then this is used as the sole POVM and is assigned the label “Mdefault”.

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.

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

The circuit simulator used to compute any requested probabilities, e.g. from probs() or bulk_probs(). The default value of “auto” automatically selects the simulation type, and is usually what you want. Other special allowed values are:

  • “matrix” : op_matrix-op_matrix products are computed and cached to get composite gates which can then quickly simulate a circuit for any preparation and outcome. High memory demand; best for a small number of (1 or 2) qubits.

  • “map” : op_matrix-state_vector products are repeatedly computed to simulate circuits. Slower for a small number of qubits, but faster and more memory efficient for higher numbers of qubits (3+).

on_construction_error{‘raise’,’warn’,ignore’}

What to do when the conversion from a value in gatedict to a LinearOperator of the type given by parameterization fails. Usually you’ll want to “raise” the error. In some cases, for example when converting as many gates as you can into parameterization=”clifford” gates, “warn” or even “ignore” may be useful.

independent_gatesbool, optional

Whether gates are allowed independent local noise or not. If False, then all gates with the same name (e.g. “Gx”) will have the same (local) noise (e.g. an overrotation by 1 degree), and the operation_bks[‘gates’] dictionary contains a single key per gate name. If True, then gates with the same name acting on different qudits may have different local noise, and so the operation_bks[‘gates’] dictionary contains a key for each gate available gate placement.

ensure_composed_gatesbool, optional

If True then the elements of the operation_bks[‘gates’] will always be ComposedOp objects. The purpose of this is to facilitate modifying the gate operations after the model is created. If False, then the appropriately parameterized gate objects (often dense gates) are used directly.

implicit_idle_mode{‘none’, ‘add_global’, ‘pad_1Q’, ‘only_global’}

The way idle operations are added implicitly within the created model. “none” doesn’t add any “extra” idle operations when there is a layer that contains some gates but not gates on all the qubits. “add_global” adds the global idle operation, i.e., the operation for a global idle layer (zero gates - a completely empty layer), to every layer that is simulated, using the global idle as a background idle that always occurs regardless of the operation. “pad_1Q” applies the 1-qubit idle gate (if one exists) to all idling qubits within a circuit layer. “only_global” uses a global idle operation, if one exists, to simulate the completely empty layer but nothing else, i.e., this idle operation is not added to other layers as in “add_global”.

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

create_processor_spec()
errorgen_coefficients(normalized_elem_gens=True)

TODO: docstring - returns a nested dict containing all the error generator coefficients for all the operations in this model.

class pygsti.models.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.OplessModel(state_space)

Bases: pygsti.models.model.Model

A model that does not have independent component operations.

OplessModel-derived classes often implement coarser models that predict the success or outcome probability of a circuit based on simple properties of the circuit and not detailed gate-level modeling.

Parameters

state_spaceStateSpace

The state space of this model.

property dim
property parameter_bounds

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

abstract circuit_outcomes(circuit)

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

Parameters
circuitCircuit

Circuit to get outcomes of.

Returns

tuple

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

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.

class pygsti.models.SuccessFailModel(state_space, use_cache=False)

Bases: OplessModel

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

Parameters

state_spaceStateSpace

The state space of this model.

use_cachebool, optional

Whether a cache should be used to increase performance.

property sim

Forward simulator for 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

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.

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.

class pygsti.models.Instrument(member_ops, evotype=None, state_space=None, called_from_reduce=False, items=None)

Bases: pygsti.modelmembers.modelmember.ModelMember, collections.OrderedDict

A generalized quantum instrument.

Meant to correspond to a quantum instrument in theory, this class generalizes that notion slightly to include a collection of gates that may or may not have all of the properties associated by a mathematical quantum instrument.

Parameters

member_opsdict of LinearOperator objects

A dict (or list of key,value pairs) of the gates.

evotypeEvotype or str, optional

The evolution type. If None, the evotype is inferred from the first instrument member. If len(member_ops) == 0 in this case, an error is raised.

state_spaceStateSpace, optional

The state space for this POVM. If None, the space is inferred from the first instrument member. If len(member_ops) == 0 in this case, an error is raised.

itemslist or dict, optional

Initial values. This should only be used internally in de-serialization.

Initialize a new ModelMember

property parameter_labels

An array of labels (usually strings) describing this model member’s parameters.

property num_elements

Return the number of total gate elements in this instrument.

This is in general different from the number of parameters, which are the number of free variables used to generate all of the matrix elements.

Returns

int

property num_params

Get the number of independent parameters which specify this Instrument.

Returns
int

the number of independent parameters.

submembers()

Get the ModelMember-derived objects contained in this one.

Returns

list

to_memoized_dict(mmg_memo)

Create a serializable dict with references to other objects in the memo.

Parameters
mmg_memo: dict

Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).

Returns
mm_dict: dict

A dict representation of this ModelMember ready for serialization This must have at least the following fields: module, class, submembers, params, state_space, evotype Additional fields may be added by derived classes.

simplify_operations(prefix='')

Creates a dictionary of simplified instrument operations.

Returns a dictionary of operations that belong to the Instrument’s parent Model - that is, whose gpindices are set to all or a subset of this instruments’s gpindices. These are used internally within computations involving the parent Model.

Parameters
prefixstr

A string, usually identitying this instrument, which may be used to prefix the simplified gate keys.

Returns

OrderedDict of Gates

to_vector()

Extract a vector of the underlying gate parameters from this Instrument.

Returns
numpy array

a 1D numpy array with length == num_params().

from_vector(v, close=False, dirty_value=True)

Initialize the Instrument using a vector of its parameters.

Parameters
vnumpy array

The 1D vector of gate parameters. Length must == num_params().

closebool, optional

Whether v is close to this Instrument’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

dirty_valuebool, optional

The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

transform_inplace(s)

Update each Instrument element matrix O with inv(s) * O * s.

Parameters
sGaugeGroupElement

A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.

Returns

None

depolarize(amount)

Depolarize this Instrument by the given amount.

Parameters
amountfloat or tuple

The amount to depolarize by. If a tuple, it must have length equal to one less than the dimension of the gate. All but the first element of each spam vector (often corresponding to the identity element) are multiplied by amount (if a float) or the corresponding amount[i] (if a tuple).

Returns

None

rotate(amount, mx_basis='gm')

Rotate this instrument by the given amount.

Parameters
amounttuple of floats, optional

Specifies the rotation “coefficients” along each of the non-identity Pauli-product axes. The gate’s matrix G is composed with a rotation operation R (so G -> dot(R, G) ) where R is the unitary superoperator corresponding to the unitary operator U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) ). Here Pauli_k ranges over all of the non-identity un-normalized Pauli operators.

mx_basis{‘std’, ‘gm’, ‘pp’, ‘qt’} or Basis object

The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

Returns

None

acton(state)

Act with this instrument upon state

Parameters
stateState

The state to act on

Returns
OrderedDict

A dictionary whose keys are the outcome labels (strings) and whose values are (prob, normalized_state) tuples giving the probability of seeing the given outcome and the resulting state that would be obtained if and when that outcome is observed.

pygsti.models.sqrt2
pygsti.models.id2x2
pygsti.models.sigmax
pygsti.models.sigmay
pygsti.models.sigmaz
pygsti.models.create_spam_vector(vec_expr, state_space, basis)

Build a rho or E vector from an expression.

Parameters

vec_exprstring

the expression which determines which vector to build. Currenlty, only integers are allowed, which specify a the vector for the pure state of that index. For example, “1” means return vectorize(|1><1|). The index labels the absolute index of the state within the entire state space, and is independent of the direct-sum decomposition of density matrix space.

state_spaceStateSpace

The state space that the created operation should act upon.

basisstr or Basis

The basis of the returned vector. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

Returns

numpy array

The vector specified by vec_expr in the desired basis.

pygsti.models.create_identity_vec(basis)

Build a the identity vector for a given space and basis.

Parameters

basisBasis object

The basis of the returned vector. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

Returns

numpy array

The identity vector in the desired basis.

pygsti.models.create_operation(op_expr, state_space, basis='pp', parameterization='full', evotype='default')

Build an operation object from an expression.

Parameters

op_exprstring

expression for the gate to build. String is first split into parts delimited by the colon (:) character, which are composed together to create the final gate. Each part takes on of the allowed forms:

  • I(ssl_0, …) = identity operation on one or more state space labels (ssl_i)

  • X(theta, ssl) = x-rotation by theta radians of qubit labeled by ssl

  • Y(theta, ssl) = y-rotation by theta radians of qubit labeled by ssl

  • Z(theta, ssl) = z-rotation by theta radians of qubit labeled by ssl

  • CX(theta, ssl0, ssl1) = controlled x-rotation by theta radians. Acts on qubit labeled by ssl1 with ssl0 being the control.

  • CY(theta, ssl0, ssl1) = controlled y-rotation by theta radians. Acts on qubit labeled by ssl1 with ssl0 being the control.

  • CZ(theta, ssl0, ssl1) = controlled z-rotation by theta radians. Acts on qubit labeled by ssl1 with ssl0 being the control.

  • CNOT(ssl0, ssl1) = standard controlled-not gate. Acts on qubit labeled by ssl1 with ssl0 being the control.

  • CPHASE(ssl0, ssl1) = standard controlled-phase gate. Acts on qubit labeled by ssl1 with ssl0 being the control.

  • LX(theta, i0, i1) = leakage between states i0 and i1. Implemented as an x-rotation between states with integer indices i0 and i1 followed by complete decoherence between the states.

state_spaceStateSpace

The state space that the created operation should act upon.

basisstr or Basis

The basis the returned operation should be represented in.

parameterization{“full”,”TP”,”static”}, optional

How to parameterize the resulting gate.

  • “full” = return a FullArbitraryOp.

  • “TP” = return a FullTPOp.

  • “static” = return a StaticArbitraryOp.

evotypeEvotype or str, optional

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

Returns

LinearOperator

A gate object representing the gate given by op_expr in the desired basis.

pygsti.models.create_explicit_model_from_expressions(state_space, op_labels, op_expressions, prep_labels=('rho0',), prep_expressions=('0',), effect_labels='standard', effect_expressions='standard', povm_labels='Mdefault', basis='auto', gate_type='full', prep_type='auto', povm_type='auto', instrument_type='auto', evotype='default')

Build a new ExplicitOpModel given lists of labels and expressions.

Parameters

state_spaceStateSpace

the state space for the model.

op_labelslist of strings
A list of labels for each created gate in the final model. To

conform with text file parsing conventions these names should begin with a capital G and can be followed by any number of lowercase characters, numbers, or the underscore character.

op_expressionslist of strings

A list of gate expressions, each corresponding to a operation label in op_labels, which determine what operation each gate performs (see documentation for create_operation()).

prep_labelslist of string

A list of labels for each created state preparation in the final model. To conform with conventions these labels should begin with “rho”.

prep_expressionslist of strings

A list of vector expressions for each state preparation vector (see documentation for _create_spam_vector()).

effect_labelslist, optional

If povm_labels is a string, then this is just a list of the effect (outcome) labels for the single POVM. If povm_labels is a tuple, then effect_labels must be a list of lists of effect labels, each list corresponding to a POVM. If set to the special string “standard” then the length-n binary strings are used when the state space consists of n qubits (e.g. “000”, “001”, … “111” for 3 qubits) and the labels “0”, “1”, … “<dim>” are used, where <dim> is the dimension of the state space, in all non-qubit cases.

effect_expressionslist, optional

A list or list-of-lists of (string) vector expressions for each POVM effect vector (see documentation for _create_spam_vector()). Expressions correspond to labels in effect_labels. If set to the special string “standard”, then the expressions “0”, “1”, … “<dim>” are used, where <dim> is the dimension of the state space.

povm_labelslist or string, optional

A list of POVM labels, or a single (string) label. In the latter case, only a single POVM is created and the format of effect_labels and effect_expressions is simplified (see above).

basis{‘gm’,’pp’,’std’,’qt’,’auto’}, optional

the basis of the matrices in the returned Model

  • “std” = operation matrix operates on density mx expressed as sum of matrix units

  • “gm” = operation matrix operates on dentity mx expressed as sum of normalized Gell-Mann matrices

  • “pp” = operation matrix operates on density mx expresses as sum of tensor-product of Pauli matrices

  • “qt” = operation matrix operates on density mx expressed as sum of Qutrit basis matrices

  • “auto” = “pp” if possible (integer num of qubits), “qt” if density matrix dim == 3, and “gm” otherwise.

parameterization{“full”,”TP”}, optional

How to parameterize the gates of the resulting Model (see documentation for create_operation()).

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.

Returns

ExplicitOpModel

The created model.

pygsti.models.create_explicit_alias_model(mdl_primitives, alias_dict)

Creates a model by applying aliases to an existing model.

The new model is created by composing the gates of an existing Model, mdl_primitives, according to a dictionary of Circuit`s, `alias_dict. The keys of alias_dict are the operation labels of the returned Model. state preparations and POVMs are unaltered, and simply copied from mdl_primitives.

Parameters

mdl_primitivesModel

A Model containing the “primitive” gates (those used to compose the gates of the returned model).

alias_dictdictionary

A dictionary whose keys are strings and values are Circuit objects specifying sequences of primitive gates. Each key,value pair specifies the composition rule for a creating a gate in the returned model.

Returns

Model

A model whose gates are compositions of primitive gates and whose spam operations are the same as those of mdl_primitives.

pygsti.models.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')
pygsti.models.create_crosstalk_free_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', on_construction_error='raise', independent_gates=False, independent_spam=True, ensure_composed_gates=False, ideal_gate_type='auto', ideal_spam_type='computational', implicit_idle_mode='none', basis='pp')

Create a n-qudit “crosstalk-free” model.

By virtue of being crosstalk-free, this model’s operations only act nontrivially on their target qudits. Gates consist of an ideal gate operation possibly followed by an error operation.

Errors can be specified using any combination of the 4 error rate/coeff arguments, but each gate name must be provided exclusively to one type of specification. Each specification results in a different type of operation, depending on the parameterization:

  • depolarization_strengths -> DepolarizeOp, StochasticNoiseOp, or exp(LindbladErrorgen)

  • stochastic_error_probs -> StochasticNoiseOp or exp(LindbladErrorgen)

  • lindblad_error_coeffs -> exp(LindbladErrorgen)

In addition to the gate names, the special values “prep” and “povm” may be used as keys to specify the error on the state preparation, measurement, respectively.

Parameters

processor_specProcessorSpec

The processor specification to create a model for. This object specifies the gate names and unitaries for the processor, and their availability on the processor.

custom_gatesdict, optional

A dictionary that associates with gate labels LinearOperator, OpFactory, or numpy.ndarray objects. These objects override any other behavior for constructing their designated operations. Keys of this dictionary may be string-type gate names or labels that include target qudits.

depolarization_strengthsdict, optional

A dictionary whose keys are gate names (e.g. “Gx”) and whose values are floats that specify the strength of uniform depolarization.

stochastic_error_probsdict, optional

A dictionary whose keys are gate names (e.g. “Gx”) and whose values are tuples that specify Pauli-stochastic rates for each of the non-trivial Paulis (so a 3-tuple would be expected for a 1Q gate and a 15-tuple for a 2Q gate).

lindblad_error_coeffsdict, optional

A dictionary whose keys are gate names (e.g. “Gx”) and whose values are dictionaries corresponding to the lindblad_term_dict kwarg taken by LindbladErrorgen. Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType can be “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples with 1 basis label indicate a diagonal term, and are the only types of terms allowed when nonham_mode != “all”. Otherwise, Stochastic term tuples can include 2 basis labels to specify “off-diagonal” non-Hamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients.

depolarization_parameterizationstr of {“depolarize”, “stochastic”, or “lindblad”}

Determines whether a DepolarizeOp, StochasticNoiseOp, or LindbladErrorgen is used to parameterize the depolarization noise, respectively. When “depolarize” (the default), a DepolarizeOp is created with the strength given in depolarization_strengths. When “stochastic”, the depolarization strength is split evenly among the stochastic channels of a StochasticOp. When “lindblad”, the depolarization strength is split evenly among the coefficients of the stochastic error generators (which are exponentiated to form a LindbladErrorgen with the “depol” parameterization).

stochastic_parameterizationstr of {“stochastic”, or “lindblad”}

Determines whether a StochasticNoiseOp or LindbladErrorgen is used to parameterize the stochastic noise, respectively. When “stochastic”, elements of stochastic_error_probs are used as coefficients in a linear combination of stochastic channels (the default). When “lindblad”, the elements of stochastic_error_probs are coefficients of stochastic error generators (which are exponentiated to form a LindbladErrorgen with the “cptp” parameterization).

lindblad_parameterization“auto” or a LindbladErrorgen paramtype

Determines the parameterization of the LindbladErrorgen. When “auto” (the default), the parameterization is inferred from the types of error generators specified in the lindblad_error_coeffs dictionaries. When not “auto”, the parameterization type is passed through to the LindbladErrorgen.

evotypeEvotype or str, optional

The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

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

The simulator used to compute predicted probabilities for the resulting Model. Using “auto” selects “matrix” when there are 2 qubits or less, and otherwise selects “map”.

on_construction_error{‘raise’,’warn’,ignore’}

What to do when the creation of a gate with the given parameterization fails. Usually you’ll want to “raise” the error. In some cases, for example when converting as many gates as you can into parameterization=”clifford” gates, “warn” or even “ignore” may be useful.

independent_gatesbool, optional

Whether gates are allowed independent local noise or not. If False, then all gates with the same name (e.g. “Gx”) will have the same (local) noise (e.g. an overrotation by 1 degree), and the operation_bks[‘gates’] dictionary contains a single key per gate name. If True, then gates with the same name acting on different qudits may have different local noise, and so the operation_bks[‘gates’] dictionary contains a key for each gate available gate placement.

ensure_composed_gatesbool, optional

If True then the elements of the operation_bks[‘gates’] will always be ComposedOp objects. The purpose of this is to facilitate modifying the gate operations after the model is created. If False, then the appropriately parameterized gate objects (often dense gates) are used directly.

ideal_gate_typestr or tuple, optional

A gate type or tuple of gate types (listed in order of priority) which is used to construct the ideal gates. A gate type usually specifies the Python class that will be created, which determines 1) the parameterization of the gate and 2) the class/category of the gate (e.g. a StaticClifford operation has no parameters and is a Clifford operation).

ideal_spam_typestr or tuple, optional

Similar to ideal_gate_type but for SPAM elements (state preparations and POVMs).

implicit_idle_mode{‘none’, ‘add_global’, ‘pad_1Q’}

The way idle operations are added implicitly within the created model. “none” doesn’t add any “extra” idle operations when there is a layer that contains some gates but not gates on all the qudits. “add_global” adds the global idle operation, i.e., the operation for a global idle layer (zero gates - a completely empty layer), to every layer that is simulated, using the global idle as a background idle that always occurs regardless of the operation. “pad_1Q” applies the 1-qubit idle gate (if one exists) to all idling qubits within a circuit layer.

basisBasis or str, optional

The basis to use when constructing operator representations for the elements of the created model.

Returns

LocalNoiseModel

A model with “rho0” prep, “Mdefault” POVM, and gates labeled by the gate names and qudit labels (as specified by processor_spec). For instance, the operation label for the “Gx” gate on the second qudit might be Label(“Gx”,1).

pygsti.models.create_cloud_crosstalk_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', independent_gates=False, independent_spam=True, errcomp_type='gates', implicit_idle_mode='none', basis='pp', verbosity=0)

Create a n-qudit “cloud-crosstalk” model.

In a cloud crosstalk model, gates consist of a (local) ideal gates followed by an error operation that can act nontrivially on any of the processor’s qudits (not just a gate’s target qudits). Typically a gate’s errors are specified relative to the gate’s target qudits, forming a “cloud” of errors around the target qudits using some notion of locality (that may not be spatial, e.g. local in frequency). Currently, the “ideal” portion of each gate can only be created as a static (parameterless) object – all gate parameters come from the error operation.

Errors can be specified using any combination of the 4 error rate/coeff arguments, but each gate name must be provided exclusively to one type of specification. Each specification results in a different type of operation, depending on the parameterization:

  • depolarization_strengths -> DepolarizeOp, StochasticNoiseOp, or exp(LindbladErrorgen)

  • stochastic_error_probs -> StochasticNoiseOp or exp(LindbladErrorgen)

  • lindblad_error_coeffs -> exp(LindbladErrorgen)

In addition to the gate names, the special values “prep” and “povm” may be used as keys to specify the error on the state preparation, measurement, respectively.

Parameters

processor_specProcessorSpec

The processor specification to create a model for. This object specifies the gate names and unitaries for the processor, and their availability on the processor.

custom_gatesdict, optional

A dictionary that associates with gate labels LinearOperator, OpFactory, or numpy.ndarray objects. These objects override any other behavior for constructing their designated operations. Keys of this dictionary may be string-type gate names or labels that include target qudits.

depolarization_strengthsdict, optional

A dictionary whose keys are gate names (e.g. “Gx”) and whose values are floats that specify the strength of uniform depolarization.

stochastic_error_probsdict, optional

A dictionary whose keys are gate names (e.g. “Gx”) and whose values are tuples that specify Pauli-stochastic rates for each of the non-trivial Paulis (so a 3-tuple would be expected for a 1Q gate and a 15-tuple for a 2Q gate).

lindblad_error_coeffsdict, optional

A dictionary whose keys are gate names (e.g. “Gx”) and whose values are dictionaries corresponding to the lindblad_term_dict kwarg taken by LindbladErrorgen. Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType can be “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples with 1 basis label indicate a diagonal term, and are the only types of terms allowed when nonham_mode != “all”. Otherwise, Stochastic term tuples can include 2 basis labels to specify “off-diagonal” non-Hamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients.

depolarization_parameterizationstr of {“depolarize”, “stochastic”, or “lindblad”}

Determines whether a DepolarizeOp, StochasticNoiseOp, or LindbladErrorgen is used to parameterize the depolarization noise, respectively. When “depolarize” (the default), a DepolarizeOp is created with the strength given in depolarization_strengths. When “stochastic”, the depolarization strength is split evenly among the stochastic channels of a StochasticOp. When “lindblad”, the depolarization strength is split evenly among the coefficients of the stochastic error generators (which are exponentiated to form a LindbladErrorgen with the “depol” parameterization).

stochastic_parameterizationstr of {“stochastic”, or “lindblad”}

Determines whether a StochasticNoiseOp or LindbladErrorgen is used to parameterize the stochastic noise, respectively. When “stochastic”, elements of stochastic_error_probs are used as coefficients in a linear combination of stochastic channels (the default). When “lindblad”, the elements of stochastic_error_probs are coefficients of stochastic error generators (which are exponentiated to form a LindbladErrorgen with the “cptp” parameterization).

lindblad_parameterization“auto” or a LindbladErrorgen paramtype

Determines the parameterization of the LindbladErrorgen. When “auto” (the default), the parameterization is inferred from the types of error generators specified in the lindblad_error_coeffs dictionaries. When not “auto”, the parameterization type is passed through to the LindbladErrorgen.

evotypeEvotype or str, optional

The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

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

The simulator used to compute predicted probabilities for the resulting Model. Using “auto” selects “matrix” when there are 2 qubits or less, and otherwise selects “map”.

independent_gatesbool, optional

Whether gates are allowed independent noise or not. If False, then all gates with the same name (e.g. “Gx”) will have the same noise (e.g. an overrotation by 1 degree), and the operation_bks[‘cloudnoise’] dictionary will contains a single key per gate name. If True, then gates with the same name acting on different qudits may have different local noise, and so the operation_bks[‘cloudnoise’] dictionary contains a key for each gate available gate placement.

independent_spambool, optional

Similar to indepenent_gates but for SPAM operations.

errcomp_type{‘gates’, ‘errorgens’}

Whether errors should be combined by composing error maps (gates) or by exponentiating the sum of error generators (composing the error generators, errorgens). The latter is only an option when the noise is given solely in terms of Lindblad error coefficients.

implicit_idle_mode{‘none’, ‘add_global’, ‘pad_1Q’}

The way idle operations are added implicitly within the created model. “none” doesn’t add any “extra” idle operations when there is a layer that contains some gates but not gates on all the qudits. “add_global” adds the global idle operation, i.e., the operation for a global idle layer (zero gates - a completely empty layer), to every layer that is simulated, using the global idle as a background idle that always occurs regardless of the operation. “pad_1Q” applies the 1-qubit idle gate (if one exists) to all idling qubits within a circuit layer.

basisBasis or str, optional

The basis to use when constructing operator representations for the elements of the created model.

verbosityint or VerbosityPrinter, optional

Amount of detail to print to stdout.

Returns

CloudNoiseModel

pygsti.models.create_cloud_crosstalk_model_from_hops_and_weights(processor_spec, custom_gates=None, max_idle_weight=1, max_spam_weight=1, maxhops=0, extra_weight_1_hops=0, extra_gate_weight=0, simulator='auto', evotype='default', gate_type='H+S', spam_type='H+S', implicit_idle_mode='none', errcomp_type='gates', independent_gates=True, independent_spam=True, connected_highweight_errors=True, basis='pp', verbosity=0)

Create a “cloud crosstalk” model based on maximum error weights and hops along the processor’s qudit graph.

This function provides a convenient way to construct cloud crosstalk models whose gate errors consist of Pauli elementary error generators (i.e. that correspond to Lindblad error coefficients) that are limited in weight (number of non-identity Paulis) and support (which qudits have non-trivial Paulis on them). Errors are taken to be approximately local, meaning they are concentrated near the target qudits of a gate, with the notion of locality taken from the processor specification’s qudit graph. The caller provides maximum-weight, maximum-hop (a “hop” is the movement along a single graph edge), and gate type arguments to specify the set of possible errors on a gate.

  • The global idle gate (corresponding to an empty circuit layer) has errors that are limited only by a maximum weight, max_idle_weight.

  • State preparation and POVM errors are constructed similarly, with a global-idle-like error following or preceding the preparation or measurement, respectively.

  • Gate errors are placed on all the qudits that can be reached with at most maxhops hops from (any of) the gate’s target qudits. Elementary error generators up to weight W, where W equals the number of target qudits (e.g., 2 for a CNOT gate) plus extra_gate_weight are allowed. Weight-1 terms are a special case, and the extra_weight_1_hops argument adds to the usual maxhops in this case to allow weight-1 errors on a possibly larger region of qudits around the target qudits.

Parameters

processor_specProcessorSpec

The processor specification to create a model for. This object specifies the gate names and unitaries for the processor, and their availability on the processor.

custom_gatesdict

A dictionary that associates with gate labels LinearOperator, OpFactory, or numpy.ndarray objects. These objects describe the full action of the gate or primitive-layer they’re labeled by (so if the model represents states by density matrices these objects are superoperators, not unitaries), and override any standard construction based on builtin gate names or nonstd_gate_unitaries. Keys of this dictionary must be string-type gate names – they cannot include state space labels – and they must be static (have zero parameters) because they represent only the ideal behavior of each gate – the cloudnoise operations represent the parameterized noise. To fine-tune how this noise is parameterized, call the CloudNoiseModel constructor directly.

max_idle_weightint, optional

The maximum-weight for errors on the global idle gate.

max_spam_weightint, optional

The maximum-weight for state preparation and measurement (SPAM) errors.

maxhopsint

The locality constraint: for a gate, errors (of weight up to the maximum weight for the gate) are allowed to occur on the gate’s target qudits and those reachable by hopping at most maxhops times from a target qudit along nearest-neighbor links (defined by the geometry).

extra_weight_1_hopsint, optional

Additional hops (adds to maxhops) for weight-1 errors. A value > 0 can be useful for allowing just weight-1 errors (of which there are relatively few) to be dispersed farther from a gate’s target qudits. For example, a crosstalk-detecting model might use this.

extra_gate_weightint, optional

Addtional weight, beyond the number of target qudits (taken as a “base weight” - i.e. weight 2 for a 2Q gate), allowed for gate errors. If this equals 1, for instance, then 1-qudit gates can have up to weight-2 errors and 2-qudit gates can have up to weight-3 errors.

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

The circuit simulator used to compute any requested probabilities, e.g. from probs() or bulk_probs(). Using “auto” selects “matrix” when there are 2 qudits or less, and otherwise selects “map”.

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.

gate_typestr, optional

The Lindblad-error parameterization type used for gate operations. This may be expanded in the future, but currently the gate errors must be of the Lindblad error-generator coefficients type, and this argument specifies what elementary error-generator coefficients are initially allowed (and linked to model parameters), before maximum-weight and locality constraints are imposed. In addition to the usual Lindblad error types, (e.g. “H”, “H+S”) the special values “none” is allowed to indicate that there should be no errors on the gates (useful if you only want errors on the SPAM, for instance).

spam_typestr, optional

Similar to gate_type but for SPAM elements (state preparations and POVMs). This specifies the Lindblad-error parameterization for the state prepearation and POVM.

implicit_idle_mode{‘none’, ‘add_global’, ‘pad_1Q’}

The way idle operations are added implicitly within the created model. “none” doesn’t add any “extra” idle operations when there is a layer that contains some gates but not gates on all the qudits. “add_global” adds the global idle operation, i.e., the operation for a global idle layer (zero gates - a completely empty layer), to every layer that is simulated, using the global idle as a background idle that always occurs regardless of the operation. “pad_1Q” applies the 1-qubit idle gate (if one exists) to all idling qubits within a circuit layer.

errcomp_type{“gates”,”errorgens”}

How errors are composed when creating layer operations in the created model. “gates” means that the errors on multiple gates in a single layer are composed as separate and subsequent processes. Specifically, the layer operation has the form Composed(target,idleErr,cloudErr) where target is a composition of all the ideal gate operations in the layer, idleErr is the global idle error if implicit_idle_mode == ‘add_global’, and cloudErr is the composition (ordered as layer-label) of cloud- noise contributions, i.e. a map that acts as the product of exponentiated error-generator matrices. “errorgens” means that layer operations have the form Composed(target, error) where target is as above and error results from composing (summing) the idle and cloud-noise error generators, i.e. a map that acts as the exponentiated sum of error generators (ordering is irrelevant in this case).

independent_gatesbool, optional

Whether the noise added to a gate when it acts on one set of target qudits is independent of its noise on a different set of target qudits. If False, then all gates with the same name (e.g. “Gx”) will be constrained to having the same noise on the cloud around the target qudits (even though the target qudits and cloud are different). If True, then gate noise operations for different sets of target qudits are independent.

independent_spambool, optional

Similar to independent_gates but for state preparation and measurement operations. When False, the noise applied to each set (individual or pair or triple etc.) of qudits must be the same, e.g., if the state preparation is a perfect preparation followed by a single-qudit rotation then this rotation must be by the same angle on all of the qudits.

connected_highweight_errorsbool, optional

An additional constraint regarding high-weight errors. When True, only high weight (weight 2+) elementary error generators whose non-trivial Paulis occupy a connected portion of the qudit graph are allowed. For example, if the qudit graph is a 1D chain of 4 qudits, 1-2-3-4, and weight-2 errors are allowed on a single-qudit gate with target = qudit-2, then weight-2 errors on 1-2 and 2-3 would be allowed, but errors on 1-3 would be forbidden. When False, no constraint is imposed.

basisBasis or str, optional

The basis to use when constructing operator representations for the elements of the created model.

verbosityint or VerbosityPrinter, optional

An integer >= 0 dictating how must output to send to stdout.

Returns

CloudNoiseModel

pygsti.models.create_qutrit_model(error_scale, x_angle=_np.pi / 2, y_angle=_np.pi / 2, ms_global=_np.pi / 2, ms_local=0, similarity=False, seed=None, basis='qt', evotype='default')

Constructs a standard qutrit Model.

This model contains the identity, XX, YY, and Molmer-Sorenson gates.

Parameters

error_scalefloat

Magnitude of random rotations to apply to the returned model. If zero, then perfect “ideal” gates are constructed.

x_anglefloat, optional

The rotation angle of each X in the XX gate.

y_anglefloat, optional

The rotation angle of each Y in the YY gate.

ms_globalfloat, optional

The global Molmer-Sorenson angle (theta)

ms_localfloat, optional

The local Molmer-Sorenson angle (theta)

similaritybool, optional

If true, then apply the random rotations (whose strengths are given by error_scale) as similarity transformations rather than just as post-multiplications to the ideal operation matrices.

seedint, optional

The seed used to generate random rotations.

basisstr, optional

The string abbreviation of the basis of the returned vector. Allowed values are Matrix-unit (std), Gell-Mann (gm) and Qutrit (qt). A Basis object may also be used.

evotypeEvotype or str, optional

The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

Returns

Model