pygsti.models
¶
pyGSTi Models Python Package
Submodules¶
pygsti.models.cloudnoisemodel
pygsti.models.explicitcalc
pygsti.models.explicitmodel
pygsti.models.fogistore
pygsti.models.gaugegroup
pygsti.models.implicitmodel
pygsti.models.layerrules
pygsti.models.localnoisemodel
pygsti.models.memberdict
pygsti.models.model
pygsti.models.modelconstruction
pygsti.models.modelnoise
pygsti.models.modelparaminterposer
pygsti.models.oplessmodel
pygsti.models.qutrit
pygsti.models.rpemodel
pygsti.models.stencillabel
Package Contents¶
Classes¶
A nqubit model using a lowweight and geometrically local error model with a common "global idle" operation. 

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

A model that stores the building blocks for layer operations and build circuitlayer operations ondemand. 

A nqubit implicit model that allows for only local noise. 

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

A model that does not have independent component operations. 

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

A generalized quantum instrument. 

The base class for all other evotype classes. 

Noise on a model containing individual gate/SPAM operations, e.g. an 

Model noise that is stored on a peroperation basis. 

Opmodel noise that is specified simply as the composition of other opmodel noise specifications. 

Noise generated by exponentiating a Lindbladian error generator. 

Pauli stochastic noise. 

Depolarization noise. 

A nqubit implicit model that allows for only local noise. 

A nqubit model using a lowweight and geometrically local error model with a common "global idle" operation. 

An ordered set of labeled matrices/vectors. 

A Basis whose elements are specified directly. 

A basis that is the direct sum of one or more "component" bases. 

A directed or undirected graph data structure used to represent geometrical layouts of qubits or qubit gates. 

Class responsible for logging things to stdout or a file. 
Functions¶

Decorator for deprecating a function. 

Build a rho or E vector from an expression. 

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

Build an operation object from an expression. 

Build a new Model given lists of operation labels and expressions. 

Build a new 

Creates a model by applying aliases to an existing model. 





local_noise=True creates lindblad ops that are embedded & composed 1Q ops, and assumes 

Construct a dictionary of potentially noisy gates that act only on their target qubits. 

Create a nqubit "crosstalkfree" model. 

Create a nqubit "crosstalkfree" model. 

Create a nqubit "cloudcrosstalk" model. 

Create a nqubit "cloudcrosstalk" model. 

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

Iterate over product of weight nonidentity Pauli 1Q basis indices 

Construct the Pauli product matrix from the given sigma_inds 







Compute the number of parameters in a particular 
Attributes¶
 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 nqubit model using a lowweight and geometrically local error model with a common “global idle” operation.
 Parameters
num_qubits (int) – The number of qubits
gatedict (dict) – A dictionary (an OrderedDict if you care about insertion order) that associates with stringtype gate names (e.g. “Gx”)
LinearOperator
, numpy.ndarray, orOpFactory
objects. When the objects may act on fewer than the total number of qubits (determined by their dimension/shape) then they are repeatedly embedded into num_qubitsqubit gates as specified by their availability. These operations represent the ideal target operations, and thus, any LinearOperator or OpFactory objects must be static, i.e., have zero parameters.availability (dict, optional) –
A dictionary whose keys are the same gate names as in gatedict and whose values are lists of qubitlabeltuples. Each qubitlabeltuple must have length equal to the number of qubits the corresponding gate acts upon, and causes that gate to be embedded to act on the specified qubits. For example, { ‘Gx’: [(0,),(1,),(2,)], ‘Gcnot’: [(0,1),(1,2)] } would cause the 1qubit `’Gx’gate to be embedded three times, acting on qubits 0, 1, and 2, and the 2qubit ‘Gcnot’gate to be embedded twice, acting on qubits 0 & 1 and 1 & 2. Instead of a list of tuples, values of availability may take the special values:
”allpermutations” and “allcombinations” equate to all possible
permutations and combinations of the appropriate number of qubit labels (deterined by the gate’s dimension).  “alledges” equates to all the vertices, for 1Q gates, and all the edges, for 2Q gates of the geometry.  “arbitrary” or “*” means that the corresponding gate can be placed on any target qubits via an
EmbeddingOpFactory
(uses less memory but slower than “allpermutations”.If a gate name (a key of gatedict) is not present in availability, the default is “alledges”.
qubit_labels (tuple, optional) – The circuitline labels for each of the qubits, which can be integers and/or strings. Must be of length num_qubits. If None, then the integers from 0 to num_qubits1 are used.
geometry ({"line","ring","grid","torus"} or QubitGraph) – The type of connectivity among the qubits, specifying a graph used to define neighbor relationships. Alternatively, a
QubitGraph
object with node labels equal to qubit_labels may be passed directly.global_idle_layer (LinearOperator) – A global idle operation which acts on all the qubits and is, if add_idle_noise_to_all_gates=True, composed with the actions of specific gates to form the layer operation of any circuit layer.
prep_layers (None or operator or dict or list, optional) – The SPAM operations as nqubit 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.
povm_layers (None or operator or dict or list, optional) – The SPAM operations as nqubit 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_fn (function, optional) – A function which takes a single
Label
as an argument and returns the cloudnoise 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_fn (function, 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 qubits 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 layerlabels correspond to the same cloud  e.g. the cloudkey for (“Gx”,2) and (“Gy”,2) might be the same and could be processed together when selecing sequences that amplify the parameters in the cloudnoise operations for these two labels. The return value should be something hashable with the property that two noise which act on the same qubits should have the same cloud key.simulator (ForwardSimulator or {"auto", "matrix", "map"}) –
The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`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_matrixop_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_matrixstate_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+).
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.
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 layerlabel) of cloud noise contributions, i.e. a map that acts as the product of exponentiated errorgenerator 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 cloudnoise error generators, i.e. a map that acts as the exponentiated sum of error generators (ordering is irrelevant in this case).
add_idle_noise_to_all_gates (bool, optional) – Whether the global idle should be added as a factor following the ideal action of each of the nonidle gates.
verbosity (int, optional) – An integer >= 0 dictating how must output to send to stdout.
 create_processor_spec(self)¶
 property clouds(self)¶
Returns the set of cloudsets used when creating sequences which amplify the parameters of this model.
 Returns
dict
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 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 dictionarylike access to their matrices. State preparation and POVM effect operations are represented as column vectors.
 Parameters
state_space (StateSpace) – 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 :method:`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_prefix (string, optional) – Key prefix for POVM effects, allowing the model to determing what type of object a key corresponds to.
gate_prefix (string, optional) – Key prefix for gates, allowing the model to determing what type of object a key corresponds to.
povm_prefix (string, optional) – Key prefix for POVMs, allowing the model to determing what type of object a key corresponds to.
instrument_prefix (string, optional) – Key prefix for instruments, allowing the model to determing what type of object a key corresponds to.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) –
The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`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_matrixop_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_matrixstate_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+).
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.
 _strict = False¶
 property _primitive_prep_label_dict(self)¶
 property _primitive_povm_label_dict(self)¶
 property _primitive_op_label_dict(self)¶
 property _primitive_instrument_label_dict(self)¶
 _iter_parameterized_objs(self)¶
 _excalc(self)¶
Create & return a special explicitmodel calculator for this model
 _embed_operation(self, op_target_labels, op_val, force=False)¶
Called by OrderedMemberDict._auto_embed to create an embeddedgate object that embeds op_val into the subspace of self.state_space given by op_target_labels.
 Parameters
op_target_labels (list) – A list of op_val’s target state space labels.
op_val (LinearOperator) – The gate object to embed. Note this should be a legitimate LinearOperatorderived object and not just a numpy array.
force (bool, optional) – Always wrap with an embedded LinearOperator, even if the dimension of op_val is the full model dimension.
 Returns
LinearOperator – A gate of the full model dimension.
 property default_gauge_group(self)¶
Gets the default gauge group for performing gauge transformations on this Model.
 Returns
GaugeGroup
 property prep(self)¶
The unique state preparation in this model, if one exists.
If not, a ValueError is raised.
 Returns
State
 property effects(self)¶
The effect vectors from the unique POVM in this model, if one exists.
If not, a ValueError is raised.
 Returns
list of POVMEffects
 __setitem__(self, label, value)¶
Set an operator, state, or POVM associated with a given label.
 Parameters
label (string) – the gate or SPAM vector label.
value (numpy array or LinearOperator or State or POVM) – a operation matrix, state vector, or POVM, which must have the appropriate state space for the Model and appropriate type given the prefix of the label.
 __getitem__(self, label)¶
Get an operation, state, or POVM associated with a given label.
 Parameters
label (string) – the gate, state vector, or POVM label.
 set_all_parameterizations(self, gate_type, prep_type='auto', povm_type='auto', instrument_type='auto', extra=None)¶
Convert all gates, states, and POVMs to a specific parameterization type.
 Parameters
parameterization_type (string) –
The gate, state, and POVM parameterization type. Allowed values are (where ‘*’ means ” terms” and ” clifford terms” evolutiontype suffixes are allowed):
”full” : each gate / state / POVM effect element is an independent parameter
”TP” : TracePreserving 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*” : CompletelyPositiveTracePreserving
”H+S+A*” : Hamiltoian, PauliStochastic, and Affine errors
”H+S*” : Hamiltonian and PauliStochastic errors
”S+A*” : PauliStochastic and Affine errors
”S*” : PauliStochastic 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).
extra (dict, optional) – For “H+S terms” type, this may specify a dictionary of unitary gates and pure state vectors to be used as the ideal operation of each gate/SPAM operation.
 Returns
None
 __setstate__(self, state_dict)¶
 property num_elements(self)¶
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(self)¶
Return the number of nongauge parameters in this model.
 Returns
int – the number of nongauge model parameters.
 property num_gauge_params(self)¶
Return the number of gauge parameters in this model.
 Returns
int – the number of gauge model parameters.
 deriv_wrt_params(self)¶
The elementwise 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_projector(self, item_weights=None, non_gauge_mix_mx=None)¶
Construct a projector onto the nongauge parameter space.
Useful for isolating the gauge degrees of freedom from the nongauge degrees of freedom.
 Parameters
