import nibabel as nib
import MultivariateDMRIAnalysis as MDA
import numpy as np
from statsmodels.sandbox.stats.multicomp import fdrcorrection0
import sys, getopt, os
import os.path

def AgingAnalysis(Vdata, ages, data_shape, numPerm=2000, tfce_flag=False, 
		  fdr_flag=False, rows=-1, alpha=0.1):
        dataDim = len(Vdata)
        numPoints = Vdata[0].shape[1]
	numSamples = Vdata[0].shape[0]
        # constructing label vector:
	X = ages[:,np.newaxis]
	
        
        # constructing parameter matrix:
	Y = np.zeros([numSamples, dataDim*numPoints])
        for k in range(dataDim):
                Y[:, k*numPoints:(k+1)*numPoints] = Vdata[k]
                
        # computing the covariance and vectors:
        cov_scores, vecs = MDA.MultivariateCovarianceAnalysis_SingleLabel_AllPoints(Y,X,dataDim)
        # computing the pvalues based on permutation tests:
	pvals, maximal_statistics, cov_s, cov_sp = MDA.PermutationTesting_AllPoints(Y, X, dataDim, numPerm)

        if tfce_flag:
		print 'Applying TFCE enhancement'
		# applies TFCE correction
                pvals, maximal_statistics = MDA.TFCECorrection_PermutationResults(cov_s, cov_sp, rows, data_shape)
	# correcting for the number of permutations
	pvals_ = pvals + 1./(numPerm + 1)
	pvals_[pvals_>1.] = 1.
        
	# applying false discovery rate correction for multiple comparisons if specified
        if fdr_flag:
		print 'Applying FDR correction @ alpha = %f' % alpha
                pvals = fdrcorrection0(pvals_, alpha=alpha)[1]
        else:
                pvals = pvals_.copy()
        
	# results are not written down here
	return cov_scores, vecs, pvals

def GroupAnalysis(Vdata, groups, data_shape, numPerm=2000, tfce_flag=False, 
		  fdr_flag=False, rows=-1, alpha=0.1):
        dataDim = len(Vdata)
        numPoints = Vdata[0].shape[1]
	indicesG = np.where(groups==1)[0]
	indicesC = np.where(groups==0)[0]
	indices = np.append(indicesC, indicesG)
	numSamples = len(indices)
        # constructing label vector:
	X = np.zeros([numSamples,1])
	X[:len(indicesC),0] = -1
	X[len(indicesC):,0] = 1
        
        # constructing parameter matrix:
	Y = np.zeros([numSamples, dataDim*numPoints])
        for k in range(dataDim):
                Y[:, k*numPoints:(k+1)*numPoints] = Vdata[k][indices,:]
                
        # computing the covariance and vectors:
        cov_scores, vecs = MDA.MultivariateCovarianceAnalysis_SingleLabel_AllPoints(Y,X,dataDim)
        # computing the pvalues based on permutation tests:
	pvals, maximal_statistics, cov_s, cov_sp = MDA.PermutationTesting_AllPoints(Y, X, dataDim, numPerm)

        if tfce_flag:
		print 'Applying TFCE enhancement'
		# applies TFCE correction
                pvals, maximal_statistics = MDA.TFCECorrection_PermutationResults(cov_s, cov_sp, rows, data_shape)
	# correcting for the number of permutations
	pvals_ = pvals + 1./(numPerm + 1)
	pvals_[pvals_>1.] = 1.
        
	# applying false discovery rate correction for multiple comparisons if specified
        if fdr_flag:
		print 'Applying FDR correction @ alpha = %f' % alpha
                pvals = fdrcorrection0(pvals_, alpha=alpha)[1]
        else:
                pvals = pvals_.copy()
        
	# results are not written down here
	return cov_scores, vecs, pvals

