<commit_before>import math

import numpy as np
from scipy.special import erf
from scipy.ndimage import correlate1d
from scipy.optimize import fmin_powell, fmin_cg

import scipy.ndimage._register as reg

import time
import glob

# Issue warning regarding heavy development status of this module
import warnings
_msg = "The registration code is under heavy development and therefore the \
public API will change in the future.  The NIPY group is actively working on \
this code, and has every intention of generalizing this for the Scipy \
community.  Use this module minimally, if at all, until it this warning is \
removed."
warnings.warn(_msg, UserWarning)

# TODO:  Add docstrings for public functions in extension code.
# Add docstrings to extension code.
#from numpy.lib import add_newdoc
#add_newdoc('scipy.ndimage._register', 'register_histogram',
#    """A joint histogram used for registration module.
#    """)


#
#  ---- co-registration and IO  ---- 
#

def resize_image(imageS, imageS_mat, imageR_mat):
    """
    zoom_image = resize_image(imageS, imageS_mat, imageR_mat)

    Fractional resample source_image to reference_image size. The
    resample is implemented with 3D cubic spline. The source
    imageS_mat is the 4x4 voxel-to-physical conversion matrix.
    
    Parameters 
    ----------

    imageS: {ndarray} 
        imageS is the source image to be resized.

    imageS_mat : {ndarray} 
        the 4x4 transform of the source image that maps voxel to physical.

    imageR_mat : {ndarray}
        the 4x4 transform of the destination image that maps voxel to physical.

    Returns 
    -------
    zoom_image : {ndarray}

    Examples
    --------

    >>> import _registration as reg
    >>> measures, image_anat, image_anat_mat, image_fmri_mat, fmri_series = reg.demo_MRI_coregistration()

    >>> resampled_fmri = reg.resize_image(fmri_series[10], image_fmri_mat, image_anat_mat)

    image 10 in the fmri_series is resampled from image_fmri_mat to image_anat coordinates

    """

    # get the zoom
    Z = imageS_mat.diagonal() / imageR_mat.diagonal()

    # new volume dimensions (rounded). D, imageS and Z are 3D and this is a vector element product
    D = (imageS.shape * Z + 0.5).astype(np.int16)

    # for the test data, set the xyz voxel sizes for fMRI volume. M is a 4x4 matrix.
    M = np.diag(imageS_mat.diagonal() / Z)    

    image = np.zeros((D[2],D[1],D[0]),np.uint8)
    
    mode  = 2
    scale = 0
    reg.register_volume_resample(imageS, image, Z, scale, mode)

    return image, M

def remap_image(image, parm_vector, resample='linear'):
    """
    remaped_image = remap_image(image, parm_vector, resample='linear')

    rotates and translates image using the 3 angles and 3 translations in the 6-dim
    parm_vector. The mapping is stored in the 4x4 M_inverse matrix from the get_inverse_mapping
    method.

    Parameters 
    ----------
    image : {ndarray} 
        image is the source image to be remapped. 

    parm_vector : {ndarray}
        parm_vector is the 6-dimensional vector (3 angles, 3 translations)
        generated from the rigid body registration.

    resample : {'linear', 'cubic'}, optional


    Returns 
    -------
    remaped_image : {ndarray}

    Examples
    --------
        image = fmri_series[i]
        x[0:6] = measures[i]['align_rotate'][0:6]
        # overwrite the fMRI volume with the aligned volume
        fmri_series[i] = remap_image(image, x, resample='cubic')

    """

    #
    # remap imageG to coordinates of imageF (creates imageG')
    # use the 6 dim parm_vector (3 angles, 3 translations) to remap
    #
    M_inverse = get_inverse_mappings(parm_vector)

    # allocate the zero image
    remaped_image = np.zeros(image.shape, dtype=np.uint8)

    step = np.array([1, 1, 1], dtype=np.int32)

    if resample == 'linear':
        # trilinear interpolation mapping.
        reg.register_linear_resample(image, remaped_image, M_inverse, step)
    elif resample == 'cubic':
        # tricubic convolve interpolation mapping. 
        reg.register_cubic_resample(image, remaped_image, M_inverse, step)

    return remaped_image

