Of course. Here is a complete and runnable implementation of a Delay-and-Sum (DAS) ultrasound beamformer using CuPy.
This code is self-contained: it defines the beamformer, simulates plausible ultrasound RF data from point scatterers, runs the beamforming on the GPU, and visualizes the resulting B-mode image.
The core of the beamformer is highly vectorized, leveraging CuPy's broadcasting capabilities to perform calculations for all pixels and all transducer elements simultaneously, making it extremely fast.
Key Features:
- Pure CuPy: All core computations are done on the GPU.
- Vectorized: Avoids slow Python loops for pixels and elements.
- Delay-and-Sum (DAS): Implements the most fundamental beamforming algorithm.
- Linear Interpolation: Provides better accuracy than nearest-neighbor sampling.
- Self-Contained Example: Includes data simulation and plotting for immediate use.
- Concise: Well under the 300-line limit.
Prerequisites
You'll need cupy and matplotlib installed.
pip install cupy-cudaXXX # Replace XXX with your CUDA version, e.g., cupy-cuda11x
pip install matplotlib
The Code
import cupy as cp
import numpy as np
import matplotlib.pyplot as plt
import time
def das_beamformer_cupy(rf_data, element_pos, fs, c, grid_x, grid_z):
"""
Performs Delay-and-Sum (DAS) beamforming on the GPU using CuPy.
Args:
rf_data (cp.ndarray): Raw RF data (num_samples, num_elements).
element_pos (cp.ndarray): X-positions of the transducer elements (num_elements,).
fs (float): Sampling frequency in Hz.
c (float): Speed of sound in m/s.
grid_x (cp.ndarray): X-coordinates of the image grid (num_pixels_x,).
grid_z (cp.ndarray): Z-coordinates of the image grid (num_pixels_z,).
Returns:
cp.ndarray: Beamformed image data (num_pixels_z, num_pixels_x).
"""
# Get dimensions
num_samples, num_elements = rf_data.shape
num_pix_z, num_pix_x = grid_z.shape[0], grid_x.shape[0]
# --- Vectorized Calculation on GPU ---
# 1. Create coordinate grids for broadcasting
# px, pz hold the coordinates for every pixel in the image
# ex holds the positions for every element
px, pz = cp.meshgrid(grid_x, grid_z) # (num_pix_z, num_pix_x)
# Reshape for broadcasting against each other:
# px, pz -> (num_pix_z, num_pix_x, 1)
# ex -> (1, 1, num_elements)
px = px[..., cp.newaxis]
pz = pz[..., cp.newaxis]
ex = element_pos[cp.newaxis, cp.newaxis, :]
# 2. Calculate round-trip distance (element -> pixel -> element)
# The result `distances` is a 3D matrix where distances[i, j, k] is the
# distance from pixel (i, j) to element k.
# This is the Pythagorean theorem, broadcast across all pixels and elements.
distances = cp.sqrt((px - ex)**2 + pz**2)
# 3. Calculate time-of-flight and corresponding sample indices
# Factor of 2 for round-trip travel
time_of_flight = 2 * distances / c
sample_indices_float = time_of_flight * fs
# --- Perform Interpolation ---
# We need to sample rf_data at non-integer indices.
# We'll use linear interpolation.
# 4. Get lower and upper sample indices and the fractional part
idx0 = cp.floor(sample_indices_float).astype(cp.int32)
frac = sample_indices_float - idx0
# 5. Get RF data values at surrounding integer indices
# Create an index for elements to align with the 3D grid
element_indices = cp.arange(num_elements)[cp.newaxis, cp.newaxis, :]
# Clip indices to be within the bounds of the rf_data array
idx0 = cp.clip(idx0, 0, num_samples - 2)
idx1 = idx0 + 1
# Fetch the values from rf_data using advanced indexing.
# rf_data[idx0, element_indices] effectively looks up the value for each
# pixel-element pair at the correct time delay.
y0 = rf_data[idx0, element_indices]
y1 = rf_data[idx1, element_indices]
# 6. Perform linear interpolation and sum along the element axis
# This is the "Sum" part of Delay-and-Sum.
interpolated_values = (1.0 - frac) * y0 + frac * y1
beamformed_image = cp.sum(interpolated_values, axis=2)
return beamformed_image
def simulate_rf_data(scatterers, element_pos, fs, c, pulse_freq, num_samples):
"""Simulates RF data from a set of point scatterers."""
num_elements = element_pos.shape[0]
rf_data = cp.zeros((num_samples, num_elements), dtype=cp.float32)
# Define a simple Gaussian-modulated sine pulse (Gabor pulse)
t = cp.arange(num_samples) / fs
pulse_t0 = 20 / fs # Center the pulse a bit
pulse_bw = 0.5 # Fractional bandwidth
pulse_sigma = (pulse_bw * pulse_freq) / (2 * np.sqrt(2 * np.log(2)))
pulse = cp.exp(-((t - pulse_t0) * pulse_sigma)**2)
pulse *= cp.sin(2 * cp.pi * pulse_freq * (t - pulse_t0))
pulse_len = pulse.shape[0]
# Add signal from each scatterer to each element
for x_s, z_s in scatterers:
for i in range(num_elements):
# Calculate round-trip time from element to scatterer
dist = np.sqrt((element_pos[i].get() - x_s)**2 + z_s**2)
t_delay = 2 * dist / c
sample_delay = int(round(t_delay * fs))
# Add the pulse at the calculated delay
if 0 <= sample_delay < num_samples - pulse_len:
rf_data[sample_delay : sample_delay + pulse_len, i] += pulse
# Add some noise
rf_data += 0.05 * cp.random.randn(num_samples, num_elements, dtype=cp.float32)
return rf_data
if __name__ == "__main__":
# --- 1. Define Simulation Parameters ---
c = 1540.0 # Speed of sound in tissue (m/s)
fs = 40e6 # Sampling frequency (40 MHz)
pulse_freq = 5e6 # Transducer center frequency (5 MHz)
num_elements = 128 # Number of elements in the transducer array
element_pitch = 0.3e-3 # Distance between elements (0.3 mm)
# --- 2. Create Transducer Array and Image Grid ---
# Element positions (centered at x=0)
transducer_width = (num_elements - 1) * element_pitch
element_pos_np = np.linspace(-transducer_width / 2, transducer_width / 2, num_elements)
element_pos = cp.asarray(element_pos_np)
# Image grid (in meters)
image_width = 40e-3
image_depth = 50e-3
num_pix_x = 256
num_pix_z = 320
grid_x_np = np.linspace(-image_width / 2, image_width / 2, num_pix_x)
grid_z_np = np.linspace(1e-3, image_depth, num_pix_z) # Start just below the transducer
grid_x = cp.asarray(grid_x_np)
grid_z = cp.asarray(grid_z_np)
# Determine required number of samples based on max depth
max_time = 2 * image_depth / c
num_samples = int(np.ceil(max_time * fs))
# --- 3. Simulate RF Data from Point Scatterers ---
print("Simulating RF data...")
scatterers = [
(0, 15e-3),
(-10e-3, 25e-3),
(10e-3, 25e-3),
(0, 35e-3),
(5e-3, 45e-3),
(-5e-3, 45e-3),
]
# Move RF data to GPU
rf_data_gpu = simulate_rf_data(scatterers, element_pos, fs, c, pulse_freq, num_samples)
# --- 4. Run the Beamformer ---
print("Starting GPU beamforming...")
start_time = time.time()
# Call the main function
bf_image_gpu = das_beamformer_cupy(rf_data_gpu, element_pos, fs, c, grid_x, grid_z)
# Synchronize the GPU to get an accurate timing
cp.cuda.Stream.null.synchronize()
end_time = time.time()
print(f"Beamforming completed in {end_time - start_time:.4f} seconds.")
# --- 5. Post-process and Visualize ---
# Envelope detection
envelope = cp.abs(bf_image_gpu)
# Log compression for better dynamic range in visualization
log_compressed = 20 * cp.log10(envelope / cp.max(envelope))
# Move final image to CPU for plotting with Matplotlib
image_to_plot = cp.asnumpy(log_compressed)
# Plotting
plt.style.use('dark_background')
fig, ax = plt.subplots(1, 1, figsize=(6, 8))
# Display the image with physical dimensions
im = ax.imshow(
image_to_plot,
extent=[
grid_x_np.min() * 1000, grid_x_np.max() * 1000, # x-axis in mm
grid_z_np.max() * 1000, grid_z_np.min() * 1000 # z-axis in mm
],
cmap='gray',
vmin=-60, # Display a 60 dB dynamic range
vmax=0,
aspect='auto'
)
ax.set_title("CuPy DAS Beamformed B-Mode Image")
ax.set_xlabel("Lateral Position (mm)")
ax.set_ylabel("Axial Position (mm)")
# Add a colorbar
cbar = fig.colorbar(im, ax=ax)
cbar.set_label("Amplitude (dB)")
plt.tight_layout()
plt.show()