Example #1
0
def geodesic_depth(command, surface_file):
    """
    Measure "travel depth" of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : travel depth C++ executable command
    surface_file : ``vtk file``

    Returns
    -------
    depth_file: string
        vtk file with geodesic depth per vertex of mesh

    """
    import os
    from nipype.interfaces.base import CommandLine

    depth_file = os.path.join(os.getcwd(),
                 os.path.splitext(os.path.basename(surface_file))[0] + '.geodesic_depth.vtk')
    cli = CommandLine(command = command)
    cli.inputs.args = ' '.join([surface_file, depth_file])
    cli.cmdline
    cli.run()

    if not os.path.exists(depth_file):
        raise(IOError(depth_file + " not found"))

    return depth_file
Example #2
0
def make_cerebellum(aseg):
      cwd = os.getcwd()
      pth, nme = os.path.split(aseg)
      os.chdir(pth)
      cl = CommandLine('fslmaths %s -thr 47 -uthr 47 right_cerebellum'% (aseg))
      cout = cl.run()
      
      if not cout.runtime.returncode == 0:
            os.chdir(cwd)
            print 'Unable to create  right cerebellum for %s'%(aseg)
            return None

      cl2 = CommandLine('fslmaths %s -thr 8 -uthr 8 left_cerebellum'% (aseg))
      cout2 = cl2.run()

      if not cout2.runtime.returncode == 0:
            os.chdir(cwd)
            print 'Unable to create  left cerebellum for %s'%(aseg)
            return None

      cl3 = CommandLine('fslmaths left_cerebellum -add right_cerebellum -bin grey_cerebellum')
      cout3 = cl3.run()
      if not cout3.runtime.returncode == 0:
            print 'Unable to create whole cerebellum for %s'%(aseg)
            print cout3.runtime.stderr
            print cout3.runtime.stdout
            return None
      
      cmd = 'rm right_cerebellum.* left_cerebellum.*'
      cl4 = CommandLine(cmd)
      cout4 = cl4.run()
      os.chdir(cwd)
      cerebellum = glob('%s/grey_cerebellum.*'%(pth))
      return cerebellum[0]
def DICOM2animatedGIF_sidebyside(dcmdir_l, dcmdir_r, outputpath, slice_i, suffix):

    dcmio = DicomIO.DicomIO()
    dwidcm_l = dcmio.ReadDICOM_frames(dcmdir_l)
    dwidcm_r = dcmio.ReadDICOM_frames(dcmdir_r)
    # Write all frames of slice into set of png files
    for frame_i in range(len(dwidcm_l)):
        slice_l = dwidcm_l[frame_i][slice_i].pixel_array.T
        slice_r = dwidcm_r[frame_i][slice_i].pixel_array.T
        dimx = slice_l.shape[0]
        dimy = slice_l.shape[1]
        newImg1 = PIL.Image.new('L', (dimx*2, dimy))
        pixels1 = newImg1.load()
        for i in range (0, dimx):
            for j in range (0, dimy):
                pixels1[i, j] = float(slice_l[i, j])
                pixels1[dimx+i, j] = float(slice_r[i, j])
        #pixels1[i, j] = float(slice[i, j]) * dwidcm[frame_i][slice_i].RescaleSlope + dwidcm[frame_i][slice_i].RescaleIntercept
        newImg1.save((outputpath + '_' + ('%02d' % frame_i) + '.png'),'PNG')
    cmd = CommandLine('convert -delay 25 -loop 0 %s_*.png %s_%s.gif' % (outputpath, outputpath, suffix))
    cmd.run()
    for frame_i in range(len(dwidcm_l)):
        os.remove((outputpath + '_' + ('%02d' % frame_i) + '.png'))
    print "convert (ImageMagick):" + cmd.cmd
    return (outputpath + '.gif')
def dicom2nrrd(dicomdir, out_prefix, out_suffix):
    import os
    from nipype.interfaces.base import CommandLine
    cmd = CommandLine('DWIConvert --inputDicomDirectory %s --outputVolume %s/%s/%s%s.nrrd' % (dicomdir, experiment_dir,out_prefix,out_prefix,out_suffix))
    print "DICOM->NRRD:" + cmd.cmd
    cmd.run()
    return os.path.abspath('%s/%s/%s%s.nrrd' % (experiment_dir,out_prefix,out_prefix,out_suffix))
Example #5
0
def area(command, surface_file):
    """
    Measure area of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : string
        Voronoi-based surface area C++ executable command
    surface_file : string
        vtk file with surface mesh

    Returns
    -------
    area_file: string
        vtk file with surface area per vertex of mesh

    """
    import os
    from nipype.interfaces.base import CommandLine

    area_file = os.path.join(os.getcwd(),
                os.path.splitext(os.path.basename(surface_file))[0] + '.area.vtk')
    cli = CommandLine(command = command)
    cli.inputs.args = ' '.join([surface_file, area_file])
    cli.cmdline
    cli.run()

    if not os.path.exists(area_file):
        raise(IOError(area_file + " not found"))

    return area_file
def elastix(input_file, target_file, mask_file, output_prefix, output_sub_prefix, param_rigid, param_BSpline):
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    import shutil
    import glob
    import os

    out_dir = experiment_dir + os.sep + output_prefix + os.sep + output_sub_prefix
    # Create output directory if it does not exist
    if os.path.exists(out_dir):
        print "rmtree: " + out_dir
        shutil.rmtree(out_dir)
    print "creating: " + out_dir
    os.makedirs(out_dir)

    cmd = CommandLine(
        (
            "/Users/eija/Documents/SW/Elastix/elastix_sources_v4.7/bin/bin/elastix -f %s -m %s -out %s -p %s -p %s -threads 8"
        )
        % (target_file, input_file, out_dir, param_rigid, param_BSpline)
    )

    print "elastix: " + cmd.cmd
    cmd.run()
    resultfiles = glob.glob(out_dir + os.sep + "result.*.tiff")
    return resultfiles
def area(command, surface_file, verbose=False):
    """
    Measure area of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : string
        Voronoi-based surface area C++ executable command
    surface_file : string
        vtk file with surface mesh
    verbose : bool
        print statements?

    Returns
    -------
    area_file: string
        vtk file with surface area per vertex of mesh

    Examples
    --------
    >>> import os
    >>> import numpy as np
    >>> from mindboggle.shapes.surface_shapes import area
    >>> from mindboggle.mio.vtks import read_scalars
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> surface_file = fetch_data(urls['left_pial'], '', '.vtk')
    >>> verbose = False
    >>> ccode_path = os.environ['vtk_cpp_tools']
    >>> command = os.path.join(ccode_path, 'area', 'PointAreaMain')
    >>> area_file = area(command, surface_file, verbose)
    >>> scalars, name = read_scalars(area_file)
    >>> np.allclose(scalars[0:8],
    ...             [0.48270401731, 0.39661528543, 0.57813454792, 0.70574099571,
    ...              0.84318527207, 0.57642554119, 0.66942016035, 0.70629953593])
    True

    """
    import os
    from nipype.interfaces.base import CommandLine

    basename = os.path.splitext(os.path.basename(surface_file))[0]
    area_file = os.path.join(os.getcwd(), basename + '.area.vtk')
    args = ' '.join([surface_file, area_file])

    if verbose:
        print("{0} {1}".format(command, args))

    cli = CommandLine(command=command)
    cli.inputs.args = args
    cli.terminal_output = 'file'
    cli.run()

    if not os.path.exists(area_file):
        raise IOError(area_file + " not found")

    return area_file
