Beispiel #1
0
def mosaic(inp, output, xy, win=None):
    '''
    Take snapshot of NIfTI-1 3D image

    :param inp: inp file
    :type inp: str
    :param output: Output file
    :type output: str
    :param xy: Snapshot image X and Y lengths, in slices
    :type xy: tuple
    :param win: Window of voxel intensity
    :type win: tuple
    '''
    if win and len(win) != 2:
        raise MosaicError("window argument must be (a,b)")
    nii = nib.load(inp)
    x, y, z = nii.shape
    logger.debug("x=%s, y=%s, z=%s", x, y, z)
    # get snapshot image x length (in numbers of voxels)
    x_width = x * xy[0]
    # determine if we need a subset of slices to fit the desired y length
    nth_vox = 1
    if xy[1]:
        nth_vox = math.ceil(float(z) / (xy[0] * xy[1]))
    # read the image data payload
    niid = nii.get_data()
    niid_min, niid_max = niid.min(), niid.max()
    logger.debug("image=%s, min=%s, max=%s", inp, niid_min, niid_max)
    # the order of arguments is important
    com = ["slicer", inp]
    if win:
        com.extend(["-i", str(win[0] * niid_min), str(win[1] * niid_max)])
    com.extend(["-u", "-S", str(nth_vox), str(x_width), output])
    fun.execute(com, kill=True)
