示例#1
0
def atlasRegistrationBatch(patientsDTI, i):
    #for i in range(len(patientsDTI)):
    sub = patientsDTI[i]

    #input/output paths from QSI prep
    preop3T = join(pathQSIPREP, "qsiprep", f"sub-{sub}", "anat",
                   f"sub-{sub}_desc-preproc_T1w.nii.gz")
    preop3Tmask = join(pathQSIPREP, "qsiprep", f"sub-{sub}", "anat",
                       f"sub-{sub}_desc-brain_mask.nii.gz")
    pathAtlasRegistration = join(pathTractography, f"sub-{sub}",
                                 "atlasRegistration")
    preop3Tbrain = join(pathAtlasRegistration, "brain.nii.gz")
    preop3TSTD = join(pathAtlasRegistration,
                      utils.baseSplitextNiiGz(preop3T)[2] + "_std.nii.gz")
    #preop3TmaskExpand = join(pathAtlasRegistration, "brain_maskExpanded.nii.gz")
    utils.checkPathAndMake(pathTractography, pathAtlasRegistration)

    #MNI registration
    if not utils.checkIfFileExists(
            join(pathAtlasRegistration, "mni_fnirt.nii.gz")):
        #extract brain
        getBrainFromMask(preop3T, preop3Tmask, preop3Tbrain)
        utils.show_slices(preop3Tbrain,
                          save=True,
                          saveFilename=join(pathAtlasRegistration,
                                            "brain.png"))
        #expand Brain mask
        register_MNI_to_preopT1(preop3T, preop3Tbrain, MNItemplatePath,
                                MNItemplateBrainPath, "mni",
                                pathAtlasRegistration)
        utils.show_slices(preop3T,
                          save=True,
                          saveFilename=join(pathAtlasRegistration,
                                            "preop3T.png"))
        utils.show_slices(join(pathAtlasRegistration, "mni_flirt.nii.gz"),
                          save=True,
                          saveFilename=join(pathAtlasRegistration,
                                            "mni_flirt.png"))
        utils.show_slices(join(pathAtlasRegistration, "mni_fnirt.nii.gz"),
                          save=True,
                          saveFilename=join(pathAtlasRegistration,
                                            "mni_fnirt.png"))

    #apply warp to atlases
    applywarp_to_atlas(atlases.getAllAtlasPaths(),
                       preop3TSTD,
                       join(pathAtlasRegistration, "mni_warp.nii.gz"),
                       pathAtlasRegistration,
                       isDir=False)
def make_spherical_regions(patient_list, SESSION, paths, radius = 7, rerun = False, show_slices = False):
    N = len(patient_list)
    for i in range(N):
        sub = patient_list[i]
        print(sub)
        localization, localization_channels = atl.get_atlas_localization_file(sub, SESSION, paths)


        #t1_image = join(paths['BIDS'], "PIER", f"sub-{sub}", f"ses-{ses}", "anat", f"sub-{sub}_ses-{ses}_space-T1w_desc-preproc_dwi.nii.gz" )
        t1_image = glob.glob(join(paths.BIDS_DERIVATIVES_ATLAS_LOCALIZATION, f"sub-{sub}", f"ses-{SESSION}", "tmp", "orig_nu_std.nii.gz" ))[0]
        img = nib.load(t1_image)
        if show_slices: utils.show_slices(img, data_type = "img")
        img_data = img.get_fdata()
        affine = img.affine
        shape = img_data.shape

        coordinates = np.array(localization[["x", "y", "z"]])

        coordinates_voxels = utils.transform_coordinates_to_voxel(coordinates, affine)

        path_spheres = join(paths.BIDS_DERIVATIVES_TRACTOGRAPHY, f"sub-{sub}", "electrodeContactSphereROIs")
        utils.checkPathAndMake(path_spheres, path_spheres, printBOOL = False)

        for e in range(len(localization_channels)):

            fname_ROIs_sub_ID = join(path_spheres, f"sub-{sub}_ses-implant01_desc-{localization_channels[e]}.nii.gz")
            if utils.checkIfFileDoesNotExist(fname_ROIs_sub_ID, printBOOL = False) or rerun:

                img_data_sphere = copy.deepcopy(img_data)
                img_data_sphere[  np.where(img_data_sphere != 0)  ] = 0
                x = coordinates_voxels[e][0]
                y = coordinates_voxels[e][1]
                z = coordinates_voxels[e][2]
                img_data_sphere = utils.make_sphere_from_point(img_data_sphere, x, y, z, radius = radius) #radius = 7mm
                img_sphere = nib.Nifti1Image(img_data_sphere, img.affine)
                nib.save(img_sphere, fname_ROIs_sub_ID)
                #utils.show_slices(img_data_sphere, data_type = "data")
            utils.printProgressBar(e+1, len(localization_channels))