Example #8
0
def gznii2nii(in_file):
    import os
    import shutil

    fileName, fileExtension = os.path.splitext(in_file)
    cmd = CommandLine('gunzip -f -k %s.nii.gz' % (fileName))
    print "gunzip NII.GZ:" + cmd.cmd
    cmd.run()
    return os.path.abspath('%s.nii' % (fileName))
Example #9
0
def travel_depth(command, surface_file, verbose=False):
    """
    Measure "travel depth" of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : string
        travel depth C++ executable command
    surface_file : string
        vtk file
    verbose : bool
        print statements?

    Returns
    -------
    depth_file: string
        vtk file with travel depth per vertex of mesh

    Examples
    --------
    >>> import os
    >>> import numpy as np
    >>> from mindboggle.shapes.surface_shapes import travel_depth
    >>> from mindboggle.mio.vtks import read_scalars
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> surface_file = fetch_data(urls['left_pial'], '', '.vtk')
    >>> verbose = False
    >>> ccode_path = os.environ['vtk_cpp_tools']
    >>> command = os.path.join(ccode_path, 'travel_depth', 'TravelDepthMain')
    >>> depth_file = travel_depth(command, surface_file, verbose)
    >>> scalars, name = read_scalars(depth_file)
    >>> print(np.array_str(np.array(scalars[0:8]), precision=5,
    ...     suppress_small=True))
    [ 0.02026  0.06009  0.12859  0.04564  0.00774  0.05284  0.05354  0.01316]

    """
    import os
    from nipype.interfaces.base import CommandLine

    basename = os.path.splitext(os.path.basename(surface_file))[0]
    depth_file = os.path.join(os.getcwd(), basename + '.travel_depth.vtk')
    args = ' '.join([surface_file, depth_file])

    if verbose:
        print("{0} {1}".format(command, args))

    cli = CommandLine(command=command)
    cli.inputs.args = args
    cli.cmdline
    cli.run()

    if not os.path.exists(depth_file):
        raise IOError(depth_file + " not found")

    return depth_file
Example #10
0
def unzip(infile):
    gunzipfile, gz = os.path.splitext(infile)
    if not 'gz' in gz:
        #when running gunzip on file when
        return infile
    else:
       c3 = CommandLine('gunzip %s'%(infile))
       c3.run()
       return gunzipfile
Example #11
0
def travel_depth(command, surface_file, verbose=False):
    """
    Measure "travel depth" of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : string
        travel depth C++ executable command
    surface_file : string
        vtk file
    verbose : bool
        print statements?

    Returns
    -------
    depth_file: string
        vtk file with travel depth per vertex of mesh

    Examples
    --------
    >>> import os
    >>> import numpy as np
    >>> from mindboggle.shapes.surface_shapes import travel_depth
    >>> from mindboggle.mio.vtks import read_scalars
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> surface_file = fetch_data(urls['left_pial'], '', '.vtk')
    >>> verbose = False
    >>> ccode_path = os.environ['vtk_cpp_tools']
    >>> command = os.path.join(ccode_path, 'travel_depth', 'TravelDepthMain')
    >>> depth_file = travel_depth(command, surface_file, verbose)
    >>> scalars, name = read_scalars(depth_file)
    >>> np.allclose(scalars[0:8], [0.020259869839, 0.06009166489, 0.12858575442, 0.045639221313, 0.007742772964, 0.052839111255, 0.053538904296, 0.013158746337])
    True

    """
    import os
    from nipype.interfaces.base import CommandLine

    basename = os.path.splitext(os.path.basename(surface_file))[0]
    depth_file = os.path.join(os.getcwd(), basename + '.travel_depth.vtk')
    args = ' '.join([surface_file, depth_file])

    if verbose:
        print("{0} {1}".format(command, args))

    cli = CommandLine(command=command)
    cli.inputs.args = args
    cli.terminal_output = 'file'
    cli.run()

    if not os.path.exists(depth_file):
        raise IOError(depth_file + " not found")

    return depth_file
Example #12
0
def nii2nrrd(filename_nii, filename_bval, filename_bvec, out_prefix, out_suffix):
    import os
    import shutil

    from nipype.interfaces.base import CommandLine
    basename = experiment_dir + os.sep + out_prefix + os.sep + out_prefix + out_suffix
    cmd = CommandLine('./DWIConvert --inputVolume %s --outputVolume %s.nrrd --conversionMode FSLToNrrd --inputBValues %s --inputBVectors %s' % (filename_nii, basename, filename_bval, filename_bvec))
    print "NII->NRRD:" + cmd.cmd
    cmd.run()
    return os.path.abspath('%s.nrrd' % (basename))
Example #13
0
 def gunzip(file):
     import os
     os.mkdir("./out")
     from nipype.interfaces.base import CommandLine
     c = CommandLine(command="tar zxvf %s"%file)
     c.run()
     from nipype.utils.filemanip import split_filename
     _,base,_  = split_filename(file)
     
     return os.path.abspath(base)
Example #14
0
def dt2Image(bfloat_file, nii_file_header):

    import os
    import shutil
    from nipype.interfaces.base import CommandLine
    fileName, fileExtension = os.path.splitext(bfloat_file)
    head, root = os.path.split(fileName)
    cmd = CommandLine('dt2nii -inputfile %s -inputdatatype float -header %s -outputroot camino_' % (bfloat_file, nii_file_header))
    print "dt2nii:" + cmd.cmd
    cmd.run()
    return os.path.abspath('%s.nii' % (root))
def dtiprep(in_file, output_prefix):
    from glob import glob
    import os
    from nipype.interfaces.base import CommandLine
    cmd = CommandLine('DTIPrepExec -c -d -f %s -n %s/%s_notes.txt -p %s -w %s/%s.nrrd' % ((experiment_dir + '/' + output_prefix),(experiment_dir + '/' + output_prefix),output_prefix,DTIprep_protocol,experiment_dir,output_prefix))
    print "DTIPREP:" + cmd.cmd
    cmd.run()
    qcfile = experiment_dir + '/' + output_prefix + '/' + output_prefix + '_QCed.nrrd'
    xmlfile = experiment_dir + '/' + output_prefix + '/' + output_prefix + '_XMLQCResult.xml'
    sumfile = experiment_dir + '/' + output_prefix + '/' + output_prefix + '_QCReport.txt'
    return qcfile, xmlfile, sumfile
Example #16
0
def convert_audio_file(old_file, new_file, command='ffmpeg',
                       input_args='-i', output_args='-ac 2'):
    """
    Convert audio file to new format.

    Parameters
    ----------
    old_file : string
        full path to the input file
    new_file : string
        full path to the output file
    command : string
        executable command without arguments
    input_args : string
        arguments preceding input file name in command
    output_args : string
        arguments preceding output file name in command

    Returns
    -------
    new_file : string
        full path to the output file

    Examples
    --------
    >>> from mhealthx.xio import convert_audio_file
    >>> old_file = '/Users/arno/mhealthx_cache/mhealthx/feature_files/test.m4a'
    >>> new_file = 'test.wav'
    >>> command = 'ffmpeg'
    >>> input_args = '-y -i'
    >>> output_args = '-ac 2'
    >>> new_file = convert_audio_file(old_file, new_file, command, input_args, output_args)

    """
    import os
    from nipype.interfaces.base import CommandLine

    if not os.path.isfile(old_file):
        raise IOError("{0} does not exist.".format(old_file))
        new_file = None
    else:
        input_args = ' '.join([input_args, old_file, output_args, new_file])
        try:
            # Nipype command line wrapper:
            cli = CommandLine(command = command)
            cli.inputs.args = input_args
            cli.cmdline
            cli.run()
        except:
            import traceback; traceback.print_exc()
            print("'{0} {1}' unsuccessful".format(command, input_args))
            new_file = None

    return new_file
