# create beam times (w/wrapping)
 cur_time = args.start_time
 timestamps = []
 for i in range(args.num_beams_total):
     timestamps.append(cur_time)
     cur_time += prt
     if cur_time >= args.end_time: cur_time = args.start_time
 timestamps = np.array(timestamps, dtype="float32")
     
 # precompute fixed-scatterer datasets
 fixed_scatterers = create_fixed_datasets(args, control_points, amplitudes, spline_degree, knot_vector, timestamps)
 
 # create two simulator instances - one for spline-only and one fixed-only
 sim_fixed  = RfSimulator("gpu")
 sim_spline = RfSimulator("gpu")
 sim_fixed.set_parameter("verbose", "0");            sim_spline.set_parameter("verbose", "0")
 sim_fixed.set_print_debug(False);                   sim_spline.set_print_debug(False)
 sim_fixed.set_parameter("sound_speed", "%f" % c0);  sim_spline.set_parameter("sound_speed", "%f" % c0)
 sim_fixed.set_parameter("phase_delay", "on");       sim_spline.set_parameter("phase_delay", "on")
 sim_fixed.set_parameter("radial_decimation", "5");  sim_spline.set_parameter("radial_decimation", "5")
 
 num_gpus = int(sim_fixed.get_parameter("num_cuda_devices"))
 print "System has %d CUDA devices" % num_gpus
 sim_fixed.set_parameter("gpu_device", "%d" % args.gpu_device_no)
 sim_spline.set_parameter("gpu_device", "%d" % args.gpu_device_no)
 print "Fixed simulator uses %s" % sim_fixed.get_parameter("cur_device_name")
 print "Spline simulator uses %s" % sim_spline.get_parameter("cur_device_name")
 
 # define excitation signal
 t_vector = np.arange(-16/args.fc, 16/args.fc, 1.0/args.fs)
 samples = np.array(gausspulse(t_vector, bw=args.bw, fc=args.fc), dtype="float32")
Пример #2
0
    Compare GPU and CPU for a linear scan in the XZ plane