item_weights (dict, 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 nongauge space, orthogonal the gauge space, that is projected onto.
non_gauge_mix_mx (numpy array, optional) – An array of shape (n_non_gauge_params,n_gauge_params) specifying how to mix the nongauge degrees of freedom into the gauge degrees of freedom that are projected out by the returned object. This argument essentially sets the offdiagonal block of the metric used for orthogonality in the “gauge + nongauge” 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 parameterspace, and has rank equal to the number of nongauge degrees of freedom.
 transform_inplace(self, 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
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 frobeniusdist(self, 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_model (Model) – the other model to difference against.
transform_mx (numpy 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_weights (dict, 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.
normalize (bool, optional) – if True (the default), the sum of weighted squareddifferences 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(self, 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_model (Model) – the other model to difference against.
transform_mx (numpy 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_weights (dict, 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
residuals (numpy.ndarray) – A 1D array of residuals (differences w.r.t. other)
nSummands (int) – The (weighted) number of elements accounted for by the residuals.
 jtracedist(self, 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_model (Model) – the other model to difference against.
transform_mx (numpy 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_spam (bool, optional) – Whether to add to the maxtracedistance the frobenius distances between corresponding SPAM operations.
 Returns
float
 diamonddist(self, other_model, transform_mx=None, include_spam=True)¶
Compute the diamondnorm distance between this model and other_model.
This is defined as the maximum of the diamondnorm distances between each corresponding gate, including spam gates.
 Parameters
other_model (Model) – the other model to difference against.
transform_mx (numpy 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_spam (bool, optional) – Whether to add to the maxdiamonddistance the frobenius distances between corresponding SPAM operations.
 Returns
float
 _tpdist(self)¶
Compute the “distance” between this model and the space of tracepreserving (TP) maps.
This is defined as the square root of the sumofsquared deviations among the first row of all operation matrices and the first element of all state preparations.
 Returns
float
 strdiff(self, 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_model (Model) – the other model to difference against.
metric ({'frobenius', 'infidelity', 'diamond'}) – Which distance metric to use.
 Returns
str
 _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.
 __str__(self)¶
Return str(self).
 all_objects(self)¶
Iterate over all of the (label, operator object) entities in this model.
This iterator runs over all state preparations, POVMS, operations, and instruments.
 depolarize(self, 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_noise (float, optional) –
 apply depolarizing noise of strength
1op_noise
to all gates in the model. (Multiplies each assumedPaulibasis operation matrix by the diagonal matrix with
(1.0op_noise)
along all the diagonal elements except the first (the identity).
 apply depolarizing noise of strength
spam_noise (float, optional) – apply depolarizing noise of strength
1spam_noise
to all SPAM opeations (state and POVM effects) in the model. (Multiplies the nonidentity part of each assumedPaulibasis state preparation vector and measurement vector by(1.0spam_noise)
).max_op_noise (float, optional) – specified instead of op_noise; apply a random depolarization with maximum strength
1max_op_noise
to each gate in the model.max_spam_noise (float, optional) – specified instead of spam_noise; apply a random depolarization with maximum strength
1max_spam_noise
to each state preparation and POVM in the model.seed (int, optional) – if not
None
, seed numpy’s random number generator with this value before generating random depolarizations.
 Returns
Model – the depolarized Model
 rotate(self, 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 nqubit models.
 Parameters
rotate (tuple 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 nonidentity unnormalized 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_rotate (float, 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).
seed (int, 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(self, 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
scale (float) – maximum element magnitude in the generator of each random unitary transform.
seed (int, optional) – if not None, seed numpy’s random number generator with this value before generating random depolarizations.
rand_state (numpy.random.RandomState) – A RandomState object to generate samples from. Can be useful to set instead of seed if you want reproducible distribution samples across multiple random function calls but you don’t want to bother with manually incrementing seeds between those calls.
 Returns
Model – the randomized Model
 increase_dimension(self, 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 zeropadded and operation matrices are padded with 1’s on the diagonal and zeros on the offdiagonal (effectively padded by identity operation).
 Parameters
new_dimension (int) – 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 increaseddimension Model
 _decrease_dimension(self, new_dimension)¶
Decrease the dimension of this model.
Shrink the spam vectors and operation matrices of model to a specified dimension, and return the resulting model.
 Parameters
new_dimension (int) – 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 decreaseddimension Model
 kick(self, 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 [biasabsmag,bias+absmag].
 Parameters
absmag (float, optional) – The maximum magnitude of the entries in the “kick” matrix relative to bias.
bias (float, optional) – The bias of the entries in the “kick” matrix.
seed (int, 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(self, 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_filter (iterable, 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(self)¶
Print to stdout relevant information about this model.
This information includes the Choi matrices and their eigenvalues.
 Returns
None
 _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.
 _member_labels_for_instrument(self, inst_lbl)¶
Gets 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.
 _reinit_opcaches(self)¶
Called when parameter vector structure changes and self._opcaches should be cleared & reinitialized
 create_processor_spec(self, qubit_labels='auto')¶
Create a processor specification from this model with the given qubit labels.
Currently this only works for models on qubits.
 Parameters
qubit_labels (tuple or “auto”, optional) – A tuple of qubit labels, e.g. (‘Q0’, ‘Q1’) or (0, 1). “auto” uses the labels in this model’s state space labels.
 Returns
QubitProcessorSpec
 create_modelmember_graph(self)¶
Generate a ModelMemberGraph for the model.
 Returns
ModelMemberGraph – A directed graph capturing dependencies among model members
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 errorgen_coefficients(self, normalized_elem_gens=True)¶
TODO: docstring  returns a nested dict containing all the error generator coefficients for all the operations in this model.
 _add_reparameterization(self, primitive_op_labels, fogi_dirs, errgenset_space_labels)¶
 _format_gauge_action_matrix(self, mx, op, reduce_to_model_space, row_basis, op_gauge_basis, create_complete_basis_fn)¶
 setup_fogi(self, initial_gauge_basis, create_complete_basis_fn=None, op_label_abbrevs=None, reparameterize=False, reduce_to_model_space=True, dependent_fogi_action='drop')¶
 fogi_errorgen_component_labels(self, include_fogv=False, typ='normal')¶
 fogi_errorgen_components_array(self, include_fogv=False, normalized_elem_gens=True)¶
 set_fogi_errorgen_components_array(self, components, include_fogv=False, normalized_elem_gens=True, truncate=False)¶
 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 circuitlayer operations ondemand.
An ImplicitOpModel represents a flexible QIP model whereby only the building blocks for layer operations are stored, and custom layerlizard logic is used to construct layer operations from these blocks on an ondemand basis.
 Parameters
state_space (StateSpace) – The state space for this model.
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.
basis (Basis) – The basis used for the state space by dense operator representations.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) – The circuit simulator used to compute any requested probabilities, e.g. from :method:`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.
 property _primitive_prep_label_dict(self)¶
 property _primitive_povm_label_dict(self)¶
 property _primitive_op_label_dict(self)¶
 property _primitive_instrument_label_dict(self)¶
 _iter_parameterized_objs(self)¶
 _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.
 __setstate__(self, state_dict)¶
 compute_clifford_symplectic_reps(self, 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_filter (iterable, 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.
 __str__(self)¶
Return str(self).
 _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
 _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.
 _member_labels_for_instrument(self, inst_lbl)¶
Gets 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.
 _reinit_opcaches(self)¶
Called when parameter vector structure changes and self._opcaches should be cleared & reinitialized
 create_modelmember_graph(self)¶
Generate a ModelMemberGraph for the model.
 Returns
ModelMemberGraph – A directed graph capturing dependencies among model members
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 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 nqubit 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
num_qubits (int) – The total number of qubits.
gatedict (dict) – 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 qubits (determined by their dimension/shape) then they are repeatedly embedded into num_qubitsqubit gates as specified by availability. While the keys of this dictionary are usually stringtype gate names, labels that include target qubits, 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 qubits (e.g. “Gx”). Furthermore,OpFactory
objects may be used in place of LinearOperator objects to allow the evaluation of labels with arguments.prep_layers (None or operator or dict or list) – The state preparateion operations as nqubit 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_layers (None or operator or dict or list) – The state preparateion operations as nqubit 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”.availability (dict, optional) –
A dictionary whose keys are the same gate names as in gatedict and whose values are lists of qubitlabeltuples. Each qubitlabeltuple must have length equal to the number of qubits the corresponding gate acts upon, and causes that gate to be embedded to act on the specified qubits. For example, { ‘Gx’: [(0,),(1,),(2,)], ‘Gcnot’: [(0,1),(1,2)] } would cause the 1qubit `’Gx’gate to be embedded three times, acting on qubits 0, 1, and 2, and the 2qubit ‘Gcnot’gate to be embedded twice, acting on qubits 0 & 1 and 1 & 2. Instead of a list of tuples, values of availability may take the special values:
”allpermutations” and “allcombinations” equate to all possible
permutations and combinations of the appropriate number of qubit labels (deterined by the gate’s dimension).  “alledges” equates to all the vertices, for 1Q gates, and all the edges, for 2Q gates of the geometry.  “arbitrary” or “*” means that the corresponding gate can be placed on any target qubits via an
EmbeddingOpFactory
(uses less memory but slower than “allpermutations”.If a gate name (a key of gatedict) is not present in availability, the default is “alledges”.
qubit_labels (tuple, optional) – The circuitline labels for each of the qubits, which can be integers and/or strings. Must be of length num_qubits. If None, then the integers from 0 to num_qubits1 are used.
geometry ({"line","ring","grid","torus"} or QubitGraph) – The type of connectivity among the qubits, specifying a graph used to define neighbor relationships. Alternatively, a
QubitGraph
object with node labels equal to qubit_labels may be passed directly.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.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) –
The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`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_matrixop_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_matrixstate_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_gates (bool, 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 qubits may have different local noise, and so the operation_bks[‘gates’] dictionary contains a key for each gate
available gate placement.
ensure_composed_gates (bool, 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.global_idle (LinearOperator, optional) – A global idle operation, which is performed once at the beginning of every circuit layer. If None, no such operation is performed. If a 1qubit operator is given and num_qubits > 1 the global idle is the parallel application of this operator on each qubit line. Otherwise the given operator must act on all num_qubits qubits.
 create_processor_spec(self)¶
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 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_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 (2tuple, 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 (2tuple, 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
 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 gatelevel modeling. Parameters
state_space (StateSpace) – The state space of this model.
 property dim(self)¶
 property parameter_bounds(self)¶
Upper and lower bounds on the values of each parameter, utilized by optimization routines
 abstract circuit_outcomes(self, circuit)¶
Get all the possible outcome labels produced by simulating this circuit.
 Parameters
circuit (Circuit) – Circuit to get outcomes of.
 Returns
tuple
 abstract 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.
 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 (2tuple, 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.
 abstract __str__(self)¶
Return str(self).
 class pygsti.models.SuccessFailModel(state_space, use_cache=False)¶
Bases:
OplessModel
An opless model that always outputs 2 (success & failure) probabilities for each circuit.
 Parameters
state_space (StateSpace) – The state space of this model.
use_cache (bool, optional) – Whether a cache should be used to increase performance.
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property sim(self)¶
Forward simulator for this model
 _post_copy(self, copy_into, memo)¶
Called after all other copying is done, to perform “linking” between the new model (copy_into) and its members.
 circuit_outcomes(self, circuit)¶
Get all the possible outcome labels produced by simulating this circuit.
 Parameters
circuit (Circuit) – Circuit to get outcomes of.
 Returns
tuple
 abstract _success_prob(self, circuit, cache)¶
 _success_dprob(self, circuit, param_slice, cache)¶
Derived classes can override this. Default implemntation is to use finite difference.
 probabilities(self, circuit, outcomes=None, time=None)¶
Construct a dictionary containing the outcome probabilities of circuit.
 Parameters
circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.
outcomes (list or tuple) – A sequence of outcomes, which can themselves be either tuples (to include intermediate measurements) or simple strings, e.g. ‘010’.
time (float, optional) – The start time at which circuit is evaluated.
 Returns
probs (OutcomeLabelDict) – A dictionary with keys equal to outcome labels and values equal to probabilities.
 bulk_probabilities(self, circuits, clip_to=None, comm=None, mem_limit=None, smartc=None)¶
Construct a dictionary containing the probabilities for an entire list of circuits.
 Parameters
circuits ((list of Circuits) or CircuitOutcomeProbabilityArrayLayout) – When a list, each element specifies a circuit to compute outcome probabilities for. A
CircuitOutcomeProbabilityArrayLayout
specifies the circuits along with an internal memory layout that reduces the time required by this function and can restrict the computed probabilities to those corresponding to only certain outcomes.clip_to (2tuple, optional) – (min,max) to clip return value if not None.
comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors. Distribution is performed over subtrees of evalTree (if it is split).
mem_limit (int, optional) – A rough memory limit in bytes which is used to determine processor allocation.
smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.
 Returns
probs (dictionary) – A dictionary such that probs[opstr] is an ordered dictionary of (outcome, p) tuples, where outcome is a tuple of labels and p is the corresponding probability.
 class pygsti.models.Instrument(member_ops, evotype=None, state_space=None, items=[])¶
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_ops (dict of LinearOperator objects) – A dict (or list of key,value pairs) of the gates.
evotype (Evotype 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_space (StateSpace, 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.
items (list or dict, optional) – Initial values. This should only be used internally in deserialization.
 submembers(self)¶
Get the ModelMemberderived objects contained in this one.
 Returns
list
 to_memoized_dict(self, 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.
 classmethod _from_memoized_dict(cls, mm_dict, serial_memo)¶
For subclasses to implement. Submemberexistence checks are performed, and the gpindices of the return value is set, by the nonunderscored :method:`from_memoized_dict` implemented in this class.
 _is_similar(self, other, rtol, atol)¶
Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers
 __setitem__(self, key, value)¶
Set self[key] to value.
 __reduce__(self)¶
Needed for OrderedDictderived classes (to set dict items)
 __pygsti_reduce__(self)¶
 simplify_operations(self, 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
prefix (str) – A string, usually identitying this instrument, which may be used to prefix the simplified gate keys.
 Returns
OrderedDict of Gates
 property parameter_labels(self)¶
An array of labels (usually strings) describing this model member’s parameters.
 property num_elements(self)¶
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(self)¶
Get the number of independent parameters which specify this Instrument.
 Returns
int – the number of independent parameters.
 to_vector(self)¶
Extract a vector of the underlying gate parameters from this Instrument.
 Returns
numpy array – a 1D numpy array with length == num_params().
 from_vector(self, v, close=False, dirty_value=True)¶
Initialize the Instrument using a vector of its parameters.
 Parameters
v (numpy array) – The 1D vector of gate parameters. Length must == num_params().
close (bool, 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_value (bool, 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(self, s)¶
Update each Instrument element matrix O with inv(s) * O * s.
 Parameters
s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.
 Returns
None
 depolarize(self, amount)¶
Depolarize this Instrument by the given amount.
 Parameters
amount (float 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(self, amount, mx_basis='gm')¶
Rotate this instrument by the given amount.
 Parameters
amount (tuple of floats, optional) – Specifies the rotation “coefficients” along each of the nonidentity Pauliproduct 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 nonidentity unnormalized Pauli operators.
mx_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The source and destination basis, respectively. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
 Returns
None
 acton(self, state)¶
Act with this instrument upon state
 Parameters
state (State) – 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.
 __str__(self)¶
Return str(self).
 class pygsti.models._Evotype(name, prefer_dense_reps=False)¶
Bases:
object
The base class for all other evotype classes.
Provides an interface for creating representations. The create_* methods specify an API used by the operation classes so they can create the representation they need.
 Parameters
name (str) – The (module) name of the evolution type
prefer_dense_reps (bool, optional) – Whether the dense representation provided by this evolution type should be preferred over more specific types, such as those for composed, embedded, and exponentiated operations. Most often this is set to True when using a
MatrixForwardSimulator
in order to get a performance gain.
 default_evotype¶
 _reptype_to_attrs¶
 classmethod cast(cls, obj, default_prefer_dense_reps=False)¶
 __getstate__(self)¶
 __setstate__(self, state)¶
 __hash__(self)¶
Return hash(self).
 __eq__(self, other_evotype)¶
Return self==value.
 __str__(self)¶
Return str(self).
 property minimal_space(self)¶
 minimal_dim(self, state_space)¶
 supported_reptypes(self)¶
 supports(self, reptype)¶
 create_dense_superop_rep(self, mx, state_space)¶
 create_dense_unitary_rep(self, mx, super_basis, state_space)¶
 create_composed_rep(self, factor_op_reps, state_space)¶
 create_embedded_rep(self, state_space, targetLabels, embedded_rep)¶
 create_experrorgen_rep(self, errorgen_rep)¶
 create_stochastic_rep(self, basis, rate_poly_dicts, initial_rates, seed_or_state, state_space)¶
 create_sum_rep(self, factor_reps, state_space)¶
 create_clifford_rep(self, unitarymx, symplecticrep, super_basis, state_space)¶
 create_repeated_rep(self, rep_to_repeat, num_repetitions, state_space)¶
 create_standard_rep(self, standard_name, super_basis, state_space)¶
 create_sparse_rep(self, data, indices, indptr, state_space)¶
 create_lindblad_errorgen_rep(self, lindblad_term_dict, basis, state_space)¶
 create_dense_state_rep(self, vec, state_space)¶
 create_pure_state_rep(self, purevec, super_basis, state_space)¶
 create_computational_state_rep(self, zvals, super_basis, state_space)¶
 create_composed_state_rep(self, state_rep, op_rep, state_space)¶
 create_tensorproduct_state_rep(self, factor_state_reps, state_space)¶
 create_conjugatedstate_effect_rep(self, state_rep)¶
 create_computational_effect_rep(self, zvals, super_basis, state_space)¶
 create_tensorproduct_effect_rep(self, povm_factors, effect_labels, state_space)¶
 create_composed_effect_rep(self, errmap_rep, effect_rep, errmap_name, state_space)¶
 create_term_rep(self, coeff, mag, logmag, pre_state, post_state, pre_effect, post_effect, pre_ops, post_ops)¶
 create_direct_term_rep(self, coeff, mag, logmag, pre_state, post_state, pre_effect, post_effect, pre_ops, post_ops)¶
 conjugate_state_term_rep(self, term_rep)¶
Turns a state term => effect term via conjugation of the state
 class pygsti.models._OpModelNoise¶
Bases:
ModelNoise
Noise on a model containing individual gate/SPAM operations, e.g. an
OpModel
object.This class is a base class that should not be instantiated directly.
 classmethod cast(cls, obj)¶
Convert an object to an
OpModelNoise
object if it isn’t already.If a dictionary is given, it is assumed to contain peroperation error specifications. If a list/tuple is given, it is assumed to contain multiple subspecifications that should be composed together (by constructing a
ComposedOpModelNoise
object). Parameters
obj (object) – The object to convert.
 Returns
OpModelNoise
 abstract keys(self)¶
The operation labels for which this object specifies noise.
 abstract __contains__(self, key)¶
 abstract create_errorgen_stencil(self, opkey, evotype, state_space, num_target_labels=None)¶
Create an “error generator stencil” for the noise corresponding to an operation label.
A stencil is one or more operator objects that have yet to be embedded on their final qubits and then composed. The embedding and composing step is done later so that, if desired, the same errors can be used on multiple sets of target qubits (often this is done when a “independent” argument to a modelcreation function is False). An “error generator stencil” is a stencil whose operators are error generators, rather than error maps.
 Parameters
opkey (Label or StencilLabel) – The operation label to create the stencil for.
evotype (str or Evotype) – The evolution type of to use when creating the stencil operators.
state_space (StateSpace) – The state space to use when creating the stencil operators. This can be a local state space, disparate from the actual processor’s state space, or the entire state space that the stencil operations will ultimately be embedded into. In the former case, num_target_labels should be left as None, indicating that state_space is the exact space being acted upon. In the latter case, num_target_labels should specify the number of target labels within state_space that this stencil will be given when it is applied (embedded) into state_space. This requires that all the labels in state_space correspond to the same type and dimension space (e.g. all are qubit spaces).
num_target_labels (int or None) – The number of labels within state_space that the op_key operation acts upon (this assumes that all the labels in state_space are similar, e.g., all qubits). If None then it acts on the entire space given by state_space.
 Returns
stencil (OrderedDict) – A dictionary with keys that are
Label
orStencilLabel
objects and values that areLinearOperator
objects. The stencil is applied by embedding each operator according to its key and then composing the results.
 abstract apply_errorgen_stencil(self, stencil, evotype, state_space, target_labels=None, qubit_graph=None, copy=False)¶
Apply an errorgenerator stencil created by this object to a specific set of target labels.
A stencil is applied by embedding each operator in the stencil according to its target state space labels (which may include stencillabel expansions) and then composing the results.
 Parameters
stencil (OrderedDict) – The stencil to apply, usually created by :method:`create_errorgen_stencil`.
evotype (str or Evotype) – The evolution type of to use when creating the embedded and composed operators, which should match that of the stencil operators (the evotype used to create the stencil).
state_space (StateSpace) – The state space to use when creating the composed and embedded operators. This should be the total state space of the model that these noise operations will be inserted into.
target_labels (tuple or None, optional) – The target labels that determine where on the qubit graph this stencil will be placed. When a tuple, it should have length equal to the num_target_labels argument passed to :method:`create_errorgen_stencil`. None indicates that the entire space is the “target” space of the stencil (e.g. a global idle, preparation, or measurement).
qubit_graph (QubitGraph, optional) – The relevant qubit graph, usually from a processor specification, that contains adjacency and direction information used to resolve stencil state space labels into absolute labels within state_space. If None, then an error will be raised if any direction or connectivity information is needed to resolve the state space labels.
copy (bool, optional) – Whether the stencil operations should be copied before embedding and composing them to apply the stencil. True can be used to make different applications of the stencil independent operations.
 Returns
LinearOperator
 create_errorgen(self, opkey, evotype, state_space, target_labels=None, qubit_graph=None)¶
Create an error generator object to implement the noise on a given model operation.
 Parameters
opkey (Label or StencilLabel) – The operation label to create the error generator for.
evotype (str or Evotype) – The evolution type to use when creating the error generator.
state_space (StateSpace) – The state space to use when creating the error generator.
target_labels (tuple or None, optional) – The target state space labels for this operation. Sometimes this is also contained in opkey, but not always, so it must be supplied as a separate argument.
qubit_graph (QubitGraph, optional) – The relevant qubit graph, usually from a processor specification, that contains adjacency and direction information used to create more complex types of errors. If None, then an error will be raised if graph information is needed.
 Returns
LinearOperator
 abstract create_errormap_stencil(self, opkey, evotype, state_space, num_target_labels=None)¶
Create an “error map stencil” for the noise corresponding to an operation label.
A stencil is one or more operator objects that have yet to be embedded on their final qubits and then composed. The embedding and composing step is done later so that, if desired, the same errors can be used on multiple sets of target qubits (often this is done when a “independent” argument to a modelcreation function is False). An “error map stencil” is a stencil whose operators are error maps
rather than error generators.
 Parameters
opkey (Label or StencilLabel) – The operation label to create the stencil for.
evotype (str or Evotype) – The evolution type of to use when creating the stencil operators.
state_space (StateSpace) – The state space to use when creating the stencil operators. This can be a local state space, disparate from the actual processor’s state space, or the entire state space that the stencil operations will ultimately be embedded into. In the former case, num_target_labels should be left as None, indicating that state_space is the exact space being acted upon. In the latter case, num_target_labels should specify the number of target labels within state_space that this stencil will be given when it is applied (embedded) into state_space. This requires that all the labels in state_space correspond to the same type and dimension space (e.g. all are qubit spaces).
num_target_labels (int or None) – The number of labels within state_space that the op_key operation acts upon (this assumes that all the labels in state_space are similar, e.g., all qubits). If None then it acts on the entire space given by state_space.
 Returns
stencil (OrderedDict) – A dictionary with keys that are
Label
orStencilLabel
objects and values that areLinearOperator
objects. The stencil is applied by embedding each operator according to its key and then composing the results.
 abstract apply_errormap_stencil(self, stencil, evotype, state_space, target_labels=None, qubit_graph=None, copy=False)¶
Apply an errormap stencil created by this object to a specific set of target labels.
A stencil is applied by embedding each operator in the stencil according to its target state space labels (which may include stencillabel expansions) and then composing the results.
 Parameters
stencil (OrderedDict) – The stencil to apply, usually created by :method:`create_errormap_stencil`.
evotype (str or Evotype) – The evolution type of to use when creating the embedded and composed operators, which should match that of the stencil operators (the evotype used to create the stencil).
state_space (StateSpace) – The state space to use when creating the composed and embedded operators. This should be the total state space of the model that these noise operations will be inserted into.
target_labels (tuple or None, optional) – The target labels that determine where on the qubit graph this stencil will be placed. When a tuple, it should have length equal to the num_target_labels argument passed to :method:`create_errormap_stencil`. None indicates that the entire space is the “target” space of the stencil (e.g. a global idle, preparation, or measurement).
qubit_graph (QubitGraph, optional) – The relevant qubit graph, usually from a processor specification, that contains adjacency and direction information used to resolve stencil state space labels into absolute labels within state_space. If None, then an error will be raised if any direction or connectivity information is needed to resolve the state space labels.
copy (bool, optional) – Whether the stencil operations should be copied before embedding and composing them to apply the stencil. True can be used to make different applications of the stencil independent operations.
 Returns
LinearOperator
 create_errormap(self, opkey, evotype, state_space, target_labels=None, qubit_graph=None)¶
Create an error map object to implement the noise on a given model operation.
 Parameters
opkey (Label or StencilLabel) – The operation label to create the error map for.
evotype (str or Evotype) – The evolution type to use when creating the error map.
state_space (StateSpace) – The state space to use when creating the error map.
target_labels (tuple or None, optional) – The target state space labels for this operation. Sometimes this is also contained in opkey, but not always, so it must be supplied as a separate argument.
qubit_graph (QubitGraph, optional) – The relevant qubit graph, usually from a processor specification, that contains adjacency and direction information used to create more complex types of errors. If None, then an error will be raised if graph information is needed.
 Returns
LinearOperator
 reset_access_counters(self)¶
Resets the internal keyaccess counters to zero.
These counters tally the number of times each operation key is accessed, and are used to identify model noise specification that are supplied by the user but never used. See :method:`warn_about_zero_counters`.
 Returns
None
 _increment_touch_count(self, opkey)¶
 warn_about_zero_counters(self)¶
Issue a warning if any of the internal keyaccess counters are zero
Used to catch noise specifications that are never utilized and that the caller/user should be warned about.
 Returns
None
 abstract compute_stencil_absolute_sslbls(self, stencil, state_space, target_labels=None, qubit_graph=None)¶
Computes the set of state space labels that would be utilized when applying a stencil.
This function computes which state space labels are nontrivially acted upon by the operation that results from applying stencil to target_labels.
 Parameters
stencil (OrderedDict) – The stencil. A dictionary with keys that are target state space labels (perhaps stencil labels) and values that are operations. This function only cares about the keys of this dictionary.
state_space (StateSpace) – The state space that would be given if/when applying stencil. This should be the total state space of the model that the applied stencil would be inserted into.
target_labels (tuple or None, optional) – The target labels that determine where on the qubit graph stencil will be placed. None indicates that the entire space is the “target” space of the stencil.
qubit_graph (QubitGraph, optional) – The relevant qubit graph that contains adjacency and direction information used to resolve stencil state space labels into absolute labels within state_space. If None, then an error will be raised if any direction or connectivity information is needed to resolve the state space labels.
 Returns
set – A set (i.e. without any duplicates) of the state space labels that would be acted upon.
 class pygsti.models._OpModelPerOpNoise(per_op_noise)¶
Bases:
OpModelNoise
Model noise that is stored on a peroperation basis.
 Parameters
per_op_noise (dict) – A dictionary mapping operation labels (which will become the keys of this
OpModelNoise
object) to eitherOpNoise
objects or to a nexted dictionary mapping absolute or stencil state space labels toOpNoise
objects. In the former case, theOpNoise
object is assumed to apply to all the target labels of the operation.
 keys(self)¶
The operation labels for which this object specifies noise.
 __contains__(self, key)¶
 create_errorgen_stencil(self, opkey, evotype, state_space, num_target_labels=None)¶
 apply_errorgen_stencil(self, stencil, evotype, state_space, target_labels=None, qubit_graph=None, copy=False)¶
 create_errormap_stencil(self, opkey, evotype, state_space, num_target_labels=None)¶
 apply_errormap_stencil(self, stencil, evotype, state_space, target_labels=None, qubit_graph=None, copy=False)¶
 _map_stencil_sslbls(self, stencil_sslbls, qubit_graph, state_space, target_lbls)¶
 compute_stencil_absolute_sslbls(self, stencil, state_space, target_labels=None, qubit_graph=None)¶
Computes the set of state space labels that would be utilized when applying a stencil.
This function computes which state space labels are nontrivially acted upon by the operation that results from applying stencil to target_labels.
 Parameters
stencil (OrderedDict) – The stencil. A dictionary with keys that are target state space labels (perhaps stencil labels) and values that are operations. This function only cares about the keys of this dictionary.
state_space (StateSpace) – The state space that would be given if/when applying stencil. This should be the total state space of the model that the applied stencil would be inserted into.
target_labels (tuple or None, optional) – The target labels that determine where on the qubit graph stencil will be placed. None indicates that the entire space is the “target” space of the stencil.
qubit_graph (QubitGraph, optional) – The relevant qubit graph that contains adjacency and direction information used to resolve stencil state space labels into absolute labels within state_space. If None, then an error will be raised if any direction or connectivity information is needed to resolve the state space labels.
 Returns
set – A set (i.e. without any duplicates) of the state space labels that would be acted upon.
 _key_to_str(self, key, prefix='')¶
 __str__(self)¶
Return str(self).
 class pygsti.models._ComposedOpModelNoise(opmodelnoises)¶
Bases:
OpModelNoise
Opmodel noise that is specified simply as the composition of other opmodel noise specifications.
 Parameters
opmodelnoises (iterable) – The sub
OpModelNoise
objects.
 ensure_no_duplicates(self)¶
Raise an AssertionError if there are any duplicates among the composed noise specifications.
 Returns
None
 keys(self)¶
The operation labels for which this object specifies noise.
 __contains__(self, key)¶
 create_errorgen_stencil(self, opkey, evotype, state_space, num_target_labels=None)¶
 apply_errorgen_stencil(self, stencil, evotype, state_space, target_labels=None, qubit_graph=None, copy=False)¶
 create_errormap_stencil(self, opkey, evotype, state_space, num_target_labels=None)¶
 apply_errormap_stencil(self, stencil, evotype, state_space, target_labels=None, qubit_graph=None, copy=False)¶
 compute_stencil_absolute_sslbls(self, stencil, state_space, target_labels=None, qubit_graph=None)¶
Computes the set of state space labels that would be utilized when applying a stencil.
This function computes which state space labels are nontrivially acted upon by the operation that results from applying stencil to target_labels.
 Parameters
stencil (OrderedDict) – The stencil. A dictionary with keys that are target state space labels (perhaps stencil labels) and values that are operations. This function only cares about the keys of this dictionary.
state_space (StateSpace) – The state space that would be given if/when applying stencil. This should be the total state space of the model that the applied stencil would be inserted into.
target_labels (tuple or None, optional) – The target labels that determine where on the qubit graph stencil will be placed. None indicates that the entire space is the “target” space of the stencil.
qubit_graph (QubitGraph, optional) – The relevant qubit graph that contains adjacency and direction information used to resolve stencil state space labels into absolute labels within state_space. If None, then an error will be raised if any direction or connectivity information is needed to resolve the state space labels.
 Returns
set – A set (i.e. without any duplicates) of the state space labels that would be acted upon.
 _key_to_str(self, key, prefix='')¶
 __str__(self)¶
Return str(self).
 class pygsti.models._LindbladNoise(error_coeffs, parameterization='auto')¶
Bases:
OpNoise
Noise generated by exponentiating a Lindbladian error generator.
The error generator is a Lindbladform sum of elementary error generators corresponding to Hamiltonian and other (stochastic, correlation, etc.) type of errors.
 Parameters
error_coeffs (dict) – A dictionary of Lindbladterm coefficients. Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType can be “H” (Hamiltonian), “S” (Stochastic/other), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2tuple) whereas Stochastic/other tuples can have 1 or 2 basis labels depending on the parameterization type. Tuples with 1 basis label indicate a stochastic (diagonal Lindblad) term, and are the only type of terms allowed when a parmeterization with nonham_mode != “all” is selected. “S” terms with 2 basis specify “offdiagonal” nonHamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients.
parameterization (str or LindbladParameterization) – Determines the parameterization of the LindbladErrorgen objects used to represent this noise. When “auto” (the default), the parameterization is inferred from the types of error generators specified in the error_coeffs dictionary. When not “auto”, the parameterization type is passed through to created
LindbladErrorgen
objects.
 classmethod from_basis_coefficients(cls, parameterization, lindblad_basis, state_space, ham_coefficients=None, nonham_coefficients=None)¶
Create a
LindbladNoise
object containing a complete basis of elementary terms.This method provides a convenient way to create a lindblad noise specification containing the complete set of terms in a Lindbladian based on a given “Lindblad basis” (often just a Pauli product basis). This routine by default creates all the terms with zero coefficients, but coefficient vectors or matrices (usually obtained by projecting an arbitrary error generator onto the lindblad basis) can be specified via the ham_coefficients and nonham_coefficients arguments.
 Parameters
parameterization (str or LindbladParameterization) – The Lindblad parameterization, specifying what constitutes the “complete” set of Lindblad terms. For example, “H” means that just Hamiltonian terms are included whereas “CPTP” includes all the terms in a standard Lindblad decomposition.
lindblad_basis (str or Basis) – The basis used to construct the Lindblad terms.
state_space (StateSpace) – The state space, used only to convert stringvalued lindblad_basis names into a
Basis
object. If lindblad_basis is given as aBasis
, then this can be set to None.ham_coefficients (numpy.ndarray or None, optional) – A 1dimensional array of coefficients giving the initial values of the Hamiltonianterm coefficients. The length of this arrays should be one less than the size of lindblad_basis (since there’s no Lindblad term for the identity element).
nonham_coefficients (numpy.ndarray or None, optional) – A 1 or 2dimensional array of coefficients for the “other” (nonHamiltonian) terms. The shape of this array should be (d,), (2,d), or (d,d) depending on parameterization (e.g. for S, S+A, and CPTP parameterizations).
 Returns
LindbladNoise
 create_errorgen(self, evotype, state_space)¶
Create an error generator for this noise operation.
 Parameters
evotype (str or Evotype) – The evolution type for the returned operator.
state_space (StateSpace) – The state space for the returned operator.
 Returns
LinearOperator
 create_errormap(self, evotype, state_space)¶
Create an error map (operator or superoperator) for this noise operation.
 Parameters
evotype (str or Evotype) – The evolution type for the returned operator.
state_space (StateSpace) – The state space for the returned operator.
 Returns
LinearOperator
 class pygsti.models._StochasticNoise(error_probs, parameterization='stochastic')¶
Bases:
OpNoise
Pauli stochastic noise.
 Parameters
error_probs (tuple) – The Paulistochastic rates for each of the nontrivial Paulis (a 3tuple is expected for a 1Q gate and a 15tuple for a 2Q gate).
parameterization ({"stochastic", or "lindblad"}) – Determines whether a
StochasticNoiseOp
orLindbladErrorgen
is used to represent the stochastic noise, respectively. When “stochastic”, elements of error_probs are used as coefficients in a linear combination of stochastic channels (the default). When “lindblad”, the elements of error_probs are coefficients of stochastic error generators (which are exponentiated to form a LindbladErrorgen with “cptp” nonHammiltonian parameterization).
 create_errorgen(self, evotype, state_space)¶
Create an error generator for this noise operation.
 Parameters
evotype (str or Evotype) – The evolution type for the returned operator.
state_space (StateSpace) – The state space for the returned operator.
 Returns
LinearOperator
 create_errormap(self, evotype, state_space)¶
Create an error map (operator or superoperator) for this noise operation.
 Parameters
evotype (str or Evotype) – The evolution type for the returned operator.
state_space (StateSpace) – The state space for the returned operator.
 Returns
LinearOperator
 class pygsti.models._DepolarizationNoise(depolarization_rate, parameterization='depolarize')¶
Bases:
OpNoise
Depolarization noise.
 Parameters
depolarization_rate (float) – The uniform depolarization strength.
parameterization ({"depolarize", "stochastic", or "lindblad"}) – Determines whether a
DepolarizeOp
,StochasticNoiseOp
, orLindbladErrorgen
is used to represent 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).
 create_errorgen(self, evotype, state_space)¶
Create an error generator for this noise operation.
 Parameters
evotype (str or Evotype) – The evolution type for the returned operator.
state_space (StateSpace) – The state space for the returned operator.
 Returns
LinearOperator
 create_errormap(self, evotype, state_space)¶
Create an error map (operator or superoperator) for this noise operation.
 Parameters
evotype (str or Evotype) – The evolution type for the returned operator.
state_space (StateSpace) – The state space for the returned operator.
 Returns
LinearOperator
 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 nqubit 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
num_qubits (int) – The total number of qubits.
gatedict (dict) – 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 qubits (determined by their dimension/shape) then they are repeatedly embedded into num_qubitsqubit gates as specified by availability. While the keys of this dictionary are usually stringtype gate names, labels that include target qubits, 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 qubits (e.g. “Gx”). Furthermore,OpFactory
objects may be used in place of LinearOperator objects to allow the evaluation of labels with arguments.prep_layers (None or operator or dict or list) – The state preparateion operations as nqubit 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_layers (None or operator or dict or list) – The state preparateion operations as nqubit 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”.availability (dict, optional) –
A dictionary whose keys are the same gate names as in gatedict and whose values are lists of qubitlabeltuples. Each qubitlabeltuple must have length equal to the number of qubits the corresponding gate acts upon, and causes that gate to be embedded to act on the specified qubits. For example, { ‘Gx’: [(0,),(1,),(2,)], ‘Gcnot’: [(0,1),(1,2)] } would cause the 1qubit `’Gx’gate to be embedded three times, acting on qubits 0, 1, and 2, and the 2qubit ‘Gcnot’gate to be embedded twice, acting on qubits 0 & 1 and 1 & 2. Instead of a list of tuples, values of availability may take the special values:
”allpermutations” and “allcombinations” equate to all possible
permutations and combinations of the appropriate number of qubit labels (deterined by the gate’s dimension).  “alledges” equates to all the vertices, for 1Q gates, and all the edges, for 2Q gates of the geometry.  “arbitrary” or “*” means that the corresponding gate can be placed on any target qubits via an
EmbeddingOpFactory
(uses less memory but slower than “allpermutations”.If a gate name (a key of gatedict) is not present in availability, the default is “alledges”.
qubit_labels (tuple, optional) – The circuitline labels for each of the qubits, which can be integers and/or strings. Must be of length num_qubits. If None, then the integers from 0 to num_qubits1 are used.
geometry ({"line","ring","grid","torus"} or QubitGraph) – The type of connectivity among the qubits, specifying a graph used to define neighbor relationships. Alternatively, a
QubitGraph
object with node labels equal to qubit_labels may be passed directly.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.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) –
The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`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_matrixop_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_matrixstate_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_gates (bool, 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 qubits may have different local noise, and so the operation_bks[‘gates’] dictionary contains a key for each gate
available gate placement.
ensure_composed_gates (bool, 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.global_idle (LinearOperator, optional) – A global idle operation, which is performed once at the beginning of every circuit layer. If None, no such operation is performed. If a 1qubit operator is given and num_qubits > 1 the global idle is the parallel application of this operator on each qubit line. Otherwise the given operator must act on all num_qubits qubits.
 create_processor_spec(self)¶
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 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 nqubit model using a lowweight and geometrically local error model with a common “global idle” operation.
 Parameters
num_qubits (int) – The number of qubits
gatedict (dict) – A dictionary (an OrderedDict if you care about insertion order) that associates with stringtype gate names (e.g. “Gx”)
LinearOperator
, numpy.ndarray, orOpFactory
objects. When the objects may act on fewer than the total number of qubits (determined by their dimension/shape) then they are repeatedly embedded into num_qubitsqubit gates as specified by their availability. These operations represent the ideal target operations, and thus, any LinearOperator or OpFactory objects must be static, i.e., have zero parameters.availability (dict, optional) –
A dictionary whose keys are the same gate names as in gatedict and whose values are lists of qubitlabeltuples. Each qubitlabeltuple must have length equal to the number of qubits the corresponding gate acts upon, and causes that gate to be embedded to act on the specified qubits. For example, { ‘Gx’: [(0,),(1,),(2,)], ‘Gcnot’: [(0,1),(1,2)] } would cause the 1qubit `’Gx’gate to be embedded three times, acting on qubits 0, 1, and 2, and the 2qubit ‘Gcnot’gate to be embedded twice, acting on qubits 0 & 1 and 1 & 2. Instead of a list of tuples, values of availability may take the special values:
”allpermutations” and “allcombinations” equate to all possible
permutations and combinations of the appropriate number of qubit labels (deterined by the gate’s dimension).  “alledges” equates to all the vertices, for 1Q gates, and all the edges, for 2Q gates of the geometry.  “arbitrary” or “*” means that the corresponding gate can be placed on any target qubits via an
EmbeddingOpFactory
(uses less memory but slower than “allpermutations”.If a gate name (a key of gatedict) is not present in availability, the default is “alledges”.
qubit_labels (tuple, optional) – The circuitline labels for each of the qubits, which can be integers and/or strings. Must be of length num_qubits. If None, then the integers from 0 to num_qubits1 are used.
geometry ({"line","ring","grid","torus"} or QubitGraph) – The type of connectivity among the qubits, specifying a graph used to define neighbor relationships. Alternatively, a
QubitGraph
object with node labels equal to qubit_labels may be passed directly.global_idle_layer (LinearOperator) – A global idle operation which acts on all the qubits and is, if add_idle_noise_to_all_gates=True, composed with the actions of specific gates to form the layer operation of any circuit layer.
prep_layers (None or operator or dict or list, optional) – The SPAM operations as nqubit 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.
povm_layers (None or operator or dict or list, optional) – The SPAM operations as nqubit 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_fn (function, optional) – A function which takes a single
Label
as an argument and returns the cloudnoise 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_fn (function, 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 qubits 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 layerlabels correspond to the same cloud  e.g. the cloudkey for (“Gx”,2) and (“Gy”,2) might be the same and could be processed together when selecing sequences that amplify the parameters in the cloudnoise operations for these two labels. The return value should be something hashable with the property that two noise which act on the same qubits should have the same cloud key.simulator (ForwardSimulator or {"auto", "matrix", "map"}) –
The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`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_matrixop_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_matrixstate_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+).
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.
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 layerlabel) of cloud noise contributions, i.e. a map that acts as the product of exponentiated errorgenerator 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 cloudnoise error generators, i.e. a map that acts as the exponentiated sum of error generators (ordering is irrelevant in this case).
add_idle_noise_to_all_gates (bool, optional) – Whether the global idle should be added as a factor following the ideal action of each of the nonidle gates.
verbosity (int, optional) – An integer >= 0 dictating how must output to send to stdout.
 create_processor_spec(self)¶
 property clouds(self)¶
Returns the set of cloudsets used when creating sequences which amplify the parameters of this model.
 Returns
dict
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 class pygsti.models._Basis(name, longname, real, sparse)¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
An ordered set of labeled matrices/vectors.
The base class for basis objects. A basis in pyGSTi is an abstract notion of a set of labeled elements, or “vectors”. Each basis has a certain size, and has .elements, .labels, and .ellookup members, the latter being a dictionary mapping of labels to elements.
An important point to note that isn’t immediately intuitive is that while Basis object holds elements (in its .elements property) these are not the same as its vectors (given by the object’s vector_elements property). Often times, in what we term a “simple” basis, the you just flatten an element to get the corresponding vectorelement. This works for bases where the elements are either vectors (where flattening does nothing) and matrices. By storing elements as distinct from vector_elements, the Basis can capture additional structure of the elements (such as viewing them as matrices) that can be helpful for their display and interpretation. The elements are also sometimes referred to as the “natural elements” because they represent how to display the element in a natrual way. A nonsimple basis occurs when vector_elements need to be stored as elements in a larger “embedded” way so that these elements can be displayed and interpeted naturally.
A second important note is that there is assumed to be some underlying “standard” basis underneath all the bases in pyGSTi. The elements in a Basis are always written in this standard basis. In the case of the “std”named basis in pyGSTi, these elements are just the trivial vector or matrix units, so one can rightly view the “std” pyGSTi basis as the “standard” basis for a that particular dimension.
The arguments below describe the basic properties of all basis objects in pyGSTi. It is important to remember that the vector_elements of a basis are different from its elements (see the
Basis
docstring), and that dim refers to the vector elements whereas elshape refers to the elements.For example, consider a 2element Basis containing the I and X Pauli matrices. The size of this basis is 2, as there are two elements (and two vector elements). Since vector elements are the length4 flattened Pauli matrices, the dimension (dim) is 4. Since the elements are 2x2 Pauli matrices, the elshape is (2,2).
As another example consider a basis which spans all the diagonal 2x2 matrices. The elements of this basis are the two matrix units with a 1 in the (0,0) or (1,1) location. The vector elements, however, are the length2 [1,0] and [0,1] vectors obtained by extracting just the diagonal entries from each basis element. Thus, for this basis, size=2, dim=2, and elshape=(2,2)  so the dimension is not just the product of elshape entries (equivalently, elsize).
 Parameters
name (string) – The name of the basis. This can be anything, but is usually short and abbreviated. There are several types of bases built into pyGSTi that can be constructed by this name.
longname (string) – A more descriptive name for the basis.
real (bool) – Elements and vector elements are always allowed to have complex entries. This argument indicates whether the coefficients in the expression of an arbitrary vector in this basis must be real. For example, if real=True, then when pyGSTi transforms a vector in some other basis to a vector in this basis, it will demand that the values of that vector (i.e. the coefficients which multiply this basis’s elements to obtain a vector in the “standard” basis) are real.
sparse (bool) – Whether the elements of .elements for this Basis are stored (when they are stored at all) as sparse matrices or vectors.
 dim¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 Type
int
 size¶
The number of elements (or vectorelements) in the basis.
 Type
int
 elshape¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 Type
int
 elndim¶
The number of element dimensions, i.e. len(self.elshape)
 Type
int
 elsize¶
The total element size, i.e. product(self.elshape)
 Type
int
 vector_elements¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Type
list
 classmethod cast(cls, name_or_basis_or_matrices, dim=None, sparse=None, classical_name='cl')¶
Convert various things that can describe a basis into a Basis object.
 Parameters
name_or_basis_or_matrices (various) –
Can take on a variety of values to produce different types of bases:
None: an empty ExpicitBasis
Basis: checked with dim and sparse and passed through.
str: BuiltinBasis or DirectSumBasis with the given name.
 list: an ExplicitBasis if given matrices/vectors or a
DirectSumBasis if given a (name, dim) pairs.
dim (int or StateSpace, optional) – The dimension of the basis to create. Sometimes this can be inferred based on name_or_basis_or_matrices, other times it must be supplied. This is the dimension of the space that this basis fully or partially spans. This is equal to the number of basis elements in a “full” (ordinary) basis. When a StateSpace object is given, a more detailed directsumoftensorproductblocks structure for the state space (rather than a single dimension) is described, and a basis is produced for this space. For instance, a DirectSumBasis basis of TensorProdBasis components can result when there are multiple tensorproduct blocks and these blocks consist of multiple factors.
sparse (bool, optional) – Whether the resulting basis should be “sparse”, meaning that its elements will be sparse rather than dense matrices.
classical_name (str, optional) – An alternate builtin basis name that should be used when constructing the bases for the classical sectors of dim, when dim is a StateSpace object.
 Returns
Basis
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 property elndim(self)¶
The number of element dimensions, i.e. len(self.elshape)
 Returns
int
 property elsize(self)¶
The total element size, i.e. product(self.elshape)
 Returns
int
 is_simple(self)¶
Whether the flattenedelement vector space is the same space as the space this basis’s vectors belong to.
 Returns
bool
 is_complete(self)¶
Whether this is a complete basis, i.e. this basis’s vectors span the entire space that they live in.
 Returns
bool
 is_partial(self)¶
The negative of :method:`is_complete`, effectively “is_incomplete”.
 Returns
bool
 property vector_elements(self)¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Returns
list – A list of 1D arrays.
 copy(self)¶
Make a copy of this Basis object.
 Returns
Basis
 with_sparsity(self, desired_sparsity)¶
Returns either this basis or a copy of it with the desired sparsity.
If this basis has the desired sparsity it is simply returned. If not, this basis is copied to one that does.
 Parameters
desired_sparsity (bool) – The sparsity (True for sparse elements, False for dense elements) that is desired.
 Returns
Basis
 abstract _copy_with_toggled_sparsity(self)¶
 __str__(self)¶
Return str(self).
 __getitem__(self, index)¶
 __len__(self)¶
 __eq__(self, other)¶
Return self==value.
 create_transform_matrix(self, to_basis)¶
Get the matrix that transforms a vector from this basis to to_basis.
 Parameters
to_basis (Basis or string) – The basis to transform to or a builtin basis name. In the latter case, a basis to transform to is built with the same structure as this basis but with all components constructed from the given name.
 Returns
numpy.ndarray (even if basis is sparse)
 reverse_transform_matrix(self, from_basis)¶
Get the matrix that transforms a vector from from_basis to this basis.
The reverse of :method:`create_transform_matrix`.
 Parameters
from_basis (Basis or string) – The basis to transform from or a builtin basis name. In the latter case, a basis to transform from is built with the same structure as this basis but with all components constructed from the given name.
 Returns
numpy.ndarray (even if basis is sparse)
 is_normalized(self)¶
Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.
Available only to bases whose elements are matrices for now.
 Returns
bool
 property to_std_transform_matrix(self)¶
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.
 Returns
numpy array or scipy.sparse.lil_matrix – An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
 property from_std_transform_matrix(self)¶
Retrieve the matrix that transforms vectors from the standard basis to this basis.
 Returns
numpy array or scipy sparse matrix – An array of shape (size, dim) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
 property to_elementstd_transform_matrix(self)¶
Get transformation matrix from this basis to the “element space”.
Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space”  that is, vectors in the same standard basis that the elements of this basis are expressed in.
 Returns
numpy array – An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
 property from_elementstd_transform_matrix(self)¶
Get transformation matrix from “element space” to this basis.
Get the matrix that transforms vectors in the “element space”  that is, vectors in the same standard basis that the elements of this basis are expressed in  to vectors in this basis (with length equal to the dim of this basis).
 Returns
numpy array – An array of shape (size, element_dim) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
 create_equivalent(self, builtin_basis_name)¶
Create an equivalent basis with components of type builtin_basis_name.
Create a
Basis
that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name. Parameters
builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.
 Returns
Basis
 create_simple_equivalent(self, builtin_basis_name=None)¶
Create a basis of type builtin_basis_name whose elements are compatible with this basis.
Create a simple basis and one without components (e.g. a
TensorProdBasis
, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_nameanalogue of the standard basis that this basis’s elements are expressed in. Parameters
builtin_basis_name (str, optional) – The name of the builtin basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and componentfree version of the same builtinbasis type.
 Returns
Basis
 is_compatible_with_state_space(self, state_space)¶
Checks whether this basis is compatible with a given state space.
 Parameters
state_space (StateSpace) – the state space to check.
 Returns
bool
 class pygsti.models._ExplicitBasis(elements, labels=None, name=None, longname=None, real=False, sparse=None)¶
Bases:
Basis
A Basis whose elements are specified directly.
All explicit bases are simple: their vector space is always taken to be that of the the flattened elements.
 Parameters
elements (numpy.ndarray) – The basis elements (sometimes different from the vectors)
labels (list) – The basis labels
name (str, optional) – The name of this basis. If None, then a name will be automatically generated.
longname (str, optional) – A more descriptive name for this basis. If None, then the short name will be used.
real (bool, optional) – Whether the coefficients in the expression of an arbitrary vector as a linear combination of this basis’s elements must be real.
sparse (bool, optional) – Whether the elements of this Basis are stored as sparse matrices or vectors. If None, then this is automatically determined by the type of the initial object: elements[0] (sparse=False is used when len(elements) == 0).
 Count¶
The number of custom bases, used for serialized naming
 Type
int
 Count = 0¶
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 _copy_with_toggled_sparsity(self)¶
 __hash__(self)¶
Return hash(self).
 class pygsti.models._DirectSumBasis(component_bases, name=None, longname=None)¶
Bases:
LazyBasis
A basis that is the direct sum of one or more “component” bases.
Elements of this basis are the union of the basis elements on each component, each embedded into a common blockdiagonal structure where each component occupies its own block. Thus, when there is more than one component, a DirectSumBasis is not a simple basis because the size of its elements is larger than the size of its vector space (which corresponds to just the diagonal blocks of its elements).
 Parameters
component_bases (iterable) – A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to :function:`Basis.cast`, e.g. (‘pp’,4).
name (str, optional) – The name of this basis. If None, the names of the component bases joined with “+” is used.
longname (str, optional) – A longer description of this basis. If None, then a long name is automatically generated.
 vector_elements¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Type
list
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 property dim(self)¶
The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.
 property size(self)¶
The number of elements (or vectorelements) in the basis.
 property elshape(self)¶
The shape of each element. Typically either a length1 or length2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).
 __hash__(self)¶
Return hash(self).
 _lazy_build_vector_elements(self)¶
 _lazy_build_elements(self)¶
 _lazy_build_labels(self)¶
 _copy_with_toggled_sparsity(self)¶
 __eq__(self, other)¶
Return self==value.
 property vector_elements(self)¶
The “vectors” of this basis, always 1D (sparse or dense) arrays.
 Returns
list
 property to_std_transform_matrix(self)¶
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.
 Returns
numpy array or scipy.sparse.lil_matrix – An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).
 property to_elementstd_transform_matrix(self)¶
Get transformation matrix from this basis to the “element space”.
Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space”  that is, vectors in the same standard basis that the elements of this basis are expressed in.
 Returns
numpy array – An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).
 create_equivalent(self, builtin_basis_name)¶
Create an equivalent basis with components of type builtin_basis_name.
Create a Basis that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name.
 Parameters
builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.
 Returns
DirectSumBasis
 create_simple_equivalent(self, builtin_basis_name=None)¶
Create a basis of type builtin_basis_name whose elements are compatible with this basis.
Create a simple basis and one without components (e.g. a
TensorProdBasis
, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_nameanalogue of the standard basis that this basis’s elements are expressed in. Parameters
builtin_basis_name (str, optional) – The name of the builtin basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and componentfree version of the same builtinbasis type.
 Returns
Basis
 class pygsti.models._QubitGraph(qubit_labels, initial_connectivity=None, initial_edges=None, directed=True, direction_names=None)¶
Bases:
pygsti.baseobjs.nicelyserializable.NicelySerializable
A directed or undirected graph data structure used to represent geometrical layouts of qubits or qubit gates.
Qubits are nodes in the graph (and can be labeled), and edges represent the ability to perform one or more types of gates between qubits (equivalent, usually, to geometrical proximity).
 Parameters
qubit_labels (list) – A list of string or integer labels of the qubits. The length of this list equals the number of qubits (nodes) in the graph.
initial_connectivity (numpy.ndarray, optional) – A (nqubits, nqubits) boolean or integer array giving the initial connectivity of the graph. If an integer array, then 0 indicates no edge and positive integers indicate present edges in the “direction” given by the positive integer. For example 1 may corresond to “left” and 2 to “right”. Names must be associated with these directions using direction_names. If a boolean array, if there’s an edge from qubit i to j then initial_connectivity[i,j]=True (integer indices of qubit labels are given by their position in qubit_labels). When directed=False, only the upper triangle is used.
initial_edges (list) – A list of (qubit_label1, qubit_label2) 2tuples or (qubit_label1, qubit_label2, direction) 3tuples specifying which edges are initially present. direction can either be a positive integer, similar to those used in initial_connectivity (in which case direction_names must be specified) or a string labeling the direction, e.g. “left”.
directed (bool, optional) – Whether the graph is directed or undirected. Directions can only be used when directed=True.
direction_names (iterable, optional) – A list (or tuple, etc) of stringvalued direction names such as “left” or “right”. These strings label the directions referenced by index in either initial_connectivity or initial_edges, and this argument is required whenever such indices are used.
 classmethod common_graph(cls, num_qubits=0, geometry='line', directed=True, qubit_labels=None, all_directions=False)¶
Create a QubitGraph that is one of several standard types of graphs.
 Parameters
num_qubits (int, optional) – The number of qubits (nodes in the graph).
geometry ({"line","ring","grid","torus"}) – The type of graph. What these correspond to should be selfevident.
directed (bool, optional) – Whether the graph is directed or undirected.
qubit_labels (iterable, optional) – The labels for the qubits. Must be of length num_qubits. If None, then the integers from 0 to num_qubits1 are used.
all_directions (bool, optional) – Whether to include edges with all directions. Typically it only makes sense to set this to True when directed=True also.
 Returns
QubitGraph
 map_qubit_labels(self, mapper)¶
Creates a new QubitGraph whose qubit (node) labels are updated according to the mapping function mapper.
 Parameters
mapper (dict or function) – A dictionary whose keys are the existing self.node_names values and whose value are the new labels, or a function which takes a single (existing qubitlabel) argument and returns a new qubit label.
 Returns
QubitProcessorSpec
 _to_nice_serialization(self)¶
 classmethod _from_nice_serialization(cls, state)¶
 copy(self)¶
Make a copy of this graph.
 Returns
QubitGraph
 _refresh_dists_and_predecessors(self)¶
 __getitem__(self, key)¶
 __setitem__(self, key, val)¶
 __len__(self)¶
 property node_names(self)¶
All the node labels of this graph.
These correpond to integer indices where appropriate, e.g. for :method:`shortest_path_distance_matrix`.
 Returns
tuple
 add_edges(self, edges)¶
Add edges (list of tuple pairs) to graph.
 Parameters
edges (list) – A list of (qubit_label1, qubit_label2) 2tuples.
 Returns
None
 add_edge(self, node1, node2, direction=None)¶
Add an edge between the qubits labeled by node1 and node2.
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
direction (str or int, optional) – Either a direction name or a direction indicex
 Returns
None
 remove_edge(self, node1, node2)¶
Add an edge between the qubits labeled by node1 and node2.
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
 Returns
None
 edges(self, double_for_undirected=False, include_directions=False)¶
Get a list of the edges in this graph as 2tuples of node/qubit labels).
When undirected, the index of the 2tuple’s first label will always be less than its second unless double_for_undirected == True, in which case both directed edges are included. The edges are sorted (by label index) in ascending order.
 Parameters
double_for_undirected (bool, optional) – Whether, for the case of an undirected graph, two 2tuples, giving both edge directions, should be included in the returned list.
include_directions (bool, optional) – Whether to include direction labels. If True and directions are present, a list of (node1, node2, direction_name) 3tuples is returned instead of the usual (node1, node2) 2tuples.
 Returns
list
 radius(self, base_nodes, max_hops)¶
Find all the nodes reachable in max_hops from any node in base_nodes.
Get a (sorted) array of node labels that can be reached from traversing at most max_hops edges starting from a node (vertex) in base_nodes.
 Parameters
base_nodes (iterable) – A list of node/qubit labels giving the possible starting locations.
max_hops (int) – The maximum number of hops (see above).
 Returns
list – A list of the node labels reachable from base_nodes in at most max_hops edge traversals.
 connected_combos(self, possible_nodes, size)¶
Computes the number of different connected subsets of possible_nodes containing size nodes.
 Parameters
possible_nodes (list) – A list of node (qubit) labels.
size (int) – The size of the connected subsets being sought (counted).
 Returns
int
 _indices_connected(self, i, j)¶
Whether nodes indexed by i and j are directly connected
 is_connected(self, node1, node2)¶
Is node1 connected to node2 (does there exist a path of any length between them?)
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
 Returns
bool
 has_edge(self, edge)¶
Is edge an edge in this graph.
Note that if this graph is undirected, either node order in edge will return True.
 Parameters
edge (tuple) – (node1,node2) tuple specifying the edge.
 Returns
bool
 is_directly_connected(self, node1, node2)¶
Is node1 directly connected to node2 (does there exist an edge between them?)
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
 Returns
bool
 _is_connected_subgraph(self, node_indices)¶
Whether the nodes indexed by the elements of node_indices form a connected subgraph.
 is_connected_graph(self)¶
Computes whether this graph is connected (there exist paths between every pair of nodes).
 Returns
bool
 is_connected_subgraph(self, nodes)¶
Do a give set of nodes form a connected subgraph?
That is, does there exist a path from every node in nodes to every other node in nodes using only the edges between the nodes in nodes.
 Parameters
nodes (list) – A list of node (qubit) labels.
 Returns
bool
 _brute_get_all_connected_sets(self, n)¶
Computes all connected sets of n qubits using a bruteforce approach.
Note that for a large device with this will be often be an unreasonably large number of sets of qubits, and so the runtime of this method will be unreasonable.
 Parameters
n (int) – The number of qubits within each set.
 Returns
list – All sets of n connected qubits.
 find_all_connected_sets(self)¶
Finds all subgraphs (connected sets of vertices) up to the full graph size.
Graph edges are treated as undirected.
 Returns
dict – A dictionary with integer keys. The value of key k is a list of all the subgraphs of length k. A subgraph is given as a tuple of sorted vertex labels.
 shortest_path(self, node1, node2)¶
Get the shortest path between two nodes (qubits).
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
 Returns
list – A list of the node labels to traverse.
 shortest_path_edges(self, node1, node2)¶
Like :method:`shortest_path`, but returns a list of (nodeA,nodeB) tuples.
These tuples define a path from node1 to node2, so the first tuple’s nodeA == node1 and the final tuple’s nodeB == node2.
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
 Returns
list – A list of the edges (2tuples of node labels) to traverse.
 shortest_path_intersect(self, node1, node2, nodes_to_intersect)¶
Check whether the shortest path between node1 and node2 contains any of the nodes in nodes_to_intersect.
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
nodes_to_intersect (list) – A list of node labels.
 Returns
bool – True if the shortest path intersects any node in nodeToIntersect.
 shortest_path_distance(self, node1, node2)¶
Get the distance of the shortest path between node1 and node2.
 Parameters
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
 Returns
int
 shortest_path_distance_matrix(self)¶
Returns a matrix of shortest path distances.
This matrix is indexed by the integerindex of each node label (as specified to __init__). The list of indexordered node labels is given by :method:`node_names`.
 Returns
numpy.ndarray – A boolean array of shape (n,n) where n is the number of nodes in this graph.
 shortest_path_predecessor_matrix(self)¶
Returns a matrix of predecessors used to construct the shortest path between two nodes.
This matrix is indexed by the integerindex of each node label (as specified to __init__). The list of indexordered node labels is given by :method:`node_names`.
 Returns
numpy.ndarray – A boolean array of shape (n,n) where n is the number of nodes in this graph.
 subgraph(self, nodes_to_keep, reset_nodes=False)¶
Return a graph that includes only nodes_to_keep and the edges between them.
 Parameters
nodes_to_keep (list) – A list of node labels defining the subgraph to return.
reset_nodes (bool, optional) – If True, nodes of returned subgraph are relabelled to be the integers starting at 0 (in 11 correspondence with the ordering in nodes_to_keep).
 Returns
QubitGraph
 resolve_relative_nodelabel(self, relative_nodelabel, target_labels)¶
Resolve a “relative nodelabel” into an actual node in this graph.
Relative node labels can use “@” to index elements of target_labels and can contain “+<dir>” directives to move along directions defined in this graph.
 Parameters
relative_nodelabel (int or str) – An absolute or relative nodelabel. For example: 0, “@0”, “@0+right”, “@1+left+up”
target_labels (list or tuple) – A list of (absolute) node labels present in this graph that may be referred to using the “@” syntax within relative_nodelabel.
 Returns
int or str
 move_in_directions(self, start_node, directions)¶
The node you end up on after moving in directions from start_node.
 Parameters
start_node (str or int) – Qubit (node) label.
directions (iterable) – A sequence of direction names.
 Returns
str or int or None – The ending node label or None if the directions were invalid.
 move_in_direction(self, start_node, direction)¶
Get the node that is one step in direction of start_node.
 Parameters
start_node (int or str) – the starting point (a node label of this graph)
direction (str or int) – the name of a direction or its index within this graphs .directions member.
 Returns
str or int or None – the node in the given direction or None if there is no node in that direction (e.g. if you reach the end of a chain).
 __str__(self)¶
Return str(self).
 pygsti.models.sqrt2¶
 pygsti.models.id2x2¶
 pygsti.models.sigmax¶
 pygsti.models.sigmay¶
 pygsti.models.sigmaz¶
 class pygsti.models._VerbosityPrinter(verbosity=1, filename=None, comm=None, warnings=True, split=False, clear_file=True)¶
Bases:
object
Class responsible for logging things to stdout or a file.
Controls verbosity and can print progress bars. ex:
>>> VerbosityPrinter(1)
would construct a printer that printed out messages of level one or higher to the screen.
>>> VerbosityPrinter(3, 'output.txt')
would construct a printer that sends verbose output to a text file
The static function
create_printer()
will construct a printer from either an integer or an already existing printer. it is a static method of the VerbosityPrinter class, so it is called like so:>>> VerbosityPrinter.create_printer(2)
or
>>> VerbostityPrinter.create_printer(VerbosityPrinter(3, 'output.txt'))
printer.log('status')
would log ‘status’ if the printers verbosity was one or higher.printer.log('status2', 2)
would log ‘status2’ if the printer’s verbosity was two or higherprinter.error('something terrible happened')
would ALWAYS log ‘something terrible happened’.printer.warning('something worrisome happened')
would log if verbosity was one or higher  the same as a normal status.Both printer.error and printer.warning will prepend ‘ERROR: ‘ or ‘WARNING: ‘ to the message they are given. Optionally, printer.log() can also prepend ‘Status_n’ to the message, where n is the message level.
Logging of progress bars/iterations:
>>> with printer_instance.progress_logging(verbosity): >>> for i, item in enumerate(data): >>> printer.show_progress(i, len(data)) >>> printer.log(...)
will output either a progress bar or iteration statuses depending on the printer’s verbosity
 Parameters
verbosity (int) – How verbose the printer should be.
filename (str, optional) – Where to put output (If none, output goes to screen)
comm (mpi4py.MPI.Comm or ResourceAllocation, optional) – Restricts output if the program is running in parallel (By default, if the rank is 0, output is sent to screen, and otherwise sent to commfiles 1, 2, …
warnings (bool, optional) – Whether or not to print warnings
split (bool, optional) – Whether to split output between stdout and stderr as appropriate, or to combine the streams so everything is sent to stdout.
clear_file (bool, optional) – Whether or not filename should be cleared (overwritten) or simply appended to.
 _comm_path¶
relative path where comm files (outputs of nonroot ranks) are stored.
 Type
str
 _comm_file_name¶
root filename for comm files (outputs of nonroot ranks).
 Type
str
 _comm_file_ext¶
filename extension for comm files (outputs of nonroot ranks).
 Type
str
 _comm_path =¶
 _comm_file_name =¶
 _comm_file_ext = .txt¶
 _create_file(self, filename)¶
 _get_comm_file(self, comm_id)¶
 clone(self)¶
Instead of deepcopy, initialize a new printer object and feed it some select deepcopied members
 Returns
VerbosityPrinter
 static create_printer(verbosity, comm=None)¶
Function for converting between interfaces
 Parameters
verbosity (int or VerbosityPrinter object, required:) – object to build a printer from
comm (mpi4py.MPI.Comm object, optional) – Comm object to build printers with. !Will override!
 Returns
VerbosityPrinter – The printer object, constructed from either an integer or another printer
 __add__(self, other)¶
Increase the verbosity of a VerbosityPrinter
 __sub__(self, other)¶
Decrease the verbosity of a VerbosityPrinter
 __getstate__(self)¶
 __setstate__(self, state_dict)¶
 _append_to(self, filename, message)¶
 _put(self, message, flush=True, stderr=False)¶
 _record(self, typ, level, message)¶
 error(self, message)¶
Log an error to the screen/file
 Parameters
message (str) – the error message
 Returns
None
 warning(self, message)¶
Log a warning to the screen/file if verbosity > 1
 Parameters
message (str) – the warning message
 Returns
None
 log(self, message, message_level=None, indent_char=' ', show_statustype=False, do_indent=True, indent_offset=0, end='\n', flush=True)¶
Log a status message to screen/file.
Determines whether the message should be printed based on current verbosity setting, then sends the message to the appropriate output
 Parameters
message (str) – the message to print (or log)
message_level (int, optional) – the minimum verbosity level at which this level is printed.
indent_char (str, optional) – what constitutes an “indent” (messages at higher levels are indented more when do_indent=True).
show_statustype (bool, optional) – if True, prepend lines with “Status Level X” indicating the message_level.
do_indent (bool, optional) – whether messages at higher message levels should be indented. Note that if this is False it may be helpful to set show_statustype=True.
indent_offset (int, optional) – an additional number of indentations to add, on top of any due to the message level.
end (str, optional) – the character (or string) to end message lines with.
flush (bool, optional) – whether stdout should be flushed right after this message is printed (this avoids delays in onscreen output due to buffering).
 Returns
None
 _progress_bar(self, iteration, total, bar_length, num_decimals, fill_char, empty_char, prefix, suffix, indent)¶
 _verbose_iteration(self, iteration, total, prefix, suffix, verbose_messages, indent, end)¶
 __str__(self)¶
Return str(self).
 verbosity_env(self, level)¶
Create a temporary environment with a different verbosity level.
This is context manager, controlled using Python’s with statement:
>>> with printer.verbosity_env(2): printer.log('Message1') # printed at verbosity level 2 printer.log('Message2') # printed at verbosity level 2
 Parameters
level (int) – the verbosity level of the environment.
 progress_logging(self, message_level=1)¶
Context manager for logging progress bars/iterations.
(The printer will return to its normal, unrestricted state when the progress logging has finished)
 Parameters
message_level (int, optional) – progress messages will not be shown until the verbosity level reaches message_level.
 show_progress(self, iteration, total, bar_length=50, num_decimals=2, fill_char='#', empty_char='', prefix='Progress:', suffix='', verbose_messages=[], indent_char=' ', end='\n')¶
Displays a progress message (to be used within a progress_logging block).
 Parameters
iteration (int) – the 0based current iteration – the interation number this message is for.
total (int) – the total number of iterations expected.
bar_length (int, optional) – the length, in characters, of a textformat progress bar (only used when the verbosity level is exactly equal to the progress_logging message level.
num_decimals (int, optional) – number of places after the decimal point that are displayed in progress bar’s percentage complete.
fill_char (str, optional) – replaces ‘#’ as the barfilling character
empty_char (str, optional) – replaces ‘’ as the emptybar character
prefix (str, optional) – message in front of the bar
suffix (str, optional) – message after the bar
verbose_messages (list, optional) – A list of strings to display after an initial “Iter X of Y” line when the verbosity level is higher than the progress_logging message level and so more verbose messages are shown (and a progress bar is not). The elements of verbose_messages will occur, one per line, after the initial “Iter X of Y” line.
indent_char (str, optional) – what constitutes an “indentation”.
end (str, optional) – the character (or string) to end message lines with.
 Returns
None
 _end_progress(self)¶
 start_recording(self)¶
Begins recording the output (to memory).
Begins recording (in memory) a list of (type, verbosityLevel, message) tuples that is returned by the next call to :method:`stop_recording`.
 Returns
None
 is_recording(self)¶
Returns whether this VerbosityPrinter is currently recording.
 Returns
bool
 stop_recording(self)¶
Stops recording and returns recorded output.
Stops a “recording” started by :method:`start_recording` and returns the list of (type, verbosityLevel, message) tuples that have been recorded since then.
 Returns
list
 pygsti.models._deprecated_fn(replacement=None)¶
Decorator for deprecating a function.
 Parameters
replacement (str, optional) – the name of the function that should replace it.
 Returns
function
 pygsti.models.create_spam_vector(vec_expr, state_space, basis)¶
Build a rho or E vector from an expression.
 Parameters
vec_expr (string) – 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 directsum decomposition of density matrix space.state_space (StateSpace) – The state space that the created operation should act upon.
basis (str or Basis) – The basis of the returned vector. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (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
basis (Basis object) – The basis of the returned vector. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (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_expr (string) –
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) = xrotation by theta radians of qubit labeled by ssl
Y(theta, ssl) = yrotation by theta radians of qubit labeled by ssl
Z(theta, ssl) = zrotation by theta radians of qubit labeled by ssl
CX(theta, ssl0, ssl1) = controlled xrotation by theta radians. Acts on qubit labeled by ssl1 with ssl0 being the control.
CY(theta, ssl0, ssl1) = controlled yrotation by theta radians. Acts on qubit labeled by ssl1 with ssl0 being the control.
CZ(theta, ssl0, ssl1) = controlled zrotation by theta radians. Acts on qubit labeled by ssl1 with ssl0 being the control.
CNOT(ssl0, ssl1) = standard controllednot gate. Acts on qubit labeled by ssl1 with ssl0 being the control.
CPHASE(ssl0, ssl1) = standard controlledphase 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 xrotation between states with integer indices i0 and i1 followed by complete decoherence between the states.
state_space (StateSpace) – The state space that the created operation should act upon.
basis (str 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.
evotype (Evotype 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, basis, op_labels, op_expressions, prep_labels=('rho0',), prep_expressions=('0',), effect_labels='standard', effect_expressions='standard', povm_labels='Mdefault', gate_type='full', prep_type='auto', povm_type='auto', instrument_type='auto', evotype='default')¶
Build a new Model given lists of operation labels and expressions.
 Parameters
state_space (StateSpace) – The state space for this model.
basis (Basis object) – The source and destination basis, respectively. Allowed values are Matrixunit (std), GellMann (gm), Pauliproduct (pp), and Qutrit (qt) (or a custom basis object).
op_labels (list 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_expressions (list 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_labels (list of string, optional) – A list of labels for each created state preparation in the final model. To conform with conventions these labels should begin with “rho”.
prep_expressions (list of strings, optional) – A list of vector expressions for each state preparation vector (see documentation for
_create_spam_vector()
).effect_labels (list, 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 lengthn 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 nonqubit cases.
effect_expressions (list, optional) – A list or listoflists 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_labels (list 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).
parameterization ({"full","TP","static"}, optional) – How to parameterize the gates of the resulting Model (see documentation for
create_operation()
).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.
 Returns
Model – The created model.
 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_space (StateSpace) – the state space for the model.
op_labels (list 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_expressions (list 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_labels (list 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_expressions (list of strings) – A list of vector expressions for each state preparation vector (see documentation for
_create_spam_vector()
).effect_labels (list, 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 lengthn 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 nonqubit cases.
effect_expressions (list, optional) – A list or listoflists 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_labels (list 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 GellMann matrices
”pp” = operation matrix operates on density mx expresses as sum of tensorproduct 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()
).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.
 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_primitives (Model) – A Model containing the “primitive” gates (those used to compose the gates of the returned model).
alias_dict (dictionary) – 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_explicit_model(processor_spec, modelnoise, custom_gates=None, evotype='default', simulator='auto', ideal_gate_type='auto', ideal_prep_type='auto', ideal_povm_type='auto', embed_gates=False, basis='pp')¶
 pygsti.models._create_spam_layers(processor_spec, modelnoise, local_noise, ideal_prep_type, ideal_povm_type, evotype, state_space, independent_gates, independent_spam)¶
local_noise=True creates lindblad ops that are embedded & composed 1Q ops, and assumes that modelnoise specifies 1Q noise. local_noise=False assumes modelnoise specifies nqubit noise
 pygsti.models._setup_local_gates(processor_spec, evotype, modelnoise=None, custom_gates=None, ideal_gate_type=('static standard', 'static clifford', 'static unitary'))¶
Construct a dictionary of potentially noisy gates that act only on their target qubits.
These gates are “local” because they act only on their intended target qubits. The gates consist of an ideal gate (obviously local, and crosstalk free) of the type given by ideal_gate_type composed with a noise operation given by modelnoise, if one exists. The returned dictionary contains keys for all the gate names in processor_spec. Custom gate objects can be given by custom_gates, which override the normal gate construction.
 Parameters
processor_spec (ProcessorSpec) – The processor to create gate operations for. This object specifies the gate names and unitaries for the processor, among other things.
evotype (Evotype) – Create gate objects with this evolution type.
modelnoise (ModelNoise, optional) – Noise that should be applied after the ideal gates. This noise must be local to each gate (i.e. acting on its target qubits). See the
ModelNoise
object documentation for details regarding how to specify different types of noise. If None, then no noise is added .custom_gates (dict, optional) – A dictionary of gate objects that should be placed in the returned dictionary in lieu of objects that would normally be constructed. Keys are gate names and values are gates.
ideal_gate_type (str 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).
 Returns
gatedict (dict) – A dictionary mapping gate names to local gate operations.
 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')¶
Create a nqubit “crosstalkfree” model.
By virtue of being crosstalkfree, this model’s operations only act nontrivially on their target qubits. 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_spec (ProcessorSpec) – 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_gates (dict, 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 stringtype gate names or labels that include target qubits.depolarization_strengths (dict, 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_probs (dict, optional) – A dictionary whose keys are gate names (e.g. “Gx”) and whose values are tuples that specify Paulistochastic rates for each of the nontrivial Paulis (so a 3tuple would be expected for a 1Q gate and a 15tuple for a 2Q gate).
lindblad_error_coeffs (dict, 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 2tuple) 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 “offdiagonal” nonHamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients.
depolarization_parameterization (str 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_parameterization (str 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.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
simulator (ForwardSimulator 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_gates (bool, 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 qubits may have different local noise, and so the operation_bks[‘gates’] dictionary contains a key for each gate
available gate placement.
ensure_composed_gates (bool, 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_type (str 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_type (str or tuple, optional) – Similar to ideal_gate_type but for SPAM elements (state preparations and POVMs).
implicit_idle_mode ({'none', 'add_global'}) – The way idel 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.
 Returns
LocalNoiseModel – A model with “rho0” prep, “Mdefault” POVM, and gates labeled by the gate names and qubit labels (as specified by processor_spec). For instance, the operation label for the “Gx” gate on the second qubit might be Label(“Gx”,1).
 pygsti.models._create_crosstalk_free_model(processor_spec, modelnoise, custom_gates=None, evotype='default', simulator='auto', on_construction_error='raise', independent_gates=False, independent_spam=True, ensure_composed_gates=False, ideal_gate_type='auto', ideal_prep_type='auto', ideal_povm_type='auto', implicit_idle_mode='none')¶
Create a nqubit “crosstalkfree” model.
Similar to :method:`create_crosstalk_free_model` but the noise is input more generally, as a
ModelNoise
object. Arguments are the same as this function except that modelnoise is given instead of several more specific noisedescribing arguments. Returns
LocalNoiseModel
 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', verbosity=0)¶
Create a nqubit “cloudcrosstalk” 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 qubits (not just a gate’s target qubits). Typically a gate’s errors are specified relative to the gate’s target qubits, forming a “cloud” of errors around the target qubits 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_spec (ProcessorSpec) – 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_gates (dict, 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 stringtype gate names or labels that include target qubits.depolarization_strengths (dict, 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_probs (dict, optional) – A dictionary whose keys are gate names (e.g. “Gx”) and whose values are tuples that specify Paulistochastic rates for each of the nontrivial Paulis (so a 3tuple would be expected for a 1Q gate and a 15tuple for a 2Q gate).
lindblad_error_coeffs (dict, 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 2tuple) 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 “offdiagonal” nonHamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients.
depolarization_parameterization (str 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_parameterization (str 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.
evotype (Evotype or str, optional) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.
simulator (ForwardSimulator 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_gates (bool, 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 qubits may have different local noise, and so the operation_bks[‘cloudnoise’] dictionary contains a key for each gate
available gate placement.
independent_spam (bool, 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'}) – The way idel 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.
verbosity (int or VerbosityPrinter, optional) – Amount of detail to print to stdout.
 Returns
CloudNoiseModel
 pygsti.models._create_cloud_crosstalk_model(processor_spec, modelnoise, custom_gates=None, evotype='default', simulator='auto', independent_gates=False, independent_spam=True, errcomp_type='errorgens', implicit_idle_mode='none', verbosity=0)¶
Create a nqubit “cloudcrosstalk” model.
Similar to :method:`create_cloud_crosstalk_model` but the noise is input more generally, as a
ModelNoise
object. Arguments are the same as this function except that modelnoise is given instead of several more specific noisedescribing arguments. 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, verbosity=0)¶
Create a “cloud crosstalk” model based on maximum error weights and hops along the processor’s qubit 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 nonidentity Paulis) and support (which qubits have nontrivial Paulis on them). Errors are taken to be approximately local, meaning they are concentrated near the target qubits of a gate, with the notion of locality taken from the processor specification’s qubit graph. The caller provides maximumweight, maximumhop (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 globalidlelike error following or preceding the preparation or measurement, respectively.
Gate errors are placed on all the qubits that can be reached with at most maxhops hops from (any of) the gate’s target qubits. Elementary error generators up to weight W, where W equals the number of target qubits (e.g., 2 for a CNOT gate) plus extra_gate_weight are allowed. Weight1 terms are a special case, and the extra_weight_1_hops argument adds to the usual maxhops in this case to allow weight1 errors on a possibly larger region of qubits around the target qubits.
 Parameters
processor_spec (ProcessorSpec) – 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_gates (dict) – A dictionary that associates with gate labels
LinearOperator
,OpFactory
, or numpy.ndarray objects. These objects describe the full action of the gate or primitivelayer 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 stringtype 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 finetune how this noise is parameterized, call theCloudNoiseModel
constructor directly.max_idle_weight (int, optional) – The maximumweight for errors on the global idle gate.
max_spam_weight (int, optional) – The maximumweight for state preparation and measurement (SPAM) errors.
maxhops (int) – 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 qubits and those reachable by hopping at most maxhops times from a target qubit along nearestneighbor links (defined by the geometry).
extra_weight_1_hops (int, optional) – Additional hops (adds to maxhops) for weight1 errors. A value > 0 can be useful for allowing just weight1 errors (of which there are relatively few) to be dispersed farther from a gate’s target qubits. For example, a crosstalkdetecting model might use this.
extra_gate_weight (int, optional) – Addtional weight, beyond the number of target qubits (taken as a “base weight”  i.e. weight 2 for a 2Q gate), allowed for gate errors. If this equals 1, for instance, then 1qubit gates can have up to weight2 errors and 2qubit gates can have up to weight3 errors.
simulator (ForwardSimulator or {"auto", "matrix", "map"}) – The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`bulk_probs`. Using “auto” selects “matrix” when there are 2 qubits or less, and otherwise selects “map”.
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.
gate_type (str, optional) – The Lindbladerror parameterization type used for gate operations. This may be expanded in the future, but currently the gate errors must be of the Lindblad errorgenerator coefficients type, and this argument specifies what elementary errorgenerator coefficients are initially allowed (and linked to model parameters), before maximumweight 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_type (str, optional) – Similar to gate_type but for SPAM elements (state preparations and POVMs). This specifies the Lindbladerror parameterization for the state prepearation and POVM.
implicit_idle_mode ({'none', 'add_global'}) – The way idel operations are added implicitly within the created model. “nonw” 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.
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 layerlabel) of cloud noise contributions, i.e. a map that acts as the product of exponentiated errorgenerator 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 cloudnoise error generators, i.e. a map that acts as the exponentiated sum of error generators (ordering is irrelevant in this case).
independent_gates (bool, optional) – Whether the noise added to a gate when it acts on one set of target qubits is independent of its noise on a different set of target qubits. 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 qubits (even though the target qubits and cloud are different). If True, then gate noise operations for different sets of target qubits are independent.
independent_spam (bool, 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 qubits must be the same, e.g., if the state preparation is a perfect preparation followed by a singlequbit rotation then this rotation must be by the same angle on all of the qubits.
connected_highweight_errors (bool, optional) – An additional constraint regarding highweight errors. When True, only high weight (weight 2+) elementary error generators whose nontrivial Paulis occupy a connected portion of the qubit graph are allowed. For example, if the qubit graph is a 1D chain of 4 qubits, 1234, and weight2 errors are allowed on a singlequbit gate with target = qubit2, then weight2 errors on 12 and 23 would be allowed, but errors on 13 would be forbidden. When False, no constraint is imposed.
verbosity (int or VerbosityPrinter, optional) – An integer >= 0 dictating how must output to send to stdout.
 Returns
CloudNoiseModel
 pygsti.models._iter_basis_inds(weight)¶
Iterate over product of weight nonidentity Pauli 1Q basis indices
 pygsti.models._pauli_product_matrix(sigma_inds)¶
Construct the Pauli product matrix from the given sigma_inds
 Parameters
sigma_inds (iterable) – A sequence of integers in the range [0,3] corresponding to the I, X, Y, Z Pauli basis matrices.
 Returns
numpy.ndarray or scipy.sparse.csr_matrix
 pygsti.models._construct_restricted_weight_pauli_basis(wt, sparse=False)¶
 pygsti.models._build_weight_maxhops_modelnoise(target_sslbls, weight_maxhops_tuples, lnd_parameterization, connected=True)¶
 pygsti.models._build_modelnoise_from_args(depolarization_strengths, stochastic_error_probs, lindblad_error_coeffs, depolarization_parameterization, stochastic_parameterization, lindblad_parameterization, allow_nonlocal)¶
 pygsti.models._nparams_xycnot_cloudnoise_model(num_qubits, geometry='line', max_idle_weight=1, maxhops=0, extra_weight_1_hops=0, extra_gate_weight=0, require_connected=False, independent_1q_gates=True, zz_only=False, bidirectional_cnots=True, verbosity=0)¶
Compute the number of parameters in a particular
CloudNoiseModel
.Returns the number of parameters in the
CloudNoiseModel
containing X(pi/2), Y(pi/2) and CNOT gates using the specified arguments without actually constructing the model (useful for considering parametercount scaling). Parameters
num_qubits (int) – The total number of qubits.
geometry ({"line","ring","grid","torus"} or QubitGraph) – The type of connectivity among the qubits, specifying a graph used to define neighbor relationships. Alternatively, a
QubitGraph
object may be passed directly.max_idle_weight (int, optional) – The maximumweight for errors on the global idle gate.
maxhops (int) – 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 qubits and those reachable by hopping at most maxhops times from a target qubit along nearestneighbor links (defined by the geometry).
extra_weight_1_hops (int, optional) – Additional hops (adds to maxhops) for weight1 errors. A value > 0 can be useful for allowing just weight1 errors (of which there are relatively few) to be dispersed farther from a gate’s target qubits. For example, a crosstalkdetecting model might use this.
extra_gate_weight (int, optional) – Addtional weight, beyond the number of target qubits (taken as a “base weight”  i.e. weight 2 for a 2Q gate), allowed for gate errors. If this equals 1, for instance, then 1qubit gates can have up to weight2 errors and 2qubit gates can have up to weight3 errors.
require_connected (bool, optional) – If True, then highweight errors only occur on connected (via geometry) qubits. For example in a line of qubits there would not be weight2 errors on qubits 1 and 3.
independent_1q_gates (bool, optional) – If True, 1Q gates on different qubits have separate (distinct) parameters. If False, the 1Q gates of each type (e.g. an pi/2 X gate) for different qubits share the same set of parameters.
zz_only (bool, optional) – If True, the only highweight errors allowed are of “Z^n” type.
bidirectional_cnots (bool) – Whether CNOT gates can be performed in either direction (and each direction should be treated as an indepedent gate)
verbosity (int, optional) – An integer >= 0 dictating how much output to send to stdout.
 Returns
int