Example #17
0
def fslmath_op_custom(input_file, operation_str, output_prefix):
    import os
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    path, name, ext = split_filename(input_file)
    outfile = path + '/' + name + '_op' + ext
    cmd = CommandLine('fslmaths %s %s %s' % (input_file, operation_str, outfile))
    print "custom fslmaths command:" + cmd.cmd
    cmd.run()

    return outfile
Example #18
0
def geodesic_depth(command, surface_file, verbose=False):
    """
    Estimate geodesic depth of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : travel depth C++ executable command
    surface_file : ``vtk file``
    verbose : bool
        print statements?

    Returns
    -------
    depth_file: string
        vtk file with geodesic depth per vertex of mesh

    Examples
    --------
    >>> import os
    >>> import numpy as np
    >>> from mindboggle.shapes.surface_shapes import geodesic_depth
    >>> from mindboggle.mio.vtks import read_scalars
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> surface_file = fetch_data(urls['left_pial'], '', '.vtk')
    >>> verbose = False
    >>> ccode_path = os.environ['vtk_cpp_tools']
    >>> command = os.path.join(ccode_path, 'geodesic_depth', 'GeodesicDepthMain')
    >>> depth_file = geodesic_depth(command, surface_file, verbose)
    >>> scalars, name = read_scalars(depth_file)
    >>> [np.float("{0:.{1}f}".format(x, 5)) for x in scalars[0:8]]
    [0.02026, 0.06009, 0.12859, 0.04564, 0.00774, 0.05284, 0.05354, 0.01316]

    """
    import os
    from nipype.interfaces.base import CommandLine

    basename = os.path.splitext(os.path.basename(surface_file))[0]
    depth_file = os.path.join(os.getcwd(), basename + '.geodesic_depth.vtk')
    args = ' '.join([surface_file, depth_file])

    if verbose:
        print("{0} {1}".format(command, args))

    cli = CommandLine(command=command)
    cli.inputs.args = args
    cli.cmdline
    cli.run()

    if not os.path.exists(depth_file):
        raise IOError(depth_file + " not found")

    return depth_file
Example #19
0
def Voxel2Image(bfloat_file, nii_file_header):

    import os
    import shutil
    from nipype.interfaces.base import CommandLine
    fileName, fileExtension = os.path.splitext(bfloat_file)
    head, root = os.path.split(fileName)
    cmd = CommandLine('cat %s | fa -inputmodel dt | voxel2image -outputroot %s -header %s -components %s' % (bfloat_file, root, nii_file_header, 1))
    print "voxel2image:" + cmd.cmd
    cmd.run()
    return os.path.abspath('%s.nii' % (root))
Example #20
0
def DICOM2mgz(dicomfiles, out_prefix):
    import os
    import shutil
    from nipype.interfaces.base import CommandLine

    # Generate arguments from input
    input_str = ''
    for dicomfile in dicomfiles:
        input_str = input_str + ' -i ' + dicomfile + ' '
    cmd = CommandLine('recon-all %s -subjid %s' % (input_str, out_prefix))
    print "DICOM->NII:" + cmd.cmd
    cmd.run()
Example #21
0
def evaluate_surface_overlaps_cpp(command, labels_file1, labels_file2,
                                  output_file):
    """
    Measure surface overlap using Joachim Giard's code.

    Note: Fails if two files have different number of vertices.

    Parameters
    ----------
    command : string
        surface overlap C++ executable command
    labels_file1 : string
        ``vtk file`` with index labels for scalar values
    labels_file2 : string
        ``vtk file`` with index labels for scalar values
    output_file : string
        (optional) output file name

    Returns
    -------
    output_file : string
        name of output text file with overlap results

    Examples
    --------
    >>> import os
    >>> from mindboggle.evaluate.evaluate_labels import evaluate_surface_overlaps_cpp
    >>> from mindboggle.mindboggle import hashes_url
    >>> from mindboggle.mio.fetch_data import fetch_check_data
    >>> hashes, url, cache_env, cache = hashes_url()
    >>> ccode_path = os.environ['MINDBOGGLE_TOOLS']
    >>> command = os.path.join(ccode_path, 'surface_overlap', 'SurfaceOverlapMain')
    >>> label_file1 = 'lh.labels.DKT25.manual.vtk'
    >>> label_file2 = 'lh.labels.DKT31.manual.vtk'
    >>> file1 = fetch_check_data(label_file1, url, hashes, cache_env, cache)
    >>> file2 = fetch_check_data(label_file2, url, hashes, cache_env, cache)
    >>> output_file = ''
    >>> evaluate_surface_overlaps_cpp(command, file1, file2, output_file)

    """
    import os
    from nipype.interfaces.base import CommandLine

    if not output_file:
        output_file = os.path.basename(labels_file1) + '_and_' + \
                           os.path.basename(labels_file2) + '.txt'
    output_file = os.path.join(os.getcwd(), output_file)
    cli = CommandLine(command = command)
    cli.inputs.args = ' '.join([labels_file1, labels_file2, output_file])
    cli.cmdline
    cli.run()

    return output_file
Example #22
0
def evaluate_surface_overlaps_cpp(command, labels_file1, labels_file2,
                                  output_file):
    """
    Measure surface overlap using Joachim Giard's code.

    Note: Fails if two files have different number of vertices.

    Parameters
    ----------
    command : string
        surface overlap C++ executable command
    labels_file1 : string
        ``vtk file`` with index labels for scalar values
    labels_file2 : string
        ``vtk file`` with index labels for scalar values
    output_file : string
        (optional) output file name

    Returns
    -------
    output_file : string
        name of output text file with overlap results

    Examples
    --------
    >>> # Compare surface label overlaps in trivial case: brain with itself:
    >>> import os
    >>> from mindboggle.evaluate.evaluate_labels import evaluate_surface_overlaps_cpp
    >>> from mindboggle.mio.fetch_data import fetch_data
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> file1 = fetch_data(urls['left_freesurfer_labels'], '', '.nii.gz')
    >>> file2 = fetch_data(urls['left_freesurfer_labels'], '', '.nii.gz')
    >>> ccode_path = os.environ['MINDBOGGLE_TOOLS'] # doctest: +SKIP
    >>> command = os.path.join(ccode_path, 'surface_overlap', 'SurfaceOverlapMain') # doctest: +SKIP
    >>> output_file = ''
    >>> evaluate_surface_overlaps_cpp(command, file1, file2, output_file) # doctest: +SKIP

    """
    import os
    from nipype.interfaces.base import CommandLine

    if not output_file:
        output_file = os.path.basename(labels_file1) + '_and_' + \
                           os.path.basename(labels_file2) + '.txt'
    output_file = os.path.join(os.getcwd(), output_file)
    cli = CommandLine(command = command)
    cli.inputs.args = ' '.join([labels_file1, labels_file2, output_file])
    cli.cmdline
    cli.run()

    return output_file
def elastix_AnalyzeWarp(input_file, output_prefix, output_sub_prefix):
    import os
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    out_dir = experiment_dir + '/' + output_prefix + '/' + output_sub_prefix + '/QC'
    # Create output directory if it does not exist
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    cmd = CommandLine((elastix_dir + 'transformix -def all -jac all -jacmat all -out %s -tp %s') % (out_dir, input_file))
    print "transformix: " + cmd.cmd
    cmd.run()
    return (out_dir + os.sep + 'deformationField.tiff'), (out_dir + os.sep + 'spatialJacobian.tiff'), (out_dir + os.sep + 'fullSpatialJacobian.tiff'), (out_dir + os.sep + 'transformix.log')
