code: def smatrix_from_nd_idx(idx, nn=0):
      """Create a sparse adjacency matrix from nd index system
  
      Parameters
      ----------
      idx:array of shape (n_samples, dim), type int
          indexes of certain positions in a nd space
      nn: int, optional
          nd neighboring system, unused at the moment
  
      Returns
      -------
      coo_mat: a sparse coo matrix,
               adjacency of the neighboring system
  
      """
      n = idx.shape[0]
      dim = idx.shape[1]
      nidx = idx - idx.min(0)
      eA = []
      eB = []
  
      # compute the edges in each possible direction
      for d in range(dim):
          mi = nidx.max(0) + 2
          a = np.hstack((1, np.cumprod(mi[: dim - 1])))
          v1 = np.dot(nidx, a)
          assert np.size(v1) == np.size(np.unique(v1))
          o1 = np.argsort(v1)
          sv1 = v1[o1]
          nz = np.squeeze(np.nonzero(sv1[: n - 1] - sv1[1:] == -1))
          nz = np.reshape(nz, np.size(nz))
          eA.append(o1[nz])
          eB.append(o1[nz + 1])
          nidx = np.roll(nidx, 1, 1)
  
      eA = np.concatenate(eA)
      eB = np.concatenate(eB)
      E = 2 * np.size(eA)
      # create a graph structure
      if E == 0:
          return sp.coo_matrix((n, n))
  
      edges = np.vstack((np.hstack((eA, eB)), np.hstack((eB, eA)))).T
      weights = np.ones(E)
      G = WeightedGraph(n, edges, weights)
      return G.to_coo_matrix()
  
imports: import numpy
  import scipy.sparse
  from nibabel import Nifti1Image, load, save
  from nipy.algorithms.graph import WeightedGraph, wgraph_from_3d_grid, wgraph_from_coo_matrix
  from nipy.io.nibcompat import get_affine, get_header
label_desc: Use image node_id 4 for calling a global function with example usage: smatrix_from_nd_idx(idx, nn) and returns: G, sp