예제 #1
0
def main():

        oversamp_factor = 1.25 #For NUFFT
        parser = argparse.ArgumentParser()
        inputs = bl832inputs_parser(parser)

        num_slice = inputs['z_numElts']
        num_angles= inputs['num_views']/inputs['view_subsmpl_fact']
        
        pad_size = np.int16(inputs['x_width']*oversamp_factor)
        num_iter = inputs['num_iter']
        nufft_scaling = (np.pi/pad_size)**2
        
        
        tomo, flats, darks, floc = tomopy.read_als_832h5(inputs['input_hdf5'],ind_tomo=range(1,inputs['num_views']+1,inputs['view_subsmpl_fact']),sino=(inputs['z_start'], inputs['z_start']+inputs['z_numElts'], 1))
        print('Data read complete')


        print('Generating angles')
        theta = tomopy.angles(num_angles)

        #Need to modify to return the raw counts for noise estimation 
        print('Normalization')
        tomo,weight = normalize_bo(tomo, flats, darks,inputs['num_dark'])

        print('Ring removal')
        tomo = tomopy.remove_stripe_fw(tomo)
        
        ################## GPU MBIR ######################
        input_params={}
        input_params['gpu_device']=inputs['gpu_device']
        input_params['oversamp_factor']=oversamp_factor
        input_params['num_iter']=num_iter
        input_params['p']=inputs['p']
        input_params['smoothness']=inputs['smoothness']
        t=time.time()
        rec_mbir_final = gpuMBIR(tomo,theta,inputs['rot_center'],input_params)
        elapsed_time = (time.time()-t)
        print('Time for reconstucting using GPU-MBIR of %d slices with %d iter : %f' % (num_slice,num_iter,elapsed_time))

        pg.image(rec_mbir_final);pg.QtGui.QApplication.exec_()
#        np.save('/home/svvenkatakrishnan/results/mbir_notch1080_70slice',rec_mbir_final)
        
#        fig = plt.figure()
#        sirt_camTomo = rec_sirt_final[124]
#        plt.imshow(sirt_camTomo,cmap=plt.cm.Greys_r,vmin=0,vmax=0.00075)
#        plt.colorbar()
#        fig.suptitle('Tomopy GPU-SIRT Reconstruction')
#        plt.draw()
#        plt.show()

        print 'main: Done!'
예제 #2
0
#script to test tomopy

from __future__ import print_function, division
import matplotlib.pyplot as plt
from skimage.io import imread
from skimage import data_dir
from skimage.transform import radon, rescale, iradon
import tomopy
from normalize import normalize_bo

dataset = '/home/svvenkatakrishnan/data/20131106_074854_S45L3_notch_OP_10x.h5'
#20130807_234356_OIM121R_SAXS_5x.h5'
algo = 'fbp'
num_sets = 2

tomo, flats, darks, floc = tomopy.read_als_832h5(dataset, sino=(1000, 1010, 1))
print('Data read complete')

print('Displaying  sinogram')
imgplot = plt.imshow(tomo[:, 0, :])
plt.show()

print('Generating angles')
theta = tomopy.angles(tomo.shape[0])

print('Normalization')
tomo, weight = normalize_bo(tomo, flats, darks, num_sets)

#print('Ring removal')
#tomo = tomopy.remove_stripe_fw(tomo)
예제 #3
0
# -*- coding: utf-8 -*-
"""
Created on Thu Dec  3 16:20:30 2015

@author: lbluque
"""

import tomopy

first, flats, darks, floc = tomopy.read_als_832h5('../../TestDatasets/20151021_105637_ALS10_RT_210lbs_10x.h5', ind_tomo=(0,))
first = tomopy.normalize_nf(first, flats, darks, floc)
base = '20151021_105637_ALS10_RT_210lbs_10x_tomopy_phase_'

dist = (0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 13.2284, 100.0, 500.0)
alpha = (1.0e-3, 1.0e-2, 1.0e-1)

