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) # Reshaping madness. # Key to tip: The last axis gets read the fastest, the first axis the fastest. shape = no_sub_y, N_elements, no_sub_x, -1 reshaped = iq_lines.T.reshape(shape) data = reshaped.sum(axis=(0, 2)).T / (no_sub_y * no_sub_x)
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()
sim_fixed.set_excitation(samples, center_index, args.fs, demod_freq) sim_spline.set_excitation(samples, center_index, args.fs, demod_freq) # create big scan sequence with all M-mode beams (for the spline algorithm) origins = np.empty((args.num_beams_total, 3), dtype="float32") directions = np.empty((args.num_beams_total, 3), dtype="float32") lateral_dirs = np.empty((args.num_beams_total, 3), dtype="float32") y_axis = np.array([0.0, 1.0, 0.0]) lateral_dir = np.cross(y_axis, direction) for beam_no in range(args.num_beams_total): origins[beam_no, :] = origin directions[beam_no, :] = direction lateral_dirs[beam_no, :] = lateral_dir # set the beam profile sim_fixed.set_analytical_beam_profile(args.sigma_lateral, args.sigma_elevational) sim_spline.set_analytical_beam_profile(args.sigma_lateral, args.sigma_elevational) # configure spline simulator sim_spline.add_spline_scatterers(int(spline_degree), knot_vector, control_points, amplitudes) sim_spline.set_scan_sequence(origins, directions, args.line_length, lateral_dirs, timestamps) # fixed iq_lines_fixed, sim_time_fixed = run_fixed_simulation( sim_fixed, origin, direction, lateral_dir, args.line_length, timestamps, fixed_scatterers) if args.only_save_png: import matplotlib
sim.set_excitation(samples, center_index, args.fs, f_demod) # configure the beam profile if args.lut_file != "": with h5py.File(args.lut_file, "r") as lut_f: samples = np.array(lut_f["beam_profile"].value, dtype="float32") r_ext = lut_f["rad_extent"].value e_ext = lut_f["ele_extent"].value l_ext = lut_f["lat_extent"].value sim.set_lut_beam_profile(float(r_ext[0]), float(r_ext[1]),\ float(l_ext[0]), float(l_ext[1]),\ float(e_ext[0]), float(e_ext[1]), samples) res_buffer.add_msg("using lookup-table: %s" % args.lut_file) else: sim.set_analytical_beam_profile(1e-3, 1e-3) res_buffer.add_msg("using analytic beam profile") res_buffer.add_msg("CASE 1: Linear scan of plaque phantom") num_scatterers = reconfigure_scatterers( sim, os.path.join(args.phantom_folder, "carotid_plaque.h5")) assert num_scatterers == sim.get_total_num_scatterers() configure_linear_scan(sim, 0.0, 1.0, args.num_lines) rep_times = simulate_with_timing( sim, args.num_rep, "benchmark_carotid_plaque_%s.png" % sim_type) ns_mean, ns_std = ns_per_scatterer(rep_times, num_scatterers, args.num_lines) res_buffer.add_msg(" Number of scatterers: %d" % num_scatterers) res_buffer.add_msg( " %3.3f +- %3.3f nanosec per scatterer per line [N=%d]" % (ns_mean, ns_std, len(rep_times)))
sim_fixed.set_excitation(samples, center_index, args.fs, demod_freq) sim_spline.set_excitation(samples, center_index, args.fs, demod_freq) # create big scan sequence with all M-mode beams (for the spline algorithm) origins = np.empty((args.num_beams_total, 3), dtype="float32") directions = np.empty((args.num_beams_total, 3), dtype="float32") lateral_dirs = np.empty((args.num_beams_total, 3), dtype="float32") y_axis = np.array([0.0, 1.0, 0.0]) lateral_dir = np.cross(y_axis, direction) for beam_no in range(args.num_beams_total): origins[beam_no, :] = origin directions[beam_no, :] = direction lateral_dirs[beam_no, :] = lateral_dir # set the beam profile sim_fixed.set_analytical_beam_profile(args.sigma_lateral, args.sigma_elevational) sim_spline.set_analytical_beam_profile(args.sigma_lateral, args.sigma_elevational) # configure spline simulator sim_spline.add_spline_scatterers(spline_degree, knot_vector, control_points, amplitudes) sim_spline.set_scan_sequence(origins, directions, args.line_length, lateral_dirs, timestamps) # fixed iq_lines_fixed, sim_time_fixed = run_fixed_simulation(sim_fixed, origin, direction, lateral_dir, args.line_length, timestamps, fixed_scatterers) if args.only_save_png: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt plt.figure(1)
sim_cpu.set_excitation(samples, center_index, fs, fc) sim_gpu.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") lateral_dirs = np.array(np.tile(x_axis, (args.num_lines, 1)), dtype="float32") timestamps = np.zeros((args.num_lines,), dtype="float32") sim_cpu.set_scan_sequence(origins, directions, args.line_length, lateral_dirs, timestamps) sim_gpu.set_scan_sequence(origins, directions, args.line_length, lateral_dirs, timestamps) # configure the beam profile sim_cpu.set_analytical_beam_profile(1e-3, 1e-3) sim_gpu.set_analytical_beam_profile(1e-3, 1e-3) print("Simulating on CPU...") rf_lines_cpu = sim_cpu.simulate_lines() print("Simulating on GPU...") rf_lines_gpu = sim_gpu.simulate_lines() num_samples, num_lines = rf_lines_cpu.shape plt.figure() plt.ion() plt.show() for line_no in range(num_lines): plt.clf() plt.subplot(2,2,1) real_cpu = np.real(rf_lines_cpu[:, line_no])
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)
plt.show() # Create big scan sequence origins = np.empty((args.num_beams, 3), dtype="float32") directions = np.empty((args.num_beams, 3), dtype="float32") lateral_dirs = np.empty((args.num_beams, 3), dtype="float32") for beam_no in range(args.num_beams): origins[beam_no, :] = [0.0, 0.0, 0.0] directions[beam_no, :] = [0.0, 0.0, 1.0] lateral_dirs[beam_no, :] = [1.0, 0.0, 0.0] timestamps = np.array(range(args.num_beams), dtype="float32")/args.prf sim.set_scan_sequence(origins, directions, args.line_length, lateral_dirs, timestamps) # Set the beam profile sim.set_analytical_beam_profile(args.sigma_lateral, args.sigma_elevational) # Do the simulation print "Simulating IQ data" start_time = time() iq_lines = sim.simulate_lines() end_time = time() print "Simulation took %f sec" % (end_time-start_time) # get slow-time samples num_samples = iq_lines.shape[0] sample_idx = int(args.sample_pos*(num_samples-1)) print "Sample index is %d" % sample_idx slowtime_samples = iq_lines[sample_idx, :]
f_demod = args.fc sim.set_excitation(samples, center_index, args.fs, f_demod) # configure the beam profile if args.lut_file != "": with h5py.File(args.lut_file, "r") as lut_f: samples = np.array(lut_f["beam_profile"].value, dtype="float32") r_ext = lut_f["rad_extent"].value e_ext = lut_f["ele_extent"].value l_ext = lut_f["lat_extent"].value sim.set_lut_beam_profile(float(r_ext[0]), float(r_ext[1]),\ float(l_ext[0]), float(l_ext[1]),\ float(e_ext[0]), float(e_ext[1]), samples) res_buffer.add_msg("using lookup-table: %s" % args.lut_file) else: sim.set_analytical_beam_profile(1e-3, 1e-3) res_buffer.add_msg("using analytic beam profile") res_buffer.add_msg("CASE 1: Linear scan of plaque phantom") num_scatterers = reconfigure_scatterers(sim, os.path.join(args.phantom_folder, "carotid_plaque.h5")) assert num_scatterers==sim.get_total_num_scatterers() configure_linear_scan(sim, 0.0, 1.0, args.num_lines) rep_times = simulate_with_timing(sim, args.num_rep, "benchmark_carotid_plaque_%s.png"%sim_type) ns_mean, ns_std = ns_per_scatterer(rep_times, num_scatterers, args.num_lines) res_buffer.add_msg(" Number of scatterers: %d" % num_scatterers) res_buffer.add_msg(" %3.3f +- %3.3f nanosec per scatterer per line [N=%d]" % (ns_mean, ns_std, len(rep_times))) res_buffer.add_msg(" (%s)" % str(rep_times)) res_buffer.add_msg("CASE 2: Tissue with flow phantom") num_scatterers = reconfigure_scatterers(sim, os.path.join(args.phantom_folder, "tissue_with_parabolic_flow.h5")) assert num_scatterers==sim.get_total_num_scatterers()
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()
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()