# `pygsti.tools.optools`

Utility functions operating on operation matrices

## Module Contents

### Functions

 `fidelity`(a, b) Returns the quantum state fidelity between density matrices. `frobeniusdist`(a, b) Returns the frobenius distance between arrays: ||a - b||_Fro. Returns the square of the frobenius distance between arrays: (||a - b||_Fro)^2. `residuals`(a, b) Calculate residuals between the elements of two matrices Compute the trace norm of matrix a given by: `tracedist`(a, b) Compute the trace distance between matrices. `diamonddist`(a, b[, mx_basis, return_x]) Returns the approximate diamond norm describing the difference between gate matrices. `jtracedist`(a, b[, mx_basis]) Compute the Jamiolkowski trace distance between operation matrices. `entanglement_fidelity`(a, b[, mx_basis, is_tp, is_unitary]) Returns the "entanglement" process fidelity between gate matrices. `average_gate_fidelity`(a, b[, mx_basis, is_tp, is_unitary]) Computes the average gate fidelity (AGF) between two gates. `average_gate_infidelity`(a, b[, mx_basis, is_tp, ...]) Computes the average gate infidelity (AGI) between two gates. `entanglement_infidelity`(a, b[, mx_basis, is_tp, ...]) Returns the entanglement infidelity (EI) between gate matrices. `gateset_infidelity`(model, target_model[, itype, ...]) Computes the average-over-gates of the infidelity between gates in model and the gates in target_model. `unitarity`(a[, mx_basis]) Returns the "unitarity" of a channel. `fidelity_upper_bound`(operation_mx) Get an upper bound on the fidelity of the given operation matrix with any unitary operation matrix. `compute_povm_map`(model, povmlbl) Constructs a gate-like quantity for the POVM within model. `povm_fidelity`(model, target_model, povmlbl) Computes the process (entanglement) fidelity between POVM maps. `povm_jtracedist`(model, target_model, povmlbl) Computes the Jamiolkowski trace distance between POVM maps using `jtracedist()`. `povm_diamonddist`(model, target_model, povmlbl) Computes the diamond distance between POVM maps using `diamonddist()`. `decompose_gate_matrix`(operation_mx) Decompse a gate matrix into fixed points, axes of rotation, angles of rotation, and decay rates. Compute the vectorized density matrix which acts as the state psi. `dmvec_to_state`(dmvec[, tol]) Compute the pure state describing the action of density matrix vector dmvec. `unitary_to_superop`(u[, superop_mx_basis]) TODO: docstring Compute the superoperator corresponding to unitary matrix u. `superop_is_unitary`(superop_mx[, mx_basis, rank_tol]) TODO: docstring `superop_to_unitary`(superop_mx[, mx_basis, ...]) TODO: docstring `process_mx_to_unitary`(superop) `std_process_mx_to_unitary`(superop_mx) Compute the unitary corresponding to the (unitary-action!) super-operator superop. `spam_error_generator`(spamvec, target_spamvec, mx_basis) Construct an error generator from a SPAM vector and it's target. `error_generator`(gate, target_op, mx_basis[, typ, ...]) Construct the error generator from a gate and its target. `operation_from_error_generator`(error_gen, target_op, ...) Construct a gate from an error generator and a target gate. `elementary_errorgens`(dim, typ, basis) Compute the elementary error generators of a certain type. `elementary_errorgens_dual`(dim, typ, basis) Compute the set of dual-to-elementary error generators of a given type. `extract_elementary_errorgen_coefficients`(errorgen, ...) TODO: docstring `project_errorgen`(errorgen, elementary_errorgen_type, ...) Compute the projections of a gate error generator onto a set of elementary error generators. `create_elementary_errorgen_nqudit`(typ, ...[, ...]) TODO: docstring - labels can be, e.g. ('H', 'XX') and basis should be a 1-qubit basis w/single-char labels `create_elementary_errorgen_nqudit_dual`(typ, ...[, ...]) TODO: docstring - labels can be, e.g. ('H', 'XX') and basis should be a 1-qubit basis w/single-char labels `rotation_gate_mx`(r[, mx_basis]) Construct a rotation operation matrix. `project_model`(model, target_model[, projectiontypes, ...]) Construct a new model(s) by projecting the error generator of model onto some sub-space then reconstructing. `compute_best_case_gauge_transform`(gate_mx, target_gate_mx) Returns a gauge transformation that maps gate_mx into a matrix that is co-diagonal with target_gate_mx. `project_to_target_eigenspace`(model, target_model[, eps]) Project each gate of model onto the eigenspace of the corresponding gate within target_model. Get the linear operator on (vectorized) density matrices corresponding to a n-qubit unitary operator on states. Whether typ is a recognized Lindblad-gate parameterization type. `effect_label_to_outcome`(povm_and_effect_lbl) Extract the outcome label from a "simplified" effect label. `effect_label_to_povm`(povm_and_effect_lbl) Extract the POVM label from a "simplified" effect label.

