def _load_images_and_labels(self, images, labels=None):

if not isinstance(images, (list, tuple)):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(type(images)))<EOL><DEDENT>if not len(images) > <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(images)))<EOL><DEDENT>if labels is not None and len(labels) != len(images):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(images), len(labels)))<EOL><DEDENT>first_file = images[<NUM_LIT:0>]<EOL>if first_file:<EOL><INDENT>first_img = NeuroImage(first_file)<EOL><DEDENT>else:<EOL><INDENT>raise('<STR_LIT>'.format(repr_imgs(first_file)))<EOL><DEDENT>for idx, image in enumerate(images):<EOL><INDENT>try:<EOL><INDENT>img = NeuroImage(image)<EOL>self.check_compatibility(img, first_img)<EOL><DEDENT>except:<EOL><INDENT>log.exception('<STR_LIT>'.format(repr_imgs(image)))<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>self.items.append(img)<EOL><DEDENT><DEDENT>self.set_labels(labels)<EOL>

Read the images, load them into self.items and set the labels.


def to_matrix(self, smooth_fwhm=<NUM_LIT:0>, outdtype=None):

if not self.all_compatible:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not outdtype:<EOL><INDENT>outdtype = self.items[<NUM_LIT:0>].dtype<EOL><DEDENT>n_voxels     = None<EOL>mask_indices = None<EOL>mask_shape   = self.items[<NUM_LIT:0>].shape[:<NUM_LIT:3>]<EOL>if self.has_mask:<EOL><INDENT>mask_arr     = self.mask.get_data()<EOL>mask_indices = np.nonzero(mask_arr)<EOL>mask_shape   = self.mask.shape<EOL>n_voxels     = np.count_nonzero(mask_arr)<EOL><DEDENT>if n_voxels is None:<EOL><INDENT>log.debug('<STR_LIT>'.format(self.mask))<EOL>n_voxels     = np.prod(mask_shape)<EOL>mask_indices = None<EOL><DEDENT>ndims = self.items[<NUM_LIT:0>].ndim<EOL>if ndims == <NUM_LIT:3>:<EOL><INDENT>subj_flat_shape = (n_voxels, )<EOL><DEDENT>elif ndims == <NUM_LIT:4>:<EOL><INDENT>subj_flat_shape = (n_voxels, self.items[<NUM_LIT:0>].shape[<NUM_LIT:3>])<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>'.format(ndims))<EOL><DEDENT>outmat = np.zeros((self.n_subjs, ) + subj_flat_shape, dtype=outdtype)<EOL>try:<EOL><INDENT>for i, image in enumerate(self.items):<EOL><INDENT>if smooth_fwhm > <NUM_LIT:0>:<EOL><INDENT>image.fwhm = smooth_fwhm<EOL><DEDENT>if self.has_mask:<EOL><INDENT>image.set_mask(self.mask)<EOL><DEDENT>outmat[i, :], _, _ = image.mask_and_flatten()<EOL>image.clear_data()<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(image)) from exc<EOL><DEDENT>else:<EOL><INDENT>return outmat, mask_indices, mask_shape<EOL><DEDENT>

Return numpy.ndarray with the masked or flatten image data and
           the relevant information (mask indices and volume shape).

        Parameters
        ----------
        smooth__fwhm: int
            Integer indicating the size of the FWHM Gaussian smoothing kernel
            to smooth the subject volumes before creating the data matrix

        outdtype: dtype
            Type of the elements of the array, if None will obtain the dtype from
            the first nifti file.

        Returns
        -------
        outmat, mask_indices, vol_shape

        outmat: Numpy array with shape N x prod(vol.shape)
                containing the N files as flat vectors.

        mask_indices: matrix with indices of the voxels in the mask

        vol_shape: Tuple with shape of the volumes, for reshaping.


def to_file(self, output_file, smooth_fwhm=<NUM_LIT:0>, outdtype=None):

outmat, mask_indices, mask_shape = self.to_matrix(smooth_fwhm, outdtype)<EOL>exporter = ExportData()<EOL>content = {'<STR_LIT:data>':         outmat,<EOL>'<STR_LIT>':       self.labels,<EOL>'<STR_LIT>': mask_indices,<EOL>'<STR_LIT>':   mask_shape, }<EOL>if self.others:<EOL><INDENT>content.update(self.others)<EOL><DEDENT>log.debug('<STR_LIT>'.format(output_file))<EOL>try:<EOL><INDENT>exporter.save_variables(output_file, content)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(output_file)) from exc<EOL><DEDENT>

Save the Numpy array created from to_matrix function to the output_file.

        Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)

            data: Numpy array with shape N x prod(vol.shape)
                  containing the N files as flat vectors.

            mask_indices: matrix with indices of the voxels in the mask

            vol_shape: Tuple with shape of the volumes, for reshaping.

        Parameters
        ----------
        output_file: str
            Path to the output file. The extension of the file will be taken into account for the file format.
            Choices of extensions: '.pyshelf' or '.shelf' (Python shelve)
                                   '.mat' (Matlab archive),
                                   '.hdf5' or '.h5' (HDF5 file)

        smooth_fwhm: int
            Integer indicating the size of the FWHM Gaussian smoothing kernel
            to smooth the subject volumes before creating the data matrix

        outdtype: dtype
            Type of the elements of the array, if None will obtain the dtype from
            the first nifti file.


try:<EOL><INDENT>if isinstance(subj_files, list):<EOL><INDENT>self.from_list(subj_files)<EOL><DEDENT>elif isinstance(subj_files, dict):<EOL><INDENT>self.from_dict(subj_files)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>') from exc<EOL><DEDENT>

Parameters
----------
subj_files: list or dict of str
    file_path -> int/str


if not os.path.exists(file_path):<EOL><INDENT>raise FileNotFound(file_path)<EOL><DEDENT>try:<EOL><INDENT>nii_img           = load_nipy_img(file_path)<EOL>nii_img.file_path = file_path<EOL>return nii_img<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(file_path)) from exc<EOL><DEDENT>

Parameters
----------
file_path: str
    Path to the nifti file

Returns
-------
nipy.Image with a file_path member


<EOL>from   nipy.algorithms.kernel_smooth import LinearFilter<EOL>if smooth_fwhm <= <NUM_LIT:0>:<EOL><INDENT>return nii_img<EOL><DEDENT>filter = LinearFilter(nii_img.coordmap, nii_img.shape)<EOL>return filter.smooth(nii_img)<EOL>

Parameters
----------
nii_img: nipy.Image

smooth_fwhm: float

Returns
-------
smoothed nipy.Image


for group_label in subj_files:<EOL><INDENT>try:<EOL><INDENT>group_files = subj_files[group_label]<EOL>self.items.extend([self._load_image(get_abspath(imgf)) for imgf in group_files])<EOL>self.labels.extend([group_label]*len(group_files))<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>'.format(group_label)) from exc<EOL><DEDENT><DEDENT>

Parameters
----------
subj_files: dict of str
    file_path -> int/str


for sf in subj_files:<EOL><INDENT>try:<EOL><INDENT>nii_img = self._load_image(get_abspath(sf))<EOL>self.items.append(nii_img)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(sf)) from exc<EOL><DEDENT><DEDENT>

Parameters
----------
subj_files: list of str
    file_paths


if len(subj_labels) != self.n_subjs:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.labels = subj_labels<EOL>

Parameters
----------
subj_labels: list of int or str
    This list will be checked to have the same size as files list
    (self.items)


vol = self.items[<NUM_LIT:0>].get_data()<EOL>if not outdtype:<EOL><INDENT>outdtype = vol.dtype<EOL><DEDENT>n_voxels     = None<EOL>mask_indices = None<EOL>mask_shape   = self.items[<NUM_LIT:0>].shape<EOL>if self.has_mask:<EOL><INDENT>mask_arr     = get_img_data(self.mask_file)<EOL>mask_indices = np.where(mask_arr > <NUM_LIT:0>)<EOL>mask_shape   = mask_arr.shape<EOL>n_voxels     = np.count_nonzero(mask_arr)<EOL><DEDENT>if n_voxels is None:<EOL><INDENT>log.debug('<STR_LIT>'.format(self.mask_file))<EOL>n_voxels = np.prod(vol.shape)<EOL><DEDENT>outmat = np.zeros((self.n_subjs, n_voxels), dtype=outdtype)<EOL>try:<EOL><INDENT>for i, nipy_img in enumerate(self.items):<EOL><INDENT>vol = self._smooth_img(nipy_img, smooth_fwhm).get_data()<EOL>if self.has_mask is not None:<EOL><INDENT>outmat[i, :] = vol[mask_indices]<EOL><DEDENT>else:<EOL><INDENT>outmat[i, :] = vol.flatten()<EOL><DEDENT><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(nipy_img.file_path)) from exc<EOL><DEDENT>else:<EOL><INDENT>return outmat, mask_indices, mask_shape<EOL><DEDENT>

Create a Numpy array with the data and return the relevant information (mask indices and volume shape).

        Parameters
        ----------
        smooth_fwhm: int
            Integer indicating the size of the FWHM Gaussian smoothing kernel
            to smooth the subject volumes before creating the data matrix

        outdtype: dtype
            Type of the elements of the array, if None will obtain the dtype from
            the first nifti file.

        Returns
        -------
        outmat, mask_indices, vol_shape

        outmat: Numpy array with shape N x prod(vol.shape)
                containing the N files as flat vectors.

        mask_indices: matrix with indices of the voxels in the mask

        vol_shape: Tuple with shape of the volumes, for reshaping.


Save the Numpy array created from to_matrix function to the output_file.

        Will save into the file: outmat, mask_indices, vol_shape

            data: Numpy array with shape N x prod(vol.shape)
                  containing the N files as flat vectors.

            mask_indices: matrix with indices of the voxels in the mask

            vol_shape: Tuple with shape of the volumes, for reshaping.

        Parameters
        ----------
        output_file: str
            Path to the output file. The extension of the file will be taken into account for the file format.
            Choices of extensions: '.pyshelf' or '.shelf' (Python shelve)
                                   '.mat' (Matlab archive),
                                   '.hdf5' or '.h5' (HDF5 file)

        smooth_fwhm: int
            Integer indicating the size of the FWHM Gaussian smoothing kernel
            to smooth the subject volumes before creating the data matrix

        # TODO
        #smooth_mask: bool
        #    If True, will smooth the mask with the same kernel.

        outdtype: dtype
            Type of the elements of the array, if None will obtain the dtype from
            the first nifti file.


shape, affine = img.shape[:<NUM_LIT:3>], img.affine<EOL>coords = np.array(np.meshgrid(*(range(i) for i in shape), indexing='<STR_LIT>'))<EOL>coords = np.rollaxis(coords, <NUM_LIT:0>, len(shape) + <NUM_LIT:1>)<EOL>mm_coords = nib.affines.apply_affine(affine, coords)<EOL>return mm_coords<EOL>

Return a grid with coordinates in 3D physical space for `img`.


try:<EOL><INDENT>mm = cm([i, j, k])<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>') from exc<EOL><DEDENT>else:<EOL><INDENT>return mm<EOL><DEDENT>

Parameters
----------
cm: nipy.core.reference.coordinate_map.CoordinateMap

i, j, k: floats
    Voxel coordinates

Returns
-------
Triplet with real 3D world coordinates


try:<EOL><INDENT>vox = cm.inverse()([x, y, z])<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>') from exc<EOL><DEDENT>else:<EOL><INDENT>return vox<EOL><DEDENT>

Parameters
----------
cm: nipy.core.reference.coordinate_map.CoordinateMap

x, y, z: floats
    Physical coordinates

Returns
-------
Triplet with 3D voxel coordinates


if isinstance(img, nib.Nifti1Image):<EOL><INDENT>img = nifti2nipy(img)<EOL><DEDENT>if img.ndim == <NUM_LIT:4>:<EOL><INDENT>from nipy.core.reference.coordinate_map import drop_io_dim<EOL>cm = drop_io_dim(img.coordmap, <NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>cm = img.coordmap<EOL><DEDENT>return cm<EOL>

Gets a 3D CoordinateMap from img.

Parameters
----------
img: nib.Nifti1Image or nipy Image

Returns
-------
nipy.core.reference.coordinate_map.CoordinateMap


return ArrayCoordMap(coordmap, shape)<EOL>


def save_niigz(filepath, vol, header=None, affine=None):

<EOL>we_have_nipy = False<EOL>try:<EOL><INDENT>import nipy.core.image as     niim<EOL>from   nipy            import save_image<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>we_have_nipy = True<EOL><DEDENT>if isinstance(vol, np.ndarray):<EOL><INDENT>log.debug('<STR_LIT>'.format(filepath))<EOL>ni = nib.Nifti1Image(vol, affine, header)<EOL>nib.save(ni, filepath)<EOL><DEDENT>elif isinstance(vol, nib.Nifti1Image):<EOL><INDENT>log.debug('<STR_LIT>'.format(filepath))<EOL>nib.save(vol, filepath)<EOL><DEDENT>elif we_have_nipy and isinstance(vol, niim.Image):<EOL><INDENT>log.debug('<STR_LIT>'.format(filepath))<EOL>save_image(vol, filepath)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr_imgs(vol)))<EOL><DEDENT>

