# `pygsti.tools.matrixtools`

Matrix related utility functions

## Module Contents

### Functions

 `is_hermitian`(mx[, tol]) Test whether mx is a hermitian matrix. `is_pos_def`(mx[, tol]) Test whether mx is a positive-definite matrix. `is_valid_density_mx`(mx[, tol]) Test whether mx is a valid density matrix (hermitian, positive-definite, and unit trace). `nullspace`(m[, tol]) Compute the nullspace of a matrix. `nullspace_qr`(m[, tol]) Compute the nullspace of a matrix using the QR decomposition. `nice_nullspace`(m[, tol, orthogonalize]) Computes the nullspace of a matrix, and tries to return a "nice" basis for it. `normalize_columns`(m[, return_norms, ord]) Normalizes the columns of a matrix. `column_norms`(m[, ord]) 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]) Checks whether a matrix contains orthogonal columns. `columns_are_orthonormal`(m[, tol]) Checks whether a matrix contains orthogonal columns. `independent_columns`(m[, initial_independent_cols, tol]) Computes the indices of the linearly-independent columns in a matrix. TODO: docstring The "sign" matrix of m `print_mx`(mx[, width, prec, withbrackets]) Print matrix in pretty format. `mx_to_string`(m[, width, prec, withbrackets]) Generate a "pretty-format" string for a matrix. `mx_to_string_complex`(m[, real_width, im_width, prec]) 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]) Construct the logarithm of superoperator matrix m that is near the identity. `approximate_matrix_log`(m, target_logm[, ...]) Construct an approximate logarithm of superoperator matrix m that is real and near the target_logm. `real_matrix_log`(m[, action_if_imaginary, tol]) 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. Returns the 1 norm of a matrix Generates a random Hermitian matrix `norm1to1`(operator[, num_samples, mx_basis, return_list]) The Hermitian 1-to-1 norm of a superoperator represented in the standard basis. 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, return_pairs, ...]) Matches the elements of two vectors, a and b by minimizing the weight between them. `minweight_match_realmxeigs`(a, b[, metricfn, ...]) Matches the elements of a and b, whose elements are assumed to either real or one-half of a conjugate pair. `safe_dot`(a, b) Performs dot(a,b) correctly when neither, either, or both arguments are sparse matrices. `safe_real`(a[, inplace, check]) Get the real-part of a, where a can be either a dense array or a sparse matrix. `safe_imag`(a[, inplace, check]) Get the imaginary-part of a, where a can be either a dense array or a sparse matrix. `safe_norm`(a[, part]) Get the frobenius norm of a matrix or vector, a, when it is either a dense array or a sparse matrix. 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, ...) Computation of the summation of several CSR-format sparse matrices. `expm_multiply_prep`(a[, tol]) Computes "prepared" meta-info about matrix a, to be used in expm_multiply_fast. `expm_multiply_fast`(prep_a, v[, tol]) Multiplies v by an exponentiated matrix. `expop_multiply_prep`(op[, a_1_norm, tol]) Returns "prepared" meta-info about operation op, which is assumed to be traceless (so no shift is needed). `sparse_equal`(a, b[, atol]) Checks whether two Scipy sparse matrices are (almost) equal. Computes the 1-norm of the scipy sparse matrix a. `ndarray_base`(a[, verbosity]) 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. 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]) Removes the linearly dependent columns of a matrix. `intersection_space`(space1, space2[, tol, ...]) TODO: docstring `union_space`(space1, space2[, tol]) TODO: docstring `jamiolkowski_angle`(hamiltonian_mx) TODO: docstring `zvals_to_dense`(self, zvals[, superket]) Construct the dense operator or superoperator representation of a computational basis state. Compute the partity of x. `zvals_int64_to_dense`(zvals_int, nqubits[, outvec, ...]) Fills a dense array with the super-ket representation of a computational basis state. `sign_fix_qr`(q, r[, tol]) Change the signs of the columns of Q and rows of R to follow a convention.

### Attributes

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

Test whether mx is a hermitian matrix.

#### Parameters

mxnumpy array

Matrix to test.

tolfloat, 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

mxnumpy array

Matrix to test.

tolfloat, 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

mxnumpy array

Matrix to test.

tolfloat, optional

Tolerance on absolute magitude of elements.

#### Returns

bool

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

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

