 # Visualizing Sparsity Pattern of matrices

Hi all, Structure plots provide a quick visual check on the

> sparsity pattern of the matrix. A structure plot is a
> rectangular array of dots; a dot is black if the
> corresponding matrix element is nonzero otherwise it is
> white.

> Is it possible to generate such plots with scipy or should
> we switch over to matplotlib ?

A quick matplotlib implementation is below. In matlab this function
is called "spy" and Alexander Schmolck requested this in an earlier
post. The spy implementation uses plot markers which are fixed sizes
(in points). For large matrices, you'll likely want to use a smaller
markersize.

Perhaps better would be to use a polygon collection setup so that the
marker sizes filled the boundaries of the matrix cell. This would
take a little more work, and would also have a different call
signature that matlab's, since matlab also uses plots markers . If
you have any thoughts on how you would like the implementation to

JDH

from matplotlib.matlab import *

def get_xyz_where(Z, Cond):
"""
Z and Cond are MxN matrices. Z are data and Cond is a boolean
matrix where some condition is satisfied. Return value is x,y,z
where x and y are the indices into Z and z are the values of Z at
those indices. x,y,z are 1D arrays

This is a lot easier in numarray - is there a more elegant way to
do this that works on both numeric and numarray?
"""

M,N = Z.shape
z = ravel(Z)
ind = nonzero( ravel(Cond) )

x = arange(M); x.shape = M,1
X = repeat(x, N, 1)
x = ravel(X)

y = arange(N); y.shape = 1,N
Y = repeat(y, M)
y = ravel(Y)

x = take(x, ind)
y = take(y, ind)
z = take(z, ind)
return x,y,z

def spy(Z, marker='s', markersize=10, **kwargs):
"""
SPY(Z, **kwrags) plots the sparsity pattern of the matrix S.

kwargs give the marker properties - see help(plot) for more
information on marker properties

"""
x,y,z = get_xyz_where(Z, Z>0)
plot(x+0.5,y+0.5, linestyle='None', marker=marker,markersize=markersize, **kwargs)

M,N = 25,20
data = zeros((M,N))*0.
data[:,12] = rand(M)
data[5,:] = rand(N)
spy(data)
axis([0,M,0,N])
show()