Beispiel #1
0
def label_fusion(target_path, atlas_img_path_list, atlas_lab_path_list, out_file, probabilities, params_list):

    out_dir = os.path.dirname(out_file)
    out_name = os.path.basename(out_file).split(os.extsep, 1)[0]

    if params_list[0] == 'Joint':

        jointfusion_path = os.path.join(os.environ['ANTSPATH'], 'jointfusion')

        prob_dir =  os.path.join(out_dir, out_name)
        prob_path = os.path.join(prob_dir, 'prob%d.nii.gz')

        cmdline = [jointfusion_path, '3', '1']
        cmdline += ['-g'] + atlas_img_path_list
        cmdline += ['-tg', target_path]
        cmdline += ['-l'] + atlas_lab_path_list
        cmdline += ['-m', 'Joint']
        cmdline += [item for sublist in zip(['-rp', '-rs'], params_list[1:]) for item in sublist]
        if probabilities:
            os.makedirs(prob_dir)
            cmdline += ['-p', prob_path]
        cmdline += [out_file]

    else:

        python_path = os.path.join(os.environ['HOME'], 'anaconda', 'envs', 'sitkpy', 'bin', 'python')
        mod_path = os.path.join(os.environ['HOME'], 'CODE', 'mod_py')
        nlwv_path = os.path.join(mod_path, 'pblf_py.py')

        cmdline = [python_path, '-u', nlwv_path]

        cmdline += ['--atlas_img_list'] + atlas_img_path_list
        cmdline += ['--target_img', target_path]
        cmdline += ['--atlas_lab_list'] + atlas_lab_path_list
        cmdline += ['--method'] + params_list[:2]
        cmdline += [item for sublist in zip(['--patch_radius', '--search_radius', '--fusion_radius', '--struct_sim', '--normalization',], params_list[2:]) for item in sublist]
        if probabilities:
            cmdline += ['--probabilities']
        cmdline += ['--out_file', out_file]

    # launch
    qsub_launcher = Launcher(' '.join(cmdline))
    qsub_launcher.name = "{}_joint".format(out_name)
    qsub_launcher.folder = out_dir
    # qsub_launcher.queue = 'short.q'
    qsub_launcher.queue = 'default.q'

    return qsub_launcher.run()
                    type=int,
                    nargs=1,
                    default=[8],
                    help='number of concurrent processes ')
parser.add_argument("--num_itk_threads",
                    type=int,
                    nargs=1,
                    default=[1],
                    help='number of threads per ANTs proc ')

args = parser.parse_args()
# args = parser.parse_args('--in_dir /Users/gsanroma/DATA/DATABASES/ADNI/atlases/kk --img_suffix moving.nii.gz --template_file /Users/gsanroma/DATA/DATABASES/ADNI/atlases/kk/fixed.nii.gz --transform Affine 4 --out_warp_intfix rigid3 --out_dir /Users/gsanroma/DATA/DATABASES/ADNI/atlases/kk --init_warp_dir_suffix /Users/gsanroma/DATA/DATABASES/ADNI/atlases/kk moving_warped0GenericAffine.mat --init_warp_dir_suffix /Users/gsanroma/DATA/DATABASES/ADNI/atlases/kk moving_masked_warped20GenericAffine.mat 1 --template_mask /Users/gsanroma/DATA/DATABASES/ADNI/atlases/kk/left2.nii.gz'.split())

from scheduler import Launcher

launcher = Launcher(args.num_procs[0])

# default num of iterations
ITS_LINEAR = [
    '%d' % int(500 / args.speedup[0]),
    '%d' % int(250 / args.speedup[0]),
    '%d' % int(125 / args.speedup[0]),
    '%d' % int(50 / args.speedup[0])
]
ITS_SYN = [
    '%d' % int(70 / args.speedup[0]),
    '%d' % int(50 / args.speedup[0]),
    '%d' % int(30 / args.speedup[0]),
    '%d' % int(10 / args.speedup[0])
]
                        args.reg_dir[0], file_name + args.in_deform_intfix[0] +
                        '1InverseWarp.nii.gz')
                ]

        cmdline += [
            '--output',
            os.path.join(args.out_dir[0],
                         file.split('.nii.gz')[0] + args.out_suffix[0])
        ]

        #
        # launch

        print "Launching warping of file {}".format(file)

        qsub_launcher = Launcher(' '.join(cmdline))
        qsub_launcher.name = file.split('.nii.gz')[0]
        qsub_launcher.folder = args.out_dir[0]
        qsub_launcher.queue = 'short.q'
        job_id = qsub_launcher.run()

        if is_hpc:
            wait_jobs += [job_id]