### Attributes

pygsti.tools.optools.IMAG_TOL = '1e-07'
pygsti.tools.optools.fidelity(a, b)

Returns the quantum state fidelity between density matrices.

This given by:

F = Tr( sqrt{ sqrt(a) * b * sqrt(a) } )^2

To compute process fidelity, pass this function the Choi matrices of the two processes, or just call `entanglement_fidelity()` with the operation matrices.

#### Parameters

anumpy array

First density matrix.

bnumpy array

Second density matrix.

#### Returns

float

The resulting fidelity.

pygsti.tools.optools.frobeniusdist(a, b)

Returns the frobenius distance between arrays: ||a - b||_Fro.

This could be inlined, but we’re keeping it for API consistency with other distance functions.

anumpy array

First matrix.

bnumpy array

Second matrix.

#### Returns

float

The resulting frobenius distance.

pygsti.tools.optools.frobeniusdist_squared(a, b)

Returns the square of the frobenius distance between arrays: (||a - b||_Fro)^2.

This could be inlined, but we’re keeping it for API consistency with other distance functions.

anumpy array

First matrix.

bnumpy array

Second matrix.

#### Returns

float

The resulting frobenius distance.

pygsti.tools.optools.residuals(a, b)

Calculate residuals between the elements of two matrices

anumpy array

First matrix.

bnumpy array

Second matrix.

#### Returns

np.array

residuals

pygsti.tools.optools.tracenorm(a)

Compute the trace norm of matrix a given by:

Tr( sqrt{ a^dagger * a } )

#### Parameters

anumpy array

The matrix to compute the trace norm of.

#### Returns

float

pygsti.tools.optools.tracedist(a, b)

Compute the trace distance between matrices.

This is given by:

D = 0.5 * Tr( sqrt{ (a-b)^dagger * (a-b) } )

anumpy array

First matrix.

bnumpy array

Second matrix.

#### Returns

float

pygsti.tools.optools.diamonddist(a, b, mx_basis='pp', return_x=False)

Returns the approximate diamond norm describing the difference between gate matrices.

This is given by :

D = ||a - b ||_diamond = sup_rho || AxI(rho) - BxI(rho) ||_1

#### Parameters

anumpy array

First matrix.

bnumpy array

Second matrix.

mx_basisBasis object

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

return_xbool, optional

Whether to return a numpy array encoding the state (rho) at which the maximal trace distance occurs.

#### Returns

dmfloat

Diamond norm

Wnumpy array

Only returned if return_x = True. Encodes the state rho, such that dm = trace( |(J(a)-J(b)).T * W| ).

pygsti.tools.optools.jtracedist(a, b, mx_basis='pp')

Compute the Jamiolkowski trace distance between operation matrices.

This is given by:

D = 0.5 * Tr( sqrt{ (J(a)-J(b))^2 } )

where J(.) is the Jamiolkowski isomorphism map that maps a operation matrix to it’s corresponding Choi Matrix.

#### Parameters

anumpy array

First matrix.

bnumpy array

Second matrix.

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

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

#### Returns

float

pygsti.tools.optools.entanglement_fidelity(a, b, mx_basis='pp', is_tp=None, is_unitary=None)

Returns the “entanglement” process fidelity between gate matrices.

This is given by:

