示例#1
0
def create_nifti_corrs_brain(corrs_atlas, sub, paths, SESSION_RESEARCH3T,
                             atlas_name):
    ses = basename(
        glob.glob(
            join(paths.BIDS_DERIVATIVES_STRUCTURAL_MATRICES, f"sub-{sub}",
                 f"ses-{SESSION_RESEARCH3T}"))[0])[4:]
    save_loc = join(paths.SEIZURE_SPREAD_ATLASES_PROBABILITIES, f"sub-{sub}")
    utils.checkPathAndMake(save_loc, save_loc, printBOOL=False)

    atlas_path = glob.glob(
        join(paths.BIDS_DERIVATIVES_STRUCTURAL_MATRICES, f"sub-{sub}",
             f"ses-{ses}", "atlas_registration", f"*{atlas_name}.nii.gz"))[0]

    img, img_data = utils.load_img_and_data(atlas_path)
    img_data_cors = copy.deepcopy(img_data)
    img_data_cors[np.where(img_data_cors == 0)] = -1
    #loop thru regions and replace regions with correlation data

    for r in range(len(corrs_atlas)):
        utils.printProgressBar(r + 1, len(corrs_atlas))
        ind = np.where(img_data == int(corrs_atlas[r, 0]))
        img_data_cors[ind] = float(corrs_atlas[r, 1])

    save_loc_atlas = join(save_loc, f"{atlas_name}.nii.gz")
    utils.save_nib_img_data(img_data_cors, img, save_loc_atlas)

    T1_path = glob.glob(
        join(paths.BIDS_DERIVATIVES_STRUCTURAL_MATRICES, f"sub-{sub}",
             f"ses-{ses}", "atlas_registration",
             "*desc-preproc_T1w_std.nii.gz"))[0]
    if utils.checkIfFileDoesNotExist(f"{join(save_loc, basename(T1_path))}"):
        utils.executeCommand(
            cmd=f"cp {T1_path} {join(save_loc, basename(T1_path))}")
示例#2
0
def get_tracts_loop_through_patient_list(
        patient_list,
        paths,
        singularity_bind_path=None,
        path_dsiStudioSingularity=None,
        SESSION_RESEARCH3T="research3Tv[0-9][0-9]"):
    if singularity_bind_path == None:
        singularity_bind_path = paths.BIDS
    if path_dsiStudioSingularity == None:
        path_dsiStudioSingularity = paths.DSI_STUDIO_SINGULARITY

    N = len(patient_list)
    for i in range(N):
        sub = patient_list[i]
        ses = basename(
            glob.glob(
                join(paths.BIDS_DERIVATIVES_QSIPREP, "qsiprep", f"sub-{sub}",
                     f"ses-{SESSION_RESEARCH3T}"))[0])[4:]
        path_dwi = join(
            paths.BIDS_DERIVATIVES_QSIPREP, "qsiprep", f"sub-{sub}",
            f"ses-{ses}", "dwi",
            f"sub-{sub}_ses-{ses}_space-T1w_desc-preproc_dwi.nii.gz")
        path_tracts = join(paths.BIDS_DERIVATIVES_TRACTOGRAPHY, f"sub-{sub}",
                           f"ses-{ses}")
        utils.checkPathAndMake(path_tracts, path_tracts, printBOOL=False)
        utils.checkIfFileExistsGlob(path_dwi, printBOOL=False)

        trk_name = f"{join(path_tracts, utils.baseSplitextNiiGz(path_dwi)[2])}.trk.gz"
        if utils.checkIfFileDoesNotExist(trk_name):
            get_tracts(singularity_bind_path, path_dsiStudioSingularity,
                       path_dwi, path_tracts)
示例#3
0
def freesurferReconAll(T1path, outputpath, overwrite=False, threads=12):

    utils.checkPathErrorGlob(outputpath)
    utils.checkPathErrorGlob(T1path)

    if utils.checkIfFileDoesNotExist(f"{outputpath}/freesurfer/surf/lh.pial",
                                     returnOpposite=overwrite):
        if utils.checkIfFileDoesNotExist(
                f"{outputpath}/freesurfer/surf/rh.pial",
                returnOpposite=overwrite):
            utils.executeCommand(f"mkdir -p {outputpath}/freesurfer/mri/orig")
            utils.executeCommand(
                f"mri_convert {T1path} {outputpath}/freesurfer/mri/orig/001.mgz"
            )

            utils.executeCommand(
                f"recon-all -subjid freesurfer -all -time -log logfile -nuintensitycor-3T -sd {outputpath} -parallel -threads {threads}"
            )
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))
示例#5
0
            with open(analysis_location_file, 'rb') as f:
                [
                    X, y, fsds, secondsBefore, secondsAfter, window,
                    skipWindow, montage
                ] = pickle.load(f)

            X_train = np.concatenate([X_train, X], axis=0)
            y_train = np.concatenate([y_train, y], axis=0)

    # LL
    version = 100 + k

    feature_name = "line_length"
    filepath = join(deepLearningModelsPath,
                    f"single_features/{feature_name}_v{version:03d}.hdf5")
    if utils.checkIfFileDoesNotExist(filepath, printBOOL=False):
        lineLength_arr_train, lineLengthNorm_train = echobase.line_length_x_train(
            X_train)
        lineLength_arr_test, lineLengthNorm_test = echobase.line_length_x_train(
            X_test)

        lineLength_arr_test_norm = lineLength_arr_test / np.max(
            lineLength_arr_train)

        analysis = [
            lineLength_arr_train, lineLengthNorm_train, lineLength_arr_test,
            lineLengthNorm_test, lineLength_arr_test_norm
        ]
        with open(filepath, 'wb') as f:
            pickle.dump(analysis, f)
    else:
