<commit_before>from __future__ import division, print_function, absolute_import
import copy
import numpy as np
from scipy.ndimage import binary_opening, label
from scipy.ndimage.filters import median_filter
from scipy.stats import threshold

def multi_median(input, median_radius, numpass):
    """
    Applies multiple times scikit-image's median filter on input data.

    Parameters
    ----------
    input : ndarray
        The input volume to apply filter on.
    median_radius : int
        Radius (in voxels) of the applied median filter 
    numpass: int
        Number of pass of the median filter
    Returns
    -------
    input : ndarray
        Filtered input volume.
    """
    outvol = np.zeros_like(input, dtype=input.dtype)
    
    # Array representing the size of the median window in each dimension.
    medarr = np.ones_like(input.shape) * ((median_radius * 2) + 1)
    
    # Multi pass
    for i in range(0, numpass):
        median_filter(input, medarr, output=input)

    return input


def otsu(image, nbins=256):
    """
    Return threshold value based on Otsu's method.
    Copied from scikit-image to remove dependency.

    Parameters
    ----------
    image : array
        Input image.
    nbins : int
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.

    Returns
    -------
    threshold : float
        Threshold value.
    """
    hist, bin_centers = np.histogram(image, nbins)
    hist = hist.astype(np.float)

    # class probabilities for all possible thresholds
    weight1 = np.cumsum(hist)
    weight2 = np.cumsum(hist[::-1])[::-1]

    # class means for all possible thresholds
    mean1 = np.cumsum(hist * bin_centers[1:]) / weight1
    mean2 = (np.cumsum((hist * bin_centers[1:])[::-1]) / weight2[::-1])[::-1]

    # Clip ends to align class 1 and class 2 variables:
    # The last value of `weight1`/`mean1` should pair with zero values in
    # `weight2`/`mean2`, which do not exist.
    variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:])**2

    idx = np.argmax(variance12)
    threshold = bin_centers[:-1][idx]
    return threshold


def applymask(vol, mask):
    """
    Recursively applies N dimensionnal mask to a M dimensionnal volume
    for N <= M.

    Parameters
    ----------
    vol : ndarray
        Volume to apply mask on.
    mask : ndarray
        Binary mask.
    """
    mask = mask.reshape(mask.shape + (vol.ndim - mask.ndim) * (1,))
    return vol * mask

def binary_threshold(vol, thresh):
    """
    Simple binary thresholding.

    Parameters
    ----------
    vol : ndarray
        Volume to apply threshold on.
    thresh : float
        Thresholding value.

    Returns
    -------
        Binary ndarray.
    """
    return np.where(vol > thresh, True, False)

def bounding_box(vol):
    """
    Compute the bounding box of nonzero intensity voxels in the volume.

    Parameters
    ----------
        vol : ndarray
            Volume to compute bounding box on.

    Returns
    -------
    npmins : array
        Array containg minimum index of each dimension
    npmaxs : array
        Array containg maximum index of each dimension
    """
    mask = vol != 0
    mins = np.zeros(mask.ndim)
    maxs = mins.copy()
    for i in range(mask.ndim):
        flat = mask.any(i)
        mins[i] = flat.argmax()
        maxs[i] = mask.shape[i] - flat[::-1].argmax()

    return mins, maxs

def crop(vol, mins, maxs):
    """
    Crops the input volume.

    Parameters
    ----------
    vol : 3D ndarray
        Volume to crop.
    mins : array
        Array containg minimum index of each dimension.
    maxs : array
        Array containg maximum index of each dimension.

    Returns
    -------
        vol : 3D ndarray
            The cropped volume.
    """
    return vol[mins[0]:maxs[0]+1, mins[1]:maxs[1]+1, mins[2]:maxs[2]+1]

