Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 98 additions & 15 deletions tests/data/test_conversion_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
)
from zea.data.convert.verasonics import (
VerasonicsFile,
bs100bw_to_iq,
baseband_mode_to_iq,
convert_verasonics,
estimate_lens_probe_params,
)
Expand Down Expand Up @@ -1808,43 +1808,126 @@ def test_invalid_lens_correction_inf(self):
estimate_lens_probe_params(float("inf"), 7e6)


class TestBs100bwToIq:
class TestBasebandModeToIq:
def _make_data(self, n_frames=2, n_tx=3, n_ax=8, n_el=4):
return np.zeros((n_frames, n_tx, n_ax, n_el, 1), dtype=np.float32)

def test_output_shape(self):
data = self._make_data()
out = bs100bw_to_iq(data)
out = baseband_mode_to_iq(data)
assert out.shape == (2, 3, 4, 4, 2)

def test_i_samples_are_even_rows(self):
data = np.zeros((1, 1, 4, 1, 1), dtype=np.float32)
data[0, 0, 0, 0, 0] = 5.0 # even index → I
data[0, 0, 2, 0, 0] = 7.0 # even index → I
out = bs100bw_to_iq(data)
out = baseband_mode_to_iq(data)
np.testing.assert_array_equal(out[0, 0, :, 0, 0], [5.0, 7.0]) # I channel

def test_q_samples_are_negated_odd_rows(self):
data = np.zeros((1, 1, 4, 1, 1), dtype=np.float32)
data[0, 0, 1, 0, 0] = 3.0 # odd index → Q (negated)
out = bs100bw_to_iq(data)
assert out[0, 0, 0, 0, 1] == -3.0 # Q channel negated

def test_wrong_ndim_raises(self):
with pytest.raises(ValueError, match="Expected shape"):
bs100bw_to_iq(np.zeros((2, 3, 8, 4)))
baseband_mode_to_iq(np.zeros((2, 3, 8, 4)))

def test_wrong_last_dim_raises(self):
with pytest.raises(ValueError, match="Expected shape"):
bs100bw_to_iq(np.zeros((2, 3, 8, 4, 2)))
baseband_mode_to_iq(np.zeros((2, 3, 8, 4, 2)))

def test_odd_axial_dim_raises(self):
with pytest.raises(ValueError, match="Axial dimension must be even"):
bs100bw_to_iq(np.zeros((2, 3, 7, 4, 1), dtype=np.float32))
baseband_mode_to_iq(np.zeros((2, 3, 7, 4, 1), dtype=np.float32))

def test_odd_rows_hold_negated_q(self):
# Odd samples hold -Q, so Q is the negated odd sample. A constant Q is unchanged
# by the fractional delay, so only the negation remains.
data = np.zeros((1, 1, 8, 1, 1), dtype=np.float32)
data[0, 0, 1::2, 0, 0] = 3.0 # odd index holds -Q
out = baseband_mode_to_iq(data)
np.testing.assert_allclose(out[0, 0, :, 0, 1], -3.0, rtol=1e-5) # Q channel

def test_invalid_carrier_periods_per_pair_raises(self):
with pytest.raises(ValueError, match="carrier_periods_per_pair"):
baseband_mode_to_iq(self._make_data(), carrier_periods_per_pair=3)

CENTER_FREQUENCY = 5e6
NUMBER_OF_IQ_SAMPLES = 256

def _true_baseband(
self,
time: np.ndarray,
periods_per_pair: int,
pulse_width_periods: float,
frequency_offset_fraction: float,
) -> np.ndarray:
"""Band-limited complex baseband pulse centered in the record.

Pulse width and frequency offset scale with ``periods_per_pair`` so that the
pulse occupies the same fraction of the IQ band in every sample mode.
"""
record_duration = self.NUMBER_OF_IQ_SAMPLES * periods_per_pair / self.CENTER_FREQUENCY
pulse_width = pulse_width_periods * periods_per_pair / self.CENTER_FREQUENCY
relative_time = time - record_duration / 2
envelope = np.exp(-0.5 * (relative_time / pulse_width) ** 2)
frequency_offset = frequency_offset_fraction * self.CENTER_FREQUENCY / periods_per_pair
phase = 2 * np.pi * frequency_offset * relative_time + 0.7
return envelope * np.exp(1j * phase)