def WriteGroupAnalysisResults(cov_scores, vecs, pvals, outname, data_shape, rows, pth=2., wtype='binary'):
	'''
	pth = pvalue threshold as -log_10
	wtype = 'binary' (default), 'nifti', 'txt'
	'''
        if wtype=='binary':
		MDA.WriteResultsInBinary(cov_scores, vecs, pvals, pth, outname, data_shape, rows)
	elif wtype == 'txt':
		MDA.WriteResultsInTxt(cov_scores, vecs, pvals, pth, outname, data_shape, rows)

def GroupAnalysisRegressingOutAge(Vdata, groups, ages, data_shape, numPerm=2000, tfce_flag=False, 
		  fdr_flag=False, rows=-1, alpha=0.1): 
	# data information 
	dataDim = len(Vdata)
	numPoints = Vdata[0].shape[1]
	indicesG = np.where(groups==1)[0]
	indicesC = np.where(groups==0)[0]
	indices = np.append(indicesC, indicesG)
	numSamples = len(indices)
	# constructing label vectors
	X_AGE = np.zeros([numSamples, 1])
	X_AGE[:, 0] = ages[indices]
	X_GRP = np.zeros([numSamples,1])
	X_GRP[:len(indicesC),0] = -1
	X_GRP[len(indicesC):,0] = 1
	
	# constructing parameter matrix:	
	Y = np.zeros([numSamples, dataDim*numPoints])
	for k in range(dataDim):
		Y[:, k*numPoints:(k+1)*numPoints] = Vdata[k][indices,:]
	
	# computing the covariance and vectors:
	cov_scores_orth, vecs_orth, cov_scores_par = MDA.MultivariateCovarianceAnalysis_RegressingOut_AllPoints(Y, X_GRP, X_AGE, dataDim)
	#computing the pvalues based on permutation tests: 
	pvals_orth, maxStats_orth, pvals_par, maxStats_par, cov_scores_p_orth, cov_scores_p_par =\
	    MDA.PermutationTesting_RegressingOut_AllPoints(Y, X_GRP, X_AGE, dataDim, numPerm)
	
	if tfce_flag: 
		print 'Applying TFCE enhancement'
		# applies TFCE correction
		pvals_orth, maxStats_orth, pvals_par, maxStats_par = MDA.TFCECorrection_PermutationRegressingOut(cov_scores_orth, cov_scores_p_orth, cov_scores_par, cov_scores_p_par, rows, data_shape)
	# correcting for the number of permutations
	pvals_orth_ = pvals_orth + 1./(numPerm + 1)
	pvals_par_ = pvals_par + 1./(numPerm + 1)
	pvals_orth_[pvals_orth_ > 1.] = 1.
	pvals_par_[pvals_par_ > 1.] = 1.
		
	# applying false discovery rate correcting for multiple comparisons if specified
	if fdr_flag:
		print 'Applying FDR correction at alpha = %f' % alpha
		pvals_orth = fdrcorrection0(pvals_orth_, alpha=alpha)[1]
		pvals_par = fdrcorrection0(pvals_par_, alpha=alpha)[1]
	else: 
		pvals_orth = pvals_orth_.copy()
		pvals_par = pvals_par_.copy()

	return cov_scores_orth, cov_scores_par, vecs_orth, pvals_orth, pvals_par

def WriteGroupAnalysisRegressingOutAgeResults(cov_scores_orth, cov_scores_par, vecs_orth, pvals_orth, pvals_par, 
					      outname, data_shape, rows, pth=2., wtype='binary'):

	if wtype == 'binary':
		MDA.WriteResultsInBinary(cov_scores_orth, vecs_orth, pvals_orth, pth, outname + 'orth_', data_shape, rows)
		MDA.WriteResultsInBinary(cov_scores_par, vecs_orth, pvals_par, pth, outname + 'par_', data_shape, rows)
                try:
                        os.remove(outname + 'par_vectors_th.dat')
                except OSError:
                        pass
	elif wtype == 'txt': 
		MDA.WriteResultsInTxt(cov_scores_orth, vecs_orth, pvals_orth, pth, outname + 'orth_', data_shape, rows)
		MDA.WriteResultsInTxt(cov_scores_par, vecs_orth, pvals_par, pth, outname + 'par_', data_shape, rows)
                try:
                        os.remove(outname + 'par_vectors_th_0.txt')
                        os.remove(outname + 'par_vectors_th_1.txt')
                        os.remove(outname + 'par_vectors_th_2.txt')
                except OSError:
                        pass
        try:
                os.remove(outname + 'par_data_info.txt')
                os.rename(outname + 'orth_data_info.txt', outname + 'data_info.txt')
        except OSError:
                pass
        