for d in dist:
    for a in alpha:
        print a
        phase = tomopy.retrieve_phase(first,
                                      pixel_size=0.000129,
                                      dist=d,
                                      alpha=a,
                                      energy=40)
        name = base + 'dist{0:.1f}_alpha{1:.1e}'.format(d*10.0, a)
        print(name)
        tomopy.write_tiff(phase, fname='filters/'+name)
예제 #4
0
def fast_tomo_recon(argv):
    """
    Reconstruct subset slices (sinograms) equally spaced within tomographic
    dataset
    """

    logger = logging.getLogger("fast_tomopy.fast_tomo_recon")

    # Parse arguments passed to function
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input", type=str, help="path to input raw " "dataset", required=True)
    parser.add_argument(
        "-o",
        "--output-file",
        type=str,
        help="full path to h5 output " "file",
        default=os.path.join(os.getcwd(), "fast-tomopy.h5"),
    )
    parser.add_argument("-sn", "--sino-num", type=int, help="Number of slices " "to reconstruct", default=5)
    parser.add_argument(
        "-a",
        "--algorithm",
        type=str,
        help="Reconstruction" " algorithm",
        default="gridrec",
        choices=[
            "art",
            "bart",
            "fbp",
            "gridrec",
            "mlem",
            "ospml_hybrid",
            "ospml_quad",
            "pml_hybrid",
            "pml_quad",
            "sirt",
        ],
    )
    parser.add_argument("-c", "--center", type=float, help="Center of rotation", default=None)
    parser.add_argument(
        "-fn",
        "--filter-name",
        type=str,
        help="Name of filter" " used for reconstruction",
        choices=["none", "shepp", "cosine", "hann", "hamming", "ramlak", "parzen", "butterworth"],
        default="butterworth",
    )
    parser.add_argument(
        "-rr",
        "--ring-remove",
        type=str,
        help="Ring removal " "method",
        choices=["Octopus", "Tomopy-FW", "Tomopy-T"],
        default="Tomopy-T",
    )
    parser.add_argument("-lf", "--log-file", type=str, help="log file name", default="fast-tomopy.log")

    args = parser.parse_args()

    fh = logging.FileHandler(args.log_file)
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if os.path.isdir(os.path.dirname(args.output_file)) is False:
        raise IOError(2, "Directory of output file does not exist", args.output_file)

    # Read file metadata
    logger.info("Reading input file metadata")
    fdata, gdata = read_als_832h5_metadata(args.input)
    proj_total = int(gdata["nangles"])
    last = proj_total - 1
    sino_total = int(gdata["nslices"])
    ray_total = int(gdata["nrays"])
    px_size = float(gdata["pxsize"]) / 10  # cm

    # Set parameters for sinograms to read
    step = sino_total // (args.sino_num + 2)
    start = step
    end = step * (args.sino_num + 1)
    sino = (start, end, step)

    # Read full first and last projection to determine center of rotation
    if args.center is None:
        logger.info("Reading full first and last projection for COR")
        first_last, flats, darks, floc = tomopy.read_als_832h5(args.input, ind_tomo=(0, last))
        first_last = tomopy.normalize(first_last, flats, darks)
        args.center = tomopy.find_center_pc(first_last[0, :, :], first_last[1, :, :], tol=0.1)
        logger.info("Detected center: %f", args.center)

    # Read and normalize raw sinograms
    logger.info("Reading raw data")
    tomo, flats, darks, floc = tomopy.read_als_832h5(args.input, sino=sino)
    logger.info("Normalizing raw data")
    tomo = tomopy.normalize_nf(tomo, flats, darks, floc)

    # Remove stripes from sinograms (remove rings)
    logger.info("Preprocessing normalized data")
    if args.ring_remove == "Tomopy-FW":
        logger.info("Removing stripes from sinograms with %s", args.ring_remove)
        tomo = tomopy.remove_stripe_fw(tomo)
    elif args.ring_remove == "Tomopy-T":
        logger.info("Removing stripes from sinograms with %s", args.ring_remove)
        tomo = tomopy.remove_stripe_ti(tomo)

    # Pad sinograms with edge values
    npad = int(np.ceil(ray_total * np.sqrt(2)) - ray_total) // 2
    tomo = tomopy.pad(tomo, 2, npad=npad, mode="edge")
    args.center += npad  # account for padding

    filter_name = np.array(args.filter_name, dtype=(str, 16))
    theta = tomopy.angles(proj_total, 270, 90)

    logger.info("Reconstructing normalized data")
    # Reconstruct sinograms
    # rec = tomopy.minus_log(tomo, out=tomo)
    rec = tomopy.recon(
        tomo, theta, center=args.center, emission=False, algorithm=args.algorithm, filter_name=filter_name
    )
    rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
    rec = rec / px_size

    # Remove rings from reconstruction
    if args.ring_remove == "Octopus":
        logger.info("Removing rings from reconstructions with %s", args.ring_remove)
        thresh = float(gdata["ring_threshold"])
        thresh_max = float(gdata["upp_ring_value"])
        thresh_min = float(gdata["low_ring_value"])
        theta_min = int(gdata["max_arc_length"])
        rwidth = int(gdata["max_ring_size"])
        rec = tomopy.remove_rings(
            rec,
            center_x=args.center,
            thresh=thresh,
            thresh_max=thresh_max,
            thresh_min=thresh_min,
            theta_min=theta_min,
            rwidth=rwidth,
        )

    # Write reconstruction data to new hdf5 file
    fdata["stage"] = "fast-tomopy"
    fdata["stage_flow"] = "/raw/" + fdata["stage"]
    fdata["stage_version"] = "fast-tomopy-0.1"
    # Generate a new uuid based on host ID and current time
    fdata["uuid"] = str(uuid.uuid1())

    gdata["Reconstruction_Type"] = "tomopy-gridrec"
    gdata["ring_removal_method"] = args.ring_remove
    gdata["rfilter"] = args.filter_name

    logger.info("Writing reconstructed data to h5 file")
    write_als_832h5(rec, args.input, fdata, gdata, args.output_file, step)

    return
