# NiBabel

### Access a cacophony of neuro-imaging file formats

# `brikhead`

Class for reading AFNI BRIK/HEAD datasets

See https://afni.nimh.nih.gov/pub/dist/doc/program_help/README.attributes.html for information on what is required to have a valid BRIK/HEAD dataset.

Unless otherwise noted, descriptions AFNI attributes in the code refer to this document.

## Notes

In the AFNI HEAD file, the first two values of the attribute DATASET_RANK determine the shape of the data array stored in the corresponding BRIK file. The first value, DATASET_RANK[0], must be set to 3 denoting a 3D image. The second value, DATASET_RANK[1], determines how many “sub-bricks” (in AFNI parlance) / volumes there are along the fourth (traditionally, but not exclusively) time axis. Thus, DATASET_RANK[1] will (at least as far as I (RM) am aware) always be >= 1. This permits sub-brick indexing common in AFNI programs (e.g., example4d+orig’[0]’).

`AFNIArrayProxy`(file_like, header, *[, mmap, ...]) | Proxy object for AFNI image array.
`AFNIHeader`(info) | Class for AFNI header
`AFNIHeaderError` | Error when reading AFNI HEAD file
`AFNIImage`(dataobj, affine[, header, extra, ...]) | AFNI Image file
`AFNIImageError` | Error when reading AFNI BRIK files
`parse_AFNI_header`(fobj) | Parses fobj to extract information from HEAD file

## `AFNIArrayProxy`

class nibabel.brikhead.AFNIArrayProxy(file_like, header, *, mmap=True, keep_file_open=None)

  Bases: `ArrayProxy`

  Proxy object for AFNI image array.

  Attributes:
    scaling np.ndarray

      Scaling factor (one factor per volume/sub-brick) for data. Default is None

  Initialize AFNI array proxy

  Parameters:
    file_like file-like object

      File-like object or filename. If file-like object, should implement at least `read` and `seek`.

    header `AFNIHeader` object
    mmap{True, False, ‘c’, ‘r’}, optional, keyword only

      mmap controls the use of numpy memory mapping for reading data. If False, do not try numpy `memmap` for data array. If one of {‘c’, ‘r’}, try numpy memmap with `mode=mmap`. A mmap value of True gives the same behavior as `mmap='c'`. If file_like cannot be memory-mapped, ignore mmap value and read array from file.

    keep_file_open{ None, True, False }, optional, keyword only

      keep_file_open controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this `ArrayProxy`. If `True`, a single file handle is created and used. If `False`, a new file handle is created every time the image is accessed. If `file_like` refers to an open file handle, this setting has no effect. The default value (`None`) will result in the value of `nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT` being used.

  __init__(file_like, header, *, mmap=True, keep_file_open=None)

    Initialize AFNI array proxy

    Parameters:
      file_like file-like object

        File-like object or filename. If file-like object, should implement at least `read` and `seek`.

      header `AFNIHeader` object
      mmap{True, False, ‘c’, ‘r’}, optional, keyword only

        mmap controls the use of numpy memory mapping for reading data. If False, do not try numpy `memmap` for data array. If one of {‘c’, ‘r’}, try numpy memmap with `mode=mmap`. A mmap value of True gives the same behavior as `mmap='c'`. If file_like cannot be memory-mapped, ignore mmap value and read array from file.

      keep_file_open{ None, True, False }, optional, keyword only

        keep_file_open controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this `ArrayProxy`. If `True`, a single file handle is created and used. If `False`, a new file handle is created every time the image is accessed. If `file_like` refers to an open file handle, this setting has no effect. The default value (`None`) will result in the value of `nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT` being used.

  property scaling

## `AFNIHeader`