def medotsu(input_volume, median_radius=4, numpass=4, autocrop=False):
    """
    Simple brain extraction tool method for b0 images from DWI data. It uses a
    median filter smoothing of the input_volume and an automatic histogram Otsu
    thresholding technique, hence the name medotsu.
<commit_msg>Crop is now generalised for n dimensions.<commit_after>from __future__ import division, print_function, absolute_import
import copy
import numpy as np
from scipy.ndimage import binary_opening, label
from scipy.ndimage.filters import median_filter
from scipy.stats import threshold

def multi_median(input, median_radius, numpass):
    """
    Applies multiple times scikit-image's median filter on input data.

    Parameters
    ----------
    input : ndarray
        The input volume to apply filter on.
    median_radius : int
        Radius (in voxels) of the applied median filter 
    numpass: int
        Number of pass of the median filter
    Returns
    -------
    input : ndarray
        Filtered input volume.
    """
    outvol = np.zeros_like(input, dtype=input.dtype)
    
    # Array representing the size of the median window in each dimension.
    medarr = np.ones_like(input.shape) * ((median_radius * 2) + 1)
    
    # Multi pass
    for i in range(0, numpass):
        median_filter(input, medarr, output=input)

    return input


def otsu(image, nbins=256):
    """
    Return threshold value based on Otsu's method.
    Copied from scikit-image to remove dependency.

    Parameters
    ----------
    image : array
        Input image.
    nbins : int
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.

    Returns
    -------
    threshold : float
        Threshold value.
    """
    hist, bin_centers = np.histogram(image, nbins)
    hist = hist.astype(np.float)

    # class probabilities for all possible thresholds
    weight1 = np.cumsum(hist)
    weight2 = np.cumsum(hist[::-1])[::-1]

    # class means for all possible thresholds
    mean1 = np.cumsum(hist * bin_centers[1:]) / weight1
    mean2 = (np.cumsum((hist * bin_centers[1:])[::-1]) / weight2[::-1])[::-1]

    # Clip ends to align class 1 and class 2 variables:
    # The last value of `weight1`/`mean1` should pair with zero values in
    # `weight2`/`mean2`, which do not exist.
    variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:])**2

    idx = np.argmax(variance12)
    threshold = bin_centers[:-1][idx]
    return threshold


def applymask(vol, mask):
    """
    Recursively applies N dimensionnal mask to a M dimensionnal volume
    for N <= M.

    Parameters
    ----------
    vol : ndarray
        Volume to apply mask on.
    mask : ndarray
        Binary mask.
    """
    mask = mask.reshape(mask.shape + (vol.ndim - mask.ndim) * (1,))
    return vol * mask

def binary_threshold(vol, thresh):
    """
    Simple binary thresholding.

    Parameters
    ----------
    vol : ndarray
        Volume to apply threshold on.
    thresh : float
        Thresholding value.

    Returns
    -------
        Binary ndarray.
    """
    return np.where(vol > thresh, True, False)

def bounding_box(vol):
    """
    Compute the bounding box of nonzero intensity voxels in the volume.

    Parameters
    ----------
        vol : ndarray
            Volume to compute bounding box on.

    Returns
    -------
    npmins : array
        Array containg minimum index of each dimension
    npmaxs : array
        Array containg maximum index of each dimension
    """
    mask = vol != 0
    mins = np.zeros(mask.ndim)
    maxs = mins.copy()
    for i in range(mask.ndim):
        flat = mask.any(i)
        mins[i] = flat.argmax()
        maxs[i] = mask.shape[i] - flat[::-1].argmax()

    return mins, maxs

def crop(vol, mins, maxs):
    """
    Crops the input volume.

    Parameters
    ----------
    vol : 3D ndarray
        Volume to crop.
    mins : array
        Array containg minimum index of each dimension.
    maxs : array
        Array containg maximum index of each dimension.

    Returns
    -------
        vol : 3D ndarray
            The cropped volume.
    """
    return vol[tuple(slice(i, j+1) for i, j in zip(mins, maxs))]

def medotsu(input_volume, median_radius=4, numpass=4, autocrop=False):
    """
    Simple brain extraction tool method for b0 images from DWI data. It uses a
    median filter smoothing of the input_volume and an automatic histogram Otsu
    thresholding technique, hence the name medotsu.

{'fraction_non_alphanumeric': 0.10965591141802596, 'fraction_numerical': 0.01238242647934278, 'mean_word_length': 2.2394909371384495, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, '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': '3472559', 'n_tokens_mistral': 2659, 'n_tokens_neox': 2514, 'n_words': 845}