# Path: samri/pipelines/extra_functions.py
# def force_dummy_scans(in_file,
# 	desired_dummy_scans=10,
# 	out_file="forced_dummy_scans_file.nii.gz",
# 	):
# 	"""Take a scan and crop initial timepoints depending upon the number of dummy scans (determined from a Bruker scan directory) and the desired number of dummy scans.
# 
# 	in_file : string
# 	BIDS-compliant path to the 4D NIfTI file for which to force dummy scans.
# 
# 	desired_dummy_scans : int , optional
# 	Desired timepoints dummy scans.
# 	"""
# 
# 	import json
# 	import nibabel as nib
# 	from os import path
# 
# 	out_file = path.abspath(path.expanduser(out_file))
# 	in_file = path.abspath(path.expanduser(in_file))
# 	in_file_dir = path.dirname(in_file)
# 	in_file_name = path.basename(in_file)
# 	in_file_noext = in_file_name.split('.', 1)[0]
# 	metadata_file = path.join(in_file_dir, in_file_noext+'.json')
# 
# 	metadata = json.load(open(metadata_file))
# 
# 	dummy_scans = 0
# 	try:
# 		dummy_scans = metadata['NumberOfVolumesDiscardedByScanner']
# 	except:
# 		pass
# 
# 	delete_scans = desired_dummy_scans - dummy_scans
# 
# 	img = nib.load(in_file)
# 	if delete_scans <= 0:
# 		nib.save(img,out_file)
# 	else:
# 		img_ = nib.Nifti1Image(img.get_data()[...,delete_scans:], img.affine, img.header)
# 		nib.save(img_,out_file)
# 	deleted_scans = delete_scans
# 
# 	return out_file, deleted_scans
# 
# def get_tr(in_file,
# 	ndim=4,
# 	):
# 	"""Return the repetiton time of a NIfTI file.
# 
# 	Parameters
# 	----------
# 
# 	in_file : str
# 		Path to NIfTI file
# 	ndim : int
# 		Dimensionality of NIfTI file
# 
# 	Returns
# 	-------
# 
# 	float :
# 		Repetition Time
# 	"""
# 
# 	import nibabel as nib
# 	from os import path
# 
# 	in_file = path.abspath(path.expanduser(in_file))
# 
# 	img = nib.load(in_file)
# 	header = img.header
# 	tr = header.get_zooms()[ndim-1]
# 
# 	return tr
# 
# Path: samri/pipelines/utils.py
# def out_path(selection_df, in_path,
# 	in_field='path',
# 	out_field='out_path',
# 	):
# 	"""Select the `out_path` field corresponding to a given `in_path` from a BIDS-style selection dataframe which includes an `out_path` column.
# 	"""
# 
# 	out_path = selection_df[selection_df[in_field]==in_path][out_field].item()
# 
# 	return out_path
# 
# def container(selection_df, out_path,
# 	kind='',
# 	out_field='out_path',
# 	):
# 
# 	subject = selection_df[selection_df[out_field]==out_path]['subject'].item()
# 	session = selection_df[selection_df[out_field]==out_path]['session'].item()
# 
# 	container = 'sub-{}/ses-{}'.format(subject,session)
# 	if kind:
# 		container += '/'
# 		container += kind
# 
# 	return container
# 
# Path: samri/utilities.py
# N_PROCS=max(mp.cpu_count()-2,2)


from os import path, listdir, getcwd, remove
from copy import deepcopy
from itertools import product
from nipype.interfaces import fsl, nipy, bru2nii
from samri.pipelines.extra_functions import force_dummy_scans, get_tr
from samri.pipelines.utils import out_path, container
from samri.utilities import N_PROCS
import inspect
import re
import shutil
import argh
import nipype.interfaces.ants as ants
import nipype.interfaces.io as nio
import nipype.interfaces.utility as util		# utility
import nipype.pipeline.engine as pe				# pypeline engine
import pandas as pd
	datafind.inputs.root_paths = bids_base
	datafind.inputs.match_regex = match_regex
	datafind_res = datafind.run()

	data_selection = zip(*[datafind_res.outputs.sub, datafind_res.outputs.ses, datafind_res.outputs.acq, datafind_res.outputs.task, datafind_res.outputs.mod, datafind_res.outputs.out_paths])
	data_selection = [list(i) for i in data_selection]
	data_selection = pd.DataFrame(data_selection,columns=('subject','session','acquisition','task','modality','path'))

	data_selection = data_selection.sort_values(['session', 'subject'], ascending=[1, 1])
	if exclude:
		for key in exclude:
			data_selection = data_selection[~data_selection[key].isin(exclude[key])]
	if include:
		for key in include:
			data_selection = data_selection[data_selection[key].isin(include[key])]

	data_selection['out_path'] = ''
	if data_selection['path'].str.contains('.nii.gz').any():
		data_selection['out_path'] = data_selection['path'].apply(lambda x: path.basename(path.splitext(path.splitext(x)[0])[0]+'_MELODIC'))
	else:
		data_selection['out_path'] = data_selection['path'].apply(lambda x: path.basename(path.splitext(x)[0]+'_MELODIC'))

	paths = data_selection['path']

	infosource = pe.Node(interface=util.IdentityInterface(fields=['path'], mandatory_inputs=False), name="infosource")
	infosource.iterables = [('path', paths)]

	bids_filename = pe.Node(name='bids_filename', interface=util.Function(function=out_path,input_names=inspect.getargspec(out_path)[0], output_names=['filename']))
	bids_filename.inputs.selection_df = data_selection