Example #24
0
def mri_convert_bm(in_file, out_file):
    # Use FREESURFERs mri_convert since the Traited interface produces errors!
    from nipype.interfaces.base import CommandLine

    out_orientation = 'RAS'

    cli = CommandLine(command='mri_convert')
    cli.inputs.args = ('--out_orientation ' + out_orientation +
                        ' --input_volume ' + in_file +
                        ' --output_volume ' + out_file)
    cli.run()

    return out_file
def nrrd2nii_pmap(in_file, output_prefix):
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    _, name, _ = split_filename(in_file)
    out_vol = experiment_dir + '/' + output_prefix + '/' + ('%s.nii.gz' % name)

    cmd = CommandLine(('DWIConvert --inputVolume %s --outputVolume %s'
                       ' --conversionMode NrrdToFSL') % (in_file, out_vol))

    print "NRRD->NIFTI:" + cmd.cmd
    cmd.run()
    return opap(out_vol), opap(out_bval), opap(out_bvec)
def elastix_PointsWarp(input_file, inputpoints_file, output_prefix, output_sub_prefix):
    import os
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    #    out_dir = experiment_dir + '/' + output_prefix + '/' + output_sub_prefix + '/QC'
    out_dir = '.'
    # Create output directory if it does not exist
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    cmd = CommandLine((elastix_dir + 'transformix -out %s -def %s -tp %s') % (out_dir, inputpoints_file, input_file))
    print "transformix: " + cmd.cmd
    cmd.run()
    return (out_dir + os.sep + 'outputpoints.txt')
def dicom2nii(dicomdir, experiment_dir, out_prefix, out_suffix):
    import os
    import shutil
    from nipype.interfaces.base import CommandLine

    dirnames = os.listdir(dicomdir)
    for d_i in range(len(dirnames)):
        fileName, fileExtension = os.path.splitext(dirnames[d_i])
        if fileExtension == '.gz':
            os.remove(os.path.join(dicomdir, dirnames[d_i]))
        if fileExtension == '.bval':
            os.remove(os.path.join(dicomdir, dirnames[d_i]))
        if fileExtension == '.bvec':
            os.remove(os.path.join(dicomdir, dirnames[d_i]))

    from nipype.interfaces.base import CommandLine
    basename = experiment_dir + '/' + out_prefix + '/' + out_prefix + out_suffix
    cmd = CommandLine('/Users/eija/Documents/osx/dcm2nii -a Y -d N -e N -i N -p N -o %s %s' % (basename,dicomdir))
    print "DICOM->NII:" + cmd.cmd
    cmd.run()

    dirnames = os.listdir(dicomdir)
    filename_nii = ''
    filename_bvec = ''
    filename_bval = ''
    for d_i in range(len(dirnames)):
        fileName, fileExtension = os.path.splitext(dirnames[d_i])
        if fileExtension == '.gz':
            if len(filename_nii) > 0:
                raise "multiple copies of .nii.gz was found"
            filename_nii = fileName
        if fileExtension == '.bval':
            if len(filename_nii) > 0:
                raise "multiple copies of .bval was found"
            filename_bval = fileName
        if fileExtension == '.bvec':
            if len(filename_nii) > 0:
                raise "multiple copies of .bvec was found"
            filename_bvec = fileName

    outfile = move_to_results((dicomdir + '/' + filename_nii + '.gz'), experiment_dir, out_prefix)
    outfile_bval = ''
    outfile_bvec = ''
    if len(filename_bval) > 0:
        outfile_bval = move_to_results((dicomdir + '/' + filename_bval + '.bval'), experiment_dir, out_prefix)
    if len(filename_bvec) > 0:
        outfile_bvec = move_to_results((dicomdir + '/' + filename_bvec + '.bvec'), experiment_dir, out_prefix)

    return outfile, outfile_bval, outfile_bvec
def gunzip_to(filename, out_prefix, destination):
    import os
    import shutil
    from nipype.interfaces.base import CommandLine
    
    cmd = CommandLine('gunzip -f %s' % (filename))
    print "gunzip NII.GZ:" + cmd.cmd
    cmd.run()
    
    basename = os.path.basename(filename[:len(filename)-3])
    outfile = destination + '/' + basename
    if os.path.isfile(outfile):
        os.remove(outfile)
    shutil.move(filename[:len(filename)-3],outfile)
    return outfile
Example #29
0
def remove_files(files):
    """removes files """
    if not hasattr(files, '__iter__'):
        cl = CommandLine('rm %s'% files)
        out = cl.run()
        if not out.runtime.returncode == 0:
            print 'failed to delete %s' % files
            print out.runtime.stderr
        return
    for f in files:
        cl = CommandLine('rm %s'% f)
        out = cl.run()
        if not out.runtime.returncode == 0:
            print 'failed to delete %s' % f
            print out.runtime.stderr
Example #30
0
 def _submit_batchtask(self, scriptfile, node):
     cmd = CommandLine('bsub', environ=os.environ.data,
                       terminal_output='allatonce')
     path = os.path.dirname(scriptfile)
     bsubargs = ''
     if self._bsub_args:
         bsubargs = self._bsub_args
     if 'bsub_args' in node.plugin_args:
         if 'overwrite' in node.plugin_args and\
            node.plugin_args['overwrite']:
             bsubargs = node.plugin_args['bsub_args']
         else:
             bsubargs += (" " + node.plugin_args['bsub_args'])
     if '-o' not in bsubargs:  # -o outfile
         bsubargs = '%s -o %s' % (bsubargs, scriptfile + ".log")
     if '-e' not in bsubargs:
         bsubargs = '%s -e %s' % (bsubargs, scriptfile + ".log")  # -e error file
     if node._hierarchy:
         jobname = '.'.join((os.environ.data['LOGNAME'],
                             node._hierarchy,
                             node._id))
     else:
         jobname = '.'.join((os.environ.data['LOGNAME'],
                             node._id))
     jobnameitems = jobname.split('.')
     jobnameitems.reverse()
     jobname = '.'.join(jobnameitems)
     cmd.inputs.args = '%s -J %s sh %s' % (bsubargs,
                                           jobname,
                                           scriptfile)  # -J job_name_spec
     logger.debug('bsub ' + cmd.inputs.args)
     oldlevel = iflogger.level
     iflogger.setLevel(logging.getLevelName('CRITICAL'))
     tries = 0
     while True:
         try:
             result = cmd.run()
         except Exception as e:
             if tries < self._max_tries:
                 tries += 1
                 sleep(
                     self._retry_timeout)  # sleep 2 seconds and try again.
             else:
                 iflogger.setLevel(oldlevel)
                 raise RuntimeError('\n'.join((('Could not submit lsf task'
                                                ' for node %s') % node._id,
                                               str(e))))
         else:
             break
     iflogger.setLevel(oldlevel)
     # retrieve lsf taskid
     match = re.search('<(\d*)>', result.runtime.stdout)
     if match:
         taskid = int(match.groups()[0])
     else:
         raise ScriptError("Can't parse submission job output id: %s" %
                           result.runtime.stdout)
     self._pending[taskid] = node.output_dir()
     logger.debug('submitted lsf task: %d for node %s' % (taskid, node._id))
     return taskid
Example #31
0
 def _grab_xml(self, module):
     cmd = CommandLine(command="Slicer3", args="--launch %s --xml" % module)
     ret = cmd.run()
     if ret.runtime.returncode == 0:
         return xml.dom.minidom.parseString(ret.runtime.stdout)
     else:
         raise Exception(cmd.cmdline + " failed:\n%s" % ret.runtime.stderr)