F = Tr( sqrt{ sqrt(J(a)) * J(b) * sqrt(J(a)) } )^2

where J(.) is the Jamiolkowski isomorphism map that maps a operation matrix to it’s corresponding Choi Matrix.

When the both of the input matrices a and b are TP, and the target matrix b is unitary then we can use a more efficient formula:

F= Tr(a @ b.conjugate().T)/d^2

#### Parameters

aarray or gate

The gate to compute the entanglement fidelity to b of. E.g., an imperfect implementation of b.

barray or gate

The gate to compute the entanglement fidelity to a of. E.g., the target gate corresponding to a.

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

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

is_tpbool, optional (default None)

Flag indicating both matrices are TP. If None (the default), an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

is_unitarybool, optional (default None)

Flag indicating that the second matrix, b, is unitary. If None (the default) an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

#### Returns

float

pygsti.tools.optools.average_gate_fidelity(a, b, mx_basis='pp', is_tp=None, is_unitary=None)

Computes the average gate fidelity (AGF) between two gates.

Average gate fidelity (F_g) is related to entanglement fidelity (F_p), via:

F_g = (d * F_p + 1)/(1 + d),

where d is the Hilbert space dimension. This formula, and the definition of AGF, can be found in Phys. Lett. A 303 249-252 (2002).

#### Parameters

aarray or gate

The gate to compute the AGI to b of. E.g., an imperfect implementation of b.

barray or gate

The gate to compute the AGI to a of. E.g., the target gate corresponding to a.

mx_basis{“std”,”gm”,”pp”} or Basis object, optional

The basis of the matrices.

is_tpbool, optional (default None)

Flag indicating both matrices are TP. If None (the default), an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

is_unitarybool, optional (default None)

Flag indicating that the second matrix, b, is unitary. If None (the default) an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

#### Returns

AGIfloat

The AGI of a to b.

pygsti.tools.optools.average_gate_infidelity(a, b, mx_basis='pp', is_tp=None, is_unitary=None)

Computes the average gate infidelity (AGI) between two gates.

Average gate infidelity is related to entanglement infidelity (EI) via:

AGI = (d * (1-EI) + 1)/(1 + d),

where d is the Hilbert space dimension. This formula, and the definition of AGI, can be found in Phys. Lett. A 303 249-252 (2002).

#### Parameters

aarray or gate

The gate to compute the AGI to b of. E.g., an imperfect implementation of b.

barray or gate

The gate to compute the AGI to a of. E.g., the target gate corresponding to a.

mx_basis{“std”,”gm”,”pp”} or Basis object, optional

The basis of the matrices.

is_tpbool, optional (default None)

Flag indicating both matrices are TP. If None (the default), an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

is_unitarybool, optional (default None)

Flag indicating that the second matrix, b, is unitary. If None (the default) an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

#### Returns

float

pygsti.tools.optools.entanglement_infidelity(a, b, mx_basis='pp', is_tp=None, is_unitary=None)

Returns the entanglement infidelity (EI) between gate matrices.

This i given by:

EI = 1 - Tr( sqrt{ sqrt(J(a)) * J(b) * sqrt(J(a)) } )^2

where J(.) is the Jamiolkowski isomorphism map that maps a operation matrix to it’s corresponding Choi Matrix.

#### Parameters

anumpy array

First matrix.

bnumpy array

Second matrix.

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

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

is_tpbool, optional (default None)

Flag indicating both matrices are TP. If None (the default), an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

is_unitarybool, optional (default None)

Flag indicating that the second matrix, b, is unitary. If None (the default) an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

#### Returns

EIfloat

The EI of a to b.

pygsti.tools.optools.gateset_infidelity(model, target_model, itype='EI', weights=None, mx_basis=None, is_tp=None, is_unitary=None)

Computes the average-over-gates of the infidelity between gates in model and the gates in target_model.

If itype is ‘EI’ then the “infidelity” is the entanglement infidelity; if itype is ‘AGI’ then the “infidelity” is the average gate infidelity (AGI and EI are related by a dimension dependent constant).

This is the quantity that RB error rates are sometimes claimed to be related to directly related.

#### Parameters

modelModel

The model to calculate the average infidelity, to target_model, of.