# Path: samri/pipelines/extra_functions.py
# def force_dummy_scans(in_file,
# 	desired_dummy_scans=10,
# 	out_file="forced_dummy_scans_file.nii.gz",
# 	):
# 	"""Take a scan and crop initial timepoints depending upon the number of dummy scans (determined from a Bruker scan directory) and the desired number of dummy scans.
# 
# 	in_file : string
# 	BIDS-compliant path to the 4D NIfTI file for which to force dummy scans.
# 
# 	desired_dummy_scans : int , optional
# 	Desired timepoints dummy scans.
# 	"""
# 
# 	import json
# 	import nibabel as nib
# 	from os import path
# 
# 	out_file = path.abspath(path.expanduser(out_file))
# 	in_file = path.abspath(path.expanduser(in_file))
# 	in_file_dir = path.dirname(in_file)
# 	in_file_name = path.basename(in_file)
# 	in_file_noext = in_file_name.split('.', 1)[0]
# 	metadata_file = path.join(in_file_dir, in_file_noext+'.json')
# 
# 	metadata = json.load(open(metadata_file))
# 
# 	dummy_scans = 0
# 	try:
# 		dummy_scans = metadata['NumberOfVolumesDiscardedByScanner']
# 	except:
# 		pass
# 
# 	delete_scans = desired_dummy_scans - dummy_scans
# 
# 	img = nib.load(in_file)
# 	if delete_scans <= 0:
# 		nib.save(img,out_file)
# 	else:
# 		img_ = nib.Nifti1Image(img.get_data()[...,delete_scans:], img.affine, img.header)
# 		nib.save(img_,out_file)
# 	deleted_scans = delete_scans
# 
# 	return out_file, deleted_scans
# 
# def get_tr(in_file,
# 	ndim=4,
# 	):
# 	"""Return the repetiton time of a NIfTI file.
# 
# 	Parameters
# 	----------
# 
# 	in_file : str
# 		Path to NIfTI file
# 	ndim : int
# 		Dimensionality of NIfTI file
# 
# 	Returns
# 	-------
# 
# 	float :
# 		Repetition Time
# 	"""
# 
# 	import nibabel as nib
# 	from os import path
# 
# 	in_file = path.abspath(path.expanduser(in_file))
# 
# 	img = nib.load(in_file)
# 	header = img.header
# 	tr = header.get_zooms()[ndim-1]
# 
# 	return tr
# 
# Path: samri/pipelines/utils.py
# def out_path(selection_df, in_path,
# 	in_field='path',
# 	out_field='out_path',
# 	):
# 	"""Select the `out_path` field corresponding to a given `in_path` from a BIDS-style selection dataframe which includes an `out_path` column.
# 	"""
# 
# 	out_path = selection_df[selection_df[in_field]==in_path][out_field].item()
# 
# 	return out_path
# 
# def container(selection_df, out_path,
# 	kind='',
# 	out_field='out_path',
# 	):
# 
# 	subject = selection_df[selection_df[out_field]==out_path]['subject'].item()
# 	session = selection_df[selection_df[out_field]==out_path]['session'].item()
# 
# 	container = 'sub-{}/ses-{}'.format(subject,session)
# 	if kind:
# 		container += '/'
# 		container += kind
# 
# 	return container
# 
# Path: samri/utilities.py
# N_PROCS=max(mp.cpu_count()-2,2)


# Path: samri/pipelines/fc.py
from os import path, listdir, getcwd, remove
from copy import deepcopy
from itertools import product
from nipype.interfaces import fsl, nipy, bru2nii
from samri.pipelines.extra_functions import force_dummy_scans, get_tr
from samri.pipelines.utils import out_path, container
from samri.utilities import N_PROCS
import inspect
import re
import shutil
import argh
import nipype.interfaces.ants as ants
import nipype.interfaces.io as nio
import nipype.interfaces.utility as util		# utility
import nipype.pipeline.engine as pe				# pypeline engine
import pandas as pd

	datafind.inputs.root_paths = bids_base
	datafind.inputs.match_regex = match_regex
	datafind_res = datafind.run()

	data_selection = zip(*[datafind_res.outputs.sub, datafind_res.outputs.ses, datafind_res.outputs.acq, datafind_res.outputs.task, datafind_res.outputs.mod, datafind_res.outputs.out_paths])
	data_selection = [list(i) for i in data_selection]
	data_selection = pd.DataFrame(data_selection,columns=('subject','session','acquisition','task','modality','path'))

	data_selection = data_selection.sort_values(['session', 'subject'], ascending=[1, 1])
	if exclude:
		for key in exclude:
			data_selection = data_selection[~data_selection[key].isin(exclude[key])]
	if include:
		for key in include:
			data_selection = data_selection[data_selection[key].isin(include[key])]

	data_selection['out_path'] = ''
	if data_selection['path'].str.contains('.nii.gz').any():
		data_selection['out_path'] = data_selection['path'].apply(lambda x: path.basename(path.splitext(path.splitext(x)[0])[0]+'_MELODIC'))
	else:
		data_selection['out_path'] = data_selection['path'].apply(lambda x: path.basename(path.splitext(x)[0]+'_MELODIC'))

	paths = data_selection['path']

	infosource = pe.Node(interface=util.IdentityInterface(fields=['path'], mandatory_inputs=False), name="infosource")
	infosource.iterables = [('path', paths)]

	bids_filename = pe.Node(name='bids_filename', interface=util.Function(function=out_path,input_names=inspect.getargspec(out_path)[0], output_names=['filename']))
	bids_filename.inputs.selection_df = data_selection


	bids_container = pe.Node(name='path_container', interface=util.Function(function=container,input_names=inspect.getargspec(container)[0], output_names=['container']))