Example #32
0
 def _submit_batchtask(self, scriptfile, node):
     cmd = CommandLine('qsub', environ=os.environ.data,
                       terminal_output='allatonce')
     path = os.path.dirname(scriptfile)
     qsubargs = ''
     if self._qsub_args:
         qsubargs = self._qsub_args
     if 'qsub_args' in node.plugin_args:
         if 'overwrite' in node.plugin_args and \
                 node.plugin_args['overwrite']:
             qsubargs = node.plugin_args['qsub_args']
         else:
             qsubargs += (" " + node.plugin_args['qsub_args'])
     if '-o' not in qsubargs:
         qsubargs = '%s -o %s' % (qsubargs, path)
     if '-e' not in qsubargs:
         qsubargs = '%s -e %s' % (qsubargs, path)
     if node._hierarchy:
         jobname = '.'.join((os.environ.data['LOGNAME'],
                             node._hierarchy,
                             node._id))
     else:
         jobname = '.'.join((os.environ.data['LOGNAME'],
                             node._id))
     jobnameitems = jobname.split('.')
     jobnameitems.reverse()
     jobname = '.'.join(jobnameitems)
     jobname = qsub_sanitize_job_name(jobname)
     cmd.inputs.args = '%s -N %s %s' % (qsubargs,
                                        jobname,
                                        scriptfile)
     oldlevel = iflogger.level
     iflogger.setLevel(logging.getLevelName('CRITICAL'))
     tries = 0
     result = list()
     while True:
         try:
             result = cmd.run()
         except Exception as e:
             if tries < self._max_tries:
                 tries += 1
                 time.sleep(
                     self._retry_timeout)  # sleep 2 seconds and try again.
             else:
                 iflogger.setLevel(oldlevel)
                 raise RuntimeError('\n'.join((('Could not submit sge task'
                                                ' for node %s') % node._id,
                                               str(e))))
         else:
             break
     iflogger.setLevel(oldlevel)
     # retrieve sge taskid
     lines = [line for line in result.runtime.stdout.split('\n') if line]
     taskid = int(re.match("Your job ([0-9]*) .* has been submitted",
                           lines[-1]).groups()[0])
     self._pending[taskid] = node.output_dir()
     self._refQstatSubstitute.add_startup_job(taskid, cmd.cmdline)
     logger.debug('submitted sge task: %d for node %s with %s' %
                  (taskid, node._id, cmd.cmdline))
     return taskid
Example #33
0
def run_palm(cope_file,
             design_file,
             contrast_file,
             group_file,
             mask_file,
             cluster_threshold=3.09):
    import os
    from glob import glob
    from nipype.interfaces.base import CommandLine
    #cmd = ("palm -i {cope_file} -m {mask_file} -d {design_file} -t {contrast_file} -eb {group_file} -T "
    #       "-C {cluster_threshold} -Cstat extent -fdr -noniiclass -twotail -logp -zstat")
    #cl = CommandLine(cmd.format(cope_file=cope_file, mask_file=mask_file, design_file=design_file,
    #                            contrast_file=contrast_file,
    #                            group_file=group_file, cluster_threshold=cluster_threshold))

    # XXX: ideally we should make it more fancy, but since we're only doing
    # 1-sample t-tests we need to omit the design, contrast, and group files
    # as for PALM's FAQs
    cmd = (
        "palm -i {cope_file} -m {mask_file} -T "
        "-C {cluster_threshold} -Cstat extent -fdr -noniiclass -twotail -logp -zstat"
    )
    cl = CommandLine(
        cmd.format(cope_file=cope_file,
                   mask_file=mask_file,
                   cluster_threshold=cluster_threshold))
    results = cl.run(terminal_output='file')
    return [os.path.join(os.getcwd(), val) for val in sorted(glob('palm*'))]
Example #34
0
def run_rand(cope_file,
             design_file,
             contrast_file,
             group_file,
             mask_file,
             cluster_threshold=2.3,
             n=10000):

    import os
    from glob import glob
    from nipype.interfaces.base import CommandLine

    cmd = (
        "randomise -i {cope_file} -m {mask_file} -d {design_file} -t {contrast_file} -e {group_file} -T "
        "-c {cluster_threshold} -x -n {n}")

    cl = CommandLine(
        cmd.format(cope_file=cope_file,
                   mask_file=mask_file,
                   design_file=design_file,
                   contrast_file=contrast_file,
                   group_file=group_file,
                   cluster_threshold=cluster_threshold,
                   n=n))
    results = cl.run(terminal_output='file')
    return [os.path.join(os.getcwd(), val) for val in sorted(glob('rand*'))]
Example #35
0
 def _submit_batchtask(self, scriptfile, node):
     cmd = CommandLine('bsub',
                       environ=os.environ.data,
                       terminal_output='allatonce')
     path = os.path.dirname(scriptfile)
     bsubargs = ''
     if self._bsub_args:
         bsubargs = self._bsub_args
     if 'bsub_args' in node.plugin_args:
         if 'overwrite' in node.plugin_args and\
            node.plugin_args['overwrite']:
             bsubargs = node.plugin_args['bsub_args']
         else:
             bsubargs += (" " + node.plugin_args['bsub_args'])
     if '-o' not in bsubargs:  # -o outfile
         bsubargs = '%s -o %s' % (bsubargs, scriptfile + ".log")
     if '-e' not in bsubargs:
         bsubargs = '%s -e %s' % (bsubargs, scriptfile + ".log"
                                  )  # -e error file
     if node._hierarchy:
         jobname = '.'.join(
             (os.environ.data['LOGNAME'], node._hierarchy, node._id))
     else:
         jobname = '.'.join((os.environ.data['LOGNAME'], node._id))
     jobnameitems = jobname.split('.')
     jobnameitems.reverse()
     jobname = '.'.join(jobnameitems)
     cmd.inputs.args = '%s -J %s sh %s' % (bsubargs, jobname, scriptfile
                                           )  # -J job_name_spec
     logger.debug('bsub ' + cmd.inputs.args)
     oldlevel = iflogger.level
     iflogger.setLevel(logging.getLevelName('CRITICAL'))
     tries = 0
     while True:
         try:
             result = cmd.run()
         except Exception as e:
             if tries < self._max_tries:
                 tries += 1
                 sleep(
                     self._retry_timeout)  # sleep 2 seconds and try again.
             else:
                 iflogger.setLevel(oldlevel)
                 raise RuntimeError('\n'.join(
                     (('Could not submit lsf task'
                       ' for node %s') % node._id, str(e))))
         else:
             break
     iflogger.setLevel(oldlevel)
     # retrieve lsf taskid
     match = re.search('<(\d*)>', result.runtime.stdout)
     if match:
         taskid = int(match.groups()[0])
     else:
         raise ScriptError("Can't parse submission job output id: %s" %
                           result.runtime.stdout)
     self._pending[taskid] = node.output_dir()
     logger.debug('submitted lsf task: %d for node %s' % (taskid, node._id))
     return taskid
Example #36
0
def nrrd2nii(in_file, experiment_dir, output_prefix):
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    _, name, _ = split_filename(in_file)
    out_vol = experiment_dir + '/' + output_prefix + '/' + ('%s.nii.gz' % name)
    out_bval = experiment_dir + '/' + output_prefix + '/' + ('%s.bval' % name)
    out_bvec = experiment_dir + '/' + output_prefix + '/' + ('%s.bvec' % name)

    cmd = CommandLine(
        ('DWIConvert --inputVolume %s --outputVolume %s --outputBValues %s'
         ' --outputBVectors %s --conversionMode NrrdToFSL') %
        (in_file, out_vol, out_bval, out_bvec))

    print "NRRD->NIFTI:" + cmd.cmd
    cmd.run()
    return opap(out_vol), opap(out_bval), opap(out_bvec)