Saves a volume into a Nifti (.nii.gz) file.

    Parameters
    ----------
    vol: Numpy 3D or 4D array
        Volume with the data to be saved.

    file_path: string
        Output file name path

    affine: (optional) 4x4 Numpy array
        Array with the affine transform of the file.
        This is needed if vol is a np.ndarray.

    header: (optional) nibabel.nifti1.Nifti1Header, optional
        Header for the file, optional but recommended.
        This is needed if vol is a np.ndarray.

    Note
    ----
    affine and header only work for numpy volumes.


try:<EOL><INDENT>h5group['<STR_LIT:data>']   = spatial_img.get_data()<EOL>h5group['<STR_LIT>'] = spatial_img.get_affine()<EOL>if hasattr(h5group, '<STR_LIT>'):<EOL><INDENT>h5group['<STR_LIT>'] = spatial_img.get_extra()<EOL><DEDENT>hdr = spatial_img.get_header()<EOL>for k in list(hdr.keys()):<EOL><INDENT>h5group['<STR_LIT:data>'].attrs[k] = hdr[k]<EOL><DEDENT><DEDENT>except ValueError as ve:<EOL><INDENT>raise Exception('<STR_LIT>' + h5group.name) from ve<EOL><DEDENT>

Saves a Nifti1Image into an HDF5 group.

    Parameters
    ----------
    h5group: h5py Group
        Output HDF5 file path

    spatial_img: nibabel SpatialImage
        Image to be saved

    h5path: str
        HDF5 group path where the image data will be saved.
        Datasets will be created inside the given group path:
        'data', 'extra', 'affine', the header information will
        be set as attributes of the 'data' dataset.


def spatialimg_to_hdfpath(file_path, spatial_img, h5path=None, append=True):

if h5path is None:<EOL><INDENT>h5path = '<STR_LIT>'<EOL><DEDENT>mode = '<STR_LIT:w>'<EOL>if os.path.exists(file_path):<EOL><INDENT>if append:<EOL><INDENT>mode = '<STR_LIT:a>'<EOL><DEDENT><DEDENT>with h5py.File(file_path, mode) as f:<EOL><INDENT>try:<EOL><INDENT>h5img = f.create_group(h5path)<EOL>spatialimg_to_hdfgroup(h5img, spatial_img)<EOL><DEDENT>except ValueError as ve:<EOL><INDENT>raise Exception('<STR_LIT>' + h5path) from ve<EOL><DEDENT><DEDENT>

Saves a Nifti1Image into an HDF5 file.

    Parameters
    ----------
    file_path: string
        Output HDF5 file path

    spatial_img: nibabel SpatialImage
        Image to be saved

    h5path: string
        HDF5 group path where the image data will be saved.
        Datasets will be created inside the given group path:
        'data', 'extra', 'affine', the header information will
        be set as attributes of the 'data' dataset.
        Default: '/img'

    append: bool
        True if you don't want to erase the content of the file
        if it already exists, False otherwise.

    Note
    ----
    HDF5 open modes
    >>> 'r' Readonly, file must exist
    >>> 'r+' Read/write, file must exist
    >>> 'w' Create file, truncate if exists
    >>> 'w-' Create file, fail if exists
    >>> 'a' Read/write if exists, create otherwise (default)


with h5py.File(file_path, '<STR_LIT:r>') as f:<EOL><INDENT>return hdfgroup_to_nifti1image(f[h5path])<EOL><DEDENT>

Returns a nibabel Nifti1Image from a HDF5 group datasets

    Parameters
    ----------
    file_path: string
        HDF5 file path

    h5path:
        HDF5 group path in file_path

    Returns
    -------
        nibabel Nifti1Image


try:<EOL><INDENT>data   = h5group['<STR_LIT:data>'][:]<EOL>affine = h5group['<STR_LIT>'][:]<EOL>extra = None<EOL>if '<STR_LIT>' in h5group:<EOL><INDENT>extra = h5group['<STR_LIT>'][:]<EOL><DEDENT>header = get_nifti1hdr_from_h5attrs(h5group['<STR_LIT:data>'].attrs)<EOL>img = nib.Nifti1Image(data, affine, header=header, extra=extra)<EOL>return img<EOL><DEDENT>except KeyError as ke:<EOL><INDENT>raise Exception('<STR_LIT>' + h5group.name) from ke<EOL><DEDENT>

Returns a nibabel Nifti1Image from a HDF5 group datasets

    Parameters
    ----------
    h5group: h5py.Group
        HDF5 group

    Returns
    -------
    nibabel Nifti1Image


hdr = nib.Nifti1Header()<EOL>for k in list(h5attrs.keys()):<EOL><INDENT>hdr[str(k)] = np.array(h5attrs[k])<EOL><DEDENT>return hdr<EOL>

Transforms an H5py Attributes set to a dict.
    Converts unicode string keys into standard strings
    and each value into a numpy array.

    Parameters
    ----------
    h5attrs: H5py Attributes

    Returns
    --------
    dict


child_nodes = []<EOL>def append_parent_if_dataset(name, obj):<EOL><INDENT>if isinstance(obj, h5py.Dataset):<EOL><INDENT>if name.split('<STR_LIT:/>')[-<NUM_LIT:1>] == '<STR_LIT:data>':<EOL><INDENT>child_nodes.append(obj.parent)<EOL><DEDENT><DEDENT><DEDENT>vols = []<EOL>h5group.visititems(append_parent_if_dataset)<EOL>for c in child_nodes:<EOL><INDENT>vols.append(hdfgroup_to_nifti1image(c))<EOL><DEDENT>return vols<EOL>

Returns in a list all images found under h5group.

    Parameters
    ----------
    h5group: h5py.Group
        HDF group

    Returns
    -------
    list of nifti1Image


def insert_volumes_in_one_dataset(file_path, h5path, file_list, newshape=None,<EOL>concat_axis=<NUM_LIT:0>, dtype=None, append=True):

def isalambda(v):<EOL><INDENT>return isinstance(v, type(lambda: None)) and v.__name__ == '<STR_LIT>'<EOL><DEDENT>mode = '<STR_LIT:w>'<EOL>if os.path.exists(file_path):<EOL><INDENT>if append:<EOL><INDENT>mode = '<STR_LIT:a>'<EOL><DEDENT><DEDENT>imgs = [nib.load(vol) for vol in file_list]<EOL>shapes = [np.array(img.get_shape()) for img in imgs]<EOL>if newshape is not None:<EOL><INDENT>if isalambda(newshape):<EOL><INDENT>nushapes = np.array([newshape(shape) for shape in shapes])<EOL><DEDENT>else:<EOL><INDENT>nushapes = np.array([shape for shape in shapes])<EOL><DEDENT><DEDENT>for nushape in nushapes:<EOL><INDENT>assert(len(nushape) - <NUM_LIT:1> < concat_axis)<EOL><DEDENT>n_dims = nushapes.shape[<NUM_LIT:1>]<EOL>ds_shape = np.zeros(n_dims, dtype=np.int)<EOL>for a in list(range(n_dims)):<EOL><INDENT>if a == concat_axis:<EOL><INDENT>ds_shape[a] = np.sum(nushapes[:, concat_axis])<EOL><DEDENT>else:<EOL><INDENT>ds_shape[a] = np.max(nushapes[:, a])<EOL><DEDENT><DEDENT>if dtype is None:<EOL><INDENT>dtype = imgs[<NUM_LIT:0>].get_data_dtype()<EOL><DEDENT>with h5py.File(file_path, mode) as f:<EOL><INDENT>try:<EOL><INDENT>ic = <NUM_LIT:0><EOL>h5grp = f.create_group(os.path.dirname(h5path))<EOL>h5ds = h5grp.create_dataset(os.path.basename(h5path),<EOL>ds_shape, dtype)<EOL>for img in imgs:<EOL><INDENT>nushape = nushapes[ic, :]<EOL>def append_to_dataset(h5ds, idx, data, concat_axis):<EOL><INDENT>"""<STR_LIT>"""<EOL>shape = data.shape<EOL>ndims = len(shape)<EOL>if ndims == <NUM_LIT:1>:<EOL><INDENT>if concat_axis == <NUM_LIT:0>:<EOL><INDENT>h5ds[idx] = data<EOL><DEDENT><DEDENT>elif ndims == <NUM_LIT:2>:<EOL><INDENT>if concat_axis == <NUM_LIT:0>:<EOL><INDENT>h5ds[idx ] = data<EOL><DEDENT>elif concat_axis == <NUM_LIT:1>:<EOL><INDENT>h5ds[idx ] = data<EOL><DEDENT><DEDENT>elif ndims == <NUM_LIT:3>:<EOL><INDENT>if concat_axis == <NUM_LIT:0>:<EOL><INDENT>h5ds[idx ] = data<EOL><DEDENT>elif concat_axis == <NUM_LIT:1>:<EOL><INDENT>h5ds[idx ] = data<EOL><DEDENT>elif concat_axis == <NUM_LIT:2>:<EOL><INDENT>h5ds[idx ] = data<EOL><DEDENT><DEDENT><DEDENT>append_to_dataset(h5ds, ic,<EOL>np.reshape(img.get_data(), tuple(nushape)),<EOL>concat_axis)<EOL>ic += <NUM_LIT:1><EOL><DEDENT><DEDENT>except ValueError as ve:<EOL><INDENT>raise Exception('<STR_LIT>'.format(h5path, file_path)) from ve<EOL><DEDENT><DEDENT>

Inserts all given nifti files from file_list into one dataset in fname.
    This will not check if the dimensionality of all files match.

    Parameters
    ----------
    file_path: string
        HDF5 file path

    h5path: string

    file_list: list of strings

    newshape: tuple or lambda function
        If None, it will not reshape the images.
        If a lambda function, this lambda will receive only the shape array.
        e.g., newshape = lambda x: (np.prod(x[0:3]), x[3])
        If a tuple, it will try to reshape all the images with the same shape.
        It must work for all the images in file_list.

    concat_axis: int
        Axis of concatenation after reshaping

    dtype: data type
    Dataset data type
    If not set, will use the type of the first file.

    append: bool

    Raises
    ------
    ValueError if concat_axis is bigger than data dimensionality.

    Note
    ----
    For now, this only works if the dataset ends up being a 2D matrix.
    I haven't tested for multi-dimensionality concatenations.


img_data = get_img_data(img)<EOL>out = np.zeros(img_data.shape, dtype=img_data.dtype)<EOL>krn_dim = [<NUM_LIT:3>] * img_data.ndim<EOL>kernel  = np.ones(krn_dim, dtype=int)<EOL>vals = np.unique(img_data)<EOL>vals = vals[vals != <NUM_LIT:0>]<EOL>for i in vals:<EOL><INDENT>roi  = img_data == i<EOL>hits = scn.binary_hit_or_miss(roi, kernel)<EOL>roi[hits] = <NUM_LIT:0><EOL>out[roi > <NUM_LIT:0>] = i<EOL><DEDENT>return out<EOL>

Find all the ROIs in img and returns a similar volume with the ROIs
    emptied, keeping only their border voxels.

    This is useful for DTI tractography.

    Parameters
    ----------
    img: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    Returns
    -------
    np.ndarray
        an array of same shape as img_data


def pick_rois(rois_img, roi_values, bg_val=<NUM_LIT:0>):

img = read_img(rois_img)<EOL>img_data = img.get_data()<EOL>if bg_val == <NUM_LIT:0>:<EOL><INDENT>out = np.zeros(img_data.shape, dtype=img_data.dtype)<EOL><DEDENT>else:<EOL><INDENT>out = np.ones(img_data.shape, dtype=img_data.dtype) * bg_val<EOL><DEDENT>for r in roi_values:<EOL><INDENT>out[img_data == r] = r<EOL><DEDENT>return nib.Nifti2Image(out, affine=img.affine, header=img.header)<EOL>

Return the `rois_img` only with the ROI values from `roi_values`.
    Parameters
    ----------
    rois_img: niimg-like

    roi_values: list of int or float
        The list of values from rois_img.

    bg_val: int or float
        The background value of `rois_img`.

    Returns
    -------
    subset_rois_img: nibabel.Nifti2Image