"""

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("h5_file", help="Hdf5 file with scatterers")
    parser.add_argument("--x0", help="Left scan width", type=float, default=-1e-2)
    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
Пример #3
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)
Пример #4
0
# Linear scan with three scatterers.
# Using a Gaussian analytic beam profile.
import sys
sys.path.append(".")
from pyrfsim import RfSimulator
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.signal import gausspulse
import numpy as np

# Create and configure CPU simulator
device = 'cpu'
device = 'gpu'

sim = RfSimulator(device)
sim.set_parameter("verbose", "1")
sim.set_print_debug(True)

# Set general simulation parameters
sim.set_parameter("sound_speed", "1540.0")
if device == 'cpu': sim.set_parameter("num_cpu_cores", "all")
sim.set_parameter("radial_decimation", "20")

# Set scatterers
num_scatterers = 16
scatterers_data = np.zeros((num_scatterers, 4), dtype="float32")
scatterers_data[:, 0] = np.linspace(-.02, 0.02, num_scatterers)
scatterers_data[:, 2] = np.linspace(0.01, 0.16, num_scatterers)
scatterers_data[:, 3] = np.ones((num_scatterers, ))
# scatterers_data[:,3] = np.arange (1, num_scatterers + 1)
sim.add_fixed_scatterers(scatterers_data)
width = lambd  #  Width of element
height = 5 / 1000  #  Height of element [m]
kerf = 0.05 / 1000  #  Kerf (gap between elements) [m]
pitch = kerf + width  #  Pitch (center-to-center distance between elements) [m]
N_elements = 192  #  Number of physical elements
no_sub_x = 1  #  Number of sub-divisions in x-direction of elements
no_sub_y = 10  #  Number of sub-divisions in y-direction of elements

# Create and configure GPU simulator

from pyrfsim import RfSimulator

sim = RfSimulator('gpu')
sim.set_print_debug(True)

sim.set_parameter('sound_speed', str(c))
sim.set_parameter('radial_decimation',
                  '1')  # depth-direction downsampling factor
sim.set_parameter('phase_delay', 'on')  # improves subsample accuracy
sim.set_parameter('use_elev_hack', 'off')


def subdivide(length, num):
    delta = length * 1 / num
    divisions = np.arange((-num // 2 + 1) * delta, (num // 2 + 1) * delta,
                          delta)

    return divisions


# Arguments very similar to xdc_linear_array in Field II
Пример #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
    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()
Пример #7
0
    parser.add_argument("--sigma_elevational", help="Elevational beamwidth", type=float, default=1e-3)
    parser.add_argument("--use_gpu", help="Perform simulations using the gpu_spline2 algorithm", action="store_true")
    parser.add_argument("--save_pdf", help="Save pdf figures", action="store_true")
    parser.add_argument("--visualize", help="Interactive figures", action="store_true")
    args = parser.parse_args()
    
    c0 = 1540.0
    
    # Create and configure
    if args.use_gpu:
        print "Using GPU"
        sim = RfSimulator("gpu")
    else:
        print "Using CPU"
        sim = RfSimulator("cpu")
        sim.set_parameter("num_cpu_cores", "all")
    sim.set_parameter("verbose", "0")
    sim.set_print_debug(False)
    sim.set_parameter("sound_speed", "%f" % c0)
    sim.set_parameter("radial_decimation", "30")

    # Enable phase-delays for smooth curves
    sim.set_parameter("phase_delay", "on")
    
    # Set spline scatterers
    with h5py.File(args.scatterer_file, "r") as f:
        control_points = np.array(f["control_points"].value, dtype="float32")
        amplitudes     = np.array(f["amplitudes"].value, dtype="float32")
        knot_vector    = np.array(f["knot_vector"].value, dtype="float32")
        spline_degree  = int(f["spline_degree"].value)
        
Пример #8
0
    parser.add_argument("--lut_file",
                        help="Use lookup table beam profile",
                        default="")
    args = parser.parse_args()

    res_buffer = ResultBuffer()

    sim_types = ["gpu"]
    if args.enable_cpu:
        sim_types.append("cpu")

    for sim_type in sim_types:
        sim = RfSimulator(sim_type)
        device_name = ""
        if sim_type == "gpu":
            sim.set_parameter("gpu_device", "%d" % args.device_no)
            device_name = sim.get_parameter("cur_device_name")
        elif sim_type == "cpu":
            sim.set_parameter("num_cpu_cores", "%d" % args.num_cpu_cores)
        res_buffer.add_msg("=== SIMULATION RESULTS WITH %s %s ===" %
                           (sim_type.upper(), device_name))
        sim.set_parameter("verbose", "0")
        sim.set_parameter("sound_speed", "1540.0")
        sim.set_parameter("radial_decimation", "30")
        sim.set_parameter("use_arc_projection", args.arc_proj)
        res_buffer.add_msg("Arc projection: %s" % args.arc_proj)
        sim.set_parameter("phase_delay", args.phase_delay)
        res_buffer.add_msg("Complex phase delay: %s" % args.phase_delay)

        # configure the RF excitation
        ts = 1.0 / args.fs
Пример #9
0
                        action="store_true")
    parser.add_argument("--visualize",
                        help="Interactive figures",
                        action="store_true")
    args = parser.parse_args()

    c0 = 1540.0

    # Create and configure
    if args.use_gpu:
        print "Using GPU"
        sim = RfSimulator("gpu")
    else:
        print "Using CPU"
        sim = RfSimulator("cpu")
        sim.set_parameter("num_cpu_cores", "all")
    sim.set_parameter("verbose", "0")
    sim.set_print_debug(False)
    sim.set_parameter("sound_speed", "%f" % c0)
    sim.set_parameter("radial_decimation", "30")

    # Enable phase-delays for smooth curves
    sim.set_parameter("phase_delay", "on")

    # Set spline scatterers
    with h5py.File(args.scatterer_file, "r") as f:
        control_points = np.array(f["control_points"].value, dtype="float32")
        amplitudes = np.array(f["amplitudes"].value, dtype="float32")
        knot_vector = np.array(f["knot_vector"].value, dtype="float32")
        spline_degree = int(f["spline_degree"].value)
Пример #10
0
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--line_length", help="Length of scanline", type=float, default=0.1)
    parser.add_argument("--fs", help="Sampling frequency [Hz]", type=float, default=50e6)
    parser.add_argument("--fc", help="Pulse center frequency [Hz] (also demod. freq.)", type=float, default=5.0e6)
    parser.add_argument("--bw", help="Pulse fractional bandwidth", type=float, default=0.2)
    parser.add_argument("--sigma_lateral", help="Lateral beamwidth", type=float, default=0.5e-3)
    parser.add_argument("--sigma_elevational", help="Elevational beamwidth", type=float, default=1e-3)
    parser.add_argument("--num_lines", help="Number of IQ lines in scansequence", type=int, default=128)
    parser.add_argument("--x0", help="Scanseq width in meters (left end)", type=float, default=-0.03)
    parser.add_argument("--x1", help="Scanseq width in meters (right end)", type=float, default=0.03)
    args = parser.parse_args()
        
    # create and configure simulator
    sim = RfSimulator("gpu")
    sim.set_parameter("verbose", "0")
    sim.set_print_debug(False)
    sim.set_parameter("sound_speed", "1540.0")
    sim.set_parameter("radial_decimation", "15")
    sim.set_parameter("phase_delay", "on")
        
    # define excitation signal
    t_vector = np.arange(-16/args.fc, 16/args.fc, 1.0/args.fs)
    samples = np.array(gausspulse(t_vector, bw=args.bw, fc=args.fc), dtype="float32")
    center_index = int(len(t_vector)/2) 
    demod_freq = args.fc
    sim.set_excitation(samples, center_index, args.fs, demod_freq)
            
    # create linear scan sequence
    origins      = np.empty((args.num_lines, 3), dtype="float32")
    directions   = np.empty((args.num_lines, 3), dtype="float32")
Пример #11
0
# DEMO 1
# Linear scan with three scatterers.
# Using a Gaussian analytic beam profile.
import sys
sys.path.append(".")
from pyrfsim import RfSimulator
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.signal import gausspulse
import numpy as np

# Create and configure CPU simulator
sim = RfSimulator("cpu")
sim.set_parameter("verbose", "1")
sim.set_print_debug(True)

# Set general simulation parameters
sim.set_parameter("sound_speed", "1540.0")
sim.set_parameter("num_cpu_cores", "all")
sim.set_parameter("radial_decimation", "20")

# Set scatterers
num_scatterers = 16
scatterers_data = np.zeros((num_scatterers, 4), dtype="float32")
scatterers_data[:,2] = np.linspace(0.01, 0.16, num_scatterers)
scatterers_data[:,3] = np.ones((num_scatterers,))
sim.add_fixed_scatterers(scatterers_data)

# Define excitation signal
fs = 50e6
ts = 1.0/fs
Пример #12
0
    parser.add_argument("--phase_delay", choices=["on", "off"], default="on")
    parser.add_argument("--enable_cpu", help="Also time CPU impl (slow)", action="store_true")
    parser.add_argument("--lut_file", help="Use lookup table beam profile", default="")
    args = parser.parse_args()

    res_buffer = ResultBuffer()
    
    sim_types = ["gpu"]
    if args.enable_cpu:
        sim_types.append("cpu")
    
    for sim_type in sim_types:
        sim = RfSimulator(sim_type)
        device_name = ""
        if sim_type == "gpu":
            sim.set_parameter("gpu_device", "%d" % args.device_no)
            device_name = sim.get_parameter("cur_device_name")
        elif sim_type == "cpu":
            sim.set_parameter("num_cpu_cores", "%d" % args.num_cpu_cores)
        res_buffer.add_msg("=== SIMULATION RESULTS WITH %s %s ===" % (sim_type.upper(), device_name))
        sim.set_parameter("verbose", "0")
        sim.set_parameter("sound_speed", "1540.0")
        sim.set_parameter("radial_decimation", "30")
        sim.set_parameter("use_arc_projection", args.arc_proj)
        res_buffer.add_msg("Arc projection: %s" % args.arc_proj)
        sim.set_parameter("phase_delay", args.phase_delay)
        res_buffer.add_msg("Complex phase delay: %s" % args.phase_delay)
            
        # configure the RF excitation
        ts = 1.0/args.fs
        tc = 1.0/args.fc
Пример #13
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()
Пример #14
0
    timestamps = []
    for i in range(args.num_beams_total):
        timestamps.append(cur_time)
        cur_time += prt
        if cur_time >= args.end_time: cur_time = args.start_time
    timestamps = np.array(timestamps, dtype="float32")

    # precompute fixed-scatterer datasets
    fixed_scatterers = create_fixed_datasets(args, control_points, amplitudes,
                                             spline_degree, knot_vector,
                                             timestamps)

    # create two simulator instances - one for spline-only and one fixed-only
    sim_fixed = RfSimulator("gpu")
    sim_spline = RfSimulator("gpu")
    sim_fixed.set_parameter("verbose", "0")
    sim_spline.set_parameter("verbose", "0")
    sim_fixed.set_print_debug(False)
    sim_spline.set_print_debug(False)
    sim_fixed.set_parameter("sound_speed", "%f" % c0)
    sim_spline.set_parameter("sound_speed", "%f" % c0)
    sim_fixed.set_parameter("phase_delay", "on")
    sim_spline.set_parameter("phase_delay", "on")
    sim_fixed.set_parameter("radial_decimation", "5")
    sim_spline.set_parameter("radial_decimation", "5")

    num_gpus = int(sim_fixed.get_parameter("num_cuda_devices"))
    print("System has %d CUDA devices" % num_gpus)
    sim_fixed.set_parameter("gpu_device", "%d" % args.gpu_device_no)
    sim_spline.set_parameter("gpu_device", "%d" % args.gpu_device_no)
    print("Fixed simulator uses %s" %
Пример #15
0
                        default=16,
                        help="Decimation when drawing RF lines")
    parser.add_argument("--device_no",
                        help="GPU device no to use",
                        type=int,
                        default=0)
    parser.add_argument("--no_gpu",
                        action="store_true",
                        help="Use CPU instead of GPU")
    args = parser.parse_args()

if args.no_gpu:
    sim = RfSimulator("cpu")
else:
    sim = RfSimulator("gpu")
    sim.set_parameter("gpu_device", "%d" % args.device_no)

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("phase_delay", "on")
sim.set_parameter("verbose", "0")

# avoid ugly part on top
sim.set_parameter("use_arc_projection", "off")

# use no radial decimation since we want to draw nice
Пример #16
0
    implementations.
"""

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("--num_scatterers", type=int, default=1000000)
    parser.add_argument("--num_lines", type=int, default=192)
    parser.add_argument("--num_frames", help="Each frame is equal, but can be used to test performance", type=int, default=1)
    parser.add_argument("--visualize", help="Visualize the middle RF line", action="store_true")
    parser.add_argument("--save_pdf", help="Save .pdf image", action="store_true")
    parser.add_argument("--device_no", help="GPU device no to use", type=int, default=0)
    parser.add_argument("--store_kernel_debug", help="Store kernel timing info", action="store_true")
    args = parser.parse_args()

