pygsti.tools

pyGSTi Tools Python Package

Submodules

Package Contents

Classes

_Basis

An ordered set of labeled matrices/vectors.

NamedDict

A dictionary that also holds category names and types.

_Basis

An ordered set of labeled matrices/vectors.

_ExplicitBasis

A Basis whose elements are specified directly.

_DirectSumBasis

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

_Label

A label used to identify a gate, circuit layer, or (sub-)circuit.

_LocalElementaryErrorgenLabel

Labels an elementary error generator by simply a type and one or two

_Label

A label used to identify a gate, circuit layer, or (sub-)circuit.

TypedDict

A dictionary that holds per-key type information.

Functions

basis_matrices(name_or_basis, dim, sparse=False)

Get the elements of the specifed basis-type which spans the density-matrix space given by dim.

basis_longname(basis)

Get the "long name" for a particular basis, which is typically used in reports, etc.

basis_element_labels(basis, dim)

Get a list of short labels corresponding to to the elements of the described basis.

is_sparse_basis(name_or_basis)

Whether a basis contains sparse matrices.

change_basis(mx, from_basis, to_basis)

Convert a operation matrix from one basis of a density matrix space to another.

create_basis_pair(mx, from_basis, to_basis)

Constructs bases from transforming mx between two basis names.

create_basis_for_matrix(mx, basis)

Construct a Basis object with type given by basis and dimension approprate for transforming mx.

resize_std_mx(mx, resize, std_basis_1, std_basis_2)

Change the basis of mx to a potentially larger or smaller 'std'-type basis given by std_basis_2.

flexible_change_basis(mx, start_basis, end_basis)

Change mx from start_basis to end_basis allowing embedding expansion and contraction if needed.

resize_mx(mx, dim_or_block_dims=None, resize=None)

Wrapper for resize_std_mx(), that manipulates mx to be in another basis.

state_to_stdmx(state_vec)

Convert a state vector into a density matrix.

state_to_pauli_density_vec(state_vec)

Convert a single qubit state vector into a Liouville vector in the Pauli basis.

vec_to_stdmx(v, basis, keep_complex=False)

Convert a vector in this basis to a matrix in the standard basis.

stdmx_to_vec(m, basis)

Convert a matrix in the standard basis to a vector in the Pauli basis.

_deprecated_fn(replacement=None)

Decorator for deprecating a function.