<EOL>volume = np.asarray(volume)<EOL>labels, num_labels = scn.label(volume)<EOL>if not num_labels:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if num_labels == <NUM_LIT:1>:<EOL><INDENT>return volume.astype(np.bool)<EOL><DEDENT>label_count = np.bincount(labels.ravel().astype(np.int))<EOL>label_count[<NUM_LIT:0>] = <NUM_LIT:0><EOL>return labels == label_count.argmax()<EOL>

Return the largest connected component of a 3D array.

    Parameters
    -----------
    volume: numpy.array
        3D boolean array.

    Returns
    --------
    volume: numpy.array
        3D boolean array with only one connected component.


labels, num_labels = scn.label(volume)<EOL>labels_to_keep = set([i for i in range(num_labels)<EOL>if np.sum(labels == i) >= min_cluster_size])<EOL>clusters_mask = np.zeros_like(volume, dtype=int)<EOL>for l in range(num_labels):<EOL><INDENT>if l in labels_to_keep:<EOL><INDENT>clusters_mask[labels == l] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return clusters_mask<EOL>

Return as mask for `volume` that includes only areas where
    the connected components have a size bigger than `min_cluster_size`
    in number of voxels.

    Parameters
    -----------
    volume: numpy.array
        3D boolean array.

    min_cluster_size: int
        Minimum size in voxels that the connected component must have.

    Returns
    --------
    volume: numpy.array
        3D int array with a mask excluding small connected components.


roifiles = []<EOL>for roi in roislist:<EOL><INDENT>try:<EOL><INDENT>roi_file = search_list(roi, filelist)[<NUM_LIT:0>]<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(str(exc)))<EOL><DEDENT>else:<EOL><INDENT>roifiles.append(roi_file)<EOL><DEDENT><DEDENT>return binarise(roifiles)<EOL>

Look for the files in filelist containing the names in roislist, these files will be opened, binarised
    and merged in one mask.

    Parameters
    ----------
    roislist: list of strings
        Names of the ROIs, which will have to be in the names of the files in filelist.

    filelist: list of strings
        List of paths to the volume files containing the ROIs.

    Returns
    -------
    numpy.ndarray
        Mask volume


rois = np.unique(arr)<EOL>rois = rois[np.nonzero(rois)]<EOL>rois.sort()<EOL>return rois<EOL>

Return a sorted list of the non-zero unique values of arr.

    Parameters
    ----------
    arr: numpy.ndarray
        The data array

    Returns
    -------
    list of items of arr.


return get_unique_nonzeros(check_img(atlas_img).get_data())<EOL>

Extract unique values from the atlas and returns them as an ordered list.

Parameters
----------
atlas_img: img-like object or str
    Volume defining different ROIs.
    Can either be:
    - a file path to a Nifti image
    - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
    If niimg is a string, consider it as a path to Nifti image and
    call nibabel.load on it. If it is an object, check if get_data()
    and get_affine() methods are present, raise TypeError otherwise.

Returns
-------
np.ndarray
    An 1D array of roi values from atlas volume.

Note
----
The roi with value 0 will be considered background so will be removed.


from scipy.ndimage.measurements import center_of_mass<EOL>roisvals = np.unique(vol)<EOL>roisvals = roisvals[roisvals != <NUM_LIT:0>]<EOL>rois_centers = OrderedDict()<EOL>for r in roisvals:<EOL><INDENT>rois_centers[r] = center_of_mass(vol, vol, r)<EOL><DEDENT>return rois_centers<EOL>

Get the center of mass for each ROI in the given volume.

    Parameters
    ----------
    vol: numpy ndarray
        Volume with different values for each ROI.

    Returns
    -------
    OrderedDict
        Each entry in the dict has the ROI value as key and the center_of_mass coordinate as value.


def partition_timeseries(image, roi_img, mask_img=None, zeroe=True, roi_values=None, outdict=False):

img  = read_img(image)<EOL>rois = read_img(roi_img)<EOL>check_img_compatibility(img, rois, only_check_3d=True)<EOL>roi_data = rois.get_data()<EOL>if roi_values is not None:<EOL><INDENT>for rv in roi_values:<EOL><INDENT>if not np.any(roi_data == rv):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(rv, repr_imgs(roi_img)))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>roi_values = get_unique_nonzeros(roi_data)<EOL><DEDENT>if mask_img is None:<EOL><INDENT>mask_data = None<EOL><DEDENT>else:<EOL><INDENT>mask = load_mask(mask_img)<EOL>check_img_compatibility(img, mask, only_check_3d=True)<EOL>mask_data = mask.get_data()<EOL><DEDENT>if outdict:<EOL><INDENT>extract_data = _extract_timeseries_dict<EOL><DEDENT>else:<EOL><INDENT>extract_data = _extract_timeseries_list<EOL><DEDENT>try:<EOL><INDENT>return extract_data(img.get_data(), rois.get_data(), mask_data,<EOL>roi_values=roi_values, zeroe=zeroe)<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>

Partition the timeseries in tsvol according to the ROIs in roivol.
    If a mask is given, will use it to exclude any voxel outside of it.

    The outdict indicates whether you want a dictionary for each set of timeseries keyed by the ROI value
    or a list of timeseries sets. If True and roi_img is not None will return an OrderedDict, if False
    or roi_img or roi_list is None will return a list.

    Background value is assumed to be 0 and won't be used here.

    Parameters
    ----------
    image: img-like object or str
        4D timeseries volume

    roi_img: img-like object or str
        3D volume defining different ROIs.

    mask_img: img-like object or str
        3D mask volume

    zeroe: bool
        If true will remove the null timeseries voxels.

    roi_values: list of ROI values (int?)
        List of the values of the ROIs to indicate the
        order and which ROIs will be processed.

    outdict: bool
        If True will return an OrderedDict of timeseries sets, otherwise a list.

    Returns
    -------
    timeseries: list or OrderedDict
        A dict with the timeseries as items and keys as the ROIs voxel values or
        a list where each element is the timeseries set ordered by the sorted values in roi_img or by the roi_values
        argument.


return partition_timeseries(*args, **kwargs)<EOL>

Look at partition_timeseries function docstring.


def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True):

if maskvol is not None:<EOL><INDENT>indices = (roivol == roivalue) * (maskvol > <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>indices = roivol == roivalue<EOL><DEDENT>if datavol.ndim == <NUM_LIT:4>:<EOL><INDENT>ts = datavol[indices, :]<EOL><DEDENT>else:<EOL><INDENT>ts = datavol[indices]<EOL><DEDENT>if zeroe:<EOL><INDENT>if datavol.ndim == <NUM_LIT:4>:<EOL><INDENT>ts = ts[ts.sum(axis=<NUM_LIT:1>) != <NUM_LIT:0>, :]<EOL><DEDENT><DEDENT>return ts<EOL>

Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.
    The ROI can be masked by `maskvol`.

    Parameters
    ----------
    datavol: numpy.ndarray
        4D timeseries volume or a 3D volume to be partitioned

    roivol: numpy.ndarray
        3D ROIs volume

    roivalue: int or float
        A value from roivol that represents the ROI to be used for extraction.

    maskvol: numpy.ndarray
        3D mask volume

    zeroe: bool
        If true will remove the null timeseries voxels.  Only applied to timeseries (4D) data.

    Returns
    -------
    values: np.array
        An array of the values in the indicated ROI.
        A 2D matrix if `datavol` is 4D or a 1D vector if `datavol` is 3D.


def _extract_timeseries_dict(tsvol, roivol, maskvol=None, roi_values=None, zeroe=True):

_check_for_partition(tsvol, roivol, maskvol)<EOL>if roi_values is None:<EOL><INDENT>roi_values = get_unique_nonzeros(roivol)<EOL><DEDENT>ts_dict = OrderedDict()<EOL>for r in roi_values:<EOL><INDENT>ts = _partition_data(tsvol, roivol, r, maskvol, zeroe)<EOL>if len(ts) == <NUM_LIT:0>:<EOL><INDENT>ts = np.zeros(tsvol.shape[-<NUM_LIT:1>])<EOL><DEDENT>ts_dict[r] = ts<EOL><DEDENT>return ts_dict<EOL>

Partition the timeseries in tsvol according to the ROIs in roivol.
    If a mask is given, will use it to exclude any voxel outside of it.

    Parameters
    ----------
    tsvol: numpy.ndarray
        4D timeseries volume or a 3D volume to be partitioned

    roivol: numpy.ndarray
        3D ROIs volume

    maskvol: numpy.ndarray
        3D mask volume

    zeroe: bool
        If true will remove the null timeseries voxels.

    roi_values: list of ROI values (int?)
        List of the values of the ROIs to indicate the
        order and which ROIs will be processed.

    Returns
    -------
    ts_dict: OrderedDict
        A dict with the timeseries as items and keys as the ROIs voxel values.


def _extract_timeseries_list(tsvol, roivol, maskvol=None, roi_values=None, zeroe=True):

_check_for_partition(tsvol, roivol, maskvol)<EOL>if roi_values is None:<EOL><INDENT>roi_values = get_unique_nonzeros(roivol)<EOL><DEDENT>ts_list = []<EOL>for r in roi_values:<EOL><INDENT>ts = _partition_data(tsvol, roivol, r, maskvol, zeroe)<EOL>if len(ts) == <NUM_LIT:0>:<EOL><INDENT>ts = np.zeros(tsvol.shape[-<NUM_LIT:1>])<EOL><DEDENT>ts_list.append(ts)<EOL><DEDENT>return ts_list<EOL>

Partition the timeseries in tsvol according to the ROIs in roivol.
    If a mask is given, will use it to exclude any voxel outside of it.

    Parameters
    ----------
    tsvol: numpy.ndarray
        4D timeseries volume or a 3D volume to be partitioned

    roivol: numpy.ndarray
        3D ROIs volume

    maskvol: numpy.ndarray
        3D mask volume

    zeroe: bool
        If true will remove the null timeseries voxels. Only applied to timeseries (4D) data.

    roi_values: list of ROI values (int?)
        List of the values of the ROIs to indicate the
        order and which ROIs will be processed.

    Returns
    -------
    ts_list: list
        A list with the timeseries arrays as items


img      = check_img(image)<EOL>hdr, aff = get_img_info(img)<EOL>if len(img.shape) != <NUM_LIT:4>:<EOL><INDENT>raise AttributeError('<STR_LIT>'.format(repr_imgs(img)))<EOL><DEDENT>if not <NUM_LIT:0> <= vol_idx < img.shape[<NUM_LIT:3>]:<EOL><INDENT>raise IndexError('<STR_LIT>'<EOL>'<STR_LIT>'.format(repr_imgs(img), img.shape[<NUM_LIT:3>], vol_idx))<EOL><DEDENT>img_data = img.get_data()<EOL>new_vol  = img_data[:, :, :, vol_idx].copy()<EOL>hdr.set_data_shape(hdr.get_data_shape()[:<NUM_LIT:3>])<EOL>return new_vol, hdr, aff<EOL>

Pick one 3D volume from a 4D nifti image file

    Parameters
    ----------
    image: img-like object or str
        Volume defining different ROIs.
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    vol_idx: int
        Index of the 3D volume to be extracted from the 4D volume.

    Returns
    -------
    vol, hdr, aff
        The data array, the image header and the affine transform matrix.


img    = check_img(image, make_it_3d=True)<EOL>values = np.unique(img.get_data())<EOL>if len(values) == <NUM_LIT:1>:<EOL><INDENT>if values[<NUM_LIT:0>] == <NUM_LIT:0> and not allow_empty:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>elif len(values) == <NUM_LIT:2>:<EOL><INDENT>if <NUM_LIT:0> not in values:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(values))<EOL><DEDENT><DEDENT>elif len(values) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(values))<EOL><DEDENT>return nib.Nifti1Image(as_ndarray(get_img_data(img), dtype=bool), img.get_affine(), img.get_header())<EOL>

Load a Nifti mask volume.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    allow_empty: boolean, optional
        Allow loading an empty mask (full of 0 values)

    Returns
    -------
    nibabel.Nifti1Image with boolean data.


mask = load_mask(image, allow_empty=allow_empty)<EOL>return get_img_data(mask), mask.get_affine()<EOL>

Load a Nifti mask volume and return its data matrix as boolean and affine.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    allow_empty: boolean, optional
        Allow loading an empty mask (full of 0 values)

    Returns
    -------
    numpy.ndarray with dtype==bool, numpy.ndarray of affine transformation


img = check_img(image)<EOL>return img.get_data() > threshold<EOL>

Binarise image with the given threshold

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    threshold: float

    Returns
    -------
    binarised_img: numpy.ndarray
        Mask volume