sim = RfSimulator("gpu")
sim.set_parameter("gpu_device", "%d"%args.device_no)
sim.set_parameter("radial_decimation", "30")
sim.set_parameter("verbose", "0")
if args.store_kernel_debug:
    sim.set_parameter("store_kernel_details", "on")

# configure scatterers (in a 3D cube)
x0 = -0.04; x1 = 0.04
y0 = -0.04; y1 = 0.04
z0 =  0.02; z1 = 0.10
scatterers_data = np.empty((args.num_scatterers, 4), dtype="float32")
scatterers_data[:,0] = np.random.uniform(low=x0, high=x1, size=(args.num_scatterers,))
scatterers_data[:,1] = np.random.uniform(low=y0, high=y1, size=(args.num_scatterers,))
scatterers_data[:,2] = np.random.uniform(low=z0, high=z1, size=(args.num_scatterers,))
scatterers_data[:,3] = np.random.uniform(low=0.0, high=1.0, size=(args.num_scatterers,))
sim.add_fixed_scatterers(scatterers_data)
Пример #17
0
    c0 = 1540.0
    prt = 1.0 / args.prf
    origin = np.array([0.0, 0.0, -5e-3])  # beam origin

    with h5py.File(args.scatterer_file, "r") as f:
        control_points = f["control_points"].value
        amplitudes = f["amplitudes"].value
        knot_vector = f["knot_vector"].value
        spline_degree = int(f["spline_degree"].value
                            )  # C++ interface expects strictly int type
    num_cs = control_points.shape[1]
    print("Loaded spline phantom with %d control points" % num_cs)

    # create and configure
    sim = RfSimulator("gpu")
    sim.set_parameter("verbose", "0")
    sim.set_print_debug(False)
    sim.set_parameter("sound_speed", "%f" % c0)
    sim.set_parameter("radial_decimation", "%d" % args.rad_decimation)
    sim.set_parameter("phase_delay", "on")

    # define excitation signal
    t_vector = np.arange(-16 / args.fc, 16 / args.fc, 1.0 / args.fs)
    samples = np.array(gausspulse(t_vector, bw=args.bw, fc=args.fc),
                       dtype="float32")
    center_index = int(len(t_vector) / 2)
    demod_freq = args.fc
    sim.set_excitation(samples, center_index, args.fs, demod_freq)

    # configure analytical beam profile
    sim.set_analytical_beam_profile(args.sigma_lateral, args.sigma_elevational)
