def gen_parc_masks(rois, roiNums, parcVol, outDir,
                   doVolStats=True, redo=False, logFN=None):
    import os
    import numpy as np
    from scipy.io import savemat as savemat
    from scai_utils import check_bin_path, check_file, \
                           cmd_stdout, saydo, info_log, error_log

    check_bin_path("fslstats", logFN=logFN)

    volStats = {"roiName": [], "nVoxels": [], "mm3": []}
    for (i0, roi) in enumerate(rois):
        roiNum = roiNums[i0]
            
        maskFN = os.path.join(outDir, "%s.diff.nii.gz" % roi)
        binCmd = "mri_binarize --i %s --match %d --o %s" % \
                 (parcVol, roiNum, maskFN)
            
        if not os.path.isfile(maskFN) or redo:
            saydo(binCmd, logFN=logFN)
        check_file(maskFN, logFN=logFN)

        #= Volume stats =#
        (so, se) = cmd_stdout("fslstats %s -V" % maskFN)
        assert(len(se) == 0)
            
        so = so.split(" ")
        assert(len(so) >= 2)
        
        volStats["nVoxels"].append(int(so[0]))
        volStats["mm3"].append(float(so[1]))
        volStats["roiName"].append(roi)
            
    if doVolStats:
        volStats["roiName"] = np.array(volStats["roiName"])
        volStats["nVoxels"] = np.array(volStats["nVoxels"])
        volStats["mm3"] = np.array(volStats["mm3"])
    
        volStatsFN = os.path.join(outDir, "vol_stats.mat")
        savemat(volStatsFN, volStats)
        check_file(volStatsFN, logFN=logFN)

        info_log("INFO: %s: Saved volume stats of the mask files at\n\t%s" \
                 % (gen_parc_masks.__name__, volStatsFN), logFN=logFN)
def get_parc_stats(fsDir, subjID, parcName, bVerbose=False):
    import sys, os
    import tempfile
    from scai_utils import (
        check_dir,
        check_file,
        check_bin_path,
        info_log,
        cmd_stdout,
        saydo,
        read_text_file,
        remove_empty_strings,
    )

    # === Constants ===#
    hemis = ["lh", "rh"]
    segStatsBin = "mri_segstats"

    # === Implementation ===#
    check_bin_path(segStatsBin)

    sDir = os.path.join(fsDir, subjID)
    check_dir(sDir)

    lblDir = os.path.join(sDir, "label")
    check_dir(sDir)

    if bVerbose:
        info_log("Label directory = %s" % lblDir)

    morphInfo = {}

    rois = []
    area_mm2 = []

    for (i0, hemi) in enumerate(hemis):
        if bVerbose:
            info_log("Working on hemisphere: %s" % hemi)

        annot = os.path.join(lblDir, "%s.%s.annot" % (hemi, parcName))
        check_file(annot)

        tmpSum = tempfile.mktemp()
        cmd = "%s --annot %s %s %s --sum %s" % (segStatsBin, subjID, hemi, parcName, tmpSum)
        saydo(cmd)

        check_file(tmpSum)
        if bVerbose:
            print("Intermediate results saved at: %s" % tmpSum)

        t = read_text_file(tmpSum)

        for (i0, tline) in enumerate(t):
            tline = tline.strip()
            if len(tline) == 0:
                continue
            elif tline.startswith("#"):
                continue

            t_items = remove_empty_strings(tline.split())
            if len(t_items) != 5:
                continue

            t_roi = t_items[4]
            if t_roi.lower() == "none":
                continue

            rois.append("%s_%s" % (hemi, t_roi))
            area_mm2.append(float(t_items[3]))

        saydo("rm -rf %s" % tmpSum)
    morphInfo["rois"] = rois
    morphInfo["area_mm2"] = area_mm2

    return morphInfo
        raise Exception, "Cannot find any BOLD volumes that match the path wild card: %s" % boldWC

    if len(dfs) == nRuns:
        info_log("The number of image files matches nRuns. Good")
        boldVols = dfs
    elif len(dfs) == 2 * nRuns:
        info_log("The number of image files equals 2 x nRuns. Assuming that thefirst of each pair os the non-motion corected volume.")
        boldVols = dfs[0::2]
    else:
        raise Exception, "The number of .nii.gz serie in directory %s is neither equal to nRuns=%d or 2*nRuns=%d" % (boldDir, nRuns, 2 * nRuns)

    #=== Copy image files and convert them to .nii ===#
    niiDir = os.path.join(sBatchDataDir, "nii")
    check_dir(niiDir, bCreate=True)

    check_bin_path("mri_convert")

    niftiFNs = []
    for i0 in range(nRuns):
        niftiFNs.append(os.path.join(niiDir, "00-%d.nii" % (i0 + 1)))
        saydo("mri_convert %s %s" % (boldVols[i0], niftiFNs[-1]))
        check_file(niftiFNs[-1])

    #=== Determine the number of contrasts ===#
    contr = loadmat(contrMat)

    nContrasts = len(contr["RegNameTContrasts"][0])
    info_log("Number of contrasts = %d" % nContrasts)


    #=== Check for the FS subject data dir ===#
