# Path: samri/report/utilities.py
# def roi_df(img_path, masker,
# 	substitution=False,
# 	feature=[],
# 	atlas='',
# 	mapping='',
# 	):
# 	"""
# 	Return a dataframe containing the mean of a Region of Interest (ROI).
# 
# 	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.
# 	substitution : dict, optional
# 		A dictionary with keys which include 'subject' and 'session'.
# 	feature : list, optional
# 		A list with labels which were used to dynalically generate the masker ROI.
# 		This parameter will be ignored if a path can be established for the masker - via `masker.mask_img.get_filename()`.
# 	"""
# 	subject_data={}
# 	if substitution:
# 		img_path = img_path.format(**substitution)
# 	img_path = path.abspath(path.expanduser(img_path))
# 	try:
# 		img = nib.load(img_path)
# 	except (FileNotFoundError, nib.py3k.FileNotFoundError):
# 		return pd.DataFrame({})
# 	else:
# 		img = masker.fit_transform(img)
# 		img = img.flatten()
# 		mean = np.nanmean(img)
# 		subject_data['session'] = substitution['session']
# 		subject_data['subject'] = substitution['subject']
# 		subject_data['t'] = mean
# 		mask_path = masker.mask_img.get_filename()
# 		if mask_path:
# 			feature = path.abspath(mask_path)
# 		subject_data['feature'] = feature
# 		subject_data['atlas'] = atlas
# 		subject_data['mapping'] = mapping
# 		df = pd.DataFrame(subject_data, index=[None])
# 		return df
# 
# def pattern_df(img_path, pattern,
# 	substitution=False,
# 	):
# 	"""
# 	Return a dataframe containing the `patern` score of `img_path` (i.e. the mean of the multiplication product).
# 
# 	Parameters
# 	----------
# 
# 	img_path : str
# 		Path to NIfTI file from which the ROI is to be extracted.
# 	pattern : nilearn.NiftiMasker
# 		Nilearn `nifti1.Nifti1Image` object to use for masking the desired ROI.
# 	substitution : dict, optional
# 		A dictionary with keys which include 'subject' and 'session'.
# 
# 	"""
# 
# 	subject_data={}
# 	if substitution:
# 		img_path = img_path.format(**substitution)
# 	img_path = path.abspath(path.expanduser(img_path))
# 	try:
# 		img = nib.load(img_path)
# 	except (FileNotFoundError, nib.py3k.FileNotFoundError):
# 		return pd.DataFrame({}), pd.DataFrame({})
# 	else:
# 		img_data = img.get_data()
# 		pattern_data = pattern.get_data()
# 		pattern_evaluation = img_data*pattern_data
# 		pattern_evaluation = pattern_evaluation.flatten()
# 		pattern_score = np.nanmean(pattern_evaluation)
# 		subject_data["session"]=substitution["session"]
# 		subject_data["subject"]=substitution["subject"]
# 		subject_data["t"]=pattern_score
# 		subject_data['feature'] = pattern.get_filename()
# 		df = pd.DataFrame(subject_data, index=[None])
# 		return df


import nibabel as nib
import numpy as np
import os
import statsmodels.formula.api as smf
import multiprocessing as mp
import pandas as pd
	import nibabel as nib
	import numpy as np
	import pandas as pd
from os import path
from nilearn.input_data import NiftiMasker
from scipy.io import loadmat
from samri.report.utilities import roi_df, pattern_df
from joblib import Parallel, delayed
	from scipy import ndimage
	from nilearn.input_data import NiftiMasker
	from os import path
	from copy import deepcopy
		from nibabel import processing
	from samri.report import roi
	from samri.utilities import bids_substitution_iterator
	from samri.fetch.local import roi_from_atlaslabel
	from os.path import basename, splitext
		roi_mask = nib.load(roi_mask)

	masker = NiftiMasker(mask_img=roi_mask)

	n_jobs = mp.cpu_count()-2
	dfs = Parallel(n_jobs=n_jobs, verbose=0, backend="threading")(map(delayed(roi_df),
		[filename_template]*len(substitutions),
		[masker]*len(substitutions),
		substitutions,
		feature*len(substitutions),
		[atlas]*len(substitutions),
		[mapping]*len(substitutions),
		))
	df = pd.concat(dfs)

	return df


def mean(img_path, mask_path):
	"""Return the mean of the masked region of an image.
	"""
	mask = path.abspath(path.expanduser(mask_path))
	if mask_path.endswith("roi"):
		mask = loadmat(mask)["ROI"]
		while mask.ndim != 3:
			mask=mask[0]
		img_path = path.abspath(path.expanduser(img_path))
		img = nib.load(img_path)
	else:
		masker = NiftiMasker(mask_img=mask)

