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).
Descriptor
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 2by3by5.
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.

Entities 
Pure states
A column vector of complex numbers, of length: prod(desc).
Phase normalization often used so that the first nonzero 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 leftmost/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_dm  Make sure a matrix describes a good DM. If yes, return unchanged. If not, issue an error 
validate_pure  Make sure a vector describes a good pure state. If yes, return unchanged. If not, issue an error 
validate_cpd  Make sure a vector describes a good CPD. If yes, return unchanged. If not, issue an error 
is_dm_valid  Is the matrix a DM? 
is_pure_valid  Is the vector a proper pure state? 
is_cpd_valid  Is 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 nonzero element real) 
is_product  Is the DM/pure a product of the singledensity 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_masks  Generate 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 statevector 
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  Inversepermute DoF of a DM 
ipermute_dof_pure  Inversepermute 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_dims  Reorder and/or merge DoF in a DM 
reorder_and_merge_pure_dims  Reorder 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 
Entanglement 
concurrence  Compute the concurrence of a 2qubit DM 
concurrence_pure  Compute the concurrence of a 2qubit pure state 
entanglement_of_formation  Compute the entanglement of formation for a two qubit state 
entanglement  The entanglement of a given bipartition of a pure state 
logarithmic_negativity  Compute the logarithmic negativity of a DM 
is_entangled_pt  PeresHorodecki entanglement witness (yes/no/don'tknow) for a given bipartition of a DM 
is_entangled_all_pt  PeresHorodecki entanglement witness for all bipartition of a DM (is there any entanglement in a state) 
negativity  Compute the negativity of a DM 
relative_entanglement  Relative entanglement (minimal KullbackLeibler distance to a separable state) 
robustness_pure  The robustness of a pure state (minimal mixing with random state to be separable) 
singlet_fraction  Compute (by searching for) the (generalized) singlet fraction for any given bipartition of any DM 
Schmidt_number  The number of nonzero Schmidt coefficients 
tangle  Compute the tangle (for 3qubit pure state or 2qubit DM) 

Entropy and mixedness 
H_Shannon  Shannon entropy 
S_Von_Neumann  Vonneumann entropy 
SvN2  Compute the Vonneumann entropy for [p 1p] 
linear_entropy  Compute the linear entropy of a given density matrix 
relative_entropy  Relative entanglement (minimal KullbackLeibler distance to a product state) 
participation_ratio  Estimate of the effective number of states in the mixture 
purity  The purity (measure of mixedness) of a given density matrix 

Mutual information 
mutual_info_dm  Mutual information for a given bipartition of a DM 
mutual_info_pure  Mutual information for a given bipartition of a pure state 
mutual_info_cpd  Mutual information for a given bipartition of a CPD 

Measurements 
act_on  Act with an operator on some of the DoF of a system 
expand_op  Expand / reorder DoF in an operator to fit the entire system 
measure  Perform a measurement on a (sub)system, returning the resulting mixed state 
collapse  Compute the various collapsed "universes" and their probabilities when measuring a system 
weak_measurement  Compute the real part of a weakly measured value 
is_Krauss_set_valid  Check if you have a complete valid set of Krauss operators (Boolean function) 
validate_Krauss_set  Validate you have a complete valid set of Krauss operators (error if not) 
complete_Krauss_set  Complete a Krauss set to unity 
collapse_povm  Perform 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 KullbackLeibler "distance" between two density matrices 
dist_KL_CPD  Compute the KullbackLeibler "distance" between two CPDs 
dist_Bures  Compute the Bures distance between two density matrices 
dist_Bures_angle  Compute the Bures angle between two density matrices 
dist_Fubini_Study  The FubiniStudy metric for two pure states 
dist_Hilbert_Schmidt  Compute the Hilbert Schmidt distance (i.e. square root of inner product) between two density matrices 
Hilbert_Schmidt_norm  Compute the Hilber Schmidt norm between two elements, abs(<A,B>), with abs(X) == sqrt(X'*X) 

Gates 
Deutsch_gate  The Deutsch gate (for pi/2 this is the Toffoli gate) 
control_gate  Activate a operation if the control bit is 1 
swap_gate  Swap gate of arbitrary sion 
cnot_gate  The generalized CNOT gate  cyclically permutes the basis vectors 

Majorization 
is_majorized_by  Tests majorization of the first DM by the second 
is_weakly_majorized_by  Tests weak majorization of the first DM by the second 
is_super_majorized_by  Tests supermajorization of the first DM by the second 
is_majorizationally_incompatible  Tests for incompatibility 

Spinor geometry 
theta_phi_from_spin  Direction of a given spinor 
spin_at_theta_phi  Spinor at requested direction 
sigma_at_theta_phi  A sigma matrix for a given 3D direction 
unitvec_from_theta_phi  Compute the unit vector for a given angle 
theta_phi_from_unitvec  Extract (theta, phi) from a unit vector 
unitvec_ortho_to_unitvec  Create a unit vector orthogonal to a given unit vector 
spin_rotation_matrix  The matrix rotating FROM a given direction TO the z basis 
 

SU(N) 
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_op  Exponential representation for unitary operator (using prod_SU_gen) 

Parameterization 
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,3  Classical probability distribution (CPD) parameterization 
param_p_1,2x,3_sqrt  Parameterization for square root of param_p_1,2x,3 
param_pure_1,2x  Parametrize a pure state 
param_dm,_2x  Density matrix parameterization 
param_sep_1,2x  Separable DM parameterization 
param_prod  Product DM parameterization 
param_prod_pure  Product pure state parameterization 
param_prod_cpd  Product CPD parameterization 
param_H_1,2  Hermitian matrix parameterization 
fully_entangled_state  Parameterization of a fully entangled bipartite state with 2N DoF 

SU(n), U(n) Parameterization 
param_SU_1,2  Parameterizations of SU(N) 
param_U_1,2  Parameterizations of U(N) 
param_SU_over_U  Parameterization of SU(N) without the phasepercolumn redundancy 
SU_gen_cache  Caches 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 functionname.
This help is also available in the help browsers.
Following is a list of demos distributed as part of QLib.
 demo_werner_measures
 Subject: Basic example, Measures
Plot various measures of the entanglement within a Werner state
 demo_Werner_measures
 Subject: Basic example, measures
Plot multiple entanglement and entropy measures for the Werner states
 demo_negativity_scale
 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
 demo_check_entropy_measure_additivity
 Subject: Basic example, Parameterization, Measures
Check the additivity of any entropy measure
 demo_fidelity_vs_dist_trace
 Subject: Basic example, Measures, Parameterizations
Show the relationship between fidelity and trace distance for a pair of randomly chosen pure states & DMs
 demo_dist_measures
 Subject: Basic example, Measures, Parameterizations
Examine how different DM distance measures relate to each other for random density matrices of various sizes
 demo_test_distance_measure
 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.
 demo_dense_coding
 Subject: Basic example, Measurements
Stepbystep implementation of dense coding
 demo_teleportation
 Subject: Basic example, Measurements
Stepbystep implementation of teleportation
 demo_show_SU_decompositions
 Subject: SU(N)
Is a sum of matrices from SU(n) x SU(m) equivalent to SU(n*m)?
 demo_SU_comm
 Subject: SU(N)
Compute the SU(N) commutation relations in terms of SU(N) elements
 demo_SU_param_equiv
 Subject: searches, parmatrizations of SU(N)
Check equivalence between the two parameterizations of SU(N)
 demo_check_SU_over_U_does_span
 Subject: SU(N) algebra
Show that the diagonal SU(N) generators, together with I,
span the diagonal matrices
 demo_factoring_of_dm
 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)
 demo_log_mat_and_prod_gens_for_exponent_decomp
 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*sxsz*II*sx+I)
 demo_reconstructing_param_sep
 Subject: Parameterizations, searches, separable states