Beispiel #4
0
def run_probtrackx(seedMask,
                   targMask,
                   bedpBase,
                   brainMask,
                   outDir,
                   doSeedNorm=True,
                   doSize=True,
                   doTargMaskedFDT=True,
                   ccStop=False,
                   bRedo=False,
                   logFN=None):
    #=========================================================#
    # Mode 1: from seed to targ
    #         Specify both seedMask and targMask
    #
    # Mode 2: from seed to all
    #         Specify only seedMask; set targMask=None
    #
    # Options:
    #         ccStop: Use corpus callosum stop mask
    #
    #=========================================================#
    import os
    from scai_utils import check_file, check_dir, check_bin_path, \
                           saydo, cmd_stdout, info_log, error_log
    from mri_utils import nz_voxels

    #== Get seed and targ nvox ==#
    check_file(seedMask, logFN=logFN)

    (seed_nVoxels, seed_mm3) = nz_voxels(seedMask)
    seed_nVoxels = float(seed_nVoxels)
    #assert(seed_nVoxels > 0)

    if targMask != None:
        check_file(targMask, logFN=logFN)

        (targ_nVoxels, targ_mm3) = nz_voxels(targMask)
        targ_nVoxels = float(targ_nVoxels)
        assert (targ_nVoxels > 0)

    check_bin_path("probtrackx", logFN=logFN)

    check_dir(outDir, logFN=logFN)

    if targMask != None:
        #= Prepare waypoint file =#
        wpfn = os.path.join(outDir, "waypoints.txt")
        wptext = os.path.abspath(targMask) + "\n"

        wpf = open(wpfn, "w")
        wpf.write(wptext)
        wpf.close()
        check_file(wpfn, logFN=logFN)

    cmd = 'probtrackx --mode=seedmask -x %s ' % seedMask + \
          '-s %s ' % bedpBase + \
          '-m %s ' % brainMask + \
          '-l -c 0.2 -S 2000 --steplength=0.5 ' + \
          '-P 5000 ' + \
          '--forcedir --opd --pd --dir=%s ' % outDir

    if targMask != None:
        cmd += "--stop=%s --waypoints=%s " % (targMask, wpfn)

    fdt_paths_fn = os.path.join(outDir, "fdt_paths.nii.gz")

    #== Get the size of fdt_paths.nii.gz. If the size is zero, start over. ==#

    if not os.path.isfile(fdt_paths_fn) \
            or os.path.getsize(fdt_paths_fn) <= 1 \
            or bRedo:
        saydo(cmd, logFN=logFN)

    #== Check for probtrackx completion ==#
    check_file(fdt_paths_fn, logFN=logFN)

    #== Save probtrackx command ==#
    cmd_fn = os.path.join(outDir, "command.txt")
    cmd_f = open(cmd_fn, "wt")
    cmd_f.write("%s\n" % cmd)
    cmd_f.close()
    check_file(cmd_fn, logFN=logFN)

    #== Generate seed size-normalized fdt_paths ==#
    fdt_paths_norm_fn = os.path.join(outDir, "fdt_paths_norm.nii.gz")
    check_bin_path("fslmaths", logFN=logFN)

    norm_cmd = "fslmaths -dt float %s -div %d %s -odt float" % \
               (fdt_paths_fn, seed_nVoxels, fdt_paths_norm_fn)
    if not os.path.isfile(fdt_paths_norm_fn) or bRedo:
        saydo(norm_cmd, logFN=logFN)

    check_file(fdt_paths_norm_fn, logFN=logFN)

    if doSize:
        #== Write to seed size file ==#
        seed_size_fn = os.path.join(outDir, 'seed_size.txt')
        seed_size_f = open(seed_size_fn, 'w')
        seed_size_f.write("%d %f" % (int(seed_nVoxels), seed_mm3))
        seed_size_f.close()
        check_file(seed_size_fn, logFN=logFN)

        info_log("INFO: Saved seed size data to file: %s" % seed_size_fn,
                 logFN=logFN)

        if targMask != None:
            #== Write to targ size file ==#
            targ_size_fn = os.path.join(outDir, 'targ_size.txt')
            targ_size_f = open(targ_size_fn, 'w')
            targ_size_f.write("%d %f" % (int(targ_nVoxels), targ_mm3))
            targ_size_f.close()
            check_file(targ_size_fn, logFN=logFN)

            info_log("INFO: Saved targ size data to file: %s" % targ_size_fn,
                     logFN=logFN)

    if (targMask != None) and doTargMaskedFDT:
        #== Get target masked tract density ==#
        check_bin_path("fslstats", logFN=logFN)
        (so, se) = cmd_stdout("fslstats %s -k %s -m" \
                              % (fdt_paths_norm_fn, targMask))
        assert (len(se) == 0)
        so = so.split()
        assert (len(so) >= 1)
        targ_masked_norm_fdt = float(so[0])

        targ_masked_norm_fdt_fn = \
            os.path.join(outDir, "targ_masked_norm_fdt.txt")
        tmnff = open(targ_masked_norm_fdt_fn, "wt")
        tmnff.write("%f" % targ_masked_norm_fdt)
        tmnff.close()

        check_file(targ_masked_norm_fdt_fn, logFN=logFN)

        info_log("INFO: Saved target-masked normalized FDT value tofile: %s" \
                 % targ_masked_norm_fdt_fn,
                 logFN=logFN)
                    help="Functional activation (sig) threshold (e.g., 3)")
    ap.add_argument("fMid", type=float, 
                    help="Functional activation (sig) mid value (e.g., 5)")

    if len(sys.argv) == 1:
        ap.print_help()
        sys.exit(1)

    args = ap.parse_args()

    if args.type == "both":
        types = ["sf10", "vol"]
    else:
        types = [args.type]

    check_bin_path(CONVERT_BIN)

    check_dir(CON_IMG_DIR)

    l2Base = os.path.abspath(L2_BATCH_BASE)
    check_dir(l2Base)
    
    stitchRes = {}
    for t_type in types:
        conDir = os.path.join(l2Base, 
                              "%s_%s_%s" % (args.grp, args.contr, t_type))
        check_dir(conDir)

        stitchRes[t_type] = {}

        if t_type.startswith("sf"):