target_modelModel

The model to calculate the average infidelity, to model, of.

itypestr, optional

The infidelity type. Either ‘EI’, corresponding to entanglement infidelity, or ‘AGI’, corresponding to average gate infidelity.

weightsdict, optional

If not None, a dictionary of floats, whereby the keys are the gates in model and the values are, possibly unnormalized, probabilities. These probabilities corresponding to the weighting in the average, so if the model contains gates A and B and weights[A] = 2 and weights[B] = 1 then the output is Inf(A)*2/3 + Inf(B)/3 where Inf(X) is the infidelity (to the corresponding element in the other model) of X. If None, a uniform-average is taken, equivalent to setting all the weights to 1.

mx_basis{“std”,”gm”,”pp”} or Basis object, optional

The basis of the models. If None, the basis is obtained from the model.

is_tpbool, optional (default None)

Flag indicating both matrices are TP. If None (the default), an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

is_unitarybool, optional (default None)

Flag indicating that the second matrix, b, is unitary. If None (the default) an explicit check is performed. If True/False, the check is skipped and the provided value is used (faster, but should only be used when the user is certain this is true apriori).

#### Returns

float

The weighted average-over-gates infidelity between the two models.

pygsti.tools.optools.unitarity(a, mx_basis='gm')

Returns the “unitarity” of a channel.

Unitarity is defined as in Wallman et al, “Estimating the Coherence of noise” NJP 17 113020 (2015). The unitarity is given by (Prop 1 in Wallman et al):

u(a) = Tr( A_u^{dagger} A_u ) / (d^2 - 1),

where A_u is the unital submatrix of a, and d is the dimension of the Hilbert space. When a is written in any basis for which the first element is the normalized identity (e.g., the pp or gm bases), The unital submatrix of a is the matrix obtained when the top row and left hand column is removed from a.

#### Parameters

aarray or gate

The gate for which the unitarity is to be computed.

mx_basis{“std”,”gm”,”pp”} or a Basis object, optional

The basis of the matrix.

#### Returns

float

pygsti.tools.optools.fidelity_upper_bound(operation_mx)

Get an upper bound on the fidelity of the given operation matrix with any unitary operation matrix.

The closeness of the result to one tells

how “unitary” the action of operation_mx is.

#### Parameters

operation_mxnumpy array

The operation matrix to act on.

#### Returns

float

The resulting upper bound on fidelity(operation_mx, anyUnitaryGateMx)

pygsti.tools.optools.compute_povm_map(model, povmlbl)

Constructs a gate-like quantity for the POVM within model.

This is done by embedding the k-outcome classical output space of the POVM in the Hilbert-Schmidt space of k by k density matrices by placing the classical probability distribution along the diagonal of the density matrix. Currently, this is only implemented for the case when k equals d, the dimension of the POVM’s Hilbert space.

#### Parameters

modelModel

The model supplying the POVM effect vectors and the basis those vectors are in.

povmlblstr

The POVM label

#### Returns

numpy.ndarray

The matrix of the “POVM map” in the model.basis basis.

pygsti.tools.optools.povm_fidelity(model, target_model, povmlbl)

Computes the process (entanglement) fidelity between POVM maps.

#### Parameters

modelModel

The model the POVM belongs to.

target_modelModel

The target model (which also has povmlbl).

povmlblLabel

Label of the POVM to get the fidelity of.

#### Returns

float

pygsti.tools.optools.povm_jtracedist(model, target_model, povmlbl)

Computes the Jamiolkowski trace distance between POVM maps using `jtracedist()`.

#### Parameters

modelModel

The model the POVM belongs to.

target_modelModel

The target model (which also has povmlbl).

povmlblLabel

Label of the POVM to get the trace distance of.

#### Returns

float

pygsti.tools.optools.povm_diamonddist(model, target_model, povmlbl)

Computes the diamond distance between POVM maps using `diamonddist()`.

#### Parameters

modelModel

The model the POVM belongs to.

target_modelModel

The target model (which also has povmlbl).

povmlblLabel

Label of the POVM to get the diamond distance of.

#### Returns

float

pygsti.tools.optools.decompose_gate_matrix(operation_mx)

