plt.yticks([])

# Record range of scatterer data

x_range = scatterers[:, 0].min(), scatterers[:, 0].max()
y_range = scatterers[:, 1].min(), scatterers[:, 1].max()
z_range = scatterers[:, 2].min(), scatterers[:, 2].max()
a_range = scatterers[:, 3].min(), scatterers[:, 3].max()

# Set scatterers

sim.clear_fixed_scatterers()  # Make this cell idempotent

data = scatterers

sim.add_fixed_scatterers(data)

# Set the beam profile

sigma_lateral = 1e-3
sigma_elevational = 1e-3
sim.set_analytical_beam_profile(sigma_lateral, sigma_elevational)

# Simulate all scanlines

decimation = 1
sim.set_parameter('radial_decimation', str(decimation))
sim.set_parameter('use_elev_hack', 'off')
iq_lines = sim.simulate_lines()
print(iq_lines.shape)
Ejemplo n.º 2
0
def do_simulation(args):
    if args.use_gpu:
        sim = RfSimulator("gpu")
        sim.set_parameter("gpu_device", "%d" % args.device_no)
        gpu_name = sim.get_parameter("cur_device_name")
        print "Using device %d: %s" % (args.device_no, gpu_name)
    else:
        sim = RfSimulator("cpu")

    sim.set_parameter("verbose", "0")

    with h5py.File(args.h5_file, "r") as f:
        scatterers_data = f["data"][()]
    sim.add_fixed_scatterers(scatterers_data)
    print "The number of scatterers is %d" % scatterers_data.shape[0]

    # configure simulation parameters
    sim.set_parameter("sound_speed", "1540.0")
    sim.set_parameter("radial_decimation", "10")
    sim.set_parameter("phase_delay", "on")
    sim.set_parameter("noise_amplitude", "%f" % args.noise_ampl)

    # configure the RF excitation
    fs = 80e6
    ts = 1.0 / fs
    fc = 5.0e6
    tc = 1.0 / fc
    t_vector = np.arange(-16 * tc, 16 * tc, ts)
    bw = 0.3
    samples = np.array(gausspulse(t_vector, bw=bw, fc=fc), dtype="float32")
    center_index = int(len(t_vector) / 2)
    sim.set_excitation(samples, center_index, fs, fc)

    # define the scan sequence
    origins = np.zeros((args.num_lines, 3), dtype="float32")
    origins[:, 0] = np.linspace(args.x0, args.x1, args.num_lines)
    x_axis = np.array([1.0, 0.0, 0.0])
    z_axis = np.array([0.0, 0.0, 1.0])
    directions = np.array(np.tile(z_axis, (args.num_lines, 1)),
                          dtype="float32")
    length = 0.06
    lateral_dirs = np.array(np.tile(x_axis, (args.num_lines, 1)),
                            dtype="float32")
    timestamps = np.zeros((args.num_lines, ), dtype="float32")
    sim.set_scan_sequence(origins, directions, length, lateral_dirs,
                          timestamps)

    # configure the beam profile
    sim.set_analytical_beam_profile(1e-3, 1e-3)

    frame_sim_times = []
    for frame_no in range(args.num_frames):
        start_time = time()
        iq_lines = sim.simulate_lines()
        frame_sim_times.append(time() - start_time)

    if args.save_simdata_file != "":
        with h5py.File(args.save_simdata_file, "w") as f:
            f["sim_data_real"] = np.array(np.real(iq_lines), dtype="float32")
            f["sim_data_imag"] = np.array(np.imag(iq_lines), dtype="float32")
        print "Simulation output written to %s" % args.save_simdata_file

    print "Simulation time: %f +- %f s  (N=%d)" % (
        np.mean(frame_sim_times), np.std(frame_sim_times), args.num_frames)

    if args.pdf_file != "" and not args.visualize:
        import matplotlib as mpl
        mpl.use("Agg")
    if args.pdf_file != "" or args.visualize:
        import matplotlib.pyplot as plt
        num_samples, num_lines = iq_lines.shape
        plt.figure(1, figsize=(18, 9))
        plt.subplot(1, 2, 1)
        plt.plot(np.real(iq_lines[:, num_lines / 2]))
        plt.title("Middle RF line")
        plt.subplot(1, 2, 2)
        plt.imshow(np.real(abs(iq_lines)),
                   aspect="auto",
                   interpolation="nearest")
        if args.pdf_file != "":
            plt.savefig(args.pdf_file)
            print "Image written to disk."
    if args.visualize:
        plt.show()