class nibabel.brikhead.AFNIHeader(info)

  Bases: `SpatialHeader`

  Class for AFNI header

  Initialize AFNI header object

  Parameters:
    info dict

      Information from HEAD file as obtained by `parse_AFNI_header()`

  Examples

      >>> fname = os.path.join(datadir, 'example4d+orig.HEAD')
      >>> header = AFNIHeader(parse_AFNI_header(fname))
      >>> header.get_data_dtype().str
      '<i2'
      >>> header.get_zooms()
      (3.0, 3.0, 3.0, 3.0)
      >>> header.get_data_shape()
      (33, 41, 25, 3)

  __init__(info)

    Initialize AFNI header object

    Parameters:
      info dict

        Information from HEAD file as obtained by `parse_AFNI_header()`

    Examples

        >>> fname = os.path.join(datadir, 'example4d+orig.HEAD')
        >>> header = AFNIHeader(parse_AFNI_header(fname))
        >>> header.get_data_dtype().str
        '<i2'
        >>> header.get_zooms()
        (3.0, 3.0, 3.0, 3.0)
        >>> header.get_data_shape()
        (33, 41, 25, 3)

  copy()

    Copy object to independent representation

    The copy should not be affected by any changes to the original object.

  classmethod from_fileobj(fileobj)
  classmethod from_header(header=None)
  get_affine()

    Returns affine of dataset

    Examples

        >>> fname = os.path.join(datadir, 'example4d+orig.HEAD')
        >>> header = AFNIHeader(parse_AFNI_header(fname))
        >>> header.get_affine()
        array([[ -3.    ,  -0.    ,  -0.    ,  49.5   ],
               [ -0.    ,  -3.    ,  -0.    ,  82.312 ],
               [  0.    ,   0.    ,   3.    , -52.3511],
               [  0.    ,   0.    ,   0.    ,   1.    ]])

  get_data_offset()

    Data offset in BRIK file

    Offset is always 0.

  get_data_scaling()

    AFNI applies volume-specific data scaling

    Examples

        >>> fname = os.path.join(datadir, 'scaled+tlrc.HEAD')
        >>> header = AFNIHeader(parse_AFNI_header(fname))
        >>> header.get_data_scaling()
        array([3.883363e-08])

  get_slope_inter()

    Use self.get_data_scaling() instead

    Holdover because `AFNIArrayProxy` (inheriting from `ArrayProxy`) requires this functionality so as to not error.

  get_space()

    Return label for anatomical space to which this dataset is aligned.

    Returns:
      space str

        AFNI “space” designation; one of [ORIG, ANAT, TLRC, MNI]

    Notes

    There appears to be documentation for these spaces at https://afni.nimh.nih.gov/pub/dist/atlases/elsedemo/AFNI_atlas_spaces.niml

  get_volume_labels()

    Returns volume labels

    Returns:
      labels list of str

        Labels for volumes along fourth dimension

    Examples

        >>> header = AFNIHeader(parse_AFNI_header(os.path.join(datadir, 'example4d+orig.HEAD')))
        >>> header.get_volume_labels()
        ['#0', '#1', '#2']

## `AFNIHeaderError`

class nibabel.brikhead.AFNIHeaderError

  Bases: `HeaderDataError`

  Error when reading AFNI HEAD file

  __init__(*args, **kwargs)

## `AFNIImage`