Decompse a gate matrix into fixed points, axes of rotation, angles of rotation, and decay rates.

This funtion computes how the action of a operation matrix can be is decomposed into fixed points, axes of rotation, angles of rotation, and decays. Also determines whether a gate appears to be valid and/or unitary.

#### Parameters

operation_mxnumpy array

The operation matrix to act on.

#### Returns

dict

A dictionary describing the decomposed action. Keys are:

‘isValid’bool

whether decomposition succeeded

‘isUnitary’bool

whether operation_mx describes unitary action

‘fixed point’numpy array

the fixed point of the action

‘axis of rotation’numpy array or nan

the axis of rotation

‘decay of diagonal rotation terms’float

decay of diagonal terms

‘rotating axis 1’numpy array or nan

1st axis orthogonal to axis of rotation

‘rotating axis 2’numpy array or nan

2nd axis orthogonal to axis of rotation

‘decay of off diagonal rotation terms’float

decay of off-diagonal terms

‘pi rotations’float

angle of rotation in units of pi radians

pygsti.tools.optools.state_to_dmvec(psi)

Compute the vectorized density matrix which acts as the state psi.

This is just the outer product map |psi> => |psi><psi| with the output flattened, i.e. dot(psi, conjugate(psi).T).

#### Parameters

psinumpy array

The state vector.

#### Returns

numpy array

The vectorized density matrix.

pygsti.tools.optools.dmvec_to_state(dmvec, tol=1e-06)

Compute the pure state describing the action of density matrix vector dmvec.

If dmvec represents a mixed state, ValueError is raised.

#### Parameters

dmvecnumpy array

The vectorized density matrix, assumed to be in the standard (matrix unit) basis.

tolfloat, optional

tolerance for determining whether an eigenvalue is zero.

#### Returns

numpy array

The pure state, as a column vector of shape = (N,1)

pygsti.tools.optools.unitary_to_superop(u, superop_mx_basis='pp')

TODO: docstring

pygsti.tools.optools.unitary_to_process_mx(u)
pygsti.tools.optools.unitary_to_std_process_mx(u)

Compute the superoperator corresponding to unitary matrix u.

Computes a super-operator (that acts on (row)-vectorized density matrices) from a unitary operator (matrix) u which acts on state vectors. This super-operator is given by the tensor product of u and conjugate(u), i.e. kron(u,u.conj).

#### Parameters

unumpy array

The unitary matrix which acts on state vectors.

#### Returns

numpy array

The super-operator process matrix.

pygsti.tools.optools.superop_is_unitary(superop_mx, mx_basis='pp', rank_tol=1e-06)

TODO: docstring

pygsti.tools.optools.superop_to_unitary(superop_mx, mx_basis='pp', check_superop_is_unitary=True)

TODO: docstring

pygsti.tools.optools.process_mx_to_unitary(superop)
pygsti.tools.optools.std_process_mx_to_unitary(superop_mx)

Compute the unitary corresponding to the (unitary-action!) super-operator superop.

This function assumes superop acts on (row)-vectorized density matrices, and that the super-operator is of the form kron(U,U.conj).

#### Parameters

superopnumpy array

The superoperator matrix which acts on vectorized density matrices (in the ‘std’ matrix-unit basis).

#### Returns

numpy array

The unitary matrix which acts on state vectors.

pygsti.tools.optools.spam_error_generator(spamvec, target_spamvec, mx_basis, typ='logGTi')

Construct an error generator from a SPAM vector and it’s target.

Computes the value of the error generator given by errgen = log( diag(spamvec / target_spamvec) ), where division is element-wise. This results in a (non-unique) error generator matrix E such that spamvec = exp(E) * target_spamvec.

Note: This is currently of very limited use, as the above algorithm fails whenever target_spamvec has zero elements where spamvec doesn’t.

#### Parameters

spamvecndarray

The SPAM vector.

target_spamvecndarray

The target SPAM vector.

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

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

typ{“logGTi”}

The type of error generator to compute. Allowed values are:

• “logGTi” : errgen = log( diag(spamvec / target_spamvec) )

#### Returns

errgenndarray