Ejemplo n.º 3
0
    parser.add_argument("--x1", help="Right scan width", type=float, default=1e-2)
    parser.add_argument("--num_lines", type=int, default=16)
    parser.add_argument("--device_no", help="GPU device no to use", type=int, default=0)
    parser.add_argument("--line_length", help="Length of scanline", type=float, default=0.12)
    args = parser.parse_args()

    sim_cpu = RfSimulator("cpu")
    sim_gpu = RfSimulator("gpu")
    sim_gpu.set_parameter("gpu_device", "%d"%args.device_no)
    
    with h5py.File(args.h5_file, "r") as f:
        # load the fixed dataset if exists
        if "data" in f:
            scatterers_data = f["data"].value
            print("Configuring %d fixed scatterers" % scatterers_data.shape[0])
            sim_cpu.add_fixed_scatterers(scatterers_data)
            sim_gpu.add_fixed_scatterers(scatterers_data)
        
        # load the spline dataset if exists
        if "spline_degree" in f:
            amplitudes     = f["amplitudes"].value
            control_points = f["control_points"].value
            knot_vector    = f["knot_vector"].value    
            spline_degree  = f["spline_degree"].value
            print("Configuring %d spline scatterers" % control_points.shape[0])
            sim_cpu.add_spline_scatterers(spline_degree, knot_vector, control_points, amplitudes)
            sim_gpu.add_spline_scatterers(spline_degree, knot_vector, control_points, amplitudes)
    
    # configure simulation parameters
    sim_cpu.set_parameter("verbose", "0");            sim_gpu.set_parameter("verbose", "0")
    sim_cpu.set_parameter("sound_speed", "1540.0");   sim_gpu.set_parameter("sound_speed", "1540.0")
Ejemplo n.º 4
0
def do_simulation(args):
    if args.use_gpu:
        sim = RfSimulator("gpu")
        sim.set_parameter("gpu_device", "%d"%args.device_no)
        gpu_name = sim.get_parameter("cur_device_name")
        print "Using device %d: %s" % (args.device_no, gpu_name)
    else:
        sim = RfSimulator("cpu")

    sim.set_parameter("verbose", "0")

    with h5py.File(args.h5_file, "r") as f:
        scatterers_data = f["data"][()]
    sim.add_fixed_scatterers(scatterers_data)
    print "The number of scatterers is %d" % scatterers_data.shape[0]

    # configure simulation parameters
    sim.set_parameter("sound_speed", "1540.0")
    sim.set_parameter("radial_decimation", "10")
    sim.set_parameter("phase_delay", "on")
    sim.set_parameter("noise_amplitude", "%f" % args.noise_ampl)

    # configure the RF excitation
    fs = 80e6
    ts = 1.0/fs
    fc = 5.0e6
    tc = 1.0/fc
    t_vector = np.arange(-16*tc, 16*tc, ts)
    bw = 0.3
    samples = np.array(gausspulse(t_vector, bw=bw, fc=fc), dtype="float32")
    center_index = int(len(t_vector)/2) 
    sim.set_excitation(samples, center_index, fs, fc)

    # configure the beam profile
    sim.set_analytical_beam_profile(1e-3, 1e-3)

    for i, y in enumerate(np.linspace(-0.005, 0.005, 100)):
        print(f"Simulating frame {i}")
        # define the scan sequence
        origins = np.zeros((args.num_lines, 3), dtype="float32")
        origins[:,1] = y
        origins[:,0] = np.linspace(args.x0, args.x1, args.num_lines)
        x_axis = np.array([1.0, 0.0, 0.0])
        z_axis = np.array([0.0, 0.0, 1.0])
        directions = np.array(np.tile(z_axis, (args.num_lines, 1)), dtype="float32")
        length = 0.06
        lateral_dirs = np.array(np.tile(x_axis, (args.num_lines, 1)), dtype="float32")
        timestamps = np.zeros((args.num_lines,), dtype="float32")
        sim.set_scan_sequence(origins, directions, length, lateral_dirs, timestamps)

        iq_lines = sim.simulate_lines()
        bmode = np.array(abs(iq_lines), dtype="float32")
        gain = 1
        dyn_range = 40
        normalize_factor = np.max(bmode.flatten())
        bmode = 20*np.log10(gain*bmode/normalize_factor)
        bmode = 255.0*(bmode+dyn_range)/dyn_range
        # clamp to [0, 255]
        bmode[bmode < 0]     = 0.0
        bmode[bmode > 255.0] = 255.0

        fig = plt.figure(frameon=False)
        fig.set_size_inches(2*bmode.shape[1], bmode.shape[0])
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        fig.add_axes(ax)
        ax.imshow(np.real(abs(iq_lines)), aspect="auto", cmap=plt.get_cmap("gray"))
        plt.savefig(f"sweep_{i:02d}.png", dpi=1)
        plt.close(fig)