Example #37
0
    def _submit_batchtask(self, scriptfile, node):
        """
        This is more or less the _submit_batchtask from sge.py with flipped variable
        names, different command line switches, and different output formatting/processing
        """
        cmd = CommandLine('sbatch',
                          environ=os.environ.data,
                          terminal_output='allatonce')
        path = os.path.dirname(scriptfile)

        sbatch_args = ''
        if self._sbatch_args:
            sbatch_args = self._sbatch_args
        if 'sbatch_args' in node.plugin_args:
            if 'overwrite' in node.plugin_args and\
               node.plugin_args['overwrite']:
                sbatch_args = node.plugin_args['sbatch_args']
            else:
                sbatch_args += (" " + node.plugin_args['sbatch_args'])
        if '-o' not in sbatch_args:
            sbatch_args = '%s -o %s' % (sbatch_args,
                                        os.path.join(path, 'slurm-%j.out'))
        if '-e' not in sbatch_args:
            sbatch_args = '%s -e %s' % (sbatch_args,
                                        os.path.join(path, 'slurm-%j.out'))
        if '-p' not in sbatch_args:
            sbatch_args = '%s -p normal' % (sbatch_args)
        if '-n' not in sbatch_args:
            sbatch_args = '%s -n 16' % (sbatch_args)
        if '-t' not in sbatch_args:
            sbatch_args = '%s -t 1:00:00' % (sbatch_args)
        if node._hierarchy:
            jobname = '.'.join(
                (os.environ.data['LOGNAME'], node._hierarchy, node._id))
        else:
            jobname = '.'.join((os.environ.data['LOGNAME'], node._id))
        jobnameitems = jobname.split('.')
        jobnameitems.reverse()
        jobname = '.'.join(jobnameitems)
        cmd.inputs.args = '%s -J %s %s' % (sbatch_args, jobname, scriptfile)
        oldlevel = iflogger.level
        iflogger.setLevel(logging.getLevelName('CRITICAL'))
        tries = 0
        while True:
            try:
                result = cmd.run()
            except Exception, e:
                if tries < self._max_tries:
                    tries += 1
                    sleep(
                        self._retry_timeout)  # sleep 2 seconds and try again.
                else:
                    iflogger.setLevel(oldlevel)
                    raise RuntimeError('\n'.join(
                        (('Could not submit sbatch task'
                          ' for node %s') % node._id, str(e))))
            else:
                break
Example #38
0
def tar_cmd(infile):
    """ given a ipped tar archive, untars"""
    cwd = os.getcwd()
    pth, nme = os.path.split(infile)
    os.chdir(pth)
    cl = CommandLine('tar xfvz %s'%(infile))
    cout = cl.run()
    os.chdir(cwd)
    return pth
Example #39
0
def measure_surface_overlap(command, labels_file1, labels_file2):
    """
    Measure surface overlap using Joachim Giard's code.

    Parameters
    ----------
    command : surface overlap C++ executable command
    labels_file1 : ``vtk file`` with index labels for scalar values
    labels_file2 : ``vtk file`` with index labels for scalar values

    Returns
    -------
    overlap_file : string
        name of output text file with overlap results

    Examples
    --------
    >>> import os
    >>> from mindboggle.evaluate.evaluate_labels import measure_surface_overlap
    >>> from mindboggle.DATA import hashes_url
    >>> from mindboggle.utils.io_uri import retrieve_data
    >>> hashes, url, cache_env, cache = hashes_url()
    >>> ccode_path = os.environ['MINDBOGGLE_TOOLS']
    >>> command = os.path.join(ccode_path, 'surface_overlap', 'SurfaceOverlapMain')
    >>> label_file1 = 'lh.labels.DKT25.manual.vtk'
    >>> label_file2 = 'lh.labels.DKT31.manual.vtk'
    >>> file1 = retrieve_data(label_file1, url, hashes, cache_env, cache)
    >>> file2 = retrieve_data(label_file2, url, hashes, cache_env, cache)
    >>> #
    >>> measure_surface_overlap(command, file1, file2)

    """
    import os
    from nipype.interfaces.base import CommandLine

    overlap_filename = os.path.basename(labels_file1) + '_and_' + \
                       os.path.basename(labels_file2) + '.txt'
    overlap_file = os.path.join(os.getcwd(), overlap_filename)
    cli = CommandLine(command=command)
    cli.inputs.args = ' '.join([labels_file1, labels_file2, overlap_file])
    cli.cmdline
    cli.run()

    return overlap_file
Example #40
0
def elastix(input_file, target_file, mask_file, output_prefix,
            output_sub_prefix):
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    out_dir = experiment_dir + '/' + output_prefix + '/' + output_sub_prefix
    # Create output directory if it does not exist
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

        #    cmd = CommandLine(('elastix -f %s -m %s -fMask %s -out %s -p %s -p %s -threads 8') % (target_file, input_file, mask_file, out_dir, param_rigid, param_BSpline))
    #cmd = CommandLine(('/Users/eija/Desktop/SW/Elastix/elastix_macosx64_v4.7/bin/elastix -f %s -m %s -out %s -p %s -threads 8') % (target_file, input_file, out_dir, param_rigid))
    cmd = CommandLine((
        '/Users/eija/Desktop/SW/Elastix/elastix_macosx64_v4.7/bin/elastix -f %s -m %s -out %s -p %s -p %s -threads 6'
    ) % (target_file, input_file, out_dir, param_rigid, param_BSpline))

    print "elastix: " + cmd.cmd
    cmd.run()
    return out_dir + '/' + 'result.0.dcm'
def elastix_AnalyzeWarp(input_file, output_prefix, output_sub_prefix):
    import os
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    out_dir = experiment_dir + '/' + output_prefix + '/' + output_sub_prefix + '/QC'
    # Create output directory if it does not exist
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    cmd = CommandLine(
        (elastix_dir +
         'transformix -def all -jac all -jacmat all -out %s -tp %s') %
        (out_dir, input_file))
    print "transformix: " + cmd.cmd
    cmd.run()
    return (out_dir + os.sep + 'deformationField.tiff'), (
        out_dir + os.sep + 'spatialJacobian.tiff'), (
            out_dir + os.sep + 'fullSpatialJacobian.tiff'), (out_dir + os.sep +
                                                             'transformix.log')
Example #42
0
 def _submit_batchtask(self, scriptfile, node):
     cmd = CommandLine('condor_qsub',
                       environ=os.environ.data,
                       terminal_output='allatonce')
     path = os.path.dirname(scriptfile)
     qsubargs = ''
     if self._qsub_args:
         qsubargs = self._qsub_args
     if 'qsub_args' in node.plugin_args:
         if 'overwrite' in node.plugin_args and\
            node.plugin_args['overwrite']:
             qsubargs = node.plugin_args['qsub_args']
         else:
             qsubargs += (" " + node.plugin_args['qsub_args'])
     if self._qsub_args:
         qsubargs = self._qsub_args
     if '-o' not in qsubargs:
         qsubargs = '%s -o %s' % (qsubargs, path)
     if '-e' not in qsubargs:
         qsubargs = '%s -e %s' % (qsubargs, path)
     if node._hierarchy:
         jobname = '.'.join(
             (os.environ.data['LOGNAME'], node._hierarchy, node._id))
     else:
         jobname = '.'.join((os.environ.data['LOGNAME'], node._id))
     jobnameitems = jobname.split('.')
     jobnameitems.reverse()
     jobname = '.'.join(jobnameitems)
     cmd.inputs.args = '%s -N %s %s' % (qsubargs, jobname, scriptfile)
     oldlevel = iflogger.level
     iflogger.setLevel(logging.getLevelName('CRITICAL'))
     tries = 0
     while True:
         try:
             result = cmd.run()
         except Exception as e:
             if tries < self._max_tries:
                 tries += 1
                 sleep(
                     self._retry_timeout)  # sleep 2 seconds and try again.
             else:
                 iflogger.setLevel(oldlevel)
                 raise RuntimeError('\n'.join(
                     (('Could not submit condor '
                       'cluster'
                       ' for node %s') % node._id, str(e))))
         else:
             break
     iflogger.setLevel(oldlevel)
     # retrieve condor clusterid
     taskid = int(result.runtime.stdout.split(' ')[2])
     self._pending[taskid] = node.output_dir()
     logger.debug('submitted condor cluster: %d for node %s' %
                  (taskid, node._id))
     return taskid