# Wait for the jobs to finish (in cluster)
if is_hpc:
    print "Waiting for warping jobs to finish..."
    call(wait_jobs)

print "Warping finished."
Beispiel #4
0
# print('FOUND: %s' % [os.path.exists(os.path.join(args.gtr_dir[0], f)) for f in gtr_files])
assert not False in [
    os.path.exists(os.path.join(args.gtr_dir[0], f)) for f in gtr_files
], "Some ground-truth segmentations not found"

Nimg = len(est_files)

# temp directory
tmp_dir = os.path.join(args.est_dir[0], 'tmp')
if os.path.exists(tmp_dir):
    rmtree(tmp_dir)
os.makedirs(tmp_dir)

imagemath_path = os.path.join(os.environ['ANTSPATH'], 'ImageMath')

launcher = Launcher(args.num_procs[0])

out_paths = []

for i_img in range(Nimg):

    est_path = os.path.join(args.est_dir[0], est_files[i_img])
    gtr_path = os.path.join(args.gtr_dir[0], gtr_files[i_img])
    out_path = os.path.join(tmp_dir, est_names[i_img])
    out_paths.append(out_path)

    cmdline = "%s 3 %s DiceAndMinDistSum %s %s" % (imagemath_path, out_path,
                                                   est_path, gtr_path)

    qsub_launcher = Launcher(cmdline)
Beispiel #5
0
        cmdline += ['--float', '1']

    
    #
    # mask

    if args.template_mask is not None:
        cmdline += ['--masks', args.template_mask[0]]

    #
    # launch

    print("Launching registration of file {}".format(mat_file))
    # os.system(' '.join(cmdline))

    qsub_launcher = Launcher(' '.join(cmdline))
    qsub_launcher.name = mat_file.split(os.extsep, 1)[0]
    qsub_launcher.folder = args.out_dir[0]
    # qsub_launcher.omp_num_threads = args.num_threads[0]
    qsub_launcher.queue = 'short'
    job_id = qsub_launcher.run()

    if is_hpc:
        wait_jobs += [job_id]

    n_jobs += 1

    # Wait for the jobs to finish (in cluster)
    if is_hpc and n_total_jobs <= n_jobs:
        print("Waiting for registration jobs to finish...")
        call(wait_jobs)
Beispiel #6
0
                    imagemath_path, '3',
                    os.path.join(tmp_dir, 'dummy.txt'), 'NormalizedCorrelation'
                ]
                cmdline += [
                    os.path.join(in_dir, in_files_list[i]),
                    os.path.join(in2_dir, in2_files_list[i2])
                ]
                if args.mask_file is not None:
                    cmdline += [
                        os.path.join(tmp_dir,
                                     os.path.basename(args.mask_file[0]))
                    ]

            job_name = "{0}X{1}".format(RID_1 + '_' + sampleid_1,
                                        RID_2 + '_' + sampleid_2)
            qsub_launcher = Launcher(' '.join(cmdline))
            qsub_launcher.name = job_name
            qsub_launcher.folder = tmp_dir
            qsub_launcher.queue = "short.q"
            job_id = qsub_launcher.run()

            if is_hpc:
                wait_jobs += [job_id]

            n_jobs += 1
            list_of_jobs.append((job_name, i, i2))
            # Wait for the jobs to finish (in cluster)
            if is_hpc and n_total_jobs <= n_jobs:
                print("Waiting for registration jobs to finish...")
                call(wait_jobs)
        '--input', '{}{}'.format(os.path.join(args.in_dir[0], img_name),
                                 args.img_suffix[0])
    ]
    cmdline += ['--input-image-type', '3']
    cmdline += ['--interpolation', 'Linear']
    cmdline += [
        '--reference-image', '{}'.format(os.path.join(args.template_dir[0]))
    ]
    cmdline += ['--transform', '{}'.format(os.path.join(args.matrix[0]))]

    # launch

    print("Launching registration of file {}".format(img_file))
    # os.system(' '.join(cmdline))

    qsub_launcher = Launcher(' '.join(cmdline))
    qsub_launcher.name = img_file.split(os.extsep, 1)[0]
    qsub_launcher.folder = args.out_dir[0]
    #qsub_launcher.omp_num_threads = args.num_threads[0]
    # qsub_launcher.queue = 'short.q'
    job_id = qsub_launcher.run()

    if is_hpc:
        wait_jobs += [job_id]

    n_jobs += 1

    # Wait for the jobs to finish (in cluster)
    if is_hpc and n_total_jobs <= n_jobs:
        print("Waiting for registration jobs to finish...")
        call(wait_jobs)
