code: def random_walker(
      data, labels, beta=130, tol=1.0e-3, copy=True, spacing=None
  ):
      """Random walker algorithm for segmentation from markers.
  
      Parameters
      ----------
      data : array_like
          Image to be segmented in phases.
          Data spacing is assumed isotropic unless
          the `spacing` keyword argument is used.
  
      labels : array of ints, of same shape as `data` without channels dimension
          Array of seed markers labeled with different positive integers
          for different phases. Zero-labeled pixels are unlabeled pixels.
          Negative labels correspond to inactive pixels that are not taken
          into account (they are removed from the graph). If labels are not
          consecutive integers, the labels array will be transformed so that
          labels are consecutive.
  
      beta : float, default=130
          Penalization coefficient for the random walker motion
          (the greater `beta`, the more difficult the diffusion).
  
      tol : float, default=1e-3
          Tolerance to achieve when solving the linear system, in
          cg' mode.
  
      copy : bool, default=True
          If copy is False, the `labels` array will be overwritten with
          the result of the segmentation. Use copy=False if you want to
          save on memory.
  
      spacing : iterable of floats, optional
          Spacing between voxels in each spatial dimension. If `None`, then
          the spacing between pixels/voxels in each dimension is assumed 1.
  
      Returns
      -------
      output : ndarray
          An array of ints of same shape as `data`, in which each pixel has
          been labeled according to the marker that reached the pixel first
          by anisotropic diffusion.
  
      Notes
      -----
      The `spacing` argument is specifically for anisotropic datasets, where
      data points are spaced differently in one or more spatial dimensions.
      Anisotropic data is commonly encountered in medical imaging.
  
      The algorithm was first proposed in [1]_.
  
      The algorithm solves the diffusion equation at infinite times for
      sources placed on markers of each phase in turn. A pixel is labeled with
      the phase that has the greatest probability to diffuse first to the pixel.
  
      The diffusion equation is solved by minimizing x.T L x for each phase,
      where L is the Laplacian of the weighted graph of the image, and x is
      the probability that a marker of the given phase arrives first at a pixel
      by diffusion (x=1 on markers of the phase, x=0 on the other markers, and
      the other coefficients are looked for). Each pixel is attributed the label
      for which it has a maximal value of x. The Laplacian L of the image
      is defined as:
  
         - L_ii = d_i, the number of neighbors of pixel i (the degree of i)
         - L_ij = -w_ij if i and j are adjacent pixels
  
      The weight w_ij is a decreasing function of the norm of the local gradient.
      This ensures that diffusion is easier between pixels of similar values.
  
      When the Laplacian is decomposed into blocks of marked and unmarked
      pixels::
  
          L = M B.T
              B A
  
      with first indices corresponding to marked pixels, and then to unmarked
      pixels, minimizing x.T L x for one phase amount to solving::
  
          A x = - B x_m
  
      where x_m = 1 on markers of the given phase, and 0 on other markers.
      This linear system is solved in the algorithm using a direct method for
      small images, and an iterative method for larger images.
  
      References
      ----------
      .. [1] Random walks for image segmentation, Leo Grady, IEEE Trans Pattern
         Anal Mach Intell. 2006 Nov;28(11):1768-83.
  
      """
      out_labels = np.copy(labels)
      if (labels != 0).all():
          warnings.warn(
              "Random walker only segments unlabeled areas, where "
              "labels == 0. No zero valued areas in labels were "
              "found. Returning provided labels."
          )
          return out_labels
  
      if (labels == 0).all():
          warnings.warn(
              "Random walker received no seed label. Returning provided labels."
          )
          return out_labels
  
      # We take multichannel as always False since we are not strictly using
      # for image processing as such with RGB values.
      multichannel = False
      if not multichannel:
          if data.ndim < 2 or data.ndim > 3:
              raise ValueError(
                  "For non-multichannel input, data must be of "
                  "dimension 2 or 3."
              )
          dims = data.shape  # To reshape final labeled result
          data = np.atleast_3d(as_float_array(data))[..., np.newaxis]
  
      # Spacing kwarg checks
      if spacing is None:
          spacing = np.asarray((1.0,) * 3)
      elif len(spacing) == len(dims):
          if (
              len(spacing) == 2
          ):  # Need a dummy spacing for singleton 3rd dim
              spacing = np.r_[spacing, 1.0]
          else:  # Convert to array
              spacing = np.asarray(spacing)
      else:
          raise ValueError(
              "Input argument `spacing` incorrect, should be an "
              "iterable with one number per spatial dimension."
          )
  
      if copy:
          labels = np.copy(labels)
      label_values = np.unique(labels)
  
      # Reorder label values to have consecutive integers (no gaps)
      if np.any(np.diff(label_values) != 1):
          mask = labels >= 0
          labels[mask] = np.searchsorted(
              np.unique(labels[mask]), labels[mask]
          ).astype(labels.dtype)
      labels = labels.astype(np.int32)
      # If the array has pruned zones, we can have two problematic situations:
      #   - isolated zero-labeled pixels that cannot be determined because they
      #     are not connected to any seed.
      #   - isolated seeds, that is pixels with labels > 0
      #     in connected components without any zero-labeled pixel
      #     to determine.
      #     This causes errors when computing the Laplacian of the graph.
      # For both cases, the problematic pixels are ignored (label is set to -1).
      if np.any(labels < 0):
          # Handle the isolated zero-labeled pixels first
          filled = ndi.binary_propagation(labels > 0, mask=labels >= 0)
          labels[
              np.logical_and(np.logical_not(filled), labels == 0)
          ] = -1
          del filled
          # Handle the isolated seeds
          filled = ndi.binary_propagation(labels == 0, mask=labels >= 0)
          isolated = np.logical_and(labels > 0, np.logical_not(filled))
          labels[isolated] = -1
          del filled
  
      # If the operations above yield only -1 pixels
      if (labels == -1).all():
          warnings.warn(
              "Random walker only segments unlabeled areas, where "
              "labels == 0. Data provided only contains isolated seeds "
              "and isolated pixels. Returning provided labels."
          )
          return out_labels
  
      labels = np.atleast_3d(labels)
      if np.any(labels < 0):
          lap_sparse = _build_laplacian(
              data, spacing, mask=labels >= 0, beta=beta
          )
      else:
          lap_sparse = _build_laplacian(data, spacing, beta=beta)
  
      lap_sparse, B = _buildAB(lap_sparse, labels)
  
      # We solve the linear system
      # lap_sparse X = B
      # where X[i, j] is the probability that a marker of label i arrives
      # first at pixel j by anisotropic diffusion.
      X = _solve_cg(lap_sparse, B, tol=tol)
  
      # Clean up results
      X = _clean_labels_ar(X + 1, labels).reshape(dims)
      return X
  
file_path: nilearn/nilearn/_utils/segmentation.py
imports: import warnings
  import numpy
  from scipy import ndimage, sparse
  from scipy.sparse.linalg import cg
  from sklearn.utils import as_float_array
label_desc: Use image node_id 9 for calling a global function with example usage: random_walker(data, labels, beta, tol, copy, spacing) and returns: X, out_labels, out_labels, out_labels