Compute the nullspace of a matrix.

#### Parameters

mnumpy array

An matrix of shape (M,N) whose nullspace to compute.

tolfloat , 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

mnumpy array

An matrix of shape (M,N) whose nullspace to compute.

tolfloat , 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, orthogonalize=False)

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

mnumpy array

An matrix of shape (M,N) whose nullspace to compute.

tolfloat , optional

Nullspace tolerance, used when comparing diagonal values of R with zero.

orthogonalizebool, optional

If True, the nullspace vectors are additionally orthogonalized.

#### 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

mnumpy.ndarray or scipy sparse matrix

The matrix.

return_normsbool, optional

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

ordint or list of ints, optional

The order of the norm. See `numpy.linalg.norm()`. An array of orders can be given to specify the norm on a per-column basis.

#### Returns

normalized_mnumpy.ndarray

The matrix after columns are normalized

column_normsnumpy.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

mnumpy.ndarray or scipy sparse matrix

The matrix.

ordint or list of ints, optional

The order of the norm. See `numpy.linalg.norm()`. An array of orders can be given to specify the norm on a per-column basis.

#### 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

mnumpy.ndarray or scipy sparse matrix

The matrix.

scale_valuesnumpy.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

mnumpy.ndarray

The matrix to check.

tolfloat, 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

mnumpy.ndarray

The matrix to check.

tolfloat, 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

mnumpy.ndarray or scipy sparse matrix

The matrix.

initial_independent_colsnumpy.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.

tolfloat, 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

mnumpy.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

mxnumpy array

the matrix (2-D array) to print.

widthint, opitonal

the width (in characters) of each printed element

precint optional

the precision (in characters) of each printed element

withbracketsbool, 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

mnumpy.ndarray

array to print.

widthint, opitonal

the width (in characters) of each converted element

precint optional

the precision (in characters) of each converted element

withbracketsbool, 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

mnumpy array

array to format.

real_widthint, opitonal

the width (in characters) of the real part of each element.

im_widthint, opitonal

the width (in characters) of the imaginary part of each element.

precint 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

mnumpy 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

mnumpy array

The superoperator matrix whose logarithm is taken

tolfloat, 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

mnumpy array

The superoperator matrix whose logarithm is taken

target_logmnumpy array

The target logarithm

target_weightfloat

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.

tolfloat, optional

Optimzer tolerance.

#### Returns

logMnumpy 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

mnumpy 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.

tolfloat, optional

An internal tolerance used when testing for equivalence and zero imaginary parts (real-ness).

#### Returns

logMnumpy 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

iint

Basis vector index.

dimint

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

mnumpy.ndarray

The matrix.

#### Returns

numpy.ndarray

pygsti.tools.matrixtools.random_hermitian(dim)

Generates a random Hermitian matrix

#### Parameters

dimint

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

operatornumpy.ndarray

The operator matrix to take the norm of.

num_samplesint, optional

Number of Monte-Carlo samples.

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

The basis of operator.

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

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

nint

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

alist or numpy.ndarray

First 1D array to match elements between.

blist or numpy.ndarray

Second 1D array to match elements between.

metricfnfunction, 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_pairsbool, optional

If True, the matching is also returned.

pass_indices_to_metricfnbool, optional

If True, the metric function is passed two indices into the a and b arrays, respectively, instead of the values.

#### Returns

weight_arraynumpy.ndarray

The array of weights corresponding to the min-weight matching. The sum of this array’s elements is the minimized total weight.

pairslist

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

anumpy.ndarray

First 1D array to match.

bnumpy.ndarray

Second 1D array to match.

metricfnfunction, 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_metricfnbool, optional

If True, the metric function is passed two indices into the a and b arrays, respectively, instead of the values.

epsfloat, optional

Tolerance when checking if eigenvalues are equal to each other.

#### Returns

pairslist

A list of 2-tuple pairs of indices (ix,iy) giving the indices into a and b respectively of each matched pair.

pygsti.tools.matrixtools.safe_dot(a, b)

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

#### Parameters

anumpy.ndarray or scipy.sparse matrix.

First matrix.

bnumpy.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

anumpy.ndarray or scipy.sparse matrix.

Array to take real part of.

inplacebool, optional

Whether this operation should be done in-place.

checkbool, 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

anumpy.ndarray or scipy.sparse matrix.

