title: Get Left, Right, Up, Down Nonzero Neighbor from SciPy Sparse Matrix
body: <p>Say that I have a 2D SciPy Sparse Matrix:</p>
  
  <pre><code>import numpy as np
  from scipy.sparse import csc_matrix
  
  arr = np.array([[0, 0, 1, 0, 1],
                  [1, 0, 0, 1, 0],
                  [0, 1, 1, 0, 0],
                  [1, 0, 0, 1, 0],
                  [0, 1, 0, 0, 0],
                 ])
  
  csc = csc_matrix(arr)
  </code></pre>
  
  <p>For each nonzero element within the matrix, I'd like to create four new sparse matrices that contain the index corresponding to the next nearest Left, Right, Up, and Down nonzero neighbor. The elements at the ends can have neighbors that are wrapped around (think circular doubly linked list in both the horizontal and vertical directions or toroidal). In the case where an element is the only nonzero element in its row/column then the corresponding index will point to itself. Additionally, since the indices can have a zero value (when referencing the first row or column) and be indistinguishable from the naturally zero elements, we set these zero indices to -1 in order to disambiguate a real index from the zero elements.</p>
  
  <p>For the matrix above, the dense Left and Down matrices would look like:</p>
  
  <pre><code>left = np.array([[0, 0, 4,  0, 2],
                   [3, 0, 0, -1, 0],
                   [0, 2, 1,  0, 0],
                   [3, 0, 0, -1, 0],
                   [0, 1, 0,  0, 0],
                  ])
  
  down = np.array([[0, 0,  2, 0, -1],
                   [3, 0,  0, 3,  0],
                   [0, 4, -1, 0,  0],
                   [1, 0,  0, 1,  0],
                   [0, 2,  0, 0,  0],
                  ])
  </code></pre>
  
  <p>Remember that elements with an index value of -1 are actually references to index zero. Of course, I need to have these matrices in sparse matrix form as my real matrices are too large and sparse to fit into memory.</p>