QLib features

Below is a complete detailing of QLib's current capabilities.


Entities - General

QLib is capable of handling a variety of objects - classical probability distributions (CPD), pure states and density matrices (DM). All of which allow any number of particles, with any number of degrees of freedom (henceforth, DoF).


Many of the QLib functions expect a "descriptor" of the state - a row vector specifying the number of DoF of each particle.
For example, a qubit, qutrite, qubit would be [2,3,2]
Desc is often used as a shorthand for the descriptor.

Name descriptor

An array of names for the "particles".
Default naming convention is {'A','B','C',...}
Some functions which change the participating particles in the state can also manipulate the name index to match the output.

Tensoric representation

In addition to the normal representation (column vector for CPDs and pure states, square matrix for DMs), a tensoric representation is also available, where each particle state is represented as a tensor.

If we consider for example a CPDs or pure state with the descriptor [2 3 5], the indexes would be (A_index, B_index, C_index), and the tensoric representation would be a 3d tensor 2-by-3-by-5.

The same descriptor applied to a DM would create a 6d tensor, 2x2x3x3x5x5, indexed (A_ket,A_bra,B_ket,B_bra,C_ket,C_bra), with "ket" being the DM's row number and "bra" the column.

Note that while the tensoric representation may be more convenient for various calculations, it does not imply any additional semantics.

Bipartition mask

For various purposes, one needs to bipartition a state (Schmidt decomposition, partial trace, etc). In these instances, QLib requires the partition be specified using a mask - a vector, the same length as the descriptor, with "1" for one side of the partition (the "selected part", if applicable) and "0" for the other.


Pure states

A column vector of complex numbers, of length: prod(desc).

Phase normalization often used so that the first non-zero element is real.

Ordering of elements is with A being the most significant digit. For example, consider a state with descriptor [3,2]. If A=0,1,2 and B=0,1, then the order of elements is (left to right) 00,01,10,11,20,21, with A being the left-most/most significant digit.

CPD - Classical Probability Distribution

Similar in structure to a pure state, except all numbers are real (normalization is, of course L1).

Density matrix

A complex (Hermitian) matrix of product(desc)^2 elements. Ordering within each row/column is as for pure states.

Entities - Functions

Handling entities - General

validate_dmMake sure a matrix describes a good DM. If yes, return unchanged. If not, issue an error
validate_pureMake sure a vector describes a good pure state. If yes, return unchanged. If not, issue an error
validate_cpdMake sure a vector describes a good CPD. If yes, return unchanged. If not, issue an error
is_dm_validIs the matrix a DM?
is_pure_validIs the vector a proper pure state?
is_cpd_validIs the vector a proper CPD?
comm, a_comm Matrix (anti) commutation
validate_pure Make sure a value describes a good pure state
validate_dm Make sure a value describes a good DM
gen_desc Generate a descriptor assuming all qubits (2^N)
gen_name_desc Generate the default name descriptor
dephase_pure Remove global phase from a pure state
is_pure Does the DM represent a pure state?
normalize_classical Normalize a classical probability distribution
normalize_pure Normalize a pure state
normalize_dm Normalize a density matrix to have trace 1
cannonize_pure Set the global phase of a pure state to 1 (i.e. make the first non-zero element real)
is_product Is the DM/pure a product of the single-density DMs?
Schmidt_decomp Find the Schmidt decomposition (coefficient and base) for a pure state
trace_norm Compute the trace norm of a matrix
all_masks Generate masks for all partitions of a set of particles
all_bipartition_masksGenerate all bipartition masks
pure_norm Find the norm of a pure state (should be 1)

Handling entities - Shape shifting