firstimg = check_img(filelist[<NUM_LIT:0>])<EOL>mask     = np.zeros_like(firstimg.get_data())<EOL>try:<EOL><INDENT>for volf in filelist:<EOL><INDENT>roiimg = check_img(volf)<EOL>check_img_compatibility(firstimg, roiimg)<EOL>mask  += get_img_data(roiimg)<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr_imgs(firstimg), repr_imgs(volf))) from exc<EOL><DEDENT>else:<EOL><INDENT>return as_ndarray(mask > <NUM_LIT:0>, dtype=bool)<EOL><DEDENT>

Creates a binarised mask with the union of the files in filelist.

Parameters
----------
filelist: list of img-like object or boyle.nifti.NeuroImage or str
    List of paths to the volume files containing the ROIs.
    Can either be:
    - a file path to a Nifti image
    - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
    If niimg is a string, consider it as a path to Nifti image and
    call nibabel.load on it. If it is an object, check if get_data()
    and get_affine() methods are present, raise TypeError otherwise.

Returns
-------
ndarray of bools
    Mask volume

Raises
------
ValueError


img  = check_img(image)<EOL>mask = check_img(mask_img)<EOL>check_img_compatibility(img, mask)<EOL>vol          = img.get_data()<EOL>mask_data, _ = load_mask_data(mask)<EOL>return vol[mask_data], mask_data<EOL>

Read a Nifti file nii_file and a mask Nifti file.
    Returns the voxels in nii_file that are within the mask, the mask indices
    and the mask shape.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    mask_img: img-like object or boyle.nifti.NeuroImage or str
        3D mask array: True where a voxel should be used.
        See img description.

    Returns
    -------
    vol[mask_indices], mask_indices

    Note
    ----
    nii_file and mask_file must have the same shape.

    Raises
    ------
    NiftiFilesNotCompatible, ValueError


img  = check_img(image)<EOL>mask = check_img(mask_img)<EOL>check_img_compatibility(img, mask, only_check_3d=True)<EOL>vol = get_data(img)<EOL>series, mask_data = _apply_mask_to_4d_data(vol, mask)<EOL>return series, mask_data<EOL>

Read a Nifti file nii_file and a mask Nifti file.
    Extract the signals in nii_file that are within the mask, the mask indices
    and the mask shape.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    mask_img: img-like object or boyle.nifti.NeuroImage or str
        3D mask array: True where a voxel should be used.
        See img description.

    smooth_mm: float #TBD
        (optional) The size in mm of the FWHM Gaussian kernel to smooth the signal.
        If True, remove_nans is True.

    remove_nans: bool #TBD
        If remove_nans is True (default), the non-finite values (NaNs and
        infs) found in the images will be replaced by zeros.

    Returns
    -------
    session_series, mask_data

    session_series: numpy.ndarray
        2D array of series with shape (voxel number, image number)

    Note
    ----
    nii_file and mask_file must have the same shape.

    Raises
    ------
    FileNotFound, NiftiFilesNotCompatible


mask_data = load_mask_data(mask_img)<EOL>return vol_data[mask_data], mask_data<EOL>

Parameters
----------
vol_data:
mask_img:

Returns
-------
masked_data, mask_indices

masked_data: numpy.ndarray
    2D array of series with shape (image number, voxel number)

Note
----
vol_data and mask_file must have the same shape.


def vector_to_volume(arr, mask, order='<STR_LIT:C>'):

if mask.dtype != np.bool:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if arr.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if arr.ndim == <NUM_LIT:2> and any(v == <NUM_LIT:1> for v in arr.shape):<EOL><INDENT>log.debug('<STR_LIT>'.format(arr.shape))<EOL>arr = arr.flatten()<EOL><DEDENT>volume = np.zeros(mask.shape[:<NUM_LIT:3>], dtype=arr.dtype, order=order)<EOL>volume[mask] = arr<EOL>return volume<EOL>

Transform a given vector to a volume. This is a reshape function for
    3D flattened and maybe masked vectors.

    Parameters
    ----------
    arr: np.array
        1-Dimensional array

    mask: numpy.ndarray
        Mask image. Must have 3 dimensions, bool dtype.

    Returns
    -------
    np.ndarray


def matrix_to_4dvolume(arr, mask, order='<STR_LIT:C>'):

if mask.dtype != np.bool:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if arr.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if mask.sum() != arr.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(mask.sum(), arr.shape))<EOL><DEDENT>data = np.zeros(mask.shape + (arr.shape[<NUM_LIT:1>],), dtype=arr.dtype,<EOL>order=order)<EOL>data[mask, :] = arr<EOL>return data<EOL>

Transform a given vector to a volume. This is a reshape function for
    4D flattened masked matrices where the second dimension of the matrix
    corresponds to the original 4th dimension.

    Parameters
    ----------
    arr: numpy.array
        2D numpy.array

    mask: numpy.ndarray
        Mask image. Must have 3 dimensions, bool dtype.

    dtype: return type
        If None, will get the type from vector

    Returns
    -------
    data: numpy.ndarray
        Unmasked data.
        Shape: (mask.shape[0], mask.shape[1], mask.shape[2], X.shape[1])


def niftilist_mask_to_array(img_filelist, mask_file=None, outdtype=None):

img = check_img(img_filelist[<NUM_LIT:0>])<EOL>if not outdtype:<EOL><INDENT>outdtype = img.dtype<EOL><DEDENT>mask_data, _ = load_mask_data(mask_file)<EOL>indices      = np.where      (mask_data)<EOL>mask = check_img(mask_file)<EOL>outmat = np.zeros((len(img_filelist), np.count_nonzero(mask_data)),<EOL>dtype=outdtype)<EOL>for i, img_item in enumerate(img_filelist):<EOL><INDENT>img = check_img(img_item)<EOL>if not are_compatible_imgs(img, mask):<EOL><INDENT>raise NiftiFilesNotCompatible(repr_imgs(img), repr_imgs(mask_file))<EOL><DEDENT>vol = get_img_data(img)<EOL>outmat[i, :] = vol[indices]<EOL><DEDENT>return outmat, mask_data<EOL>

From the list of absolute paths to nifti files, creates a Numpy array
    with the masked data.

    Parameters
    ----------
    img_filelist: list of str
        List of absolute file paths to nifti files. All nifti files must have
        the same shape.

    mask_file: str
        Path to a Nifti mask file.
        Should be the same shape as the files in nii_filelist.

    outdtype: dtype
        Type of the elements of the array, if not set will obtain the dtype from
        the first nifti file.

    Returns
    -------
    outmat:
        Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors.

    mask_indices:
        Tuple with the 3D spatial indices of the masking voxels, for reshaping
        with vol_shape and remapping.

    vol_shape:
        Tuple with shape of the volumes, for reshaping.


fwhm = np.asarray(fwhm)<EOL>return fwhm / np.sqrt(<NUM_LIT:8> * np.log(<NUM_LIT:2>))<EOL>

Convert a FWHM value to sigma in a Gaussian kernel.

    Parameters
    ----------
    fwhm: float or numpy.array
       fwhm value or values

    Returns
    -------
    fwhm: float or numpy.array
       sigma values


sigma = np.asarray(sigma)<EOL>return np.sqrt(<NUM_LIT:8> * np.log(<NUM_LIT:2>)) * sigma<EOL>

Convert a sigma in a Gaussian kernel to a FWHM value.

    Parameters
    ----------
    sigma: float or numpy.array
       sigma value or values

    Returns
    -------
    fwhm: float or numpy.array
       fwhm values corresponding to `sigma` values


return smooth_imgs(image, smoothmm)<EOL>


def _smooth_data_array(arr, affine, fwhm, copy=True):

if arr.dtype.kind == '<STR_LIT:i>':<EOL><INDENT>if arr.dtype == np.int64:<EOL><INDENT>arr = arr.astype(np.float64)<EOL><DEDENT>else:<EOL><INDENT>arr = arr.astype(np.float32)<EOL><DEDENT><DEDENT>if copy:<EOL><INDENT>arr = arr.copy()<EOL><DEDENT>arr[np.logical_not(np.isfinite(arr))] = <NUM_LIT:0><EOL>try:<EOL><INDENT>affine = affine[:<NUM_LIT:3>, :<NUM_LIT:3>]<EOL>fwhm_sigma_ratio = np.sqrt(<NUM_LIT:8> * np.log(<NUM_LIT:2>))<EOL>vox_size         = np.sqrt(np.sum(affine ** <NUM_LIT:2>, axis=<NUM_LIT:0>))<EOL>sigma            = fwhm / (fwhm_sigma_ratio * vox_size)<EOL>for n, s in enumerate(sigma):<EOL><INDENT>ndimage.gaussian_filter1d(arr, s, output=arr, axis=n)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return arr<EOL><DEDENT>

Smooth images with a a Gaussian filter.

    Apply a Gaussian filter along the three first dimensions of arr.

    Parameters
    ----------
    arr: numpy.ndarray
        3D or 4D array, with image number as last dimension.

    affine: numpy.ndarray
        Image affine transformation matrix for image.

    fwhm: scalar, numpy.ndarray
        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.
        If a scalar is given, kernel width is identical on all three directions.
        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.

    copy: bool
        if True, will make a copy of the input array. Otherwise will directly smooth the input array.

    Returns
    -------
    smooth_arr: numpy.ndarray