def EffectTypeComparison(Vdata, groups, data_shape, numPerm=2000, tfce_flag=False, 
			 fdr_flag=False, rows=-1, alpha=0.1, region_th=0.1, pth=2., 
			 outName='./', wtype='binary'):
	
	# data information and indices
	dataDim = len(Vdata)
        numPoints = Vdata[0].shape[1]
	
	indicesG1 = np.where(groups==1)[0]
	indicesCN = np.where(groups==0)[0]
	indicesG2 = np.where(groups==2)[0]	
	indicesG1vCN = np.append(indicesCN, indicesG1)
	indicesG2vCN = np.append(indicesCN, indicesG2)
	numSamplesG1vCN = len(indicesG1vCN)
	numSamplesG2vCN = len(indicesG2vCN)
	numSamplesG1 = len(indicesG1)
	numSamplesG2 = len(indicesG2)
	numSamplesCN = len(indicesCN)

	# constructing labels
	X_G1vCN = np.zeros([numSamplesG1vCN,1])
	X_G1vCN[:len(indicesCN),0] = -1
	X_G1vCN[len(indicesCN):,0] = 1
	
	X_G2vCN = np.zeros([numSamplesG2vCN,1])
	X_G2vCN[:len(indicesCN),0] = -1
	X_G2vCN[len(indicesCN):,0] = 1
	
	# determining the group differences independently
	# constructing parameter matrices: 		
	Y = np.zeros([numSamplesG1vCN, dataDim*numPoints])
	for k in range(dataDim): 
		Y[:, k*numPoints:(k+1)*numPoints] = Vdata[k][indicesG1vCN,:]
	pvals_G1vCN = MDA.PermutationTesting_AllPoints(Y, X_G1vCN, dataDim, numPerm)[0]
	Y = np.zeros([numSamplesG2vCN, dataDim*numPoints])
	for k in range(dataDim): 
		Y[:, k*numPoints:(k+1)*numPoints] = Vdata[k][indicesG2vCN,:]
	pvals_G2vCN = MDA.PermutationTesting_AllPoints(Y, X_G2vCN, dataDim, numPerm)[0]
	# determining the regions where phase difference analysis will be performed
	regions = ((pvals_G1vCN) < region_th)*((pvals_G2vCN) < region_th)
	joint_rows = np.where(regions > 0)[0]
	numPointsJoint = joint_rows.shape[0]
    
	# restricting the analysis to the joint regions only
	mag_diff_im = np.zeros(numPointsJoint)
	phase_diff_im = np.zeros(numPointsJoint)
	p_values_mag = np.zeros(numPointsJoint)
	p_values_phase = np.zeros(numPointsJoint)
        
        # base analysis
	Y_G1vCN = np.zeros([numSamplesG1vCN, dataDim*numPointsJoint])
	for k in range(dataDim): 
		Y_G1vCN[:, k*numPointsJoint:(k+1)*numPointsJoint] = Vdata[k][indicesG1vCN[:,np.newaxis],joint_rows[np.newaxis,:]]

	Y_G2vCN = np.zeros([numSamplesG2vCN, dataDim*numPointsJoint])	
	for k in range(dataDim):
		Y_G2vCN[:, k*numPointsJoint:(k+1)*numPointsJoint] = Vdata[k][indicesG2vCN[:,np.newaxis], joint_rows[np.newaxis,:]]

	cov_scores_G1vCN, vecs_G1vCN = MDA.MultivariateCovarianceAnalysis_SingleLabel_AllPoints(Y_G1vCN,X_G1vCN,dataDim)
	cov_scores_G2vCN, vecs_G2vCN = MDA.MultivariateCovarianceAnalysis_SingleLabel_AllPoints(Y_G2vCN,X_G2vCN,dataDim)
	mag_diff_im = np.abs(cov_scores_G2vCN[:,0] - cov_scores_G1vCN[:,0])
	phase_diff_im = 1.0 - np.sum(vecs_G2vCN[:,:,0]*vecs_G1vCN[:,:,0],axis=0)
	# TFCE enhancement if desired
	if tfce_flag: 
		print 'Applying TFCE enhancement'
		tmp_im_full = np.zeros(numPoints)
		tmp_im_full[joint_rows] = mag_diff_im
		mag_diff_im = MDA.TFCECorrection_Basic(tmp_im_full, rows, data_shape)[joint_rows]
		tmp_im_full = np.zeros(numPoints)
		tmp_im_full[joint_rows] = phase_diff_im
		phase_diff_im = MDA.TFCECorrection_Basic(tmp_im_full, rows, data_shape)[joint_rows]
		
    
	for n in range(numPerm):
		perm_indices = np.random.permutation(np.append(indicesG1, indicesG2))
		perm_indices_G1 = perm_indices[:numSamplesG1]
		perm_indices_G2 = perm_indices[numSamplesG1:]
		perm_indices_G1vCN = np.append(indicesCN, perm_indices_G1)
		perm_indices_G2vCN = np.append(indicesCN, perm_indices_G2)
		Y_G1vCN = Y_G1vCN * 0.
		Y_G2vCN = Y_G2vCN * 0.
		for k in range(dataDim): 
			Y_G1vCN[:,k*numPointsJoint:(k+1)*numPointsJoint] = Vdata[k][perm_indices_G1vCN[:,np.newaxis], joint_rows[np.newaxis,:]]
			Y_G2vCN[:,k*numPointsJoint:(k+1)*numPointsJoint] = Vdata[k][perm_indices_G2vCN[:,np.newaxis], joint_rows[np.newaxis,:]]

		perm_cov_scores_G1vCN, perm_vecs_G1vCN = MDA.MultivariateCovarianceAnalysis_SingleLabel_AllPoints(Y_G1vCN,X_G1vCN,dataDim)
		perm_cov_scores_G2vCN, perm_vecs_G2vCN = MDA.MultivariateCovarianceAnalysis_SingleLabel_AllPoints(Y_G2vCN,X_G2vCN,dataDim)    
		perm_mag_diff_im = np.abs(perm_cov_scores_G2vCN[:,0] - perm_cov_scores_G1vCN[:,0])
		perm_phase_diff_im = 1.0 - np.sum(perm_vecs_G2vCN[:,:,0]*perm_vecs_G1vCN[:,:,0],axis=0)
		# TFCE enhancement if desired
		if tfce_flag: 
			tmp_im_full = np.zeros(numPoints)
			tmp_im_full[joint_rows] = perm_mag_diff_im
			perm_mag_diff_im = MDA.TFCECorrection_Basic(tmp_im_full, rows, data_shape)[joint_rows]
			tmp_im_full = np.zeros(numPoints)
			tmp_im_full[joint_rows] = perm_phase_diff_im
			perm_phase_diff_im = MDA.TFCECorrection_Basic(tmp_im_full, rows, data_shape)[joint_rows]

		p_values_mag += (perm_mag_diff_im >= mag_diff_im).astype(float)
		p_values_phase += (perm_phase_diff_im >= phase_diff_im).astype(float)
		if n % 100 == 0: 
			print '{0} / {1} done.'.format(n, numPerm)
			
	p_values_mag = p_values_mag / float(numPerm)
	p_values_phase = p_values_phase / float(numPerm)

	p_values_mag_ = p_values_mag + 1./(numPerm + 1)
	p_values_phase_ = p_values_phase + 1./(numPerm + 1)
	p_values_mag_[p_values_mag_ > 1.] = 1.
	p_values_phase_[p_values_phase_ > 1.] = 1.
	
	# FDR correction
	if fdr_flag: 
		print 'Applying FDR correction at alpha = %f' % alpha
		p_values_mag = fdrcorrection0(p_values_mag_, alpha=alpha)[1]
		p_values_phase = fdrcorrection0(p_values_phase_, alpha=alpha)[1]
	else:
		p_values_mag = p_values_mag_.copy()
		p_values_phase = p_values_phase_.copy()
	
	tmp_im_full = np.ones(numPoints)
	tmp_im_full[joint_rows] = p_values_phase
	if wtype == 'binary': 		
		# writing the pvalues
		MDA.WritePValResultsInBinary(np.ones(numPoints), tmp_im_full, pth, outName + 'effect_type_diff_', data_shape, rows)
		# writing the regions where the analysis has been made
		regionImage = np.zeros(data_shape)
		regionImage[rows] = regions.astype(int)
		fid = open(outName + 'regions.dat', 'w')
		regionImage.tofile(fid)
		fid.close()		
	elif wtype == 'txt':
		# writing the pvalues
		MDA.WritePValResultsInTxt(np.ones(numPoints), tmp_im_full, pth, outName + 'effect_type_diff_', data_shape, rows)
		# writing the regions where the analysis has been made
		regionImage = np.zeros(data_shape)
		regionImage[rows] = regions.astype(int)
		np.savetxt(outName + 'regions.txt', regionImage.reshape(np.prod(data_shape)))

	# writing the data shape
	np.savetxt(outName + 'data_info.txt', np.append(data_shape, dataDim))

