original_fp = '/home/grg/spm/analyses/analysis_20170228/MD_DARTEL_csf5_interaction_linearage/estimatecontrasts/spmT_0028.nii'
thresholded_map, threshold = thresholding.map_threshold(original_fp, threshold=1e-3)
thresholded_fp = '/tmp/thresholded_map.nii.gz'
thresholded_map.to_filename(thresholded_fp)  # Save it on disk

"""
Explanation: Kind recipe to extract clusters from thresholded SPMt maps and make them as a map of ROIs
First threshold your SPMt map
End of explanation
"""



roi_dir = '/home/grg/spm/ROIapoE/ROI_DARTEL/csf5/'
rois_fp = [e for e in glob(osp.join(roi_dir, '*.nii.gz')) if not '_cleaned' in e and not 'rois' in e]
print rois_fp
print len(rois_fp), 'files found.'

"""
Explanation: Define a folder containing rough hand-drawn ROIs over the clusters
The given names are very approximative with respect to the rough location of the cluster.
End of explanation
"""


thresholded_img = np.asarray(nib.load(thresholded_fp).dataobj)

for roi_fp in rois_fp:
    print roi_fp
    roi = np.array(image.load_img(roi_fp).dataobj)
    roi[thresholded_img==0] = 0
    img = image.new_img_like(roi_fp, roi)
    plotting.plot_roi(img)
    img.to_filename(osp.splitext(roi_fp)[0] + '_cleaned.nii.gz')

"""
Explanation: Take each hand-drawn ROI and generate a cleaned version of it using the intersection with the thresholded map
End of explanation
"""


rois_fp = '/tmp/rois2.nii.gz' # File where the ROIs will be collected
roi_fps = glob(osp.join(roi_dir, '*_cleaned.nii.gz'))
print roi_fps
print len(roi_fps), 'cleaned ROIs found'

img = np.asarray(image.load_img(roi_fps[0]).dataobj)
for i in range(1, len(roi_fps)):
    new_img = np.asarray(image.load_img(roi_fps[i]).dataobj)
    img[new_img!=0] = i+1
    
finalimg = image.new_img_like(roi_fps[0], img)
finalimg.to_filename(rois_fp)
plotting.plot_roi(finalimg)

"""
Explanation: Collect all the cleaned ROIs in a single Nifti
End of explanation
"""


roivalues_wd = '/tmp/roivalues_csf.5' # Folder where the files containing the ROI values will be stored
data_wd = '/home/grg/dartel_csf.5/' # Folder containing the images over which the ROI values will be extracted

subjects = json.load(open(osp.join('/home/grg/spm', 'data', 'subjects.json'))) # List of subjects

# Load the collection of ROIs
rois = np.asarray(nib.load(rois_fp).dataobj)
nb_roi = len(np.unique(rois)) - 1
print nb_roi, 'regions - ', len(subjects), 'subjects'

# Iterate over subjects
for s in subjects:
    try:
        mdfp = glob(osp.join(data_wd, 'rswr%s*.nii'%s))[0]
        # Build the command and run it
        cmd = 'AimsRoiFeatures -i %s -s %s -o %s'%(rois_fp, mdfp, osp.join(roivalues_wd, '%s_stats.csv'%s))
        print cmd
        os.system(cmd)
    except Exception as e:
        print s, e

"""
Explanation: Compile values from create ROI
End of explanation
"""


%run /home/grg/git/alfa/roicollect.py
%matplotlib inline
from IPython.display import display
data = pd.read_excel('/tmp/covariates.xls') # a table containing ApoE group, gender, educational years, ventricles
data['subject'] = data.index # Adding subject as an extra column
display(data.head())

regions = [0,1] #list(np.unique(rois))
regions.remove(0)
plot_regions(data, regions, src=roivalues_wd)

"""
Explanation: Generate a plot with these ROI values
With relation to age, grouping subjects by genotypes, and correcting values for covariates
End of explanation
"""