xformPATH = join(path, "xformINV.mat" )



T1img = nib.load(T1PATH)
T1data = T1img.get_fdata() 

T00img = nib.load(T00PATH)
T00data = T00img.get_fdata() 


coordinates = pd.read_csv(coordinatesPATH, header=None)
coordinates = coordinates.iloc[:, [10,11,12]]
coordinates = np.array(coordinates)

utils.show_slices(T1data, isPath=False)


T1img.affine


xform = np.array(pd.read_csv(xformPATH, header=None, sep = "\s\s",engine='python'))





apply_affine(xform, coordinates)[0]


示例#4
0
antsBrainExtraction.sh -d 3 -a antsBTPtemplate0.nii.gz -e /media/arevell/sharedSSD/linux/revellLab/tools/templates/OASIS/T_template0.nii.gz -m /media/arevell/sharedSSD/linux/revellLab/tools/templates/OASIS/T_template0_BrainCerebellumProbabilityMask.nii.gz -k true -o ./template_
"""

#%%Analysis

Tctrl_img = nib.load(join(T1wDirTemplate2, 'antsBTPtemplate0.nii.gz'))
Tctrl_Data = Tctrl_img.get_fdata()

Tpt_img = nib.load(join(T1wDirTemplatePatients01, 'PIER_template0.nii.gz'))
Tpt_Data = Tpt_img.get_fdata()

mask = nib.load(
    join(T1wDir, "brainExtraction", 'template_BrainExtractionMask.nii.gz'))
mask_data = mask.get_fdata()

utils.show_slices(Tctrl_Data, isPath=False)
utils.show_slices(Tpt_Data, isPath=False)
utils.show_slices(mask_data, isPath=False)

Tctrl_Data[np.where(mask_data <= 0)] = 0
Tpt_Data[np.where(mask_data <= 0)] = 0
utils.show_slices(Tctrl_Data, isPath=False)
utils.show_slices(Tpt_Data, isPath=False)
#normalize

Tctrl_DataNORM = Tctrl_Data / np.max(Tctrl_Data)
Tpt_DataNORM = Tpt_Data / np.max(Tpt_Data)

utils.show_slices(Tctrl_DataNORM, isPath=False)
utils.show_slices(Tpt_DataNORM, isPath=False)
        
    img_data[np.where(img_data < -0.99)] = np.nan
    img_data_all[:,:,:,a] = img_data
    count = count +1
    
img_data_avg = np.nanmean(img_data_all, axis = 3)

#removing regions outside brain
brain_mask = glob.glob(join(paths.BIDS_DERIVATIVES_STRUCTURAL_MATRICES, f"sub-{sub}",  f"ses-{ses}", "atlas_registration", "*desc-preproc_T1w_brain_std.nii.gz"))[0]
img_mask_data = utils.load_img_data(brain_mask)
#utils.show_slices(brain_mask)


img_data_avg[np.where(img_mask_data <= 0)] = np.nan

utils.show_slices(img_data_avg, data_type="data", cmap = "viridis")

img, img_data  = utils.load_img_and_data(save_loc_atlas)
utils.save_nib_img_data(img_data_avg, img,  join(save_loc, "average.nii.gz"))





#%% Making pictures of atlases


atlas_names_all_standard = []
for k in range(len(atlas_metadata_json["STANDARD"].keys())):
    key_item = list(atlas_metadata_json["STANDARD"].keys())[k]
    atlas_metadata_json["STANDARD"][key_item]["name"]
示例#6
0
def calculate_mean_rank_deep_learning(i, patientsWithseizures, version, threshold=0.6, smoothing = 20, model_ID="WN", secondsAfter=180, secondsBefore=180, tanh = False):
    #override_soz if True, then if there are no soz marking, then use the resection markings and assume those are SOZ contacts
    RID = np.array(patientsWithseizures["subject"])[i]
    idKey = np.array(patientsWithseizures["idKey"])[i]
    seizure_length = patientsWithseizures.length[i]
    
    
    #CHECKING IF SPREAD FILES EXIST

    fname = DataJson.get_fname_ictal(RID, "Ictal", idKey, dataset= datasetiEEG, session = session, startUsec = None, stopUsec= None, startKey = "EEC", secondsBefore = secondsBefore, secondsAfter = secondsAfter )
    
    spread_location = join(BIDS, datasetiEEG_spread, f"v{version:03d}", f"sub-{RID}" )
    spread_location_file_basename = f"{splitext(fname)[0]}_spread.pickle"
    spread_location_file = join(spread_location, spread_location_file_basename)
    
    
    feature_name = "absolute_slope"
    location_feature = join(BIDS, datasetiEEG_spread, "single_features", f"sub-{RID}" )
    location_abs_slope_basename = f"{splitext(fname)[0]}_{feature_name}.pickle"
    location_abs_slope_file = join(location_feature, location_abs_slope_basename)
    
    feature_name = "line_length"
    location_line_length_basename = f"{splitext(fname)[0]}_{feature_name}.pickle"
    location_line_length_file = join(location_feature, location_line_length_basename)
    
    feature_name = "power_broadband"
    location_power_broadband_basename = f"{splitext(fname)[0]}_{feature_name}.pickle"
    location_power_broadband = join(location_feature, location_power_broadband_basename)
   
    
    if utils.checkIfFileExists( spread_location_file , printBOOL=False) and utils.checkIfFileExists( location_abs_slope_file , printBOOL=False):
        #print("\n\n\n\nSPREAD FILE EXISTS\n\n\n\n")
    
    
    
        #Getting SOZ labels
        RID_keys =  list(jsonFile["SUBJECTS"].keys() )
        hup_num_all = [jsonFile["SUBJECTS"][x]["HUP"]  for  x   in  RID_keys]
        
        hup_int = hup_num_all[RID_keys.index(RID)]
        hup_int_pad = f"{hup_int:03d}" 
        
        i_patient = patients.index(f"HUP{hup_int_pad}")
        HUP = patients[i_patient]
        hup = int(HUP[3:])
        
    
        
        channel_names = labels[i_patient]
        soz_ind = np.where(soz[i_patient] == 1)[0]
        soz_channel_names = np.array(channel_names)[soz_ind]
        
        resected_ind = np.where(resect[i_patient] == 1)[0]
        resected_channel_names = np.array(channel_names)[resected_ind]
        
        ignore_ind = np.where(ignore[i_patient] == 1)[0]
        ignore__channel_names = np.array(channel_names)[ignore_ind]
        
        soz_channel_names = echobase.channel2std(soz_channel_names)
        resected_channel_names = echobase.channel2std(resected_channel_names)
        #ignore__channel_names = echobase.channel2std(ignore__channel_names)
        

        
        soz_channel_names = channel2std_ECoG(soz_channel_names)
        resected_channel_names = channel2std_ECoG(resected_channel_names)
        ignore__channel_names = channel2std_ECoG(ignore__channel_names)
        #%
        THRESHOLD = threshold
        SMOOTHING = smoothing #in seconds
        
    
        
        if model_ID == "WN" or model_ID == "CNN" or model_ID == "LSTM":
            with open(spread_location_file, 'rb') as f:[probWN, probCNN, probLSTM, data_scalerDS, channels, window, skipWindow, secondsBefore, secondsAfter] = pickle.load(f)
            
        
        if model_ID == "WN":
            #print(model_ID)
            prob_array= probWN
        elif model_ID == "CNN":
            #print(model_ID)
            prob_array= probCNN
        elif model_ID == "LSTM":
            #print(model_ID)
            prob_array= probLSTM
        elif model_ID == "absolute_slope":
            if utils.checkIfFileExists(location_abs_slope_file, printBOOL=False):
                with open(location_abs_slope_file, 'rb') as f:[abs_slope_normalized, abs_slope_normalized_tanh, channels, window, skipWindow, secondsBefore, secondsAfter] = pickle.load(f)
                if not tanh:
                    #abs_slope_normalized = utils.apply_arctanh(abs_slope_normalized_tanh)/1e-1 
                    abs_slope_normalized/np.max(abs_slope_normalized)
                    abs_slope_normalized = abs_slope_normalized/np.max(abs_slope_normalized)
                    prob_array=  abs_slope_normalized
                else:
                    prob_array= abs_slope_normalized_tanh
            else: 
                print(f"{i} {RID} file does not exist {location_abs_slope_file}\n")
        elif model_ID == "line_length":
            if utils.checkIfFileExists(location_line_length_file, printBOOL=False):
                with open(location_line_length_file, 'rb') as f:[probLL, probLL_tanh, channels, window, skipWindow, secondsBefore, secondsAfter] = pickle.load(f)
                if not tanh:
                    probLL = probLL/np.max(probLL)
                    prob_array= probLL
                else:
                    prob_array= probLL_tanh
            else: 
                print(f"{i} {RID} file does not exist {location_line_length_file}\n")
        elif model_ID == "power_broadband":
            if utils.checkIfFileExists(location_power_broadband, printBOOL=False):
                with open(location_power_broadband, 'rb') as f:[power_total, power_total_tanh, channels, window, skipWindow, secondsBefore, secondsAfter] = pickle.load(f)
                if not tanh:
                    #power_total = utils.apply_arctanh(power_total_tanh)/7e-2  
                    power_total = power_total/np.max(power_total)
                    prob_array=  power_total
                    
                else:
                    prob_array= power_total_tanh
            
            else: 
                print(f"{i} {RID} file does not exist {location_power_broadband}\n")
        else:
            print("model ID not recognized. Using Wavenet")
            prob_array= probWN
        
        #####
        seizure_start = int((secondsBefore-0)/skipWindow)
        seizure_stop = int((secondsBefore + seizure_length)/skipWindow)
        
        probability_arr_movingAvg, probability_arr_threshold = prob_threshold_moving_avg(prob_array, fsds, skip, threshold = THRESHOLD, smoothing = SMOOTHING)
        #sns.heatmap( probability_arr_movingAvg.T )      
        #sns.heatmap( probability_arr_threshold.T)    
        spread_start, seizure_start, spread_start_loc, channel_order, channel_order_labels = get_start_times(secondsBefore, skipWindow, fsds, channels, 0, seizure_length, probability_arr_threshold)
   
        
        channel_order_labels = remove_EGG_and_ref(channel_order_labels)
        channels2 = remove_EGG_and_ref(channels)
        
        channel_order_labels = channel2std_ECoG(channel_order_labels)
        channels2 = channel2std_ECoG(channels2)
        
        #print(soz_channel_names)
        #print(resected_channel_names)
        #print(channel_order_labels)
    
    
        #remove ignore electrodes from channel_order_labels
        #ignore_index = np.intersect1d(  channel_order_labels, ignore__channel_names, return_indices=True)
        #channel_order_labels[-ignore_index[1]]
        #channel_order_labels = np.delete(channel_order_labels, ignore_index[1])
        
        
        atlas_localization_path = join(paths.BIDS_DERIVATIVES_ATLAS_LOCALIZATION, f"sub-{RID}", f"ses-{session}", f"sub-{RID}_ses-{session}_desc-atlasLocalization.csv")
        if utils.checkIfFileExists(atlas_localization_path, printBOOL=False):
            atlas_localization = pd.read_csv(atlas_localization_path)
            
            
            atlas_localization.channel = channel2std_ECoG(atlas_localization.channel)
            
            
            for r in range(len(atlas_localization)):
                reg_AAL = atlas_localization.AAL_label[r]
                reg_BNA = atlas_localization.BN_Atlas_246_1mm_label[r]
                reg_HO = atlas_localization["HarvardOxford-combined_label"][r]
                
                
        coord_start_times = pd.DataFrame(columns = ["channel", "x", "y", "z", "start_time"])
        
        coord_start_times["channel"] = channels2
        
        for ch in range(len(coord_start_times)):
            x = np.array(atlas_localization[channels2[ch]  == atlas_localization.channel]["x"])[0]
            y = np.array(atlas_localization[channels2[ch]  == atlas_localization.channel]["y"])[0]
            z = np.array(atlas_localization[channels2[ch]  == atlas_localization.channel]["z"])[0]
            
            x = np.array(atlas_localization[channels2[ch]  == atlas_localization.channel]["x"])[0]
            y = np.array(atlas_localization[channels2[ch]  == atlas_localization.channel]["y"])[0]
            z = np.array(atlas_localization[channels2[ch]  == atlas_localization.channel]["z"])[0]
            
            
            coord_start_times.loc[coord_start_times["channel"] == coord_start_times["channel"][ch]   ,    "x"] = x
            coord_start_times.loc[coord_start_times["channel"] == coord_start_times["channel"][ch]   ,    "y"] = y
            coord_start_times.loc[coord_start_times["channel"] == coord_start_times["channel"][ch]   ,    "z"] = z
            
            spread_start
            
            channel_start = spread_start[coord_start_times["channel"][ch] == channels2 ] * skipWindow
            if len(channel_start) > 0:
                channel_start = channel_start[0]
                if channel_start > seizure_length:
                    channel_start = np.nan
            else:
                channel_start = np.nan
            coord_start_times.loc[coord_start_times["channel"] == coord_start_times["channel"][ch]   ,    "start_time"] = channel_start
          
            
        t1_image = glob.glob(join(paths.BIDS_DERIVATIVES_ATLAS_LOCALIZATION, f"sub-{RID}", f"ses-implant01", "tmp", "orig_nu_std.nii.gz" ))[0]
        t1_image_brain = glob.glob(join(paths.BIDS_DERIVATIVES_ATLAS_LOCALIZATION, f"sub-{RID}", f"ses-implant01", "tmp", "brain_std.nii.gz" ))[0]
        img = nib.load(t1_image)
        img_brain = nib.load(t1_image_brain)
        #utils.show_slices(img, data_type = "img")
        img_data = img.get_fdata()
        brain_data = img_brain.get_fdata()
        affine = img.affine
        shape = img_data.shape
        img_data_total = copy.deepcopy(img_data)
        img_data_total[  np.where(img_data_total != 0)  ] = 0
        
        img_data_N = copy.deepcopy(img_data)
        img_data_N[  np.where(img_data_N != 0)  ] = 0
        
        
       
        for ch in range(len(coord_start_times)):
            print(f"\r{ch}/{len(coord_start_times)}    ", end = "\r")
            coord = coord_start_times.iloc[ch]
            radius = 40
            
            img_data_sphere = copy.deepcopy(img_data)
            img_data_sphere[  np.where(img_data_sphere != 0)  ] = 0
            
            coordinates = np.array(coord[["x", "y", "z"]]).astype(float)
            coordinates_voxels = utils.transform_coordinates_to_voxel(coordinates, affine)
            x,y,z = coordinates_voxels[0],coordinates_voxels[1],coordinates_voxels[2]
            sphere = utils.make_sphere_from_point(img_data_sphere, x,   y,  z, radius = radius)
            if not np.isnan(coord_start_times.start_time[ch]):
                img_data_N = img_data_N + sphere
                sphere[np.where(sphere >0)] = coord_start_times.start_time[ch]
                img_data_total = img_data_total + sphere
            
            #utils.show_slices(sphere, data_type = "data")
            
        utils.show_slices(img_data_N, data_type = "data")
        utils.show_slices(img_data_total, data_type = "data", cmap = "mako")
        
        
        utils.show_slices(brain_data, data_type = "data")
        
    
    
        img_data_avg = img_data_total/img_data_N
        img_data_avg[np.where(brain_data <= 0)] = np.nan
        
        utils.show_slices(img, data_type = "img")
        utils.show_slices(img_data_avg, data_type = "data", cmap = "mako")
        
        #img_data_avg[np.isnan(img_data_avg)] = seizure_length
        
        low, middle, high = 0.33,0.48,0.7
        slices_t1 = [   img_data[:, int((img_data.shape[1]*low)), : ] , img_data[:, int(img_data.shape[1]*middle), :] , img_data[:, int(img_data.shape[1]*high), :]   ]
        slices_heat = [   img_data_avg[:, int((img_data_avg.shape[1]*low)), : ] , img_data_avg[:, int(img_data_avg.shape[1]*middle), :] , img_data_avg[:, int(img_data_avg.shape[1]*high), :]   ]
        slices_brain = [   brain_data[:, int((brain_data.shape[1]*low)), : ] , brain_data[:, int(brain_data.shape[1]*middle), :] , brain_data[:, int(brain_data.shape[1]*high), :]   ]
        
        cmap1 = "gray"
        cmap2 = "Wistia_r"
        """
        fig, axes = utils.plot_make()
        #sns.heatmap(slices_t1[1], cmap=cmap1, ax = axes, square = True)
        axes.imshow(slices_t1[1].T, cmap=cmap1, origin="lower")
        pos = axes.imshow(slices_heat[1].T, cmap=cmap2, origin="lower")
        fig.colorbar(pos, ax=axes)
        """
        slice_image = slices_heat[1]
        
        mask = np.where(~np.isnan(slice_image))
        interp = interpolate.NearestNDInterpolator(np.transpose(mask), slice_image[mask])
        filled_data = interp(*np.indices(slice_image.shape))
        
        filled_data_copy_gaussian = scipy.ndimage.gaussian_filter(filled_data, sigma = 2)
        
        filled_data_copy = copy.deepcopy(filled_data_copy_gaussian)
        filled_data_copy[np.where(slices_brain[1] <= 0)] = np.nan

        plt.style.use('default')
        cmap1 = "gray"
        cmap2 = "Spectral"
        fig, axes = utils.plot_make()
        axes.imshow(slices_t1[1].T, cmap=cmap1, origin="lower")
        pos = axes.imshow(filled_data_copy.T, cmap=cmap2, origin="lower")
        fig.colorbar(pos, ax=axes)
    

        
        plt.savefig(join(paths.SEIZURE_SPREAD_FIGURES, "spread_by_coordinates", "spread_by_coordinates2.pdf"))
#%%Begin Pipeline: Orient all images to standard RAS

print(
    f"\n\n{fillerString}Part 1 of 4\nReorientation of Images\nEstimated time: 10-30 seconds{fillerString}\nReorient all images to standard RAS\n"
)
cmd = f"fslreorient2std {preop_T1} {preop_T1_std}"
print(cmd)
os.system(cmd)
cmd = f"fslreorient2std {preop_T1_bet} {preop_T1_bet_std}"
print(cmd)
os.system(cmd)

#visualize
utils.show_slices(f"{preop_T1_std}",
                  low=0.33,
                  middle=0.5,
                  high=0.66,
                  save=True,
                  saveFilename=join(atlas_registration, "pic_T1.png"))
utils.show_slices(f"{preop_T1_bet_std}",
                  low=0.33,
                  middle=0.5,
                  high=0.66,
                  save=True,
                  saveFilename=join(atlas_registration, "pic_T1_brain.png"))

#%%Registration of MNI to patient space (atlases are all in MNI space, so using this warp to apply to the atlases)
print(
    f"\n\n{fillerString}Part 3 of 4\nMNI and atlas registration\nEstimated time: 1-2+ hours{fillerString}\nRegistration of MNI template to patient space\n"
)

#linear reg of MNI to preopT1 space
示例#8
0
print(cmd)
os.system(cmd)

print("\n\n\nReslice all standard RAS images to 1x1x1mm voxels\n")
#Make images 1x1x1 mm in size (usually clinical images from electrodeLocalization pipelines are 0.98x0.98x1; others are even more different than 1x1x1)
cmd = f"flirt -in {preopT1_output}_std.nii.gz -ref {preopT1_output}_std.nii.gz -applyisoxfm 1.0 -nosearch -out {preopT1_output}_std1x1x1.nii.gz"
print(cmd)
os.system(cmd)
cmd = f"flirt -in {preopT1bet_output}_std.nii.gz -ref {preopT1bet_output}_std.nii.gz -applyisoxfm 1.0 -nosearch -out {preopT1bet_output}_std1x1x1.nii.gz"
print(cmd)
os.system(cmd)

#visualize
utils.show_slices(f"{preopT1_output}_std1x1x1.nii.gz",
                  low=0.33,
                  middle=0.5,
                  high=0.66,
                  save=True,
                  saveFilename=join(outputDirectory, "pic_T00.png"))
utils.show_slices(f"{preopT1bet_output}_std1x1x1.nii.gz",
                  low=0.33,
                  middle=0.5,
                  high=0.66,
                  save=True,
                  saveFilename=join(outputDirectory, "pic_T00bet.png"))

print(
    f"\n\nPictures are saved to {outputDirectory}\nPlease check for quality assurance"
)

#%%Tissue segmentation
print(
示例#9
0
def mni_registration_to_T1(sub,
                           paths,
                           SESSION_RESEARCH3T="research3Tv[0-9][0-9]"):

    #getting directories and files

    #structural connectivity derivatives
    atlas_registration, structural_matrices, mni_images, mni_warp, ses, preop_T1, preop_T1_std, path_fib, path_trk = get_atlas_registration_and_tractography_paths(
        sub=sub, paths=paths, SESSION_RESEARCH3T=SESSION_RESEARCH3T)

    if not utils.checkIfFileExists(f"{mni_images}_fnirt.nii.gz",
                                   printBOOL=False):

        #QSI prep outputs
        preop_T1 = os.path.join(paths.BIDS_DERIVATIVES_QSIPREP, "qsiprep",
                                f"sub-{sub}", "anat",
                                f"sub-{sub}_desc-preproc_T1w.nii.gz")
        preop_T1_mask = os.path.join(paths.BIDS_DERIVATIVES_QSIPREP, "qsiprep",
                                     f"sub-{sub}", "anat",
                                     f"sub-{sub}_desc-brain_mask.nii.gz")
        preop_T1_bet = os.path.join(
            atlas_registration, f"sub-{sub}_desc-preproc_T1w_brain.nii.gz")

        #checking all images exist
        utils.checkPathError(preop_T1)
        utils.checkPathError(preop_T1_mask)
        utils.checkPathError(paths.MNI_TEMPLATE)
        utils.checkPathError(paths.MNI_TEMPLATE_BRAIN)

        #copying relevant images from QSI prep to registration folder
        cmd = f"cp  {preop_T1} {os.path.join(atlas_registration, os.path.basename(preop_T1))}"
        os.system(cmd)
        cmd = f"cp  {preop_T1_mask} {os.path.join(atlas_registration, os.path.basename(preop_T1_mask))}"
        os.system(cmd)
        cmd = f"fslmaths  {preop_T1} -mul {preop_T1_mask} {preop_T1_bet}"
        os.system(cmd)

        #intemediary files output names
        preop_T1 = os.path.join(atlas_registration, os.path.basename(preop_T1))
        preop_T1_mask = os.path.join(atlas_registration,
                                     os.path.basename(preop_T1_mask))

        preop_T1_std = f"{splitext(splitext(preop_T1)[0])[0]}_std.nii.gz"
        preop_T1_bet_std = f"{splitext(splitext(preop_T1_bet)[0])[0]}_std.nii.gz"

        #Begin Pipeline: Orient all images to standard RAS

        fillerString = "\n###########################" * 3
        print(
            f"\n\n{fillerString}\nPart 1 of 2\nReorientation of Images\nEstimated time: 10-30 seconds{fillerString}\nReorient all images to standard RAS\n"
        )
        cmd = f"fslreorient2std {preop_T1} {preop_T1_std}"
        print(cmd)
        os.system(cmd)
        cmd = f"fslreorient2std {preop_T1_bet} {preop_T1_bet_std}"
        print(cmd)
        os.system(cmd)

        #visualize
        utils.show_slices(f"{preop_T1_std}",
                          low=0.33,
                          middle=0.5,
                          high=0.66,
                          save=True,
                          saveFilename=join(atlas_registration, "pic_T1.png"))
        utils.show_slices(f"{preop_T1_bet_std}",
                          low=0.33,
                          middle=0.5,
                          high=0.66,
                          save=True,
                          saveFilename=join(atlas_registration,
                                            "pic_T1_brain.png"))

        #Registration of MNI to patient space (atlases are all in MNI space, so using this warp to apply to the atlases)
        print(
            f"\n\n{fillerString}\nPart 2 of 2\nMNI and atlas registration\nEstimated time: 1-2+ hours{fillerString}\nRegistration of MNI template to patient space\n"
        )

        #linear reg of MNI to preopT1 space
        if not utils.checkIfFileExists(f"{mni_images}_flirt.nii.gz",
                                       printBOOL=False):
            cmd = f"flirt -in {paths.MNI_TEMPLATE_BRAIN} -ref {preop_T1_bet_std} -dof 12 -out {mni_images}_flirt -omat {mni_images}_flirt.mat -v"
            print(cmd)
            os.system(cmd)
        #non linear reg of MNI to preopT1 space
        utils.show_slices(f"{mni_images}_flirt.nii.gz",
                          low=0.33,
                          middle=0.5,
                          high=0.66,
                          save=True,
                          saveFilename=join(atlas_registration,
                                            "pic_mni_to_T1_flirt.png"))
        print(
            "\n\nLinear registration of MNI template to image is done\n\nStarting Non-linear registration:\n\n\n"
        )
        if not utils.checkIfFileExists(f"{mni_images}_fnirt.nii.gz",
                                       printBOOL=False):
            cmd = f"fnirt --in={paths.MNI_TEMPLATE} --ref={preop_T1_std} --aff={mni_images}_flirt.mat --iout={mni_images}_fnirt -v --cout={mni_images}_coef --fout={mni_images}_warp"
            print(cmd)
            os.system(cmd)
        utils.show_slices(f"{mni_images}_fnirt.nii.gz",
                          low=0.33,
                          middle=0.5,
                          high=0.66,
                          save=True,
                          saveFilename=join(atlas_registration,
                                            "pic_mni_to_T1_fnirt.png"))
        print(f"\n\n{fillerString}\nDone{fillerString}\n\n\n\n")
    else:
        print(f"\n\n\n\nMNI registration already performed\n\n\n\n")