Example #43
0
    def _run_interface(self, runtime):

        #change the name of the first iteration directory to prevent overlap of files with second iteration
        if self.inputs.second:
            mk_tmp = CommandLine('mv', args='ants_mc_tmp first_ants_mc_tmp')
            mk_tmp.run()

        #make a tmp directory to store the files
        import os
        os.makedirs('ants_mc_tmp', exist_ok=True)

        # Run the command line as a natural CommandLine interface
        runtime = super(antsMotionCorr, self)._run_interface(runtime)

        setattr(self, 'csv_params', 'ants_mc_tmp/motcorrMOCOparams.csv')
        setattr(self, 'motcorr_warp', 'ants_mc_tmp/motcorrWarp.nii.gz')
        setattr(self, 'mc_corrected_bold', 'ants_mc_tmp/motcorr.nii.gz')
        setattr(self, 'avg_image', 'ants_mc_tmp/motcorr_avg.nii.gz')

        return runtime
Example #44
0
 def _is_pending(self, taskid):
     cmd = CommandLine('condor_q')
     cmd.inputs.args = '%d' % taskid
     # check condor cluster
     oldlevel = iflogger.level
     iflogger.setLevel(logging.getLevelName('CRITICAL'))
     result = cmd.run(ignore_exception=True)
     iflogger.setLevel(oldlevel)
     if result.runtime.stdout.count('\n%d' % taskid):
         return True
     return False
Example #45
0
def make_whole_cerebellume(aseg):
      """
      os.system('fslmaths rad_aseg -thr 46 -uthr 47 whole_right_cerebellum')
      os.system('fslmaths rad_aseg -thr 7 -uthr 8 whole_left_cerebellum')
      os.system('fslmaths whole_left_cerebellum -add whole_right_cerebellum -bin whole_cerebellum')
      """
      cwd = os.getcwd()
      pth, nme = os.path.split(aseg)
      os.chdir(pth)
      cmd = 'fslmaths %s -thr 46 -uthr 47 whole_right_cerebellum'%(aseg)
      cl = CommandLine(cmd)
      cout = cl.run()
      if not cout.runtime.returncode == 0:
            os.chdir(cwd)
            print 'Unable to create  right whole cerebellum for %s'%(aseg)
            return None
      
      cmd = 'fslmaths %s -thr 7 -uthr 8 whole_left_cerebellum'%(aseg)
      cl2 = CommandLine(cmd)
      cout2 = cl2.run()
      if not cout2.runtime.returncode == 0:
            os.chdir(cwd)
            print 'Unable to create  whole left cerebellum for %s'%(aseg)
            return None     

      cmd = 'fslmaths whole_left_cerebellum -add whole_right_cerebellum' + \
            ' -bin whole_cerebellum'
      cl3 = CommandLine(cmd)
      cout3 = cl3.run()
      if not cout3.runtime.returncode == 0:
            os.chdir(cwd)
            print 'Unable to create  whole cerebellum for %s'%(aseg)
            print cout3.runtime.stderr
            print cout3.runtime.stdout
            return None     
      cmd = 'rm whole_right_cerebellum.* whole_left_cerebellum.*'
      cl4 = CommandLine(cmd)
      cout4 = cl4.run()      
      whole_cerebellum = glob('%s/whole_cerebellum.*'%(pth))
      os.chdir(cwd)
      return whole_cerebellum[0]
Example #46
0
def ecat2nifti(ecat, newname):
    """run ecat_convert_nibabel.py"""
    cmd = 'ecat_convert_nibabel.py'
    format = '-format NIFTI'
    outname = '-newname %s'%(newname)
    cmdstr = ' '.join([cmd, format, outname,ecat])    
    cl = CommandLine(cmdstr)
    out = cl.run()
    if not out.runtime.returncode == 0:
        return False
    else:
        return True
def run_palm(cope_file, design_file, contrast_file, group_file, mask_file, 
             cluster_threshold=3.09):
    import os
    from glob import glob
    from nipype.interfaces.base import CommandLine
    cmd = ("palm -i {cope_file} -m {mask_file} -d {design_file} -t {contrast_file} -eb {group_file} -T " 
           "-C {cluster_threshold} -Cstat extent -fdr -noniiclass -twotail -logp -zstat")
    cl = CommandLine(cmd.format(cope_file=cope_file, mask_file=mask_file, design_file=design_file, 
                                contrast_file=contrast_file,
                                group_file=group_file, cluster_threshold=cluster_threshold))
    results = cl.run(terminal_output='file')
    return [os.path.join(os.getcwd(), val) for val in sorted(glob('palm*'))]
Example #48
0
def zip_files(files):
    if not hasattr(files, '__iter__'):
        files = [files]
    for f in files:
        base, ext = os.path.splitext(f)
        if 'gz' in ext:
            # file already gzipped
            continue
        cmd = CommandLine('gzip %s' % f)
        cout = cmd.run()
        if not cout.runtime.returncode == 0:
            logging.error('Failed to zip %s'%(f))
Example #49
0
def run_resample(in_file, like):
    import os
    from glob import glob
    from nipype.interfaces.base import CommandLine

    #cmd = ("palm -i {cope_file} -m {mask_file} -d {design_file} -t {contrast_file} -eb {group_file} -T "
    #   "-fdr -noniiclass -twotail -logp -zstat")
    cmd = ("rg_realign {in_file} {like} resampled trf.mat")

    cl = CommandLine(cmd.format(in_file=in_file, like=like))
    results = cl.run(terminal_output='file')
    return os.path.join(os.getcwd(), 'trf.mat')
Example #50
0
def convert(infile, outfile):
    """converts freesurfer .mgz format to nifti
    """
    c1 = CommandLine('mri_convert --out_orientation LAS %s %s'%(infile,
                                                                outfile))
    out = c1.run()
    if not out.runtime.returncode == 0:
        #failed
        print 'did not convert %s from .mgz to .nii'%(infile)
    else:
        path = os.path.split(infile)[0]
        niifile = os.path.join(path,outfile)
        return niifile
def DICOM2animatedGIF(dcmdir, outputpath, slice_i, suffix):

    dcmio = DicomIO.DicomIO()
    dwidcm = dcmio.ReadDICOM_frames(dcmdir)
    # Write all frames of slice into set of png files
    for frame_i in range(len(dwidcm)):
        slice = dwidcm[frame_i][slice_i].pixel_array
        dimx = slice.shape[0]
        dimy = slice.shape[1]
        newImg1 = PIL.Image.new('L', (dimx, dimy))
        pixels1 = newImg1.load()
        for i in range (0, dimx):
            for j in range (0, dimy):
                pixels1[i, j] = float(slice[i, j])
        #pixels1[i, j] = float(slice[i, j]) * dwidcm[frame_i][slice_i].RescaleSlope + dwidcm[frame_i][slice_i].RescaleIntercept
        newImg1.save((outputpath + '_' + ('%02d' % frame_i) + '.png'),'PNG')
    cmd = CommandLine('convert -delay 25 -loop 0 %s_*.png %s_%s.gif' % (outputpath, outputpath, suffix))
    cmd.run()
    for frame_i in range(len(dwidcm)):
        os.remove((outputpath + '_' + ('%02d' % frame_i) + '.png'))
    print "convert (ImageMagick):" + cmd.cmd
    return (outputpath + '.gif')
