code: def _apply_mask_and_get_affinity(
      seeds, niimg, radius, allow_overlap, mask_img=None
  ):
      """Get only the rows which are occupied by sphere \
      at given seed locations and the provided radius.
  
      Rows are in target_affine and target_shape space.
  
      Parameters
      ----------
      seeds : List of triplets of coordinates in native space
          Seed definitions. List of coordinates of the seeds in the same space
          as target_affine.
  
      niimg : 3D/4D Niimg-like object
          See :ref:`extracting_data`.
          Images to process.
          If a 3D niimg is provided, a singleton dimension will be added to
          the output to represent the single scan in the niimg.
  
      radius : float
          Indicates, in millimeters, the radius for the sphere around the seed.
  
      allow_overlap : boolean
          If False, a ValueError is raised if VOIs overlap
  
      mask_img : Niimg-like object, optional
          Mask to apply to regions before extracting signals. If niimg is None,
          mask_img is used as a reference space in which the spheres 'indices are
          placed.
  
      Returns
      -------
      X : 2D numpy.ndarray
          Signal for each brain voxel in the (masked) niimgs.
          shape: (number of scans, number of voxels)
  
      A : scipy.sparse.lil_matrix
          Contains the boolean indices for each sphere.
          shape: (number of seeds, number of voxels)
  
      """
      seeds = list(seeds)
  
      # Compute world coordinates of all in-mask voxels.
      if niimg is None:
          mask, affine = masking.load_mask_img(mask_img)
          # Get coordinate for all voxels inside of mask
          mask_coords = np.asarray(np.nonzero(mask)).T.tolist()
          X = None
  
      elif mask_img is not None:
          affine = niimg.affine
          mask_img = check_niimg_3d(mask_img)
          mask_img = image.resample_img(
              mask_img,
              target_affine=affine,
              target_shape=niimg.shape[:3],
              interpolation="nearest",
          )
          mask, _ = masking.load_mask_img(mask_img)
          mask_coords = list(zip(*np.where(mask != 0)))
  
          X = masking.apply_mask_fmri(niimg, mask_img)
  
      elif niimg is not None:
          affine = niimg.affine
          if np.isnan(np.sum(safe_get_data(niimg))):
              warnings.warn(
                  "The imgs you have fed into fit_transform() contains NaN "
                  "values which will be converted to zeroes."
              )
              X = (
                  safe_get_data(niimg, True)
                  .reshape([-1, niimg.shape[3]])
                  .T
              )
          else:
              X = safe_get_data(niimg).reshape([-1, niimg.shape[3]]).T
  
          mask_coords = list(np.ndindex(niimg.shape[:3]))
  
      else:
          raise ValueError(
              "Either a niimg or a mask_img must be provided."
          )
  
      # For each seed, get coordinates of nearest voxel
      nearests = []
      for sx, sy, sz in seeds:
          nearest = np.round(
              image.resampling.coord_transform(
                  sx, sy, sz, np.linalg.inv(affine)
              )
          )
          nearest = nearest.astype(int)
          nearest = (nearest[0], nearest[1], nearest[2])
          try:
              nearests.append(mask_coords.index(nearest))
          except ValueError:
              nearests.append(None)
  
      mask_coords = np.asarray(list(zip(*mask_coords)))
      mask_coords = image.resampling.coord_transform(
          mask_coords[0], mask_coords[1], mask_coords[2], affine
      )
      mask_coords = np.asarray(mask_coords).T
  
      clf = neighbors.NearestNeighbors(radius=radius)
      A = clf.fit(mask_coords).radius_neighbors_graph(seeds)
      A = A.tolil()
      for i, nearest in enumerate(nearests):
          if nearest is None:
              continue
  
          A[i, nearest] = True
  
      # Include the voxel containing the seed itself if not masked
      mask_coords = mask_coords.astype(int).tolist()
      for i, seed in enumerate(seeds):
          try:
              A[i, mask_coords.index(list(map(int, seed)))] = True
          except ValueError:
              # seed is not in the mask
              pass
  
      sphere_sizes = np.asarray(A.tocsr().sum(axis=1)).ravel()
      empty_spheres = np.nonzero(sphere_sizes == 0)[0]
      if len(empty_spheres) != 0:
          raise ValueError(f"These spheres are empty: {empty_spheres}")
  
      if (not allow_overlap) and np.any(A.sum(axis=0) >= 2):
          raise ValueError("Overlap detected between spheres")
  
      return X, A
  
imports: import warnings
  import numpy
  from joblib import Memory
  from scipy import sparse
  from sklearn import neighbors
  from nilearn import image, masking
  from nilearn._utils import CacheMixin, fill_doc, logger
  from nilearn._utils.class_inspect import get_params
  from nilearn._utils.niimg import img_data_dtype
  from nilearn._utils.niimg_conversions import check_niimg_3d, check_niimg_4d, safe_get_data
  from nilearn.datasets import load_mni152_template
  from nilearn.maskers._utils import compute_middle_image
  from nilearn.maskers.base_masker import BaseMasker, _filter_and_extract
label_desc: Use image node_id 1 for calling a global function with example usage: _apply_mask_and_get_affinity(seeds, niimg, radius, allow_overlap, mask_img) and returns: X,  A