Skip to content

sparsity

Josh Fogg edited this page Aug 8, 2024 · 1 revision
sparsity(matrix, explicit_as_nz)

A quick shortcut function which computes the sparsity of a matrix, i.e. the proportion of its entries which are equal to zero. Designed to work with both NumPy and SciPy objects.

Parameters

  • matrix : ArrayLike
    Any matrix or matrix-like object. Does not have to be square.
  • explicit_as_nz : bool, optional
    If the matrix is not a SciPy spmatrix object, this will be ignored. If it is an spmatrix and this parameter is True sparsity will be computed while treating explicit zeros as non-zeros, and if False treating them as zeros. The default value is True.

Returns

  • float
    The sparsity of the matrix, i.e. the number of zero entries divided by the number of entries total.

Examples

When working with pedigree data, typically there's some degree of sparsity in both WRNM and its inverse. For example, if the relationship has some sparsity

>>> A = np.array([
 [1.    0.    0.5   0.5   0.5   0.5   0.5   0.    0.25 ],
 [0.    1.    0.5   0.5   0.5   0.    0.    0.5   0.25 ],
 [0.5   0.5   1.    0.5   0.5   0.25  0.25  0.25  0.25 ],
 [0.5   0.5   0.5   1.    0.5   0.25  0.25  0.25  0.25 ],
 [0.5   0.5   0.5   0.5   1.    0.25  0.25  0.25  0.25 ],
 [0.5   0.    0.25  0.25  0.25  1.    0.25  0.    0.125],
 [0.5   0.    0.25  0.25  0.25  0.25  1.    0.    0.5  ],
 [0.    0.5   0.25  0.25  0.25  0.    0.    1.    0.5  ],
 [0.25  0.25  0.25  0.25  0.25  0.125 0.5   0.5   1.   ]])
>>> sparsity(A)
0.14814814814814814

then it has an inverse which is typically hypersparse

>>> invA = np.array([
 [ 3.167  1.5   -1.    -1.    -1.    -0.667 -0.667  0.     0.   ],
 [ 1.5    2.833 -1.    -1.    -1.     0.     0.    -0.667  0.   ],
 [-1.    -1.     2.     0.     0.     0.     0.     0.     0.   ],
 [-1.    -1.     0.     2.     0.     0.     0.     0.     0.   ],
 [-1.    -1.     0.     0.     2.     0.     0.     0.     0.   ],
 [-0.667  0.     0.     0.     0.     1.333  0.     0.     0.   ],
 [-0.667  0.     0.     0.     0.     0.     1.833  0.5   -1.   ],
 [ 0.    -0.667  0.     0.     0.     0.     0.5    1.833 -1.   ],
 [ 0.     0.     0.     0.     0.     0.    -1.    -1.     2.   ]])
>>> sparsity(invA)
0.5679012345679013