Ejemplo n.º 5
0
 plt.figure()
 plt.ion()
 plt.show()
 
 sim_times = []
 sim_nums  = []
 for num_scatterers in all_nums:
     
     # configure with random scatterers
     data = np.empty((num_scatterers, 4), dtype="float32")
     data[:, 0] = np.random.uniform(low=args.x0, high=args.x1, size=(num_scatterers,))
     data[:, 1] = np.random.uniform(low=args.x0, high=args.x1, size=(num_scatterers,))
     data[:, 2] = np.random.uniform(low=0.0, high=args.line_length+1e-2, size=(num_scatterers,))
     data[:, 3] = np.random.uniform(low=-1.0, high=1.0, size=(num_scatterers,))
     sim.clear_fixed_scatterers()
     sim.add_fixed_scatterers(data)
     
     # do the simulation
     start_time = time()
     iq_lines = sim.simulate_lines()
     end_time = time()
     elapsed_time = end_time-start_time
     print "Simulation took %f sec @ %d scatterers." % (elapsed_time, num_scatterers)
     
     # store time per IQ-line
     sim_times.append(elapsed_time/args.num_lines)
     sim_nums.append(num_scatterers)
     
     plt.clf()
     plt.plot(sim_nums, sim_times)
     plt.xlabel("Number of scatterers")