pure2dm Convert a pure state to a density matrix
dm2pure Convert a DM representing a pure state to a state-vector
dm2tensor Transforms a matrix into a density tensor
tensor2dm Transforms a density tensor to a density matrix
partial_trace Trace out any number of DoF from a DM
partial_trace_pure Trace out any number of DoF from a pure state
partial_trace_cpd Trace out any number of DoF from a CPD
permute_dof_dm Permute DoF of a DM
permute_dof_pure Permute DoF of a pure state
ipermute_dof_dm Inverse-permute DoF of a DM
ipermute_dof_pure Inverse-permute DoF of a pure state
partial_transpose Transpose any subset of particles
classical2dm Convert a classical distribution vector to a DM
dm2classical Convert a DM to a classical distribution vector
pure2tensor Convert a pure state or classical distribution vectors to a tensor
tensor2pure Convert a tensor to a pure state or classical distribution vectors
reorder_and_merge_dm_dimsReorder and/or merge DoF in a DM
reorder_and_merge_pure_dimsReorder and/or merge DoF in a pure state
purify_compact Purify a mixed state using the minimal number of DoF possible
purify_full Purify a mixed state using the same no. of DoF as in the original state

Handling entities - Famous states
Note: The Bell states are provided as constants under the qlib.Bell global variable. See below.

GHZ Generate a (generalized) GHZ state
W101 Generate a (generalized) W state
Werner Generate a (generalized) Werner state
Gisin Generate the Gisin state
rho3 Generate the rho3 state

Entropy, Entanglement, Distances, etc


