code: def test_volume_source_morph_basic(tmp_path):
      """Test volume source estimate morph, special cases and exceptions."""
      nib = pytest.importorskip("nibabel")
      pytest.importorskip("h5io")
      pytest.importorskip("dipy")
      inverse_operator_vol = read_inverse_operator(fname_inv_vol)
      stc_vol = read_source_estimate(fname_vol_w, "sample")
  
      # check for invalid input type
      with pytest.raises(TypeError, match="src must be"):
          compute_source_morph(src=42)
  
      # check for raising an error if neither
      # inverse_operator_vol['src'][0]['subject_his_id'] nor subject_from is set,
      # but attempting to perform a volume morph
      src = inverse_operator_vol["src"]
      assert src._subject is None  # already None on disk (old!)
  
      with pytest.raises(
          ValueError, match="subject_from could not be inferred"
      ):
          with pytest.warns(
              RuntimeWarning, match="recommend regenerating"
          ):
              compute_source_morph(src=src, subjects_dir=subjects_dir)
  
      # check infer subject_from from src[0]['subject_his_id']
      src[0]["subject_his_id"] = "sample"
  
      with pytest.raises(
          ValueError, match="Inter-hemispheric morphing"
      ):
          compute_source_morph(
              src=src, subjects_dir=subjects_dir, xhemi=True
          )
  
      with pytest.raises(
          ValueError, match="Only surface.*sparse morph"
      ):
          compute_source_morph(
              src=src, sparse=True, subjects_dir=subjects_dir
          )
  
      # terrible quality but fast
      zooms = 20
      kwargs = dict(zooms=zooms, niter_sdr=(1,), niter_affine=(1,))
      source_morph_vol = compute_source_morph(
          subjects_dir=subjects_dir,
          src=fname_inv_vol,
          subject_from="sample",
          **kwargs,
      )
      shape = (13,) * 3  # for the given zooms
  
      assert source_morph_vol.subject_from == "sample"
  
      # the brain used in sample data has shape (255, 255, 255)
      assert tuple(source_morph_vol.sdr_morph.domain_shape) == shape
  
      assert tuple(source_morph_vol.pre_affine.domain_shape) == shape
  
      # proofs the above
      assert_array_equal(source_morph_vol.zooms, (zooms,) * 3)
  
      # assure proper src shape
      mri_size = (
          src[0]["mri_height"],
          src[0]["mri_depth"],
          src[0]["mri_width"],
      )
      assert source_morph_vol.src_data["src_shape_full"] == mri_size
  
      fwd = read_forward_solution(fname_fwd_vol)
      fwd["src"][0][
          "subject_his_id"
      ] = "sample"  # avoid further warnings
      source_morph_vol = compute_source_morph(
          fwd["src"],
          "sample",
          "sample",
          subjects_dir=subjects_dir,
          **kwargs,
      )
  
      # check wrong subject_to
      with pytest.raises(OSError, match="cannot read file"):
          compute_source_morph(
              fwd["src"], "sample", "42", subjects_dir=subjects_dir
          )
  
      # two different ways of saving
      source_morph_vol.save(tmp_path / "vol")
  
      # check loading
      source_morph_vol_r = read_source_morph(tmp_path / "vol-morph.h5")
  
      # check for invalid file name handling ()
      with pytest.raises(OSError, match="not found"):
          read_source_morph(tmp_path / "42")
  
      # check morph
      stc_vol_morphed = source_morph_vol.apply(stc_vol)
      # old way, verts do not match
      assert not np.array_equal(
          stc_vol_morphed.vertices[0], stc_vol.vertices[0]
      )
  
      # vector
      stc_vol_vec = VolVectorSourceEstimate(
          np.tile(stc_vol.data[:, np.newaxis], (1, 3, 1)),
          stc_vol.vertices,
          0,
          1,
      )
      stc_vol_vec_morphed = source_morph_vol.apply(stc_vol_vec)
      assert isinstance(stc_vol_vec_morphed, VolVectorSourceEstimate)
      for ii in range(3):
          assert_allclose(
              stc_vol_vec_morphed.data[:, ii], stc_vol_morphed.data
          )
  
      # check output as NIfTI
      assert isinstance(
          source_morph_vol.apply(stc_vol_vec, output="nifti2"),
          nib.Nifti2Image,
      )
  
      # check for subject_from mismatch
      source_morph_vol_r.subject_from = "42"
      with pytest.raises(ValueError, match="subject_from must match"):
          source_morph_vol_r.apply(stc_vol_morphed)
  
      # check if nifti is in grid morph space with voxel_size == spacing
      img_morph_res = source_morph_vol.apply(stc_vol, output="nifti1")
  
      # assure morph spacing
      assert isinstance(img_morph_res, nib.Nifti1Image)
      assert img_morph_res.header.get_zooms()[:3] == (zooms,) * 3
  
      # assure src shape
      img_mri_res = source_morph_vol.apply(
          stc_vol, output="nifti1", mri_resolution=True
      )
      assert isinstance(img_mri_res, nib.Nifti1Image)
      assert img_mri_res.shape == (
          src[0]["mri_height"],
          src[0]["mri_depth"],
          src[0]["mri_width"],
      ) + (img_mri_res.shape[3],)
  
      # check if nifti is defined resolution with voxel_size == (5., 5., 5.)
      img_any_res = source_morph_vol.apply(
          stc_vol, output="nifti1", mri_resolution=(5.0, 5.0, 5.0)
      )
      assert isinstance(img_any_res, nib.Nifti1Image)
      assert img_any_res.header.get_zooms()[:3] == (5.0, 5.0, 5.0)
  
      # check if morph outputs correct data
      assert isinstance(stc_vol_morphed, VolSourceEstimate)
  
      # check if loaded and saved objects contain the same
      assert all(
          [
              read == saved
              for read, saved in zip(
                  sorted(source_morph_vol_r.__dict__),
                  sorted(source_morph_vol.__dict__),
              )
          ]
      )
  
      # check __repr__
      assert "volume" in repr(source_morph_vol)
  
      # check Nifti2Image
      assert isinstance(
          source_morph_vol.apply(
              stc_vol,
              mri_resolution=True,
              mri_space=True,
              output="nifti2",
          ),
          nib.Nifti2Image,
      )
  
      # Degenerate conditions
      with pytest.raises(TypeError, match="output must be"):
          source_morph_vol.apply(stc_vol, output=1)
      with pytest.raises(
          ValueError, match="subject_from does not match"
      ):
          compute_source_morph(src=src, subject_from="42")
      with pytest.raises(ValueError, match="output"):
          source_morph_vol.apply(stc_vol, output="42")
      with pytest.raises(ValueError, match="subject_to cannot be None"):
          compute_source_morph(
              src, "sample", None, subjects_dir=subjects_dir
          )
      # Check if not morphed, but voxel size not boolean, raise ValueError.
      # Note that this check requires dipy to not raise the dipy ImportError
      # before checking if the actual voxel size error will raise.
      with pytest.raises(
          ValueError, match="Cannot infer original voxel size"
      ):
          stc_vol.as_volume(
              inverse_operator_vol["src"], mri_resolution=4
          )
  
      stc_surf = read_source_estimate(fname_stc, "sample")
      with pytest.raises(
          TypeError, match="stc_from must be an instance"
      ):
          source_morph_vol.apply(stc_surf)
  
      # src_to
      source_morph_vol = compute_source_morph(
          fwd["src"],
          subject_from="sample",
          src_to=fwd["src"],
          subject_to="sample",
          subjects_dir=subjects_dir,
          **kwargs,
      )
      stc_vol_2 = source_morph_vol.apply(stc_vol)
      # new way, verts match
      assert_array_equal(stc_vol.vertices[0], stc_vol_2.vertices[0])
      stc_vol_bad = VolSourceEstimate(
          stc_vol.data[:-1],
          [stc_vol.vertices[0][:-1]],
          stc_vol.tmin,
          stc_vol.tstep,
      )
      match = (
          "vertices do not match between morph \\(4157\\) and stc \\(4156\\).*"
          "\n.*\n.*\n.*Vertices were likely excluded during forward computatio.*"
      )
      with pytest.raises(ValueError, match=match):
          source_morph_vol.apply(stc_vol_bad)
  
      # nifti outputs and stc equiv
      img_vol = source_morph_vol.apply(stc_vol, output="nifti1")
      img_vol_2 = stc_vol_2.as_volume(
          src=fwd["src"], mri_resolution=False
      )
      assert_allclose(img_vol.affine, img_vol_2.affine)
      img_vol = img_vol.get_fdata()
      img_vol_2 = img_vol_2.get_fdata()
      assert img_vol.shape == img_vol_2.shape
      assert_allclose(img_vol, img_vol_2)
  
imports: from inspect import signature
  import numpy
  import pytest
  from numpy.testing import assert_allclose, assert_array_equal, assert_array_less
  from scipy.sparse import csr_matrix
  from scipy.sparse import eye
  from scipy.spatial.distance import cdist
  import mne
  from mne import SourceEstimate, SourceMorph, VectorSourceEstimate, VolSourceEstimate, VolVectorSourceEstimate, compute_source_morph, get_volume_labels_from_aseg, grade_to_vertices, make_ad_hoc_cov, make_forward_solution, make_sphere_model, read_evokeds, read_forward_solution, read_freesurfer_lut, read_source_estimate, read_source_morph, setup_volume_source_space
  from mne._freesurfer import _get_atlas_values, _get_mri_info_data
  from mne.datasets import testing
  from mne.fixes import _get_img_fdata
  from mne.minimum_norm import apply_inverse, make_inverse_operator, read_inverse_operator
  from mne.source_space._source_space import _add_interpolator, _grid_interp
  from mne.transforms import quat_to_rot
  from mne.utils import _record_warnings, catch_logging
label_desc: Use image node_id 9 for calling a global function with example usage: test_volume_source_morph_basic(tmp_path) without return types