# Path: samri/utilities.py
# def collapse(img,
# 	min_dim=3,
# 	):
# 	"""
# 	Collapse a nibabel image allong its last axis
# 
# 	Parameters
# 	----------
# 	img : nibabel.nifti1.Nifti1Image
# 		Nibabel image to be collapsed.
# 	min_dim : int
# 		Bimensionality beyond which not to collapse.
# 	"""
# 
# 	ndim = 0
# 	data = img.get_data()
# 	for i in range(len(img.header['dim'])-1):
# 		current_dim = img.header['dim'][i+1]
# 		if current_dim == 1:
# 			break
# 		ndim += 1
# 	if ndim <= min_dim:
# 		return img
# 	img.header['dim'][0] = ndim
# 	img.header['pixdim'][ndim+1:] = 0
# 	data = np.mean(data,axis=(ndim-1))
# 	img = nib.nifti1.Nifti1Image(data, img.affine, img.header)
# 	return img
# 
# Path: samri/report/utilities.py
# def roi_data(img_path, masker,
# 	substitution={},
# 	exclude_zero=False,
# 	zero_threshold=0.1,
# 	):
# 	"""
# 	Return the mean of a Region of Interest (ROI) score.
# 
# 	Parameters
# 	----------
# 
# 	img_path : str
# 		Path to NIfTI file from which the ROI is to be extracted.
# 	makser : nilearn.NiftiMasker
# 		Nilearn `nifti1.Nifti1Image` object to use for masking the desired ROI.
# 	exclude_zero : bool, optional
# 		Whether to filter out zero values.
# 	substitution : dict, optional
# 		A dictionary with keys which include 'subject' and 'session'.
# 	zero_threshold : float, optional
# 		Absolute value below which values are to be considered zero.
# 	"""
# 	if substitution:
# 		img_path = img_path.format(**substitution)
# 	img_path = path.abspath(path.expanduser(img_path))
# 	img = nib.load(img_path)
# 	try:
# 		masked_data = masker.fit_transform(img)
# 	except:
# 		masker = path.abspath(path.expanduser(masker))
# 		masker = NiftiMasker(mask_img=masker)
# 		masked_data = masker.fit_transform(img)
# 	masked_data = masked_data.flatten()
# 	masked_data = masked_data[~np.isnan(masked_data)]
# 	if exclude_zero:
# 		masked_data = masked_data[np.abs(masked_data)>=zero_threshold]
# 	masked_mean = np.mean(masked_data)
# 	masked_median = np.median(masked_data)
# 	return masked_mean, masked_median