Beispiel #8
0
        # the output.

        out_path = img_file.replace(in_dir, args.out_dir[0])
        if not os.path.exists(os.path.dirname(out_path)):
            os.makedirs(os.path.dirname(out_path))

        cmdline = [n4_path, '--image-dimensionality', '3']
        cmdline += ['--input-image', img_file]
        cmdline += ['--shrink-factor', '3']
        cmdline += ['--convergence', '50x50x30x20', '1e-6']
        cmdline += ['--bspline-fitting', '300']
        cmdline += ['--output', out_path]

        print("Launching N4 for {}".format(img_file))

        qsub_launcher = Launcher(' '.join(cmdline))
        qsub_launcher.name = os.path.splitext(os.path.basename(img_file))[0]
        qsub_launcher.folder = os.path.dirname(out_path)
        qsub_launcher.queue = 'short'
        job_id = qsub_launcher.run()
        njobs = njobs + 1
        if is_hpc:
            wait_jobs += [job_id]

        if is_hpc and njobs >= n_total_jobs:
            print("Limit found. Wait for jobs to finish...")
            call(wait_jobs)
            njobs = 0
            wait_jobs = [
                os.path.join(os.environ['ANTSSCRIPTS'], "waitForSlurmJobs.pl"),
                '0', '10'
        '10'
    ]

    out_paths = []

    for i_img in range(Nimg):

        est_path = os.path.join(est_dir[0], est_files[i_img])
        gtr_path = os.path.join(args.gtr_dir[0], gtr_files[i_img])
        out_path = os.path.join(tmp_dir, est_names[i_img])
        out_paths += [out_path]

        cmdline = "{} 3 {} DiceAndMinDistSum {} {}\n".format(
            imagemath_path, out_path, est_path, gtr_path)

        qsub_launcher = Launcher(cmdline)

        print "Launching Dice evaluation job for labels {}".format(
            est_names[i_img])

        qsub_launcher.name = est_names[i_img]
        qsub_launcher.folder = tmp_dir
        qsub_launcher.queue = 'short.q'
        job_id = qsub_launcher.run()

        if is_hpc:
            wait_jobs += [job_id]

    if is_hpc:
        print "Waiting for Dice evaluation jobs to finish..."
        subprocess.call(wait_jobs)
    f for f in atlas_files_list if f.endswith(args.atlas_linear_suffix[i][0])
] for i in range(len(args.atlas_linear_suffix))]
atlas_nearest_superlist = [[
    f for f in atlas_files_list if f.endswith(args.atlas_nearest_suffix[i][0])
] for i in range(len(args.atlas_nearest_suffix))]

# create output directory
if not os.path.exists(args.out_dir[0]):
    os.makedirs(args.out_dir[0])

if not args.inverse:
    print "Warping each atlas to target"
else:
    print "Warping target to each atlas"

launcher = Launcher(args.num_procs[0])

antsapplytransforms_path = os.path.join(os.environ['ANTSPATH'],
                                        'antsApplyTransforms')

target_name = os.path.basename(args.target_file[0]).split(
    args.target_suffix[0])[0]

for atlas_files_list, suffix, interpolation in zip(atlas_linear_superlist, args.atlas_linear_suffix, ['Linear']*len(args.atlas_linear_suffix)) + \
        zip(atlas_nearest_superlist, args.atlas_nearest_suffix, ['NearestNeighbor']*len(args.atlas_nearest_suffix)):

    for atlas_file in atlas_files_list:

        cmdline = [antsapplytransforms_path, '--dimensionality', '3']
        cmdline += ['--interpolation', interpolation]
        cmdline += ['--default-value', '0']