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 ?

Here's another implementation that uses images - likely to be much
faster for very large matrices.

import random
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.matlab import *

def spy2(Z):
    """
    SPY(Z) plots the sparsity pattern of the matrix S as an image
    """

    #binary colormap min white, max black
    cmapdata = {
         'red' : ((0., 1., 1.), (1., 0., 0.)),
         'green': ((0., 1., 1.), (1., 0., 0.)),
         'blue' : ((0., 1., 1.), (1., 0., 0.))
         }
    binary = LinearSegmentedColormap('binary', cmapdata, 2)

    Z = where(Z>0,1.,0.)
    imshow(transpose(Z), interpolation='nearest', cmap=binary)

def get_sparse_matrix(M,N,frac=0.1):
    'return a MxN sparse matrix with frac elements randomly filled'
    data = zeros((M,N))*0.
    for i in range(int(M*N*frac)):
        x = random.randint(0,M-1)
        y = random.randint(0,N-1)
        data[x,y] = rand()
    return data

data = get_sparse_matrix(50,60)
spy2(data)
show()