<commit_before>"""
Utilities to resample a Nifti Image
"""
# Author: <NAME>, <NAME>
# License: simplified BSD


import numpy as np
from scipy import ndimage
from nibabel import Nifti1Image

from .utils import check_niimg


def to_matrix_vector(transform):
    """Split a transform into it's matrix and vector components.

    The tranformation must be represented in homogeneous coordinates
    and is split into it's rotation matrix and translation vector
    components.

    Parameters
    ----------
    transform : ndarray
        Transform matrix in homogeneous coordinates.  Example, a 4x4
        transform representing rotations and translations in 3
        dimensions.

    Returns
    -------
    matrix, vector : ndarray
        The matrix and vector components of the transform matrix.  For
        an NxN transform, matrix will be N-1xN-1 and vector will be
        1xN-1.

    See Also
    --------
    from_matrix_vector

    """

    ndimin = transform.shape[0] - 1
    ndimout = transform.shape[1] - 1
    matrix = transform[0:ndimin, 0:ndimout]
    vector = transform[0:ndimin, ndimout]
    return matrix, vector


def from_matrix_vector(matrix, vector):
    """Combine a matrix and vector into a homogeneous transform.

    Combine a rotation matrix and translation vector into a transform
    in homogeneous coordinates.

    Parameters
    ----------
    matrix : ndarray
        An NxN array representing the rotation matrix.
    vector : ndarray
        A 1xN array representing the translation.

    Returns
    -------
    xform : ndarray
        An N+1xN+1 transform matrix.

    See Also
    --------
    to_matrix_vector

    """

    nin, nout = matrix.shape
    t = np.zeros((nin + 1, nout + 1), matrix.dtype)
    t[0:nin, 0:nout] = matrix
    t[nin,   nout] = 1.
    t[0:nin, nout] = vector
    return t


def get_bounds(shape, affine):
    """ Return the world-space bounds occupied by an array given an affine.
    """
    adim, bdim, cdim = shape
    adim -= 1
    bdim -= 1
    cdim -= 1
    # form a collection of vectors for each 8 corners of the box
    box = np.array([[0.,   0,    0,    1],
                    [adim, 0,    0,    1],
                    [0,    bdim, 0,    1],
                    [0,    0,    cdim, 1],
                    [adim, bdim, 0,    1],
                    [adim, 0,    cdim, 1],
                    [0,    bdim, cdim, 1],
                    [adim, bdim, cdim, 1]]).T
    box = np.dot(affine, box)[:3]
    return zip(box.min(axis=-1), box.max(axis=-1))


def resample_img(niimg, target_affine=None, target_shape=None,
                 interpolation='continuous', copy=True):
    """ Resample a Nifti Image

    Parameters
    ----------
    niimg: nisl nifti image
        Path to a nifti file or nifti-like object

    target_affine: numpy matrix, optional
        If specified, the image is resampled corresponding to this new affine.
        target_affine can be a 3x3 or a 4x4 matrix

    target_shape: 3-tuple, optional
        If specified, the image will be resized to match this new shape.

    interpolation: string, optional
        Can be continuous' (default) or 'nearest'. Indicate the resample method

    copy: boolean, optional
        If true, copy source data to avoid side-effects.
    """

    niimg = check_niimg(niimg)
    data = niimg.get_data()
    affine = niimg.get_affine()

    if copy:
        import copy
        data = copy.copy(data)
        affine = copy.copy(affine)
    if target_affine is None and target_shape is None:
        return niimg
    if target_affine is None and target_shape is not None:
        raise ValueError("If target_shape is specified, target_affine should"
                         " be specified too.")
    if target_affine is None:
        target_affine = np.eye(4)
    if target_shape is None:
        target_shape = data.shape[:3]
    target_shape = list(target_shape)
    if target_affine.shape[0] == 3:
        # We have a 3D affine, we need to find out the offset and
        # shape to keep the same bounding box in the new space
        affine4d = np.eye(4)<commit_msg>ENH: avoid useless resampling<commit_after>"""
Utilities to resample a Nifti Image
"""
# Author: <NAME>, <NAME>
# License: simplified BSD