예제 #5
0
# import sirtfbp

datasets ={ '/home/svvenkatakrishnan/data/20130807_234356_OIM121R_SAXS_5x.h5': 1272}
algorithms = ('fbp',)
sinos = (10,10,1)
cores = (1,) #range(mp.cpu_count(), 0, -4)
f = open('benchmark_results.txt', 'a')

for dataset in datasets:
    f.write('*****************************************************************************************************\n')
    f.write(dataset + '\n\n')
    for algorithm in algorithms:
        for sino in sinos:
            for core in cores:
                start_time = time.time()
                tomo, flats, darks, floc = tomopy.read_als_832h5(dataset,
                                                                 sino=(0, sino, 1))
                end_time = time.time() - start_time
                f.write('Function: {0}, Number of sinos: {1}, Runtime (s): {2}\n'.format('read', sino, end_time))
                theta = tomopy.angles(tomo.shape[0])
                tomo = tomopy.normalize(tomo, flats, darks, ncore=core)
                end_time = time.time() - start_time - end_time 
                f.write('Function: {0}, Number of sinos: {1}, Number of cores: {2}, Runtime (s): {3}\n'.format('normalize', sino, core, end_time))
                tomo = tomopy.remove_stripe_fw(tomo, ncore=core)
                end_time = time.time() - start_time - end_time 
                f.write('Function: {0}, Number of sinos: {1}, Number of cores: {2}, Runtime (s): {3}\n'.format('stripe_fw', sino, core, end_time))
                rec = tomopy.recon(tomo, theta, center=datasets[dataset],
                                   algorithm=algorithm, emission=False,
                                   ncore=core)
                end_time = time.time() - start_time - end_time
                rec = tomopy.circ_mask(rec, 0)
                f.write('Function: {0}, Number of sinos: {1}, Number of cores: {2}, Algorithm: {3}, Runtime (s): {4}\n'.format('recon', sino, core, algorithm, end_time))