def ParseInput(argv): 
	options = {'-h' : InputHelp, '-d' : GetData, '-g' : GetGroup, '-a' : GetAge, '-s' : GetShape, '-t' : SetAnalysisType, '-tfce' : GetTFCEFlag, '-fdr' : GetFDRFlag, '-fdr_alpha' : GetFDRAlpha, '-nperm' : GetNumPerm, '-o' : GetOutputName, '-otype' : GetOutputType, '-pth' : GetPThreshold, '-rth' : GetRegionTh, '-tract' : GetTractFlag}

	lena = len(argv)
	k = 0
	if lena == 0: 
		InputHelp(argv, k)
	while k < lena: 
		if argv[k][0] == '-':
			options[argv[k]](argv, k)			
		k += 1
	

def InputHelp(argv, k): 
	print 'USAGE: \n python MultivariateProcedures.py -d image1 image2 ... \n -s data_shape \n -g group_file \n -a age_file \n -t type_of_analysis[group(default)|regressing_out|effect_comparison|aging] \n -tfce tfce_flag[0(default)|1] \n -fdr fdr_flag[0(default)|1] \n -fdr_alpha alpha[0.1(default)] \n -nperm number_of_permutation[2000(default)] \n -o output_file_prefix \n -otype output_type[binary(default)|txt] \n -pth pvalue_threshold_negLog10[2.(default)] \n -rth region_threshold[0.1(default)] -tract'
	print 'Parameters:'
	print '==========='
	print '\t-d : images. different modalities are given as separate files. each image file is a matrix of numPoints x numSamples. numPoints is the total number of points in the image. Even if only a certain part of the image has non-zero values please provide the entire image. Internally such regions are detected and analysis is not performed. txt or csv files are accepted. if csv do not use "," as delimiter. '
	print '\t-s : data shape. this is a series of integers indicating the shape of the image or volume. one number is given if tract or surface files, two numbers are given if 2D image and 3 if the image is a volume, e.g. 100 100 (for a 100x100 2D image) '
	print '\t-g : group file. this is a txt file indicating labels, as integers, for each subject in the sample. in the label file 0 corresponds to controls and 1 to the group of interest. For effect_type analysis one also needs to provide label 2 for the 2nd group of interest.'
	print '\t-a : age file. this is a txt file indicating ages or another continuous variable for each subject'
	print '\t-t : type of analysis. options are group (for basic group comparison), aging (for continuous valued analysis such as aging), regressing_out (group comparison with regressing out nuissance continuous parameter age), effect_comparison (comparing effects of different conditions as given with different labels in the group file)'
	print '\t-tfce : 0 or 1. Flag to perform TFCE enhancement. TFCE enhancement is only available for tracts, 2D images and 3D volumes. There is no enhancement implemented for surfaces at the moment.'
	print '\t-fdr : 0 or 1. flag to perform FDR correction'
	print '\t-fdr_alpha : alpha value of the FDR correction'
	print '\t-nperm : number of permutations using the statistical test, e.g. 1000'
	print '\t-o : prefix of the output file. the actual file names depend on the analysis'
	print '\t-otype : binary or txt. type of the output file. if binary the images are written down in binary and should be read as such. the images are written row-major (C-format)'
	print '\t-pth : a floating point number. threshold for the -log_10(pvalue)'
	print '\t-rth : a region threshold to constraint the effect-comparison analysis to the areas where both conditions are significant. threshold is on the probability'
	print '\t-tract : flag to indicate whether the data is a tract or 1D data with spatial context in it. Default is false and when -tract is given it is set as true and TFCE in 1D becomes available.'
	print '============'
	print 'See dev_run.csh for examples'
	print 'For easiest execution please use within anaconda or enthought python environment' 
	print 'Ender Konukoglu 2016 - ender.konukoglu@gmail.com'
	print '*******\nPLEASE CITE: Ender Konukoglu, Jean-Philippe Coutu, David Salat and Bruce Fischl, "Multivariate Statistical Analysis of Diffusion Imaging Parameters using Partial Least Squares: Application to White Matter Variations in Alzheimers Disease", Neuroimage 2016\n*******'
	sys.exit(2)

