code: def as_xyz_image(img, name2xyz=None):
      """Return version of `img` that has a valid xyz affine, or raise error
  
      Parameters
      ----------
      img : ``Image`` instance or nibabel image
          It has a ``coordmap`` attribute (``Image``) or a ``get_affine`` method
          (nibabel image object)
      name2xyz : None or mapping
          Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or
          raises a KeyError for a str ``ax_name``.  None means use module default.
          Not used for nibabel `img` input.
  
      Returns
      -------
      reo_img : ``Image`` instance or nibabel image
          Returns image of same type as `img` input. If necessary, `reo_img` has
          its data and coordmap changed to allow it to return an xyz affine.  If
          `img` is already xyz affable we return the input unchanged (``img is
          reo_img``).
  
      Raises
      ------
      SpaceTypeError : if `img` does not have an affine coordinate map
      AxesError : if not all of x, y, z recognized in `img` ``coordmap`` range
      AffineError : if axes dropped from the affine contribute to x, y, z
      coordinates
      """
      try:
          aff = xyz_affine(img, name2xyz)
      except (rsp.AxesError, rsp.AffineError):
          pass
      else:
          return img
      cmap = img.coordmap
      order = rsp.xyz_order(cmap.function_range, name2xyz)
      # Reorder reference to canonical order
      reo_img = img.reordered_reference(order)
      # Which input axes correspond?
      ornt = io_orientation(reo_img.coordmap.affine)
      current_in_order = ornt[:, 0]
      # Set nan to inf to make np.argsort work for old numpy versions
      current_in_order[np.isnan(current_in_order)] = np.inf
      # Do we have the first three axes somewhere?
      if not {0, 1, 2}.issubset(current_in_order):
          raise rsp.AxesError(
              "One of x, y or z outputs missing a "
              "corresponding input axis"
          )
      desired_input_order = np.argsort(current_in_order)
      reo_img = reo_img.reordered_axes(list(desired_input_order))
      try:
          aff = xyz_affine(reo_img, name2xyz)
      except rsp.SpaceError:
          # Python 2.5 / 3 compatibility
          e = sys.exc_info()[1]
          raise e.__class__(
              "Could not reorder so xyz coordinates did not "
              "depend on the other axis coordinates: " + str(e)
          )
      return reo_img
  
file_path: nipy/nipy/core/image/image_spaces.py
imports: import sys
  import numpy
  from nibabel import io_orientation
  from ...io import nibcompat
  from ..image.image import Image
  from ..reference import spaces
  from ..reference.coordinate_map import AffineTransform
label_desc: Use image node_id 3 for calling a global function with example usage: as_xyz_image(img, name2xyz) and returns: reo_img, img