def _baseband_samples(self, periods_per_pair: int, **pulse) -> np.ndarray:
"""Sample RF at four times the center frequency and keep the first two samples of
every ``4 * periods_per_pair``, as BS100BW (1) and BS50BW (2) do."""
samples_per_pair = 4 * periods_per_pair
time = np.arange(samples_per_pair * self.NUMBER_OF_IQ_SAMPLES) / (4 * self.CENTER_FREQUENCY)
carrier = np.exp(2j * np.pi * self.CENTER_FREQUENCY * time)
rf = np.real(self._true_baseband(time, periods_per_pair, **pulse) * carrier)
return rf.reshape(self.NUMBER_OF_IQ_SAMPLES, samples_per_pair)[:, :2].reshape(-1)

def _true_baseband_at_iq_times(self, periods_per_pair: int, **pulse) -> np.ndarray:
iq_times = np.arange(self.NUMBER_OF_IQ_SAMPLES) * periods_per_pair / self.CENTER_FREQUENCY
return self._true_baseband(iq_times, periods_per_pair, **pulse)

@staticmethod
def _relative_error(estimate: np.ndarray, reference: np.ndarray) -> float:
return np.linalg.norm(estimate - reference) / np.linalg.norm(reference)

NARROWBAND_PULSE = {"pulse_width_periods": 3, "frequency_offset_fraction": 0.2}
WIDEBAND_PULSE = {"pulse_width_periods": 1, "frequency_offset_fraction": 0.0}

@pytest.mark.parametrize(
"periods_per_pair, pulse, tolerance",
[
(1, NARROWBAND_PULSE, 1e-3),
(2, NARROWBAND_PULSE, 1e-3),
(1, WIDEBAND_PULSE, 1e-2),
(2, WIDEBAND_PULSE, 1e-2),
],
ids=["bs100bw-narrowband", "bs50bw-narrowband", "bs100bw-wideband", "bs50bw-wideband"],
)
def test_matches_true_baseband(self, periods_per_pair, pulse, tolerance):
interleaved = self._baseband_samples(periods_per_pair, **pulse)
iq = baseband_mode_to_iq(
interleaved[None, None, :, None, None], carrier_periods_per_pair=periods_per_pair
)[0, 0, :, 0]
estimated_baseband = iq[:, 0] + 1j * iq[:, 1]
reference = self._true_baseband_at_iq_times(periods_per_pair, **pulse)
assert self._relative_error(estimated_baseband, reference) < tolerance

@pytest.mark.parametrize("periods_per_pair", [1, 2], ids=["bs100bw", "bs50bw"])
def test_unaligned_differs_from_true_baseband(self, periods_per_pair):
interleaved = self._baseband_samples(periods_per_pair, **self.NARROWBAND_PULSE)
# Even samples hold I and odd samples hold -Q, so I + jQ = even - j * odd.
unaligned_baseband = interleaved[0::2] - 1j * interleaved[1::2]
reference = self._true_baseband_at_iq_times(periods_per_pair, **self.NARROWBAND_PULSE)
assert self._relative_error(unaligned_baseband, reference) > 1e-2

def test_bs50bw_needs_its_own_delay(self):
# Aligning BS50BW with the BS100BW delay must not reach the BS50BW accuracy.
interleaved = self._baseband_samples(2, **self.NARROWBAND_PULSE)
iq = baseband_mode_to_iq(interleaved[None, None, :, None, None])[0, 0, :, 0]
reference = self._true_baseband_at_iq_times(2, **self.NARROWBAND_PULSE)
assert self._relative_error(iq[:, 0] + 1j * iq[:, 1], reference) > 1e-2

def test_int16_saturation_no_overflow(self):
data = np.full((1, 1, 2, 1, 1), -32768, dtype=np.int16)
out = bs100bw_to_iq(data)
# Q channel negation of -32768 would overflow in int16; must be 32768.0
out = baseband_mode_to_iq(data)
# Negating the odd sample -32768 to recover Q would overflow in int16; must be 32768.0
assert out[0, 0, 0, 0, 1] == 32768.0
assert out.dtype == np.float32
70 changes: 64 additions & 6 deletions zea/data/convert/verasonics.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@

import h5py
import numpy as np
import scipy.fft
import yaml
from keras import ops

Expand Down Expand Up @@ -184,15 +185,23 @@ def estimate_lens_probe_params(
}