Ejemplo n.º 6
0
def do_simulation(args):
    if args.use_gpu:
        sim = RfSimulator("gpu")
        sim.set_parameter("gpu_device", "%d"%args.device_no)
        gpu_name = sim.get_parameter("cur_device_name")
        print("Using device %d: %s" % (args.device_no, gpu_name))
    else:
        sim = RfSimulator("cpu")

    sim.set_parameter("verbose", "0")

    with h5py.File(args.h5_file, "r") as f:
        scatterers_data = f["data"].value # TODO: inspect type
    sim.add_fixed_scatterers(scatterers_data)
    print("The number of scatterers is %d" % scatterers_data.shape[0])

    # configure simulation parameters
    sim.set_parameter("sound_speed", "1540.0")
    sim.set_parameter("radial_decimation", "10")
    sim.set_parameter("phase_delay", "on")
    sim.set_parameter("noise_amplitude", "%f" % args.noise_ampl)

    # configure the RF excitation
    fs = 80e6
    ts = 1.0/fs
    fc = 5.0e6
    tc = 1.0/fc
    t_vector = np.arange(-16*tc, 16*tc, ts)
    bw = 0.3
    samples = np.array(gausspulse(t_vector, bw=bw, fc=fc), dtype="float32")
    center_index = int(len(t_vector)/2)
    sim.set_excitation(samples, center_index, fs, fc)

    # define the scan sequence
    origins = np.zeros((args.num_lines, 3), dtype="float32")
    origins[:,0] = np.linspace(args.x0, args.x1, args.num_lines)
    x_axis = np.array([1.0, 0.0, 0.0])
    z_axis = np.array([0.0, 0.0, 1.0])
    directions = np.array(np.tile(z_axis, (args.num_lines, 1)), dtype="float32")
    length = 0.06
    lateral_dirs = np.array(np.tile(x_axis, (args.num_lines, 1)), dtype="float32")
    timestamps = np.zeros((args.num_lines,), dtype="float32")
    sim.set_scan_sequence(origins, directions, length, lateral_dirs, timestamps)

    # configure the beam profile
    sim.set_analytical_beam_profile(1e-3, 1e-3)

    frame_sim_times = []
    for frame_no in range(args.num_frames):
        start_time = time()
        iq_lines = sim.simulate_lines()
        frame_sim_times.append(time()-start_time)

    if args.save_simdata_file != "":
        with h5py.File(args.save_simdata_file, "w") as f:
            f["sim_data_real"] = np.array(np.real(iq_lines), dtype="float32")
            f["sim_data_imag"] = np.array(np.imag(iq_lines), dtype="float32")
        print("Simulation output written to %s" % args.save_simdata_file)

    print("Simulation time: %f +- %f s  (N=%d)" % (np.mean(frame_sim_times), np.std(frame_sim_times), args.num_frames))

    if args.pdf_file != "" and not args.visualize:
        import matplotlib as mpl
        mpl.use("Agg")
    if args.pdf_file != "" or args.visualize:
        num_samples, num_lines = iq_lines.shape

        center_data = abs (iq_lines[:, num_lines//2].real)
        data = abs (iq_lines)
        # data = 20 * np.log10(1e-2 + data / data.mean ())

        import matplotlib.pyplot as plt

        print ('iq_lines.shape = (num_samples: {}, num_lines: {})'.format (num_samples, num_lines))
        fig = plt.figure(1, figsize=(24, 12))
        # fig = plt.figure(1, figsize=(9, 6))
        ax = plt.subplot(1,2,1)
        plt.plot(center_data, color=(153/255,102/255,204/255))
        plt.xlabel ('Depth', fontsize=14, labelpad=15)
        plt.ylabel ('Amplitude', fontsize=14, labelpad=15)
        plt.yticks ([])
        plt.grid ()
        plt.title ('Middle RF-Line', fontsize=16, pad=15)

        for side in ['top', 'right', 'left']:
            ax.spines[side].set_visible (False)

        ax = plt.subplot(1,2,2)
        image = plt.imshow (data, cmap='gray', aspect=2, interpolation="nearest")
        # cbar = fig.colorbar (image)
        # cbar.set_label ('  (dB)', fontsize=12)
        plt.xlabel ('Width', fontsize=14, labelpad=15)
        plt.ylabel ('Depth', fontsize=14, labelpad=15)
        from os import path
        name = path.basename (args.h5_file).split ('.')[0].replace ('_', ' ').title ()
        plt.title ('Simulated "{}"'.format (name), fontsize=16, pad=15)
        plt.grid ()
        plt.tick_params (axis='both', which='both', bottom=True, top=False,
                        labelbottom=True, left=True, right=False, labelleft=True)
        # cbar.ax.tick_params (axis='y', which='both', bottom=False, top=False,
                        # labelbottom=False, left=False, right=False, labelright=True)

        # for side in ['top', 'right', 'bottom', 'left']:
            # cbar.ax.spines[side].set_visible (False)

        for side in ['top', 'right', 'bottom', 'left']:
            ax.spines[side].set_visible (False)

        # plt.xticks (tuple (np.arange (0, num_lines, 50)) + (num_lines,))

        for side in ['bottom', 'left']:
            ax.spines[side].set_position(('outward', 1))


        if args.pdf_file != "":
            plt.savefig(args.pdf_file)
            print("Image written to disk.")

    if args.visualize:
        plt.show()
Ejemplo n.º 7
0
def do_simulation(args):
    if args.use_gpu:
        sim = RfSimulator("gpu")
        sim.set_parameter("gpu_device", "%d"%args.device_no)
        gpu_name = sim.get_parameter("cur_device_name")
        print "Using device %d: %s" % (args.device_no, gpu_name)
    else:
        sim = RfSimulator("cpu")

    sim.set_parameter("verbose", "0")

    with h5py.File(args.h5_file, "r") as f:
        scatterers_data = f["data"].value
    sim.add_fixed_scatterers(scatterers_data)
    print "The number of scatterers is %d" % scatterers_data.shape[0]

    # configure simulation parameters
    sim.set_parameter("sound_speed", "1540.0")
    sim.set_parameter("radial_decimation", "10")
    sim.set_parameter("phase_delay", "on")
    sim.set_parameter("noise_amplitude", "%f" % args.noise_ampl)

    # configure the RF excitation
    fs = 80e6
    ts = 1.0/fs
    fc = 5.0e6
    tc = 1.0/fc
    t_vector = np.arange(-16*tc, 16*tc, ts)
    bw = 0.3
    samples = np.array(gausspulse(t_vector, bw=bw, fc=fc), dtype="float32")
    center_index = int(len(t_vector)/2) 
    sim.set_excitation(samples, center_index, fs, fc)

    # define the scan sequence
    origins = np.zeros((args.num_lines, 3), dtype="float32")
    origins[:,0] = np.linspace(args.x0, args.x1, args.num_lines)
    x_axis = np.array([1.0, 0.0, 0.0])
    z_axis = np.array([0.0, 0.0, 1.0])
    directions = np.array(np.tile(z_axis, (args.num_lines, 1)), dtype="float32")
    length = 0.06
    lateral_dirs = np.array(np.tile(x_axis, (args.num_lines, 1)), dtype="float32")
    timestamps = np.zeros((args.num_lines,), dtype="float32")
    sim.set_scan_sequence(origins, directions, length, lateral_dirs, timestamps)

    # configure the beam profile
    sim.set_analytical_beam_profile(1e-3, 1e-3)

    frame_sim_times = []
    for frame_no in range(args.num_frames):
        start_time = time()
        iq_lines = sim.simulate_lines()
        frame_sim_times.append(time()-start_time)
        
    if args.save_simdata_file != "":
        with h5py.File(args.save_simdata_file, "w") as f:
            f["sim_data_real"] = np.array(np.real(iq_lines), dtype="float32")
            f["sim_data_imag"] = np.array(np.imag(iq_lines), dtype="float32")
        print "Simulation output written to %s" % args.save_simdata_file
        
    print "Simulation time: %f +- %f s  (N=%d)" % (np.mean(frame_sim_times), np.std(frame_sim_times), args.num_frames)    

    if args.pdf_file != "" and not args.visualize:
        import matplotlib as mpl
        mpl.use("Agg")
    if args.pdf_file != "" or args.visualize:
        import matplotlib.pyplot as plt
        num_samples, num_lines = iq_lines.shape
        plt.figure(1, figsize=(18,9))
        plt.subplot(1,2,1)
        plt.plot(np.real(iq_lines[:, num_lines/2]))
        plt.title("Middle RF line")
        plt.subplot(1,2,2)
        plt.imshow(np.real(abs(iq_lines)), aspect="auto", interpolation="nearest")
        if args.pdf_file != "":
            plt.savefig(args.pdf_file)
            print "Image written to disk."
    if args.visualize:
        plt.show()