nws_tools.nw_zip

nws_tools.nw_zip(ntw)[source]

Convert the upper triangular portion of a real symmetric matrix to a vector and vice versa

Parameters:

ntw : NumPy 1d/2d/3d array

Array representing either (a) a vector (1d array) or (b) a set of vectors (2d array) holding the upper triangular part of a symmetric matrix in column-wise order or (c) a matrix (2d array) or (d) a rank 3 tensor comprising a cohort of symmetric matrices whose upper triangular entries will be extracted. If ntw is a 2d array, it may either represent a symmetric matrix for compression or an array of column vectors. Specifically, a K by M array will be reconstructed to form a N-by-N-by`M` array of symmetric N-by-N matrices, where K = N * (N - 1) / 2. Conversely, if the input is a 3d-array, its format is assumed to be N-by-N-by-M. See Notes below for details.

Returns:

nws : NumPy 1d/2d/3d array

Depending on the input, the returned array is either a compressed representation of the symmetric input matrix/matrices or a full matrix/tensor reconstructed from the provided upper triangular values.

See also

None

Notes

Note, that this routine does NOT consider diagonal elements, i.e., only off-diagonal entries will be stored/reconstructed. By design, entries are assumed to be ordered column-wise. Note further, that a symmetric N-by-N matrix contains K = N * (N - 1) / 2 upper triangular elements. Thus, if N = 3 then K = 3 so that any symmetric 3-by-3 array can either represent a symmetric matrix or a set of three 3-element vectors representing upper triangular entries of three different symmetric matrices. In this case, the routine always assumes that the input represents a symmetric matrix and prints a warning message.

Examples

Consider the symmetric matrix mat

>>> mat 
array([[ 0.,  1.,  2.,  3.],
       [ 1.,  0.,  4.,  5.],
       [ 2.,  4.,  0.,  6.],
       [ 3.,  5.,  6.,  0.]])

Using nw_zip to compress mat yields the array vec

>>> import nws_tools as nwt
>>> vec = nwt.nw_zip(mat)
>>> vec
array([ 1.,  2.,  3.,  4.,  5.,  6.])

Now reconstruct mat from vec

>>> nwt.nw_zip(vec)
array([[ 0.,  1.,  2.,  3.],
       [ 1.,  0.,  4.,  5.],
       [ 2.,  4.,  0.,  6.],
       [ 3.,  5.,  6.,  0.]])

Consider a second symmetric matrix mat2

>>> mat2
array([[  0.,   7.,   8.,   9.],
       [  7.,   0.,  10.,  11.],
       [  8.,  10.,   0.,  12.],
       [  9.,  11.,  12.,   0.]])

Now, collect mat and mat2 in a tensor and use nw_zip to compress it

>>> mats = np.zeros((4,4,2))
>>> mats[:,:,0] = mat
>>> mats[:,:,1] = mat2
>>> vecs = nw_zip(mats)
>>> vecs
array([[  1.,   7.],
       [  2.,   8.],
       [  3.,   9.],
       [  4.,  10.],
       [  5.,  11.],
       [  6.,  12.]])

Uncompressing vecs yields mats again

>>> (mats == nw_zip(vecs)).min()
True