Given a state, find the closest separable state, and display the parameterization
in humanreadable form

Global variables 
QLib defines a set of oftenused 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.
 Singlet
 The canonical psi_minus (0011)/sqrt(2)
 sigma.*
 Spin half states: x,y,z,I
 Bell.*
 psi_plus, psi_minus, phi_plus, phi_minus
 GHZ
 Guess
 gates
 With the subfields CNOT, cpahse, Hadamard, swap, Toffoli
 close_enough
 Accuracy limit for the various numerics (such as is_close)
 eps{n}
 The antisymmetric tensors, generated by epsilon_tensor
 SU{n}
 A structure containing the generators and other info. See SU_gen_cache for details
 base_path
 Path under which the QLib package currently resides
 Version
 QLib version number

Searching and optimization 
QLib implements a search algorithm alternating stages of hillclimbing 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 almosteverywhere 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 paramspace 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 

Utilities 
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_Hermitian  Is a matrix Hermitian? (or close_enough) 
is_Unitary  Is a matrix unitary? (or close_enough) 
is_normal_matrix  Is this matrix a normal matrix (A*A' == A'*A)? 
is_pos_semidef  Is this matrix positive semidefinite? 
direct_sum  The direct sum of any number of matrices 
kron2  kron any number of matrices 
gram_schmidt  Transform a set of objects (vectors, matrices, tensors) into an orthonormal set using the Gram Schmidt process 
gram_schmidt_t  A 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_independent  Are these vectors/matrices/tensors linearly independent? 
find_span  Decompose an object as linear sum of objects of same sionality 
span  Reconstructs a decompose an object as linear sum of objects of same sionality 
jordanFix  There is a bug in matlab's "jordan"  the maple eval does not go through 
jordan2  Jordan decomposition, returning the list of blocks (eigenvalues) as threecolumn matrix 
jordan3  A refined jordan2, with sorting of eigenvalues & GramSchmidt where applicable 
eig2  A variant of "eig" with sorted & normalized eigenvectors 
mat_abs  Absolute value of (any) normal matrix 
mat2sun  Convert a matrix (DM, unitary or Hermitian) to the kron(SU(desc(1)), SU(desc(2)), ...) basis 
sun2mat  Convert a matrix (DM, unitary or Hermitian) from the kron(SU(desc(1)), SU(desc(2)), ...) basis to the normal representation 
epsilon_tensor  Compute the epsilon antisymmetric tensor to any given degree 