if fwhm <= <NUM_LIT:0>:<EOL><INDENT>return images<EOL><DEDENT>if not isinstance(images, string_types) and hasattr(images, '<STR_LIT>'):<EOL><INDENT>only_one = False<EOL><DEDENT>else:<EOL><INDENT>only_one = True<EOL>images = [images]<EOL><DEDENT>result = []<EOL>for img in images:<EOL><INDENT>img    = check_img(img)<EOL>affine = img.get_affine()<EOL>smooth = _smooth_data_array(img.get_data(), affine, fwhm=fwhm, copy=True)<EOL>result.append(nib.Nifti1Image(smooth, affine))<EOL><DEDENT>if only_one:<EOL><INDENT>return result[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>

Smooth images using a Gaussian filter.

    Apply a Gaussian filter along the three first dimensions of each image in images.
    In all cases, non-finite values in input are zeroed.

    Parameters
    ----------
    imgs: str or img-like object or iterable of img-like objects
        See boyle.nifti.read.read_img
        Image(s) to smooth.

    fwhm: scalar or numpy.ndarray
        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.
        If a scalar is given, kernel width is identical on all three directions.
        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.

    Returns
    -------
    smooth_imgs: nibabel.Nifti1Image or list of.
        Smooth input image/s.


def _smooth_array(arr, affine, fwhm=None, ensure_finite=True, copy=True, **kwargs):

if arr.dtype.kind == '<STR_LIT:i>':<EOL><INDENT>if arr.dtype == np.int64:<EOL><INDENT>arr = arr.astype(np.float64)<EOL><DEDENT>else:<EOL><INDENT>arr = arr.astype(np.float32)<EOL><DEDENT><DEDENT>if copy:<EOL><INDENT>arr = arr.copy()<EOL><DEDENT>if ensure_finite:<EOL><INDENT>arr[np.logical_not(np.isfinite(arr))] = <NUM_LIT:0><EOL><DEDENT>if fwhm == '<STR_LIT>':<EOL><INDENT>arr = _fast_smooth_array(arr)<EOL><DEDENT>elif fwhm is not None:<EOL><INDENT>affine = affine[:<NUM_LIT:3>, :<NUM_LIT:3>]<EOL>fwhm_over_sigma_ratio = np.sqrt(<NUM_LIT:8> * np.log(<NUM_LIT:2>))<EOL>vox_size = np.sqrt(np.sum(affine ** <NUM_LIT:2>, axis=<NUM_LIT:0>))<EOL>sigma = fwhm / (fwhm_over_sigma_ratio * vox_size)<EOL>for n, s in enumerate(sigma):<EOL><INDENT>ndimage.gaussian_filter1d(arr, s, output=arr, axis=n, **kwargs)<EOL><DEDENT><DEDENT>return arr<EOL>

Smooth images by applying a Gaussian filter.
    Apply a Gaussian filter along the three first dimensions of arr.

    This is copied and slightly modified from nilearn:
    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py
    Added the **kwargs argument.

    Parameters
    ==========
    arr: numpy.ndarray
        4D array, with image number as last dimension. 3D arrays are also
        accepted.
    affine: numpy.ndarray
        (4, 4) matrix, giving affine transformation for image. (3, 3) matrices
        are also accepted (only these coefficients are used).
        If fwhm='fast', the affine is not used and can be None
    fwhm: scalar, numpy.ndarray, 'fast' or None
        Smoothing strength, as a full-width at half maximum, in millimeters.
        If a scalar is given, width is identical on all three directions.
        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.
        If fwhm == 'fast', a fast smoothing will be performed with
        a filter [0.2, 1, 0.2] in each direction and a normalisation
        to preserve the local average value.
        If fwhm is None, no filtering is performed (useful when just removal
        of non-finite values is needed).
    ensure_finite: bool
        if True, replace every non-finite values (like NaNs) by zero before
        filtering.
    copy: bool
        if True, input array is not modified. False by default: the filtering
        is performed in-place.
    kwargs: keyword-arguments
        Arguments for the ndimage.gaussian_filter1d function.

    Returns
    =======
    filtered_arr: numpy.ndarray
        arr, filtered.
    Notes
    =====
    This function is most efficient with arr in C order.


<EOL>if hasattr(imgs, "<STR_LIT>")and not isinstance(imgs, string_types):<EOL><INDENT>single_img = False<EOL><DEDENT>else:<EOL><INDENT>single_img = True<EOL>imgs = [imgs]<EOL><DEDENT>ret = []<EOL>for img in imgs:<EOL><INDENT>img = check_niimg(img)<EOL>affine = img.get_affine()<EOL>filtered = _smooth_array(img.get_data(), affine, fwhm=fwhm,<EOL>ensure_finite=True, copy=True, **kwargs)<EOL>ret.append(new_img_like(img, filtered, affine, copy_header=True))<EOL><DEDENT>if single_img:<EOL><INDENT>return ret[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return ret<EOL><DEDENT>

Smooth images by applying a Gaussian filter.
    Apply a Gaussian filter along the three first dimensions of arr.
    In all cases, non-finite values in input image are replaced by zeros.

    This is copied and slightly modified from nilearn:
    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py
    Added the **kwargs argument.

    Parameters
    ==========
    imgs: Niimg-like object or iterable of Niimg-like objects
        See http://nilearn.github.io/manipulating_images/manipulating_images.html#niimg.
        Image(s) to smooth.
    fwhm: scalar, numpy.ndarray, 'fast' or None
        Smoothing strength, as a Full-Width at Half Maximum, in millimeters.
        If a scalar is given, width is identical on all three directions.
        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.
        If fwhm == 'fast', a fast smoothing will be performed with
        a filter [0.2, 1, 0.2] in each direction and a normalisation
        to preserve the scale.
        If fwhm is None, no filtering is performed (useful when just removal
        of non-finite values is needed)
    Returns
    =======
    filtered_img: nibabel.Nifti1Image or list of.
        Input image, filtered. If imgs is an iterable, then filtered_img is a
        list.


try:<EOL><INDENT>get_data   = getattr(obj, '<STR_LIT>')<EOL>get_affine = getattr(obj, '<STR_LIT>')<EOL>return isinstance(get_data,   collections.Callable) andisinstance(get_affine, collections.Callable)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>

Check for get_data and get_affine method in an object

    Parameters
    ----------
    obj: any object
        Tested object

    Returns
    -------
    is_img: boolean
        True if get_data and get_affine methods are present and callable,
        False otherwise.


if hasattr(img, '<STR_LIT>') and img._data_cache is None:<EOL><INDENT>img = copy.deepcopy(img)<EOL><DEDENT>gc.collect()<EOL>return img.get_data()<EOL>

Get the data in the image without having a side effect on the Nifti1Image object

    Parameters
    ----------
    img: Nifti1Image

    Returns
    -------
    np.ndarray


if hasattr(img, '<STR_LIT>'):<EOL><INDENT>shape = img.shape<EOL><DEDENT>else:<EOL><INDENT>shape = img.get_data().shape<EOL><DEDENT>return shape<EOL>

Return the shape of img.

    Paramerers
    -----------
    img:

    Returns
    -------
    shape: tuple


imgx, imgy, imgz = get_shape(img)<EOL>return (i >= <NUM_LIT:0> and i < imgx) and(j >= <NUM_LIT:0> and j < imgy) and(k >= <NUM_LIT:0> and k < imgz)<EOL>

Return True if the given (i, j, k) voxel grid coordinate values are within the img boundaries.

    Parameters
    ----------
    @param img:
    @param i:
    @param j:
    @param k:

    Returns
    -------
    bool


try:<EOL><INDENT>check_img_compatibility(one_img, another_img)<EOL><DEDENT>except :<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>

Return true if one_img and another_img have the same shape.
    False otherwise.
    If both are nibabel.Nifti1Image will also check for affine matrices.

    Parameters
    ----------
    one_img: nibabel.Nifti1Image or np.ndarray

    another_img: nibabel.Nifti1Image  or np.ndarray

    Returns
    -------
    bool


def check_img_compatibility(one_img, another_img, only_check_3d=False):

nd_to_check = None<EOL>if only_check_3d:<EOL><INDENT>nd_to_check = <NUM_LIT:3><EOL><DEDENT>if hasattr(one_img, '<STR_LIT>') and hasattr(another_img, '<STR_LIT>'):<EOL><INDENT>if not have_same_shape(one_img, another_img, nd_to_check=nd_to_check):<EOL><INDENT>msg = '<STR_LIT>'.format(one_img.shape,<EOL>another_img.shape)<EOL>raise NiftiFilesNotCompatible(repr_imgs(one_img), repr_imgs(another_img), message=msg)<EOL><DEDENT><DEDENT>if hasattr(one_img, '<STR_LIT>') and hasattr(another_img, '<STR_LIT>'):<EOL><INDENT>if not have_same_affine(one_img, another_img, only_check_3d=only_check_3d):<EOL><INDENT>msg = '<STR_LIT>''<STR_LIT>'.format(one_img.get_affine(), another_img.get_affine())<EOL>raise NiftiFilesNotCompatible(repr_imgs(one_img), repr_imgs(another_img), message=msg)<EOL><DEDENT><DEDENT>

Return true if one_img and another_img have the same shape.
    False otherwise.
    If both are nibabel.Nifti1Image will also check for affine matrices.

    Parameters
    ----------
    one_img: nibabel.Nifti1Image or np.ndarray

    another_img: nibabel.Nifti1Image  or np.ndarray

    only_check_3d: bool
        If True will check only the 3D part of the affine matrices when they have more dimensions.

    Raises
    ------
    NiftiFilesNotCompatible


def have_same_affine(one_img, another_img, only_check_3d=False):

img1 = check_img(one_img)<EOL>img2 = check_img(another_img)<EOL>ndim1 = len(img1.shape)<EOL>ndim2 = len(img2.shape)<EOL>if ndim1 < <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr_imgs(img1), ndim1))<EOL><DEDENT>if ndim2 < <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr_imgs(img2), ndim1))<EOL><DEDENT>affine1 = img1.get_affine()<EOL>affine2 = img2.get_affine()<EOL>if only_check_3d:<EOL><INDENT>affine1 = affine1[:<NUM_LIT:3>, :<NUM_LIT:3>]<EOL>affine2 = affine2[:<NUM_LIT:3>, :<NUM_LIT:3>]<EOL><DEDENT>try:<EOL><INDENT>return np.allclose(affine1, affine2)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>

Return True if the affine matrix of one_img is close to the affine matrix of another_img.
    False otherwise.

    Parameters
    ----------
    one_img: nibabel.Nifti1Image

    another_img: nibabel.Nifti1Image

    only_check_3d: bool
        If True will extract only the 3D part of the affine matrices when they have more dimensions.

    Returns
    -------
    bool

    Raises
    ------
    ValueError


shape = get_shape(img)<EOL>if len(shape) == <NUM_LIT:3>:<EOL><INDENT>return img<EOL><DEDENT>elif (len(shape) == <NUM_LIT:4> and shape[<NUM_LIT:3>] == <NUM_LIT:1>):<EOL><INDENT>try:<EOL><INDENT>data   = get_data(img)<EOL>affine = img.get_affine()<EOL>img    = nib.Nifti1Image(data[:, :, :, <NUM_LIT:0>], affine)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception("<STR_LIT>".format(img)) from exc<EOL><DEDENT>else:<EOL><INDENT>return img<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>".format(shape))<EOL><DEDENT>

Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
    i.e., remove dimensions of size 1.

    Parameters
    ----------
    img: img-like object

    Returns
    -------
    3D img-like object


if isinstance(image, string_types):<EOL><INDENT>if not op.exists(image):<EOL><INDENT>raise FileNotFound(image)<EOL><DEDENT>try:<EOL><INDENT>img = nib.load(image)<EOL>if make_it_3d:<EOL><INDENT>img = _make_it_3d(img)<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(image)) from exc<EOL><DEDENT>else:<EOL><INDENT>return img<EOL><DEDENT><DEDENT>elif isinstance(image, nib.Nifti1Image) or is_img(image):<EOL><INDENT>return image<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(type(image)))<EOL><DEDENT>

Check that image is a proper img. Turn filenames into objects.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    make_it_3d: boolean, optional
        If True, check if the image is a 3D image and raise an error if not.

    Returns
    -------
    result: nifti-like
       result can be nibabel.Nifti1Image or the input, as-is. It is guaranteed
       that the returned object has get_data() and get_affine() methods.


if isinstance(imgs, string_types):<EOL><INDENT>return imgs<EOL><DEDENT>if isinstance(imgs, collections.Iterable):<EOL><INDENT>return '<STR_LIT>'.format('<STR_LIT:U+002CU+0020>'.join(repr_imgs(img) for img in imgs))<EOL><DEDENT>try:<EOL><INDENT>filename = imgs.get_filename()<EOL>if filename is not None:<EOL><INDENT>img_str = "<STR_LIT>".format(imgs.__class__.__name__, filename)<EOL><DEDENT>else:<EOL><INDENT>img_str = "<STR_LIT>".format(imgs.__class__.__name__,<EOL>repr(get_shape(imgs)),<EOL>repr(imgs.get_affine()))<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>log.error('<STR_LIT>')<EOL>return repr(imgs)<EOL><DEDENT>else:<EOL><INDENT>return img_str<EOL><DEDENT>


return repr_imgs(img)<EOL>


def have_same_shape(array1, array2, nd_to_check=None):

shape1 = array1.shape<EOL>shape2 = array2.shape<EOL>if nd_to_check is not None:<EOL><INDENT>if len(shape1) < nd_to_check:<EOL><INDENT>msg = '<STR_LIT>'.format(shape1)<EOL>raise ValueError(msg)<EOL><DEDENT>elif len(shape2) < nd_to_check:<EOL><INDENT>msg = '<STR_LIT>'.format(shape2)<EOL>raise ValueError(msg)<EOL><DEDENT>shape1 = shape1[:nd_to_check]<EOL>shape2 = shape2[:nd_to_check]<EOL><DEDENT>return shape1 == shape2<EOL>

Returns true if array1 and array2 have the same shapes, false
otherwise.

Parameters
----------
array1: numpy.ndarray

array2: numpy.ndarray

nd_to_check: int
    Number of the dimensions to check, i.e., if == 3 then will check only the 3 first numbers of array.shape.
Returns
-------
bool


img1shape = nib.load(fname1).get_shape()<EOL>img2shape = nib.load(fname2).get_shape()<EOL>return have_same_shape(img1shape, img2shape)<EOL>

@param fname1: string
File path of an image

@param fname2: string
File path of an image

@return: bool
True if both have the same geometry


img1shape = nib.load(fname1).get_shape()<EOL>img2shape = nib.load(fname2).get_shape()<EOL>return img1shape[:<NUM_LIT:3>] == img2shape[:<NUM_LIT:3>]<EOL>


if not have_same_geometry(fname1, fname2):<EOL><INDENT>raise ArithmeticError('<STR_LIT>' + fname1 + '<STR_LIT>' + fname2)<EOL><DEDENT>


if not have_same_spatial_geometry(fname1, fname2):<EOL><INDENT>raise ArithmeticError('<STR_LIT>' + fname1 + '<STR_LIT>' + fname2)<EOL><DEDENT>


return func_img.get_header().get_zooms()[-<NUM_LIT:1>]<EOL>

Extracts the supposed sampling interval (TR) from the nifti file header.

@param func_img: a NiBabel SpatialImage

@return: float
The TR value from the image header


