pygsti.models.explicitmodel
¶
Defines the ExplicitOpModel class and supporting functionality.
Module Contents¶
Classes¶
Encapsulates a set of gate, state preparation, and POVM effect operations. 

Rule: layer must appear explicitly as a "primitive op" 
 class pygsti.models.explicitmodel.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.explicitmodel.ExplicitLayerRules¶
Bases:
pygsti.models.layerrules.LayerRules
Rule: layer must appear explicitly as a “primitive op”
 prep_layer_operator(self, model, layerlbl, caches)¶
Create the operator corresponding to layerlbl.
 Parameters
layerlbl (Label) – A circuit layer label.
 Returns
State