concurrenceCompute the concurrence of a 2-qubit DM
concurrence_pureCompute the concurrence of a 2-qubit pure state
entanglement_of_formationCompute the entanglement of formation for a two qubit state
entanglementThe entanglement of a given bipartition of a pure state
logarithmic_negativityCompute the logarithmic negativity of a DM
is_entangled_ptPeres-Horodecki entanglement witness (yes/no/don't-know) for a given bipartition of a DM
is_entangled_all_ptPeres-Horodecki entanglement witness for all bipartition of a DM (is there any entanglement in a state)
negativityCompute the negativity of a DM
relative_entanglementRelative entanglement (minimal Kullback-Leibler distance to a separable state)
robustness_pureThe robustness of a pure state (minimal mixing with random state to be separable)
singlet_fractionCompute (by searching for) the (generalized) singlet fraction for any given bipartition of any DM
Schmidt_numberThe number of non-zero Schmidt coefficients
tangleCompute the tangle (for 3-qubit pure state or 2-qubit DM)

Entropy and mixedness

H_ShannonShannon entropy
S_Von_NeumannVon-neumann entropy
SvN2Compute the Von-neumann entropy for [p 1-p]
linear_entropyCompute the linear entropy of a given density matrix
relative_entropyRelative entanglement (minimal Kullback-Leibler distance to a product state)
participation_ratioEstimate of the effective number of states in the mixture
purityThe purity (measure of mixedness) of a given density matrix

Mutual information

mutual_info_dmMutual information for a given bipartition of a DM
mutual_info_pureMutual information for a given bipartition of a pure state
mutual_info_cpdMutual information for a given bipartition of a CPD


act_onAct with an operator on some of the DoF of a system
expand_opExpand / reorder DoF in an operator to fit the entire system
measurePerform a measurement on a (sub)system, returning the resulting mixed state
collapseCompute the various collapsed "universes" and their probabilities when measuring a system
weak_measurementCompute the real part of a weakly measured value
is_Krauss_set_validCheck if you have a complete valid set of Krauss operators (Boolean function)
validate_Krauss_setValidate you have a complete valid set of Krauss operators (error if not)
complete_Krauss_setComplete a Krauss set to unity
collapse_povmPerform a generalized measurement using a set of Krauss operators

Distance Measures

dist_trace The trace distance
fidelity Fidelity between two DMs
dist_KL Compute the Kullback-Leibler "distance" between two density matrices
dist_KL_CPD Compute the Kullback-Leibler "distance" between two CPDs
dist_BuresCompute the Bures distance between two density matrices
dist_Bures_angleCompute the Bures angle between two density matrices
dist_Fubini_StudyThe Fubini-Study metric for two pure states
dist_Hilbert_SchmidtCompute the Hilbert Schmidt distance (i.e. square root of inner product) between two density matrices
Hilbert_Schmidt_normCompute the Hilber Schmidt norm between two elements, abs(<A,B>), with abs(X) == sqrt(X'*X)


Deutsch_gateThe Deutsch gate (for pi/2 this is the Toffoli gate)
control_gateActivate a operation if the control bit is 1
swap_gateSwap gate of arbitrary sion
cnot_gateThe generalized CNOT gate - cyclically permutes the basis vectors


is_majorized_byTests majorization of the first DM by the second
is_weakly_majorized_byTests weak majorization of the first DM by the second
is_super_majorized_byTests super-majorization of the first DM by the second
is_majorizationally_incompatibleTests for incompatibility

Spinor geometry

theta_phi_from_spinDirection of a given spinor
spin_at_theta_phiSpinor at requested direction
sigma_at_theta_phiA sigma matrix for a given 3D direction
unitvec_from_theta_phiCompute the unit vector for a given angle
theta_phi_from_unitvecExtract (theta, phi) from a unit vector
unitvec_ortho_to_unitvecCreate a unit vector orthogonal to a given unit vector
spin_rotation_matrixThe matrix rotating FROM a given direction TO the z basis


QLib can generate the SU(N) generators and use them both for parameterization of SU(N) elements, pure states and DMs, and as a base with which to expand any Hermitian and unitary matrices. See the individual functions for details.

The generators are cached under the QLib.SU global variable. See below for details.

calc_SU_gen Calculates the generators of SU(N), in the fundamental (NxN) representation
prod_SU_gen Find all products of the SU(desc(k)) generators
exp_rep_for_unitary_opExponential representation for unitary operator (using prod_SU_gen)


In order to search a space of some type of entity (say DMs), one needs to formulate a coordinate system for that space. Depending on the application, some requirements may be imposed on this coordinate system, and in most cases, more than a single coordinate system is possible. Once a coordinate system is in place, one may search for a coordinate which extremizes some condition, draw a random coordinate, etc.

QLib is capable of a wide range of parameterizations:
  • CPDs
  • pure states
  • separable states
  • DMs
  • (special) unitary matrices
  • Hermitian matrices
For each, more than one parameterization is provide. Trial and error are normally the best guide as to which parameterization of the space is better suited.
All parameterization routines have a common guidelines which they all follow:
  • Coordinates (parameters for a point) are always a row of real numbers
  • Only measure zero of the coordinate space may not be translatable to the object it represents (for example the axis origin)
  • All coordinate spaces are infinite (so all optimization can be unbounded) and often cyclic.
  • Scaling of coordinates is almost always within a small finite range (well under 100). Therefore, generating a random number in the thousands range will cover the entire space. See individual parameterizations for exact details.
In addition, there are standard naming rules which apply to all parameterization functions
  • Often more than one parameterization is implemented for each entity type. The functions will be called param_XXX_1, param_XXX_2, ...
  • If a parameterization requires more parameters than is strictly required, the numeral will be followed by x, such as param_sep_2x. This is often done for speed and/or to simplify the topology for searches.
  • To find the number of parameters required, call param_XXX_n_size(desc)
  • To generate a random object, call param_XXX_n_rand(desc)
Finally, refer to the search & optimization functions below for details on how to optimize within the parametrized space.

Specific parameterizations

param_p_1,2x,3Classical probability distribution (CPD) parameterization
param_p_1,2x,3_sqrtParameterization for square root of param_p_1,2x,3
param_pure_1,2xParametrize a pure state
param_dm,_2xDensity matrix parameterization
param_sep_1,2xSeparable DM parameterization
param_prodProduct DM parameterization
param_prod_pureProduct pure state parameterization
param_prod_cpdProduct CPD parameterization
param_H_1,2Hermitian matrix parameterization
fully_entangled_stateParameterization of a fully entangled bi-partite state with 2N DoF

SU(n), U(n) Parameterization

param_SU_1,2Parameterizations of SU(N)
param_U_1,2Parameterizations of U(N)
param_SU_over_UParameterization of SU(N) without the phase-per-column redundancy
SU_gen_cacheCaches various calculations having to do with the SU group and it's

Help & Demos

For general help (an abridged version of this page), use help qlib.
For help on a specific function, use help function-name.
This help is also available in the help browsers.

Following is a list of demos distributed as part of QLib.

Subject: Basic example, Measures
Plot various measures of the entanglement within a Werner state
Subject: Basic example, measures
Plot multiple entanglement and entropy measures for the Werner states
Subjects: Basic example, Negativity, GHZ, partial states
Show the scaling of the negativity for a division an "n of M" bipartition of the GHZ state
Subject: Basic example, Parameterization, Measures
Check the additivity of any entropy measure
Subject: Basic example, Measures, Parameterizations
Show the relationship between fidelity and trace distance for a pair of randomly chosen pure states & DMs
Subject: Basic example, Measures, Parameterizations
Examine how different DM distance measures relate to each other for random density matrices of various sizes
Subject: Basic example, Parameterization, Measures
Is a given function a good distance measure?
You specify the function, and the program tests the measure for the various required properties.
Subject: Basic example, Measurements
Step-by-step implementation of dense coding
Subject: Basic example, Measurements
Step-by-step implementation of teleportation
Subject: SU(N)
Is a sum of matrices from SU(n) x SU(m) equivalent to SU(n*m)?
Subject: SU(N)
Compute the SU(N) commutation relations in terms of SU(N) elements
Subject: searches, parmatrizations of SU(N)
Check equivalence between the two parameterizations of SU(N)
Subject: SU(N) algebra
Show that the diagonal SU(N) generators, together with I, span the diagonal matrices
Subject: SU(N), linear algebra, multipartite DMs
Decompose a density matrix into a sum of SU generators.
For example: singlet = 1/4* (1 - sx*sx - sy*sy - sz*sz)
Subject: matrix exponentiation, linear algebra, multipartite DMs, SU(N)
Decompose a unitary operator into expm(sum of SU(N) krons)
For example: CNOT = expm i*pi/4*(sz*sx-sz*I-I*sx+I)
Subject: Parameterizations, searches, separable states
Given a state, find the closest separable state, and display the parameterization in human-readable form

Global variables

QLib defines a set of often-used global variables, for example QLib.Singlet.
These can be accessed in any function by adding global QLib; to the beginning of the function.
All global variables are under members of the QLib structure.

The canonical psi_minus (00-11)/sqrt(2)
Spin half states: x,y,z,I
psi_plus, psi_minus, phi_plus, phi_minus
With the sub-fields CNOT, cpahse, Hadamard, swap, Toffoli
Accuracy limit for the various numerics (such as is_close)
The anti-symmetric tensors, generated by epsilon_tensor
A structure containing the generators and other info. See SU_gen_cache for details
Path under which the QLib package currently resides
QLib version number

Searching and optimization

QLib implements a search algorithm alternating stages of hill-climbing and simulated annealing.

Our experience with this search indicates it is able to avoid almost all local extrema and almost always locate the global extreme with good accuracy, provided that the topology of the space scanner is almost-everywhere smooth.

The search function requires the goal function to extremize, and an "initial guess" coordinates, which also serve to specify the size of the parameter space. Finally, many options can be used to control how the optimization process proceeds.

fmin_combo A combined search function utilizing both fminsearch and simulated annealing, alternatively it can locate the place in param-space where a goal value is reached
fmax_combo Complementary to the above
fmin_combo_opt Option setting for fmin/fmax_combo
fmin_anneal Simulated annealing search for a global minima
fmax_anneal Complementary to the above
fmin_anneal_opt Option settings for fmin/fmax_anneal
fmaxsearch A complementary routine for Matlab's fminsearch
fmaxunc A complementary routine for Matlab's fminunc


QLib includes a wide selection of utilities, which while not strictly "quantum" go a long way towards achieving QLib's goal of quickly testing hypothesis.

Linear algebra

is_HermitianIs a matrix Hermitian? (or close_enough)
is_UnitaryIs a matrix unitary? (or close_enough)
is_normal_matrixIs this matrix a normal matrix (A*A' == A'*A)?
is_pos_semidefIs this matrix positive semi-definite?
direct_sumThe direct sum of any number of matrices
kron2kron any number of matrices
gram_schmidtTransform a set of objects (vectors, matrices, tensors) into an orthonormal set using the Gram Schmidt process
gram_schmidt_tA gram_schmidt process, but in this version the calculation done by a diagonalization technique. This results in "nicer" vectors, with more zeros
are_these_linearly_independentAre these vectors/matrices/tensors linearly independent?
find_spanDecompose an object as linear sum of objects of same sionality
spanReconstructs a decompose an object as linear sum of objects of same sionality
jordanFixThere is a bug in matlab's "jordan" - the maple eval does not go through
jordan2Jordan decomposition, returning the list of blocks (eigenvalues) as three-column matrix
jordan3A refined jordan2, with sorting of eigenvalues & Gram-Schmidt where applicable
eig2A variant of "eig" with sorted & normalized eigenvectors
mat_absAbsolute value of (any) normal matrix
mat2sunConvert a matrix (DM, unitary or Hermitian) to the kron(SU(desc(1)), SU(desc(2)), ...) basis
sun2matConvert a matrix (DM, unitary or Hermitian) from the kron(SU(desc(1)), SU(desc(2)), ...) basis to the normal representation
epsilon_tensorCompute the epsilon anti-symmetric tensor to any given degree

Math - Metrics

EuclideanReturns the Euclidean distance between two vectors
ManhattanReturns Manhattan distance (sum of differences) between two vectors
ChebyshevReturns Chebyshev distance (max of differences) between two vectors

Math - general

stepsGenerate a vector with a given number of equally spaced points
randrowGenerate a row of random numbers
irandGenerate integer random numbers in a given range
vrandChoose an element at random given a vector of element probabilities
rand_directionGenerates a uniform distribution of points on the surface of a sphere
mminn,mmaxxGlobal minimum/maximum over all matrix elements (arbitrary dim)
ssummGlobal summation
fracThe fractional part
clipClip all elements to a given range
is_niceIs it a "normal" number (not NaN of Inf)?
is_eqlCompare matrices NaN ~= NaN, same as build-in isequal
is_eql_2Compare matrices, NaN == NaN
is_closeCompare two values (scalar or matrix) up to "QLib.close_enough" accuracy
is_close_2Same as above, except NaNs are close to each other as are equal-signed Infs
cleanupHuristic clean-up of values (almost integers are rounded, almost reals almost imaginary are "treated")
mat_scaleFind the scale factor between two matrices or NaN if it doesn't exist
NaNsSimilar to "zeros", except it returns NaNs
all_permGenerate all unique permutations of a given data
all_perm_by_countAs above, with data given as values and number of repetitions
yn3_and/or3-way logic (yes/no/don't-know). Useful for combining witness functions
log_quietNatural logarithm returning -Inf for 0
p_log2_pCompute -p*log_2 (p), returning 0 for p==0
smooth_maSmoothed moving average
smooth_minSmoothed minimum using a moving window
bilinear_interpGiven a grid of values for a 2D function, compute additional points using bilinear interpolation


format_delta_tFormat a period of time suppied in seconds as an easy-to-read string
gen_all_idxsA list of indexes into all elements of a multisional tensor
num2maskConvert a number to a mask
permute_1D_cell_arrayPermute a 1D cell array
runstampPrint the script/function being executed, and the time it was run
sub3indA version of sub2ind accepting the indevidual indexes as an array
to_row, to_colConvert anything to a row/column vector
to_squareConvert a vector to a square matrix of sqrt(length(v))^2 elements
unique2Find unique values in an array and the number of times they appear
iffState a condition as a function call (similar to the C language "?" operator)
swapSwap values without resorting to a temporary variable
RatMatConvert a matrix to symbolic form (fix for Matlab's sym)
doubleFixMatlabRootOfBugFix a matlab bug in the "double" function converting a symbolic matrix from Maple
print_matrix_for_mathematicaConvert a Matlab matrix to a format you can copy & paste into Mathematica


draw2d_funcDraw a 1d function in 2d of a given function
draw3d_funcDraw a 2d function in 3d of a given function
draw_histDraw a histogram of the values returned by a given function
set_x/y/z_axisForce axis limits on graphs
save_current_plotSaves the current plot in 3 formats - PNG, EPS and FIG