if is_atlas2anat_inverted:<EOL><INDENT>anat_to_mni_nl_inv = atlas2anat_nonlin_xfm_filepath<EOL><DEDENT>else:<EOL><INDENT>output_dir         = op.abspath   (op.dirname(atlasinanat_out_filepath))<EOL>ext                = get_extension(atlas2anat_nonlin_xfm_filepath)<EOL>anat_to_mni_nl_inv = op.join(output_dir, remove_ext(op.basename(atlas2anat_nonlin_xfm_filepath)) + '<STR_LIT>' + ext)<EOL><DEDENT>invwarp_cmd   = op.join('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>applywarp_cmd = op.join('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>fslsub_cmd    = op.join('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>if parallel:<EOL><INDENT>invwarp_cmd   = fslsub_cmd + '<STR_LIT:U+0020>' + invwarp_cmd<EOL>applywarp_cmd = fslsub_cmd + '<STR_LIT:U+0020>' + applywarp_cmd<EOL><DEDENT>if rewrite or (not is_atlas2anat_inverted and not op.exists(anat_to_mni_nl_inv)):<EOL><INDENT>log.debug('<STR_LIT>'.format(anat_to_mni_nl_inv))<EOL>cmd  = invwarp_cmd + '<STR_LIT:U+0020>'<EOL>cmd += '<STR_LIT>'.format(atlas2anat_nonlin_xfm_filepath)<EOL>cmd += '<STR_LIT>'.format(anat_to_mni_nl_inv)<EOL>cmd += '<STR_LIT>'.format(anatbrain_filepath)<EOL>log.debug('<STR_LIT>'.format(cmd))<EOL>check_call(cmd)<EOL><DEDENT>if rewrite or not op.exists(atlasinanat_out_filepath):<EOL><INDENT>log.debug('<STR_LIT>'.format(atlasinanat_out_filepath))<EOL>cmd  = applywarp_cmd + '<STR_LIT:U+0020>'<EOL>cmd += '<STR_LIT>'.format(atlas_filepath)<EOL>cmd += '<STR_LIT>'.format(anatbrain_filepath)<EOL>cmd += '<STR_LIT>'.format(anat_to_mni_nl_inv)<EOL>cmd += '<STR_LIT>'.format(interp)<EOL>cmd += '<STR_LIT>'.format(atlasinanat_out_filepath)<EOL>log.debug('<STR_LIT>'.format(cmd))<EOL>check_call(cmd)<EOL><DEDENT>if rewrite or not op.exists(atlasinfunc_out_filepath):<EOL><INDENT>log.debug('<STR_LIT>'.format(atlasinfunc_out_filepath))<EOL>cmd  = applywarp_cmd + '<STR_LIT:U+0020>'<EOL>cmd += '<STR_LIT>'.format(atlasinanat_out_filepath)<EOL>cmd += '<STR_LIT>'.format(meanfunc_filepath)<EOL>cmd += '<STR_LIT>'.format(anat2func_lin_xfm_filepath)<EOL>cmd += '<STR_LIT>'.format(interp)<EOL>cmd += '<STR_LIT>'.format(atlasinfunc_out_filepath)<EOL>log.debug('<STR_LIT>'.format(cmd))<EOL>check_call(cmd)<EOL><DEDENT>

Call FSL tools to apply transformations to a given atlas to a functional image.
    Given the transformation matrices.

    Parameters
    ----------
    atlas_filepath: str
        Path to the 3D atlas volume file.

    anatbrain_filepath: str
        Path to the anatomical brain volume file (skull-stripped and registered to the same space as the atlas,
        e.g., MNI).

    meanfunc_filepath: str
        Path to the average functional image to be used as reference in the last applywarp step.

    atlas2anat_nonlin_xfm_filepath: str
        Path to the atlas to anatomical brain linear transformation .mat file.
        If you have the inverse transformation, i.e., anatomical brain to atlas, set is_atlas2anat_inverted to True.

    is_atlas2anat_inverted: bool
        If False will have to calculate the inverse atlas2anat transformation to apply the transformations.
        This step will be performed with FSL invwarp.

    anat2func_lin_xfm_filepath: str
        Path to the anatomical to functional .mat linear transformation file.

    atlasinanat_out_filepath: str
        Path to output file which will contain the 3D atlas in the subject anatomical space.

    atlasinfunc_out_filepath: str
        Path to output file which will contain the 3D atlas in the subject functional space.

    verbose: bool
        If verbose will show DEBUG log info.

    rewrite: bool
        If True will re-run all the commands overwriting any existing file. Otherwise will check if
        each file exists and if it does won't run the command.

    parallel: bool
        If True will launch the commands using ${FSLDIR}/fsl_sub to use the cluster infrastructure you have setup
        with FSL (SGE or HTCondor).


<EOL>if not images:<EOL><INDENT>return None<EOL><DEDENT>axis_dim = {'<STR_LIT:x>': <NUM_LIT:0>,<EOL>'<STR_LIT:y>': <NUM_LIT:1>,<EOL>'<STR_LIT:z>': <NUM_LIT:2>,<EOL>'<STR_LIT:t>': <NUM_LIT:3>,<EOL>}<EOL>if axis not in axis_dim:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(set(axis_dim.keys()), axis))<EOL><DEDENT>img1 = images[<NUM_LIT:0>]<EOL>for img in images:<EOL><INDENT>check_img_compatibility(img1, img)<EOL><DEDENT>image_data = []<EOL>for img in images:<EOL><INDENT>image_data.append(check_img(img).get_data())<EOL><DEDENT>work_axis = axis_dim[axis]<EOL>ndim = image_data[<NUM_LIT:0>].ndim<EOL>if ndim - <NUM_LIT:1> < work_axis:<EOL><INDENT>image_data = [np.expand_dims(img, axis=work_axis) for img in image_data]<EOL><DEDENT>return np.concatenate(image_data, axis=work_axis)<EOL>

Concatenate `images` in the direction determined in `axis`.

    Parameters
    ----------
    images: list of str or img-like object.
        See NeuroImage constructor docstring.

    axis: str
      't' : concatenate images in time
      'x' : concatenate images in the x direction
      'y' : concatenate images in the y direction
      'z' : concatenate images in the z direction

    Returns
    -------
    merged: img-like object


@wraps(f)<EOL>def wrapped(*args, **kwargs):<EOL><INDENT>r = f(*args, **kwargs)<EOL>img = read_img(args[<NUM_LIT:0>])<EOL>return nib.Nifti1Image(r, affine=img.get_affine(), header=img.header)<EOL><DEDENT>return wrapped<EOL>

Picks a function whose first argument is an `img`, processes its
    data and returns a numpy array. This decorator wraps this numpy array
    into a nibabel.Nifti1Image.


@nifti_out<EOL>def thr_img(img, thr=<NUM_LIT>, mode='<STR_LIT:+>'):

vol  = read_img(img).get_data()<EOL>if mode == '<STR_LIT:+>':<EOL><INDENT>mask = vol > thr<EOL><DEDENT>elif mode == '<STR_LIT>' or mode == '<STR_LIT>':<EOL><INDENT>mask = np.abs(vol) > thr<EOL><DEDENT>elif mode == '<STR_LIT:->':<EOL><INDENT>mask = vol < -thr<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(mode))<EOL><DEDENT>return vol * mask<EOL>

Use the given magic function name `func` to threshold with value `thr`
    the data of `img` and return a new nibabel.Nifti1Image.
    Parameters
    ----------
    img: img-like

    thr: float or int
        The threshold value.

    mode: str
        Choices: '+' for positive threshold,
                 '+-' for positive and negative threshold and
                 '-' for negative threshold.
    Returns
    -------
    thr_img: nibabel.Nifti1Image
        Thresholded image


return read_img(img).get_data() > <NUM_LIT:0><EOL>

Return an image with the positive voxels of the data of `img`.


bool_img = read_img(img).get_data() > <NUM_LIT:0><EOL>return bool_img.astype(int)<EOL>


bool_img = read_img(img).get_data() < <NUM_LIT:0><EOL>return bool_img.astype(int)<EOL>

Return an image with the negative voxels of the data of `img`.


if is_img(div2):<EOL><INDENT>return img1.get_data()/div2.get_data()<EOL><DEDENT>elif isinstance(div2, (float, int)):<EOL><INDENT>return img1.get_data()/div2<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>'.format(type(img1),<EOL>img1,<EOL>type(div2),<EOL>div2))<EOL><DEDENT>

Pixelwise division or divide by a number


from .mask import apply_mask<EOL>vol, _ = apply_mask(img, mask)<EOL>return vector_to_volume(vol, read_img(mask).get_data().astype(bool))<EOL>

Return the image with the given `mask` applied.


bool_img = np.abs(read_img(img).get_data())<EOL>return bool_img.astype(int)<EOL>

Return an image with the binarised version of the data of `img`.


vol = read_img(icc).get_data()<EOL>v2 = vol[vol != <NUM_LIT:0>]<EOL>if center_image:<EOL><INDENT>v2 = detrend(v2, axis=<NUM_LIT:0>)<EOL><DEDENT>vstd = np.linalg.norm(v2, ord=<NUM_LIT:2>) / np.sqrt(np.prod(v2.shape) - <NUM_LIT:1>)<EOL>eps = np.finfo(vstd.dtype).eps<EOL>vol /= (eps + vstd)<EOL>return vol<EOL>

Return a z-scored version of `icc`.
    This function is based on GIFT `icatb_convertImageToZScores` function.


@nifti_out<EOL>def spatial_map(icc, thr, mode='<STR_LIT:+>'):

return thr_img(icc_img_to_zscore(icc), thr=thr, mode=mode).get_data()<EOL>


def filter_icc(icc, mask=None, thr=<NUM_LIT:2>, zscore=True, mode="<STR_LIT:+>"):

if zscore:<EOL><INDENT>icc_filt = thr_img(icc_img_to_zscore(icc), thr=thr, mode=mode)<EOL><DEDENT>else:<EOL><INDENT>icc_filt = thr_img(icc, thr=thr, mode=mode)<EOL><DEDENT>if mask is not None:<EOL><INDENT>icc_filt = apply_mask(icc_filt, mask)<EOL><DEDENT>return icc_filt<EOL>

Threshold then mask an IC correlation map.
    Parameters
    ----------
    icc: img-like
        The 'raw' ICC map.

    mask: img-like
        If not None. Will apply this masks in the end of the process.

    thr: float
        The threshold value.

    zscore: bool
        If True will calculate the z-score of the ICC before thresholding.

    mode: str
        Choices: '+' for positive threshold,
                 '+-' for positive and negative threshold and
                 '-' for negative threshold.

    Returns
    -------
    icc_filt: nibabel.NiftiImage
        Thresholded and masked ICC.


return check_img(img_file)<EOL>

Return a representation of the image, either a nibabel.Nifti1Image or the same object as img_file.
    See boyle.nifti.check_img.

    Parameters
    ----------
    img: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    Returns
    -------
    img


warnings.warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>return get_img_info(img_file)<EOL>


warnings.warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>return get_img_data(nii_file)<EOL>


try:<EOL><INDENT>img = check_img(image)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(repr_imgs(image))) from exc<EOL><DEDENT>else:<EOL><INDENT>return img.get_header(), img.get_affine()<EOL><DEDENT>

Return the header and affine matrix from a Nifti file.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    Returns
    -------
    hdr, aff


try:<EOL><INDENT>img = check_img(image)<EOL>if copy:<EOL><INDENT>return get_data(img)<EOL><DEDENT>else:<EOL><INDENT>return img.get_data()<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(repr_imgs(image))) from exc<EOL><DEDENT>

Return the voxel matrix of the Nifti file.
    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    copy: bool
    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.

    Returns
    -------
    array_like


<EOL>import nipy<EOL>if not os.path.exists(nii_file):<EOL><INDENT>raise FileNotFound(nii_file)<EOL><DEDENT>try:<EOL><INDENT>return nipy.load_image(nii_file)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(repr_imgs(nii_file))) from exc<EOL><DEDENT>

Read a Nifti file and return as nipy.Image

    Parameters
    ----------
    param nii_file: str
        Nifti file path

    Returns
    -------
    nipy.Image


try:<EOL><INDENT>first_img = img_filelist[<NUM_LIT:0>]<EOL>vol       = get_img_data(first_img)<EOL><DEDENT>except IndexError as ie:<EOL><INDENT>raise Exception('<STR_LIT>'.format(repr_imgs(img_filelist[<NUM_LIT:0>]))) from ie<EOL><DEDENT>if not outdtype:<EOL><INDENT>outdtype = vol.dtype<EOL><DEDENT>outmat = np.zeros((len(img_filelist), np.prod(vol.shape)), dtype=outdtype)<EOL>try:<EOL><INDENT>for i, img_file in enumerate(img_filelist):<EOL><INDENT>vol = get_img_data(img_file)<EOL>outmat[i, :] = vol.flatten()<EOL><DEDENT><DEDENT>except Exception as exc:<EOL><INDENT>raise Exception('<STR_LIT>'.format(img_file)) from exc<EOL><DEDENT>return outmat, vol.shape<EOL>

From the list of absolute paths to nifti files, creates a Numpy array
with the data.

Parameters
----------
img_filelist:  list of str
    List of absolute file paths to nifti files. All nifti files must have
    the same shape.

outdtype: dtype
    Type of the elements of the array, if not set will obtain the dtype from
    the first nifti file.