Пример #18
0
height = 5 / 1000          #  Height of element [m]
kerf = 0.05 / 1000         #  Kerf (gap between elements) [m]
pitch = kerf + width       #  Pitch (center-to-center distance between elements) [m]
N_elements = 192           #  Number of physical elements
no_sub_x = 5               #  Number of sub-divisions in x-direction of elements
no_sub_y = 5              #  Number of sub-divisions in y-direction of elements


# Create and configure GPU simulator

from pyrfsim import RfSimulator

sim = RfSimulator ('gpu')
sim.set_print_debug (True)

sim.set_parameter ('sound_speed', str (c))
sim.set_parameter ('radial_decimation', '1') # depth-direction downsampling factor
sim.set_parameter ('phase_delay', 'on') # improves subsample accuracy
sim.set_parameter ('use_elev_hack', 'off')


def subdivide (length, num):
  delta = length * 1/num
  divisions = np.arange ((-num//2 + 1) * delta, (num//2 + 1) * delta, delta)

  return divisions

# Arguments very similar to xdc_linear_array in Field II
def linear_transducer (N_elements, width, height, kerf, no_sub_x=1, no_sub_y=1, as_array=False):
  '''Calculates the origin positions of the (sub-)elements in a linear array transducer.'''
Пример #19
0
                        help="Number of IQ lines in scansequence",
                        type=int,
                        default=128)
    parser.add_argument("--x0",
                        help="Scanseq width in meters (left end)",
                        type=float,
                        default=-0.03)
    parser.add_argument("--x1",
                        help="Scanseq width in meters (right end)",
                        type=float,
                        default=0.03)
    args = parser.parse_args()

    # create and configure simulator
    sim = RfSimulator("gpu")
    sim.set_parameter("verbose", "0")
    sim.set_print_debug(False)
    sim.set_parameter("sound_speed", "1540.0")
    sim.set_parameter("radial_decimation", "15")
    sim.set_parameter("phase_delay", "on")

    # define excitation signal
    t_vector = np.arange(-16 / args.fc, 16 / args.fc, 1.0 / args.fs)
    samples = np.array(gausspulse(t_vector, bw=args.bw, fc=args.fc),
                       dtype="float32")
    center_index = int(len(t_vector) / 2)
    demod_freq = args.fc
    sim.set_excitation(samples, center_index, args.fs, demod_freq)

    # create linear scan sequence
    origins = np.empty((args.num_lines, 3), dtype="float32")
Пример #20
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()
Пример #21
0
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("--h5_file", help="Hdf5 file with [fixed] scatterers", default="../generated_phantoms/carotid_plaque.h5")
    parser.add_argument("--x0", help="Left scan width", type=float, default=-0.08)
    parser.add_argument("--x1", help="Right scan width", type=float, default=0.076)
    parser.add_argument("--num_lines", type=int, help="Total number of B-mode lines", default=512)
    parser.add_argument("--tx_decimation", type=int, default=16, help="Decimation when drawing RF lines")
    parser.add_argument("--device_no", help="GPU device no to use", type=int, default=0)
    parser.add_argument("--no_gpu", action="store_true", help="Use CPU instead of GPU")
    args = parser.parse_args()

if args.no_gpu:
    sim = RfSimulator("cpu")
else:
    sim = RfSimulator("gpu")
    sim.set_parameter("gpu_device", "%d"%args.device_no)

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("phase_delay", "on")
sim.set_parameter("verbose", "0")

# avoid ugly part on top
sim.set_parameter("use_arc_projection", "off")

# use no radial decimation since we want to draw nice