def GetData(argv, k): 
	global Vdata
	global rows
	V = []
	m = 1
	while k+m < len(argv) and argv[k+m][0] != '-':
		tmp = np.loadtxt(argv[k+m]).T
		V = V + [tmp]
		m += 1
	rows = np.zeros(V[0].shape[1], dtype=bool)
	for m in range(len(V)):
		rows += np.sum(np.abs(V[m]),axis=0) > 0
	rows = rows > 0
	for m in range(len(V)): 
		Vdata = Vdata + [V[m][:,rows]]

def GetGroup(argv, k): 
	global groups
	groups = np.loadtxt(argv[k+1])

def GetAge(argv, k): 
	global ages
	ages = np.loadtxt(argv[k+1])

def GetShape(argv, k): 
	global data_shape
	dshape = []
	m = 1
	while k+m < len(argv) and argv[k+m][0] != '-': 
		dshape = dshape + [np.int(argv[k+m])]
		m += 1
	data_shape = np.asarray(dshape, dtype=int)

def SetAnalysisType(argv, k): 
	global analysis_type
	analysis_type = argv[k+1]

def CheckInputs(): 
	global tfce_flag
	global data_shape
	if len(rows) == 0: 
		print 'ERROR: Data is not set right. Please see the documentation and the examples in the example_data folder.'
		sys.exit(2)
	if len(data_shape) == 0: 
		print 'WARNING: Data shape is not provided. Please use the -s flag to set the data shape. Run python MultivariateProcedures.py -h for help. For the current analysis the data_shape is set to the number of points in the data files. '
		data_shape = np.asarray([len(rows)])
	if len(data_shape) == 1 and tract_flag: 
		print 'WARNING: TFCE is only available for volumetric, 2D data or tract data.' 
		tfce_flag = False