Returns
-------
outmat: Numpy array with shape N x prod(vol.shape)
        containing the N files as flat vectors.

vol_shape: Tuple with shape of the volumes, for reshaping.


def _crop_img_to(image, slices, copy=True):

img    = check_img(image)<EOL>data   = img.get_data()<EOL>affine = img.get_affine()<EOL>cropped_data = data[slices]<EOL>if copy:<EOL><INDENT>cropped_data   = cropped_data.copy()<EOL><DEDENT>linear_part        = affine[:<NUM_LIT:3>, :<NUM_LIT:3>]<EOL>old_origin         = affine[:<NUM_LIT:3>,  <NUM_LIT:3>]<EOL>new_origin_voxel   = np.array([s.start for s in slices])<EOL>new_origin         = old_origin + linear_part.dot(new_origin_voxel)<EOL>new_affine         = np.eye(<NUM_LIT:4>)<EOL>new_affine[:<NUM_LIT:3>, :<NUM_LIT:3>] = linear_part<EOL>new_affine[:<NUM_LIT:3>,  <NUM_LIT:3>] = new_origin<EOL>new_img = nib.Nifti1Image(cropped_data, new_affine)<EOL>return new_img<EOL>

Crops image to a smaller size

    Crop img to size indicated by slices and modify the affine accordingly.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

        Image to be cropped.

    slices: list of slices
        Defines the range of the crop.
        E.g. [slice(20, 200), slice(40, 150), slice(0, 100)]
        defines a 3D cube

        If slices has less entries than image has dimensions,
        the slices will be applied to the first len(slices) dimensions.

    copy: boolean
        Specifies whether cropped data is to be copied or not.
        Default: True

    Returns
    -------
    cropped_img: img-like object
        Cropped version of the input image


def crop_img(image, rtol=<NUM_LIT>, copy=True):

img              = check_img(image)<EOL>data             = img.get_data()<EOL>infinity_norm    = max(-data.min(), data.max())<EOL>passes_threshold = np.logical_or(data < -rtol * infinity_norm,<EOL>data >  rtol * infinity_norm)<EOL>if data.ndim == <NUM_LIT:4>:<EOL><INDENT>passes_threshold = np.any(passes_threshold, axis=-<NUM_LIT:1>)<EOL><DEDENT>coords = np.array(np.where(passes_threshold))<EOL>start  = coords.min(axis=<NUM_LIT:1>)<EOL>end    = coords.max(axis=<NUM_LIT:1>) + <NUM_LIT:1><EOL>start = np.maximum(start - <NUM_LIT:1>, <NUM_LIT:0>)<EOL>end   = np.minimum(end   + <NUM_LIT:1>, data.shape[:<NUM_LIT:3>])<EOL>slices = [slice(s, e) for s, e in zip(start, end)]<EOL>return _crop_img_to(img, slices, copy=copy)<EOL>

Crops img as much as possible

    Will crop img, removing as many zero entries as possible
    without touching non-zero entries. Will leave one voxel of
    zero padding around the obtained non-zero area in order to
    avoid sampling issues later on.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

        Image to be cropped.

    rtol: float
        relative tolerance (with respect to maximal absolute
        value of the image), under which values are considered
        negligeable and thus croppable.

    copy: boolean
        Specifies whether cropped data is copied or not.

    Returns
    -------
    cropped_img: image
        Cropped version of the input image


def new_img_like(ref_niimg, data, affine=None, copy_header=False):

<EOL>if not (hasattr(ref_niimg, '<STR_LIT>')<EOL>and hasattr(ref_niimg,'<STR_LIT>')):<EOL><INDENT>if isinstance(ref_niimg, _basestring):<EOL><INDENT>ref_niimg = nib.load(ref_niimg)<EOL><DEDENT>elif operator.isSequenceType(ref_niimg):<EOL><INDENT>ref_niimg = nib.load(ref_niimg[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(('<STR_LIT>'<EOL>'<STR_LIT>') % ref_niimg )<EOL><DEDENT><DEDENT>if affine is None:<EOL><INDENT>affine = ref_niimg.get_affine()<EOL><DEDENT>if data.dtype == bool:<EOL><INDENT>default_dtype = np.int8<EOL>if (LooseVersion(nib.__version__) >= LooseVersion('<STR_LIT>') and<EOL>isinstance(ref_niimg, nib.freesurfer.mghformat.MGHImage)):<EOL><INDENT>default_dtype = np.uint8<EOL><DEDENT>data = as_ndarray(data, dtype=default_dtype)<EOL><DEDENT>header = None<EOL>if copy_header:<EOL><INDENT>header = copy.copy(ref_niimg.get_header())<EOL>header['<STR_LIT>'] = <NUM_LIT:0.><EOL>header['<STR_LIT>'] = <NUM_LIT:0.><EOL>header['<STR_LIT>'] = <NUM_LIT:0.><EOL>header['<STR_LIT>'] = np.max(data) if data.size > <NUM_LIT:0> else <NUM_LIT:0.><EOL>header['<STR_LIT>'] = np.min(data) if data.size > <NUM_LIT:0> else <NUM_LIT:0.><EOL><DEDENT>return ref_niimg.__class__(data, affine, header=header)<EOL>

Create a new image of the same class as the reference image

    Parameters
    ----------
    ref_niimg: image
        Reference image. The new image will be of the same type.

    data: numpy array
        Data to be stored in the image

    affine: 4x4 numpy array, optional
        Transformation matrix

    copy_header: boolean, optional
        Indicated if the header of the reference image should be used to
        create the new image

    Returns
    -------
    new_img: image
        A loaded image with the same type (and header) as the reference image.


if isinstance(image, string_types):<EOL><INDENT>if not op.exists(image):<EOL><INDENT>raise FileNotFound(image)<EOL><DEDENT>ext = get_extension(image).lower()<EOL>if not '<STR_LIT>' in ext:<EOL><INDENT>warnings.warn('<STR_LIT>'.format(image))<EOL><DEDENT>img, hdr = load_raw_data_with_mhd(image)<EOL>if make_it_3d:<EOL><INDENT>img = _make_it_3d(img)<EOL><DEDENT>return img<EOL><DEDENT>elif is_img(image):<EOL><INDENT>return image<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(type(image)))<EOL><DEDENT>

Check that image is a proper img. Turn filenames into objects.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a .mhd file. (if it is a .raw file, this won't work).
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to .mhd image and
        call load_raw_data_with_mhd on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    make_it_3d: boolean, optional
        If True, check if the image is a 3D image and raise an error if not.

    Returns
    -------
    result: nifti-like
       result can be nibabel.Nifti1Image or the input, as-is. It is guaranteed
       that the returned object has get_data() and get_affine() methods.


shape = img.shape<EOL>if len(shape) == <NUM_LIT:3>:<EOL><INDENT>return img<EOL><DEDENT>elif len(shape) == <NUM_LIT:4> and shape[<NUM_LIT:3>] == <NUM_LIT:1>:<EOL><INDENT>return img[:, :, :, <NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(shape))<EOL><DEDENT>

Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
    i.e., remove dimensions of size 1.

    Parameters
    ----------
    img: numpy.ndarray
        Image data array

    Returns
    -------
    3D numpy ndarray object


header = '<STR_LIT>'<EOL>for tag in MHD_TAGS:<EOL><INDENT>if tag in meta_dict.keys():<EOL><INDENT>header += '<STR_LIT>'.format(tag, meta_dict[tag])<EOL><DEDENT><DEDENT>with open(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(header)<EOL><DEDENT>

Write the content of the `meta_dict` into `filename`.

    Parameters
    ----------
    filename: str
        Path to the output file

    meta_dict: dict
        Dictionary with the fields of the metadata .mhd file


if data.ndim == <NUM_LIT:3>:<EOL><INDENT>data = data.reshape([data.shape[<NUM_LIT:0>], data.shape[<NUM_LIT:1>]*data.shape[<NUM_LIT:2>]])<EOL><DEDENT>a = array.array('<STR_LIT:f>')<EOL>for o in data:<EOL><INDENT>a.fromlist(list(o.flatten()))<EOL><DEDENT>with open(filename, '<STR_LIT:wb>') as rawf:<EOL><INDENT>a.tofile(rawf)<EOL><DEDENT>

Write the data into a raw format file. Big endian is always used.

    Parameters
    ----------
    filename: str
        Path to the output file

    data: numpy.ndarray
        n-dimensional image data array.


def write_mhd_file(filename, data, shape=None, meta_dict=None):

<EOL>ext = get_extension(filename)<EOL>fname = op.basename(filename)<EOL>if ext != '<STR_LIT>' or ext != '<STR_LIT>':<EOL><INDENT>mhd_filename = fname + '<STR_LIT>'<EOL>raw_filename = fname + '<STR_LIT>'<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>mhd_filename = fname<EOL>raw_filename = remove_ext(fname) + '<STR_LIT>'<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>mhd_filename = remove_ext(fname) + '<STR_LIT>'<EOL>raw_filename = fname<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(ext, filename))<EOL><DEDENT>if meta_dict is None:<EOL><INDENT>meta_dict = {}<EOL><DEDENT>if shape is None:<EOL><INDENT>shape = data.shape<EOL><DEDENT>meta_dict['<STR_LIT>']             = meta_dict.get('<STR_LIT>',             '<STR_LIT>')<EOL>meta_dict['<STR_LIT>']             = meta_dict.get('<STR_LIT>',             '<STR_LIT:True>' )<EOL>meta_dict['<STR_LIT>'] = meta_dict.get('<STR_LIT>', '<STR_LIT:False>')<EOL>meta_dict['<STR_LIT>']            = meta_dict.get('<STR_LIT>',            NUMPY_TO_MHD_TYPE[data.dtype.type])<EOL>meta_dict['<STR_LIT>']                  = meta_dict.get('<STR_LIT>',                  str(len(shape)))<EOL>meta_dict['<STR_LIT>']                = meta_dict.get('<STR_LIT>',                '<STR_LIT:U+0020>'.join([str(i) for i in shape]))<EOL>meta_dict['<STR_LIT>']        = meta_dict.get('<STR_LIT>',        raw_filename)<EOL>mhd_filename = op.join(op.dirname(filename), mhd_filename)<EOL>raw_filename = op.join(op.dirname(filename), raw_filename)<EOL>write_meta_header(mhd_filename, meta_dict)<EOL>dump_raw_data(raw_filename, data)<EOL>return mhd_filename, raw_filename<EOL>

Write the `data` and `meta_dict` in two files with names
    that use `filename` as a prefix.

    Parameters
    ----------
    filename: str
        Path to the output file.
        This is going to be used as a preffix.
        Two files will be created, one with a '.mhd' extension
        and another with '.raw'. If `filename` has any of these already
        they will be taken into account to build the filenames.

    data: numpy.ndarray
        n-dimensional image data array.

    shape: tuple
        Tuple describing the shape of `data`
        Default: data.shape

    meta_dict: dict
        Dictionary with the fields of the metadata .mhd file
        Default: {}

    Returns
    -------
    mhd_filename: str
        Path to the .mhd file

    raw_filename: str
        Path to the .raw file


<EOL>if not op.exists(src):<EOL><INDENT>raise IOError('<STR_LIT>'.format(src))<EOL><DEDENT>ext = get_extension(src)<EOL>if ext != '<STR_LIT>':<EOL><INDENT>msg = '<STR_LIT>'.format(src)<EOL>raise ValueError(msg)<EOL><DEDENT>meta_src = _read_meta_header(src)<EOL>src_raw = meta_src['<STR_LIT>']<EOL>if not op.isabs(src_raw):<EOL><INDENT>src_raw = op.join(op.dirname(src), src_raw)<EOL><DEDENT>if op.isdir(dst):<EOL><INDENT>shutil.copyfile(src, dst)<EOL>shutil.copyfile(src_raw, dst)<EOL>return dst<EOL><DEDENT>dst_raw = op.join(op.dirname(dst), remove_ext(op.basename(dst))) + '<STR_LIT>'<EOL>if get_extension(dst) != '<STR_LIT>':<EOL><INDENT>dst += '<STR_LIT>'<EOL><DEDENT>log.debug('<STR_LIT>'.format(src,     dst))<EOL>log.debug('<STR_LIT>'.format(src_raw, dst_raw))<EOL>shutil.copyfile(src, dst)<EOL>shutil.copyfile(src_raw, dst_raw)<EOL>if op.basename(dst) != op.basename(src):<EOL><INDENT>log.debug('<STR_LIT>'.format(dst, src_raw,<EOL>op.basename(dst_raw)))<EOL>meta_dst = _read_meta_header(dst)<EOL>meta_dst['<STR_LIT>'] = op.basename(dst_raw)<EOL>write_meta_header(dst, meta_dst)<EOL><DEDENT>return dst<EOL>

Copy .mhd and .raw files to dst.

    If dst is a folder, won't change the file, but if dst is another filepath,
    will modify the ElementDataFile field in the .mhd to point to the
    new renamed .raw file.

    Parameters
    ----------
    src: str
        Path to the .mhd file to be copied

    dst: str
        Path to the destination of the .mhd and .raw files.
        If a new file name is given, the extension will be ignored.

    Returns
    -------
    dst: str


fileIN = open(filename, '<STR_LIT:r>')<EOL>line   = fileIN.readline()<EOL>meta_dict = {}<EOL>tag_flag = [False]*len(MHD_TAGS)<EOL>while line:<EOL><INDENT>tags = str.split(line, '<STR_LIT:=>')<EOL>for i in range(len(MHD_TAGS)):<EOL><INDENT>tag = MHD_TAGS[i]<EOL>if (str.strip(tags[<NUM_LIT:0>]) == tag) and (not tag_flag[i]):<EOL><INDENT>meta_dict[tag] = str.strip(tags[<NUM_LIT:1>])<EOL>tag_flag[i] = True<EOL><DEDENT><DEDENT>line = fileIN.readline()<EOL><DEDENT>fileIN.close()<EOL>return meta_dict<EOL>

Return a dictionary of meta data from meta header file.

    Parameters
    ----------
    filename: str
        Path to a .mhd file

    Returns
    -------
    meta_dict: dict
        A dictionary with the .mhd header content.


meta_dict = _read_meta_header(filename)<EOL>dim       = int(meta_dict['<STR_LIT>'])<EOL>assert (meta_dict['<STR_LIT>'] in MHD_TO_NUMPY_TYPE)<EOL>arr = [int(i) for i in meta_dict['<STR_LIT>'].split()]<EOL>volume = reduce(lambda x, y: x*y, arr[<NUM_LIT:0>:dim-<NUM_LIT:1>], <NUM_LIT:1>)<EOL>pwd       = op.dirname(filename)<EOL>raw_file  = meta_dict['<STR_LIT>']<EOL>data_file = op.join(pwd, raw_file)<EOL>ndtype    = MHD_TO_NUMPY_TYPE[meta_dict['<STR_LIT>']]<EOL>arrtype   = NDARRAY_TO_ARRAY_TYPE[ndtype]<EOL>with open(data_file, '<STR_LIT:rb>') as fid:<EOL><INDENT>binvalues = array.array(arrtype)<EOL>binvalues.fromfile(fid, volume*arr[dim-<NUM_LIT:1>])<EOL><DEDENT>data = np.array  (binvalues, ndtype)<EOL>data = np.reshape(data, (arr[dim-<NUM_LIT:1>], volume))<EOL>if dim >= <NUM_LIT:3>:<EOL><INDENT>dimensions = [int(i) for i in meta_dict['<STR_LIT>'].split()]<EOL>data       = data.reshape(dimensions)<EOL><DEDENT>return data, meta_dict<EOL>

Return a dictionary of meta data from meta header file.

    Parameters
    ----------
    filename: str
        Path to a .mhd file

    Returns
    -------
    data: numpy.ndarray
        n-dimensional image data array.

    meta_dict: dict
        A dictionary with the .mhd header content.


def remove_4th_element_from_hdr_string(hdr, fieldname):<EOL><INDENT>if fieldname in hdr:<EOL><INDENT>hdr[fieldname] = '<STR_LIT:U+0020>'.join(hdr[fieldname].split()[:<NUM_LIT:3>])<EOL><DEDENT><DEDENT>vol, hdr = load_raw_data_with_mhd(filename)<EOL>if vol.ndim != <NUM_LIT:4>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(op.join(op.dirname(filename),<EOL>hdr['<STR_LIT>'])))<EOL><DEDENT>if not <NUM_LIT:0> <= vol_idx < vol.shape[<NUM_LIT:3>]:<EOL><INDENT>raise IndexError('<STR_LIT>'.format(filename,<EOL>vol.shape[<NUM_LIT:3>], vol_idx))<EOL><DEDENT>new_vol = vol[:, :, :, vol_idx].copy()<EOL>hdr['<STR_LIT>'] = <NUM_LIT:3><EOL>remove_4th_element_from_hdr_string(hdr, '<STR_LIT>')<EOL>remove_4th_element_from_hdr_string(hdr, '<STR_LIT>')<EOL>return new_vol, hdr<EOL>

Return a 3D volume from a 4D nifti image file

    Parameters
    ----------
    filename: str
        Path to the 4D .mhd file

    vol_idx: int
        Index of the 3D volume to be extracted from the 4D volume.

    Returns
    -------
    vol, hdr
        The data array and the new 3D image header.


return tabulate(self, tablefmt=tablefmt)<EOL>

:param tablefmt: string
 Supported table formats are:
"plain"
"simple"
"grid"
"pipe"
"orgtbl"
"rst"
"mediawiki"
"latex"

:return: tabulate
Tabulated content


return tabulate(list(self.items()), tablefmt=tablefmt)<EOL>


return self.img.affine<EOL>


return self.img.header<EOL>


return self.get_header().get_zooms()<EOL>

Return the voxel size in the header of the file.


if safe_copy:<EOL><INDENT>data = get_data(self.img)<EOL><DEDENT>else:<EOL><INDENT>data = self.img.get_data(caching=self._caching)<EOL><DEDENT>return data<EOL>

Get the data in the image.
         If save_copy is True, will perform a deep copy of the data and return it.

        Parameters
        ----------
        smoothed: (optional) bool
            If True and self._smooth_fwhm > 0 will smooth the data before masking.

        masked: (optional) bool
            If True and self.has_mask will return the masked data, the plain data otherwise.

        safe_copy: (optional) bool

        Returns
        -------
        np.ndarray


save_niigz(outpath, self.img)<EOL>

Save this object instance in outpath.

        Parameters
        ----------
        outpath: str
            Output file path


if fwhm != self._smooth_fwhm:<EOL><INDENT>self._is_data_smooth = False<EOL><DEDENT>self._smooth_fwhm = fwhm<EOL>

Set a smoothing Gaussian kernel given its FWHM in mm.


def get_data(self, smoothed=True, masked=True, safe_copy=False):

if not safe_copy and smoothed == self._is_data_smooth and masked == self._is_data_masked:<EOL><INDENT>if self.has_data_loaded() and self._caching == '<STR_LIT>':<EOL><INDENT>return self.get_data()<EOL><DEDENT><DEDENT>if safe_copy:<EOL><INDENT>data = get_data(self.img)<EOL><DEDENT>else:<EOL><INDENT>data = self.img.get_data(caching=self._caching)<EOL><DEDENT>is_smoothed = False<EOL>if smoothed and self._smooth_fwhm > <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>data = _smooth_data_array(data, self.get_affine(), self._smooth_fwhm, copy=False)<EOL><DEDENT>except ValueError as ve:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(self.img, self._smooth_fwhm)) from ve<EOL><DEDENT>else:<EOL><INDENT>is_smoothed = True<EOL><DEDENT><DEDENT>is_data_masked = False<EOL>if masked and self.has_mask():<EOL><INDENT>try:<EOL><INDENT>data = self.unmask(self._mask_data(data)[<NUM_LIT:0>])<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>is_data_masked = True<EOL><DEDENT><DEDENT>if not safe_copy:<EOL><INDENT>self._is_data_masked = is_data_masked<EOL>self._is_data_smooth = is_smoothed<EOL><DEDENT>return data<EOL>


