code: def test_closest_canonical():
      # Use 32-bit data so that the AnalyzeImage class doesn't complain
      arr = np.arange(24, dtype=np.int32).reshape((2, 3, 4, 1))
  
      # Test with an AnalyzeImage first
      img = AnalyzeImage(arr, np.eye(4))
      xyz_img = as_closest_canonical(img)
      assert img is xyz_img
  
      # And a case where the Analyze image has to be flipped
      img = AnalyzeImage(arr, np.diag([-1, 1, 1, 1]))
      xyz_img = as_closest_canonical(img)
      assert img is not xyz_img
      out_arr = xyz_img.get_fdata()
      assert_array_equal(out_arr, np.flipud(arr))
  
      # Now onto the NIFTI cases (where dim_info also has to be updated)
  
      # No funky stuff, returns same thing
      img = Nifti1Image(arr, np.eye(4))
      # set freq/phase/slice dim so that we can check that we
      # re-order them properly
      img.header.set_dim_info(0, 1, 2)
      xyz_img = as_closest_canonical(img)
      assert img is xyz_img
  
      # a axis flip
      img = Nifti1Image(arr, np.diag([-1, 1, 1, 1]))
      img.header.set_dim_info(0, 1, 2)
      xyz_img = as_closest_canonical(img)
      assert img is not xyz_img
      assert img.header.get_dim_info() == xyz_img.header.get_dim_info()
      out_arr = xyz_img.get_fdata()
      assert_array_equal(out_arr, np.flipud(arr))
  
      # no error for enforce_diag in this case
      xyz_img = as_closest_canonical(img, True)
      # but there is if the affine is not diagonal
      aff = np.eye(4)
      aff[0, 1] = 0.1
      # although it's more or less canonical already
      img = Nifti1Image(arr, aff)
      xyz_img = as_closest_canonical(img)
      assert img is xyz_img
      # it's still not diagnonal
      with pytest.raises(OrientationError):
          as_closest_canonical(img, True)
  
      # an axis swap
      aff = np.diag([1, 0, 0, 1])
      aff[1, 2] = 1
      aff[2, 1] = 1
      img = Nifti1Image(arr, aff)
      img.header.set_dim_info(0, 1, 2)
  
      xyz_img = as_closest_canonical(img)
      assert img is not xyz_img
      # Check both the original and new objects
      assert img.header.get_dim_info() == (0, 1, 2)
      assert xyz_img.header.get_dim_info() == (0, 2, 1)
      out_arr = xyz_img.get_fdata()
      assert_array_equal(out_arr, np.transpose(arr, (0, 2, 1, 3)))
  
      # same axis swap but with None dim info (except for slice dim)
      img.header.set_dim_info(None, None, 2)
      xyz_img = as_closest_canonical(img)
      assert xyz_img.header.get_dim_info() == (None, None, 1)
  
file_path: nibabel/nibabel/tests/test_funcs.py
imports: import numpy
  import pytest
  from numpy.testing import assert_array_equal
  from ..analyze import AnalyzeImage
  from ..funcs import OrientationError, as_closest_canonical, concat_images
  from ..loadsave import save
  from ..nifti1 import Nifti1Image
  from ..tmpdirs import InTemporaryDirectory
label_desc: Use image node_id 3 for calling a global function with example usage: test_closest_canonical() without return types