chi2(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(-10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Computes the total (aggregate) chi^2 for a set of circuits.

chi2_per_circuit(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(-10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Computes the per-circuit chi^2 contributions for a set of cirucits.

chi2_jacobian(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(-10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the gradient of the chi^2 function computed by :function:`chi2`.

chi2_hessian(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(-10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the Hessian matrix of the chi2() function.

chi2_approximate_hessian(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(-10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute and approximate Hessian matrix of the chi2() function.

chialpha(alpha, model, dataset, circuits=None, pfratio_stitchpt=0.01, pfratio_derivpt=0.01, prob_clip_interval=(-10000, 10000), radius=None, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the chi-alpha objective function.

chialpha_per_circuit(alpha, model, dataset, circuits=None, pfratio_stitchpt=0.01, pfratio_derivpt=0.01, prob_clip_interval=(-10000, 10000), radius=None, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the per-circuit chi-alpha objective function.

chi2fn_2outcome(n, p, f, min_prob_clip_for_weighting=0.0001)

Computes chi^2 for a 2-outcome measurement.

chi2fn_2outcome_wfreqs(n, p, f)

Computes chi^2 for a 2-outcome measurement using frequency-weighting.

chi2fn(n, p, f, min_prob_clip_for_weighting=0.0001)

Computes the chi^2 term corresponding to a single outcome.

chi2fn_wfreqs(n, p, f, min_freq_clip_for_weighting=0.0001)

Computes the frequency-weighed chi^2 term corresponding to a single outcome.

bonferroni_correction(significance, numtests)

Calculates the standard Bonferroni correction.

sidak_correction(significance, numtests)

Sidak correction.

generalized_bonferroni_correction(significance, weights, numtests=None, nested_method='bonferroni', tol=1e-10)

Generalized Bonferroni correction.

jamiolkowski_iso(operation_mx, op_mx_basis='pp', choi_mx_basis='pp')

Given a operation matrix, return the corresponding Choi matrix that is normalized to have trace == 1.

jamiolkowski_iso_inv(choi_mx, choi_mx_basis='pp', op_mx_basis='pp')

Given a choi matrix, return the corresponding operation matrix.

fast_jamiolkowski_iso_std(operation_mx, op_mx_basis)

The corresponding Choi matrix in the standard basis that is normalized to have trace == 1.

fast_jamiolkowski_iso_std_inv(choi_mx, op_mx_basis)

Given a choi matrix in the standard basis, return the corresponding operation matrix.

sum_of_negative_choi_eigenvalues(model, weights=None)

Compute the amount of non-CP-ness of a model.

sums_of_negative_choi_eigenvalues(model)

Compute the amount of non-CP-ness of a model.

magnitudes_of_negative_choi_eigenvalues(model)

Compute the magnitudes of the negative eigenvalues of the Choi matricies for each gate in model.

warn_deprecated(name, replacement=None)

Formats and prints a deprecation warning message.

deprecate(replacement=None)

Decorator for deprecating a function.

deprecate_imports(module_name, replacement_map, warning_msg)

Utility to deprecate imports from a module.

logl(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, wildcard=None, mdc_store=None, comm=None, mem_limit=None)

The log-likelihood function.

logl_per_circuit(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, wildcard=None, mdc_store=None, comm=None, mem_limit=None)

Computes the per-circuit log-likelihood contribution for a set of circuits.

logl_jacobian(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None, verbosity=0)

The jacobian of the log-likelihood function.

logl_hessian(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None, verbosity=0)

The hessian of the log-likelihood function.

logl_approximate_hessian(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None, verbosity=0)

An approximate Hessian of the log-likelihood function.

logl_max(model, dataset, circuits=None, poisson_picture=True, op_label_aliases=None, mdc_store=None)

The maximum log-likelihood possible for a DataSet.

logl_max_per_circuit(model, dataset, circuits=None, poisson_picture=True, op_label_aliases=None, mdc_store=None)

The vector of maximum log-likelihood contributions for each circuit, aggregated over outcomes.

two_delta_logl_nsigma(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, dof_calc_method='modeltest', wildcard=None)

See docstring for :function:`pygsti.tools.two_delta_logl`

two_delta_logl(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, dof_calc_method=None, wildcard=None, mdc_store=None, comm=None)

Twice the difference between the maximum and actual log-likelihood.

two_delta_logl_per_circuit(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(-1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, dof_calc_method=None, wildcard=None, mdc_store=None, comm=None)

Twice the per-circuit difference between the maximum and actual log-likelihood.

two_delta_logl_term(n, p, f, min_prob_clip=1e-06, poisson_picture=True)

Term of the 2*[log(L)-upper-bound - log(L)] sum corresponding to a single circuit and spam label.

basis_matrices(name_or_basis, dim, sparse=False)

Get the elements of the specifed basis-type which spans the density-matrix space given by dim.

hamiltonian_to_lindbladian(hamiltonian, sparse=False)

Construct the Lindbladian corresponding to a given Hamiltonian.

stochastic_lindbladian(q, sparse=False)

Construct the Lindbladian corresponding to stochastic q-errors.

affine_lindbladian(q, sparse=False)

Construct the Lindbladian corresponding to affine q-errors.

nonham_lindbladian(Lm, Ln, sparse=False)

Construct the Lindbladian corresponding to generalized non-Hamiltonian (stochastic) errors.

remove_duplicates_in_place(l, index_to_test=None)

Remove duplicates from the list passed as an argument.

remove_duplicates(l, index_to_test=None)

Remove duplicates from the a list and return the result.

compute_occurrence_indices(lst)

A 0-based list of integers specifying which occurrence, i.e. enumerated duplicate, each list item is.

find_replace_tuple(t, alias_dict)

Replace elements of t according to rules in alias_dict.

find_replace_tuple_list(list_of_tuples, alias_dict)

Applies find_replace_tuple() on each element of list_of_tuples.

apply_aliases_to_circuits(list_of_circuits, alias_dict)

Applies alias_dict to the circuits in list_of_circuits.

sorted_partitions(n)

Iterate over all sorted (decreasing) partitions of integer n.

partitions(n)

Iterate over all partitions of integer n.

partition_into(n, nbins)

Iterate over all partitions of integer n into nbins bins.

_partition_into_slow(n, nbins)

Helper function for partition_into that performs the same task for

incd_product(*args)

Like itertools.product but returns the first modified (incremented) index along with the product tuple itself.

dot_mod2(m1, m2)

Returns the product over the integers modulo 2 of two matrices.

multidot_mod2(mlist)

Returns the product over the integers modulo 2 of a list of matrices.

det_mod2(m)

Returns the determinant of a matrix over the integers modulo 2 (GL(n,2)).

matrix_directsum(m1, m2)

Returns the direct sum of two square matrices of integers.

inv_mod2(m)

Finds the inverse of a matrix over GL(n,2)

Axb_mod2(A, b)

Solves Ax = b over GF(2)

gaussian_elimination_mod2(a)

Gaussian elimination mod2 of a.

diagonal_as_vec(m)

Returns a 1D array containing the diagonal of the input square 2D array m.

strictly_upper_triangle(m)

Returns a matrix containing the strictly upper triangle of m and zeros elsewhere.

diagonal_as_matrix(m)

Returns a diagonal matrix containing the diagonal of m.

albert_factor(d, failcount=0)

Returns a matrix M such that d = M M.T for symmetric d, where d and M are matrices over [0,1] mod 2.

random_bitstring(n, p, failcount=0)

Constructs a random bitstring of length n with parity p

random_invertable_matrix(n, failcount=0)

Finds a random invertable matrix M over GL(n,2)

random_symmetric_invertable_matrix(n)

Creates a random, symmetric, invertible matrix from GL(n,2)

onesify(a, failcount=0, maxfailcount=100)

Returns M such that M a M.T has ones along the main diagonal

permute_top(a, i)

Permutes the first row & col with the i'th row & col

fix_top(a)

Computes the permutation matrix P such that the [1:t,1:t] submatrix of P a P is invertible.

proper_permutation(a)

Computes the permutation matrix P such that all [n:t,n:t] submatrices of P a P are invertible.

_check_proper_permutation(a)

Check to see if the matrix has been properly permuted.

change_basis(mx, from_basis, to_basis)

Convert a operation matrix from one basis of a density matrix space to another.

trace(m)

The trace of a matrix, sum_i m[i,i].

is_hermitian(mx, tol=1e-09)

Test whether mx is a hermitian matrix.

is_pos_def(mx, tol=1e-09)

Test whether mx is a positive-definite matrix.

is_valid_density_mx(mx, tol=1e-09)

Test whether mx is a valid density matrix (hermitian, positive-definite, and unit trace).

frobeniusnorm(ar)

Compute the frobenius norm of an array (or matrix),

frobeniusnorm_squared(ar)

Compute the squared frobenius norm of an array (or matrix),

nullspace(m, tol=1e-07)

Compute the nullspace of a matrix.

nullspace_qr(m, tol=1e-07)

Compute the nullspace of a matrix using the QR decomposition.

nice_nullspace(m, tol=1e-07)

Computes the nullspace of a matrix, and tries to return a "nice" basis for it.

normalize_columns(m, return_norms=False, ord=None)

Normalizes the columns of a matrix.

column_norms(m, ord=None)

Compute the norms of the columns of a matrix.

scale_columns(m, scale_values)

Scale each column of a matrix by a given value.

columns_are_orthogonal(m, tol=1e-07)

Checks whether a matrix contains orthogonal columns.

columns_are_orthonormal(m, tol=1e-07)

Checks whether a matrix contains orthogonal columns.

independent_columns(m, initial_independent_cols=None, tol=1e-07)

Computes the indices of the linearly-independent columns in a matrix.

pinv_of_matrix_with_orthogonal_columns(m)

TODO: docstring

matrix_sign(m)

The "sign" matrix of m

print_mx(mx, width=9, prec=4, withbrackets=False)

Print matrix in pretty format.

mx_to_string(m, width=9, prec=4, withbrackets=False)

Generate a "pretty-format" string for a matrix.

mx_to_string_complex(m, real_width=9, im_width=9, prec=4)

Generate a "pretty-format" string for a complex-valued matrix.

unitary_superoperator_matrix_log(m, mx_basis)

Construct the logarithm of superoperator matrix m.

near_identity_matrix_log(m, tol=1e-08)

Construct the logarithm of superoperator matrix m that is near the identity.

approximate_matrix_log(m, target_logm, target_weight=10.0, tol=1e-06)

Construct an approximate logarithm of superoperator matrix m that is real and near the target_logm.

real_matrix_log(m, action_if_imaginary='raise', tol=1e-08)

Construct a real logarithm of real matrix m.

column_basis_vector(i, dim)

Returns the ith standard basis vector in dimension dim.

vec(matrix_in)

Stacks the columns of a matrix to return a vector

unvec(vector_in)

Slices a vector into the columns of a matrix.

norm1(m)

Returns the 1 norm of a matrix

random_hermitian(dim)

Generates a random Hermitian matrix

norm1to1(operator, num_samples=10000, mx_basis='gm', return_list=False)

The Hermitian 1-to-1 norm of a superoperator represented in the standard basis.

complex_compare(a, b)

Comparison function for complex numbers that compares real part, then imaginary part.

prime_factors(n)

GCD algorithm to produce prime factors of n

minweight_match(a, b, metricfn=None, return_pairs=True, pass_indices_to_metricfn=False)

Matches the elements of two vectors, a and b by minimizing the weight between them.

minweight_match_realmxeigs(a, b, metricfn=None, pass_indices_to_metricfn=False, eps=1e-09)

Matches the elements of a and b, whose elements are assumed to either real or one-half of a conjugate pair.

_fas(a, inds, rhs, add=False)

Fancy Assignment, equivalent to a[*inds] = rhs but with

_findx_shape(a, inds)

Returns the shape of a fancy-indexed array (a[*inds].shape)

_findx(a, inds, always_copy=False)

Fancy Indexing, equivalent to a[*inds].copy() but with

safe_dot(a, b)

Performs dot(a,b) correctly when neither, either, or both arguments are sparse matrices.

safe_real(a, inplace=False, check=False)

Get the real-part of a, where a can be either a dense array or a sparse matrix.

safe_imag(a, inplace=False, check=False)

Get the imaginary-part of a, where a can be either a dense array or a sparse matrix.

safe_norm(a, part=None)

Get the frobenius norm of a matrix or vector, a, when it is either a dense array or a sparse matrix.

safe_onenorm(a)

Computes the 1-norm of the dense or sparse matrix a.

csr_sum_indices(csr_matrices)

Precomputes the indices needed to sum a set of CSR sparse matrices.

csr_sum(data, coeffs, csr_mxs, csr_sum_indices)

Accelerated summation of several CSR-format sparse matrices.

csr_sum_flat_indices(csr_matrices)

Precomputes quantities allowing fast computation of linear combinations of CSR sparse matrices.

csr_sum_flat(data, coeffs, flat_dest_index_array, flat_csr_mx_data, mx_nnz_indptr)

Computation of the summation of several CSR-format sparse matrices.

expm_multiply_prep(a, tol=EXPM_DEFAULT_TOL)

Computes "prepared" meta-info about matrix a, to be used in expm_multiply_fast.

expm_multiply_fast(prep_a, v, tol=EXPM_DEFAULT_TOL)

Multiplies v by an exponentiated matrix.

_custom_expm_multiply_simple_core(a, b, mu, m_star, s, tol, eta)

a helper function. Note that this (python) version works when a is a LinearOperator

expop_multiply_prep(op, a_1_norm=None, tol=EXPM_DEFAULT_TOL)

Returns "prepared" meta-info about operation op, which is assumed to be traceless (so no shift is needed).

sparse_equal(a, b, atol=1e-08)

Checks whether two Scipy sparse matrices are (almost) equal.

sparse_onenorm(a)

Computes the 1-norm of the scipy sparse matrix a.

ndarray_base(a, verbosity=0)

Get the base memory object for numpy array a.

to_unitary(scaled_unitary)

Compute the scaling factor required to turn a scalar multiple of a unitary matrix to a unitary matrix.

sorted_eig(mx)

Similar to numpy.eig, but returns sorted output.

compute_kite(eigenvalues)

Computes the "kite" corresponding to a list of eigenvalues.

find_zero_communtant_connection(u, u_inv, u0, u0_inv, kite)

Find a matrix R such that u_inv R u0 is diagonal AND log(R) has no projection onto the commutant of G0.

project_onto_kite(mx, kite)

Project mx onto kite, so mx is zero everywhere except on the kite.

project_onto_antikite(mx, kite)

Project mx onto the complement of kite, so mx is zero everywhere on the kite.

remove_dependent_cols(mx, tol=1e-07)

Removes the linearly dependent columns of a matrix.

intersection_space(space1, space2, tol=1e-07, use_nice_nullspace=False)

TODO: docstring

union_space(space1, space2, tol=1e-07)

TODO: docstring

jamiolkowski_angle(hamiltonian_mx)

TODO: docstring

zvals_to_dense(self, zvals, superket=True)

Construct the dense operator or superoperator representation of a computational basis state.

int64_parity(x)

Compute the partity of x.

zvals_int64_to_dense(zvals_int, nqubits, outvec=None, trust_outvec_sparsity=False, abs_elval=None)

Fills a dense array with the super-ket representation of a computational basis state.

parallel_apply(f, l, comm)

Apply a function, f to every element of a list, l in parallel, using MPI.

mpi4py_comm()

Get a comm object

starmap_with_kwargs(fn, num_runs, num_processors, args_list, kwargs_list)

_flat_mut_blks(i, j, block_dims)

_hack_sqrtm(a)

fidelity(a, b)

Returns the quantum state fidelity between density matrices.

frobeniusdist(a, b)

Returns the frobenius distance between gate or density matrices.

frobeniusdist_squared(a, b)

Returns the square of the frobenius distance between gate or density matrices.

residuals(a, b)

Calculate residuals between the elements of two matrices

tracenorm(a)

Compute the trace norm of matrix a given by:

tracedist(a, b)

Compute the trace distance between matrices.

diamonddist(a, b, mx_basis='pp', return_x=False)

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

jtracedist(a, b, mx_basis='pp')

Compute the Jamiolkowski trace distance between operation matrices.

entanglement_fidelity(a, b, mx_basis='pp')

Returns the "entanglement" process fidelity between gate matrices.

average_gate_fidelity(a, b, mx_basis='pp')

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

average_gate_infidelity(a, b, mx_basis='gm')

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

entanglement_infidelity(a, b, mx_basis='pp')

Returns the entanglement infidelity (EI) between gate matrices.

gateset_infidelity(model, target_model, itype='EI', weights=None, mx_basis=None)

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

unitarity(a, mx_basis='gm')

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.

state_to_dmvec(psi)

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

dmvec_to_state(dmvec, tol=1e-06)

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

unitary_to_process_mx(u)

Compute the superoperator corresponding to unitary matrix u.

process_mx_to_unitary(superop)

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

spam_error_generator(spamvec, target_spamvec, mx_basis, typ='logGTi')

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

error_generator(gate, target_op, mx_basis, typ='logG-logT', logG_weight=None)

Construct the error generator from a gate and its target.

operation_from_error_generator(error_gen, target_op, mx_basis, typ='logG-logT')

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

std_scale_factor(dim, projection_type)

Gets the scaling factors required to turn std_error_generators() output into projectors.

std_error_generators(dim, projection_type, projection_basis)

Compute the gate error generators for a standard set of errors.

std_errorgen_projections(errgen, projection_type, projection_basis, mx_basis='gm', return_generators=False, return_scale_fctr=False)

Compute the projections of a gate error generator onto generators for a standard set of errors.

_assert_shape(ar, shape, sparse=False)

Asserts ar.shape == shape ; works with sparse matrices too

lindblad_error_generator(errorgen_type, basis_element_labels, basis_1q, normalize, 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

lindblad_error_generators(dmbasis_ham, dmbasis_other, normalize, other_mode='all')

Compute the superoperator-generators corresponding to Lindblad terms.

lindblad_errorgen_projections(errgen, ham_basis, other_basis, mx_basis='gm', normalize=True, return_generators=False, other_mode='all', sparse=False)

Compute the projections of an error generator onto generators for the Lindblad-term errors.

projections_to_lindblad_terms(ham_projs, other_projs, ham_basis, other_basis, other_mode='all', return_basis=True)

Converts error-generator projections into a dictionary of error coefficients.

lindblad_terms_to_projections(lindblad_term_dict, basis, other_mode='all')

Convert a set of Lindblad terms into a dense matrix/grid of projections.

lindblad_param_labels(ham_basis, other_basis, param_mode='cptp', other_mode='all', dim=None)

Generate human-readable labels for the Lindblad parameters.

lindblad_projections_to_paramvals(ham_projs, other_projs, param_mode='cptp', other_mode='all', truncate=True)

Compute Lindblad-gate parameter values from error generator projections.

lindblad_terms_projection_indices(ham_basis, other_basis, other_mode='all')

Constructs a dictionary mapping Lindblad term labels to projection coefficients.

paramvals_to_lindblad_projections(paramvals, ham_basis_size, other_basis_size, param_mode='cptp', other_mode='all', cache_mx=None)

Construct Lindblad-term projections from Lindblad-operator parameter values.

paramvals_to_lindblad_projections_deriv(paramvals, ham_basis_size, other_basis_size, param_mode='cptp', other_mode='all', cache_mx=None)

Construct derivative of Lindblad-term projections with respect to the parameter values.

rotation_gate_mx(r, mx_basis='gm')

Construct a rotation operation matrix.

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.

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.

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.

unitary_to_pauligate(u)

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

is_valid_lindblad_paramtype(typ)

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.

unitary_to_pauligate(u)

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

single_qubit_gate(hx, hy, hz, noise=0)

Construct the single-qubit operation matrix.

two_qubit_gate(ix=0, iy=0, iz=0, xi=0, xx=0, xy=0, xz=0, yi=0, yx=0, yy=0, yz=0, zi=0, zx=0, zy=0, zz=0, ii=0)

Construct the single-qubit operation matrix.

deprecate(replacement=None)

Decorator for deprecating a function.

cache_by_hashed_args(obj)

Decorator for caching a function values

timed_block(label, time_dict=None, printer=None, verbosity=2, round_places=6, pre_message=None, format_str=None)

Context manager that times a block of code

time_hash()

Get string-version of current time

tvd(p, q)

Calculates the total variational distance between two probability distributions.

classical_fidelity(p, q)

Calculates the (classical) fidelity between two probability distributions.

predicted_rb_number(model, target_model, weights=None, d=None, rtype='EI')

Predicts the RB error rate from a model.

predicted_rb_decay_parameter(model, target_model, weights=None)

Computes the second largest eigenvalue of the 'L matrix' (see the L_matrix function).

rb_gauge(model, target_model, weights=None, mx_basis=None, eigenvector_weighting=1.0)

Computes the gauge transformation required so that the RB number matches the average model infidelity.

transform_to_rb_gauge(model, target_model, weights=None, mx_basis=None, eigenvector_weighting=1.0)

Transforms a Model into the "RB gauge" (see the RB_gauge function).

L_matrix(model, target_model, weights=None)

Constructs a generalization of the 'L-matrix' linear operator on superoperators.

R_matrix_predicted_rb_decay_parameter(model, group, group_to_model=None, weights=None)

Returns the second largest eigenvalue of a generalization of the 'R-matrix' [see the R_matrix function].

R_matrix(model, group, group_to_model=None, weights=None)

Constructs a generalization of the 'R-matrix' of Proctor et al Phys. Rev. Lett. 119, 130502 (2017).

errormaps(model, target_model)

Computes the 'left-multiplied' error maps associated with a noisy gate set, along with the average error map.

gate_dependence_of_errormaps(model, target_model, norm='diamond', mx_basis=None)

Computes the "gate-dependence of errors maps" parameter defined by

length(s)

Returns the length (the number of indices) contained in a slice.

shift(s, offset)

Returns a new slice whose start and stop points are shifted by offset.

intersect(s1, s2)

Returns the intersection of two slices (which must have the same step).

intersect_within(s1, s2)

Returns the intersection of two slices (which must have the same step).

indices(s, n=None)

Returns a list of the indices specified by slice s.

list_to_slice(lst, array_ok=False, require_contiguous=True)

Returns a slice corresponding to a given list of (integer) indices, if this is possible.

to_array(slc_or_list_like)

Returns slc_or_list_like as an index array (an integer numpy.ndarray).

divide(slc, max_len)

Divides a slice into sub-slices based on a maximum length (for each sub-slice).

slice_of_slice(slc, base_slc)

A slice that is the composition of base_slc and slc.

slice_hash(slc)

smart_cached(obj)

Decorator for applying a smart cache to a single function or method.

symplectic_form(n, convention='standard')

Creates the symplectic form for the number of qubits specified.

change_symplectic_form_convention(s, outconvention='standard')

Maps the input symplectic matrix between the 'standard' and 'directsum' symplectic form conventions.

check_symplectic(m, convention='standard')

Checks whether a matrix is symplectic.

inverse_symplectic(s)

Returns the inverse of a symplectic matrix over the integers mod 2.

inverse_clifford(s, p)

Returns the inverse of a Clifford gate in the symplectic representation.

check_valid_clifford(s, p)

Checks if a symplectic matrix - phase vector pair (s,p) is the symplectic representation of a Clifford.

construct_valid_phase_vector(s, pseed)

Constructs a phase vector that, when paired with the provided symplectic matrix, defines a Clifford gate.

find_postmultipled_pauli(s, p_implemented, p_target, qubit_labels=None)

Finds the Pauli layer that should be appended to a circuit to implement a given Clifford.

find_premultipled_pauli(s, p_implemented, p_target, qubit_labels=None)

Finds the Pauli layer that should be prepended to a circuit to implement a given Clifford.

find_pauli_layer(pvec, qubit_labels, pauli_labels=['I', 'X', 'Y', 'Z'])

TODO: docstring

find_pauli_number(pvec)

TODO: docstring

compose_cliffords(s1, p1, s2, p2, do_checks=True)

Multiplies two cliffords in the symplectic representation.

symplectic_kronecker(sp_factors)

Takes a kronecker product of symplectic representations.

prep_stabilizer_state(nqubits, zvals=None)

Contruct the (s,p) stabilizer representation for a computational basis state given by zvals.

apply_clifford_to_stabilizer_state(s, p, state_s, state_p)

Applies a clifford in the symplectic representation to a stabilizer state in the standard stabilizer representation.

pauli_z_measurement(state_s, state_p, qubit_index)

Computes the probabilities of 0/1 (+/-) outcomes from measuring a Pauli operator on a stabilizer state.

colsum(i, j, s, p, n)

A helper routine used for manipulating stabilizer state representations.

colsum_acc(acc_s, acc_p, j, s, p, n)

A helper routine used for manipulating stabilizer state representations.

stabilizer_measurement_prob(state_sp_tuple, moutcomes, qubit_filter=None, return_state=False)

Compute the probability of a given outcome when measuring some or all of the qubits in a stabilizer state.

embed_clifford(s, p, qubit_inds, n)

Embeds the (s,p) Clifford symplectic representation into a larger symplectic representation.

compute_internal_gate_symplectic_representations(gllist=None)

Creates a dictionary of the symplectic representations of 'standard' Clifford gates.

symplectic_rep_of_clifford_circuit(circuit, srep_dict=None, pspec=None)

Returns the symplectic representation of the composite Clifford implemented by the specified Clifford circuit.

symplectic_rep_of_clifford_layer(layer, n=None, q_labels=None, srep_dict=None, add_internal_sreps=True)

Constructs the symplectic representation of the n-qubit Clifford implemented by a single quantum circuit layer.

one_q_clifford_symplectic_group_relations()

Gives the group relationship between the 'I', 'H', 'P' 'HP', 'PH', and 'HPH' up-to-Paulis operators.

unitary_is_clifford(unitary)

Returns True if the unitary is a Clifford gate (w.r.t the standard basis), and False otherwise.

_unitary_to_symplectic_1q(u, flagnonclifford=True)

Returns the symplectic representation of a single qubit Clifford unitary,

_unitary_to_symplectic_2q(u, flagnonclifford=True)

Returns the symplectic representation of a two-qubit Clifford unitary,

unitary_to_symplectic(u, flagnonclifford=True)

Returns the symplectic representation of a one-qubit or two-qubit Clifford unitary.

random_symplectic_matrix(n, convention='standard', rand_state=None)

Returns a symplectic matrix of dimensions 2n x 2n sampled uniformly at random from the symplectic group S(n).

random_clifford(n, rand_state=None)

Returns a Clifford, in the symplectic representation, sampled uniformly at random from the n-qubit Clifford group.

random_phase_vector(s, n, rand_state=None)

Generates a uniformly random phase vector for a n-qubit Clifford.

bitstring_for_pauli(p)

Get the bitstring corresponding to a Pauli.

apply_internal_gate_to_symplectic(s, gate_name, qindex_list, optype='row')

Applies a Clifford gate to the n-qubit Clifford gate specified by the 2n x 2n symplectic matrix.

compute_num_cliffords(n)

The number of Clifford gates in the n-qubit Clifford group.

compute_num_symplectics(n)

The number of elements in the symplectic group S(n) over the 2-element finite field.

compute_num_cosets(n)

Returns the number of different cosets for the symplectic group S(n) over the 2-element finite field.

symplectic_innerproduct(v, w)

Returns the symplectic inner product of two vectors in F_2^(2n).

symplectic_transvection(k, v)

Applies transvection Z k to v.

int_to_bitstring(i, n)

Converts integer i to an length n array of bits.

bitstring_to_int(b, n)

Converts an n-bit string b to an integer between 0 and 2^`n` - 1.

find_symplectic_transvection(x, y)

A utility function for selecting a random Clifford element.

compute_symplectic_matrix(i, n)

Returns the 2n x 2n symplectic matrix, over the finite field containing 0 and 1, with the "canonical" index i.

compute_symplectic_label(gn, n=None)

Returns the "canonical" index of 2n x 2n symplectic matrix gn over the finite field containing 0 and 1.

random_symplectic_index(n, rand_state=None)

The index of a uniformly random 2n x 2n symplectic matrix over the finite field containing 0 and 1.

Attributes

_basis_constructor_dict

gmvec_to_stdmx

ppvec_to_stdmx

qtvec_to_stdmx

stdvec_to_stdmx

stdmx_to_ppvec

stdmx_to_gmvec

stdmx_to_stdvec

TOL

_fastcalc

EXPM_DEFAULT_TOL

IMAG_TOL

id2x2

sigmax

sigmay

sigmaz

sigmaii

sigmaix

sigmaiy

sigmaiz

sigmaxi

sigmaxx

sigmaxy

sigmaxz

sigmayi

sigmayx

sigmayy

sigmayz

sigmazi

sigmazx

sigmazy

sigmazz

_fastcalc

pygsti.tools._basis_constructor_dict
pygsti.tools.basis_matrices(name_or_basis, dim, sparse=False)

Get the elements of the specifed basis-type which spans the density-matrix space given by dim.

Parameters
  • name_or_basis ({'std', 'gm', 'pp', 'qt'} or Basis) – The basis type. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt). If a Basis object, then the basis matrices are contained therein, and its dimension is checked to match dim.

  • dim (int) – The dimension of the density-matrix space.

  • sparse (bool, optional) – Whether any built matrices should be SciPy CSR sparse matrices or dense numpy arrays (the default).

Returns

list – A list of N numpy arrays each of shape (dmDim, dmDim), where dmDim is the matrix-dimension of the overall “embedding” density matrix (the sum of dim_or_block_dims) and N is the dimension of the density-matrix space, equal to sum( block_dim_i^2 ).

pygsti.tools.basis_longname(basis)

Get the “long name” for a particular basis, which is typically used in reports, etc.

Parameters

basis (Basis or str) – The basis or standard-basis-name.

Returns

string

pygsti.tools.basis_element_labels(basis, dim)

Get a list of short labels corresponding to to the elements of the described basis.

These labels are typically used to label the rows/columns of a box-plot of a matrix in the basis.

Parameters
  • basis ({'std', 'gm', 'pp', 'qt'}) – Which basis the model is represented in. Allowed options are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp) and Qutrit (qt). If the basis is not known, then an empty list is returned.

  • dim (int or list) – Dimension of basis matrices. If a list of integers, then gives the dimensions of the terms in a direct-sum decomposition of the density matrix space acted on by the basis.

Returns

list of strings – A list of length dim, whose elements label the basis elements.

pygsti.tools.is_sparse_basis(name_or_basis)

Whether a basis contains sparse matrices.

Parameters

name_or_basis (Basis or str) – The basis or standard-basis-name.

Returns

bool

pygsti.tools.change_basis(mx, from_basis, to_basis)

Convert a operation matrix from one basis of a density matrix space to another.

Parameters
  • mx (numpy array) – The operation matrix (a 2D square array) in the from_basis basis.

  • from_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The source basis. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

  • to_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The destination basis. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

Returns

numpy array – The given operation matrix converted to the to_basis basis. Array size is the same as mx.

pygsti.tools.create_basis_pair(mx, from_basis, to_basis)

Constructs bases from transforming mx between two basis names.

Construct a pair of Basis objects with types from_basis and to_basis, and dimension appropriate for transforming mx (if they’re not already given by from_basis or to_basis being a Basis rather than a str).

Parameters
  • mx (numpy.ndarray) – A matrix, assumed to be square and have a dimension that is a perfect square.

  • from_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The source basis (named because it’s usually the source basis for a basis change). Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). If a custom basis object is provided, it’s dimension should be equal to sqrt(mx.shape[0]) == sqrt(mx.shape[1]).

  • to_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The destination basis (named because it’s usually the destination basis for a basis change). Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). If a custom basis object is provided, it’s dimension should be equal to sqrt(mx.shape[0]) == sqrt(mx.shape[1]).

Returns

from_basis, to_basis (Basis)

pygsti.tools.create_basis_for_matrix(mx, basis)

Construct a Basis object with type given by basis and dimension approprate for transforming mx.

Dimension is taken from mx (if it’s not given by basis) that is sqrt(mx.shape[0]).

Parameters
  • mx (numpy.ndarray) – A matrix, assumed to be square and have a dimension that is a perfect square.

  • basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – A basis name or Basis object. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). If a custom basis object is provided, it’s dimension must equal sqrt(mx.shape[0]), as this will be checked.

Returns

Basis

pygsti.tools.resize_std_mx(mx, resize, std_basis_1, std_basis_2)

Change the basis of mx to a potentially larger or smaller ‘std’-type basis given by std_basis_2.

(mx is assumed to be in the ‘std’-type basis given by std_basis_1.)

This is possible when the two ‘std’-type bases have the same “embedding dimension”, equal to the sum of their block dimensions. If, for example, std_basis_1 has block dimensions (kite structure) of (4,2,1) then mx, expressed as a sum of 4^2 + 2^2 + 1^2 = 21 basis elements, can be “embedded” within a larger ‘std’ basis having a single block with dimension 7 (7^2 = 49 elements).

When std_basis_2 is smaller than std_basis_1 the reverse happens and mx is irreversibly truncated, or “contracted” to a basis having a particular kite structure.

Parameters
  • mx (numpy array) – A square matrix in the std_basis_1 basis.

  • resize ({'expand','contract'}) – Whether mx can be expanded or contracted.

  • std_basis_1 (Basis) – The ‘std’-type basis that mx is currently in.

  • std_basis_2 (Basis) – The ‘std’-type basis that mx should be converted to.

Returns

numpy.ndarray

pygsti.tools.flexible_change_basis(mx, start_basis, end_basis)

Change mx from start_basis to end_basis allowing embedding expansion and contraction if needed.

(see resize_std_mx() for more details).

Parameters
  • mx (numpy array) – The operation matrix (a 2D square array) in the start_basis basis.

  • start_basis (Basis) – The source basis.

  • end_basis (Basis) – The destination basis.

Returns

numpy.ndarray

pygsti.tools.resize_mx(mx, dim_or_block_dims=None, resize=None)

Wrapper for resize_std_mx(), that manipulates mx to be in another basis.

This function first constructs two ‘std’-type bases using dim_or_block_dims and sum(dim_or_block_dims). The matrix mx is converted from the former to the latter when resize == “expand”, and from the latter to the former when resize == “contract”.

Parameters
  • mx (numpy array) – Matrix of size N x N, where N is the dimension of the density matrix space, i.e. sum( dimOrBlockDims_i^2 )

  • dim_or_block_dims (int or list of ints) – Structure of the density-matrix space. Gives the matrix dimensions of each block.

  • resize ({'expand','contract'}) – Whether mx should be expanded or contracted.

Returns

numpy.ndarray

pygsti.tools.state_to_stdmx(state_vec)

Convert a state vector into a density matrix.

Parameters

state_vec (list or tuple) – State vector in the standard (sigma-z) basis.

Returns

numpy.ndarray – A density matrix of shape (d,d), corresponding to the pure state given by the length-d array, state_vec.

pygsti.tools.state_to_pauli_density_vec(state_vec)

Convert a single qubit state vector into a Liouville vector in the Pauli basis.

Parameters

state_vec (list or tuple) – State vector in the sigma-z basis, len(state_vec) == 2

Returns

numpy array – The 2x2 density matrix of the pure state given by state_vec, given as a 4x1 column vector in the Pauli basis.

pygsti.tools.vec_to_stdmx(v, basis, keep_complex=False)

Convert a vector in this basis to a matrix in the standard basis.

Parameters
  • v (numpy array) – The vector length 4 or 16 respectively.

  • basis ({'std', 'gm', 'pp', 'qt'} or Basis) – The basis type. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt). If a Basis object, then the basis matrices are contained therein, and its dimension is checked to match v.

  • keep_complex (bool, optional) – If True, leave the final (output) array elements as complex numbers when v is complex. Usually, the final elements are real (even though v is complex) and so when keep_complex=False the elements are forced to be real and the returned array is float (not complex) valued.

Returns

numpy array – The matrix, 2x2 or 4x4 depending on nqubits

pygsti.tools.gmvec_to_stdmx
pygsti.tools.ppvec_to_stdmx
pygsti.tools.qtvec_to_stdmx
pygsti.tools.stdvec_to_stdmx
pygsti.tools.stdmx_to_vec(m, basis)

Convert a matrix in the standard basis to a vector in the Pauli basis.

Parameters
  • m (numpy array) – The matrix, shape 2x2 (1Q) or 4x4 (2Q)

  • basis ({'std', 'gm', 'pp', 'qt'} or Basis) – The basis type. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt). If a Basis object, then the basis matrices are contained therein, and its dimension is checked to match m.

Returns

numpy array – The vector, length 4 or 16 respectively.

pygsti.tools.stdmx_to_ppvec
pygsti.tools.stdmx_to_gmvec
pygsti.tools.stdmx_to_stdvec
pygsti.tools._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.tools.chi2(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(- 10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Computes the total (aggregate) chi^2 for a set of circuits.

The chi^2 test statistic obtained by summing up the contributions of a given set of circuits or all the circuits available in a dataset. For the gradient or Hessian, see the :function:`chi2_jacobian` and :function:`chi2_hessian` functions.

Parameters
  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi^2 sum. Default value (None) means “all strings in dataset”.

  • min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by the model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

chi2 (float) – chi^2 value, equal to the sum of chi^2 terms from all specified circuits

pygsti.tools.chi2_per_circuit(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(- 10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Computes the per-circuit chi^2 contributions for a set of cirucits.

This function returns the same value as chi2() except the contributions from different circuits are not summed but returned as an array (the contributions of all the outcomes of a given cirucit are summed together).

Parameters
  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi^2 sum. Default value (None) means “all strings in dataset”.

  • min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by the model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

chi2 (numpy.ndarray) – Array of length either len(circuits) or len(dataset.keys()). Values are the chi2 contributions of the corresponding circuit aggregated over outcomes.

pygsti.tools.chi2_jacobian(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(- 10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the gradient of the chi^2 function computed by :function:`chi2`.

The returned value holds the derivatives of the chi^2 function with respect to model’s parameters.

Parameters
  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi^2 sum. Default value (None) means “all strings in dataset”.

  • min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by the model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

numpy array – The gradient vector of length model.num_params, the number of model parameters.

pygsti.tools.chi2_hessian(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(- 10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the Hessian matrix of the chi2() function.

Parameters
  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi^2 sum. Default value (None) means “all strings in dataset”.

  • min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by the model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

numpy array – The Hessian matrix of shape (nModelParams, nModelParams), where nModelParams = model.num_params.

pygsti.tools.chi2_approximate_hessian(model, dataset, circuits=None, min_prob_clip_for_weighting=0.0001, prob_clip_interval=(- 10000, 10000), op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute and approximate Hessian matrix of the chi2() function.

This approximation neglects terms proportional to the Hessian of the probabilities w.r.t. the model parameters (which can take a long time to compute). See logl_approximate_hessian for details on the analogous approximation for the log-likelihood Hessian.

Parameters
  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi^2 sum. Default value (None) means “all strings in dataset”.

  • min_prob_clip_for_weighting (float, optional) – defines the clipping interval for the statistical weight.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by the model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

numpy array – The Hessian matrix of shape (nModelParams, nModelParams), where nModelParams = model.num_params.

pygsti.tools.chialpha(alpha, model, dataset, circuits=None, pfratio_stitchpt=0.01, pfratio_derivpt=0.01, prob_clip_interval=(- 10000, 10000), radius=None, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the chi-alpha objective function.

Parameters
  • alpha (float) – The alpha parameter, which lies in the interval (0,1].

  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi-alpha sum. Default value (None) means “all strings in dataset”.

  • pfratio_stitchpt (float, optional) – The x-value (x = probility/frequency ratio) below which the chi-alpha function is replaced with it second-order Taylor expansion.

  • pfratio_derivpt (float, optional) – The x-value at which the Taylor expansion derivatives are evaluated at.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • radius (float, optional) – If radius is not None then a “harsh” method of regularizing the zero-frequency terms (where the local function = N*p) is used. If radius is None, then fmin is used to handle the zero-frequency terms.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

float

pygsti.tools.chialpha_per_circuit(alpha, model, dataset, circuits=None, pfratio_stitchpt=0.01, pfratio_derivpt=0.01, prob_clip_interval=(- 10000, 10000), radius=None, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None)

Compute the per-circuit chi-alpha objective function.

Parameters
  • alpha (float) – The alpha parameter, which lies in the interval (0,1].

  • model (Model) – The model used to specify the probabilities and SPAM labels

  • dataset (DataSet) – The data used to specify frequencies and counts

  • circuits (list of Circuits or tuples, optional) – List of circuits whose terms will be included in chi-alpha sum. Default value (None) means “all strings in dataset”.

  • pfratio_stitchpt (float, optional) – The x-value (x = probility/frequency ratio) below which the chi-alpha function is replaced with it second-order Taylor expansion.

  • pfratio_derivpt (float, optional) – The x-value at which the Taylor expansion derivatives are evaluated at.

  • prob_clip_interval (tuple, optional) – A (min, max) tuple that specifies the minium (possibly negative) and maximum values allowed for probabilities generated by model. If the model gives probabilities outside this range they are clipped to min or max. These values can be quite generous, as the optimizers are quite tolerant of badly behaved probabilities.

  • radius (float, optional) – If radius is not None then a “harsh” method of regularizing the zero-frequency terms (where the local function = N*p) is used. If radius is None, then fmin is used to handle the zero-frequency terms.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

numpy.ndarray – Array of length either len(circuits) or len(dataset.keys()). Values are the chi-alpha contributions of the corresponding circuit aggregated over outcomes.

pygsti.tools.chi2fn_2outcome(n, p, f, min_prob_clip_for_weighting=0.0001)

Computes chi^2 for a 2-outcome measurement.

The chi-squared function for a 2-outcome measurement using a clipped probability for the statistical weighting.

Parameters
  • n (float or numpy array) – Number of samples.

  • p (float or numpy array) – Probability of 1st outcome (typically computed).

  • f (float or numpy array) – Frequency of 1st outcome (typically observed).

  • min_prob_clip_for_weighting (float, optional) – Defines clipping interval (see return value).

Returns

float or numpy array – n(p-f)^2 / (cp(1-cp)), where cp is the value of p clipped to the interval (min_prob_clip_for_weighting, 1-min_prob_clip_for_weighting)

pygsti.tools.chi2fn_2outcome_wfreqs(n, p, f)

Computes chi^2 for a 2-outcome measurement using frequency-weighting.

The chi-squared function for a 2-outcome measurement using the observed frequency in the statistical weight.

Parameters
  • n (float or numpy array) – Number of samples.

  • p (float or numpy array) – Probability of 1st outcome (typically computed).

  • f (float or numpy array) – Frequency of 1st outcome (typically observed).

Returns

float or numpy array – n(p-f)^2 / (f*(1-f*)), where f* = (f*n+1)/n+2 is the frequency value used in the statistical weighting (prevents divide by zero errors)

pygsti.tools.chi2fn(n, p, f, min_prob_clip_for_weighting=0.0001)

Computes the chi^2 term corresponding to a single outcome.

The chi-squared term for a single outcome of a multi-outcome measurement using a clipped probability for the statistical weighting.

Parameters
  • n (float or numpy array) – Number of samples.

  • p (float or numpy array) – Probability of 1st outcome (typically computed).

  • f (float or numpy array) – Frequency of 1st outcome (typically observed).

  • min_prob_clip_for_weighting (float, optional) – Defines clipping interval (see return value).

Returns

float or numpy array – n(p-f)^2 / cp , where cp is the value of p clipped to the interval (min_prob_clip_for_weighting, 1-min_prob_clip_for_weighting)

pygsti.tools.chi2fn_wfreqs(n, p, f, min_freq_clip_for_weighting=0.0001)

Computes the frequency-weighed chi^2 term corresponding to a single outcome.

The chi-squared term for a single outcome of a multi-outcome measurement using the observed frequency in the statistical weight.

Parameters
  • n (float or numpy array) – Number of samples.

  • p (float or numpy array) – Probability of 1st outcome (typically computed).

  • f (float or numpy array) – Frequency of 1st outcome (typically observed).

  • min_freq_clip_for_weighting (float, optional) – The minimum frequency weighting used in the weighting, i.e. the largest weighting factor is 1 / fmin_freq_clip_for_weighting.

Returns

float or numpy array

pygsti.tools.bonferroni_correction(significance, numtests)

Calculates the standard Bonferroni correction.

This is used for reducing the “local” significance for > 1 statistical hypothesis test to guarantee maintaining a “global” significance (i.e., a family-wise error rate) of significance.

Parameters
  • significance (float) – Significance of each individual test.

  • numtests (int) – The number of hypothesis tests performed.

Returns

  • The Boferroni-corrected local significance, given by

  • significance / numtests.

pygsti.tools.sidak_correction(significance, numtests)

Sidak correction.

TODO: docstring - better explanaition

Parameters
  • significance (float) – Significance of each individual test.

  • numtests (int) – The number of hypothesis tests performed.

Returns

float

pygsti.tools.generalized_bonferroni_correction(significance, weights, numtests=None, nested_method='bonferroni', tol=1e-10)

Generalized Bonferroni correction.

Parameters
  • significance (float) – Significance of each individual test.

  • weights (array-like) – An array of non-negative floating-point weights, one per individual test, that sum to 1.0.

  • numtests (int) – The number of hypothesis tests performed.

  • nested_method ({'bonferroni', 'sidak'}) – Which method is used to find the significance of the composite test.

  • tol (float, optional) – Tolerance when checking that the weights add to 1.0.

Returns

float

class pygsti.tools._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 vector-element. 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 non-simple 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 2-element 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 length-4 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 length-2 [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 vector-elements) in the basis.

Type

int

elshape

The shape of each element. Typically either a length-1 or length-2 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 direct-sum-of-tensor-product-blocks 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 tensor-product 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 vector-elements) in the basis.

property elshape(self)

The shape of each element. Typically either a length-1 or length-2 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 flattened-element 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 built-in 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 built-in 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_name-analogue of the standard basis that this basis’s elements are expressed in.

Parameters

builtin_basis_name (str, optional) – The name of the built-in 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 component-free version of the same builtin-basis 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

pygsti.tools.jamiolkowski_iso(operation_mx, op_mx_basis='pp', choi_mx_basis='pp')

Given a operation matrix, return the corresponding Choi matrix that is normalized to have trace == 1.

Parameters
  • operation_mx (numpy array) – the operation matrix to compute Choi matrix of.

  • op_mx_basis (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).

  • choi_mx_basis (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 – the Choi matrix, normalized to have trace == 1, in the desired basis.

pygsti.tools.jamiolkowski_iso_inv(choi_mx, choi_mx_basis='pp', op_mx_basis='pp')

Given a choi matrix, return the corresponding operation matrix.

This function performs the inverse of :function:`jamiolkowski_iso`.

Parameters
  • choi_mx (numpy array) – the Choi matrix, normalized to have trace == 1, to compute operation matrix for.

  • choi_mx_basis (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).

  • op_mx_basis (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 – operation matrix in the desired basis.

pygsti.tools.fast_jamiolkowski_iso_std(operation_mx, op_mx_basis)

The corresponding Choi matrix in the standard basis that is normalized to have trace == 1.

This routine only computes the case of the Choi matrix being in the standard (matrix unit) basis, but does so more quickly than jamiolkowski_iso() and so is particuarly useful when only the eigenvalues of the Choi matrix are needed.

Parameters
  • operation_mx (numpy array) – the operation matrix to compute Choi matrix of.

  • op_mx_basis (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 – the Choi matrix, normalized to have trace == 1, in the std basis.

pygsti.tools.fast_jamiolkowski_iso_std_inv(choi_mx, op_mx_basis)

Given a choi matrix in the standard basis, return the corresponding operation matrix.

This function performs the inverse of :function:`fast_jamiolkowski_iso_std`.

Parameters
  • choi_mx (numpy array) – the Choi matrix in the standard (matrix units) basis, normalized to have trace == 1, to compute operation matrix for.

  • op_mx_basis (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 – operation matrix in the desired basis.

pygsti.tools.sum_of_negative_choi_eigenvalues(model, weights=None)

Compute the amount of non-CP-ness of a model.

This is defined (somewhat arbitarily) by summing the negative eigenvalues of the Choi matrix for each gate in model.

Parameters
  • model (Model) – The model to act on.

  • weights (dict) – A dictionary of weights used to multiply the negative eigenvalues of different gates. Keys are operation labels, values are floating point numbers.

Returns

float – the sum of negative eigenvalues of the Choi matrix for each gate.

pygsti.tools.sums_of_negative_choi_eigenvalues(model)

Compute the amount of non-CP-ness of a model.

This is defined (somewhat arbitarily) by summing the negative eigenvalues of the Choi matrix for each gate in model separately. This function is different from :function:`sum_of_negative_choi_eigenvalues` in that it returns sums separately for each operation of model.

Parameters

model (Model) – The model to act on.

Returns

list of floats – each element == sum of the negative eigenvalues of the Choi matrix for the corresponding gate (as ordered by model.operations.iteritems()).

pygsti.tools.magnitudes_of_negative_choi_eigenvalues(model)

Compute the magnitudes of the negative eigenvalues of the Choi matricies for each gate in model.

Parameters

model (Model) – The model to act on.

Returns

list of floats – list of the magnitues of all negative Choi eigenvalues. The length of this list will vary based on how many negative eigenvalues are found, as positive eigenvalues contribute nothing to this list.

pygsti.tools.warn_deprecated(name, replacement=None)

Formats and prints a deprecation warning message.

Parameters
  • name (str) – The name of the function that is now deprecated.

  • replacement (str, optional) – the name of the function that should replace it.

Returns

None

pygsti.tools.deprecate(replacement=None)

Decorator for deprecating a function.

Parameters

replacement (str, optional) – the name of the function that should replace it.

Returns

function

pygsti.tools.deprecate_imports(module_name, replacement_map, warning_msg)

Utility to deprecate imports from a module.

This works by swapping the underlying module in the import mechanisms with a ModuleType object that overrides attribute lookup to check against the replacement map.

Note that this will slow down module attribute lookup substantially. If you need to deprecate multiple names, DO NOT call this method more than once on a given module! Instead, use the replacement map to batch multiple deprecations into one call. When using this method, plan to remove the deprecated paths altogether sooner rather than later.

Parameters
  • module_name (str) – The fully-qualified name of the module whose names have been deprecated.

  • replacement_map ({name: function}) – A map of each deprecated name to a factory which will be called with no arguments when importing the name.

  • warning_msg (str) – A message to be displayed as a warning when importing a deprecated name. Optionally, this may include the format string name, which will be formatted with the deprecated name.

Returns

None

pygsti.tools.TOL = 1e-20
pygsti.tools.logl(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, wildcard=None, mdc_store=None, comm=None, mem_limit=None)

The log-likelihood function.

Parameters
  • model (Model) – Model of parameterized gates

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the log-likelihood-in-the-Poisson-picture terms should be included in the returned logl value.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • wildcard (WildcardBudget) – A wildcard budget to apply to this log-likelihood computation. This increases the returned log-likelihood value by adjusting (by a maximal amount measured in TVD, given by the budget) the probabilities produced by model to optimially match the data (within the bugetary constraints) evaluating the log-likelihood.

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

float – The log likelihood

pygsti.tools.logl_per_circuit(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, wildcard=None, mdc_store=None, comm=None, mem_limit=None)

Computes the per-circuit log-likelihood contribution for a set of circuits.

Parameters
  • model (Model) – Model of parameterized gates

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the log-likelihood-in-the-Poisson-picture terms should be included in the returned logl value.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • wildcard (WildcardBudget) – A wildcard budget to apply to this log-likelihood computation. This increases the returned log-likelihood value by adjusting (by a maximal amount measured in TVD, given by the budget) the probabilities produced by model to optimially match the data (within the bugetary constraints) evaluating the log-likelihood.

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

Returns

numpy.ndarray – Array of length either len(circuits) or len(dataset.keys()). Values are the log-likelihood contributions of the corresponding circuit aggregated over outcomes.

pygsti.tools.logl_jacobian(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None, verbosity=0)

The jacobian of the log-likelihood function.

Parameters
  • model (Model) – Model of parameterized gates (including SPAM)

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the Poisson-picutre log-likelihood should be differentiated.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

  • verbosity (int, optional) – How much detail to print to stdout.

Returns

numpy array – array of shape (M,), where M is the length of the vectorized model.

pygsti.tools.logl_hessian(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None, verbosity=0)

The hessian of the log-likelihood function.

Parameters
  • model (Model) – Model of parameterized gates (including SPAM)

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the Poisson-picutre log-likelihood should be differentiated.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

  • verbosity (int, optional) – How much detail to print to stdout.

Returns

numpy array – array of shape (M,M), where M is the length of the vectorized model.

pygsti.tools.logl_approximate_hessian(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None, verbosity=0)

An approximate Hessian of the log-likelihood function.

An approximation to the true Hessian is computed using just the Jacobian (and not the Hessian) of the probabilities w.r.t. the model parameters. Let J = d(probs)/d(params) and denote the Hessian of the log-likelihood w.r.t. the probabilities as d2(logl)/dprobs2 (a diagonal matrix indexed by the term, i.e. probability, of the log-likelihood). Then this function computes:

H = J * d2(logl)/dprobs2 * J.T

Which simply neglects the d2(probs)/d(params)2 terms of the true Hessian. Since this curvature is expected to be small at the MLE point, this approximation can be useful for computing approximate error bars.

Parameters
  • model (Model) – Model of parameterized gates (including SPAM)

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the Poisson-picutre log-likelihood should be differentiated.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • mem_limit (int, optional) – A rough memory limit in bytes which restricts the amount of intermediate values that are computed and stored.

  • verbosity (int, optional) – How much detail to print to stdout.

Returns

numpy array – array of shape (M,M), where M is the length of the vectorized model.

pygsti.tools.logl_max(model, dataset, circuits=None, poisson_picture=True, op_label_aliases=None, mdc_store=None)

The maximum log-likelihood possible for a DataSet.

That is, the log-likelihood obtained by a maximal model that can fit perfectly the probability of each circuit.

Parameters
  • model (Model) – the model, used only for circuit compilation

  • dataset (DataSet) – the data set to use.

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the max-log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • poisson_picture (boolean, optional) – Whether the Poisson-picture maximum log-likelihood should be returned.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

Returns

float

pygsti.tools.logl_max_per_circuit(model, dataset, circuits=None, poisson_picture=True, op_label_aliases=None, mdc_store=None)

The vector of maximum log-likelihood contributions for each circuit, aggregated over outcomes.

Parameters
  • model (Model) – the model, used only for circuit compilation

  • dataset (DataSet) – the data set to use.

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the max-log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • poisson_picture (boolean, optional) – Whether the Poisson-picture maximum log-likelihood should be returned.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

Returns

numpy.ndarray – Array of length either len(circuits) or len(dataset.keys()). Values are the maximum log-likelihood contributions of the corresponding circuit aggregated over outcomes.

pygsti.tools.two_delta_logl_nsigma(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, dof_calc_method='modeltest', wildcard=None)

See docstring for :function:`pygsti.tools.two_delta_logl`

Parameters
  • model (Model) – Model of parameterized gates

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the log-likelihood-in-the-Poisson-picture terms should be included in the returned logl value.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • dof_calc_method ({"all", "modeltest"}) – How model’s number of degrees of freedom (parameters) are obtained when computing the number of standard deviations and p-value relative to a chi2_k distribution, where k is additional degrees of freedom possessed by the maximal model. “all” uses model.num_params whereas “modeltest” uses model.num_modeltest_params (the number of non-gauge parameters by default).

  • wildcard (WildcardBudget) – A wildcard budget to apply to this log-likelihood computation. This increases the returned log-likelihood value by adjusting (by a maximal amount measured in TVD, given by the budget) the probabilities produced by model to optimially match the data (within the bugetary constraints) evaluating the log-likelihood.

Returns

float

pygsti.tools.two_delta_logl(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, dof_calc_method=None, wildcard=None, mdc_store=None, comm=None)

Twice the difference between the maximum and actual log-likelihood.

Optionally also can return the Nsigma (# std deviations from mean) and p-value relative to expected chi^2 distribution (when dof_calc_method is not None).

This function’s arguments are supersets of :function:`logl`, and :function:`logl_max`. This is a convenience function, equivalent to 2*(logl_max(…) - logl(…)), whose value is what is often called the log-likelihood-ratio between the “maximal model” (that which trivially fits the data exactly) and the model given by model.

Parameters
  • model (Model) – Model of parameterized gates

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the log-likelihood-in-the-Poisson-picture terms should be included in the computed log-likelihood values.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • dof_calc_method ({None, "all", "modeltest"}) – How model’s number of degrees of freedom (parameters) are obtained when computing the number of standard deviations and p-value relative to a chi2_k distribution, where k is additional degrees of freedom possessed by the maximal model. If None, then Nsigma and pvalue are not returned (see below).

  • wildcard (WildcardBudget) – A wildcard budget to apply to this log-likelihood computation. This increases the returned log-likelihood value by adjusting (by a maximal amount measured in TVD, given by the budget) the probabilities produced by model to optimially match the data (within the bugetary constraints) evaluating the log-likelihood.

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

Returns

  • twoDeltaLogL (float) – 2*(loglikelihood(maximal_model,data) - loglikelihood(model,data))

  • Nsigma, pvalue (float) – Only returned when dof_calc_method is not None.

pygsti.tools.two_delta_logl_per_circuit(model, dataset, circuits=None, min_prob_clip=1e-06, prob_clip_interval=(- 1000000.0, 1000000.0), radius=0.0001, poisson_picture=True, op_label_aliases=None, dof_calc_method=None, wildcard=None, mdc_store=None, comm=None)

Twice the per-circuit difference between the maximum and actual log-likelihood.

Contributions are aggregated over each circuit’s outcomes, but no further.

Optionally (when dof_calc_method is not None) returns parallel vectors containing the Nsigma (# std deviations from mean) and the p-value relative to expected chi^2 distribution for each sequence.

Parameters
  • model (Model) – Model of parameterized gates

  • dataset (DataSet) – Probability data

  • circuits (list of (tuples or Circuits), optional) – Each element specifies a circuit to include in the log-likelihood sum. Default value of None implies all the circuits in dataset should be used.

  • min_prob_clip (float, optional) – The minimum probability treated normally in the evaluation of the log-likelihood. A penalty function replaces the true log-likelihood for probabilities that lie below this threshold so that the log-likelihood never becomes undefined (which improves optimizer performance).

  • prob_clip_interval (2-tuple or None, optional) – (min,max) values used to clip the probabilities predicted by models during MLEGST’s search for an optimal model (if not None). if None, no clipping is performed.

  • radius (float, optional) – Specifies the severity of rounding used to “patch” the zero-frequency terms of the log-likelihood.

  • poisson_picture (boolean, optional) – Whether the log-likelihood-in-the-Poisson-picture terms should be included in the returned logl value.

  • op_label_aliases (dictionary, optional) – Dictionary whose keys are operation label “aliases” and whose values are tuples corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined) e.g. op_label_aliases[‘Gx^3’] = (‘Gx’,’Gx’,’Gx’)

  • dof_calc_method ({"all", "modeltest"}) – How model’s number of degrees of freedom (parameters) are obtained when computing the number of standard deviations and p-value relative to a chi2_k distribution, where k is additional degrees of freedom possessed by the maximal model.

  • wildcard (WildcardBudget) – A wildcard budget to apply to this log-likelihood computation. This increases the returned log-likelihood value by adjusting (by a maximal amount measured in TVD, given by the budget) the probabilities produced by model to optimially match the data (within the bugetary constraints) evaluating the log-likelihood.

  • mdc_store (ModelDatasetCircuitsStore, optional) – An object that bundles cached quantities along with a given model, dataset, and circuit list. If given, model and dataset and circuits should be set to None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

Returns

  • twoDeltaLogL_terms (numpy.ndarray)

  • Nsigma, pvalue (numpy.ndarray) – Only returned when dof_calc_method is not None.

pygsti.tools.two_delta_logl_term(n, p, f, min_prob_clip=1e-06, poisson_picture=True)

Term of the 2*[log(L)-upper-bound - log(L)] sum corresponding to a single circuit and spam label.

Parameters
  • n (float or numpy array) – Number of samples.

  • p (float or numpy array) – Probability of 1st outcome (typically computed).

  • f (float or numpy array) – Frequency of 1st outcome (typically observed).

  • min_prob_clip (float, optional) – Minimum probability clip point to avoid evaluating log(number <= zero)

  • poisson_picture (boolean, optional) – Whether the log-likelihood-in-the-Poisson-picture terms should be included in the returned logl value.

Returns

float or numpy array

pygsti.tools.basis_matrices(name_or_basis, dim, sparse=False)

Get the elements of the specifed basis-type which spans the density-matrix space given by dim.

Parameters
  • name_or_basis ({'std', 'gm', 'pp', 'qt'} or Basis) – The basis type. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt). If a Basis object, then the basis matrices are contained therein, and its dimension is checked to match dim.

  • dim (int) – The dimension of the density-matrix space.

  • sparse (bool, optional) – Whether any built matrices should be SciPy CSR sparse matrices or dense numpy arrays (the default).

Returns

list – A list of N numpy arrays each of shape (dmDim, dmDim), where dmDim is the matrix-dimension of the overall “embedding” density matrix (the sum of dim_or_block_dims) and N is the dimension of the density-matrix space, equal to sum( block_dim_i^2 ).

pygsti.tools.hamiltonian_to_lindbladian(hamiltonian, sparse=False)

Construct the Lindbladian corresponding to a given Hamiltonian.

Mathematically, for a d-dimensional Hamiltonian matrix H, this routine constructs the d^2-dimension Lindbladian matrix L whose action is given by L(rho) = -1j*sqrt(d)/2*[ H, rho ], where square brackets denote the commutator and rho is a density matrix. L is returned as a superoperator matrix that acts on a vectorized density matrices.

Parameters
  • hamiltonian (ndarray) – The hamiltonian matrix used to construct the Lindbladian.

  • sparse (bool, optional) – Whether to construct a sparse or dense (the default) matrix.

Returns

ndarray or Scipy CSR matrix

pygsti.tools.stochastic_lindbladian(q, sparse=False)

Construct the Lindbladian corresponding to stochastic q-errors.

Mathematically, for a d-dimensional matrix q, this routine constructs the d^2-dimension Lindbladian matrix L whose action is given by L(rho) = q*rho*q^dag where rho is a density matrix. L is returned as a superoperator matrix that acts on a vectorized density matrices.

Parameters
  • q (ndarray) – The matrix used to construct the Lindbladian.

  • sparse (bool, optional) – Whether to construct a sparse or dense (the default) matrix.

Returns

ndarray or Scipy CSR matrix

pygsti.tools.affine_lindbladian(q, sparse=False)

Construct the Lindbladian corresponding to affine q-errors.

Mathematically, for a d-dimensional matrix q, this routine constructs the d^2-dimension Lindbladian matrix L whose action is given by L(rho) = q where rho is a density matrix. L is returned as a superoperator matrix that acts on a vectorized density matrices.

Parameters
  • q (ndarray) – The matrix used to construct the Lindbladian.

  • sparse (bool, optional) – Whether to construct a sparse or dense (the default) matrix.

Returns

ndarray or Scipy CSR matrix

pygsti.tools.nonham_lindbladian(Lm, Ln, sparse=False)

Construct the Lindbladian corresponding to generalized non-Hamiltonian (stochastic) errors.

Mathematically, for d-dimensional matrices Lm and Ln, this routine constructs the d^2-dimension Lindbladian matrix L whose action is given by:

L(rho) = Ln*rho*Lm^dag - 1/2(rho*Lm^dag*Ln + Lm^dag*Ln*rho)

where rho is a density matrix. L is returned as a superoperator matrix that acts on a vectorized density matrices.

Parameters
  • Lm (numpy.ndarray) – d-dimensional matrix.

  • Ln (numpy.ndarray) – d-dimensional matrix.

  • sparse (bool, optional) – Whether to construct a sparse or dense (the default) matrix.

Returns

ndarray or Scipy CSR matrix

pygsti.tools.remove_duplicates_in_place(l, index_to_test=None)

Remove duplicates from the list passed as an argument.

Parameters
  • l (list) – The list to remove duplicates from.

  • index_to_test (int, optional) – If not None, the index within the elements of l to test. For example, if all the elements of l contain 2 tuples (x,y) then set index_to_test == 1 to remove tuples with duplicate y-values.

Returns

None

pygsti.tools.remove_duplicates(l, index_to_test=None)

Remove duplicates from the a list and return the result.

Parameters
  • l (iterable) – The list/set to remove duplicates from.

  • index_to_test (int, optional) – If not None, the index within the elements of l to test. For example, if all the elements of l contain 2 tuples (x,y) then set index_to_test == 1 to remove tuples with duplicate y-values.

Returns

list – the list after duplicates have been removed.

pygsti.tools.compute_occurrence_indices(lst)

A 0-based list of integers specifying which occurrence, i.e. enumerated duplicate, each list item is.

For example, if lst = [ ‘A’,’B’,’C’,’C’,’A’] then the returned list will be [ 0 , 0 , 0 , 1 , 1 ]. This may be useful when working with DataSet objects that have collisionAction set to “keepseparate”.

Parameters

lst (list) – The list to process.

Returns

list

pygsti.tools.find_replace_tuple(t, alias_dict)

Replace elements of t according to rules in alias_dict.

Parameters
  • t (tuple or list) – The object to perform replacements upon.

  • alias_dict (dictionary) – Dictionary whose keys are potential elements of t and whose values are tuples corresponding to a sub-sequence that the given element should be replaced with. If None, no replacement is performed.

Returns

tuple

pygsti.tools.find_replace_tuple_list(list_of_tuples, alias_dict)

Applies find_replace_tuple() on each element of list_of_tuples.

Parameters
  • list_of_tuples (list) – A list of tuple objects to perform replacements upon.

  • alias_dict (dictionary) – Dictionary whose keys are potential elements of t and whose values are tuples corresponding to a sub-sequence that the given element should be replaced with. If None, no replacement is performed.

Returns

list

pygsti.tools.apply_aliases_to_circuits(list_of_circuits, alias_dict)

Applies alias_dict to the circuits in list_of_circuits.

Parameters
  • list_of_circuits (list) – A list of circuits to make replacements in.

  • alias_dict (dict) – A dictionary whose keys are layer Labels (or equivalent tuples or strings), and whose values are Circuits or tuples of labels.

Returns

list

pygsti.tools.sorted_partitions(n)

Iterate over all sorted (decreasing) partitions of integer n.

A partition of n here is defined as a list of one or more non-zero integers which sum to n. Sorted partitions (those iterated over here) have their integers in decreasing order.

Parameters

n (int) – The number to partition.

pygsti.tools.partitions(n)

Iterate over all partitions of integer n.

A partition of n here is defined as a list of one or more non-zero integers which sum to n. Every partition is iterated over exacty once - there are no duplicates/repetitions.

Parameters

n (int) – The number to partition.

pygsti.tools.partition_into(n, nbins)

Iterate over all partitions of integer n into nbins bins.

Here, unlike in :function:`partition`, a “partition” is allowed to contain zeros. For example, (4,1,0) is a valid partition of 5 using 3 bins. This function fixes the number of bins and iterates over all possible length- nbins partitions while allowing zeros. This is equivalent to iterating over all usual partitions of length at most nbins and inserting zeros into all possible places for partitions of length less than nbins.

Parameters
  • n (int) – The number to partition.

  • nbins (int) – The fixed number of bins, equal to the length of all the partitions that are iterated over.

pygsti.tools._partition_into_slow(n, nbins)

Helper function for partition_into that performs the same task for a general number n.

pygsti.tools.incd_product(*args)

Like itertools.product but returns the first modified (incremented) index along with the product tuple itself.

Parameters

*args (iterables) – Any number of iterable things that we’re taking the product of.

pygsti.tools.dot_mod2(m1, m2)

Returns the product over the integers modulo 2 of two matrices.

Parameters
  • m1 (numpy.ndarray) – First matrix

  • m2 (numpy.ndarray) – Second matrix

Returns

numpy.ndarray

pygsti.tools.multidot_mod2(mlist)

Returns the product over the integers modulo 2 of a list of matrices.

Parameters

mlist (list) – A list of matrices.

Returns

numpy.ndarray

pygsti.tools.det_mod2(m)

Returns the determinant of a matrix over the integers modulo 2 (GL(n,2)).

Parameters

m (numpy.ndarray) – Matrix to take determinant of.

Returns

numpy.ndarray

pygsti.tools.matrix_directsum(m1, m2)

Returns the direct sum of two square matrices of integers.

Parameters
  • m1 (numpy.ndarray) – First matrix

  • m2 (numpy.ndarray) – Second matrix

Returns

numpy.ndarray

pygsti.tools.inv_mod2(m)

Finds the inverse of a matrix over GL(n,2)

Parameters

m (numpy.ndarray) – Matrix to take inverse of.

Returns

numpy.ndarray

pygsti.tools.Axb_mod2(A, b)

Solves Ax = b over GF(2)

Parameters
  • A (numpy.ndarray) – Matrix to operate on.

  • b (numpy.ndarray) – Vector to operate on.

Returns

numpy.ndarray

pygsti.tools.gaussian_elimination_mod2(a)

Gaussian elimination mod2 of a.

Parameters

a (numpy.ndarray) – Matrix to operate on.

Returns

numpy.ndarray

pygsti.tools.diagonal_as_vec(m)

Returns a 1D array containing the diagonal of the input square 2D array m.

Parameters

m (numpy.ndarray) – Matrix to operate on.

Returns

numpy.ndarray

pygsti.tools.strictly_upper_triangle(m)

Returns a matrix containing the strictly upper triangle of m and zeros elsewhere.

Parameters

m (numpy.ndarray) – Matrix to operate on.

Returns

numpy.ndarray

pygsti.tools.diagonal_as_matrix(m)

Returns a diagonal matrix containing the diagonal of m.

Parameters

m (numpy.ndarray) – Matrix to operate on.

Returns

numpy.ndarray

pygsti.tools.albert_factor(d, failcount=0)

Returns a matrix M such that d = M M.T for symmetric d, where d and M are matrices over [0,1] mod 2.

The algorithm mostly follows the proof in “Orthogonal Matrices Over Finite Fields” by Jessie MacWilliams in The American Mathematical Monthly, Vol. 76, No. 2 (Feb., 1969), pp. 152-164

There is generally not a unique albert factorization, and this algorthm is randomized. It will general return a different factorizations from multiple calls.

Parameters
  • d (array-like) – Symmetric matrix mod 2.

  • failcount (int, optional) – UNUSED.

Returns

numpy.ndarray

pygsti.tools.random_bitstring(n, p, failcount=0)

Constructs a random bitstring of length n with parity p

Parameters
  • n (int) – Number of bits.

  • p (int) – Parity.

  • failcount (int, optional) – Internal use only.

Returns

numpy.ndarray

pygsti.tools.random_invertable_matrix(n, failcount=0)

Finds a random invertable matrix M over GL(n,2)

Parameters
  • n (int) – matrix dimension

  • failcount (int, optional) – Internal use only.

Returns

numpy.ndarray

pygsti.tools.random_symmetric_invertable_matrix(n)

Creates a random, symmetric, invertible matrix from GL(n,2)

Parameters

n (int) – Matrix dimension.

Returns

numpy.ndarray

pygsti.tools.onesify(a, failcount=0, maxfailcount=100)

Returns M such that M a M.T has ones along the main diagonal

Parameters
  • a (numpy.ndarray) – The matrix.

  • failcount (int, optional) – Internal use only.

  • maxfailcount (int, optional) – Maximum number of tries before giving up.

Returns

numpy.ndarray

pygsti.tools.permute_top(a, i)

Permutes the first row & col with the i’th row & col

Parameters
  • a (numpy.ndarray) – The matrix to act on.

  • i (int) – index to permute with first row/col.

Returns

numpy.ndarray

pygsti.tools.fix_top(a)

Computes the permutation matrix P such that the [1:t,1:t] submatrix of P a P is invertible.

Parameters

a (numpy.ndarray) – A symmetric binary matrix with ones along the diagonal.

Returns

numpy.ndarray

pygsti.tools.proper_permutation(a)

Computes the permutation matrix P such that all [n:t,n:t] submatrices of P a P are invertible.

Parameters

a (numpy.ndarray) – A symmetric binary matrix with ones along the diagonal.

Returns

numpy.ndarray

pygsti.tools._check_proper_permutation(a)

Check to see if the matrix has been properly permuted.

This should be redundent to what is already built into ‘fix_top’.

Parameters

a (numpy.ndarray) – A matrix.

Returns

bool

pygsti.tools.change_basis(mx, from_basis, to_basis)

Convert a operation matrix from one basis of a density matrix space to another.

Parameters
  • mx (numpy array) – The operation matrix (a 2D square array) in the from_basis basis.

  • from_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The source basis. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

  • to_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The destination basis. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

Returns

numpy array – The given operation matrix converted to the to_basis basis. Array size is the same as mx.

pygsti.tools._fastcalc
pygsti.tools.EXPM_DEFAULT_TOL
pygsti.tools.trace(m)

The trace of a matrix, sum_i m[i,i].

A memory leak in some version of numpy can cause repeated calls to numpy’s trace function to eat up all available system memory, and this function does not have this problem.

Parameters

m (numpy array) – the matrix (any object that can be double-indexed)

Returns

element type of m – The trace of m.

pygsti.tools.is_hermitian(mx, tol=1e-09)

Test whether mx is a hermitian matrix.

Parameters
  • mx (numpy array) – Matrix to test.

  • tol (float, optional) – Tolerance on absolute magitude of elements.

Returns

bool – True if mx is hermitian, otherwise False.

pygsti.tools.is_pos_def(mx, tol=1e-09)

Test whether mx is a positive-definite matrix.

Parameters
  • mx (numpy array) – Matrix to test.

  • tol (float, optional) – Tolerance on absolute magitude of elements.

Returns

bool – True if mx is positive-semidefinite, otherwise False.

pygsti.tools.is_valid_density_mx(mx, tol=1e-09)

Test whether mx is a valid density matrix (hermitian, positive-definite, and unit trace).

Parameters
  • mx (numpy array) – Matrix to test.

  • tol (float, optional) – Tolerance on absolute magitude of elements.

Returns

bool – True if mx is a valid density matrix, otherwise False.

pygsti.tools.frobeniusnorm(ar)

Compute the frobenius norm of an array (or matrix),

sqrt( sum( each_element_of_a^2 ) )

Parameters

ar (numpy array) – What to compute the frobenius norm of. Note that ar can be any shape or number of dimenions.

Returns

float or complex – depending on the element type of ar.

pygsti.tools.frobeniusnorm_squared(ar)

Compute the squared frobenius norm of an array (or matrix),

sum( each_element_of_a^2 ) )

Parameters

ar (numpy array) – What to compute the squared frobenius norm of. Note that ar can be any shape or number of dimenions.

Returns

float or complex – depending on the element type of ar.

pygsti.tools.nullspace(m, tol=1e-07)

Compute the nullspace of a matrix.

Parameters
  • m (numpy array) – An matrix of shape (M,N) whose nullspace to compute.

  • tol (float , optional) – Nullspace tolerance, used when comparing singular values with zero.

Returns

An matrix of shape (M,K) whose columns contain nullspace basis vectors.

pygsti.tools.nullspace_qr(m, tol=1e-07)

Compute the nullspace of a matrix using the QR decomposition.

The QR decomposition is faster but less accurate than the SVD used by nullspace().

Parameters
  • m (numpy array) – An matrix of shape (M,N) whose nullspace to compute.

  • tol (float , optional) – Nullspace tolerance, used when comparing diagonal values of R with zero.

Returns

An matrix of shape (M,K) whose columns contain nullspace basis vectors.

pygsti.tools.nice_nullspace(m, tol=1e-07)

Computes the nullspace of a matrix, and tries to return a “nice” basis for it.

Columns of the returned value (a basis for the nullspace) each have a maximum absolute value of 1.0 and are chosen so as to align with the the original matrix’s basis as much as possible (the basis is found by projecting each original basis vector onto an arbitrariliy-found nullspace and keeping only a set of linearly independent projections).

Parameters
  • m (numpy array) – An matrix of shape (M,N) whose nullspace to compute.

  • tol (float , optional) – Nullspace tolerance, used when comparing diagonal values of R with zero.

Returns

An matrix of shape (M,K) whose columns contain nullspace basis vectors.

pygsti.tools.normalize_columns(m, return_norms=False, ord=None)

Normalizes the columns of a matrix.

Parameters
  • m (numpy.ndarray or scipy sparse matrix) – The matrix.

  • return_norms (bool, optional) – If True, also return a 1D array containing the norms of the columns (before they were normalized).

  • ord (int, optional) – The order of the norm. See :function:`numpy.linalg.norm`.

Returns

  • normalized_m (numpy.ndarray) – The matrix after columns are normalized

  • column_norms (numpy.ndarray) – Only returned when return_norms=True, a 1-dimensional array of the pre-normalization norm of each column.

pygsti.tools.column_norms(m, ord=None)

Compute the norms of the columns of a matrix.

Parameters
Returns

numpy.ndarray – A 1-dimensional array of the column norms (length is number of columns of m).

pygsti.tools.scale_columns(m, scale_values)

Scale each column of a matrix by a given value.

Usually used for normalization purposes, when the matrix columns represent vectors.

Parameters
  • m (numpy.ndarray or scipy sparse matrix) – The matrix.

  • scale_values (numpy.ndarray) – A 1-dimensional array of scale values, one per column of m.

Returns

numpy.ndarray or scipy sparse matrix – A copy of m with scaled columns, possibly with different sparsity structure.

pygsti.tools.columns_are_orthogonal(m, tol=1e-07)

Checks whether a matrix contains orthogonal columns.

The columns do not need to be normalized. In the complex case, two vectors v and w are considered orthogonal if dot(v.conj(), w) == 0.

Parameters
  • m (numpy.ndarray) – The matrix to check.

  • tol (float, optional) – Tolerance for checking whether dot products are zero.

Returns

bool

pygsti.tools.columns_are_orthonormal(m, tol=1e-07)

Checks whether a matrix contains orthogonal columns.

The columns do not need to be normalized. In the complex case, two vectors v and w are considered orthogonal if dot(v.conj(), w) == 0.

Parameters
  • m (numpy.ndarray) – The matrix to check.

  • tol (float, optional) – Tolerance for checking whether dot products are zero.

Returns

bool

pygsti.tools.independent_columns(m, initial_independent_cols=None, tol=1e-07)

Computes the indices of the linearly-independent columns in a matrix.

Optionally starts with a “base” matrix of independent columns, so that the returned indices indicate the columns of m that are independent of all the base columns and the other independent columns of m.

Parameters
  • m (numpy.ndarray or scipy sparse matrix) – The matrix.

  • initial_independent_cols (numpy.ndarray or scipy sparse matrix, optional) – If not None, a matrix of known-to-be independent columns so to test the columns of m with respect to (in addition to the already chosen independent columns of m.

  • tol (float, optional) – Tolerance threshold used to decide whether a singular value is nonzero (it is if it’s is greater than tol).

Returns

list – A list of the independent-column indices of m.

pygsti.tools.pinv_of_matrix_with_orthogonal_columns(m)

TODO: docstring

pygsti.tools.matrix_sign(m)

The “sign” matrix of m

Parameters

m (numpy.ndarray) – the matrix.

Returns

numpy.ndarray

pygsti.tools.print_mx(mx, width=9, prec=4, withbrackets=False)

Print matrix in pretty format.

Will print real or complex matrices with a desired precision and “cell” width.

Parameters
  • mx (numpy array) – the matrix (2-D array) to print.

  • width (int, opitonal) – the width (in characters) of each printed element

  • prec (int optional) – the precision (in characters) of each printed element

  • withbrackets (bool, optional) – whether to print brackets and commas to make the result something that Python can read back in.

Returns

None

pygsti.tools.mx_to_string(m, width=9, prec=4, withbrackets=False)

Generate a “pretty-format” string for a matrix.

Will generate strings for real or complex matrices with a desired precision and “cell” width.

Parameters
  • m (numpy.ndarray) – array to print.

  • width (int, opitonal) – the width (in characters) of each converted element

  • prec (int optional) – the precision (in characters) of each converted element

  • withbrackets (bool, optional) – whether to print brackets and commas to make the result something that Python can read back in.

Returns

string – matrix m as a pretty formated string.

pygsti.tools.mx_to_string_complex(m, real_width=9, im_width=9, prec=4)

Generate a “pretty-format” string for a complex-valued matrix.

Parameters
  • m (numpy array) – array to format.

  • real_width (int, opitonal) – the width (in characters) of the real part of each element.

  • im_width (int, opitonal) – the width (in characters) of the imaginary part of each element.

  • prec (int optional) – the precision (in characters) of each element’s real and imaginary parts.

Returns

string – matrix m as a pretty formated string.

pygsti.tools.unitary_superoperator_matrix_log(m, mx_basis)

Construct the logarithm of superoperator matrix m.

This function assumes that m acts as a unitary on density-matrix space, (m: rho -> U rho Udagger) so that log(m) can be written as the action by Hamiltonian H:

log(m): rho -> -i[H,rho].

Parameters
  • m (numpy array) – The superoperator matrix whose logarithm is taken

  • 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 matrix logM, of the same shape as m, such that m = exp(logM) and logM can be written as the action rho -> -i[H,rho].

pygsti.tools.near_identity_matrix_log(m, tol=1e-08)

Construct the logarithm of superoperator matrix m that is near the identity.

If m is real, the resulting logarithm will be real.

Parameters
  • m (numpy array) – The superoperator matrix whose logarithm is taken

  • tol (float, optional) – The tolerance used when testing for zero imaginary parts.

Returns

numpy array – An matrix logM, of the same shape as m, such that m = exp(logM) and logM is real when m is real.

pygsti.tools.approximate_matrix_log(m, target_logm, target_weight=10.0, tol=1e-06)

Construct an approximate logarithm of superoperator matrix m that is real and near the target_logm.

The equation m = exp( logM ) is allowed to become inexact in order to make logM close to target_logm. In particular, the objective function that is minimized is (where || indicates the 2-norm):

|exp(logM) - m|_1 + target_weight * ||logM - target_logm||^2

Parameters
  • m (numpy array) – The superoperator matrix whose logarithm is taken

  • target_logm (numpy array) – The target logarithm

  • target_weight (float) – A weighting factor used to blance the exactness-of-log term with the closeness-to-target term in the optimized objective function. This value multiplies the latter term.

  • tol (float, optional) – Optimzer tolerance.

Returns

logM (numpy array) – An matrix of the same shape as m.

pygsti.tools.real_matrix_log(m, action_if_imaginary='raise', tol=1e-08)

Construct a real logarithm of real matrix m.

This is possible when negative eigenvalues of m come in pairs, so that they can be viewed as complex conjugate pairs.

Parameters
  • m (numpy array) – The matrix to take the logarithm of

  • action_if_imaginary ({"raise","warn","ignore"}, optional) – What action should be taken if a real-valued logarithm cannot be found. “raise” raises a ValueError, “warn” issues a warning, and “ignore” ignores the condition and simply returns the complex-valued result.

  • tol (float, optional) – An internal tolerance used when testing for equivalence and zero imaginary parts (real-ness).

Returns

logM (numpy array) – An matrix logM, of the same shape as m, such that m = exp(logM)

pygsti.tools.column_basis_vector(i, dim)

Returns the ith standard basis vector in dimension dim.

Parameters
  • i (int) – Basis vector index.

  • dim (int) – Vector dimension.

Returns

numpy.ndarray – An array of shape (dim, 1) that is all zeros except for its i-th element, which equals 1.

pygsti.tools.vec(matrix_in)

Stacks the columns of a matrix to return a vector

Parameters

matrix_in (numpy.ndarray) –

Returns

numpy.ndarray

pygsti.tools.unvec(vector_in)

Slices a vector into the columns of a matrix.

Parameters

vector_in (numpy.ndarray) –

Returns

numpy.ndarray

pygsti.tools.norm1(m)

Returns the 1 norm of a matrix

Parameters

m (numpy.ndarray) – The matrix.

Returns

numpy.ndarray

pygsti.tools.random_hermitian(dim)

Generates a random Hermitian matrix

Parameters

dim (int) – the matrix dimensinon.

Returns

numpy.ndarray

pygsti.tools.norm1to1(operator, num_samples=10000, mx_basis='gm', return_list=False)

The Hermitian 1-to-1 norm of a superoperator represented in the standard basis.

This is calculated via Monte-Carlo sampling. The definition of Hermitian 1-to-1 norm can be found in arxiv:1109.6887.

Parameters
  • operator (numpy.ndarray) – The operator matrix to take the norm of.

  • num_samples (int, optional) – Number of Monte-Carlo samples.

  • mx_basis ({'std', 'gm', 'pp', 'qt'} or Basis) – The basis of operator.

  • return_list (bool, optional) – Whether the entire list of sampled values is returned or just the maximum.

Returns

float or list – Depends on the value of return_list.

pygsti.tools.complex_compare(a, b)

Comparison function for complex numbers that compares real part, then imaginary part.

Parameters
  • a (complex) –

  • b (complex) –

Returns

  • -1 if a < b – 0 if a == b

  • +1 if a > b

pygsti.tools.prime_factors(n)

GCD algorithm to produce prime factors of n

Parameters

n (int) – The number to factorize.

Returns

list – The prime factors of n.

pygsti.tools.minweight_match(a, b, metricfn=None, return_pairs=True, pass_indices_to_metricfn=False)

Matches the elements of two vectors, a and b by minimizing the weight between them.

The weight is defined as the sum of metricfn(x,y) over all (x,y) pairs (x in a and y in b).

Parameters
  • a (list or numpy.ndarray) – First 1D array to match elements between.

  • b (list or numpy.ndarray) – Second 1D array to match elements between.

  • metricfn (function, optional) – A function of two float parameters, x and y,which defines the cost associated with matching x with y. If None, abs(x-y) is used.

  • return_pairs (bool, optional) – If True, the matching is also returned.

  • pass_indices_to_metricfn (bool, optional) – If True, the metric function is passed two indices into the a and b arrays, respectively, instead of the values.

Returns

  • weight_array (numpy.ndarray) – The array of weights corresponding to the min-weight matching. The sum of this array’s elements is the minimized total weight.

  • pairs (list) – Only returned when return_pairs == True, a list of 2-tuple pairs of indices (ix,iy) giving the indices into a and b respectively of each matched pair. The first (ix) indices will be in continuous ascending order starting at zero.

pygsti.tools.minweight_match_realmxeigs(a, b, metricfn=None, pass_indices_to_metricfn=False, eps=1e-09)

Matches the elements of a and b, whose elements are assumed to either real or one-half of a conjugate pair.

Matching is performed by minimizing the weight between elements, defined as the sum of metricfn(x,y) over all (x,y) pairs (x in a and y in b). If straightforward matching fails to preserve eigenvalue conjugacy relations, then real and conjugate- pair eigenvalues are matched separately to ensure relations are preserved (but this can result in a sub-optimal matching). A ValueError is raised when the elements of a and b have incompatible conjugacy structures (#’s of conjugate vs. real pairs).

Parameters
  • a (numpy.ndarray) – First 1D array to match.

  • b (numpy.ndarray) – Second 1D array to match.

  • metricfn (function, optional) – A function of two float parameters, x and y,which defines the cost associated with matching x with y. If None, abs(x-y) is used.

  • pass_indices_to_metricfn (bool, optional) – If True, the metric function is passed two indices into the a and b arrays, respectively, instead of the values.

  • eps (float, optional) – Tolerance when checking if eigenvalues are equal to each other.

Returns

pairs (list) – A list of 2-tuple pairs of indices (ix,iy) giving the indices into a and b respectively of each matched pair.

pygsti.tools._fas(a, inds, rhs, add=False)

Fancy Assignment, equivalent to a[*inds] = rhs but with the elements of inds (allowed to be integers, slices, or integer arrays) always specifing a generalize-slice along the given dimension. This avoids some weird numpy indexing rules that make using square brackets a pain.

pygsti.tools._findx_shape(a, inds)

Returns the shape of a fancy-indexed array (a[*inds].shape)

pygsti.tools._findx(a, inds, always_copy=False)

Fancy Indexing, equivalent to a[*inds].copy() but with the elements of inds (allowed to be integers, slices, or integer arrays) always specifing a generalize-slice along the given dimension. This avoids some weird numpy indexing rules that make using square brackets a pain.

pygsti.tools.safe_dot(a, b)

Performs dot(a,b) correctly when neither, either, or both arguments are sparse matrices.

Parameters
  • a (numpy.ndarray or scipy.sparse matrix.) – First matrix.

  • b (numpy.ndarray or scipy.sparse matrix.) – Second matrix.

Returns

numpy.ndarray or scipy.sparse matrix

pygsti.tools.safe_real(a, inplace=False, check=False)

Get the real-part of a, where a can be either a dense array or a sparse matrix.

Parameters
  • a (numpy.ndarray or scipy.sparse matrix.) – Array to take real part of.

  • inplace (bool, optional) – Whether this operation should be done in-place.

  • check (bool, optional) – If True, raise a ValueError if a has a nonzero imaginary part.

Returns

numpy.ndarray or scipy.sparse matrix

pygsti.tools.safe_imag(a, inplace=False, check=False)

Get the imaginary-part of a, where a can be either a dense array or a sparse matrix.

Parameters
  • a (numpy.ndarray or scipy.sparse matrix.) – Array to take imaginary part of.

  • inplace (bool, optional) – Whether this operation should be done in-place.

  • check (bool, optional) – If True, raise a ValueError if a has a nonzero real part.

Returns

numpy.ndarray or scipy.sparse matrix

pygsti.tools.safe_norm(a, part=None)

Get the frobenius norm of a matrix or vector, a, when it is either a dense array or a sparse matrix.

Parameters
  • a (ndarray or scipy.sparse matrix) – The matrix or vector to take the norm of.

  • part ({None,'real','imag'}) – If not None, return the norm of the real or imaginary part of a.

Returns

float

pygsti.tools.safe_onenorm(a)

Computes the 1-norm of the dense or sparse matrix a.

Parameters

a (ndarray or sparse matrix) – The matrix or vector to take the norm of.

Returns

float

pygsti.tools.csr_sum_indices(csr_matrices)

Precomputes the indices needed to sum a set of CSR sparse matrices.

Computes the index-arrays needed for use in :method:`csr_sum`, along with the index pointer and column-indices arrays for constructing a “template” CSR matrix to be the destination of csr_sum.

Parameters

csr_matrices (list) – The SciPy CSR matrices to be summed.

Returns

  • ind_arrays (list) – A list of numpy arrays giving the destination data-array indices of each element of csr_matrices.

  • indptr, indices (numpy.ndarray) – The row-pointer and column-indices arrays specifying the sparsity structure of a the destination CSR matrix.

  • N (int) – The dimension of the destination matrix (and of each member of csr_matrices)

pygsti.tools.csr_sum(data, coeffs, csr_mxs, csr_sum_indices)

Accelerated summation of several CSR-format sparse matrices.

:method:`csr_sum_indices` precomputes the necessary indices for summing directly into the data-array of a destination CSR sparse matrix. If data is the data-array of matrix D (for “destination”), then this method performs:

D += sum_i( coeff[i] * csr_mxs[i] )

Note that D is not returned; the sum is done internally into D’s data-array.

Parameters
  • data (numpy.ndarray) – The data-array of the destination CSR-matrix.

  • coeffs (iterable) – The weight coefficients which multiply each summed matrix.

  • csr_mxs (iterable) – A list of CSR matrix objects whose data-array is given by obj.data (e.g. a SciPy CSR sparse matrix).

  • csr_sum_indices (list) – A list of precomputed index arrays as returned by :method:`csr_sum_indices`.

Returns

None

pygsti.tools.csr_sum_flat_indices(csr_matrices)

Precomputes quantities allowing fast computation of linear combinations of CSR sparse matrices.

The returned quantities can later be used to quickly compute a linear combination of the CSR sparse matrices csr_matrices.

Computes the index and data arrays needed for use in :method:`csr_sum_flat`, along with the index pointer and column-indices arrays for constructing a “template” CSR matrix to be the destination of csr_sum_flat.

Parameters

csr_matrices (list) – The SciPy CSR matrices to be summed.

Returns

  • flat_dest_index_array (numpy array) – A 1D array of one element per nonzero element in any of csr_matrices, giving the destination-index of that element.

  • flat_csr_mx_data (numpy array) – A 1D array of the same length as flat_dest_index_array, which simply concatenates the data arrays of csr_matrices.

  • mx_nnz_indptr (numpy array) – A 1D array of length len(csr_matrices)+1 such that the data for the i-th element of csr_matrices lie in the index-range of mx_nnz_indptr[i] to mx_nnz_indptr[i+1]-1 of the flat arrays.

  • indptr, indices (numpy.ndarray) – The row-pointer and column-indices arrays specifying the sparsity structure of a the destination CSR matrix.

  • N (int) – The dimension of the destination matrix (and of each member of csr_matrices)

pygsti.tools.csr_sum_flat(data, coeffs, flat_dest_index_array, flat_csr_mx_data, mx_nnz_indptr)

Computation of the summation of several CSR-format sparse matrices.

:method:`csr_sum_flat_indices` precomputes the necessary indices for summing directly into the data-array of a destination CSR sparse matrix. If data is the data-array of matrix D (for “destination”), then this method performs:

D += sum_i( coeff[i] * csr_mxs[i] )

Note that D is not returned; the sum is done internally into D’s data-array.

Parameters
Returns

None

pygsti.tools.expm_multiply_prep(a, tol=EXPM_DEFAULT_TOL)

Computes “prepared” meta-info about matrix a, to be used in expm_multiply_fast.

This includes a shifted version of a.

Parameters
  • a (numpy.ndarray) – the matrix that will belater exponentiated.

  • tol (float, optional) – Tolerance used to within matrix exponentiation routines.

Returns

tuple – A tuple of values to pass to expm_multiply_fast.

pygsti.tools.expm_multiply_fast(prep_a, v, tol=EXPM_DEFAULT_TOL)

Multiplies v by an exponentiated matrix.

Parameters
  • prep_a (tuple) – A tuple of values from :function:`expm_multiply_prep` that defines the matrix to be exponentiated and holds other pre-computed quantities.

  • v (numpy.ndarray) – Vector to multiply (take dot product with).

  • tol (float, optional) – Tolerance used to within matrix exponentiation routines.

Returns

numpy.ndarray

pygsti.tools._custom_expm_multiply_simple_core(a, b, mu, m_star, s, tol, eta)

a helper function. Note that this (python) version works when a is a LinearOperator as well as a SciPy CSR sparse matrix.

pygsti.tools.expop_multiply_prep(op, a_1_norm=None, tol=EXPM_DEFAULT_TOL)

Returns “prepared” meta-info about operation op, which is assumed to be traceless (so no shift is needed).

Used as input for use with _custom_expm_multiply_simple_core or fast C-reps.

Parameters
  • op (scipy.sparse.linalg.LinearOperator) – The operator to exponentiate.

  • a_1_norm (float, optional) – The 1-norm (if computed separately) of op.

  • tol (float, optional) – Tolerance used to within matrix exponentiation routines.

Returns

tuple – A tuple of values to pass to expm_multiply_fast.

pygsti.tools.sparse_equal(a, b, atol=1e-08)

Checks whether two Scipy sparse matrices are (almost) equal.

Parameters
  • a (scipy.sparse matrix) – First matrix.

  • b (scipy.sparse matrix) – Second matrix.

  • atol (float, optional) – The tolerance to use, passed to numpy.allclose, when comparing the elements of a and b.

Returns

bool

pygsti.tools.sparse_onenorm(a)

Computes the 1-norm of the scipy sparse matrix a.

Parameters

a (scipy sparse matrix) – The matrix or vector to take the norm of.

Returns

float

pygsti.tools.ndarray_base(a, verbosity=0)

Get the base memory object for numpy array a.

This is found by following .base until it comes up None.

Parameters
  • a (numpy.ndarray) – Array to get base of.

  • verbosity (int, optional) – Print additional debugging information if this is > 0.

Returns

numpy.ndarray

pygsti.tools.to_unitary(scaled_unitary)

Compute the scaling factor required to turn a scalar multiple of a unitary matrix to a unitary matrix.

Parameters

scaled_unitary (ndarray) – A scaled unitary matrix

Returns

  • scale (float)

  • unitary (ndarray) – Such that scale * unitary == scaled_unitary.

pygsti.tools.sorted_eig(mx)

Similar to numpy.eig, but returns sorted output.

In particular, the eigenvalues and vectors sorted by eigenvalue, where sorting is done according to (real_part, imaginary_part) tuple.

Parameters

mx (numpy.ndarray) – Matrix to act on.

Returns

  • eigenvalues (numpy.ndarray)

  • eigenvectors (numpy.ndarray)

pygsti.tools.compute_kite(eigenvalues)

Computes the “kite” corresponding to a list of eigenvalues.

The kite is defined as a list of integers, each indicating that there is a degnenerate block of that many eigenvalues within eigenvalues. Thus the sum of the list values equals len(eigenvalues).

Parameters

eigenvalues (numpy.ndarray) – A sorted array of eigenvalues.

Returns

list – A list giving the multiplicity structure of evals.

pygsti.tools.find_zero_communtant_connection(u, u_inv, u0, u0_inv, kite)

Find a matrix R such that u_inv R u0 is diagonal AND log(R) has no projection onto the commutant of G0.

More specifically, find a matrix R such that u_inv R u0 is diagonal (so G = R G0 Rinv if G and G0 share the same eigenvalues and have eigenvectors u and u0 respectively) AND log(R) has no (zero) projection onto the commutant of G0 = u0 diag(evals) u0_inv.

Parameters
  • u (numpy.ndarray) – Usually the eigenvector matrix of a gate (G).

  • u_inv (numpy.ndarray) – Inverse of u.

  • u0 (numpy.ndarray) – Usually the eigenvector matrix of the corresponding target gate (G0).

  • u0_inv (numpy.ndarray) – Inverse of u0.

  • kite (list) – The kite structure of u0.

Returns

numpy.ndarray

pygsti.tools.project_onto_kite(mx, kite)

Project mx onto kite, so mx is zero everywhere except on the kite.

Parameters
  • mx (numpy.ndarray) – Matrix to project.

  • kite (list) – A kite structure.

Returns

numpy.ndarray

pygsti.tools.project_onto_antikite(mx, kite)

Project mx onto the complement of kite, so mx is zero everywhere on the kite.

Parameters
  • mx (numpy.ndarray) – Matrix to project.

  • kite (list) – A kite structure.

Returns

numpy.ndarray

pygsti.tools.remove_dependent_cols(mx, tol=1e-07)

Removes the linearly dependent columns of a matrix.

Parameters

mx (numpy.ndarray) – The input matrix

Returns

A linearly independent subset of the columns of mx.

pygsti.tools.intersection_space(space1, space2, tol=1e-07, use_nice_nullspace=False)

TODO: docstring

pygsti.tools.union_space(space1, space2, tol=1e-07)

TODO: docstring

pygsti.tools.jamiolkowski_angle(hamiltonian_mx)

TODO: docstring

pygsti.tools.zvals_to_dense(self, zvals, superket=True)

Construct the dense operator or superoperator representation of a computational basis state.

Parameters
  • zvals (list or numpy.ndarray) – The z-values, each 0 or 1, defining the computational basis state.

  • superket (bool, optional) – If True, the super-ket representation of the state is returned. If False, then the complex ket representation is returned.

Returns

numpy.ndarray

pygsti.tools.int64_parity(x)

Compute the partity of x.

Recursively divide a (64-bit) integer (x) into two equal halves and take their XOR until only 1 bit is left.

Parameters

x (int64) –

Returns

int64

pygsti.tools.zvals_int64_to_dense(zvals_int, nqubits, outvec=None, trust_outvec_sparsity=False, abs_elval=None)

Fills a dense array with the super-ket representation of a computational basis state.

Parameters
  • zvals_int (int64) – The array of (up to 64) z-values, encoded as the 0s and 1s in the binary representation of this integer.

  • nqubits (int) – The number of z-values (up to 64)

  • outvec (numpy.ndarray, optional) – The output array, which must be a 1D array of length 4**nqubits or None, in which case a new array is allocated.

  • trust_outvec_sparsity (bool, optional) – When True, it is assumed that the provided outvec starts as all zeros and so only non-zero elements of outvec need to be set.

  • abs_elval (float) – the value 1 / (sqrt(2)**nqubits), which can be passed here so that it doesn’t need to be recomputed on every call to this function. If None, then we just compute the value.

Returns

numpy.ndarray

pygsti.tools.parallel_apply(f, l, comm)

Apply a function, f to every element of a list, l in parallel, using MPI.

Parameters
  • f (function) – function of an item in the list l

  • l (list) – list of items as arguments to f

  • comm (MPI Comm) – MPI communicator object for organizing parallel programs

Returns

results (list) – list of items after f has been applied

pygsti.tools.mpi4py_comm()

Get a comm object

Returns

MPI.Comm – Comm object to be passed down to parallel pygsti routines

pygsti.tools.starmap_with_kwargs(fn, num_runs, num_processors, args_list, kwargs_list)
class pygsti.tools.NamedDict(keyname=None, keytype=None, valname=None, valtype=None, items=())

Bases: dict, pygsti.baseobjs.nicelyserializable.NicelySerializable

A dictionary that also holds category names and types.

This dict-derived class holds a catgory name applicable to its keys, and key and value type names indicating the types of its keys and values.

The main purpose of this class is to utilize its :method:`to_dataframe` method.

Parameters
  • keyname (str, optional) – A category name for the keys of this dict. For example, if the dict contained the keys “dog” and “cat”, this might be “animals”. This becomes a column header if this dict is converted to a data frame.

  • keytype ({"float", "int", "category", None}, optional) – The key-type, in correspondence with different pandas series types.

  • valname (str, optional) – A category name for the keys of this dict. This becomse a column header if this dict is converted to a data frame.

  • valtype ({"float", "int", "category", None}, optional) – The value-type, in correspondence with different pandas series types.

  • items (list or dict, optional) – Initial items, used in serialization.

classmethod create_nested(cls, key_val_type_list, inner)

Creates a nested NamedDict.

Parameters
  • key_val_type_list (list) – A list of (key, value, type) tuples, one per nesting layer.

  • inner (various) – The value that will be set to the inner-most nested dictionary’s value, supplying any additional layers of nesting (if inner is a NamedDict) or the value contained in all of the nested layers.

__reduce__(self)

Helper for pickle.

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
to_dataframe(self)

Render this dict as a pandas data frame.

Returns

pandas.DataFrame

_add_to_columns(self, columns, seriestypes, row_prefix)
class pygsti.tools._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 vector-element. 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 non-simple 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 2-element 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 length-4 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 length-2 [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 vector-elements) in the basis.

Type

int

elshape

The shape of each element. Typically either a length-1 or length-2 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 direct-sum-of-tensor-product-blocks 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 tensor-product 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 vector-elements) in the basis.

property elshape(self)

The shape of each element. Typically either a length-1 or length-2 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 flattened-element 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 built-in 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 built-in 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_name-analogue of the standard basis that this basis’s elements are expressed in.

Parameters

builtin_basis_name (str, optional) – The name of the built-in 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 component-free version of the same builtin-basis 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.tools._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 vector-elements) in the basis.

property elshape(self)

The shape of each element. Typically either a length-1 or length-2 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.tools._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 block-diagonal 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 vector-elements) in the basis.

property elshape(self)

The shape of each element. Typically either a length-1 or length-2 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_name-analogue of the standard basis that this basis’s elements are expressed in.

Parameters

builtin_basis_name (str, optional) – The name of the built-in 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 component-free version of the same builtin-basis type.

Returns

Basis

class pygsti.tools._Label

Bases: object

A label used to identify a gate, circuit layer, or (sub-)circuit.

A label consisting of a string along with a tuple of integers or sector-names specifying which qubits, or more generally, parts of the Hilbert space that is acted upon by an object so-labeled.

property depth(self)

The depth of this label, viewed as a sub-circuit.

property reps(self)

Number of repetitions (of this label’s components) that this label represents.

property has_nontrivial_components(self)
collect_args(self)
strip_args(self)
expand_subcircuits(self)

Expand any sub-circuits within this label.

Returns a list of component labels which doesn’t include any CircuitLabel labels. This effectively expands any “boxes” or “exponentiation” within this label.

Returns

tuple – A tuple of component Labels (none of which should be :class:`CircuitLabel`s).

class pygsti.tools._LocalElementaryErrorgenLabel(errorgen_type, basis_element_labels)

Bases: ElementaryErrorgenLabel

Labels an elementary error generator by simply a type and one or two basis element labels.

classmethod cast(cls, obj, sslbls=None, identity_label='I')
__hash__(self)

Return hash(self).

__eq__(self, other)

Return self==value.

__str__(self)

Return str(self).

__repr__(self)

Return repr(self).

pygsti.tools.IMAG_TOL = 1e-07
pygsti.tools._flat_mut_blks(i, j, block_dims)
pygsti.tools._hack_sqrtm(a)
pygsti.tools.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 :function:`entanglement_fidelity` with the operation matrices.

Parameters
  • a (numpy array) – First density matrix.

  • b (numpy array) – Second density matrix.

Returns

float – The resulting fidelity.

pygsti.tools.frobeniusdist(a, b)

Returns the frobenius distance between gate or density matrices.

This is given by :

sqrt( sum( (a_ij-b_ij)^2 ) )

Parameters
  • a (numpy array) – First matrix.

  • b (numpy array) – Second matrix.

Returns

float – The resulting frobenius distance.

pygsti.tools.frobeniusdist_squared(a, b)

Returns the square of the frobenius distance between gate or density matrices.

This is given by :

sum( (A_ij-B_ij)^2 )

Parameters
  • a (numpy array) – First matrix.

  • b (numpy array) – Second matrix.

Returns

float – The resulting frobenius distance.

pygsti.tools.residuals(a, b)

Calculate residuals between the elements of two matrices

Parameters
  • a (numpy array) – First matrix.

  • b (numpy array) – Second matrix.

Returns

np.array – residuals

pygsti.tools.tracenorm(a)

Compute the trace norm of matrix a given by:

Tr( sqrt{ a^dagger * a } )

Parameters

a (numpy array) – The matrix to compute the trace norm of.

Returns

float

pygsti.tools.tracedist(a, b)

Compute the trace distance between matrices.

This is given by:

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

Parameters
  • a (numpy array) – First matrix.

  • b (numpy array) – Second matrix.

Returns

float

pygsti.tools.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
  • a (numpy array) – First matrix.

  • b (numpy array) – Second matrix.

  • mx_basis (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_x (bool, optional) – Whether to return a numpy array encoding the state (rho) at which the maximal trace distance occurs.

Returns

  • dm (float) – Diamond norm

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

pygsti.tools.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
  • a (numpy array) – First matrix.

  • b (numpy 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.entanglement_fidelity(a, b, mx_basis='pp')

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.

Parameters
  • a (numpy array) – First matrix.

  • b (numpy 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).

Returns

float

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

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
  • a (array or gate) – The gate to compute the AGI to b of. E.g., an imperfect implementation of b.

  • b (array 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.

Returns

AGI (float) – The AGI of a to b.

pygsti.tools.average_gate_infidelity(a, b, mx_basis='gm')

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
  • a (array or gate) – The gate to compute the AGI to b of. E.g., an imperfect implementation of b.

  • b (array 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.

Returns

float

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

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
  • a (numpy array) – First matrix.

  • b (numpy 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).

Returns

EI (float) – The EI of a to b.

pygsti.tools.gateset_infidelity(model, target_model, itype='EI', weights=None, mx_basis=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
  • model (Model) – The model to calculate the average infidelity, to target_model, of.

  • target_model (Model) – The model to calculate the average infidelity, to model, of.

  • itype (str, optional) – The infidelity type. Either ‘EI’, corresponding to entanglement infidelity, or ‘AGI’, corresponding to average gate infidelity.

  • weights (dict, 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.

Returns

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

pygsti.tools.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
  • a (array 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.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_mx (numpy array) – The operation matrix to act on.

Returns

float – The resulting upper bound on fidelity(operation_mx, anyUnitaryGateMx)

pygsti.tools.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
  • model (Model) – The model supplying the POVM effect vectors and the basis those vectors are in.

  • povmlbl (str) – The POVM label

Returns

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

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

Computes the process (entanglement) fidelity between POVM maps.

Parameters
  • model (Model) – The model the POVM belongs to.

  • target_model (Model) – The target model (which also has povmlbl).

  • povmlbl (Label) – Label of the POVM to get the fidelity of.

Returns

float

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

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

Parameters
  • model (Model) – The model the POVM belongs to.

  • target_model (Model) – The target model (which also has povmlbl).

  • povmlbl (Label) – Label of the POVM to get the trace distance of.

Returns

float

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

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

Parameters
  • model (Model) – The model the POVM belongs to.

  • target_model (Model) – The target model (which also has povmlbl).

  • povmlbl (Label) – Label of the POVM to get the diamond distance of.

Returns

float

pygsti.tools.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_mx (numpy 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.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

psi (numpy array) – The state vector.

Returns

numpy array – The vectorized density matrix.

pygsti.tools.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
  • dmvec (numpy array) – The vectorized density matrix, assumed to be in the standard (matrix unit) basis.

  • tol (float, 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.unitary_to_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

u (numpy array) – The unitary matrix which acts on state vectors.

Returns

numpy array – The super-operator process matrix.

pygsti.tools.process_mx_to_unitary(superop)

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

This function assumes superop acts on (row)-vectorized density matrices. The super-operator must be of the form kron(U,U.conj) or an error will be thrown.

Parameters

superop (numpy 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.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
  • spamvec (ndarray) – The SPAM vector.

  • target_spamvec (ndarray) – 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

errgen (ndarray) – The error generator.

pygsti.tools.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
  • gate (ndarray) – The operation matrix

  • target_op (ndarray) – 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

errgen (ndarray) – The error generator.

pygsti.tools.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_gen (ndarray) – The error generator matrix

  • target_op (ndarray) – 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.std_scale_factor(dim, projection_type)

Gets the scaling factors required to turn std_error_generators() output into projectors.

Returns the multiplicative scaling that should be applied to the output of :func”std_error_generators, before using them as projectors, in order to compute the “standard” reported projection onto that type of error (i.e. the coefficient of the standard generator terms built un-normalized-Paulis).

Parameters
  • dim (int) – The dimension of the error generators; also the associated gate dimension. This must be a perfect square, as sqrt(dim) is the dimension of density matrices. For a single qubit, dim == 4.

  • projection_type ({"hamiltonian", "stochastic", "affine"}) – The type/class of error generators to get the scaling for.

Returns

float

pygsti.tools.std_error_generators(dim, projection_type, projection_basis)

Compute the gate error generators for a standard set of errors.

Specifically, these errors can correspond to “Hamiltonian”-, “Stochastic”-, or “Affine”-type errors in terms of the elements of the specified basis.

Parameters
  • dim (int) – 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.

  • projection_type ({"hamiltonian", "stochastic", "affine"}) – The type of error generators to construct. If “hamiltonian”, then the Hamiltonian generators which take a density matrix rho -> -i*[ H, rho ] for Pauli-product matrix H. If “stochastic”, then the Stochastic error generators which take rho -> P*rho*P for Pauli-product matrix P. If “affine”, then the affine generators which take rho -> P.

  • projection_basis ({'std', 'gm', 'pp', 'qt'}) – Which basis is used to construct the error generators. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp) and Qutrit (qt).

Returns

generators (numpy.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.std_errorgen_projections(errgen, projection_type, projection_basis, mx_basis='gm', return_generators=False, return_scale_fctr=False)

Compute the projections of a gate error generator onto generators for a standard set of errors.

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

Parameters
  • errgen (: 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_generators (bool, optional) – If True, return the error generators projected against along with the projection values themseves.

  • return_scale_fctr (bool, 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

  • projections (numpy.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).

  • generators (numpy.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.

  • scale (float) – Only returned when return_scale_fctr == True. A mulitplicative scaling constant that has already been applied to projections.

pygsti.tools._assert_shape(ar, shape, sparse=False)

Asserts ar.shape == shape ; works with sparse matrices too

pygsti.tools.lindblad_error_generator(errorgen_type, basis_element_labels, basis_1q, normalize, 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.lindblad_error_generators(dmbasis_ham, dmbasis_other, normalize, other_mode='all')

Compute the superoperator-generators corresponding to Lindblad terms.

This routine computes the Hamiltonian and Non-Hamiltonian (“other”) superoperator generators which correspond to the terms of the Lindblad expression:

L(rho) = sum_i( h_i [A_i,rho] ) +
sum_ij( o_ij * (B_i rho B_j^dag -

0.5( rho B_j^dag B_i + B_j^dag B_i rho) ) )

where {A_i} and {B_i} are bases (possibly the same) for Hilbert Schmidt (density matrix) space with the identity element removed so that each A_i and B_i are traceless. If we write L(rho) in terms of superoperators H_i and O_ij,

L(rho) = sum_i( h_i H_i(rho) ) + sum_ij( o_ij O_ij(rho) )

then this function computes the matrices for H_i and O_ij using the given density matrix basis. Thus, if dmbasis is expressed in the standard basis (as it should be), the returned matrices are also in this basis.

If these elements are used as projectors it may be usedful to normalize them (by setting normalize=True). Note, however, that these projectors are not all orthogonal - in particular the O_ij’s are not orthogonal to one another.

Parameters
  • dmbasis_ham (list) – A list of basis matrices {B_i} including the identity as the first element, for the returned Hamiltonian-type error generators. This argument is easily obtained by call to pp_matrices() or a similar function. The matrices are expected to be in the standard basis, and should be traceless except for the identity. Matrices should be NumPy arrays or SciPy CSR sparse matrices.

  • dmbasis_other (list) – A list of basis matrices {B_i} including the identity as the first element, for the returned Stochastic-type error generators. This argument is easily obtained by call to pp_matrices() or a similar function. The matrices are expected to be in the standard basis, and should be traceless except for the identity. Matrices should be NumPy arrays or SciPy CSR sparse matrices.

  • normalize (bool) – Whether or not generators should be normalized so that numpy.linalg.norm(generator.flat) == 1.0 Note that the generators will still, in general, be non-orthogonal.

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian Lindblad error generators to construct. Allowed values are: “diagonal” (only the diagonal Stochastic generators are returned; that is, the generators corresponding to the i==j terms in the Lindblad expression.), “diag_affine” (diagonal + affine generators), and “all” (all generators).

Returns

  • ham_generators (numpy.ndarray or list of SciPy CSR matrices) – If dense matrices where given, an array of shape (d-1,d,d), where d is the size of the basis, i.e. d == len(dmbasis). ham_generators[i] gives the matrix for H_i. If sparse matrices were given, a list of shape (d,d) CSR matrices.

  • other_generators (numpy.ndarray or list of lists of SciPy CSR matrices) – If dense matrices where given, An array of shape (d-1,d-1,d,d), (2,d-1,d,d), or (d-1,d,d), where d is the size of the basis, for other_mode equal to “all”, “diag_affine”, or “diagonal”, respectively. For instance, in the “all” case, other_generators[i,j] gives the matrix for O_ij. If sparse matrices were given, the all but the final 2 dimensions are lists (e.g. the “all” case returns a list of lists of shape (d,d) CSR matrices).

pygsti.tools.lindblad_errorgen_projections(errgen, ham_basis, other_basis, mx_basis='gm', normalize=True, return_generators=False, other_mode='all', sparse=False)

Compute the projections of an error generator onto generators for the Lindblad-term errors.

Note that these Lindblad-term errors are expressed in given bases.

Parameters
  • errgen (: ndarray) – The error generator matrix to project.

  • ham_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct the Hamiltonian-type lindblad error Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • other_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct the Stochastic-type lindblad error Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • mx_basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The source basis. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

  • normalize (bool, optional) – Whether or not the generators being projected onto are normalized, so that numpy.linalg.norm(generator.flat) == 1.0. Note that the generators will still, in general, be non-orthogonal.

  • return_generators (bool, optional) – If True, return the error generators projected against along with the projection values themseves.

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian Lindblad error projections to obtain. Allowed values are: “diagonal” (only the diagonal Stochastic), “diag_affine” (diagonal + affine generators), and “all” (all generators).

  • sparse (bool, optional) – Whether to create sparse or dense basis matrices when strings are given as ham_basis and other_basis

Returns

  • ham_projections (numpy.ndarray) – An array of length d-1, where d is the dimension of the gate, giving the projections onto the Hamiltonian-type Lindblad terms.

  • other_projections (numpy.ndarray) – An array of shape (d-1,d-1), (2,d-1), or (d-1,), where d is the dimension of the gate, for other_mode equal to “all”, “diag_affine”, or “diagonal”, respectively. Values give the projections onto the non-Hamiltonian-type Lindblad terms.

  • ham_generators (numpy.ndarray) – The Hamiltonian-type Lindblad term generators, as would be returned from lindblad_error_generators(pp_matrices(sqrt(d)), normalize). Shape is (d-1,d,d), and ham_generators[i] is in the standard basis.

  • other_generators (numpy.ndarray) – The Stochastic-type Lindblad term generators, as would be returned from lindblad_error_generators(pp_matrices(sqrt(d)), normalize). Shape is (d-1,d-1,d,d), (2,d-1,d,d), or (d-1,d,d) for other_mode equal to “all”, “diag_affine”, or “diagonal”, respectively, and other_generators[i] is in the std basis.

pygsti.tools.projections_to_lindblad_terms(ham_projs, other_projs, ham_basis, other_basis, other_mode='all', return_basis=True)

Converts error-generator projections into a dictionary of error coefficients.

Converts the projections of an error generator onto basis elements into a Lindblad-term dictionary and basis used to individually specify Lindblad terms.

Parameters
  • ham_projs (numpy.ndarray) – An array of length d-1, where d is the dimension of the projected error generator, giving the projections onto the Hamiltonian-type Lindblad terms.

  • other_projs (numpy.ndarray) – An array of shape (d-1,d-1), (2,d-1), or (d-1,), where d is the dimension of the projected error generator, for other_mode equal to “all”, “diag_affine”, or “diagonal”, respectively. Values give the projections onto the non-Hamiltonian-type Lindblad terms.

  • ham_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct ham_projs. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • other_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct other_projs. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian Lindblad error projections other_projs includes. Allowed values are: “diagonal” (only the diagonal Stochastic), “diag_affine” (diagonal + affine generators), and “all” (all generators).

  • return_basis (bool, optional) – Whether to return a Basis containing the elements corresponding to labels within the returned Ltermdict.

Returns

  • Ltermdict (dict) – Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify off-diagonal non-Hamiltonian Lindblad terms. Basis labels are taken from ham_basis and other_basis. Values are complex coefficients (the projections).

  • basis (Basis) – A single basis containing all the basis labels used in Ltermdict (and only those elements). Only returned when return_basis == True.

pygsti.tools.lindblad_terms_to_projections(lindblad_term_dict, basis, other_mode='all')

Convert a set of Lindblad terms into a dense matrix/grid of projections.

Essentially the inverse of :function:`projections_to_lindblad_terms`.

Parameters
  • lindblad_term_dict (dict) – A dictionary specifying which Linblad terms are present in the gate parameteriztion. Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples with 1 basis label indicate a diagonal term, and are the only types of terms allowed when nonham_mode != “all”. Otherwise, Stochastic term tuples can include 2 basis labels to specify “off-diagonal” non-Hamiltonian Lindblad terms. Basis labels can be strings or integers. Values are complex coefficients (error rates).

  • basis (Basis) – A basis mapping the labels used in the keys of lindblad_term_dict to basis matrices (e.g. numpy arrays or Scipy sparse matrices). The first element of this basis should be an identity element, and will be propagated to the returned ham_basis and other_basis.

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian terms are allowed in lindblad_term_dict. Allowed values are: “diagonal” (only the diagonal Stochastic), “diag_affine” (diagonal + affine generators), and “all” (all generators).

Returns

  • hamProjs (numpy.ndarray) – An array of length basisdim-1, giving the projections onto a full set of the Hamiltonian-type Lindblad terms (onto each element of ham_basis).

  • otherProjs (numpy.ndarray) – An array of shape (d-1,d-1), (2,d-1), or (d-1,), where d=`basisdim` for other_mode equal to “all”, “diag_affine”, or “diagonal”, respectively. Values give the projections onto the non-Hamiltonian -type Lindblad terms.

  • ham_basis (Basis) – The basis used to construct hamProjs.

  • other_basis (Basis) – The basis used to construct otherProjs.

  • hamBasisIndices (OrderedDict) – A dictionary mapping the some or all of the basis labels of basisdict to the integers 0 to len(ham_basis). These are indices into hamProjs, giving the projection associated with each Hamiltonian basis element.

  • otherBasisIndices (OrderedDict) – A dictionary mapping the some or all of the basis labels of basisdict to the integers 0 to len(other_basis). These are row and column indices into otherProjs, giving the projection associated with each pair of “other” basis elements (or single basis element if other_mode!=”all”).

pygsti.tools.lindblad_param_labels(ham_basis, other_basis, param_mode='cptp', other_mode='all', dim=None)

Generate human-readable labels for the Lindblad parameters.

Computes labels corresponding to the parameters obtained via calls to :function:`lindblad_errorgen_projections` and then :function:`lindblad_projections_to_paramvals`. The arguments to this function must match those given to the above (where they overlap).

Parameters
  • ham_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct the Hamiltonian-type lindblad error Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • other_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct the Stochastic-type lindblad error Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • param_mode ({"unconstrained", "cptp", "depol", "reldepol"}) – Describes how values in ham_projs and otherProj relate to the returned parameter values. Allowed values are: “unconstrained” (projs are independent unconstrained parameters), “cptp” (independent parameters but constrained so map is CPTP), “reldepol” (all non-Ham. diagonal projs take the same value), “depol” (same as “reldepol” but projs must be positive)

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian Lindblad error projections other_projs includes. Allowed values are: “diagonal” (only the diagonal Stochastic), “diag_affine” (diagonal + affine generators), and “all”.

  • dim (int, optional) – The dimension of the error generator matrix, used if the bases are given as strings.

Returns

param_labels (list) – A list of strings that describe each parameter.

pygsti.tools.lindblad_projections_to_paramvals(ham_projs, other_projs, param_mode='cptp', other_mode='all', truncate=True)

Compute Lindblad-gate parameter values from error generator projections.

Constructs an array of paramter values from the separate arrays of Hamiltonian and non-Hamiltonian Lindblad-term projections.

When cptp=True, this function handles parameterizing the projections to that for (real) parameter values correspond to projections for a valid CPTP gate (e.g. by parameterizing the Cholesky decomposition of other_projs instead of other_projs itself). This function is closely related to implementation details of the LindbladOp class.

Parameters
  • ham_projs (numpy.ndarray) – An array of length d-1, where d is the gate dimension, giving the projections onto a full set of the Hamiltonian-type Lindblad terms.

  • other_projs (numpy.ndarray) – An array of shape (d-1,d-1), (2,d-1), or (d-1,), where d is the gate dimension, for other_mode equal to “all”,`”diag_affine”, or `”diagonal”, respectively. Values give the projections onto a full set of non-Hamiltonian-type Lindblad terms.

  • param_mode ({"unconstrained", "cptp", "depol", "reldepol"}) – Describes how values in ham_projs and otherProj relate to the returned parameter values. Allowed values are: “unconstrained” (projs are independent unconstrained parameters), “cptp” (independent parameters but constrained so map is CPTP), “reldepol” (all non-Ham. diagonal projs take the same value), “depol” (same as “reldepol” but projs must be positive)

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian Lindblad error projections other_projs includes. Allowed values are: “diagonal” (only the diagonal Stochastic), “diag_affine” (diagonal + affine generators), and “all”.

  • truncate (bool or float, optional) – Whether to truncate the projections onto the Lindblad terms in order to meet constraints (e.g. to preserve CPTP) when necessary. If >= 0 or False, then an error is thrown when the given projections cannot be parameterized as specified, using the value given as the the maximum negative eigenvalue that is tolerated (False is equivalent to 1e-12). True tolerates any negative eigenvalues.

Returns

param_vals (numpy.ndarray) – A 1D array of real parameter values consisting of d-1 Hamiltonian values followed by either (d-1)^2, 2*(d-1), or just d-1 non-Hamiltonian values for other_mode equal to “all”, “diag_affine”, or “diagonal”, respectively.

pygsti.tools.lindblad_terms_projection_indices(ham_basis, other_basis, other_mode='all')

Constructs a dictionary mapping Lindblad term labels to projection coefficients.

This method is used for finding the index of a particular error generator coefficient in the 1D array formed by concatenating the Hamiltonian and flattened stochastic projection arrays.

Parameters
  • ham_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct ham_projs. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • other_basis ({'std', 'gm', 'pp', 'qt'}, list of matrices, or Basis object) – The basis used to construct other_projs. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt), list of numpy arrays, or a custom basis object.

  • other_mode ({"diagonal", "diag_affine", "all"}) – Which non-Hamiltonian Lindblad error projections other_projs includes. Allowed values are: “diagonal” (only the diagonal Stochastic), “diag_affine” (diagonal + affine generators), and “all” (all generators).

Returns

Ltermdict (dict) – Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify off-diagonal non-Hamiltonian Lindblad terms. Basis labels are taken from ham_basis and other_basis. Values are integer indices.

pygsti.tools.paramvals_to_lindblad_projections(paramvals, ham_basis_size, other_basis_size, param_mode='cptp', other_mode='all', cache_mx=None)

Construct Lindblad-term projections from Lindblad-operator parameter values.

Computes the separate arrays of Hamiltonian and non-Hamiltonian Lindblad-term projections from an array of Lindblad-operator parameter values.

This function essentially performs the inverse of :function:`lindblad_projections_to_paramvals`.

Parameters
  • paramvals (numpy.ndarray) – A 1D array of real parameter values consisting of d-1 Hamiltonian values followed by either (d-1)^2 or just d-1 non-Hamiltonian values (the latter when other_mode in (‘diagonal’,’diag_affine’)).

  • ham_basis_size (int) – The number of elements in the Hamiltonian basis used to construct paramvals. As such, ham_basis_size gives the offset into paramvals where the non-Hamiltonian parameters begin.

  • other_basis_size (int) – The number of elements in the non-Hamiltonian basis used to construct paramvals.

  • param_mode ({"unconstrained", "cptp", "depol", "reldepol"}) – Specifies how the Lindblad-term coefficients are mapped to the set of (real) parameter values. This really just applies to the “other” (non-Hamiltonian) coefficients. “unconstrained” means that ranging over the parameter values lets the coefficient-matrix vary over all matrices, “cptp” restricts this to postitive matrices. “depol” maps all of the coefficients to the same, positive parameter (only available for “diagonal” and “diag_affine” other-modes), and “reldepol” does the same thing but without the positivity constraint.

  • other_mode ({"all", "diagonal", "diag_affine"}) – Specifies the structure of the matrix of other (non-Hamiltonian) coefficients. If d is the gate dimension, “all” means a (d-1,d-1) matrix is used; “diagonal” means just the (d2-1,) diagonal of this matrix is used; “diag_affine” means the coefficients are in a (2,d2-1) array with the diagonal-term coefficients being the first row and the affine coefficients being the second row.

  • cache_mx (ndarray, optional) – Scratch space that is used to store the lower-triangular Cholesky decomposition matrix that is used to construct the “other” projections when there is a CPTP constraint.

Returns

  • ham_projs (numpy.ndarray) – An array of length d-1, where d is the gate dimension, giving the projections onto a full set of the Hamiltonian-type Lindblad terms.

  • other_projs (numpy.ndarray) – An array of shape (d-1,d-1) or (d-1,) or (2,d-1) where d is the gate dimension, giving the projections onto a full set of non-Hamiltonian -type Lindblad terms (see other_mode above).

pygsti.tools.paramvals_to_lindblad_projections_deriv(paramvals, ham_basis_size, other_basis_size, param_mode='cptp', other_mode='all', cache_mx=None)

Construct derivative of Lindblad-term projections with respect to the parameter values.

Computes separate derivative arrays of Hamiltonian and non-Hamiltonian Lindblad-term projections from an array of Lindblad-operator parameter values.

This function gives the Jacobian of what is returned by :function:`paramvals_to_lindblad_projections` (as a function of the parameters).

Parameters
  • paramvals (numpy.ndarray) – A 1D array of real parameter values consisting of d-1 Hamiltonian values followed by either (d-1)^2 or just d-1 non-Hamiltonian values (the latter when other_mode in (‘diagonal’,’diag_affine’)).

  • ham_basis_size (int) – The number of elements in the Hamiltonian basis used to construct paramvals. As such, ham_basis_size gives the offset into paramvals where the non-Hamiltonian parameters begin.

  • other_basis_size (int) – The number of elements in the non-Hamiltonian basis used to construct paramvals.

  • param_mode ({"unconstrained", "cptp", "depol", "reldepol"}) – Specifies how the Lindblad-term coefficients are mapped to the set of (real) parameter values. This really just applies to the “other” (non-Hamiltonian) coefficients. “unconstrained” means that ranging over the parameter values lets the coefficient-matrix vary over all matrices, “cptp” restricts this to postitive matrices. “depol” maps all of the coefficients to the same, positive parameter (only available for “diagonal” and “diag_affine” other-modes), and “reldepol” does the same thing but without the positivity constraint.

  • other_mode ({"all", "diagonal", "diag_affine"}) – Specifies the structure of the matrix of other (non-Hamiltonian) coefficients. If d is the gate dimension, “all” means a (d-1,d-1) matrix is used; “diagonal” means just the (d2-1,) diagonal of this matrix is used; “diag_affine” means the coefficients are in a (2,d2-1) array with the diagonal-term coefficients being the first row and the affine coefficients being the second row.

  • cache_mx (ndarray, optional) – Scratch space that is used to store the lower-triangular Cholesky decomposition matrix that is used to construct the “other” projections when there is a CPTP constraint.

Returns

  • ham_projs_deriv (numpy.ndarray) – A real array of shape (d-1,nP), where d is the Hamiltonian basis size and nP is the number of parameters (the length of paramvals).

  • other_projs_deriv (numpy.ndarray) – An array of shape (d-1,d-1,nP) or (d-1,nP) or (2,d-1,nP) where d is the size of the “other” basis and nP is the number of parameters (the length of paramvals). In the first case, when param_mode is “unconstrained” or “cptp”, the array is complex, otherwise it is real.

pygsti.tools.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 :function:`pp_matrices` to they are equal to products of the standard Pauli matrices.

Parameters
  • r (tuple) – 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.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
  • model (Model) – The model whose error generator should be projected.

  • target_model (Model) – The set of target (ideal) gates.

  • projectiontypes (tuple 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_models (list of Models) – Elements are projected versions of model corresponding to the elements of projectiontypes.

  • Nps (list of parameter counts) – Integer parameter counts for each model in projected_models. Useful for computing the expected log-likelihood or chi2.

pygsti.tools.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_mx (numpy.ndarray) – Gate matrix to transform.

  • target_gate_mx (numpy.ndarray) – Target gate matrix.

  • return_all (bool, 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

  • U (numpy.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, Utgt (numpy.ndarray) – only if return_all == True. See above.

pygsti.tools.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
  • model (Model) – Model to act on.

  • target_model (Model) – The target model, whose gates define the target eigenspaces being projected onto.

  • eps (float, 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.unitary_to_pauligate(u)

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

Parameters

u (numpy 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.

pygsti.tools.is_valid_lindblad_paramtype(typ)

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

typ (str) – A paramterization type.

Returns

bool

pygsti.tools.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_lbl (Label) – Simplified effect vector.

Returns

str

pygsti.tools.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_lbl (Label) – Simplified effect vector.

Returns

str

pygsti.tools.id2x2
pygsti.tools.sigmax
pygsti.tools.sigmay
pygsti.tools.sigmaz
pygsti.tools.unitary_to_pauligate(u)

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

Parameters

u (numpy 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.

pygsti.tools.sigmaii
pygsti.tools.sigmaix
pygsti.tools.sigmaiy
pygsti.tools.sigmaiz
pygsti.tools.sigmaxi
pygsti.tools.sigmaxx
pygsti.tools.sigmaxy
pygsti.tools.sigmaxz
pygsti.tools.sigmayi
pygsti.tools.sigmayx
pygsti.tools.sigmayy
pygsti.tools.sigmayz
pygsti.tools.sigmazi
pygsti.tools.sigmazx
pygsti.tools.sigmazy
pygsti.tools.sigmazz
pygsti.tools.single_qubit_gate(hx, hy, hz, noise=0)

Construct the single-qubit operation matrix.

Build the operation matrix given by exponentiating -i * (hx*X + hy*Y + hz*Z), where X, Y, and Z are the sigma matrices. Thus, hx, hy, and hz correspond to rotation angles divided by 2. Additionally, a uniform depolarization noise can be applied to the gate.

Parameters
  • hx (float) – Coefficient of sigma-X matrix in exponent.

  • hy (float) – Coefficient of sigma-Y matrix in exponent.

  • hz (float) – Coefficient of sigma-Z matrix in exponent.

  • noise (float, optional) – The amount of uniform depolarizing noise.

Returns

numpy array – 4x4 operation matrix which operates on a 1-qubit density matrix expressed as a vector in the Pauli basis ( {I,X,Y,Z}/sqrt(2) ).

pygsti.tools.two_qubit_gate(ix=0, iy=0, iz=0, xi=0, xx=0, xy=0, xz=0, yi=0, yx=0, yy=0, yz=0, zi=0, zx=0, zy=0, zz=0, ii=0)

Construct the single-qubit operation matrix.

Build the operation matrix given by exponentiating -i * (xx*XX + xy*XY + …) where terms in the exponent are tensor products of two Pauli matrices.

Parameters
  • ix (float, optional) – Coefficient of IX matrix in exponent.

  • iy (float, optional) – Coefficient of IY matrix in exponent.

  • iz (float, optional) – Coefficient of IZ matrix in exponent.

  • xi (float, optional) – Coefficient of XI matrix in exponent.

  • xx (float, optional) – Coefficient of XX matrix in exponent.

  • xy (float, optional) – Coefficient of XY matrix in exponent.

  • xz (float, optional) – Coefficient of XZ matrix in exponent.

  • yi (float, optional) – Coefficient of YI matrix in exponent.

  • yx (float, optional) – Coefficient of YX matrix in exponent.

  • yy (float, optional) – Coefficient of YY matrix in exponent.

  • yz (float, optional) – Coefficient of YZ matrix in exponent.

  • zi (float, optional) – Coefficient of ZI matrix in exponent.

  • zx (float, optional) – Coefficient of ZX matrix in exponent.

  • zy (float, optional) – Coefficient of ZY matrix in exponent.

  • zz (float, optional) – Coefficient of ZZ matrix in exponent.

  • ii (float, optional) – Coefficient of II matrix in exponent.

Returns

numpy array – 16x16 operation matrix which operates on a 2-qubit density matrix expressed as a vector in the Pauli-Product basis.

pygsti.tools.deprecate(replacement=None)

Decorator for deprecating a function.

Parameters

replacement (str, optional) – the name of the function that should replace it.

Returns

function

pygsti.tools.cache_by_hashed_args(obj)

Decorator for caching a function values

Deprecated since version v0.9.8.3: cache_by_hashed_args() will be removed in pyGSTi v0.9.9. Use functools.lru_cache() instead.

Parameters

obj (function) – function to decorate

Returns

function

pygsti.tools.timed_block(label, time_dict=None, printer=None, verbosity=2, round_places=6, pre_message=None, format_str=None)

Context manager that times a block of code

Parameters
  • label (str) – An identifying label for this timed block.

  • time_dict (dict, optional) – A dictionary to store the final time in, under the key label.

  • printer (VerbosityPrinter, optional) – A printer object to log the timer’s message. If None, this message will be printed directly.

  • verbosity (int, optional) – The verbosity level at which to print the time message (if printer is given).

  • round_places (int, opitonal) – How many decimal places of precision to print time with (in seconds).

  • pre_message (str, optional) – A format string to print out before the timer’s message, which formats the label arguent, e.g. “My label is {}”.

  • format_str (str, optional) – A format string used to format the label before the resulting “rendered label” is used as the first argument in the final formatting string “{} took {} seconds”.

pygsti.tools.time_hash()

Get string-version of current time

Returns

str

pygsti.tools.tvd(p, q)

Calculates the total variational distance between two probability distributions.

The distributions must be dictionaries, where keys are events (e.g., bit strings) and values are the probabilities. If an event in the keys of one dictionary isn’t in the keys of the other then that probability is assumed to be zero. There are no checks that the input probability distributions are valid (i.e., that the probabilities sum up to one and are postiive).

Parameters
  • p (dicts) – The distributions to calculate the TVD between.

  • q (dicts) – The distributions to calculate the TVD between.

Returns

float

pygsti.tools.classical_fidelity(p, q)

Calculates the (classical) fidelity between two probability distributions.

The distributions must be dictionaries, where keys are events (e.g., bit strings) and values are the probabilities. If an event in the keys of one dictionary isn’t in the keys of the other then that probability is assumed to be zero. There are no checks that the input probability distributions are valid (i.e., that the probabilities sum up to one and are postiive).

Parameters
  • p (dicts) – The distributions to calculate the TVD between.

  • q (dicts) – The distributions to calculate the TVD between.

Returns

float

pygsti.tools.predicted_rb_number(model, target_model, weights=None, d=None, rtype='EI')

Predicts the RB error rate from a model.

Uses the “L-matrix” theory from Proctor et al Phys. Rev. Lett. 119, 130502 (2017). Note that this gives the same predictions as the theory in Wallman Quantum 2, 47 (2018).

This theory is valid for various types of RB, including standard Clifford RB – i.e., it will accurately predict the per-Clifford error rate reported by standard Clifford RB. It is also valid for “direct RB” under broad circumstances.

For this function to be valid the model should be trace preserving and completely positive in some representation, but the particular representation of the model used is irrelevant, as the predicted RB error rate is a gauge-invariant quantity. The function is likely reliable when complete positivity is slightly violated, although the theory on which it is based assumes complete positivity.

Parameters
  • model (Model) – The model to calculate the RB number of. This model is the model randomly sampled over, so this is not necessarily the set of physical primitives. In Clifford RB this is a set of Clifford gates; in “direct RB” this normally would be the physical primitives.

  • target_model (Model) – The target model, corresponding to model. This function is not invariant under swapping model and target_model: this Model must be the target model, and should consistent of perfect gates.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at each stage of the RB protocol. If not None, the values in weights must all be non-negative, and they must not all be zero. Because, when divided by their sum, they must be a valid probability distribution. If None, the weighting defaults to an equal weighting on all gates, as this is used in many RB protocols (e.g., Clifford RB). But, this weighting is flexible in the “direct RB” protocol.

  • d (int, optional) – The Hilbert space dimension. If None, then sqrt(model.dim) is used.

  • rtype (str, optional) –

    The type of RB error rate, either “EI” or “AGI”, corresponding to different dimension-dependent rescalings of the RB decay constant p obtained from fitting to Pm = A + Bp^m. “EI” corresponds to an RB error rate that is associated with entanglement infidelity, which is the probability of error for a gate with stochastic errors. This is the RB error rate defined in the “direct RB” protocol, and is given by:

    r = (d^2 - 1)(1 - p)/d^2,

    The AGI-type r is given by

    r = (d - 1)(1 - p)/d,

    which is the conventional r definition in Clifford RB. This r is associated with (gate-averaged) average gate infidelity.

Returns

r (float.) – The predicted RB number.

pygsti.tools.predicted_rb_decay_parameter(model, target_model, weights=None)

Computes the second largest eigenvalue of the ‘L matrix’ (see the L_matrix function).

For standard Clifford RB and direct RB, this corresponds to the RB decay parameter p in Pm = A + Bp^m for “reasonably low error” trace preserving and completely positive gates. See also the predicted_rb_number function.

Parameters
  • model (Model) – The model to calculate the RB decay parameter of. This model is the model randomly sampled over, so this is not necessarily the set of physical primitives. In Clifford RB this is a set of Clifford gates; in “direct RB” this normally would be the physical primitives.

  • target_model (Model) – The target model corresponding to model. This function is not invariant under swapping model and target_model: this Model must be the target model, and should consistent of perfect gates.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at each stage of the RB protocol. If not None, the values in weights must all be non-negative, and they must not all be zero. Because, when divided by their sum, they must be a valid probability distribution. If None, the weighting defaults to an equal weighting on all gates, as this is used in many RB protocols (e.g., Clifford RB). But, this weighting is flexible in the “direct RB” protocol.

Returns

p (float.) – The second largest eigenvalue of L. This is the RB decay parameter for various types of RB.

pygsti.tools.rb_gauge(model, target_model, weights=None, mx_basis=None, eigenvector_weighting=1.0)

Computes the gauge transformation required so that the RB number matches the average model infidelity.

This function computes the gauge transformation required so that, when the model is transformed via this gauge-transformation, the RB number – as predicted by the function predicted_rb_number – is the average model infidelity between the transformed model model and the target model target_model. This transformation is defined Proctor et al Phys. Rev. Lett. 119, 130502 (2017), and see also Wallman Quantum 2, 47 (2018).

Parameters
  • model (Model) – The RB model. This is not necessarily the set of physical primitives – it is the model randomly sampled over in the RB protocol (e.g., the Cliffords).

  • target_model (Model) – The target model corresponding to model. This function is not invariant under swapping model and target_model: this Model must be the target model, and should consistent of perfect gates.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at each stage of the RB protocol. If not None, the values in weights must all be non-negative, and they must not all be zero. Because, when divided by their sum, they must be a valid probability distribution. If None, the weighting defaults to an equal weighting on all gates, as this is used in many RB protocols (e.g., Clifford RB). But, this weighting is flexible in the “direct RB” protocol.

  • mx_basis ({"std","gm","pp"}, optional) – The basis of the models. If None, the basis is obtained from the model.

  • eigenvector_weighting (float, optional) – Must be non-zero. A weighting on the eigenvector with eigenvalue that is the RB decay parameter, in the sum of this eigenvector and the eigenvector with eigenvalue of 1 that defines the returned matrix l_operator. The value of this factor does not change whether this l_operator transforms into a gauge in which r = AGsI, but it may impact on other properties of the gates in that gauge. It is irrelevant if the gates are unital.

Returns

l_operator (array) – The matrix defining the gauge-transformation.

pygsti.tools.transform_to_rb_gauge(model, target_model, weights=None, mx_basis=None, eigenvector_weighting=1.0)

Transforms a Model into the “RB gauge” (see the RB_gauge function).

This notion was introduced in Proctor et al Phys. Rev. Lett. 119, 130502 (2017). This gauge is a function of both the model and its target. These may be input in any gauge, for the purposes of obtaining “r = average model infidelity” between the output Model and target_model.

Parameters
  • model (Model) – The RB model. This is not necessarily the set of physical primitives – it is the model randomly sampled over in the RB protocol (e.g., the Cliffords).

  • target_model (Model) – The target model corresponding to model. This function is not invariant under swapping model and target_model: this Model must be the target model, and should consistent of perfect gates.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at each stage of the RB protocol. If not None, the values in weights must all be non-negative, and they must not all be zero. Because, when divided by their sum, they must be a valid probability distribution. If None, the weighting defaults to an equal weighting on all gates, as this is used in many RB protocols (e.g., Clifford RB). But, this weighting is flexible in the “direct RB” protocol.

  • mx_basis ({"std","gm","pp"}, optional) – The basis of the models. If None, the basis is obtained from the model.

  • eigenvector_weighting (float, optional) – Must be non-zero. A weighting on the eigenvector with eigenvalue that is the RB decay parameter, in the sum of this eigenvector and the eigenvector with eigenvalue of 1 that defines the returned matrix l_operator. The value of this factor does not change whether this l_operator transforms into a gauge in which r = AGsI, but it may impact on other properties of the gates in that gauge. It is irrelevant if the gates are unital.

Returns

model_in_RB_gauge (Model) – The model model transformed into the “RB gauge”.

pygsti.tools.L_matrix(model, target_model, weights=None)

Constructs a generalization of the ‘L-matrix’ linear operator on superoperators.

From Proctor et al Phys. Rev. Lett. 119, 130502 (2017), the ‘L-matrix’ is represented as a matrix via the “stack” operation. This eigenvalues of this matrix describe the decay constant (or constants) in an RB decay curve for an RB protocol whereby random elements of the provided model are sampled according to the weights probability distribution over the model. So, this facilitates predictions of Clifford RB and direct RB decay curves.

Parameters
  • model (Model) – The RB model. This is not necessarily the set of physical primitives – it is the model randomly sampled over in the RB protocol (e.g., the Cliffords).

  • target_model (Model) – The target model corresponding to model. This function is not invariant under swapping model and target_model: this Model must be the target model, and should consistent of perfect gates.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at each stage of the RB protocol. If not None, the values in weights must all be non-negative, and they must not all be zero. Because, when divided by their sum, they must be a valid probability distribution. If None, the weighting defaults to an equal weighting on all gates, as this is used in many RB protocols (e.g., Clifford RB). But, this weighting is flexible in the “direct RB” protocol.

Returns

L (float) – A weighted version of the L operator from Proctor et al Phys. Rev. Lett. 119, 130502 (2017), represented as a matrix using the ‘stacking’ convention.

pygsti.tools.R_matrix_predicted_rb_decay_parameter(model, group, group_to_model=None, weights=None)

Returns the second largest eigenvalue of a generalization of the ‘R-matrix’ [see the R_matrix function].

Introduced in Proctor et al Phys. Rev. Lett. 119, 130502 (2017). This number is a prediction of the RB decay parameter for trace-preserving gates and a variety of forms of RB, including Clifford and direct RB. This function creates a matrix which scales super-exponentially in the number of qubits.

Parameters
  • model (Model) – The model to predict the RB decay paramter for. If group_to_model is None, the labels of the gates in model should be the same as the labels of the group elements in group. For Clifford RB this would be the clifford model, for direct RB it would be the primitive gates.

  • group (MatrixGroup) – The group that the model model contains gates from (model does not need to be the full group, and could be a subset of group). For Clifford RB and direct RB, this would be the Clifford group.

  • group_to_model (dict, optional) – If not None, a dictionary that maps labels of group elements to labels of model. If model and group elements have the same labels, this dictionary is not required. Otherwise it is necessary.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at each stage of the RB protocol. If not None, the values in weights must all be positive or zero, and they must not all be zero (because, when divided by their sum, they must be a valid probability distribution). If None, the weighting defaults to an equal weighting on all gates, as used in most RB protocols.

Returns

p (float) – The predicted RB decay parameter. Valid for standard Clifford RB or direct RB with trace-preserving gates, and in a range of other circumstances.

pygsti.tools.R_matrix(model, group, group_to_model=None, weights=None)

Constructs a generalization of the ‘R-matrix’ of Proctor et al Phys. Rev. Lett. 119, 130502 (2017).

This matrix described the exact behaviour of the average success probablities of RB sequences. This matrix is super-exponentially large in the number of qubits, but can be constructed for 1-qubit models.

Parameters
  • model (Model) – The noisy model (e.g., the Cliffords) to calculate the R matrix of. The correpsonding target model (not required in this function) must be equal to or a subset of (a faithful rep of) the group group. If group_to_model `is None, the labels of the gates in model should be the same as the labels of the corresponding group elements in `group. For Clifford RB model should be the clifford model; for direct RB this should be the native model.

  • group (MatrixGroup) – The group that the model model contains gates from. For Clifford RB or direct RB, this would be the Clifford group.

  • group_to_model (dict, optional) – If not None, a dictionary that maps labels of group elements to labels of model. This is required if the labels of the gates in model are different from the labels of the corresponding group elements in group.

  • weights (dict, optional) – If not None, a dictionary of floats, whereby the keys are the gates in model and the values are the unnormalized probabilities to apply each gate at for each layer of the RB protocol. If None, the weighting defaults to an equal weighting on all gates, as used in most RB protocols (e.g., Clifford RB).

Returns

R (float) – A weighted, a subset-sampling generalization of the ‘R-matrix’ from Proctor et al Phys. Rev. Lett. 119, 130502 (2017).

pygsti.tools.errormaps(model, target_model)

Computes the ‘left-multiplied’ error maps associated with a noisy gate set, along with the average error map.

This is the model [E_1,…] such that

G_i = E_iT_i,

where T_i is the gate which G_i is a noisy implementation of. There is an additional gate in the set, that has the key ‘Gavg’. This is the average of the error maps.

Parameters
  • model (Model) – The imperfect model.

  • target_model (Model) – The target model.

Returns

errormaps (Model) – The left multplied error gates, along with the average error map, with the key ‘Gavg’.

pygsti.tools.gate_dependence_of_errormaps(model, target_model, norm='diamond', mx_basis=None)

Computes the “gate-dependence of errors maps” parameter defined by

delta_avg = avg_i|| E_i - avg_i(E_i) ||,

where E_i are the error maps, and the norm is either the diamond norm or the 1-to-1 norm. This quantity is defined in Magesan et al PRA 85 042311 2012.

Parameters
  • model (Model) – The actual model

  • target_model (Model) – The target model.

  • norm (str, optional) – The norm used in the calculation. Can be either ‘diamond’ for the diamond norm, or ‘1to1’ for the Hermitian 1 to 1 norm.

  • mx_basis ({"std","gm","pp"}, optional) – The basis of the models. If None, the basis is obtained from the model.

Returns

delta_avg (float) – The value of the parameter defined above.

pygsti.tools.length(s)

Returns the length (the number of indices) contained in a slice.

Parameters

s (slice) – The slice to operate upon.

Returns

int

pygsti.tools.shift(s, offset)

Returns a new slice whose start and stop points are shifted by offset.

Parameters
  • s (slice) – The slice to operate upon.

  • offset (int) – The amount to shift the start and stop members of s.

Returns

slice

pygsti.tools.intersect(s1, s2)

Returns the intersection of two slices (which must have the same step).

Parameters
  • s1 (slice) – First slice.

  • s2 (slice) – Second slice.

Returns

slice

pygsti.tools.intersect_within(s1, s2)

Returns the intersection of two slices (which must have the same step). and the sub-slice of s1 and s2 that specifies the intersection.

Furthermore, s2 may be an array of indices, in which case the returned slices become arrays as well.

Parameters
  • s1 (slice) – First slice. Must have definite boundaries (start & stop cannot be None).

  • s2 (slice or numpy.ndarray) – Second slice or index array.

Returns

  • intersection (slice or numpy.ndarray) – The intersection of s1 and s2.

  • subslice1 (slice or numpy.ndarray) – The portion of s1 that yields intersection.

  • subslice2 (slice or numpy.ndarray) – The portion of s2 that yields intersection.

pygsti.tools.indices(s, n=None)

Returns a list of the indices specified by slice s.

Parameters
  • s (slice) – The slice to operate upon.

  • n (int, optional) – The number of elements in the array being indexed, used for computing negative start/stop points.

Returns

list of ints

pygsti.tools.list_to_slice(lst, array_ok=False, require_contiguous=True)

Returns a slice corresponding to a given list of (integer) indices, if this is possible.

If not, array_ok determines the behavior.

Parameters
  • lst (list) – The list of integers to convert to a slice (must be contiguous if require_contiguous == True).

  • array_ok (bool, optional) – If True, an integer array (of type numpy.ndarray) is returned when lst does not correspond to a single slice. Otherwise, an AssertionError is raised.

  • require_contiguous (bool, optional) – If True, then lst will only be converted to a contiguous (step=1) slice, otherwise either a ValueError is raised (if array_ok is False) or an array is returned.

Returns

numpy.ndarray or slice

pygsti.tools.to_array(slc_or_list_like)

Returns slc_or_list_like as an index array (an integer numpy.ndarray).

Parameters

slc_or_list_like (slice or list) – A slice, list, or array.

Returns

numpy.ndarray

pygsti.tools.divide(slc, max_len)

Divides a slice into sub-slices based on a maximum length (for each sub-slice).

For example: divide(slice(0,10,2), 2) == [slice(0,4,2), slice(4,8,2), slice(8,10,2)]

Parameters
  • slc (slice) – The slice to divide

  • max_len (int) – The maximum length (i.e. number of indices) allowed in a sub-slice.

Returns

list of slices

pygsti.tools.slice_of_slice(slc, base_slc)

A slice that is the composition of base_slc and slc.

So that when indexing an array a, a[slice_of_slice(slc, base_slc)] == a[base_slc][slc]

Parameters
  • slc (slice) – the slice to take out of base_slc.

  • base_slc (slice) – the original “base” slice to act upon.

Returns

slice

pygsti.tools.slice_hash(slc)
class pygsti.tools._Label

Bases: object

A label used to identify a gate, circuit layer, or (sub-)circuit.

A label consisting of a string along with a tuple of integers or sector-names specifying which qubits, or more generally, parts of the Hilbert space that is acted upon by an object so-labeled.

property depth(self)

The depth of this label, viewed as a sub-circuit.

property reps(self)

Number of repetitions (of this label’s components) that this label represents.

property has_nontrivial_components(self)
collect_args(self)
strip_args(self)
expand_subcircuits(self)

Expand any sub-circuits within this label.

Returns a list of component labels which doesn’t include any CircuitLabel labels. This effectively expands any “boxes” or “exponentiation” within this label.

Returns

tuple – A tuple of component Labels (none of which should be :class:`CircuitLabel`s).

pygsti.tools.smart_cached(obj)

Decorator for applying a smart cache to a single function or method.

Parameters

obj (function) – function to decorate.

Returns

function

pygsti.tools._fastcalc
pygsti.tools.symplectic_form(n, convention='standard')

Creates the symplectic form for the number of qubits specified.

There are two variants, of the sympletic form over the finite field of the integers modulo 2, used in pyGSTi. These corresponding to the ‘standard’ and ‘directsum’ conventions. In the case of ‘standard’, the symplectic form is the 2n x 2n matrix of ((0,1),(1,0)), where ‘1’ and ‘0’ are the identity and all-zeros matrices of size n x n. The ‘standard’ symplectic form is probably the most commonly used, and it is the definition used throughout most of the code, including the Clifford compilers. In the case of ‘directsum’, the symplectic form is the direct sum of n 2x2 bit-flip matrices. This is only used in pyGSTi for sampling from the symplectic group.

Parameters
  • n (int) – The number of qubits the symplectic form should be constructed for. That is, the function creates a 2n x 2n matrix that is a sympletic form

  • convention (str, optional) – Can be either ‘standard’ or ‘directsum’, which correspond to two different definitions for the symplectic form.

Returns

numpy array – The specified symplectic form.

pygsti.tools.change_symplectic_form_convention(s, outconvention='standard')

Maps the input symplectic matrix between the ‘standard’ and ‘directsum’ symplectic form conventions.

That is, if the input is a symplectic matrix with respect to the ‘directsum’ convention and outconvention =’standard’ the output of this function is the equivalent symplectic matrix in the ‘standard’ symplectic form convention. Similarily, if the input is a symplectic matrix with respect to the ‘standard’ convention and outconvention = ‘directsum’ the output of this function is the equivalent symplectic matrix in the ‘directsum’ symplectic form convention.

Parameters
  • s (numpy.ndarray) – The input symplectic matrix.

  • outconvention (str, optional) – Can be either ‘standard’ or ‘directsum’, which correspond to two different definitions for the symplectic form. This is the convention the input is being converted to (and so the input should be a symplectic matrix in the other convention).

Returns

numpy array – The matrix s converted to outconvention.

pygsti.tools.check_symplectic(m, convention='standard')

Checks whether a matrix is symplectic.

Parameters
  • m (numpy array) – The matrix to check.

  • convention (str, optional) – Can be either ‘standard’ or ‘directsum’, Specifies the convention of the symplectic form with respect to which the matrix should be sympletic.

Returns

bool – A bool specifying whether the matrix is symplectic

pygsti.tools.inverse_symplectic(s)

Returns the inverse of a symplectic matrix over the integers mod 2.

Parameters

s (numpy array) – The matrix to invert

Returns

numpy array – The inverse of s, over the field of the integers mod 2.

pygsti.tools.inverse_clifford(s, p)

Returns the inverse of a Clifford gate in the symplectic representation.

This uses the formualas derived in Hostens and De Moor PRA 71, 042315 (2005).

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the Clifford

Returns

  • sinverse (numpy array) – The symplectic matrix representing the inverse of the input Clifford.

  • pinverse (numpy array) – The ‘phase vector’ representing the inverse of the input Clifford.

pygsti.tools.check_valid_clifford(s, p)

Checks if a symplectic matrix - phase vector pair (s,p) is the symplectic representation of a Clifford.

This uses the formualas derived in Hostens and De Moor PRA 71, 042315 (2005).

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the Clifford

Returns

bool – True if (s,p) is the symplectic representation of some Clifford.

pygsti.tools.construct_valid_phase_vector(s, pseed)

Constructs a phase vector that, when paired with the provided symplectic matrix, defines a Clifford gate.

If the seed phase vector, when paired with s, represents some Clifford this seed is returned. Otherwise 1 mod 4 is added to the required elements of the pseed in order to make it at valid phase vector (which is one of many possible phase vectors that, together with s, define a valid Clifford).

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford

  • pseed (numpy array) – The seed ‘phase vector’ over the integers mod 4.

Returns

numpy array – Some p such that (s,p) is the symplectic representation of some Clifford.

pygsti.tools.find_postmultipled_pauli(s, p_implemented, p_target, qubit_labels=None)

Finds the Pauli layer that should be appended to a circuit to implement a given Clifford.

If some circuit implements the clifford described by the symplectic matrix s and the vector p_implemented, this function returns the Pauli layer that should be appended to this circuit to implement the clifford described by s and the vector p_target.

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford implemented by the circuit

  • p_implemented (numpy array) – The ‘phase vector’ over the integers mod 4 representing the Clifford implemented by the circuit

  • p_target (numpy array) – The ‘phase vector’ over the integers mod 4 that, together with s represents the Clifford that you want to implement. Together with s, this vector must define a valid Clifford.

  • qubit_labels (list, optional) – A list of qubit labels, that are strings or ints. The length of this list should be equal to the number of qubits the Clifford acts on. The ith element of the list is the label corresponding to the qubit at the ith index of s and the two phase vectors. If None, defaults to the integers from 0 to number of qubits - 1.

Returns

list – A list that defines a Pauli layer, with the ith element containig one of the 4 tuples (P,qubit_labels[i]) with P = ‘I’, ‘Z’, ‘Y’ and ‘Z’

pygsti.tools.find_premultipled_pauli(s, p_implemented, p_target, qubit_labels=None)

Finds the Pauli layer that should be prepended to a circuit to implement a given Clifford.

If some circuit implements the clifford described by the symplectic matrix s and the vector p_implemented, this function returns the Pauli layer that should be prefixed to this circuit to implement the clifford described by s and the vector p_target.

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford implemented by the circuit

  • p_implemented (numpy array) – The ‘phase vector’ over the integers mod 4 representing the Clifford implemented by the circuit

  • p_target (numpy array) – The ‘phase vector’ over the integers mod 4 that, together with s represents the Clifford that you want to implement. Together with s, this vector must define a valid Clifford.

  • qubit_labels (list, optional) – A list of qubit labels, that are strings or ints. The length of this list should be equal to the number of qubits the Clifford acts on. The ith element of the list is the label corresponding to the qubit at the ith index of s and the two phase vectors. If None, defaults to the integers from 0 to number of qubits - 1.

Returns

list – A list that defines a Pauli layer, with the ith element containig one of the 4 tuples (‘I’,i), (‘X’,i), (‘Y’,i), (‘Z’,i).

pygsti.tools.find_pauli_layer(pvec, qubit_labels, pauli_labels=['I', 'X', 'Y', 'Z'])

TODO: docstring

pygsti.tools.find_pauli_number(pvec)

TODO: docstring

pygsti.tools.compose_cliffords(s1, p1, s2, p2, do_checks=True)

Multiplies two cliffords in the symplectic representation.

The output corresponds to the symplectic representation of C2 times C1 (i.e., C1 acts first) where s1 (s2) and p1 (p2) are the symplectic matrix and phase vector, respectively, for Clifford C1 (C2). This uses the formualas derived in Hostens and De Moor PRA 71, 042315 (2005).

Parameters
  • s1 (numpy array) – The symplectic matrix over the integers mod 2 representing the first Clifford

  • p1 (numpy array) – The ‘phase vector’ over the integers mod 4 representing the first Clifford

  • s2 (numpy array) – The symplectic matrix over the integers mod 2 representing the second Clifford

  • p2 (numpy array) – The ‘phase vector’ over the integers mod 4 representing the second Clifford

  • do_checks (bool) – If True (default), check inputs and output are valid cliffords. If False, these checks are skipped (for speed)

Returns

  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the composite Clifford

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the compsite Clifford

pygsti.tools.symplectic_kronecker(sp_factors)

Takes a kronecker product of symplectic representations.

Construct a single (s,p) symplectic (or stabilizer) representation that corresponds to the tensor (kronecker) product of the objects represented by each (s,p) element of sp_factors.

This is performed by inserting each factor’s s and p elements into the appropriate places of the final (large) s and p arrays. This operation works for combining Clifford operations AND also stabilizer states.

Parameters

sp_factors (iterable) – A list of (s,p) symplectic (or stabilizer) representation factors.

Returns

  • s (numpy.ndarray) – An array of shape (2n,2n) where n is the total number of qubits (the sum of the number of qubits in each sp_factors element).

  • p (numpy.ndarray) – A 1D array of length 2n.

pygsti.tools.prep_stabilizer_state(nqubits, zvals=None)

Contruct the (s,p) stabilizer representation for a computational basis state given by zvals.

Parameters
  • nqubits (int) – Number of qubits

  • zvals (iterable, optional) – An iterable over anything that can be cast as True/False to indicate the 0/1 value of each qubit in the Z basis. If None, the all-zeros state is created. If None, then all zeros is assumed.

Returns

s,p (numpy.ndarray) – The stabilizer “matrix” and phase vector corresponding to the desired state. s has shape (2n,2n) (it includes antistabilizers) and p has shape 2n, where n equals nqubits.

pygsti.tools.apply_clifford_to_stabilizer_state(s, p, state_s, state_p)

Applies a clifford in the symplectic representation to a stabilizer state in the standard stabilizer representation.

The output corresponds to the stabilizer representation of the output state.

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the Clifford

  • state_s (numpy array) – The matrix over the integers mod 2 representing the stabilizer state

  • state_p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the stabilizer state

Returns

  • out_s (numpy array) – The symplectic matrix over the integers mod 2 representing the output state

  • out_p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the output state

pygsti.tools.pauli_z_measurement(state_s, state_p, qubit_index)

Computes the probabilities of 0/1 (+/-) outcomes from measuring a Pauli operator on a stabilizer state.

Parameters
  • state_s (numpy array) – The matrix over the integers mod 2 representing the stabilizer state

  • state_p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the stabilizer state

  • qubit_index (int) – The index of the qubit being measured

Returns

  • p0, p1 (float) – Probabilities of 0 (+ eigenvalue) and 1 (- eigenvalue) outcomes.

  • state_s_0, state_s_1 (numpy array) – Matrix over the integers mod 2 representing the output stabilizer states.

  • state_p_0, state_p_1 (numpy array) – Phase vectors over the integers mod 4 representing the output stabilizer states.

pygsti.tools.colsum(i, j, s, p, n)

A helper routine used for manipulating stabilizer state representations.

Updates the i-th stabilizer generator (column of s and element of p) with the group-action product of the j-th and the i-th generators, i.e.

generator[i] -> generator[j] + generator[i]

Parameters
  • i (int) – Destination generator index.

  • j (int) – Sournce generator index.

  • s (numpy array) – The matrix over the integers mod 2 representing the stabilizer state

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the stabilizer state

  • n (int) – The number of qubits. s must be shape (2n,2n) and p must be length 2n.

Returns

None

pygsti.tools.colsum_acc(acc_s, acc_p, j, s, p, n)

A helper routine used for manipulating stabilizer state representations.

Similar to :function:`colsum` except a separate “accumulator” column is used instead of the i-th column of s and element of p. I.e., this performs:

acc[0] -> generator[j] + acc[0]

Parameters
  • acc_s (numpy array) – The matrix over the integers mod 2 representing the “accumulator” stabilizer state

  • acc_p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the “accumulator” stabilizer state

  • j (int) – Index of the stabilizer generator being accumulated (see above).

  • s (numpy array) – The matrix over the integers mod 2 representing the stabilizer state

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the stabilizer state

  • n (int) – The number of qubits. s must be shape (2n,2n) and p must be length 2n.

Returns

None

pygsti.tools.stabilizer_measurement_prob(state_sp_tuple, moutcomes, qubit_filter=None, return_state=False)

Compute the probability of a given outcome when measuring some or all of the qubits in a stabilizer state.

Returns this probability, optionally along with the updated (post-measurement) stabilizer state.

Parameters
  • state_sp_tuple (tuple) – A (s,p) tuple giving the stabilizer state to measure.

  • moutcomes (array-like) – The z-values identifying which measurement outcome (a computational basis state) to compute the probability for.

  • qubit_filter (iterable, optional) – If not None, a list of qubit indices which are measured. len(qubit_filter) should always equal len(moutcomes). If None, then assume all qubits are measured (len(moutcomes) == num_qubits).

  • return_state (bool, optional) – Whether the post-measurement (w/outcome moutcomes) state is also returned.

Returns

  • p (float) – The probability of the given measurement outcome.

  • state_s,state_p (numpy.ndarray) – Only returned when return_state=True. The post-measurement stabilizer state representation (an updated version of state_sp_tuple).

pygsti.tools.embed_clifford(s, p, qubit_inds, n)

Embeds the (s,p) Clifford symplectic representation into a larger symplectic representation.

The action of (s,p) takes place on the qubit indices specified by qubit_inds.

Parameters
  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the Clifford

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the Clifford

  • qubit_inds (list) – A list or array of integers specifying which qubits s and p act on.

  • n (int) – The total number of qubits

Returns

  • s (numpy array) – The symplectic matrix over the integers mod 2 representing the embedded Clifford

  • p (numpy array) – The ‘phase vector’ over the integers mod 4 representing the embedded Clifford

pygsti.tools.compute_internal_gate_symplectic_representations(gllist=None)

Creates a dictionary of the symplectic representations of ‘standard’ Clifford gates.

Returns a dictionary containing the symplectic matrices and phase vectors that represent the specified ‘standard’ Clifford gates, or the representations of all the standard gates if no list of operation labels is supplied. These ‘standard’ Clifford gates are those gates that are already known to the code gates (e.g., the label ‘CNOT’ has a specfic meaning in the code), and are recorded as unitaries in “internalgates.py”.

Parameters

gllist (list, optional) – If not None, a list of strings corresponding to operation labels for any of the standard gates that have fixed meaning for the code (e.g., ‘CNOT’ corresponds to the CNOT gate with the first qubit the target). For example, this list could be gllist = [‘CNOT’,’H’,’P’,’I’,’X’].

Returns

srep_dict (dict) – dictionary of (smatrix,svector) tuples, where smatrix and svector are numpy arrays containing the symplectic matrix and phase vector representing the operation label given by the key.

pygsti.tools.symplectic_rep_of_clifford_circuit(circuit, srep_dict=None, pspec=None)

Returns the symplectic representation of the composite Clifford implemented by the specified Clifford circuit.

This uses the formualas derived in Hostens and De Moor PRA 71, 042315 (2005).

Parameters
  • circuit (Circuit) – The Clifford circuit to calculate the global action of, input as a Circuit object.

  • srep_dict (dict, optional) – If not None, a dictionary providing the (symplectic matrix, phase vector) tuples associated with each operation label. If the circuit layer contains only ‘standard’ gates which have a hard-coded symplectic representation this may be None. Alternatively, if pspec is specifed and it contains the gates in circuit in a Clifford model, it also does not need to be specified (and it is ignored if it is specified). Otherwise it must be specified.

  • pspec (QubitProcessorSpec, optional) – A QubitProcessorSpec that contains a Clifford model that defines the symplectic action of all of the gates in circuit. If this is not None it over-rides srep_dict. Both pspec and srep_dict can only be None if the circuit contains only gates with names that are hard-coded into pyGSTi.

Returns

  • s (numpy array) – The symplectic matrix representing the Clifford implement by the input circuit

  • p (dictionary of numpy arrays) – The phase vector representing the Clifford implement by the input circuit

pygsti.tools.symplectic_rep_of_clifford_layer(layer, n=None, q_labels=None, srep_dict=None, add_internal_sreps=True)

Constructs the symplectic representation of the n-qubit Clifford implemented by a single quantum circuit layer.

(Gates in a “single layer” must act on disjoint sets of qubits, but not all qubits need to be acted upon in the layer.)

Parameters
  • layer (Label) – A layer label, often a compound label with components. Specifies The Clifford gate(s) to calculate the global action of.

  • n (int, optional) – The total number of qubits. Must be specified if q_labels is None.

  • q_labels (list, optional) – A list of all the qubit labels. If the layer is over qubits that are not labelled by integers 0 to n-1 then it is necessary to specify this list. Note that this should contain all the qubit labels for the circuit that this is a layer from, and they should be ordered as in that circuit, otherwise the symplectic rep returned might not be of the correct dimension or of the correct order.

  • srep_dict (dict, optional) – If not None, a dictionary providing the (symplectic matrix, phase vector) tuples associated with each operation label. If the circuit layer contains only ‘standard’ gates which have a hard-coded symplectic representation this may be None. Otherwise it must be specified. If the layer contains some standard gates it is not necesary to specify the symplectic represenation for those gates.

  • add_internal_sreps (bool, optional) – If True, the symplectic reps for internal gates are calculated and added to srep_dict. For speed, calculate these reps once, store them in srep_dict, and set this to False.

Returns

  • s (numpy array) – The symplectic matrix representing the Clifford implement by specified circuit layer

  • p (numpy array) – The phase vector representing the Clifford implement by specified circuit layer

pygsti.tools.one_q_clifford_symplectic_group_relations()

Gives the group relationship between the ‘I’, ‘H’, ‘P’ ‘HP’, ‘PH’, and ‘HPH’ up-to-Paulis operators.

The returned dictionary contains keys (A,B) for all A and B in the above list. The value for key (A,B) is C if BA = C x some Pauli operator. E,g, (‘P’,’P’) = ‘I’.

This dictionary is important for Compiling multi-qubit Clifford gates without unneccessary 1-qubit gate over-heads. But note that this dictionary should not be used for compressing circuits containing these gates when the exact action of the circuit is of importance (not only the up-to-Paulis action of the circuit).

Returns

dict

pygsti.tools.unitary_is_clifford(unitary)

Returns True if the unitary is a Clifford gate (w.r.t the standard basis), and False otherwise.

Parameters

unitary (numpy.ndarray) – A unitary matrix to test.

Returns

bool

pygsti.tools._unitary_to_symplectic_1q(u, flagnonclifford=True)

Returns the symplectic representation of a single qubit Clifford unitary, input as a complex matrix in the standard computational basis.

Parameters
  • u (numpy array) – The unitary matrix to construct the symplectic representation for. This must be a single-qubit gate (so, it is a 2 x 2 matrix), and it must be in the standard computational basis. E.g., the unitary for the Z gate is matrix ((1.,0.),(0.,-1.)). It also must be a Clifford gate in the standard sense.

  • flagnonclifford (bool, opt) – If True, a ValueError is raised when the input unitary is not a Clifford gate. If False, when the unitary is not a Clifford the returned s and p are None.

Returns

  • s (numpy array or None) – The symplectic matrix representing the unitary, or None if the input unitary is not a Clifford and flagnonclifford is False

  • p (numpy array or None) – The phase vector representing the unitary, or None if the input unitary is not a Clifford and flagnonclifford is False

pygsti.tools._unitary_to_symplectic_2q(u, flagnonclifford=True)

Returns the symplectic representation of a two-qubit Clifford unitary, input as a complex matrix in the standard computational basis.

Parameters
  • u (numpy array) – The unitary matrix to construct the symplectic representation for. This must be a two-qubit gate (so, it is a 4 x 4 matrix), and it must be in the standard computational basis. It also must be a Clifford gate in the standard sense.

  • flagnonclifford (bool, opt) – If True, n ValueError is raised when the input unitary is not a Clifford gate. If False, when the unitary is not a Clifford the returned s and p are None.

Returns

  • s (numpy array or None) – The symplectic matrix representing the unitary, or None if the input unitary is not a Clifford and flagnonclifford is False

  • p (numpy array or None) – The phase vector representing the unitary, or None if the input unitary is not a Clifford and flagnonclifford is False

pygsti.tools.unitary_to_symplectic(u, flagnonclifford=True)

Returns the symplectic representation of a one-qubit or two-qubit Clifford unitary.

The Clifford is input as a complex matrix in the standard computational basis.

Parameters
  • u (numpy array) – The unitary matrix to construct the symplectic representation for. This must be a one-qubit or two-qubit gate (so, it is a 2 x 2 or 4 x 4 matrix), and it must be provided in the standard computational basis. It also must be a Clifford gate in the standard sense.

  • flagnonclifford (bool, opt) – If True, a ValueError is raised when the input unitary is not a Clifford gate. If False, when the unitary is not a Clifford the returned s and p are None.

Returns

  • s (numpy array or None) – The symplectic matrix representing the unitary, or None if the input unitary is not a Clifford and flagnonclifford is False

  • p (numpy array or None) – The phase vector representing the unitary, or None if the input unitary is not a Clifford and flagnonclifford is False

pygsti.tools.random_symplectic_matrix(n, convention='standard', rand_state=None)

Returns a symplectic matrix of dimensions 2n x 2n sampled uniformly at random from the symplectic group S(n).

This uses the method of Robert Koenig and John A. Smolin, presented in “How to efficiently select an arbitrary Clifford group element”.

Parameters
  • n (int) – The size of the symplectic group to sample from.

  • convention (str, optional) – Can be either ‘standard’ or ‘directsum’, which correspond to two different definitions for the symplectic form. In the case of ‘standard’, the symplectic form is the 2n x 2n matrix of ((0,1),(1,0)), where ‘1’ and ‘0’ are the identity and all-zeros matrices of size n x n. The ‘standard’ symplectic form is the convention used throughout most of the code. In the case of ‘directsum’, the symplectic form is the direct sum of n 2x2 bit-flip matrices.

  • rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG

Returns

s (numpy array) – A uniformly sampled random symplectic matrix.

pygsti.tools.random_clifford(n, rand_state=None)

Returns a Clifford, in the symplectic representation, sampled uniformly at random from the n-qubit Clifford group.

The core of this function uses the method of Robert Koenig and John A. Smolin, presented in “How to efficiently select an arbitrary Clifford group element”, for sampling a uniformly random symplectic matrix.

Parameters
  • n (int) – The number of qubits the Clifford group is over.

  • rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG

Returns

  • s (numpy array) – The symplectic matrix representating the uniformly sampled random Clifford.

  • p (numpy array) – The phase vector representating the uniformly sampled random Clifford.

pygsti.tools.random_phase_vector(s, n, rand_state=None)

Generates a uniformly random phase vector for a n-qubit Clifford.

(This vector, together with the provided symplectic matrix, define a valid Clifford operation.) In combination with a uniformly random s the returned p defines a uniformly random Clifford gate.

Parameters
  • s (numpy array) – The symplectic matrix to construct a random phase vector

  • n (int) – The number of qubits the Clifford group is over.

  • rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG

Returns

p (numpy array) – A phase vector sampled uniformly at random from all those phase vectors that, as a pair with s, define a valid n-qubit Clifford.

pygsti.tools.bitstring_for_pauli(p)

Get the bitstring corresponding to a Pauli.

The state, represented by a bitstring, that the Pauli operator represented by the phase-vector p creates when acting on the standard input state.

Parameters

p (numpy.ndarray) – Phase vector of a symplectic representation, encoding a Pauli operation.

Returns

list – A list of 0 or 1 elements.

pygsti.tools.apply_internal_gate_to_symplectic(s, gate_name, qindex_list, optype='row')

Applies a Clifford gate to the n-qubit Clifford gate specified by the 2n x 2n symplectic matrix.

The Clifford gate is specified by the internally hard-coded name gate_name. This gate is applied to the qubits with indices in qindex_list, where these indices are w.r.t to indeices of s. This gate is applied from the left (right) of s if optype is ‘row’ (‘column’), and has a row-action (column-action) on s. E.g., the Hadmard (‘H’) on qubit with index i swaps the ith row (or column) with the (i+n)th row (or column) of s; CNOT adds rows, etc.

Note that this function updates s, and returns None.

Parameters
  • s (np.array) – A even-dimension square array over [0,1] that is the symplectic representation of some (normally multi-qubit) Clifford gate.

  • gate_name (str) – The gate name. Should be one of the gate-names of the hard-coded gates used internally in pyGSTi that is also a Clifford gate. Currently not all of those gates are supported, and gate_name must be one of: ‘H’, ‘P’, ‘CNOT’, ‘SWAP’.

  • qindex_list (list or tuple) – The qubit indices that gate_name acts on (can be either length 1 or 2 depending on whether the gate acts on 1 or 2 qubits).

  • optype ({'row', 'column'}, optional) – Whether the symplectic operator type uses rows or columns: TODO: docstring - better explanation.

Returns

None

pygsti.tools.compute_num_cliffords(n)

The number of Clifford gates in the n-qubit Clifford group.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters

n (int) – The number of qubits the Clifford group is over.

Returns

long integer – The cardinality of the n-qubit Clifford group.

pygsti.tools.compute_num_symplectics(n)

The number of elements in the symplectic group S(n) over the 2-element finite field.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters

n (int) – S(n) group parameter.

Returns

int

pygsti.tools.compute_num_cosets(n)

Returns the number of different cosets for the symplectic group S(n) over the 2-element finite field.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters

n (int) – S(n) group parameter.

Returns

int

pygsti.tools.symplectic_innerproduct(v, w)

Returns the symplectic inner product of two vectors in F_2^(2n).

Here F_2 is the finite field containing 0 and 1, and 2n is the length of the vectors. Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters
  • v (numpy.ndarray) – A length-2n vector.

  • w (numpy.ndarray) – A length-2n vector.

Returns

int

pygsti.tools.symplectic_transvection(k, v)

Applies transvection Z k to v.

Code from “How to efficiently select an arbitrary Clifford group element by Robert Koenig and John A. Smolin.

Parameters
  • k (numpy.ndarray) – A length-2n vector.

  • v (numpy.ndarray) – A length-2n vector.

Returns

numpy.ndarray

pygsti.tools.int_to_bitstring(i, n)

Converts integer i to an length n array of bits.

Code from “How to efficiently select an arbitrary Clifford group element by Robert Koenig and John A. Smolin.

Parameters
  • i (int) – Any integer.

  • n (int) – Number of bits

Returns

numpy.ndarray – Integer array of 0s and 1s.

pygsti.tools.bitstring_to_int(b, n)

Converts an n-bit string b to an integer between 0 and 2^`n` - 1.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters
  • b (list, tuple, or array) – Sequence of bits (a bitstring).

  • n (int) – Number of bits.

Returns

int

pygsti.tools.find_symplectic_transvection(x, y)

A utility function for selecting a random Clifford element.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters
  • x (numpy.ndarray) – A length-2n vector.

  • y (numpy.ndarray) – A length-2n vector.

Returns

numpy.ndarray

pygsti.tools.compute_symplectic_matrix(i, n)

Returns the 2n x 2n symplectic matrix, over the finite field containing 0 and 1, with the “canonical” index i.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters
  • i (int) – Canonical index.

  • n (int) – Number of qubits.

Returns

numpy.ndarray

pygsti.tools.compute_symplectic_label(gn, n=None)

Returns the “canonical” index of 2n x 2n symplectic matrix gn over the finite field containing 0 and 1.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters
  • gn (numpy.ndarray) – symplectic matrix

  • n (int, optional) – Number of qubits (if None, use gn.shape[0] // 2).

Returns

int – The canonical index of gn.

pygsti.tools.random_symplectic_index(n, rand_state=None)

The index of a uniformly random 2n x 2n symplectic matrix over the finite field containing 0 and 1.

Code from “How to efficiently select an arbitrary Clifford group element” by Robert Koenig and John A. Smolin.

Parameters
  • n (int) – Number of qubits (half dimension of symplectic matrix).

  • rand_state (RandomState, optional) – A np.random.RandomState object for seeding RNG

Returns

numpy.ndarray

class pygsti.tools.TypedDict(types=None, items=())

Bases: dict

A dictionary that holds per-key type information.

This type of dict is used for the “leaves” in a tree of nested NamedDict objects, specifying a collection of data of different types pertaining to some set of category labels (the index-path of the named dictionaries).

When converted to a data frame, each key specifies a different column and values contribute the values of a single data frame row. Columns will be series of the held data types.

Parameters
  • types (dict, optional) – Keys are the keys that can appear in this dictionary, and values are valid data frame type strings, e.g. “int”, “float”, or “category”, that specify the type of each value.

  • items (dict or list) – Initial data, used for serialization.

__reduce__(self)

Helper for pickle.

as_dataframe(self)

Render this dict as a pandas data frame.

Returns

pandas.DataFrame

_add_to_columns(self, columns, seriestypes, row_prefix)