Example #52
0
def travel_depth(command, surface_file, verbose=False):
    """
    Measure "travel depth" of each vertex in a surface mesh.
    (Calls Joachim Giard's C++ code)

    Parameters
    ----------
    command : string
        travel depth C++ executable command
    surface_file : string
        vtk file
    verbose : bool
        print statements?

    Returns
    -------
    depth_file: string
        vtk file with travel depth per vertex of mesh

    """
    import os
    from nipype.interfaces.base import CommandLine

    basename = os.path.splitext(os.path.basename(surface_file))[0]
    depth_file = os.path.join(os.getcwd(), basename + '.travel_depth.vtk')
    args = ' '.join([surface_file, depth_file])

    if verbose:
        print("{0} {1}".format(command, args))

    cli = CommandLine(command=command)
    cli.inputs.args = args
    cli.cmdline
    cli.run()

    if not os.path.exists(depth_file):
        raise IOError(depth_file + " not found")

    return depth_file
Example #53
0
def unzip_file(infile):
    """ looks for gz  at end of file,
    unzips and returns unzipped filename"""
    base, ext = os.path.splitext(infile)
    if not ext == '.gz':
        return infile
    else:
        cmd = CommandLine('gunzip %s' % infile)
        cout = cmd.run()
        if not cout.runtime.returncode == 0:
            print 'Failed to unzip %s'%(infile)
            return None
        else:
            return base
Example #54
0
def convert_dicom(dcm0, fname):
    """given first dicom and fname uses mri_convert to convert
    to a 4d nii.gz file"""
    

    cmd = '/usr/local/freesurfer_x86_64-5.1.0/bin/mri_convert '
    cmd = cmd + ' --out_orientation LAS %s %s'%(dcm0, fname)
    cl = CommandLine(cmd)
    cout = cl.run()
    if not cout.runtime.returncode == 0:
        logging.error('DICOM Failed to convert %s'%(dcm0))
        return None
    else:
        return fname
Example #55
0
def make_brainstem(aseg):

      cwd = os.getcwd()
      pth, nme = os.path.split(aseg)
      os.chdir(pth)
      cl = CommandLine('fslmaths %s -thr 16 -uthr 16 brainstem'% (aseg))
      cout = cl.run()
      os.chdir(cwd)
      if not cout.runtime.returncode == 0:
            print 'Unable to create brainstem for %s'%(aseg)
            return None
      else:
            os.remove(aseg)
            return 'brainstem'
Example #56
0
def copy_file(infile, newdir):
    """ copy infile to new directory
    return full path of new file
    """
    cl = CommandLine('cp %s %s'%(infile, newdir))
    out = cl.run()
    if not out.runtime.returncode == 0:
        print 'failed to copy %s' % infile
        print out.runtime.stderr
        return None
    else:
        basenme = os.path.split(infile)[1]
        newfile = os.path.join(newdir, basenme)
        return newfile
Example #57
0
 def _submit_batchtask(self, scriptfile, node):
     cmd = CommandLine('qsub', environ=os.environ.data,
                       terminal_output='allatonce')
     path = os.path.dirname(scriptfile)
     qsubargs = ''
     if self._qsub_args:
         qsubargs = self._qsub_args
     if 'qsub_args' in node.plugin_args:
         if 'overwrite' in node.plugin_args and \
                 node.plugin_args['overwrite']:
             qsubargs = node.plugin_args['qsub_args']
         else:
             qsubargs += (" " + node.plugin_args['qsub_args'])
     if '-o' not in qsubargs:
         qsubargs = '%s -o %s' % (qsubargs, path)
     if '-e' not in qsubargs:
         qsubargs = '%s -e %s' % (qsubargs, path)
     if node._hierarchy:
         jobname = '.'.join((os.environ.data['LOGNAME'],
                             node._hierarchy,
                             node._id))
     else:
         jobname = '.'.join((os.environ.data['LOGNAME'],
                             node._id))
     jobnameitems = jobname.split('.')
     jobnameitems.reverse()
     jobname = '.'.join(jobnameitems)
     jobname = qsub_sanitize_job_name(jobname)
     cmd.inputs.args = '%s -N %s %s' % (qsubargs,
                                        jobname,
                                        scriptfile)
     oldlevel = iflogger.level
     iflogger.setLevel(logging.getLevelName('CRITICAL'))
     tries = 0
     result = list()
     while True:
         try:
             result = cmd.run()
         except Exception, e:
             if tries < self._max_tries:
                 tries += 1
                 time.sleep(
                     self._retry_timeout)  # sleep 2 seconds and try again.
             else:
                 iflogger.setLevel(oldlevel)
                 raise RuntimeError('\n'.join((('Could not submit sge task'
                                                ' for node %s') % node._id,
                                               str(e))))
         else:
             break
Example #58
0
def fsl_mask(infile, mask, outname='grey_cerebellum_tu.nii'):
    """use fslmaths to mask img with mask"""

    pth, nme = os.path.split(infile)
    outfile = os.path.join(pth, outname)
    c1 = CommandLine('fslmaths %s -mas %s %s' % (infile, mask, outfile))
    out = c1.run()

    if not out.runtime.returncode == 0:
        print 'failed to mask %s' % (infile)
        print out.runtime.stderr
        return None
    else:
        return outfile
def palm_corr(in_file, mask, design, contrast):
    import os
    from glob import glob
    from nipype.interfaces.base import CommandLine

    cmd = ("palm \
    -i {in_file} \
    -m {mask} \
    -d {design} -t {contrast} \
    -T -tfce2D -noniiclass -n 10000 -corrcon -save1-p -o palm_corr_dti")

    cl = CommandLine(
        cmd.format(in_file=in_file,
                   mask=mask,
                   design=design,
                   contrast=contrast))
    cl.run()
    tstat1 = os.path.abspath('palm_corr_dti_vox_tstat_c1.nii.gz')
    tstat2 = os.path.abspath('palm_corr_dti_vox_tstat_c2.nii.gz')
    P_value1 = os.path.abspath('palm_corr_dti_tfce_tstat_fwep_c1.nii.gz')
    P_value2 = os.path.abspath('palm_corr_dti_tfce_tstat_fwep_c2.nii.gz')

    return tstat1, tstat2, P_value1, P_value2
Example #60
0
def elastix(input_file, target_file, mask_file, output_prefix,
            output_sub_prefix):
    from os.path import abspath as opap
    from nipype.interfaces.base import CommandLine
    from nipype.utils.filemanip import split_filename
    import shutil
    import glob
    import os
    out_dir = experiment_dir + '/' + output_prefix + '/' + output_sub_prefix
    # Create output directory if it does not exist
    if os.path.exists(out_dir):
        print "rmtree: " + out_dir
        shutil.rmtree(out_dir)
    print "creating: " + out_dir
    os.makedirs(out_dir)

    cmd = CommandLine((
        '/Users/eija/Desktop/SW/Elastix/elastix_macosx64_v4.7/bin/elastix -f %s -m %s -out %s -p %s -threads 8'
    ) % (target_file, input_file, out_dir, param_rigid))

    print "elastix: " + cmd.cmd
    cmd.run()
    resultfiles = glob.glob(out_dir + os.sep + 'result.*.tiff')
    return resultfiles