import numpy as np
from scipy import ndimage
from nibabel import Nifti1Image

from .utils import check_niimg


def to_matrix_vector(transform):
    """Split a transform into it's matrix and vector components.

    The tranformation must be represented in homogeneous coordinates
    and is split into it's rotation matrix and translation vector
    components.

    Parameters
    ----------
    transform : ndarray
        Transform matrix in homogeneous coordinates.  Example, a 4x4
        transform representing rotations and translations in 3
        dimensions.

    Returns
    -------
    matrix, vector : ndarray
        The matrix and vector components of the transform matrix.  For
        an NxN transform, matrix will be N-1xN-1 and vector will be
        1xN-1.

    See Also
    --------
    from_matrix_vector

    """

    ndimin = transform.shape[0] - 1
    ndimout = transform.shape[1] - 1
    matrix = transform[0:ndimin, 0:ndimout]
    vector = transform[0:ndimin, ndimout]
    return matrix, vector


def from_matrix_vector(matrix, vector):
    """Combine a matrix and vector into a homogeneous transform.

    Combine a rotation matrix and translation vector into a transform
    in homogeneous coordinates.

    Parameters
    ----------
    matrix : ndarray
        An NxN array representing the rotation matrix.
    vector : ndarray
        A 1xN array representing the translation.

    Returns
    -------
    xform : ndarray
        An N+1xN+1 transform matrix.

    See Also
    --------
    to_matrix_vector

    """

    nin, nout = matrix.shape
    t = np.zeros((nin + 1, nout + 1), matrix.dtype)
    t[0:nin, 0:nout] = matrix
    t[nin,   nout] = 1.
    t[0:nin, nout] = vector
    return t


def get_bounds(shape, affine):
    """ Return the world-space bounds occupied by an array given an affine.
    """
    adim, bdim, cdim = shape
    adim -= 1
    bdim -= 1
    cdim -= 1
    # form a collection of vectors for each 8 corners of the box
    box = np.array([[0.,   0,    0,    1],
                    [adim, 0,    0,    1],
                    [0,    bdim, 0,    1],
                    [0,    0,    cdim, 1],
                    [adim, bdim, 0,    1],
                    [adim, 0,    cdim, 1],
                    [0,    bdim, cdim, 1],
                    [adim, bdim, cdim, 1]]).T
    box = np.dot(affine, box)[:3]
    return zip(box.min(axis=-1), box.max(axis=-1))


def resample_img(niimg, target_affine=None, target_shape=None,
                 interpolation='continuous', copy=True):
    """ Resample a Nifti Image

    Parameters
    ----------
    niimg: nisl nifti image
        Path to a nifti file or nifti-like object

    target_affine: numpy matrix, optional
        If specified, the image is resampled corresponding to this new affine.
        target_affine can be a 3x3 or a 4x4 matrix

    target_shape: 3-tuple, optional
        If specified, the image will be resized to match this new shape.

    interpolation: string, optional
        Can be continuous' (default) or 'nearest'. Indicate the resample method

    copy: boolean, optional
        If true, copy source data to avoid side-effects.
    """

    niimg = check_niimg(niimg)
    data = niimg.get_data()
    affine = niimg.get_affine()

    if copy:
        import copy
        data = copy.copy(data)
        affine = copy.copy(affine)
    if target_affine is None and target_shape is None:
        return niimg
    if (np.all(np.array(target_shape) == data.shape) and
                    np.all(target_affine == affine)):
        return niimg
    if target_affine is None and target_shape is not None:
        raise ValueError("If target_shape is specified, target_affine should"
                         " be specified too.")
    if target_affine is None:
        target_affine = np.eye(4)
    if target_shape is None:
        target_shape = data.shape[:3]
    target_shape = list(target_shape)
    if target_affine.shape[0] == 3:
        # We have a 3D affine, we need to find out the offset and
        # shape to keep the same bounding box in the new space
        affine4d = np.eye(4)
{'fraction_non_alphanumeric': 0.09167065581617999, 'fraction_numerical': 0.01507898516036381, 'mean_word_length': 2.0837638376383762, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3697271', 'n_tokens_mistral': 2614, 'n_tokens_neox': 2466, 'n_words': 894}