def get_inverse_mappings(parm_vector):
    """
    M_inverse = get_inverse_mappings(parm_vector)<commit_msg>replace parameter vector with inverse affine matrix as input to remap_image method<commit_after>#
# written by <NAME>
# rigid body 3D registration
#


import math
import numpy as np
from scipy.special import erf
from scipy.ndimage import correlate1d
from scipy.optimize import fmin_powell, fmin_cg

import scipy.ndimage._register as reg

import time
import glob

# Issue warning regarding heavy development status of this module
import warnings
_msg = "The registration code is under heavy development and therefore the \
public API will change in the future.  The NIPY group is actively working on \
this code, and has every intention of generalizing this for the Scipy \
community.  Use this module minimally, if at all, until it this warning is \
removed."
warnings.warn(_msg, UserWarning)

# TODO:  Add docstrings for public functions in extension code.
# Add docstrings to extension code.
#from numpy.lib import add_newdoc
#add_newdoc('scipy.ndimage._register', 'register_histogram',
#    """A joint histogram used for registration module.
#    """)


#
#  ---- co-registration and IO  ---- 
#

def resize_image(imageS, imageS_mat, imageR_mat):
    """
    zoom_image = resize_image(imageS, imageS_mat, imageR_mat)

    Fractional resample source_image to reference_image size. The
    resample is implemented with 3D cubic spline. The source
    imageS_mat is the 4x4 voxel-to-physical conversion matrix.
    
    Parameters 
    ----------

    imageS: {ndarray} 
        imageS is the source image to be resized.

    imageS_mat : {ndarray} 
        the 4x4 transform of the source image that maps voxel to physical.

    imageR_mat : {ndarray}
        the 4x4 transform of the destination image that maps voxel to physical.

    Returns 
    -------
    zoom_image : {ndarray}

    Examples
    --------

    >>> import _registration as reg
    >>> measures, image_anat, image_anat_mat, image_fmri_mat, fmri_series = reg.demo_MRI_coregistration()

    >>> resampled_fmri = reg.resize_image(fmri_series[10], image_fmri_mat, image_anat_mat)

    image 10 in the fmri_series is resampled from image_fmri_mat to image_anat coordinates

    """

    # get the zoom
    Z = imageS_mat.diagonal() / imageR_mat.diagonal()

    # new volume dimensions (rounded). D, imageS and Z are 3D and this is a vector element product
    D = (imageS.shape * Z + 0.5).astype(np.int16)

    # for the test data, set the xyz voxel sizes for fMRI volume. M is a 4x4 matrix.
    M = np.diag(imageS_mat.diagonal() / Z)    

    image = np.zeros((D[2],D[1],D[0]),np.uint8)
    
    mode  = 2
    scale = 0
    reg.register_volume_resample(imageS, image, Z, scale, mode)

    return image, M

def remap_image(image, M_inverse, resample='linear'):
    """
    remaped_image = remap_image(image, parm_vector, resample='linear')

    rotates and translates image using the 3 angles and 3 translations in the 6-dim
    parm_vector. The mapping is stored in the 4x4 M_inverse matrix from the get_inverse_mapping
    method.

    Parameters 
    ----------
    image : {ndarray} 
        image is the source image to be remapped. 

    M_inverse : {ndarray}
        M_inverse is the 4x4 inverse affine matrix 

    resample : {'linear', 'cubic'}, optional


    Returns 
    -------
    remaped_image : {ndarray}

    Examples
    --------
        image = fmri_series[i]
        x[0:6] = measures[i]['align_rotate'][0:6]
	M = get_inverse_mappings(x)
        # overwrite the fMRI volume with the aligned volume
        fmri_series[i] = remap_image(image, M, resample='cubic')

    """

    # allocate the zero image
    remaped_image = np.zeros(image.shape, dtype=np.uint8)

    step = np.array([1, 1, 1], dtype=np.int32)

    if resample == 'linear':
        # trilinear interpolation mapping.
        reg.register_linear_resample(image, remaped_image, M_inverse, step)
    elif resample == 'cubic':
        # tricubic convolve interpolation mapping. 
        reg.register_cubic_resample(image, remaped_image, M_inverse, step)

    return remaped_image


def get_inverse_mappings(parm_vector):
    """
    M_inverse = get_inverse_mappings(parm_vector)
{'fraction_non_alphanumeric': 0.09067017082785808, 'fraction_numerical': 0.010631943614860829, 'mean_word_length': 3.0739659367396595, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 22, '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': '3197467', 'n_tokens_mistral': 2782, 'n_tokens_neox': 2558, 'n_words': 851}