def __init__(self, in_file='path', **options): from nipype.interfaces.fsl import ExtractROI fslroi = ExtractROI() fslroi.inputs.in_file = in_file for ef in options: setattr(fslroi.inputs, ef, options[ef]) self.res = fslroi.run()
def fslmath_ExtractROI_T(input_file, tmin, tsize, out_prefix): from nipype.interfaces.fsl import ExtractROI import os splitM = ExtractROI() splitM.inputs.in_file = input_file splitM.inputs.t_min = tmin splitM.inputs.t_size = tsize splitM.inputs.output_type = 'NIFTI_GZ' print "ExtractROI [" + os.path.basename(input_file) + "]:" + splitM.cmdline res = splitM.run() outfile = d2s.move_to_results(res.outputs.roi_file, out_prefix) return outfile
def preproc(data_dir, sink_dir, subject, task, session, run, masks, motion_thresh, moco): from nipype.interfaces.fsl import MCFLIRT, FLIRT, FNIRT, ExtractROI, ApplyWarp, MotionOutliers, InvWarp, FAST #from nipype.interfaces.afni import AlignEpiAnatPy from nipype.interfaces.utility import Function from nilearn.plotting import plot_anat from nilearn import input_data #WRITE A DARA GRABBER def get_niftis(subject_id, data_dir, task, run, session): from os.path import join, exists t1 = join(data_dir, subject_id, 'session-{0}'.format(session), 'anatomical', 'anatomical-0', 'anatomical.nii.gz') #t1_brain_mask = join(data_dir, subject_id, 'session-1', 'anatomical', 'anatomical-0', 'fsl', 'anatomical-bet.nii.gz') epi = join(data_dir, subject_id, 'session-{0}'.format(session), task, '{0}-{1}'.format(task, run), '{0}.nii.gz'.format(task)) assert exists(t1), "t1 does not exist at {0}".format(t1) assert exists(epi), "epi does not exist at {0}".format(epi) standard = '/home/applications/fsl/5.0.8/data/standard/MNI152_T1_2mm.nii.gz' return t1, epi, standard data = Function( function=get_niftis, input_names=["subject_id", "data_dir", "task", "run", "session"], output_names=["t1", "epi", "standard"]) data.inputs.data_dir = data_dir data.inputs.subject_id = subject data.inputs.run = run data.inputs.session = session data.inputs.task = task grabber = data.run() if session == 0: sesh = 'pre' if session == 1: sesh = 'post' #reg_dir = '/home/data/nbc/physics-learning/data/first-level/{0}/session-1/retr/retr-{1}/retr-5mm.feat/reg'.format(subject, run) #set output paths for quality assurance pngs qa1 = join( sink_dir, 'qa', '{0}-session-{1}_{2}-{3}_t1_flirt.png'.format(subject, session, task, run)) qa2 = join( sink_dir, 'qa', '{0}-session-{1}_{2}-{3}_mni_flirt.png'.format(subject, session, task, run)) qa3 = join( sink_dir, 'qa', '{0}-session-{1}_{2}-{3}_mni_fnirt.png'.format(subject, session, task, run)) confound_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_confounds.txt'.format(subject, session, task, run)) #run motion correction if indicated if moco == True: mcflirt = MCFLIRT(ref_vol=144, save_plots=True, output_type='NIFTI_GZ') mcflirt.inputs.in_file = grabber.outputs.epi #mcflirt.inputs.in_file = join(data_dir, subject, 'session-1', 'retr', 'retr-{0}'.format(run), 'retr.nii.gz') mcflirt.inputs.out_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mcf.nii.gz'.format( subject, session, task, run)) flirty = mcflirt.run() motion = np.genfromtxt(flirty.outputs.par_file) else: print "no moco needed" motion = 0 #calculate motion outliers try: mout = MotionOutliers(metric='fd', threshold=motion_thresh) mout.inputs.in_file = grabber.outputs.epi mout.inputs.out_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_fd-gt-{3}mm'.format( subject, session, task, run, motion_thresh)) mout.inputs.out_metric_plot = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_metrics.png'.format( subject, session, task, run)) mout.inputs.out_metric_values = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_fd.txt'.format(subject, session, task, run)) moutliers = mout.run() outliers = np.genfromtxt(moutliers.outputs.out_file) e = 'no errors in motion outliers, yay' except Exception as e: print(e) outliers = np.genfromtxt(mout.inputs.out_metric_values) #set everything above the threshold to 1 and everything below to 0 outliers[outliers > motion_thresh] = 1 outliers[outliers < motion_thresh] = 0 #concatenate motion parameters and motion outliers to form confounds file #outliers = outliers.reshape((outliers.shape[0],1)) conf = outliers np.savetxt(confound_file, conf, delimiter=',') #extract an example volume for normalization ex_fun = ExtractROI(t_min=144, t_size=1) ex_fun.inputs.in_file = flirty.outputs.out_file ex_fun.inputs.roi_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}-example_func.nii.gz'.format( subject, session, task, run)) fun = ex_fun.run() warp = ApplyWarp(interp="nn", abswarp=True) if not exists( '/home/data/nbc/physics-learning/data/first-level/{0}/session-{1}/{2}/{2}-{3}/{2}-5mm.feat/reg/example_func2standard_warp.nii.gz' .format(subject, session, task, run)): #two-step normalization using flirt and fnirt, outputting qa pix flit = FLIRT(cost_func="corratio", dof=12) reg_func = flit.run( reference=fun.outputs.roi_file, in_file=grabber.outputs.t1, searchr_x=[-180, 180], searchr_y=[-180, 180], out_file=join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_t1-flirt.nii.gz'.format( subject, session, task, run)), out_matrix_file=join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_t1-flirt.mat'.format( subject, session, task, run))) reg_mni = flit.run( reference=grabber.outputs.t1, in_file=grabber.outputs.standard, searchr_y=[-180, 180], searchr_z=[-180, 180], out_file=join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mni-flirt-t1.nii.gz'.format( subject, session, task, run)), out_matrix_file=join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mni-flirt-t1.mat'.format( subject, session, task, run))) #plot_stat_map(aligner.outputs.out_file, bg_img=fun.outputs.roi_file, colorbar=True, draw_cross=False, threshold=1000, output_file=qa1a, dim=-2) display = plot_anat(fun.outputs.roi_file, dim=-1) display.add_edges(reg_func.outputs.out_file) display.savefig(qa1, dpi=300) display.close() display = plot_anat(grabber.outputs.t1, dim=-1) display.add_edges(reg_mni.outputs.out_file) display.savefig(qa2, dpi=300) display.close() perf = FNIRT(output_type='NIFTI_GZ') perf.inputs.warped_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mni-fnirt-t1.nii.gz'.format( subject, session, task, run)) perf.inputs.affine_file = reg_mni.outputs.out_matrix_file perf.inputs.in_file = grabber.outputs.standard perf.inputs.subsampling_scheme = [8, 4, 2, 2] perf.inputs.fieldcoeff_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mni-fnirt-t1-warpcoeff.nii.gz'.format( subject, session, task, run)) perf.inputs.field_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mni-fnirt-t1-warp.nii.gz'.format( subject, session, task, run)) perf.inputs.ref_file = grabber.outputs.t1 reg2 = perf.run() warp.inputs.field_file = reg2.outputs.field_file #plot fnirted MNI overlaid on example func display = plot_anat(grabber.outputs.t1, dim=-1) display.add_edges(reg2.outputs.warped_file) display.savefig(qa3, dpi=300) display.close() else: warpspeed = InvWarp(output_type='NIFTI_GZ') warpspeed.inputs.warp = '/home/data/nbc/physics-learning/data/first-level/{0}/session-{1}/{2}/{2}-{3}/{2}-5mm.feat/reg/example_func2standard_warp.nii.gz'.format( subject, session, task, run) warpspeed.inputs.reference = fun.outputs.roi_file warpspeed.inputs.inverse_warp = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_mni-fnirt-t1-warp.nii.gz'.format( subject, session, task, run)) mni2epiwarp = warpspeed.run() warp.inputs.field_file = mni2epiwarp.outputs.inverse_warp for key in masks.keys(): #warp takes us from mni to epi warp.inputs.in_file = masks[key] warp.inputs.ref_file = fun.outputs.roi_file warp.inputs.out_file = join( sink_dir, sesh, subject, '{0}-session-{1}_{2}-{3}_{4}.nii.gz'.format( subject, session, task, run, key)) net_warp = warp.run() qa_file = join( sink_dir, 'qa', '{0}-session-{1}_{2}-{3}_qa_{4}.png'.format( subject, session, task, run, key)) display = plotting.plot_roi(net_warp.outputs.out_file, bg_img=fun.outputs.roi_file, colorbar=True, vmin=0, vmax=18, draw_cross=False) display.savefig(qa_file, dpi=300) display.close() return flirty.outputs.out_file, confound_file, e
# get fileparts of input path_file, name_file, ext_file = get_filename(file_in[i]) # filenames file_vol0 = os.path.join(path_file, name_file + "_vol0" + ext_file) file_out = os.path.join(path_file, name_file + "_gnlcorr" + ext_file) # extract first volume fslroi = ExtractROI() fslroi.inputs.in_file = file_in[i] fslroi.inputs.roi_file = file_vol0 fslroi.inputs.output_type = "NIFTI" fslroi.inputs.t_min = 0 fslroi.inputs.t_size = 1 fslroi.run() # exexute gnl correction gnl_correction(file_vol0, file_bash, file_coeff, python3_env, python2_env, path_file, False) # apply warp to first volume applywarp = ApplyWarp() applywarp.inputs.in_file = file_in[i] applywarp.inputs.ref_file = file_in[i] applywarp.inputs.relwarp = True applywarp.inputs.field_file = os.path.join(path_file, "grad", "warp.nii.gz") applywarp.inputs.output_type = "NIFTI" applywarp.inputs.out_file = file_out applywarp.inputs.interp = "spline"
DWI_FMAP=list(filter(lambda x: "_dwi.nii.gz" in x, FMAP_SCANS)) if OPT_GEN_FMAP_DWI == "TRUE" and DWI_SCANS and DWI_FMAP: JSON=list(filter(lambda x: "_dwi.json" in x, DWI_SCANS))[0] NIFTI=list(filter(lambda x: "_dwi.nii.gz" in x, DWI_SCANS))[0] CONTENT=json.load(open(JSON), object_pairs_hook=OrderedDict) PHASE_NEW=DICT_DIR.get(CONTENT.get("PhaseEncodingDirection")) TEMP_OUTPUT=list(filter(lambda x: "_dwi.nii.gz" in x, FMAP_SCANS))[0].replace("","") OUTPUT=TEMP_OUTPUT.replace([x for x in TEMP_OUTPUT.split("_") if "acq-" in x][0],"acq-{}".format(PHASE_NEW)) Extract = ExtractROI( in_file=NIFTI, roi_file=OUTPUT, output_type="NIFTI_GZ", t_min=0, t_size=1) Extract.run() json.dump(CONTENT, open(OUTPUT.replace("nii.gz","json"), "w"), indent=12) FMAP_SCANS=list(filter(lambda x:'/fmap/sub-' in x, directory_structure(DIR_SUB))) ############################################################# ### Create Directionary Keys of Task Names for FUNC Scans ### ############################################################# if FUNC_SCANS: FUNC_JSONS=list(filter(lambda x:'bold.json' in x, FUNC_SCANS)) for FUNC_JSON in FUNC_JSONS: if any(not 'task-' for elem in os.path.basename(FUNC_JSON).split("_")): Error = open(os.path.join('.', 'Fatal_BIDS_Error.txt'), 'w') Error.write('BOLD Labels Do Not Include Task Name') Error.close() sys.exit()
def convert_single_subject(subj_folder): import os import nibabel as nb import numpy as np t1_folder = path.join(subj_folder, "PROCESSED", "MPRAGE", "SUBJ_111") subj_id = os.path.basename(subj_folder) print("Converting ", subj_id) numerical_id = (subj_id.split("_"))[1] bids_id = "sub-OASIS1" + str(numerical_id) bids_subj_folder = path.join(dest_dir, bids_id) if not os.path.isdir(bids_subj_folder): os.mkdir(bids_subj_folder) session_folder = path.join(bids_subj_folder, "ses-M00") if not os.path.isdir(session_folder): os.mkdir(path.join(session_folder)) os.mkdir(path.join(session_folder, "anat")) # In order do convert the Analyze format to Nifti the path to the .img file is required img_file_path = glob(path.join(t1_folder, "*.img"))[0] output_path = path.join( session_folder, "anat", bids_id + "_ses-M00_T1w.nii.gz" ) # First, convert to Nifti so that we can extract the s_form with NiBabel # (NiBabel creates an 'Spm2AnalyzeImage' object that does not contain 'get_sform' method img_with_wrong_orientation_analyze = nb.load(img_file_path) # OASIS-1 images have the same header but sform is incorrect # To solve this issue, we use header from images converted with FreeSurfer # to generate a 'clean hard-coded' header # affine: # [[ 0. 0. -1. 80.] # [ 1. 0. 0. -128.] # [ 0. 1. 0. -128.] # [ 0. 0. 0. 1.]] # fmt: off affine = np.array( [ 0, 0, -1, 80, 1, 0, 0, -128, 0, 1, 0, -128, 0, 0, 0, 1 ] ).reshape(4, 4) # fmt: on s_form = affine.astype(np.int16) hdr = nb.Nifti1Header() hdr.set_data_shape((256, 256, 160)) hdr.set_data_dtype(np.int16) hdr["bitpix"] = 16 hdr.set_sform(s_form, code="scanner") hdr.set_qform(s_form, code="scanner") hdr["extents"] = 16384 hdr["xyzt_units"] = 10 img_with_good_orientation_nifti = nb.Nifti1Image( np.round(img_with_wrong_orientation_analyze.get_data()).astype( np.int16 ), s_form, header=hdr, ) nb.save(img_with_good_orientation_nifti, output_path) # Header correction to obtain dim0 = 3 fslroi = ExtractROI( in_file=output_path, roi_file=output_path, t_min=0, t_size=1 ) fslroi.run()