示例#6
0
 #check if freesurfer has been run on implant session
 elif utils.checkIfFileExists( join(freesurferReconAllDir, f"sub-{sub}", f"ses-{implantName}", "freesurfer", "surf", "lh.pial" ) ) and utils.checkIfFileExists( join(freesurferReconAllDir, f"sub-{sub}", f"ses-{implantName}", "freesurfer", "surf", "rh.pial" ) ):
         sessionPath = np.array(glob( join(freesurferReconAllDir, f"sub-{sub}", f"ses-{implantName}")))[0]
         session = basename(sessionPath)[4:]
         outputpath = join(BIDS, "derivatives", f"{derivativesOutput}", f"sub-{sub}", f"ses-{session}")
         utils.checkPathAndMake(outputpath, join(outputpath, "freesurfer", 'mri' ))
         utils.checkPathAndMake(outputpath, join(outputpath, "freesurfer", 'surf' ))
         utils.checkPathAndMake(outputpath, join(outputpath, "html"))
         utils.executeCommand(f"cp {join(sessionPath, 'freesurfer', 'mri' , 'orig_nu.mgz')}  {join(outputpath, 'freesurfer', 'mri' )} ")
         utils.executeCommand(f"cp {join(sessionPath, 'freesurfer', 'mri' , 'brain.mgz')}  {join(outputpath, 'freesurfer', 'mri' )} ")
         utils.executeCommand(f"cp {join(sessionPath, 'freesurfer', 'surf' , 'lh.pial')}  {join(outputpath, 'freesurfer', 'surf')} ")
         utils.executeCommand(f"cp {join(sessionPath, 'freesurfer', 'surf' , 'rh.pial')}  {join(outputpath, 'freesurfer', 'surf')} ")
 else:
     continue
 #check if lh and rh.pial have been moved to implantRenders derivatives path properly 
 if utils.checkIfFileDoesNotExist(f"{outputpath}/html/brain.glb", returnOpposite=False):
     if utils.checkIfFileExists(f"{join(outputpath, 'freesurfer', 'surf' ,'lh.pial')}" ) and utils.checkIfFileExists( f"{join(outputpath, 'freesurfer', 'surf' ,'rh.pial')}") :       
             # combined surfs
             utils.executeCommand(   f"cp {outputpath}/freesurfer/surf/lh.pial {outputpath}/freesurfer/"    )
             utils.executeCommand(   f"cp {outputpath}/freesurfer/surf/rh.pial {outputpath}/freesurfer/"    )
             utils.executeCommand(   f"mris_convert --to-scanner {outputpath}/freesurfer/lh.pial {outputpath}/freesurfer/lh.pial"    )
             utils.executeCommand(   f"mris_convert --to-scanner {outputpath}/freesurfer/rh.pial {outputpath}/freesurfer/rh.pial"    )
             utils.executeCommand(   f"mris_convert --combinesurfs {outputpath}/freesurfer/rh.pial {outputpath}/freesurfer/lh.pial {outputpath}/freesurfer/combined.stl"    )
             cmd = f"blender --background --factory-startup --addons io_scene_gltf2 --python {revellLabPath}/packages/imaging/electrodeLocalization/blender_compress_mesh.py -- -i {outputpath}/freesurfer/combined.stl -o {outputpath}/html/brain.glb"
             utils.executeCommand(cmd)          
             utils.executeCommand(f"cp {join(sessionPath, 'freesurfer', 'mri' , 'aseg.mgz')}  {join(outputpath, 'freesurfer', 'mri' )} ")
             outputDirTMP = join(outputpath, "freesurfer")      
             T1 =join(outputpath, 'freesurfer', 'mri', 'orig_nu.mgz' )
             T1brain =join(outputpath, 'freesurfer', 'mri', 'brain.mgz' )
             aseg =join(outputpath, 'freesurfer', 'mri', 'aseg.mgz' )
             T00 = glob(T00)[0]
示例#7
0
#%% Copy from server to local


listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(BIDSserver):
    listOfFiles += [join(dirpath, file) for file in filenames]


for f in range(len(listOfFiles)):
    #print(f)
    SERVERfile =  listOfFiles[f]
    LOCALfile = join( BIDSlocal, relpath(SERVERfile, BIDSserver))
    #ignore git
    if not ".git" in relpath(SERVERfile, BIDSserver):
        if utils.checkIfFileDoesNotExist(LOCALfile, printBOOL = False):
            print(f"\n{LOCALfile}")
            utils.checkPathAndMake( dirname(LOCALfile), dirname(LOCALfile), printBOOL = False  )
            utils.executeCommand( f"cp -r {SERVERfile} {LOCALfile}", printBOOL = False  )

#%% Copy from local to server


listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(BIDSlocal):
    listOfFiles += [join(dirpath, file) for file in filenames]


for f in range(len(listOfFiles)):
    print(f)
    LOCALfile =  listOfFiles[f]