def main(): """Main function.""" args = parse_args() syris.init(loglevel=logging.INFO, double_precision=args.double_precision) units = q.Quantity(1, args.units) triangles = make_cube( ).magnitude if args.input is None else read_blender_obj(args.input) triangles = triangles * units tr = geom.Trajectory([(0, 0, 0)] * units) mesh = Mesh(triangles, tr, center=args.center, iterations=args.supersampling) LOG.info('Number of triangles: {}'.format(mesh.num_triangles)) shape = (args.n, args.n) if args.pixel_size is None: if args.input is None: fov = 4. * units else: # Maximum sample size in x and y direction max_diff = np.max(mesh.extrema[:-1, 1] - mesh.extrema[:-1, 0]) fov = max_diff fov *= args.margin args.pixel_size = fov / args.n else: fov = args.n * args.pixel_size if args.translate is None: translate = (fov.simplified.magnitude / 2., fov.simplified.magnitude / 2., 0) * q.m else: translate = (args.translate[0].simplified.magnitude, args.translate[1].simplified.magnitude, 0) * q.m LOG.info('Translation: {}'.format(translate.rescale(q.um))) mesh.translate(translate) mesh.rotate(args.y_rotate, geom.Y_AX) mesh.rotate(args.x_rotate, geom.X_AX) fmt = 'n: {}, pixel size: {}, FOV: {}' LOG.info( fmt.format(args.n, args.pixel_size.rescale(q.um), fov.rescale(q.um))) st = time.time() proj = mesh.project(shape, args.pixel_size, t=None).get() LOG.info('Duration: {} s'.format(time.time() - st)) offset = (0, translate[1].simplified, -(fov / 2.).simplified) * q.m if args.projection_filename is not None: save_image(args.projection_filename, proj) if args.compute_slice: sl = mesh.compute_slices((1, ) + shape, args.pixel_size, offset=offset).get()[0] if args.slice_filename is not None: save_image(args.slice_filename, sl) show(sl, title='Slice at y = {}'.format(args.n / 2)) show(proj, title='Projection') plt.show()
def main(): args = parse_args() syris.init() prg = cl.Program(cfg.OPENCL.ctx, get_kernel()).build() if len(args.k) == 1: complexities = args.k else: complexities = np.arange(args.k[0], args.k[1] + args.k[2], args.k[2]) print 'Complexities: {}'.format(complexities) results = [] for complexity in complexities: runs = [] for i in range(args.runs): print 'Run {} / {}'.format(i + 1, args.runs) runs.append(run(args.n, args.m, complexity, prg, verbose=args.verbose)) if args.output: np.save(args.output.format(complexity), runs) results.append(np.mean(runs)) print print '===============================' for i, result in enumerate(results): print 'Complexity: {:.2f}, speedup: {:.2f}'.format(complexities[i], result) print '===============================' if args.plot: plt.figure() plt.plot(complexities, results) plt.xlabel('Complexity') plt.xlabel('Speedup') plt.grid() plt.show()
def test_init(): syris.init(profiling=True, loglevel=logging.DEBUG, double_precision=True) assert logging.DEBUG == syris.physics.LOG.getEffectiveLevel() assert cfg.OPENCL.ctx is not None assert cfg.PRECISION.cl_float == 8 assert syris.profiling.PROFILER is not None assert cfg.PRECISION.vfloat2 == cl_array.vec.double2
def make_topo_tomo_flat(args, highspeed=True, scintillator=None): syris.init(device_index=0, loglevel='INFO') dimax = make_pco_dimax() n = dimax.shape[0] energies = np.arange(5, 30) * q.keV bm, detector = make_devices(n, energies, camera=dimax, highspeed=highspeed, scintillator=scintillator) # Customize the setup for the 2013_03_07-08 experiment air = MaterialFilter(1 * q.m, get_material('air_5_30_kev.mat')) filters = [air] dimax.bpp = 32 dimax.dtype = np.float32 dimax.fps = 450 / q.s detector.lens.f_number = 2.8 bm.el_current = 130 * q.mA # Compte the flat field flat = get_flat(dimax.shape, energies, detector, bm, filters=filters, shot_noise=True, amplifier_noise=True) fmt = 'min: {}, max: {}, mean: {}, middle row std: {}' print fmt.format(flat.min(), flat.max(), flat.mean(), flat[n / 2].std()) show(flat) plt.show() return flat
def main(): args = parse_args() syris.init(profiling=True) prg = cl.Program(cfg.OPENCL.ctx, get_kernel()).build() if len(args.k) == 1: complexities = args.k else: complexities = np.arange(args.k[0], args.k[1] + args.k[2], args.k[2]) print("Complexities: {}".format(complexities)) results = [] for complexity in complexities: runs = [] for i in range(args.runs): print("Run {} / {}".format(i + 1, args.runs)) runs.append(run(args.n, args.m, complexity, prg, verbose=args.verbose)) if args.output: np.save(args.output.format(complexity), runs) results.append(np.mean(runs)) print() print("===============================") for i, result in enumerate(results): print("Complexity: {:.2f}, speedup: {:.2f}".format(complexities[i], result)) print("===============================") if args.plot: plt.figure() plt.plot(complexities, results) plt.xlabel("Complexity") plt.xlabel("Speedup") plt.grid() plt.show()
def main(): args = parse_args() syris.init() n = 32 ps = 1 * q.um energies = np.arange(5, 30) * q.keV energy = 10 * q.keV lam = energy_to_wavelength(energy) # Delta causes phase shift between two adjacent pixels by 2 Pi delta = (lam / ps).simplified.magnitude ri = np.ones_like(energies.magnitude, dtype=np.complex) * delta + 0j material = Material("dummy", ri, energies) fmt = "Computing with n: {:>4}, pixel size: {}" wedge = np.tile(np.arange(n), [n, 1]) * ps # Non-supersampled object shape causes phase shifts 0, 2Pi, 4Pi, ..., thus the phase is constant # as an extreme result of aliasing print(fmt.format(n, ps)) u = compute_transmission_function(n, ps, 1, energy, material) # Supersampling helps resolve the transmission function print(fmt.format(n * args.supersampling, ps / args.supersampling)) u_s = compute_transmission_function(n, ps, args.supersampling, energy, material) show(wedge.magnitude, title="Projected Object [um]") show(u.real, title="Re[T(x, y)]") show(u_s.real, title="Re[T(x, y)] Supersampled") plt.show()
def setUp(self): syris.init(device_index=0) self.data = np.arange(10).astype(cfg.PRECISION.np_float) self.mem = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.data)
def setUp(self): syris.init(double_precision=True, device_index=0) self.energy = 20 * q.keV self.lam = 6.19920937165e-11 * q.m self.size = 64 self.distance = 1 * q.m self.pixel_size = 1 * q.um
def main(): parser = get_default_parser(__doc__) subparsers = parser.add_subparsers(help='sub-command help') manual = subparsers.add_parser( 'manual', help='Manual positioning via simple transformations') trajectory = subparsers.add_parser( 'trajectory', help='Automatic positioning via trajectories') subtrajectories = subparsers.add_parser('subtrajectories', help='Automatic positioning with ' 'local sub-body trajectories') manual.set_defaults(_func=make_manual_sequence) trajectory.set_defaults(_func=make_trajectory_sequence) subtrajectories.add_argument( '--t', type=float, help='Time at which to compute the projection normalized to ' '[0, 1], if not specified, complete sequence is shown') subtrajectories.set_defaults(_func=make_complex_trajectory_sequence) args = parser.parse_args() syris.init(device_index=0) # Set constants args.n = 512 args.shape = (args.n, args.n) args.ps = 1 * q.um args._func(args)
def test_no_opencl_init(): """Initialization by broken OpenCL must work too, just the context and profiling not.""" cl.get_platforms = lambda: None syris.init(profiling=False, loglevel=logging.DEBUG, double_precision=True) assert logging.DEBUG == syris.physics.LOG.getEffectiveLevel() assert cfg.PRECISION.cl_float == 8 assert cfg.PRECISION.vfloat2 == cl_array.vec.double2
def main(): args = parse_args() syris.init() n = 1024 d = args.propagation_distance * q.m shape = (n, n) ps = 1 * q.um energy = 20 * q.keV tr = Trajectory([(n / 2, n / 2, 0)] * ps, pixel_size=ps) sample = make_sphere(n, n / 30 * ps, pixel_size=ps, material=get_material('air_5_30_kev.mat')) bm = make_topotomo(pixel_size=ps, trajectory=tr) print 'Source size FWHM (height x width): {}'.format(bm.size.rescale(q.um)) u = bm.transfer(shape, ps, energy, t=0 * q.s) u = sample.transfer(shape, ps, energy) intensity = propagate([sample], shape, [energy], d, ps).get() incoh = bm.apply_blur(intensity, d, ps).get() region = (n / 4, n / 4, n / 2, n / 2) intensity = ip.crop(intensity, region).get() incoh = ip.crop(incoh, region).get() show(intensity, title='Coherent') show(incoh, title='Applied source blur') plt.show()
def main(): """main""" args = parse_args() n = 256 ps = 10 * q.um syris.init() mb = create_sample(n, ps) mb.bind_trajectory(ps) tr = mb.trajectory print 'Length: {}, time: {}'.format(tr.length.rescale(q.mm), tr.time) plt.figure() plt.plot(tr.points[0].rescale(q.um), tr.points[1].rescale(q.um)) plt.title('Trajectory') times, points = get_diffs(mb, ps) if args.output is not None: if not os.path.exists(args.output): os.makedirs(args.output, mode=0o755) for i, t in enumerate(times): mb.clear_transformation() proj = mb.project((n, n), ps, t=t).get() scipy.misc.imsave(os.path.join(args.output, 'projection_{:>04}.tif'.format(i)), proj) plt.show()
def main(): args = parse_args() syris.init() n = 32 ps = 1 * q.um energies = np.arange(5, 30) * q.keV energy = 10 * q.keV lam = energy_to_wavelength(energy) # Delta causes phase shift between two adjacent pixels by 2 Pi delta = (lam / ps).simplified.magnitude ri = np.ones_like(energies.magnitude, dtype=np.complex) * delta + 0j material = Material('dummy', ri, energies) fmt = 'Computing with n: {:>4}, pixel size: {}' wedge = np.tile(np.arange(n), [n, 1]) * ps # Non-supersampled object shape causes phase shifts 0, 2Pi, 4Pi, ..., thus the phase is constant # as an extreme result of aliasing print fmt.format(n, ps) u = compute_transmission_function(n, ps, 1, energy, material) # Supersampling helps resolve the transmission function print fmt.format(n * args.supersampling, ps / args.supersampling) u_s = compute_transmission_function(n, ps, args.supersampling, energy, material) show(wedge.magnitude, title='Projected Object [um]') show(u.real, title='Re[T(x, y)]') show(u_s.real, title='Re[T(x, y)] Supersampled') plt.show()
def test_fft(self): data = gpu_util.get_array(np.random.normal(100, 100, size=(4, 4)).astype(cfg.PRECISION.np_float)) orig = gpu_util.get_host(data) data = ip.fft_2(data) ip.ifft_2(data) np.testing.assert_almost_equal(orig, data.get().real, decimal=4) # With a plan from pyfft.cl import Plan plan = Plan((4, 4), queue=cfg.OPENCL.queue) data = ip.fft_2(np.copy(orig), plan=plan) ip.ifft_2(data, plan=plan) np.testing.assert_almost_equal(orig, data.get().real, decimal=4) # Test double precision syris.init(double_precision=True, device_index=0) data = gpu_util.get_array(np.random.normal(100, 100, size=(4, 4)).astype(cfg.PRECISION.np_float)) gt = np.fft.fft2(data.get()) data = ip.fft_2(data) np.testing.assert_almost_equal(gt, data.get(), decimal=4) gt = np.fft.ifft2(data.get()) data = ip.ifft_2(data) np.testing.assert_almost_equal(gt, data.get(), decimal=4)
def main(): args = parse_args() syris.init(device_index=0) m = 20 if args.input == 'grid': image = make_grid(args.n, m * q.m).thickness.get() elif args.input == 'lena': from scipy.misc import lena image = lena().astype(cfg.PRECISION.np_float) if args.n != image.shape[0]: image = gutil.get_host(ip.rescale(image, (args.n, args.n))) n = image.shape[0] crop_n = n - 2 * m - 2 y, x = np.mgrid[-n / 2:n / 2, -n / 2:n / 2] # Compute a such that the disk diameter is exactly the period when distance from the middle is n # / 2 a = m / (2 * (crop_n / 2.) ** 2) radii = (a * np.sqrt(x ** 2 + y ** 2) ** 2 + 1e-3).astype(cfg.PRECISION.np_float) x_param = radii y_param = radii result = ip.varconvolve_disk(image, (y_param, x_param)).get() result = ip.crop(result, (m - 1, m - 1, crop_n, crop_n)).get() radii = ip.crop(radii, (m - 1, m - 1, crop_n, crop_n)).get() image = ip.crop(image, (m - 1, m - 1, crop_n, crop_n)).get() if args.output: save_image(args.output, result) show(image, title='Original Image') show(2 * radii, title='Blurring Disk Diameters') show(result, title='Blurred Image') plt.show()
def main(): parser = get_default_parser(__doc__) subparsers = parser.add_subparsers(help="sub-command help", dest="sub-commands", required=True) manual = subparsers.add_parser( "manual", help="Manual positioning via simple transformations") trajectory = subparsers.add_parser( "trajectory", help="Automatic positioning via trajectories") subtrajectories = subparsers.add_parser("subtrajectories", help="Automatic positioning with " "local sub-body trajectories") manual.set_defaults(_func=make_manual_sequence) trajectory.set_defaults(_func=make_trajectory_sequence) subtrajectories.add_argument( "--t", type=float, help="Time at which to compute the projection normalized to " "[0, 1], if not specified, complete sequence is shown", ) subtrajectories.set_defaults(_func=make_complex_trajectory_sequence) args = parser.parse_args() syris.init(device_index=0) # Set constants args.n = 512 args.shape = (args.n, args.n) args.ps = 1 * q.um args._func(args)
def main(): args = parse_args() syris.init(device_index=0) m = 20 if args.input == 'grid': image = make_grid(args.n, m * q.m).thickness.get() elif args.input == 'lena': from scipy.misc import lena image = lena().astype(cfg.PRECISION.np_float) if args.n != image.shape[0]: image = gutil.get_host(ip.rescale(image, (args.n, args.n))) n = image.shape[0] crop_n = n - 2 * m - 2 y, x = np.mgrid[-n / 2:n / 2, -n / 2:n / 2] # Compute a such that the disk diameter is exactly the period when distance from the middle is n # / 2 a = m / (2 * (crop_n / 2.)**2) radii = (a * np.sqrt(x**2 + y**2)**2 + 1e-3).astype(cfg.PRECISION.np_float) x_param = radii y_param = radii result = ip.varconvolve_disk(image, (y_param, x_param)).get() result = ip.crop(result, (m - 1, m - 1, crop_n, crop_n)).get() radii = ip.crop(radii, (m - 1, m - 1, crop_n, crop_n)).get() image = ip.crop(image, (m - 1, m - 1, crop_n, crop_n)).get() if args.output: save_image(args.output, result) show(image, title='Original Image') show(2 * radii, title='Blurring Disk Diameters') show(result, title='Blurred Image') plt.show()
def main(): """main""" syris.init(double_precision=True) n = 512 ps = 0.5 * q.um energy = 10 * q.keV lam = energy_to_wavelength(energy) # Compute the sampling limit for given n, ps and lam ca = (lam / 2 / ps).simplified.magnitude tga = np.tan(np.arccos(ca)) distance = (tga * n * ps / 2).simplified print 'Propagation distance:', distance propagator = compute_propagator(n, distance, lam, ps, apply_phase_factor=True, mollified=False).get() full_propagator = compute_propagator(n, distance, lam, ps, fresnel=False, mollified=False).get() np_propagator = compute_fourier_propagator(n, lam, distance, ps) np_full_propagator = compute_fourier_propagator(n, lam, distance, ps, fresnel=False) diff = propagator - np_propagator full_diff = full_propagator - np_full_propagator show(np.fft.fftshift(propagator.real), 'Syris Fresnel Propagator (Real Part)') show(np.fft.fftshift(np_propagator.real), 'Numpy Fresnel propagator (Real Part)') show(np.fft.fftshift(diff.real), 'Fresnel Syris - Fresnel Numpy (Real Part)') show(np.fft.fftshift(full_propagator.real), 'Syris Full Propagator (Real Part)') show(np.fft.fftshift(np_full_propagator.real), 'Numpy Full propagator (Real Part)') show(np.fft.fftshift(full_diff.real), 'Full Syris - Full Numpy (Real Part)') plt.show()
def setUp(self): syris.init(device_index=0) energies = range(10, 20) * q.keV self.energy = energies[len(energies) / 2] self.material = Material('foo', np.arange(len(energies), dtype=np.complex), energies)
def process(args, device_index): import syris from syris.geometry import Trajectory from syris.bodies.mesh import Mesh, read_blender_obj syris.init(device_index=device_index, logfile=args.logfile, double_precision=args.double_precision) path, ext = os.path.splitext(args.input) if ext == ".obj": tri = read_blender_obj(args.input) else: tri = np.load(args.input) tri = tri * q.um tr = Trajectory([(0, 0, 0)] * q.um) mesh = Mesh(tri, tr, center=None, iterations=args.supersampling_projection) if args.n: n = args.n fov = n * args.pixel_size else: fov = max([ends[1] - ends[0] for ends in mesh.extrema[:-1]]) * 1.1 n = int(np.ceil((fov / args.pixel_size).simplified.magnitude)) shape = (n, n) if args.make_gt: LOG.info("--- Args info ---") log_attributes(args) return make_ground_truth(args, shape, mesh) else: num_projs = int( np.pi * n) if args.num_projections is None else args.num_projections angles = np.linspace(0, args.rotation_angle, num_projs, endpoint=False) * q.deg if device_index == 0: LOG.info("n: {}, ps: {}, FOV: {}".format(n, args.pixel_size, fov)) LOG.info("Total rotation angle: {} deg".format( args.rotation_angle)) LOG.info("Number of projections: {}".format(num_projs)) LOG.info("--- Mesh info ---") log_attributes(mesh) LOG.info("--- Args info ---") log_attributes(args) return scan( shape, args.pixel_size, args.rotation_axis, mesh, angles, args.prefix, lamino_angle=args.lamino_angle, index=device_index, num_devices=args.num_devices, ss=args.supersampling, )
def make_motion(args): syris.init() n = 256 shape = (n, n) energies = np.arange(5, 30, 1) * q.keV bm, detector = make_devices(n, energies) mb = create_sample(n, detector.pixel_size, velocity=20 * q.mm / q.s) mb_2 = create_sample(n, detector.pixel_size, velocity=10 * q.mm / q.s) mb.material = get_material('pmma_5_30_kev.mat') mb_2.material = mb.material cube = make_cube() / q.m * 30 * detector.pixel_size + 0.1 * detector.pixel_size fov = detector.pixel_size * n circle = make_circle().magnitude * fov / 30000 + fov / 2 tr = Trajectory(circle, velocity=10 * q.um / q.s) glass = get_material('glass.mat') mesh = Mesh(cube, tr, material=glass) ex = Experiment([bm, mb, mb_2, mesh], bm, detector, 0 * q.m, energies) for sample in ex.samples: if sample != bm: sample.trajectory.bind(detector.pixel_size) if args.show_flat: show(get_flat(shape, energies, detector, bm), title='Counts') plt.show() if args.conduct: if args.output is not None and not os.path.exists(args.output): os.makedirs(args.output, mode=0o755) t_0 = 0 * q.s if args.num_images: t_1 = args.num_images / detector.camera.fps else: t_1 = ex.time st = time.time() mpl_im = None for i, proj in enumerate(ex.make_sequence(t_0, t_1)): image = get_host(proj) if args.show: if mpl_im is None: plt.figure() mpl_im = plt.imshow(image) plt.show(False) else: mpl_im.set_data(image) plt.draw() if args.output: path = os.path.join(args.output, 'projection_{:>05}.png').format(i) scipy.misc.imsave(path, image) print 'Maximum intensity:', image.max() print 'Duration: {} s'.format(time.time() - st) plt.show()
def setUp(self): syris.init(device_index=0) self.pixel_size = 1e-3 self.precision_places = int(np.log10(1 / self.pixel_size)) self.prg = g_util.get_program(g_util.get_metaobjects_source()) self.poly_deg = 4 self.roots_mem = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE, size=(self.poly_deg + 1) * cfg.PRECISION.cl_float)
def default_syris_init(double_precision=False, profiling=False): syris.init( device_type=cl.device_type.CPU, device_index=0, double_precision=double_precision, profiling=profiling, loglevel=logging.CRITICAL, )
def setUp(self): syris.init(device_index=0) self.pixel_size = 1 * q.um control_points = get_linear_points(geom.X, start=(1, 1, 1)) traj = Trajectory(control_points, velocity=1 * q.mm / q.s) self.metaball = MetaBall(traj, 1 * q.mm) self.metaball_2 = MetaBall(Trajectory(get_linear_points(geom.Z)), 2 * q.mm) self.composite = CompositeBody(traj, bodies=[self.metaball, self.metaball_2])
def setUp(self): syris.init(device_index=0) self.energies = np.arange(10, 20) * q.keV self.energy = 15 * q.keV delta = np.linspace(1e-5, 1e-6, len(self.energies)) beta = np.linspace(1e-8, 1e-9, len(self.energies)) self.material = Material('foo', delta + beta * 1j, self.energies) self.thickness = 1 * q.mm self.fltr = MaterialFilter(self.thickness, self.material)
def setUp(self): # Double precision needed for spherical phase profile syris.init(double_precision=True, device_index=0) self.dE = 0.1 * q.keV self.energies = np.arange(14.8, 15, self.dE.magnitude) * q.keV self.trajectory = Trajectory([(0, 0, 0)] * q.m) self.ps = 10 * q.um self.source = BendingMagnet(2.5 * q.GeV, 150 * q.mA, 1.5 * q.T, 30 * q.m, self.dE, np.array([0.2, 0.8]) * q.mm, self.ps, self.trajectory)
def test_simple(): syris.init(device_index=0) n = 8 ps = 1 * q.um thickness = np.arange(n**2).reshape(n, n).astype( cfg.PRECISION.np_float) * q.m go = StaticBody(thickness, ps) # Same projection = go.project((n, n), ps).get() np.testing.assert_almost_equal(thickness.magnitude, projection) # Cropped upsampled shape = (n, n) gt = rescale(thickness.magnitude, shape).get() projection = go.project(shape, ps / 2).get() gt = rescale(crop(thickness.magnitude, (0, 0, n / 2, n / 2)), shape).get() np.testing.assert_almost_equal(gt, projection) # Cropped downsampled shape = (n / 4, n / 4) gt = rescale(thickness.magnitude, shape).get() projection = go.project(shape, 2 * ps).get() gt = rescale(crop(thickness.magnitude, (0, 0, n / 2, n / 2)), shape).get() np.testing.assert_almost_equal(gt, projection) # Padded upsampled shape = (4 * n, 4 * n) projection = go.project(shape, ps / 2, offset=(-n / 2, -n / 2) * ps).get() gt = rescale(pad(thickness.magnitude, (n / 2, n / 2, 2 * n, 2 * n)), shape).get() np.testing.assert_almost_equal(gt, projection) # Padded downsampled shape = (n, n) projection = go.project(shape, 2 * ps, offset=(-n / 2, -n / 2) * ps).get() gt = rescale(pad(thickness.magnitude, (4, 4, 2 * n, 2 * n)), shape).get() np.testing.assert_almost_equal(gt, projection) # Crop and pad and upsample def crop_pad_rescale(ss): shape = (n, n) target_ps = ps / ss fov = shape * ps offset = (2, -2) * q.um shape = (int(n / 2 * ss), int(ss * 3 * n / 2)) projection = go.project(shape, target_ps, offset=offset).get() gt = rescale( pad(thickness[n / 4:3 * n / 4, :], (0, n / 4, n / 2, 3 * n / 2)), shape).get() np.testing.assert_almost_equal(gt, projection) crop_pad_rescale(2) crop_pad_rescale(0.5)
def setUp(self): syris.init(device_index=0) self.prg = g_util.get_program( g_util.get_source(["polyobject.cl", "heapsort.cl"], precision_sensitive=True)) self.num = 10 self.data = np.array([1, 8, np.nan, -1, np.nan, 8, 680, 74, 2, 0]).\ astype(cfg.PRECISION.np_float) self.mem = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.data)
def setUp(self): syris.init(device_index=0) self.num_0 = np.array([17 - 38j], dtype=cfg.PRECISION.np_cplx) self.num_1 = np.array([-135 + 563j], dtype=cfg.PRECISION.np_cplx) self.mem_0 = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.num_0) self.mem_1 = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.num_1) self.mem_out = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE, cfg.PRECISION.cl_cplx) self.host_array = np.empty(1, cfg.PRECISION.np_cplx) src = gpu_util.get_source(["vcomplex.cl"]) self.prg = cl.Program(cfg.OPENCL.ctx, src).build()
def main(): args = parse_args() syris.init(device_index=0) shape = (args.n, args.n) pixel_size = 1 * q.um if args.method == "random": # Random metaballs creation metaballs, objects_all = create_metaballs_random( args.n, pixel_size, args.num, args.min_radius, args.max_radius, distance_from_center=args.distance_from_center, ) elif args.method == "file": # 1e6 because packing converts to meters values = np.fromfile(args.input, dtype=np.float32) * 1e6 metaballs, objects_all = create_metaballs( values.reshape(len(values) // 4, 4), pixel_size) else: distance = args.distance or args.n / 4 positions = [ (args.n / 2 - distance, args.n / 2, 0, args.n / 6), (args.n / 2 + distance, args.n / 2, 0, args.n / 6), ] metaballs, objects_all = create_metaballs(positions, pixel_size) if args.output: with open(args.output, mode="wb") as out_file: out_file.write(objects_all) z_min, z_max = get_z_range(metaballs) print("z min, max:", z_min.rescale(q.um), z_max.rescale(q.um), args.n * pixel_size + z_min) if args.algorithm == "fast": traj = Trajectory([(0, 0, 0)] * q.m) comp = MetaBalls(traj, metaballs) thickness = comp.project(shape, pixel_size).get() else: print("Z steps:", int(((z_max - z_min) / pixel_size).simplified.magnitude + 0.5)) thickness = project_metaballs_naive(metaballs, shape, make_tuple(pixel_size)).get() if args.output_thickness: imageio.imwrite(args.output_thickness, thickness) show(thickness) plt.show()
def main(): args = parse_args() syris.init() # Propagate to 20 cm d = 5 * q.cm # Compute grid n_camera = 256 n = n_camera * args.supersampling shape = (n, n) material = get_material("pmma_5_30_kev.mat") energy = 15 * q.keV ps = 1 * q.um ps_hd = ps / args.supersampling radius = n / 4.0 * ps_hd fmt = " Wavelength: {}" print(fmt.format(energy_to_wavelength(energy))) fmt = "Pixel size used for propagation: {}" print(fmt.format(ps_hd.rescale(q.um))) print(" Field of view: {}".format(n * ps_hd.rescale(q.um))) fmt = " Sphere diameter: {}" print(fmt.format(2 * radius)) sample = make_sphere(n, radius, pixel_size=ps_hd, material=material) projection = sample.project((n, n), ps_hd).get() * 1e6 projection = decimate(projection, (n_camera, n_camera), average=True).get() # Propagation with a monochromatic plane incident wave hd = propagate([sample], shape, [energy], d, ps_hd).get() ld = decimate(hd, (n_camera, n_camera), average=True).get() kernel = compute_tie_kernel(n_camera, ps, d, material, energy) mju = material.get_attenuation_coefficient(energy).rescale(1 / q.m).magnitude f_ld = fft_2(ld) f_ld *= get_array(kernel.astype(cfg.PRECISION.np_float)) retrieved = ifft_2(f_ld).get().real retrieved = -1 / mju * np.log(retrieved) * 1e6 if args.output_thickness: imageio.imwrite(args.output_thickness, projection) if args.output_projection: imageio.imwrite(args.output_projection, ld) if args.output_retrieved: imageio.imwrite(args.output_retrieved, retrieved) show(hd, title="High resolution") show(ld, title="Low resolution (detector)") show(retrieved, title="Retrieved [um]") show(projection, title="Projection [um]") show(projection - retrieved, title="Projection - retrieved") plt.show()
def setUp(self): syris.init(device_index=0) wavelengths = np.arange(10) * q.nm qe = np.ones(len(wavelengths)) self.camera = Camera(1e-3 * q.um, 1.0, 10.0, 0, 10, (64, 64), wavelengths=wavelengths, quantum_efficiencies=qe, exp_time=1 * q.s, fps=1 / q.s)
def setUp(self): syris.init(device_index=0) self.data = [] sizes = [8, 32] tile_counts = [2, 4] for j in range(len(sizes)): for i in range(len(sizes)): size = sizes[j], sizes[i] for t_j in range(len(tile_counts)): for t_i in range(len(tile_counts)): tiles_count = tile_counts[t_j], tile_counts[t_i] self.data.append((size, tiles_count))
def main(): syris.init() energies = np.arange(10, 30) * q.keV n = 1024 pixel_size = 0.4 * q.um distance = 2 * q.m material = make_henke('PMMA', energies) sample = make_sphere(n, n / 4 * pixel_size, pixel_size, material=material) image = propagate([sample], (n, n), energies, distance, pixel_size).get() show(image) plt.show()
def main(): args = parse_args() syris.init() n = 1024 shape = (n, n) ps = 1 * q.um tr = Trajectory([(n / 2, n / 2, 0)] * ps, pixel_size=ps) energy_center = args.energy_center * q.keV fwhm = args.energy_resolution * energy_center sigma = smath.fwnm_to_sigma(fwhm, n=2) # Make sure we resolve the curve nicely energies = np.arange(max(1 * q.keV, energy_center - 2 * fwhm), energy_center + 2 * fwhm, fwhm / 25) * q.keV dE = energies[1] - energies[0] print 'Energy from, to, step, number:', energies[0], energies[-1], dE, len( energies) bm = make_topotomo(dE=dE, pixel_size=ps, trajectory=tr) spectrum_energies = np.arange(1, 50, 1) * q.keV native_spectrum = get_spectrum(bm, spectrum_energies, ps) fltr = GaussianFilter(energies, energy_center, sigma) gauss = get_gauss(energies.magnitude, energy_center.magnitude, sigma.magnitude) filtered_spectrum = get_spectrum(bm, energies, ps) * gauss intensity = propagate([bm, fltr], shape, energies, 0 * q.m, ps).get() show(intensity, title='Intensity for energy range {} - {}'.format( energies[0], energies[-1])) plt.figure() plt.plot(spectrum_energies.magnitude, native_spectrum) plt.title('Source Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.figure() plt.plot(energies.magnitude, gauss) plt.title('Gaussian Filter') plt.xlabel('Energy [keV]') plt.ylabel('Transmitted intensity') plt.figure() plt.plot(energies.magnitude, filtered_spectrum) plt.title('Filtered Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.show()
def setUp(self): syris.init(device_index=0) lens = Lens(3., f_number=1.4, focal_length=100.0 * q.mm) camera = Camera(1 * q.um, 0.1, 10, 1.0, 12, (64, 64)) detector = Detector(None, lens, camera) ps = detector.pixel_size t = np.linspace(0, 1, 10) * q.mm x = t y = np.zeros(len(t)) z = np.zeros(len(t)) points = zip(x, y, z) * q.mm mb_0 = MetaBall(Trajectory(points, pixel_size=ps, furthest_point=1 * q.um, velocity=1 * q.mm / q.s), 1 * q.um) mb_1 = MetaBall(Trajectory(points, pixel_size=ps, furthest_point=1 * q.um, velocity=2 * q.mm / q.s), 1 * q.um) self.experiment = Experiment([mb_0, mb_1], None, detector, 0 * q.m, None)
def setUp(self): syris.init(device_index=0) self.poly_deg = 4 self.coeffs = np.array([5, 87, -2, 37, 17], dtype=cfg.PRECISION.np_float) self.coeffs_mem = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.coeffs) self.scalar_mem = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE, size=cfg.PRECISION.cl_float) self.pixel_size = 1e-3 self.precision_places = int(np.log10(1 / self.pixel_size)) self.prg = g_util.get_program(g_util.get_metaobjects_source()) self.roots_mem = cl.Buffer(cfg.OPENCL.ctx, cl.mem_flags.READ_WRITE, size=(self.poly_deg + 1) * cfg.PRECISION.cl_float)
def main(): args = parse_args() syris.init() n = 1024 shape = (n, n) ps = 1 * q.um tr = Trajectory([(n / 2, n / 2, 0)] * ps, pixel_size=ps) energy_center = args.energy_center * q.keV fwhm = args.energy_resolution * energy_center sigma = smath.fwnm_to_sigma(fwhm, n=2) # Make sure we resolve the curve nicely energies = np.arange(max(1 * q.keV, energy_center - 2 * fwhm), energy_center + 2 * fwhm, fwhm / 25) * q.keV dE = energies[1] - energies[0] print 'Energy from, to, step, number:', energies[0], energies[-1], dE, len(energies) bm = make_topotomo(dE=dE, pixel_size=ps, trajectory=tr) spectrum_energies = np.arange(1, 50, 1) * q.keV native_spectrum = get_spectrum(bm, spectrum_energies, ps) fltr = GaussianFilter(energies, energy_center, sigma) gauss = get_gauss(energies.magnitude, energy_center.magnitude, sigma.magnitude) filtered_spectrum = get_spectrum(bm, energies, ps) * gauss intensity = propagate([bm, fltr], shape, energies, 0 * q.m, ps).get() show(intensity, title='Intensity for energy range {} - {}'.format(energies[0], energies[-1])) plt.figure() plt.plot(spectrum_energies.magnitude, native_spectrum) plt.title('Source Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.figure() plt.plot(energies.magnitude, gauss) plt.title('Gaussian Filter') plt.xlabel('Energy [keV]') plt.ylabel('Transmitted intensity') plt.figure() plt.plot(energies.magnitude, filtered_spectrum) plt.title('Filtered Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.show()
def main(): syris.init() n = 256 shape = (n, n) ps = 1 * q.um fov = n * ps triangles = make_cube().magnitude * n / 8. * ps # Rotation around the vertical axis points = make_circle(axis='y').magnitude * fov / 30000 + fov / 2 trajectory = geom.Trajectory(points, pixel_size=ps, velocity=10 * q.um / q.s) # *orientation* aligns the object with the trajectory derivative mesh = Mesh(triangles, trajectory, orientation=geom.Z_AX) # Compute projection at the angle Pi/4 projection = mesh.project(shape, ps, t=trajectory.time / 8).get() show(projection) plt.show()
def process(args, device_index): import syris from syris.geometry import Trajectory from syris.bodies.mesh import Mesh, read_blender_obj syris.init(device_index=device_index, logfile=args.logfile, double_precision=args.double_precision) path, ext = os.path.splitext(args.input) if ext == '.obj': tri = read_blender_obj(args.input) else: tri = np.load(args.input) tri = tri * q.um tr = Trajectory([(0, 0, 0)] * q.um) mesh = Mesh(tri, tr, center=None, iterations=args.supersampling_projection) if args.n: n = args.n fov = n * args.pixel_size else: fov = max([ends[1] - ends[0] for ends in mesh.extrema[:-1]]) * 1.1 n = int(np.ceil((fov / args.pixel_size).simplified.magnitude)) shape = (n, n) if args.make_gt: LOG.info('--- Args info ---') log_attributes(args) return make_ground_truth(args, shape, mesh) else: num_projs = int(np.pi * n) if args.num_projections is None else args.num_projections angles = np.linspace(0, args.rotation_angle, num_projs, endpoint=False) * q.deg if device_index == 0: LOG.info('n: {}, ps: {}, FOV: {}'.format(n, args.pixel_size, fov)) LOG.info('Total rotation angle: {} deg'.format(args.rotation_angle)) LOG.info('Number of projections: {}'.format(num_projs)) LOG.info('--- Mesh info ---') log_attributes(mesh) LOG.info('--- Args info ---') log_attributes(args) return scan(shape, args.pixel_size, args.rotation_axis, mesh, angles, args.prefix, lamino_angle=args.lamino_angle, index=device_index, num_devices=args.num_devices, ss=args.supersampling)
def main(): args = parse_args() syris.init(platform_name=args.platform, loglevel='INFO') if args.num_devices > len(cfg.OPENCL.queues): fmt = "There are only {} devices available for platform '{}'" raise ValueError(fmt.format(len(cfg.OPENCL.devices), args.platform)) queues = cfg.OPENCL.queues[:args.num_devices] result = [] for n in args.n: mean, std = run(n, args.pixel_size * q.um, args.runs, queues) result.append((n, mean, std)) if args.output: np.savetxt(args.output, result, fmt='%g', header='n\tmean duration [s]\tstd [s], number of runs: {}'.format(args.runs), delimiter='\t') return result
def main(): args = parse_args() syris.init(device_index=0) shape = (args.n, args.n) pixel_size = 1 * q.um if args.method == 'random': # Random metaballs creation metaballs, objects_all = create_metaballs_random(args.n, pixel_size, args.num, args.min_radius, args.max_radius) elif args.method == 'file': # 1e6 because packing converts to meters values = np.fromfile(args.input, dtype=np.float32) * 1e6 metaballs, objects_all = create_metaballs(values.reshape(len(values) / 4, 4)) else: distance = args.distance or args.n / 4 positions = [(args.n / 2 - distance, args.n / 2, 0, args.n / 6), (args.n / 2 + distance, args.n / 2, 0, args.n / 6)] metaballs, objects_all = create_metaballs(positions) if args.output: with open(args.output, mode='wb') as out_file: out_file.write(objects_all) z_min, z_max = get_z_range(metaballs) print 'z min, max:', z_min.rescale(q.um), z_max.rescale(q.um), args.n * pixel_size + z_min if args.algorithm == 'fast': traj = Trajectory([(0, 0, 0)] * q.m) comp = MetaBalls(traj, metaballs) thickness = comp.project(shape, pixel_size).get() else: print 'Z steps:', int(((z_max - z_min) / pixel_size).simplified.magnitude + 0.5) thickness = project_metaballs_naive(metaballs, shape, make_tuple(pixel_size)).get() if args.output_thickness: save_image(args.output_thickness, thickness) show(thickness) plt.show()
def main(): syris.init() args = parse_args() n = 256 shape = (n, n) ps = 1 * q.um num_projections = None cube_edge = n / 4 * ps fmt = os.path.join(args.output, 'projection_{:04}.tif') x = np.linspace(n / 4 + n / 8, 3 * n / 4 + n / 8, num=10) y = z = np.zeros(x.shape) cube_0 = make_cube_body(n, ps, cube_edge) cube_1 = make_cube_body(n, ps, cube_edge, phase_shift=np.pi * q.rad) # Vertical motion component has such velocity that the cubes are displaced by their edge length # 1 pixel for making sure we have one "complete" sinogram velocity = (cube_edge - ps) / cube_0.trajectory.time traj_y = geom.Trajectory(zip(y, x, z) * ps, pixel_size=ps, velocity=velocity) composite = CompositeBody(traj_y, bodies=[cube_0, cube_1]) # Total time is the rotation time because we want one tomographic data set total_time = cube_0.trajectory.time dt = composite.get_next_time(0 * q.s, ps) if num_projections is None: num_projections = int(np.ceil((total_time / dt).simplified.magnitude)) print ' num_projs:', num_projections print ' rotation time:', cube_0.trajectory.time print ' vertical motion time:', traj_y.time print ' simulation time:', total_time for i in range(num_projections): t = total_time / num_projections * i composite.move(t) projection = composite.project(shape, ps).get() tifffile.imsave(fmt.format(i), projection) show(projection) plt.show()
def main(): syris.init() n = 512 shape = (n, n) ps = 1 * q.um dE = 1 * q.keV energies = np.arange(5, 30, dE.magnitude) * q.keV cp = make_triangle(n=16) * 1e-1 tr = Trajectory(cp, velocity=10 * q.um / q.s, pixel_size=ps) bm = BendingMagnet(2.5 * q.GeV, 100 * q.mA, 1.5 * q.T, 30 * q.m, dE, (200, 800) * q.um, ps, tr) # Flat at time = 0 flat_0 = (abs(bm.transfer((512, 256), ps, energies[0], t=0 * q.s)) ** 2).real.get() # Flat at half the time flat_1 = (abs(bm.transfer((512, 256), ps, energies[0], t=tr.time / 2)) ** 2).real.get() plt.subplot(121) plt.imshow(flat_0) f = plt.subplot(122) plt.imshow(flat_1) plt.show()
def main(): parser = get_default_parser(__doc__) subparsers = parser.add_subparsers(help='sub-command help') manual = subparsers.add_parser('manual', help='Manual positioning via simple transformations') trajectory = subparsers.add_parser('trajectory', help='Automatic positioning via trajectories') subtrajectories = subparsers.add_parser('subtrajectories', help='Automatic positioning with ' 'local sub-body trajectories') manual.set_defaults(_func=make_manual_sequence) trajectory.set_defaults(_func=make_trajectory_sequence) subtrajectories.add_argument('--t', type=float, help='Time at which to compute the projection normalized to ' '[0, 1], if not specified, complete sequence is shown') subtrajectories.set_defaults(_func=make_complex_trajectory_sequence) args = parser.parse_args() syris.init(device_index=0) # Set constants args.n = 512 args.shape = (args.n, args.n) args.ps = 1 * q.um args._func(args)
def main(): args = parse_args() syris.init() # Propagate to 20 cm d = 20 * q.cm # Compute grid n_camera = 256 n = n_camera * args.supersampling shape = (n, n) material = get_material('pmma_5_30_kev.mat') energies = material.energies dE = energies[1] - energies[0] # Lens with magnification 5 and numerical aperture 0.25 lens = Lens(5, na=0.25) # Considered visible light wavelengths vis_wavelengths = np.arange(500, 700) * q.nm # Simple camera quantum efficiencies cam_qe = 0.1 * np.ones(len(vis_wavelengths)) camera = Camera(10 * q.um, 0.1, 500, 23, 32, (256, 256), exp_time=args.exposure * q.ms, fps=1 / q.s, quantum_efficiencies=cam_qe, wavelengths=vis_wavelengths, dtype=np.float32) # Scintillator emits visible light into a region given by a Gaussian distribution x = camera.wavelengths.rescale(q.nm).magnitude sigma = fwnm_to_sigma(50) emission = np.exp(-(x - 600) ** 2 / (2 * sigma ** 2)) / (sigma * np.sqrt(2 * np.pi)) # Scintillator 50 um thick, light yield 14 and refractive index 1.84 luag = get_material('luag.mat') scintillator = Scintillator(50 * q.um, luag, 14 * np.ones(len(energies)) / q.keV, energies, emission / q.nm, camera.wavelengths, 1.84) detector = Detector(scintillator, lens, camera) # Pixel size used for propagation ps = detector.pixel_size / args.supersampling fmt = 'Pixel size used for propagation: {}' print fmt.format(ps.rescale(q.um)) fmt = ' Effective detector pixel size: {}' print fmt.format(detector.pixel_size.rescale(q.um)) print ' Field of view: {}'.format(n * ps.rescale(q.um)) # Bending magnet source trajectory = Trajectory([(n / 2, n / 2, 0)] * ps) source = make_topotomo(dE=dE, trajectory=trajectory, pixel_size=ps) sample = make_sphere(n, n / 4. * ps, pixel_size=ps, material=material) # Propagation with a monochromatic plane incident wave coherent = propagate([source, sample], shape, [15 * q.keV], d, ps, t=0 * q.s, detector=detector).get() coherent *= camera.exp_time.simplified.magnitude # Decimate to fit the effective pixel size of the detector system coherent_ld = camera.get_image(coherent, shot_noise=False, amplifier_noise=False) # Propagation which takes into account polychromaticity poly = propagate([source, sample], shape, range(10, 30) * q.keV, d, ps, t=0 * q.s, detector=detector).get() poly *= camera.exp_time.simplified.magnitude poly_ld = camera.get_image(poly, shot_noise=args.noise, amplifier_noise=args.noise) # Compute and show some of the used propagators propagator_10 = get_propagator_psf(n, d, ps, 10 * q.keV) propagator_30 = get_propagator_psf(n, d, ps, 30 * q.keV) show(coherent, title='Coherent Supersampled') show(coherent_ld, title='Coherent Detector') show(propagator_10.real, title='Propagator PSF for 10 keV (real part)') show(propagator_30.real, title='Propagator PSF for 30 keV (real part)') show(poly, title='Polychromatic Supersampled') show(poly_ld, title='Polychromatic Detector') plt.show()
def main(): """Main function.""" args = parse_args() syris.init(loglevel=logging.INFO, device_index=-1) lam = energy_to_wavelength(args.energy * q.keV).simplified w = args.aperture / 2 * q.um # Width of the aperture is 2w, make the aperture half the image size fov = 4 * w ss = args.supersampling d = (w ** 2 / args.fn / lam).simplified ns, ps = compute_propagation_sampling(lam, d, fov, fresnel=True) # Convolution outlier ns *= 2 ps /= ss fmt = 'n sampling: {}, ps: {}, FOV: {}, propagation distance: {}' LOG.info(fmt.format(ns, np.round(ps.rescale(q.nm), 2), fov, np.round(d.rescale(q.cm), 2))) res_a = propagate_analytically(ns * ss, w, ps, d, lam) # Power of two for FFT n = int(2 ** np.ceil(np.log2(ns))) # Supersampling of the pixel size requires supersampling^2 more data points because we enlarge # the FOV by changing the diffraction angle via changing the pixel size and this enlarged FOV is # then sampled by supersampling-smaller pixel size n_proper = n * ss ** 2 numerical_results = {} for divisor in args.numerical_divisors: if np.modf(np.log2(divisor))[0] != 0: raise ValueError('All divisors must be power of two') n_current = n_proper / divisor if n_current < n * ss: raise ValueError('divisor too large, maximum is {}'.format(ss)) numerical_results[n_current] = propagate_numerically(n_current, w, ps, d, lam) x_data = np.linspace(-2 * w.magnitude, 2 * w.magnitude, res_a.shape[0]) aperture = np.zeros(res_a.shape[1]) aperture[res_a.shape[1] / 4:3 * res_a.shape[1] / 4] = res_a[n / 4 / ss].max() if args.txt_output: txt_data = [x_data, aperture, res_a[n / 4 / ss]] txt_header = 'x\taperture\tanalytical' plt.figure() plt.plot(x_data, aperture, label='Aperture') for n_pixels, num_result in numerical_results.items(): fraction = n_pixels / float(n_proper) if args.txt_output: txt_header += '\t{}'.format(fraction) txt_data.append(num_result[n / 4 / ss]) plt.plot(x_data, num_result[n / 4 / ss], '--', label='Numerical {}'.format(fraction)) LOG.info('MSE: {}'.format(np.mean((num_result - res_a) ** 2))) plt.plot(x_data, res_a[n / 4 / ss], '-.', label='Analytical') plt.title('Analytical vs. Numerical Diffraction Pattern') plt.xlabel(r'$\mu m$') plt.ylabel(r'$I$') plt.legend(loc='best') plt.grid() if args.txt_output: txt_data = np.array(txt_data).T np.savetxt(args.txt_output, txt_data, fmt='%g', delimiter='\t', header=txt_header) plt.show()