예제 #6
0
def fast_tomo_recon(argv):
    """
    Reconstruct subset slices (sinograms) equally spaced within tomographic
    dataset
    """

    logger = logging.getLogger('fast_tomopy.fast_tomo_recon')

    # Parse arguments passed to function
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input', type=str, help='path to input raw '
                        'dataset', required=True)
    parser.add_argument('-o', '--output-file', type=str, help='full path to h5 output '
                        'file', default=os.path.join(os.getcwd(), "fast-tomopy.h5"))
    parser.add_argument('-sn', '--sino-num', type=int, help='Number of slices '
                        'to reconstruct', default=5)
    parser.add_argument('-a', '--algorithm', type=str, help='Reconstruction'
                        ' algorithm', default='gridrec',
                        choices=['art', 'bart', 'fbp', 'gridrec', 'mlem',
                                 'ospml_hybrid', 'ospml_quad', 'pml_hybrid',
                                 'pml_quad', 'sirt'])
    parser.add_argument('-c', '--center', type=float, help='Center of rotation',
                        default=None)
    parser.add_argument('-fn', '--filter-name', type=str, help='Name of filter'
                        ' used for reconstruction',
                        choices=['none', 'shepp', 'cosine', 'hann', 'hamming',
                                 'ramlak', 'parzen', 'butterworth'],
                        default='butterworth')
    parser.add_argument('-rr', '--ring-remove', type=str, help='Ring removal '
                        'method', choices=['Octopus', 'Tomopy-FW', 'Tomopy-T'],
                        default='Tomopy-T')
    parser.add_argument('-lf', '--log-file', type=str, help='log file name',
                        default='fast-tomopy.log')

    args = parser.parse_args()

    fh = logging.FileHandler(args.log_file)
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if os.path.isdir(os.path.dirname(args.output_file)) is False:
        raise IOError(2, 'Directory of output file does not exist', args.output_file)

    # Read file metadata
    logger.info('Reading input file metadata')
    fdata, gdata = read_als_832h5_metadata(args.input)
    proj_total = int(gdata['nangles'])
    last = proj_total - 1
    sino_total = int(gdata['nslices'])
    ray_total = int(gdata['nrays'])
    px_size = float(gdata['pxsize'])/10  # cm

    # Set parameters for sinograms to read
    step = sino_total // (args.sino_num + 2)
    start = step
    end = step*(args.sino_num + 1)
    sino = (start, end, step)

    # Read full first and last projection to determine center of rotation
    if args.center is None:
        logger.info('Reading full first and last projection for COR')
        first_last, flats, darks, floc = tomopy.read_als_832h5(args.input,
                                                               ind_tomo=(0, last))
        first_last = tomopy.normalize(first_last, flats, darks)
        args.center = tomopy.find_center_pc(first_last[0, :, :],
                                            first_last[1, :, :], tol=0.1)
        logger.info('Detected center: %f', args.center)

    # Read and normalize raw sinograms
    logger.info('Reading raw data')
    tomo, flats, darks, floc = tomopy.read_als_832h5(args.input, sino=sino)
    logger.info('Normalizing raw data')
    tomo = tomopy.normalize_nf(tomo, flats, darks, floc)

    # Remove stripes from sinograms (remove rings)
    logger.info('Preprocessing normalized data')
    if args.ring_remove == 'Tomopy-FW':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_fw(tomo)
    elif args.ring_remove == 'Tomopy-T':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_ti(tomo)

    # Pad sinograms with edge values
    npad = int(np.ceil(ray_total*np.sqrt(2)) - ray_total)//2
    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')
    args.center += npad # account for padding

    filter_name = np.array(args.filter_name, dtype=(str, 16))
    theta = tomopy.angles(proj_total, 270, 90)

    logger.info('Reconstructing normalized data')
    # Reconstruct sinograms
    # rec = tomopy.minus_log(tomo, out=tomo)
    rec = tomopy.recon(tomo, theta, center=args.center, emission=False,
                       algorithm=args.algorithm, filter_name=filter_name)
    rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
    rec = rec/px_size

    # Remove rings from reconstruction
    if args.ring_remove == 'Octopus':
        logger.info('Removing rings from reconstructions with %s',
                    args.ring_remove)
        thresh = float(gdata['ring_threshold'])
        thresh_max = float(gdata['upp_ring_value'])
        thresh_min = float(gdata['low_ring_value'])
        theta_min = int(gdata['max_arc_length'])
        rwidth = int(gdata['max_ring_size'])
        rec = tomopy.remove_rings(rec, center_x=args.center, thresh=thresh,
                                  thresh_max=thresh_max, thresh_min=thresh_min,
                                  theta_min=theta_min, rwidth=rwidth)

    # Write reconstruction data to new hdf5 file
    fdata['stage'] = 'fast-tomopy'
    fdata['stage_flow'] = '/raw/' + fdata['stage']
    fdata['stage_version'] = 'fast-tomopy-0.1'
    # Generate a new uuid based on host ID and current time
    fdata['uuid'] = str(uuid.uuid1())

    gdata['Reconstruction_Type'] = 'tomopy-gridrec'
    gdata['ring_removal_method'] = args.ring_remove
    gdata['rfilter'] = args.filter_name

    logger.info('Writing reconstructed data to h5 file')
    write_als_832h5(rec, args.input, fdata, gdata, args.output_file, step)

    return