def run_probtrackx(seedMask, targMask, bedpBase, brainMask, outDir, 
                   doSeedNorm=True, doSize=True, 
                   doTargMaskedFDT=True, 
                   ccStop=False, 
                   bRedo=False,
                   logFN=None):
#=========================================================#
# Mode 1: from seed to targ
#         Specify both seedMask and targMask
#
# Mode 2: from seed to all
#         Specify only seedMask; set targMask=None
#
# Options:
#         ccStop: Use corpus callosum stop mask
#
#=========================================================#
    import os
    from scai_utils import check_file, check_dir, check_bin_path, \
                           saydo, cmd_stdout, info_log, error_log
    from mri_utils import nz_voxels

    #== Get seed and targ nvox ==#
    check_file(seedMask, logFN=logFN)

    (seed_nVoxels, seed_mm3) = nz_voxels(seedMask)
    seed_nVoxels = float(seed_nVoxels)
    #assert(seed_nVoxels > 0)
    
    if targMask != None:
        check_file(targMask, logFN=logFN)
        
        (targ_nVoxels, targ_mm3) = nz_voxels(targMask)
        targ_nVoxels = float(targ_nVoxels)
        assert(targ_nVoxels > 0)
        
    check_bin_path("probtrackx", logFN=logFN)
        
    check_dir(outDir, logFN=logFN)

    if targMask != None:
        #= Prepare waypoint file =#
        wpfn = os.path.join(outDir, "waypoints.txt")
        wptext = os.path.abspath(targMask) + "\n"

        wpf = open(wpfn, "w")
        wpf.write(wptext)
        wpf.close()
        check_file(wpfn, logFN=logFN)
        
    cmd = 'probtrackx --mode=seedmask -x %s ' % seedMask + \
          '-s %s ' % bedpBase + \
          '-m %s ' % brainMask + \
          '-l -c 0.2 -S 2000 --steplength=0.5 ' + \
          '-P 5000 ' + \
          '--forcedir --opd --pd --dir=%s ' % outDir

    if targMask != None:
        cmd += "--stop=%s --waypoints=%s " % (targMask, wpfn)
        
    fdt_paths_fn = os.path.join(outDir, "fdt_paths.nii.gz")
    
    #== Get the size of fdt_paths.nii.gz. If the size is zero, start over. ==#

    if not os.path.isfile(fdt_paths_fn) \
            or os.path.getsize(fdt_paths_fn) <= 1 \
            or bRedo:
        saydo(cmd, logFN=logFN)

    #== Check for probtrackx completion ==#
    check_file(fdt_paths_fn, logFN=logFN)

    #== Save probtrackx command ==#
    cmd_fn = os.path.join(outDir, "command.txt")
    cmd_f = open(cmd_fn, "wt")
    cmd_f.write("%s\n" % cmd)
    cmd_f.close()
    check_file(cmd_fn, logFN=logFN)

    #== Generate seed size-normalized fdt_paths ==#
    fdt_paths_norm_fn = os.path.join(outDir, "fdt_paths_norm.nii.gz")
    check_bin_path("fslmaths", logFN=logFN)

    norm_cmd = "fslmaths -dt float %s -div %d %s -odt float" % \
               (fdt_paths_fn, seed_nVoxels, fdt_paths_norm_fn)
    if not os.path.isfile(fdt_paths_norm_fn) or bRedo:
        saydo(norm_cmd, logFN=logFN)
        
    check_file(fdt_paths_norm_fn, logFN=logFN)

    if doSize:
        #== Write to seed size file ==#
        seed_size_fn = os.path.join(outDir, 'seed_size.txt')
        seed_size_f = open(seed_size_fn, 'w')
        seed_size_f.write("%d %f" % (int(seed_nVoxels), seed_mm3))
        seed_size_f.close()
        check_file(seed_size_fn, logFN=logFN)

        info_log("INFO: Saved seed size data to file: %s" % seed_size_fn, 
                 logFN=logFN)

        if targMask != None:
            #== Write to targ size file ==#
            targ_size_fn = os.path.join(outDir, 'targ_size.txt')
            targ_size_f = open(targ_size_fn, 'w')
            targ_size_f.write("%d %f" % (int(targ_nVoxels), targ_mm3))
            targ_size_f.close()
            check_file(targ_size_fn, logFN=logFN)

            info_log("INFO: Saved targ size data to file: %s" % targ_size_fn,
                     logFN=logFN)

    if (targMask != None) and doTargMaskedFDT:
        #== Get target masked tract density ==#
        check_bin_path("fslstats", logFN=logFN)
        (so, se) = cmd_stdout("fslstats %s -k %s -m" \
                              % (fdt_paths_norm_fn, targMask))
        assert(len(se) == 0)
        so = so.split()
        assert(len(so) >= 1)
        targ_masked_norm_fdt = float(so[0])

        targ_masked_norm_fdt_fn = \
            os.path.join(outDir, "targ_masked_norm_fdt.txt")
        tmnff = open(targ_masked_norm_fdt_fn, "wt")
        tmnff.write("%f" % targ_masked_norm_fdt)
        tmnff.close()

        check_file(targ_masked_norm_fdt_fn, logFN=logFN)

        info_log("INFO: Saved target-masked normalized FDT value tofile: %s" \
                 % targ_masked_norm_fdt_fn,
                 logFN=logFN)