import nibabel as nib
import numpy as np
import pandas as pd
import scipy.stats as sps
import multiprocessing as mp
from os import path
from copy import deepcopy
from joblib import Parallel, delayed
from nilearn.input_data import NiftiMasker
from samri.utilities import collapse
from samri.report.utilities import roi_data
		4D files will be collapsed to 3D using the mean function.
	masker : str or nilearn.NiftiMasker, optional
		Path to a NIfTI file containing a mask (1 and 0 values) or a `nilearn.NiftiMasker` object.
		NOT YET SUPPORTED!
	threshold : float, optional
		A float giving the voxel value threshold.
	threshold_is_percentile : bool, optional
		Whether `threshold` is to be interpreted not literally, but as a percentile of the data matrix.
		This is useful for making sure that the volume estimation is not susceptible to the absolute value range, but only the value distribution.
	inverted_data : bool, optional
		Whether data is inverted (flipped with respect to 0).
		If `True`, the inverse of the threshold is automatically computed.

	Returns
	-------
	float
		The volume (in volume units of the respective NIfTI) containing values above the given threshold.
	"""

	if substitution:
		in_file = in_file.format(**substitution)
	in_file = path.abspath(path.expanduser(in_file))
	try:
		img = nib.load(in_file)
	except FileNotFoundError:
		return float('NaN')

	if img.header['dim'][0] > 4:
		raise ValueError("Files with more than 4 dimensions are not currently supported.")
	elif img.header['dim'][0] > 3:

# Path: samri/utilities.py
# def collapse(img,
# 	min_dim=3,
# 	):
# 	"""
# 	Collapse a nibabel image allong its last axis
# 
# 	Parameters
# 	----------
# 	img : nibabel.nifti1.Nifti1Image
# 		Nibabel image to be collapsed.
# 	min_dim : int
# 		Bimensionality beyond which not to collapse.
# 	"""
# 
# 	ndim = 0
# 	data = img.get_data()
# 	for i in range(len(img.header['dim'])-1):
# 		current_dim = img.header['dim'][i+1]
# 		if current_dim == 1:
# 			break
# 		ndim += 1
# 	if ndim <= min_dim:
# 		return img
# 	img.header['dim'][0] = ndim
# 	img.header['pixdim'][ndim+1:] = 0
# 	data = np.mean(data,axis=(ndim-1))
# 	img = nib.nifti1.Nifti1Image(data, img.affine, img.header)
# 	return img
# 
# Path: samri/report/utilities.py
# def roi_data(img_path, masker,
# 	substitution={},
# 	exclude_zero=False,
# 	zero_threshold=0.1,
# 	):
# 	"""
# 	Return the mean of a Region of Interest (ROI) score.
# 
# 	Parameters
# 	----------
# 
# 	img_path : str
# 		Path to NIfTI file from which the ROI is to be extracted.
# 	makser : nilearn.NiftiMasker
# 		Nilearn `nifti1.Nifti1Image` object to use for masking the desired ROI.
# 	exclude_zero : bool, optional
# 		Whether to filter out zero values.
# 	substitution : dict, optional
# 		A dictionary with keys which include 'subject' and 'session'.
# 	zero_threshold : float, optional
# 		Absolute value below which values are to be considered zero.
# 	"""
# 	if substitution:
# 		img_path = img_path.format(**substitution)
# 	img_path = path.abspath(path.expanduser(img_path))
# 	img = nib.load(img_path)
# 	try:
# 		masked_data = masker.fit_transform(img)
# 	except:
# 		masker = path.abspath(path.expanduser(masker))
# 		masker = NiftiMasker(mask_img=masker)
# 		masked_data = masker.fit_transform(img)
# 	masked_data = masked_data.flatten()
# 	masked_data = masked_data[~np.isnan(masked_data)]
# 	if exclude_zero:
# 		masked_data = masked_data[np.abs(masked_data)>=zero_threshold]
# 	masked_mean = np.mean(masked_data)
# 	masked_median = np.median(masked_data)
# 	return masked_mean, masked_median


# Path: samri/report/snr.py
import nibabel as nib
import numpy as np
import pandas as pd
import scipy.stats as sps
import multiprocessing as mp
from os import path
from copy import deepcopy
from joblib import Parallel, delayed
from nilearn.input_data import NiftiMasker
from samri.utilities import collapse
from samri.report.utilities import roi_data

		4D files will be collapsed to 3D using the mean function.
	masker : str or nilearn.NiftiMasker, optional
		Path to a NIfTI file containing a mask (1 and 0 values) or a `nilearn.NiftiMasker` object.
		NOT YET SUPPORTED!
	threshold : float, optional
		A float giving the voxel value threshold.
	threshold_is_percentile : bool, optional
		Whether `threshold` is to be interpreted not literally, but as a percentile of the data matrix.
		This is useful for making sure that the volume estimation is not susceptible to the absolute value range, but only the value distribution.
	inverted_data : bool, optional
		Whether data is inverted (flipped with respect to 0).
		If `True`, the inverse of the threshold is automatically computed.

	Returns
	-------
	float
		The volume (in volume units of the respective NIfTI) containing values above the given threshold.
	"""

	if substitution:
		in_file = in_file.format(**substitution)
	in_file = path.abspath(path.expanduser(in_file))
	try:
		img = nib.load(in_file)
	except FileNotFoundError:
		return float('NaN')

	if img.header['dim'][0] > 4:
		raise ValueError("Files with more than 4 dimensions are not currently supported.")
	elif img.header['dim'][0] > 3:

		img = collapse(img)