# Path: samri/report/utilities.py
# def roi_df(img_path, masker,
# 	substitution=False,
# 	feature=[],
# 	atlas='',
# 	mapping='',
# 	):
# 	"""
# 	Return a dataframe containing the mean of a Region of Interest (ROI).
# 
# 	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.
# 	substitution : dict, optional
# 		A dictionary with keys which include 'subject' and 'session'.
# 	feature : list, optional
# 		A list with labels which were used to dynalically generate the masker ROI.
# 		This parameter will be ignored if a path can be established for the masker - via `masker.mask_img.get_filename()`.
# 	"""
# 	subject_data={}
# 	if substitution:
# 		img_path = img_path.format(**substitution)
# 	img_path = path.abspath(path.expanduser(img_path))
# 	try:
# 		img = nib.load(img_path)
# 	except (FileNotFoundError, nib.py3k.FileNotFoundError):
# 		return pd.DataFrame({})
# 	else:
# 		img = masker.fit_transform(img)
# 		img = img.flatten()
# 		mean = np.nanmean(img)
# 		subject_data['session'] = substitution['session']
# 		subject_data['subject'] = substitution['subject']
# 		subject_data['t'] = mean
# 		mask_path = masker.mask_img.get_filename()
# 		if mask_path:
# 			feature = path.abspath(mask_path)
# 		subject_data['feature'] = feature
# 		subject_data['atlas'] = atlas
# 		subject_data['mapping'] = mapping
# 		df = pd.DataFrame(subject_data, index=[None])
# 		return df
# 
# def pattern_df(img_path, pattern,
# 	substitution=False,
# 	):
# 	"""
# 	Return a dataframe containing the `patern` score of `img_path` (i.e. the mean of the multiplication product).
# 
# 	Parameters
# 	----------
# 
# 	img_path : str
# 		Path to NIfTI file from which the ROI is to be extracted.
# 	pattern : nilearn.NiftiMasker
# 		Nilearn `nifti1.Nifti1Image` object to use for masking the desired ROI.
# 	substitution : dict, optional
# 		A dictionary with keys which include 'subject' and 'session'.
# 
# 	"""
# 
# 	subject_data={}
# 	if substitution:
# 		img_path = img_path.format(**substitution)
# 	img_path = path.abspath(path.expanduser(img_path))
# 	try:
# 		img = nib.load(img_path)
# 	except (FileNotFoundError, nib.py3k.FileNotFoundError):
# 		return pd.DataFrame({}), pd.DataFrame({})
# 	else:
# 		img_data = img.get_data()
# 		pattern_data = pattern.get_data()
# 		pattern_evaluation = img_data*pattern_data
# 		pattern_evaluation = pattern_evaluation.flatten()
# 		pattern_score = np.nanmean(pattern_evaluation)
# 		subject_data["session"]=substitution["session"]
# 		subject_data["subject"]=substitution["subject"]
# 		subject_data["t"]=pattern_score
# 		subject_data['feature'] = pattern.get_filename()
# 		df = pd.DataFrame(subject_data, index=[None])
# 		return df


# Path: samri/report/roi.py
import nibabel as nib
import numpy as np
import os
import statsmodels.formula.api as smf
import multiprocessing as mp
import pandas as pd
	import nibabel as nib
	import numpy as np
	import pandas as pd
from os import path
from nilearn.input_data import NiftiMasker
from scipy.io import loadmat
from samri.report.utilities import roi_df, pattern_df
from joblib import Parallel, delayed
	from scipy import ndimage
	from nilearn.input_data import NiftiMasker
	from os import path
	from copy import deepcopy
		from nibabel import processing
	from samri.report import roi
	from samri.utilities import bids_substitution_iterator
	from samri.fetch.local import roi_from_atlaslabel
	from os.path import basename, splitext

		roi_mask = nib.load(roi_mask)

	masker = NiftiMasker(mask_img=roi_mask)

	n_jobs = mp.cpu_count()-2
	dfs = Parallel(n_jobs=n_jobs, verbose=0, backend="threading")(map(delayed(roi_df),
		[filename_template]*len(substitutions),
		[masker]*len(substitutions),
		substitutions,
		feature*len(substitutions),
		[atlas]*len(substitutions),
		[mapping]*len(substitutions),
		))
	df = pd.concat(dfs)

	return df


def mean(img_path, mask_path):
	"""Return the mean of the masked region of an image.
	"""
	mask = path.abspath(path.expanduser(mask_path))
	if mask_path.endswith("roi"):
		mask = loadmat(mask)["ROI"]
		while mask.ndim != 3:
			mask=mask[0]
		img_path = path.abspath(path.expanduser(img_path))
		img = nib.load(img_path)
	else:
		masker = NiftiMasker(mask_img=mask)

		roi_df(img_path,masker)