def GetTFCEFlag(argv, k): 
	global tfce_flag
	if np.int(argv[k+1]) > 0:
		tfce_flag = True

def GetFDRFlag(argv, k): 
	global fdr_flag
	if np.int(argv[k+1]) > 0: 
		fdr_flag = True

def GetFDRAlpha(argv, k): 
	global fdr_alpha
	fdr_alpha = np.float(argv[k+1])

def GetNumPerm(argv, k): 
	global numPerm
	numPerm = np.int(argv[k+1])

def GetOutputName(argv, k):
	global output_name
	output_name = argv[k+1]

def GetOutputType(argv, k): 
	global output_type
	output_type = argv[k+1]

def GetPThreshold(argv, k): 
	global pth
	pth = np.float(argv[k+1])

def GetRegionTh(argv, k): 
	global region_th
	region_th = np.float(argv[k+1])

def GetTractFlag(argv, k): 
	global tract_flag
	tract_flag = True

if __name__ == "__main__":
	Vdata = []
	groups = []
	ages = []
	rows = []
	data_shape = []
	analysis_type = 'group'
	tfce_flag = False
	fdr_flag = False
	fdr_alpha = 0.1
	numPerm = 2000
	pth = 2.
	region_th = 0.1
	output_name = './'
	output_type = 'txt'
	tract_flag = False
	ParseInput(sys.argv[1:])
	CheckInputs()
	
	print '--- INFORMATION ON DATA ---'
	print 'number of channels: %d' % len(Vdata)
	print 'number of samples:  %d' % Vdata[0].shape[0]
	print 'number of points:   %d' % Vdata[0].shape[1]
	print 'mean age: %f' % np.mean(ages) 
	print 'std age:  %f' % np.std(ages)
	print 'analysis type: {0}'.format(analysis_type)
	print 'data shape: {0}'.format(data_shape)
	print 'pvalue threshold: %f' % pth
	print '--- ------------------- ---'
	
	rows = rows.reshape(data_shape)
	if analysis_type == 'group': 
		cov_scores, vecs, pvals = GroupAnalysis(Vdata, groups, data_shape, numPerm=numPerm, tfce_flag=tfce_flag, fdr_flag=fdr_flag, rows=rows, alpha=fdr_alpha)

		WriteGroupAnalysisResults(cov_scores, vecs, pvals, output_name, data_shape, rows, pth=pth, wtype=output_type)
	elif analysis_type == 'aging': 
		cov_scores, vecs, pvals = AgingAnalysis(Vdata, ages, data_shape, numPerm=numPerm, tfce_flag=tfce_flag, fdr_flag=fdr_flag, rows=rows, alpha=fdr_alpha)

		WriteGroupAnalysisResults(cov_scores, vecs, pvals, output_name, data_shape, rows, pth=pth, wtype=output_type)
	elif analysis_type == 'regressing_out': 
		cov_scores_orth, cov_scores_par, vecs_orth, pvals_orth, pvals_par = GroupAnalysisRegressingOutAge(Vdata, groups, ages, data_shape, numPerm=numPerm, tfce_flag=tfce_flag, fdr_flag=fdr_flag, rows=rows, alpha=fdr_alpha)
		WriteGroupAnalysisRegressingOutAgeResults(cov_scores_orth, cov_scores_par, vecs_orth, pvals_orth, pvals_par, output_name, data_shape, rows, pth=pth, wtype=output_type)
	elif analysis_type == 'effect_comparison': 
		EffectTypeComparison(Vdata, groups, data_shape, numPerm=numPerm, tfce_flag=tfce_flag, fdr_flag=fdr_flag, rows=rows, alpha=fdr_alpha, region_th=region_th, pth=pth, outName=output_name, wtype=output_type)
	