def bs100bw_to_iq(data: np.ndarray) -> np.ndarray:
def baseband_mode_to_iq(data: np.ndarray, carrier_periods_per_pair: int = 1) -> np.ndarray:
"""Convert BS100BW/BS50BW interleaved data to IQ format.

Both Verasonics baseband modes (BS100BW and BS50BW) interleave I and Q
samples along the axial axis: even samples are I, odd samples are Q
(negated).
Both Verasonics baseband modes (BS100BW and BS50BW) store pairs of samples taken a
quarter carrier period apart. One pair is taken every carrier period (BS100BW) or
every two carrier periods (BS50BW).

With ``x(t) = I(t) cos(2π f_c t) - Q(t) sin(2π f_c t)``, the even samples fall where
``cos = 1`` and hold ``I``, and the odd samples fall where ``sin = 1`` and hold
``-Q``. The odd samples are therefore negated to recover ``Q``. Because Q is sampled
a quarter carrier period after I, Q is then shifted back to the I sample times with
a band-limited fractional delay.

Args:
data: Input array of shape ``(n_frames, n_tx, n_ax_raw, n_el, 1)``.
carrier_periods_per_pair: Number of carrier periods between consecutive sample
pairs: 1 for BS100BW, 2 for BS50BW. Defaults to 1.

Returns:
IQ array of shape ``(n_frames, n_tx, n_ax, n_el, 2)``.
Expand All @@ -201,8 +210,54 @@ def bs100bw_to_iq(data: np.ndarray) -> np.ndarray:
raise ValueError(f"Expected shape (n_frames, n_tx, n_ax_raw, n_el, 1), got {data.shape}")
if data.shape[2] % 2 != 0:
raise ValueError(f"Axial dimension must be even for IQ deinterleaving, got {data.shape[2]}")
if carrier_periods_per_pair not in (1, 2):
raise ValueError(
f"carrier_periods_per_pair must be 1 (BS100BW) or 2 (BS50BW), "
f"got {carrier_periods_per_pair}"
)
d = data.astype(np.float32)
return np.stack([d[:, :, 0::2, :, 0], -d[:, :, 1::2, :, 0]], axis=-1)
# Even samples hold I, odd samples hold -Q.
iq_data = np.stack([d[:, :, 0::2, :, 0], -d[:, :, 1::2, :, 0]], axis=-1)
del d
# Q lags I by a quarter carrier period, expressed here in IQ samples.
q_delay = 0.25 / carrier_periods_per_pair
return _align_baseband_quadrature(iq_data, axis=2, q_delay=q_delay)


def _align_baseband_quadrature(iq: np.ndarray, axis: int = 2, q_delay: float = 0.25) -> np.ndarray:
"""Shift Q back to the I sample times in IQ data built from BS100BW/BS50BW pairs.

The baseband sample modes capture I at time ``t`` and Q a quarter carrier period
later. With ``Ts`` the IQ sample period, that is ``Q(t + Ts/4)`` for BS100BW and
``Q(t + Ts/8)`` for BS50BW. This function applies a band-limited fractional delay
of ``q_delay`` samples to Q so that it is evaluated at the I sample times.

Q is overwritten in place to limit peak memory on full recordings.

Args:
iq: Float32 IQ data with I and Q on the last axis. Modified in place.
axis: The axial (fast-time) axis.
q_delay: How far Q lags I, in IQ samples. 0.25 for BS100BW, 0.125 for BS50BW.
Defaults to 0.25.

Returns:
``iq``, with Q evaluated at the I sample times.
"""
q_data = np.moveaxis(iq[..., 1], axis, -1)
n_ax = q_data.shape[-1]
# Mirror the record so the circular FFT shift sees no jump between its end and start.
n_fft = 2 * n_ax
q_data_extended = np.concatenate([q_data, q_data[..., ::-1]], axis=-1)
spectrum = scipy.fft.rfft(q_data_extended, axis=-1, workers=-1)
del q_data_extended
frequency = scipy.fft.rfftfreq(n_fft)
# Q[n] holds Im b at sample n + q_delay; evaluate it at sample n.
spectrum *= np.exp(-2j * np.pi * frequency * q_delay).astype(spectrum.dtype)
q_aligned = scipy.fft.irfft(spectrum, n=n_fft, axis=-1, workers=-1)
del spectrum

iq[..., 1] = np.moveaxis(q_aligned[..., :n_ax], -1, axis)
return iq


def _validate_convert_config(data):
Expand Down Expand Up @@ -750,7 +805,10 @@ def read_raw_data(self, frames="all", buffer_index=0, first_frame_idx=None):
raw_data = raw_data[..., None]

if self.is_baseband_mode:
raw_data = bs100bw_to_iq(raw_data)
# BS100BW takes a sample pair every carrier period, BS50BW every two.
raw_data = baseband_mode_to_iq(
raw_data, carrier_periods_per_pair=100 // self.sample_mode
)

return raw_data

Expand Down
Loading