Array to take imaginary part of.

inplacebool, optional

Whether this operation should be done in-place.

checkbool, 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

andarray 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

andarray 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 `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_matriceslist

The SciPy CSR matrices to be summed.

#### Returns

ind_arrayslist

A list of numpy arrays giving the destination data-array indices of each element of csr_matrices.

indptr, indicesnumpy.ndarray

The row-pointer and column-indices arrays specifying the sparsity structure of a the destination CSR matrix.

Nint

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.

`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

datanumpy.ndarray

The data-array of the destination CSR-matrix.

coeffsiterable

The weight coefficients which multiply each summed matrix.

csr_mxsiterable

A list of CSR matrix objects whose data-array is given by obj.data (e.g. a SciPy CSR sparse matrix).

csr_sum_indiceslist

A list of precomputed index arrays as returned by `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 `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_matriceslist

The SciPy CSR matrices to be summed.

#### Returns

flat_dest_index_arraynumpy 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_datanumpy array

A 1D array of the same length as flat_dest_index_array, which simply concatenates the data arrays of csr_matrices.

mx_nnz_indptrnumpy 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, indicesnumpy.ndarray

The row-pointer and column-indices arrays specifying the sparsity structure of a the destination CSR matrix.

Nint

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.

`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

datanumpy.ndarray

The data-array of the destination CSR-matrix.

coeffsndarray

The weight coefficients which multiply each summed matrix.

flat_dest_index_arrayndarray

The index array generated by `csr_sum_flat_indices()`.

flat_csr_mx_datandarray

The data array generated by `csr_sum_flat_indices()`.

mx_nnz_indptrndarray

The number-of-nonzero-elements pointer array generated by `csr_sum_flat_indices()`.

#### 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

anumpy.ndarray

the matrix that will be later exponentiated.

tolfloat, 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_atuple

A tuple of values from `expm_multiply_prep()` that defines the matrix to be exponentiated and holds other pre-computed quantities.

vnumpy.ndarray

Vector to multiply (take dot product with).

tolfloat, optional

Tolerance used to within matrix exponentiation routines.

#### Returns

numpy.ndarray

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

opscipy.sparse.linalg.LinearOperator

The operator to exponentiate.

a_1_normfloat, optional

The 1-norm (if computed separately) of op.

tolfloat, 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

ascipy.sparse matrix

First matrix.

bscipy.sparse matrix

Second matrix.

atolfloat, 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

ascipy 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

anumpy.ndarray

Array to get base of.

verbosityint, 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_unitaryndarray

A scaled unitary matrix

#### Returns

scale : float

unitaryndarray

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

mxnumpy.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

eigenvaluesnumpy.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

unumpy.ndarray

Usually the eigenvector matrix of a gate (G).

u_invnumpy.ndarray

Inverse of u.

u0numpy.ndarray

Usually the eigenvector matrix of the corresponding target gate (G0).

u0_invnumpy.ndarray

Inverse of u0.

kitelist

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

mxnumpy.ndarray

Matrix to project.

kitelist

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

mxnumpy.ndarray

Matrix to project.

kitelist

A kite structure.

#### Returns

numpy.ndarray

pygsti.tools.matrixtools.remove_dependent_cols(mx, tol=1e-07)

Removes the linearly dependent columns of a matrix.

mxnumpy.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

zvalslist or numpy.ndarray

The z-values, each 0 or 1, defining the computational basis state.

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

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_intint64

The array of (up to 64) z-values, encoded as the 0s and 1s in the binary representation of this integer.

nqubitsint

The number of z-values (up to 64)

outvecnumpy.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_sparsitybool, 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_elvalfloat

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.matrixtools.sign_fix_qr(q, r, tol=1e-06)

Change the signs of the columns of Q and rows of R to follow a convention.

Flips the signs of Q-columns and R-rows from a QR decomposition so that the largest absolute element in each Q-column is positive. This is an arbitrary but consisten convention that resolves sign-ambiguity in the output of a QR decomposition.

#### Parameters

q, rnumpy.ndarray

Input Q and R matrices from QR decomposition.

tolfloat, optional

Tolerance for computing the maximum element, i.e., anything within tol of the true max is counted as a maximal element, the first of which is set positive by the convention.

#### Returns

qq, rrnumpy.ndarray

Updated versions of q and r.