The error generator.

pygsti.tools.optools.error_generator(gate, target_op, mx_basis, typ='logG-logT', logG_weight=None)

Construct the error generator from a gate and its target.

Computes the value of the error generator given by errgen = log( inv(target_op) * gate ), so that gate = target_op * exp(errgen).

#### Parameters

gatendarray

The operation matrix

target_opndarray

The target operation matrix

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

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

typ{“logG-logT”, “logTiG”, “logGTi”}

The type of error generator to compute. Allowed values are:

• “logG-logT” : errgen = log(gate) - log(target_op)

• “logTiG” : errgen = log( dot(inv(target_op), gate) )

• “logGTi” : errgen = log( dot(gate,inv(target_op)) )

logG_weight: float or None (default)

Regularization weight for logG-logT penalty of approximate logG. If None, the default weight in `approximate_matrix_log()` is used. Note that this will result in a logG close to logT, but G may not exactly equal exp(logG). If self-consistency with func:operation_from_error_generator is desired, consider testing lower (or zero) regularization weight.

#### Returns

errgenndarray

The error generator.

pygsti.tools.optools.operation_from_error_generator(error_gen, target_op, mx_basis, typ='logG-logT')

Construct a gate from an error generator and a target gate.

Inverts the computation done in `error_generator()` and returns the value of the gate given by gate = target_op * exp(error_gen).

#### Parameters

error_genndarray

The error generator matrix

target_opndarray

The target operation matrix

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

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

typ{“logG-logT”, “logG-logT-quick”, “logTiG”, “logGTi”}

The type of error generator to invert. Allowed values are:

• “logG-logT” : gate = exp( errgen + log(target_op) ) using internal logm

• “logG-logT-quick” : gate = exp( errgen + log(target_op) ) using SciPy logm

• “logTiG” : gate = dot( target_op, exp(errgen) )

• “logGTi” : gate = dot( exp(errgen), target_op )

#### Returns

ndarray

The operation matrix.

pygsti.tools.optools.elementary_errorgens(dim, typ, basis)

Compute the elementary error generators of a certain type.

#### Parameters

dimint

The dimension of the error generators to be returned. This is also the associated gate dimension, and must be a perfect square, as sqrt(dim) is the dimension of density matrices. For a single qubit, dim == 4.

typ{‘H’, ‘S’, ‘C’, ‘A’}

The type of error generators to construct.

basisBasis or str

Which basis is used to construct the error generators. Note that this is not the basis of the returned error generators (which is always the ‘std’ matrix-unit basis) but that used to define the different elementary generator operations themselves.

#### Returns

generatorsnumpy.ndarray