class nibabel.brikhead.AFNIImage(dataobj: ArrayLike, affine: np.ndarray | None, header: FileBasedHeader | ty.Mapping | None = None, extra: ty.Mapping | None = None, file_map: FileMap | None = None)

  Bases: `SpatialImage`

  AFNI Image file

  Can be loaded from either the BRIK or HEAD file (but MUST specify one!)

  Examples

      >>> import nibabel as nib
      >>> brik = nib.load(os.path.join(datadir, 'example4d+orig.BRIK.gz'))
      >>> brik.shape
      (33, 41, 25, 3)
      >>> brik.affine
      array([[ -3.    ,  -0.    ,  -0.    ,  49.5   ],
             [ -0.    ,  -3.    ,  -0.    ,  82.312 ],
             [  0.    ,   0.    ,   3.    , -52.3511],
             [  0.    ,   0.    ,   0.    ,   1.    ]])
      >>> head = load(os.path.join(datadir, 'example4d+orig.HEAD'))
      >>> np.array_equal(head.get_fdata(), brik.get_fdata())
      True

  Initialize image

  The image is a combination of (array-like, affine matrix, header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.

  Parameters:
    dataobj object

      Object containing image data. It should be some object that returns an array from `np.asanyarray`. It should have a `shape` attribute or property

    affine None or (4,4) array-like

      homogeneous affine giving relationship between voxel coordinates and world coordinates. Affine can also be None. In this case, `obj.affine` also returns None, and the affine as written to disk will depend on the file format.

    header None or mapping or header instance, optional

      metadata for this image format

    extra None or mapping, optional

      metadata to associate with image that cannot be stored in the metadata of this image type

    file_map mapping, optional

      mapping giving file information for this image format

  __init__(dataobj: ArrayLike, affine: np.ndarray | None, header: FileBasedHeader | ty.Mapping | None = None, extra: ty.Mapping | None = None, file_map: FileMap | None = None)

    Initialize image

    The image is a combination of (array-like, affine matrix, header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.

    Parameters:
      dataobj object

        Object containing image data. It should be some object that returns an array from `np.asanyarray`. It should have a `shape` attribute or property

      affine None or (4,4) array-like

        homogeneous affine giving relationship between voxel coordinates and world coordinates. Affine can also be None. In this case, `obj.affine` also returns None, and the affine as written to disk will depend on the file format.

      header None or mapping or header instance, optional

        metadata for this image format

      extra None or mapping, optional

        metadata to associate with image that cannot be stored in the metadata of this image type

      file_map mapping, optional

        mapping giving file information for this image format

  ImageArrayProxy

    alias of `AFNIArrayProxy`

  files_types: tuple[ExtensionSpec, ...] = (('image', '.brik'), ('header', '.head'))
  classmethod filespec_to_file_map(filespec)

    Make file_map from filename filespec

    AFNI BRIK files can be compressed, but HEAD files cannot - see afni.nimh.nih.gov/pub/dist/doc/program_help/README.compression.html. Thus, if you have AFNI files my_image.HEAD and my_image.BRIK.gz and you want to load the AFNI BRIK / HEAD pair, you can specify:

    > - The HEAD filename - e.g., my_image.HEAD

    > - The BRIK filename w/o compressed extension - e.g., my_image.BRIK

    > - The full BRIK filename - e.g., my_image.BRIK.gz

    Parameters:
      filespec str

        Filename that might be for this image file type.

    Returns:
      file_map dict

        dict with keys `image` and `header` where values are fileholder objects for the respective BRIK and HEAD files

    Raises:
      ImageFileError

        If filespec is not recognizable as being a filename for this image type.

  classmethod from_file_map(file_map, *, mmap=True, keep_file_open=None)

    Creates an AFNIImage instance from file_map

    Parameters:
      file_map dict

        dict with keys `image, header` and values being fileholder objects for the respective BRIK and HEAD files

      mmap{True, False, ‘c’, ‘r’}, optional, keyword only

        mmap controls the use of numpy memory mapping for reading image array data. If False, do not try numpy `memmap` for data array. If one of {‘c’, ‘r’}, try numpy memmap with `mode=mmap`. A mmap value of True gives the same behavior as `mmap='c'`. If image data file cannot be memory-mapped, ignore mmap value and read array from file.

      keep_file_open{None, True, False}, optional, keyword only

        keep_file_open controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this `ArrayProxy`. If `True`, a single file handle is created and used. If `False`, a new file handle is created every time the image is accessed. If `file_like` refers to an open file handle, this setting has no effect. The default value (`None`) will result in the value of `nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT` being used.

  header_class

    alias of `AFNIHeader`

  makeable: bool = False
  rw: bool = False
  valid_exts: tuple[str, ...] = ('.brik', '.head')

## `AFNIImageError`

class nibabel.brikhead.AFNIImageError

  Bases: `ImageDataError`

  Error when reading AFNI BRIK files

  __init__(*args, **kwargs)

## parse_AFNI_header

nibabel.brikhead.parse_AFNI_header(fobj)

  Parses fobj to extract information from HEAD file

  Parameters:
    fobj file-like object

      AFNI HEAD file object or filename. If file object, should implement at least `read`

  Returns:
    info dict

      Dictionary containing AFNI-style key:value pairs from HEAD file

  Examples

      >>> fname = os.path.join(datadir, 'example4d+orig.HEAD')
      >>> info = parse_AFNI_header(fname)
      >>> print(info['BYTEORDER_STRING'])
      LSB_FIRST
      >>> print(info['BRICK_TYPES'])
      [1, 1, 1]