def run_hippocampal_segmentation(project_id, subject_id, view, hemisphere):
    ''' Run External Surface Segmentation from ENIGMA cortical pipeline'''    

    local_fs = './freesurfer/' + subject_id
    output_path = './freesurfer/QC'
    current_files = glob.glob(output_path + '/' + subject_id + '/*.png')
    datetime_start = datetime.datetime.now()  
    
    # Run segmentation
    if not os.path.exists(local_fs):
        print("%s: ERROR: Didn't find FreeSurfer output for %s subject. Please run run_freesurfer function first."  (datetime_start,subject_id))
    else:
        
        print("%s: Getting External Surface Segmentation for %s subject..." % (str(datetime_start), subject_id))    
        if len(current_files) > 1:
            datetime_end = datetime.datetime.now()    
            print("%s: External Surface Segmentation was already obtained for %s subject." % (str(datetime_end),subject_id))        
        else:
             
            cmd = ['/bin/bash', './scripts/QC_subfields_step_1_prepare_extension.sh', subject_id, output_path]
            output = utils.run_command(cmd)
            cmd = ['octave-cli', '/NIfTI/QC_subfields_step_2_prepare_extension']
            output = utils.run_command(cmd)
        
            datetime_end = datetime.datetime.now()
            print("%s: Segmentation FINISHED (Total time: %s)." % (str(datetime_end), str(datetime_end-datetime_start)))

        datetime_plot = str(datetime.datetime.now())       
        print("%s: Visualizing results:" % (datetime_plot))
        get_hippocampal_qc(project_id, subject_id, current_files, view, hemisphere)        
def extract_hippocampal_measures(project_id, subject_id):
    ''' Run Hippocampal Measures Extraction for ENIGMA Hippocampal pipeline'''

    subject_path = './freesurfer'
    local_output = subject_path + '/' + subject_id
    datetime_start = datetime.datetime.now()

    # Run Hippocampal measures extraction
    if not os.path.exists(local_output):
        print(
            "%s: ERROR: Didn't find FreeSurfer output for %s subject. Please run run_freesurfer function first."
        )(datetime_start, subject_id)
    else:

        print("%s: Extracting hippocampal measures for %s subject..." %
              (str(datetime_start), subject_id))
        output_file = './results/' + project_id + '/hippo_' + subject_id + '.csv'

        cmd = [
            '/bin/bash', './scripts/extract_subfields.sh', subject_id,
            subject_path, output_file
        ]
        output = utils.run_command(cmd)

        datetime_end = datetime.datetime.now()
        print("%s: Extraction FINISHED (Total time: %s)." %
              (str(datetime_end), str(datetime_end - datetime_start)))

    return output_file
def run_freesurfer_hippocampal(project_id, subject_id, mri_type = "T1-weighted"):
    ''' Run FreeSurfer for ENIGMA Hippocampal pipeline'''

    # Query data
    query_txt = """query {
                      mri_exam(project_id: "%s", scan_type: "%s", with_path_to:{type:"case", submitter_id:"%s"}){
                         mri_images{   
                             file_name
                             id
                         }
                      }
                }""" % (project_id, mri_type, subject_id)
    data = query_api(query_txt)

    # Get file from S3
    filename = data['data']['mri_exam'][0]['mri_images'][0]['file_name']
    fileid = data['data']['mri_exam'][0]['mri_images'][0]['file_name']
    localpath = utils.download_file(auth, api_url, fileid, filename)
    
    # Run freesurfer
    datetime_start = datetime.datetime.now()
    print("%s: Running FreeSurfer for %s subject..." % (str(datetime_start),subject_id))
    local_output = './freesurfer/' + subject_id
    if not os.path.exists(local_output):
        cmd = ['/bin/bash', './scripts/run_freesurfer_hippocampal.sh', subject_id, localpath]
        output = utils.run_command(cmd)
        datetime_end = datetime.datetime.now()
        print("%s: Hippocampal FreeSurfer FINISHED (Total time: %s)." % (str(datetime_end), str(datetime_end-datetime_start)))
    else:
        print("%s: Hippocampal FreeSurfer results were already found for %s subject." % (str(datetime_start), subject_id))
def run_external_segmentation(project_id, subject_id):
    ''' Run External Surface Segmentation from ENIGMA cortical pipeline'''    

    local_fs = './freesurfer/' + subject_id
    output_path = './results/' + project_id
    current_files = glob.glob(output_path + '/' + subject_id + '*.tif')
    datetime_start = datetime.datetime.now()  
    
    # Run segmentation
    if not os.path.exists(local_fs):
        print("%s: ERROR: Didn't find FreeSurfer output for %s subject. Please run run_freesurfer function first."  (datetime_start,subject_id))
    else:
        
        print("%s: Getting External Surface Segmentation for %s subject..." % (str(datetime_start), subject_id))         
        if len(current_files) > 1:
            datetime_end = datetime.datetime.now()    
            print("%s: Segmentation FINISHED: External Surface Segmentation was already obtained for %s subject." % (str(datetime_end),subject_id))       
        else:
             
            cmd = ['/bin/bash', './scripts/fsqc.sh', subject_id, output_path]
            output = utils.run_command(cmd)
        
            datetime_end = datetime.datetime.now()
            print("%s: Segmentation FINISHED (Total time: %s)." % (str(datetime_end), str(datetime_end-datetime_start)))

        datetime_plot = str(datetime.datetime.now())       
        print("%s: Visualizing results:" % (datetime_plot))
        get_external_surface_qc(project_id, subject_id)
def extract_cortical_measures(project_id, subject_id):
    ''' Run Cortical Measures Extraction for ENIGMA cortical pipeline'''

    subject_path = './freesurfer'
    local_output = subject_path + '/' + subject_id
    datetime_start = datetime.datetime.now()

    # Run Cortical measures extraction
    if not os.path.exists(local_output):
        print(
            "%s: ERROR: Didn't find FreeSurfer output for %s subject. Please run run_freesurfer function first."
        )(datetime_start, subject_id)
    else:
        resultDir_forProject = './results/' + project_id
        if not os.path.exists(resultDir_forProject):
            os.system('mkdir -p ' + resultDir_forProject)
        print("%s: Extracting cortical measures for %s subject..." %
              (str(datetime_start), subject_id))

        #output_thickAvg = resultDir_forProject + '/cort_' + subject_id + '_thickAvg.csv'
        #output_surfAvg = resultDir_forProject + '/cort_' + subject_id + '_surfAvg.csv'
        #os.makedirs(os.path.dirname(output_thickAvg))
        #os.makedirs(os.path.dirname(output_surfAvg))
        output_thickAvg = '/home/jovyan/pd/demos/ENIGMA_Cortical_Thickness/results/' + project_id + '/cort_' + subject_id + '_thickAvg.csv'
        output_surfAvg = '/home/jovyan/pd/demos/ENIGMA_Cortical_Thickness/results/' + project_id + '/cort_' + subject_id + '_surfAvg.csv'
        cmd = [
            '/bin/bash', './extract_singleSubject.sh', subject_id,
            subject_path, output_thickAvg, output_surfAvg
        ]
        output = utils.run_command(cmd)

        datetime_end = datetime.datetime.now()
        print("%s: Extraction FINISHED (Total time: %s)." %
              (str(datetime_end), str(datetime_end - datetime_start)))

    return output_thickAvg, output_surfAvg