self.set_mask(mask_img)<EOL>return self.get_data(masked=True, smoothed=True, safe_copy=True)<EOL>

First set_mask and the get_masked_data.

        Parameters
        ----------
        mask_img:  nifti-like image, NeuroImage or str
            3D mask array: True where a voxel should be used.
            Can either be:
            - a file path to a Nifti image
            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
            If niimg is a string, consider it as a path to Nifti image and
            call nibabel.load on it. If it is an object, check if get_data()
            and get_affine() methods are present, raise TypeError otherwise.

        Returns
        -------
        The masked data deepcopied


mask = load_mask(mask_img, allow_empty=True)<EOL>check_img_compatibility(self.img, mask, only_check_3d=True) <EOL>self.mask = mask<EOL>

Sets a mask img to this. So every operation to self, this mask will be taken into account.

        Parameters
        ----------
        mask_img: nifti-like image, NeuroImage or str
            3D mask array: True where a voxel should be used.
            Can either be:
            - a file path to a Nifti image
            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
            If niimg is a string, consider it as a path to Nifti image and
            call nibabel.load on it. If it is an object, check if get_data()
            and get_affine() methods are present, raise TypeError otherwise.

        Note
        ----
        self.img and mask_file must have the same shape.

        Raises
        ------
        FileNotFound, NiftiFilesNotCompatible


self._check_for_mask()<EOL>msk_data = self.mask.get_data()<EOL>if self.ndim == <NUM_LIT:3>:<EOL><INDENT>return data[msk_data], np.where(msk_data)<EOL><DEDENT>elif self.ndim == <NUM_LIT:4>:<EOL><INDENT>return _apply_mask_to_4d_data(data, self.mask)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(self, self.ndim, self.mask))<EOL><DEDENT>

Return the data masked with self.mask

        Parameters
        ----------
        data: np.ndarray

        Returns
        -------
        masked np.ndarray

        Raises
        ------
        ValueError if the data and mask dimensions are not compatible.
        Other exceptions related to numpy computations.


if smooth_fwhm <= <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>old_smooth_fwhm   = self._smooth_fwhm<EOL>self._smooth_fwhm = smooth_fwhm<EOL>try:<EOL><INDENT>data = self.get_data(smoothed=True, masked=True, safe_copy=True)<EOL><DEDENT>except ValueError as ve:<EOL><INDENT>self._smooth_fwhm = old_smooth_fwhm<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>self._smooth_fwhm = smooth_fwhm<EOL>return data<EOL><DEDENT>

Set self._smooth_fwhm and then smooths the data.
        See boyle.nifti.smooth.smooth_imgs.

        Returns
        -------
        the smoothed data deepcopied.


self._check_for_mask()<EOL>return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indices()],self.get_mask_indices(), self.mask.shape<EOL>

Return a vector of the masked data.

        Returns
        -------
        np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape


self._check_for_mask()<EOL>if <NUM_LIT:1> > arr.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'.format(arr.ndim,<EOL>len(self.mask.shape)))<EOL><DEDENT>if arr.ndim == <NUM_LIT:2>:<EOL><INDENT>return matrix_to_4dvolume(arr, self.mask.get_data())<EOL><DEDENT>elif arr.ndim == <NUM_LIT:1>:<EOL><INDENT>return vector_to_volume(arr, self.mask.get_data())<EOL><DEDENT>

Use self.mask to reshape arr and self.img to get an affine and header to create
        a new self.img using the data in arr.
        If self.has_mask() is False, will return the same arr.


if not self.has_mask() and not self.is_smoothed():<EOL><INDENT>save_niigz(outpath, self.img)<EOL><DEDENT>else:<EOL><INDENT>save_niigz(outpath, self.get_data(masked=True, smoothed=True),<EOL>self.get_header(), self.get_affine())<EOL><DEDENT>


<EOL>if not op.exists(filepath):<EOL><INDENT>raise IOError('<STR_LIT>'.format(filepath))<EOL><DEDENT>def open_nifti_file(filepath):<EOL><INDENT>return NiftiImage(filepath)<EOL><DEDENT>def open_mhd_file(filepath):<EOL><INDENT>return MedicalImage(filepath)<EOL>vol_data, hdr_data = load_raw_data_with_mhd(filepath)<EOL>return vol_data, hdr_data<EOL><DEDENT>def open_mha_file(filepath):<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>def _load_file(filepath, loader):<EOL><INDENT>return loader(filepath)<EOL><DEDENT>filext_loader = {<EOL>'<STR_LIT>': open_nifti_file,<EOL>'<STR_LIT>': open_mhd_file,<EOL>'<STR_LIT>': open_mha_file,<EOL>}<EOL>ext = get_extension(filepath)<EOL>loader = None<EOL>for e in filext_loader:<EOL><INDENT>if ext in e:<EOL><INDENT>loader = filext_loader[e]<EOL><DEDENT><DEDENT>if loader is None:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(filepath))<EOL><DEDENT>return _load_file(filepath, loader)<EOL>

Open a volumetric file using the tools following the file extension.

    Parameters
    ----------
    filepath: str
        Path to a volume file

    Returns
    -------
    volume_data: np.ndarray
        Volume data

    pixdim: 1xN np.ndarray
        Vector with the description of the voxels physical size (usually in mm) for each volume dimension.

    Raises
    ------
    IOError
        In case the file is not found.