Math  Metrics 
Euclidean  Returns the Euclidean distance between two vectors 
Manhattan  Returns Manhattan distance (sum of differences) between two vectors 
Chebyshev  Returns Chebyshev distance (max of differences) between two vectors 

Math  general 
steps  Generate a vector with a given number of equally spaced points 
randrow  Generate a row of random numbers 
irand  Generate integer random numbers in a given range 
vrand  Choose an element at random given a vector of element probabilities 
rand_direction  Generates a uniform distribution of points on the surface of a sphere 
mminn,mmaxx  Global minimum/maximum over all matrix elements (arbitrary dim) 
ssumm  Global summation 
frac  The fractional part 
clip  Clip all elements to a given range 
is_nice  Is it a "normal" number (not NaN of Inf)? 
is_eql  Compare matrices NaN ~= NaN, same as buildin isequal 
is_eql_2  Compare matrices, NaN == NaN 
is_close  Compare two values (scalar or matrix) up to "QLib.close_enough" accuracy 
is_close_2  Same as above, except NaNs are close to each other as are equalsigned Infs 
cleanup  Huristic cleanup of values (almost integers are rounded, almost reals almost imaginary are "treated") 
mat_scale  Find the scale factor between two matrices or NaN if it doesn't exist 
NaNs  Similar to "zeros", except it returns NaNs 
all_perm  Generate all unique permutations of a given data 
all_perm_by_count  As above, with data given as values and number of repetitions 
yn3_and/or  3way logic (yes/no/don'tknow). Useful for combining witness functions 
log_quiet  Natural logarithm returning Inf for 0 
p_log2_p  Compute p*log_2 (p), returning 0 for p==0 
smooth_ma  Smoothed moving average 
smooth_min  Smoothed minimum using a moving window 
bilinear_interp  Given a grid of values for a 2D function, compute additional points using bilinear interpolation 

General 
format_delta_t  Format a period of time suppied in seconds as an easytoread string 
gen_all_idxs  A list of indexes into all elements of a multisional tensor 
num2mask  Convert a number to a mask 
permute_1D_cell_array  Permute a 1D cell array 
runstamp  Print the script/function being executed, and the time it was run 
sub3ind  A version of sub2ind accepting the indevidual indexes as an array 
to_row, to_col  Convert anything to a row/column vector 
to_square  Convert a vector to a square matrix of sqrt(length(v))^2 elements 
unique2  Find unique values in an array and the number of times they appear 
iff  State a condition as a function call (similar to the C language "?" operator) 
swap  Swap values without resorting to a temporary variable 
RatMat  Convert a matrix to symbolic form (fix for Matlab's sym) 
doubleFixMatlabRootOfBug  Fix a matlab bug in the "double" function converting a symbolic matrix from Maple 
print_matrix_for_mathematica  Convert a Matlab matrix to a format you can copy & paste into Mathematica 

Graphics 
draw2d_func  Draw a 1d function in 2d of a given function 
draw3d_func  Draw a 2d function in 3d of a given function 
draw_hist  Draw a histogram of the values returned by a given function 
set_x/y/z_axis  Force axis limits on graphs 
save_current_plot  Saves the current plot in 3 formats  PNG, EPS and FIG 