예제 #7
0
    axis : int
        Axis to crop along

    Returns
    -------
    ndarray:
        Cropped array
    """

    slc = []
    pts = [p11, p12, p21, p22, p31, p32]
    for n in range(len(arr.shape)):
        slc.append(slice(pts.pop(0), pts.pop(0)))
    return arr[slc]


if __name__ == '__main__':
    import tomopy
    from matplotlib.pyplot import imshow, show, figure
    d = tomopy.read_als_832h5('/home/lbluque/TestDatasetsLocal/dleucopodia.h5',
                              ind_tomo=(500, 501, 502, 503))
    # d = np.array(d[0], dtype=np.float32)
    d = d[0]
    c = convert_data(d, imin=0, imax=0)
    print d.dtype
    print c.dtype
    figure(0)
    imshow(d[0])
    figure(1)
    imshow(c[0])
    show()
예제 #8
0
def main():

    parser = argparse.ArgumentParser()
    inputs = bl832inputs_parser(parser)

    num_slice = inputs['z_numElts']
    num_angles = inputs['num_views'] / inputs['view_subsmpl_fact']

    oversamp_factor = 1.25
    pad_size = np.int16(inputs['x_width'] * oversamp_factor)
    fbp_filter_param = inputs['fbp_filter_param']
    nufft_scaling = (np.pi / pad_size)**2

    algorithm = 'gridrec'

    tomo, flats, darks, floc = tomopy.read_als_832h5(
        inputs['input_hdf5'],
        ind_tomo=range(1, inputs['num_views'] + 1,
                       inputs['view_subsmpl_fact']),
        sino=(inputs['z_start'], inputs['z_start'] + inputs['z_numElts'], 1))
    print('Data read complete')

    print('Displaying  sinogram')
    #imgplot = plt.imshow(tomo[:,0,:])

    print('Generating angles')
    theta = tomopy.angles(num_angles)

    #Need to modify to return the raw counts for noise estimation
    print('Normalization')
    tomo, weight = normalize_bo(tomo, flats, darks, inputs['num_dark'])

    print('Ring removal')
    tomo = tomopy.remove_stripe_fw(tomo)

    #        fig = plt.figure()
    #        plt.imshow(tomo[:,1,:],cmap=plt.cm.Greys_r)
    #        fig.suptitle('Sinogram')

    ################## GPU gridrec() ######################
    input_params = {}
    input_params['gpu_device'] = inputs['gpu_device']
    input_params['fbp_filter_param'] = inputs['fbp_filter_param']
    input_params['oversamp_factor'] = oversamp_factor

    t = time.time()
    rec_nufft_final = gpuGridrec(tomo, theta, inputs['rot_center'],
                                 input_params)
    elapsed_time = time.time() - t
    print('Time for NUFFT Gridrec of %d slices : %f' %
          (num_slice, elapsed_time))
    pg.image(rec_nufft_final)
    pg.QtGui.QApplication.exec_()

    #        np.save('/home/svvenkatakrishnan/results/gridrec_notch1080_70slice',rec_nufft_final)

    ##################TomoPy Recon#####################
    #        print('Recon - tomopy GridRec')
    #        t=time.time()
    #        rec_tomopy = tomopy.recon(tomo, theta, center=inputs['rot_center'],algorithm=algorithm)#emission=False)
    #        elapsed_time = (time.time()-t)
    #        print('Time for reconstucting using Tomopy GridRec of %d slices : %f' % (num_slice,elapsed_time))

    #       print('Recon - tomopy Astra')
    #       t=time.time()
    #       options = {'proj_type':'cuda', 'method':'FBP_CUDA'}
    #       rec_astra = tomopy.recon(tomo, theta, center=inputs['rot_center'], algorithm=tomopy.astra, options=options)
    #       elapsed_time = (time.time()-t)
    #       print('Time for reconstucting using Tomopy Astra of %d slices : %f' % (num_slice,elapsed_time))

    #        fig = plt.figure()
    #        plt.imshow(np.abs(np.flipud(rec_tomopy[0])),cmap=plt.cm.Greys_r)
    #        plt.colorbar()
    #        fig.suptitle('Tomopy Gridrec Reconstruction')

    #        fig = plt.figure()
    #        plt.imshow(rec_nufft[0].real,cmap=plt.cm.Greys_r)
    #        plt.colorbar()
    #        fig.suptitle('GPU NUFFT Reconstruction')

    print 'main: Done!'
예제 #9
0
'''
bl832 test hdf5 file: center of rotation
'20150820_130628_Dleucopodia_10458_pieceA_10x_z30mm.h5': 1155.75
'20150820_124324_Dleucopodia_10458_pieceA_10x_z80mm_moreangles.h5': 1223,
'20140829_132953_euc60mesh_1M-KI_10percLoad_time0_5x_33p5keV_10cmSampDet.h5': 1334.85
These files can be found in /global/cscratch1/sd/lbluque/tomobench_datasets
'''
fname = "path/to/bl832.h5"


# Load real data from ALS 832 ------------

# load DataExchange data
t = time.time()
prj, flt, drk, flc = tomopy.read_als_832h5(fname) # sino=(1000, 1032)) #sino kwarg only if you only what to read in a subset of sinograms
# ignore the flc variable...
print prj.shape, flt.shape, drk.shape
print time.time() - t

# define projection angles
ang = tomopy.angles(prj.shape[0])

# data normalization
t = time.time()
prj = tomopy.normalize(prj, flt, drk)
print time.time() - t


# Processing funcs --------------
예제 #10
0
def fast_tomo_recon(argv):
    """
    Reconstruct subset slices (sinograms) equally spaced within tomographic
    dataset
    """

    logger = logging.getLogger('fast_tomopy.fast_tomo_recon')

    # Parse arguments passed to function
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input', type=str, help='path to input raw '
                        'dataset', required=True)
    parser.add_argument('-o', '--output-file', type=str, help='full path to h5 output '
                        'file', default=os.path.join(os.getcwd(), "fast-tomopy.h5"))
    parser.add_argument('-sn', '--sino-num', type=int, help='Number of slices '
                        'to reconstruct', default=5)
    parser.add_argument('-a', '--algorithm', type=str, help='Reconstruction'
                        ' algorithm', default='gridrec',
                        choices=['art', 'bart', 'fbp', 'gridrec', 'mlem',
                                 'ospml_hybrid', 'ospml_quad', 'pml_hybrid',
                                 'pml_quad', 'sirt'])
    parser.add_argument('-c', '--center', type=float, help='Center of rotation',
                        default=None)
    parser.add_argument('-fn', '--filter-name', type=str, help='Name of filter'
                        ' used for reconstruction',
                        choices=['none', 'shepp', 'cosine', 'hann', 'hamming',
                                 'ramlak', 'parzen', 'butterworth'],
                        default='butterworth')
    parser.add_argument('-rr', '--ring-remove', type=str, help='Ring removal '
                        'method', choices=['Octopus', 'Tomopy-FW', 'Tomopy-T'],
                        default='Tomopy-FW')
    parser.add_argument('-lf', '--log-file', type=str, help='log file name',
                        default='fast-tomopy.log')

    args = parser.parse_args()

    fh = logging.FileHandler(args.log_file)
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if os.path.isdir(os.path.dirname(args.output_file)) is False:
        raise IOError(2, 'Directory of output file does not exist', args.output_file)

    # Read file metadata
    logger.info('Reading input file metadata')
    fdata, gdata = tomopy.read_als_832h5_metadata(args.input)
    proj_total = int(gdata['nangles'])
    last = proj_total - 1
    sino_total = int(gdata['nslices'])
    ray_total = int(gdata['nrays'])
    px_size = float(gdata['pxsize'])/10  # cm

    # Set parameters for sinograms to read
    step = sino_total // (args.sino_num + 2)
    start = step
    end = step*(args.sino_num + 1)
    sino = (start, end, step)

    # Read full first and last projection to determine center of rotation
    if args.center is None:
        logger.info('Reading full first and last projection for COR')
        first_last, flats, darks, floc = tomopy.read_als_832h5(args.input,
                                                               ind_tomo=(0, last))
        first_last = tomopy.normalize_nf(first_last, flats, darks, floc)
        args.center = tomopy.find_center_pc(first_last[0, :, :],
                                            first_last[1, :, :], tol=0.1)
        logger.info('Detected center: %f', args.center)

    # Read and normalize raw sinograms
    logger.info('Reading raw data')
    tomo, flats, darks, floc = tomopy.read_als_832h5(args.input, sino=sino)
    logger.info('Normalizing raw data')
    tomo = tomopy.normalize_nf(tomo, flats, darks, floc)

    # Remove stripes from sinograms (remove rings)
    logger.info('Preprocessing normalized data')
    if args.ring_remove == 'Tomopy-FW':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_fw(tomo)
    elif args.ring_remove == 'Tomopy-T':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_ti(tomo)

    # Pad sinograms with edge values
    npad = int(np.ceil(ray_total*np.sqrt(2)) - ray_total)//2
    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')
    args.center += npad # account for padding

    filter_name = np.array(args.filter_name, dtype=(str, 16))
    theta = tomopy.angles(tomo.shape[0], 270, 90)

    logger.info('Reconstructing normalized data')
    # Reconstruct sinograms
    rec = tomopy.recon(tomo, theta, center=args.center, emission=False,
                       algorithm=args.algorithm, filter_name=filter_name)
    rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
    rec = rec/px_size

    # Remove rings from reconstruction
    if args.ring_remove == 'Octopus':
        logger.info('Removing rings from reconstructions with %s',
                    args.ring_remove)
        thresh = float(gdata['ring_threshold'])
        thresh_max = float(gdata['upp_ring_value'])
        thresh_min = float(gdata['low_ring_value'])
        theta_min = int(gdata['max_arc_length'])
        rwidth = int(gdata['max_ring_size'])
        rec = tomopy.remove_rings(rec, center_x=args.center, thresh=thresh,
                                  thresh_max=thresh_max, thresh_min=thresh_min,
                                  theta_min=theta_min, rwidth=rwidth)

    # Write reconstruction data to new hdf5 file
    fdata['stage'] = 'fast-tomopy'
    fdata['stage_flow'] = '/raw/' + fdata['stage']
    fdata['stage_version'] = 'fast-tomopy-0.1'
    # WHAT ABOUT uuid ????? Who asigns this???
    del fdata['uuid']  # I'll get rid of it altogether then...

    gdata['Reconstruction_Type'] = 'tomopy-gridrec'
    gdata['ring_removal_method'] = args.ring_remove
    gdata['rfilter'] = args.filter_name

    logger.info('Writing reconstructed data to h5 file')
    write_als_832h5(rec, args.input, fdata, gdata, args.output_file, step)

    return