An array of shape (#basis-elements,dim,dim). generators[i] is the generator corresponding to the ith basis matrix in the std (matrix unit) basis. (Note that in most cases #basis-elements == dim, so the size of generators is (dim,dim,dim) ). Each generator is normalized so that as a vector it has unit Frobenius norm.

pygsti.tools.optools.elementary_errorgens_dual(dim, typ, basis)

Compute the set of dual-to-elementary error generators of a given type.

These error generators are dual to the elementary error generators constructed by `elementary_errorgens()`.

#### Parameters

dimint

The dimension of the error generators to be returned. This is also the associated gate dimension, and must be a perfect square, as sqrt(dim) is the dimension of density matrices. For a single qubit, dim == 4.

typ{‘H’, ‘S’, ‘C’, ‘A’}

The type of error generators to construct.

basisBasis or str

Which basis is used to construct the error generators. Note that this is not the basis of the returned error generators (which is always the ‘std’ matrix-unit basis) but that used to define the different elementary generator operations themselves.

#### Returns

generatorsnumpy.ndarray

An array of shape (#basis-elements,dim,dim). generators[i] is the generator corresponding to the ith basis matrix in the std (matrix unit) basis. (Note that in most cases #basis-elements == dim, so the size of generators is (dim,dim,dim) ). Each generator is normalized so that as a vector it has unit Frobenius norm.

pygsti.tools.optools.extract_elementary_errorgen_coefficients(errorgen, elementary_errorgen_labels, elementary_errorgen_basis='pp', errorgen_basis='pp', return_projected_errorgen=False)

TODO: docstring

pygsti.tools.optools.project_errorgen(errorgen, elementary_errorgen_type, elementary_errorgen_basis, errorgen_basis='pp', return_dual_elementary_errorgens=False, return_projected_errorgen=False)

Compute the projections of a gate error generator onto a set of elementary error generators. TODO: docstring update

This standard set of errors is given by projection_type, and is constructed from the elements of the projection_basis basis.

#### Parameters

errorgen: ndarray

The error generator matrix to project.

projection_type{“hamiltonian”, “stochastic”, “affine”}

The type of error generators to project the gate error generator onto. If “hamiltonian”, then use the Hamiltonian generators which take a density matrix rho -> -i*[ H, rho ] for Pauli-product matrix H. If “stochastic”, then use the Stochastic error generators which take rho -> P*rho*P for Pauli-product matrix P (recall P is self adjoint). If “affine”, then use the affine error generators which take rho -> P (superop is |P>><<1|).

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

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

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

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

return_generatorsbool, optional

If True, return the error generators projected against along with the projection values themseves.

return_scale_fctrbool, optional

If True, also return the scaling factor that was used to multply the projections onto normalized error generators to get the returned values.

#### Returns

projectionsnumpy.ndarray

An array of length equal to the number of elements in the basis used to construct the projectors. Typically this is is also the dimension of the gate (e.g. 4 for a single qubit).

generatorsnumpy.ndarray

Only returned when return_generators == True. An array of shape (#basis-els,op_dim,op_dim) such that generators[i] is the generator corresponding to the i-th basis element. Note that these matricies are in the std (matrix unit) basis.

pygsti.tools.optools.create_elementary_errorgen_nqudit(typ, basis_element_labels, basis_1q, normalize=False, sparse=False, tensorprod_basis=False)

TODO: docstring - labels can be, e.g. (‘H’, ‘XX’) and basis should be a 1-qubit basis w/single-char labels

pygsti.tools.optools.create_elementary_errorgen_nqudit_dual(typ, basis_element_labels, basis_1q, normalize=False, sparse=False, tensorprod_basis=False)

TODO: docstring - labels can be, e.g. (‘H’, ‘XX’) and basis should be a 1-qubit basis w/single-char labels

pygsti.tools.optools.rotation_gate_mx(r, mx_basis='gm')

Construct a rotation operation matrix.

Build the operation matrix corresponding to the unitary

exp(-i * (r[0]/2*PP[0]*sqrt(d) + r[1]/2*PP[1]*sqrt(d) + …) )

where PP’ is the array of Pauli-product matrices obtained via `pp_matrices(d), where d = sqrt(len(r)+1). The division by 2 is for convention, and the sqrt(d) is to essentially un-normalise the matrices returned by `pp_matrices()` to they are equal to products of the standard Pauli matrices.

#### Parameters

rtuple

A tuple of coeffiecients, one per non-identity Pauli-product basis element

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

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

#### Returns

numpy array

a d^2 x d^2 operation matrix in the specified basis.

pygsti.tools.optools.project_model(model, target_model, projectiontypes=('H', 'S', 'H+S', 'LND'), gen_type='logG-logT', logG_weight=None)

Construct a new model(s) by projecting the error generator of model onto some sub-space then reconstructing.

#### Parameters

modelModel

The model whose error generator should be projected.

target_modelModel

The set of target (ideal) gates.

projectiontypestuple of {‘H’,’S’,’H+S’,’LND’,’LNDF’}

Which projections to use. The length of this tuple gives the number of Model objects returned. Allowed values are:

• ‘H’ = Hamiltonian errors

• ‘S’ = Stochastic Pauli-channel errors

• ‘H+S’ = both of the above error types

• ‘LND’ = errgen projected to a normal (CPTP) Lindbladian

• ‘LNDF’ = errgen projected to an unrestricted (full) Lindbladian

gen_type{“logG-logT”, “logTiG”, “logGTi”}

The type of error generator to compute. For more details, see func:error_generator.

logG_weight: float or None (default)

Regularization weight for approximate logG in logG-logT generator. For more details, see func:error_generator.

#### Returns

projected_modelslist of Models

Elements are projected versions of model corresponding to the elements of projectiontypes.

Npslist of parameter counts

Integer parameter counts for each model in projected_models. Useful for computing the expected log-likelihood or chi2.

pygsti.tools.optools.compute_best_case_gauge_transform(gate_mx, target_gate_mx, return_all=False)

Returns a gauge transformation that maps gate_mx into a matrix that is co-diagonal with target_gate_mx.

(Co-diagonal means that they share a common set of eigenvectors.)

Gauge transformations effectively change the basis of all the gates in a model. From the perspective of a single gate a gauge transformation leaves it’s eigenvalues the same and changes its eigenvectors. This function finds a real transformation that transforms the eigenspaces of gate_mx so that there exists a set of eigenvectors which diagonalize both gate_mx and target_gate_mx.

#### Parameters

gate_mxnumpy.ndarray

Gate matrix to transform.

target_gate_mxnumpy.ndarray

Target gate matrix.

return_allbool, optional

If true, also return the matrices of eigenvectors for Ugate for gate_mx and Utgt for target_gate_mx such that U = dot(Utgt, inv(Ugate)) is real.

#### Returns

Unumpy.ndarray

A gauge transformation such that if epgate = U * gate_mx * U_inv, then epgate (which has the same eigenalues as gate_mx), can be diagonalized with a set of eigenvectors that also diagonalize target_gate_mx. Furthermore, U is real.

Ugate, Utgtnumpy.ndarray

only if return_all == True. See above.

pygsti.tools.optools.project_to_target_eigenspace(model, target_model, eps=1e-06)

Project each gate of model onto the eigenspace of the corresponding gate within target_model.

Returns the resulting Model.

#### Parameters

modelModel

Model to act on.

target_modelModel

The target model, whose gates define the target eigenspaces being projected onto.

epsfloat, optional

Small magnitude specifying how much to “nudge” the target gates before eigen-decomposing them, so that their spectra will have the same conjugacy structure as the gates of model.

#### Returns

Model

pygsti.tools.optools.unitary_to_pauligate(u)

Get the linear operator on (vectorized) density matrices corresponding to a n-qubit unitary operator on states.

#### Parameters

unumpy array

A dxd array giving the action of the unitary on a state in the sigma-z basis. where d = 2 ** n-qubits

#### Returns

numpy array

The operator on density matrices that have been vectorized as d**2 vectors in the Pauli basis.

Whether typ is a recognized Lindblad-gate parameterization type.

A Lindblad type is comprised of a parameter specification followed optionally by an evolution-type suffix. The parameter spec can be “GLND” (general unconstrained Lindbladian), “CPTP” (cptp-constrained), or any/all of the letters “H” (Hamiltonian), “S” (Stochastic, CPTP), “s” (Stochastic), “A” (Affine), “D” (Depolarization, CPTP), “d” (Depolarization) joined with plus (+) signs. Note that “A” cannot appear without one of {“S”,”s”,”D”,”d”}. The suffix can be non-existent (density-matrix), “terms” (state-vector terms) or “clifford terms” (stabilizer-state terms). For example, valid Lindblad types are “H+S”, “H+d+A”, “CPTP clifford terms”, or “S+A terms”.

#### Parameters

typstr

A paramterization type.

#### Returns

bool

pygsti.tools.optools.effect_label_to_outcome(povm_and_effect_lbl)

Extract the outcome label from a “simplified” effect label.

Simplified effect labels are not themselves so simple. They combine POVM and effect labels so that accessing any given effect vector is simpler.

If povm_and_effect_lbl is None then “NONE” is returned.

#### Parameters

povm_and_effect_lblLabel

Simplified effect vector.

#### Returns

str

pygsti.tools.optools.effect_label_to_povm(povm_and_effect_lbl)

Extract the POVM label from a “simplified” effect label.

Simplified effect labels are not themselves so simple. They combine POVM and effect labels so that accessing any given effect vector is simpler.

If povm_and_effect_lbl is None then “NONE” is returned.

#### Parameters

povm_and_effect_lblLabel

Simplified effect vector.

str