Beispiel #2
0
def fslmerge_342e312e37(input, output, **kwargs):
    '''
    FSL v4.0.3 merge tool
    '''
    fslmerge = fun.which("fslmerge")
    if not fslmerge:
        raise commons.CommandNotFoundError("could not find fslmerge")
    output = str(output)
    cmd = ["fslmerge"]
    if "axis" in kwargs:
        if kwargs["axis"] == commons.Axis.X:
            cmd.append("-x")
        elif kwargs["axis"] == commons.Axis.Y:
            cmd.append("-y")
        elif kwargs["axis"] == commons.Axis.Z:
            cmd.append("-z")
        elif kwargs["axis"] == commons.Axis.T:
            cmd.append("-t")
    else:
        raise commons.APIError("axis argument required")
    cmd.append(output)
    cmd.extend(input)
    cwd = os.getcwd()
    tic = time.time()
    fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(fslmerge, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #3
0
def fslroi_342e312e37(input, output, **kwargs):
    '''
    FSL region of interest utility. 

    Important: Assumes input image shape is x/y/z/t.
    '''
    fslroi = fun.which("fslroi")
    if not fslroi:
        raise commons.CommandNotFoundError("could not find fslroi")
    input, output = str(input), str(output)
    # get image dimensions
    img = nib.load(input)
    x, y, z, t = img.shape
    # build command
    cmd = [fslroi, input, output]
    if "xmin" in kwargs:
        cmd.append(str(kwargs["xmin"]))
    else:
        cmd.append('0')
    if "xsize" in kwargs:
        cmd.append(str(kwargs["xsize"]))
    else:
        cmd.append(str(x))
    if "ymin" in kwargs:
        cmd.append(str(kwargs["ymin"]))
    else:
        cmd.append('0')
    if "ysize" in kwargs:
        cmd.append(str(kwargs["ysize"]))
    else:
        cmd.append(str(y))
    if "zmin" in kwargs:
        cmd.append(str(kwargs["zmin"]))
    else:
        cmd.append('0')
    if "zsize" in kwargs:
        cmd.append(str(kwargs["zsize"]))
    else:
        cmd.append(str(z))
    if "tmin" in kwargs:
        cmd.append(str(kwargs["tmin"]))
    else:
        cmd.append('0')
    if "tsize" in kwargs:
        cmd.append(str(kwargs["tsize"]))
    else:
        cmd.append(str(t))
    # execute command
    cwd = os.getcwd()
    tic = time.time()
    fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(fslroi, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #4
0
def niftiqa(niifile, output_dir, skip=4, mask_threshold=200.0, exe=NIFTIQA):
    '''
    Run standard niftiqa script
    '''
    if not os.path.exists(output_dir):
        os.makedirs(output_dir, 2755)
    com = [
        exe, "--skip",
        str(skip), "--mask-threshold",
        str(mask_threshold), "--mean-slice-plot-format", "png", "--all",
        "--output-dir", output_dir, niifile
    ]
    fun.execute(com, kill=True)
Beispiel #5
0
def niftiqa_312e30(input, output, skip, mask_threshold, snap=(None, None)):
    '''
    Produce QA data for a NIfTI-1 file.
    '''
    niftiqa = fun.which("niftiqa_hcp.py")
    if not niftiqa:
        raise commons.CommandNotFoundError("could not find niftiqa_hcp.py")
    input, output = str(input), str(output)
    if not os.path.exists(output):
        os.makedirs(output)
    cmd = [
        niftiqa, "--output-dir", output, "--skip",
        str(skip), "--mask-threshold",
        str(mask_threshold), "--debug"
    ]
    if snap[0] is not None:
        cmd.extend(["--snap-x", str(snap[0])])
    if snap[1] is not None:
        cmd.extend(["--snap-y", str(snap[1])])
    cmd.append(input)
    cwd = os.getcwd()
    tic = time.time()
    summary = fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(niftiqa, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #6
0
def flirt_342e312e37(input, output, **kwargs):
    '''
    Fast linear image registration
    '''
    flirt = fun.which("flirt")
    if not flirt:
        raise commons.CommandNotFoundError("could not find flirt")
    input,output = str(input),str(output)
    cmd = [flirt, "-in", input, "-out", output]
    if "input_matrix" in kwargs:
        cmd.extend(["-init", str(kwargs["input_matrix"])])
    if "output_matrix" in kwargs:
        cmd.extend(["-omat", str(kwargs["output_matrix"])])
    if "reference" in kwargs:
        cmd.extend(["-ref", kwargs["reference"]])
    if "cost" in kwargs:
        cmd.extend(["-cost", kwargs["cost"]])
    if "dof" in kwargs:
        cmd.extend(["-dof", str(kwargs["dof"])])
    if "searchr_x" in kwargs:
        a,b = str(kwargs["searchr_x"][0]),str(kwargs["searchr_x"][1])
        cmd.extend(["-searchrx", a, b])
    if "searchr_y" in kwargs:
        a,b = str(kwargs["searchr_y"][0]),str(kwargs["searchr_y"][1])
        cmd.extend(["-searchry", a, b])
    if "searchr_z" in kwargs:
        a,b = str(kwargs["searchr_z"][0]),str(kwargs["searchr_z"][1])
        cmd.extend(["-searchrz", a, b])
    if "interp" in kwargs:
        cmd.extend(["-interp", kwargs["interp"]])
    if "applyisoxfm" in kwargs:
        cmd.extend(["-applyisoxfm", str(kwargs["applyisoxfm"])])
    if "applyxfm" in kwargs and kwargs["applyxfm"]:
        cmd.append("-applyxfm")
    if "forcescaling" in kwargs:
        cmd.append("-forcescaling")
    cwd = os.getcwd()
    tic = time.time()
    fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(flirt, cmd, cwd, tic, toc)
    return summary,provenance
Beispiel #7
0
def convert_xfm_342e312e37(input, output, **kwargs):
    '''
    Manipulate transformation matrix
    '''
    convert_xfm = fun.which("convert_xfm")
    if not convert_xfm:
        raise commons.CommandNotFoundError("could not find convert_xfm")
    input, output = str(input), str(output)
    cmd = [convert_xfm, "-omat", output]
    if "invert" in kwargs and kwargs["invert"]:
        cmd.append("-inverse")
    cmd.append(input)
    cwd = os.getcwd()
    tic = time.time()
    fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(convert_xfm, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #8
0
def fslorient_342e312e37(input, output, orientation):
    '''
    Reorient file
    '''
    fslorient = fun.which("fslorient")
    if not fslorient:
        raise commons.CommandNotFoundError("could not find fslorient")
    input, output = str(input), str(output)
    # fslorient will overwrite the input file
    if fun.expand(input) != fun.expand(output):
        shutil.copy(input, output)
    else:
        output = input
    # get the desired orientation as a string
    if orientation == commons.Orient.NEUROLOGICAL:
        orientation = 'NEUROLOGICAL'
    elif orientation == commons.Orient.RADIOLOGICAL:
        orientation = 'RADIOLOGICAL'
    # get the current orientation of the file
    cmd = ["fslorient", "-getorient", input]
    summary = fun.execute(cmd)
    try:
        current_orientation = summary.stdout.strip().upper()
    except:
        logger.warning(summary)
        raise
    # return now if the file is already in the desired orientation
    if current_orientation == orientation:
        return
    # swap the orientation
    cmd = [fslorient, "-swaporient", output]
    cwd = os.getcwd()
    tic = time.time()
    fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(fslorient, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #9
0
def fslswapdim_342e312e37(input, output, rule):
    '''
    Swap dimensions of input file
    '''
    fslswapdim = fun.which("fslswapdim")
    if not fslswapdim:
        raise commons.CommandNotFoundError("could not find fslswapdim")
    input, output = str(input), str(output)
    cmd = [fslswapdim, input] + rule + [output]
    cwd = os.getcwd()
    tic = time.time()
    summary = fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(fslswapdim, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #10
0
def bet_342e312e37(input, output, **kwargs):
    '''
    FSL v4.0.3 Brain Extraction Tool
    '''
    bet = fun.which(bet)
    if not bet:
        raise commons.CommandNotFoundError("could not find bet")
    input,output = str(input),str(output)
    cmd = [bet, input, output]
    if "vertical_gradient" in kwargs:
        cmd.extend(["-g", str(kwargs["vertical_gradient"])])
    cwd = os.getcwd()
    tic = time.time()
    summary = fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(bet, cmd, cwd, tic, toc)
    return summary,provenance
Beispiel #11
0
def mri_convert_323031355f31325f3033(infile, outfile, **kwargs):
    '''
    Greve mri_convert/2015_11_09 file converter
    '''
    mri_convert = fun.which("mri_convert")
    if not mri_convert:
        raise commons.CommandNotFoundError("could not find mri_convert")
    infile, outfile = str(infile), str(outfile)
    d = os.path.dirname(outfile)
    if not os.path.exists(d):
        os.makedirs(d)
    cmd = [mri_convert, infile]
    if "outtype" in kwargs:
        cmd.extend(["-ot", kwargs["outtype"]])
    cmd.append(outfile)
    cwd = os.getcwd()
    tic = time.time()
    summary = fun.execute(cmd, kill=True)
    toc = time.time()
    provenance = commons.provenance(mri_convert, cmd, cwd, tic, toc)
    return summary, provenance
Beispiel #12
0
def stackcheck_ext_312e30(input, output, skip, mask_threshold, experiment,
                          scan):
    '''
    Produce *extended* motion correction metrics.
    '''
    stackcheck_ext = fun.which("stackcheck_ext.sh")
    if not stackcheck_ext:
        raise commons.CommandNotFoundError("could not find stackcheck_ext.sh")
    input, output = str(input), str(output)
    logger.info(experiment)
    if not os.path.exists(output):
        os.makedirs(output, 2755)
    cmd = [
        stackcheck_ext, "-p", "-M", "-T", "-X", "-f", input, "-o", output,
        "-s",
        str(skip), "-N",
        str(scan), "-t",
        str(mask_threshold)
    ]
    try:
        if experiment.id:
            cmd.extend(["-S", str(experiment.id)])
    except AttributeError:
        logger.debug(
            'experiment has no id attribute but this is an optional argument to stackcheck.sh, continuing without it.'
        )

    if experiment.project:
        cmd.extend(["-P", str(experiment.project)])
    cwd = os.getcwd()
    tic = time.time()
    summary = fun.execute(cmd, kill=True)
    toc = time.time()
    if not os.path.exists(output):
        raise commons.SubprocessError(cmd)
    provenance = commons.provenance(stackcheck_ext, cmd, cwd, tic, toc)
    return summary, provenance