pygsti.tools.matrixtools¶

Matrix related utility functions

Module Contents¶

Functions¶

 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), 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. 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. 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. 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.

Attributes¶

pygsti.tools.matrixtools._fastcalc
pygsti.tools.matrixtools.EXPM_DEFAULT_TOL
pygsti.tools.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.pinv_of_matrix_with_orthogonal_columns(m)

TODO: docstring

pygsti.tools.matrixtools.matrix_sign(m)

The “sign” matrix of m

Parameters

m (numpy.ndarray) – the matrix.

Returns

numpy.ndarray

pygsti.tools.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.vec(matrix_in)

Stacks the columns of a matrix to return a vector

Parameters

matrix_in (numpy.ndarray) –

Returns

numpy.ndarray

pygsti.tools.matrixtools.unvec(vector_in)

Slices a vector into the columns of a matrix.

Parameters

vector_in (numpy.ndarray) –

Returns

numpy.ndarray

pygsti.tools.matrixtools.norm1(m)

Returns the 1 norm of a matrix

Parameters

m (numpy.ndarray) – The matrix.

Returns

numpy.ndarray

pygsti.tools.matrixtools.random_hermitian(dim)

Generates a random Hermitian matrix

Parameters

dim (int) – the matrix dimensinon.

Returns

numpy.ndarray

pygsti.tools.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.

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.matrixtools._findx_shape(a, inds)

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

pygsti.tools.matrixtools._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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools._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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.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.matrixtools.intersection_space(space1, space2, tol=1e-07, use_nice_nullspace=False)

TODO: docstring

pygsti.tools.matrixtools.union_space(space1, space2, tol=1e-07)

TODO: docstring

pygsti.tools.matrixtools.jamiolkowski_angle(hamiltonian_mx)

TODO: docstring

pygsti.tools.matrixtools.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.matrixtools.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.matrixtools.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