Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
43 changes: 43 additions & 0 deletions tests/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,49 @@ def test_low_pass_filter_iq():
return output


def test_filter_bandwidth_from_parameters():
"""A config-built pipeline with ``low_pass_filter`` and ``band_pass_filter`` runs without an
explicit ``bandwidth``: it is derived from the probe metadata, and explicit values still win.
"""
from zea import Config

rng = np.random.default_rng(DEFAULT_TEST_SEED)
center_frequency, sampling_frequency = 2e6, 12.5e6
derived_bandwidth = center_frequency * 60.0 / 100

def run(operation, data, parameters, **overrides):
pipeline = Pipeline.from_config(
Config({"pipeline": {"operations": [{"name": operation, "params": {"num_taps": 63}}]}})
)
inputs = pipeline.prepare_parameters(parameters, **overrides)
return keras.ops.convert_to_numpy(pipeline(data=data, **inputs)["data"])

def parameters(**kwargs):
return Parameters(
center_frequency=center_frequency,
sampling_frequency=sampling_frequency,
probe_bandwidth_percent=60.0,
**kwargs,
)

for operation, n_ch in (("low_pass_filter", 2), ("band_pass_filter", 1)):
data = rng.standard_normal((1, 256, 4, n_ch)).astype("float32")

derived = run(operation, data, parameters())
explicit_derived = run(operation, data, parameters(bandwidth=derived_bandwidth))
np.testing.assert_allclose(derived, explicit_derived, rtol=1e-5, atol=1e-6)

# An explicit bandwidth, on the parameters or as an override, wins over the derived one.
parameter_level = run(operation, data, parameters(bandwidth=3e6))
call_level = run(operation, data, parameters(), bandwidth=3e6)
np.testing.assert_allclose(parameter_level, call_level, rtol=1e-5, atol=1e-6)
assert not np.allclose(derived, parameter_level, rtol=1e-5, atol=1e-6)

# A call-time override also wins over a bandwidth set on the parameters.
overridden = run(operation, data, parameters(bandwidth=derived_bandwidth), bandwidth=3e6)
np.testing.assert_allclose(overridden, call_level, rtol=1e-5, atol=1e-6)


@pytest.mark.parametrize(
"factor, batch_size",
[
Expand Down
52 changes: 52 additions & 0 deletions tests/test_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,58 @@ def test_custom_parameters_passthrough_to_tensor():
assert parameters.wavelength == parameters.sound_speed / parameters.center_frequency


def test_bandwidth_derived_from_probe():
"""Left unset, the bandwidth is center_frequency * probe_bandwidth_percent / 100."""
parameters = Parameters(center_frequency=5e6, probe_bandwidth_percent=60.0)
assert parameters.bandwidth == pytest.approx(3e6)

# Changing a dependency invalidates the cached value.
parameters.probe_bandwidth_percent = 80.0
assert parameters.bandwidth == pytest.approx(4e6)

# Without probe_bandwidth_percent in the file, its 100 % default applies.
assert Parameters(center_frequency=5e6).bandwidth == pytest.approx(5e6)

assert "bandwidth" in Parameters(**scan_args).to_tensor(include=["bandwidth"])


def test_bandwidth_follows_in_place_changes():
"""In-place changes to center_frequency refresh the derived bandwidth."""
parameters = Parameters(center_frequency=np.full(3, 5e6), probe_bandwidth_percent=60.0)
assert parameters.bandwidth == pytest.approx(3e6)

parameters.center_frequency[:] = 6e6
assert parameters.bandwidth == pytest.approx(3.6e6)


def test_bandwidth_explicit_value_wins():
"""An explicit bandwidth overrides the derived one, and unsetting it falls back."""
parameters = Parameters(center_frequency=5e6, probe_bandwidth_percent=60.0, bandwidth=1e6)
assert parameters.bandwidth == pytest.approx(1e6)

# Dependencies do not affect an explicit value.
parameters.center_frequency = 7e6
assert parameters.bandwidth == pytest.approx(1e6)

parameters.update(bandwidth=2e6)
assert parameters.bandwidth == pytest.approx(2e6)
assert "bandwidth" in parameters._params

parameters.bandwidth = None
assert parameters.bandwidth == pytest.approx(4.2e6)


def test_bandwidth_per_transmit_center_frequency():
"""A per-transmit center_frequency that is the same everywhere gives a scalar bandwidth."""
uniform = Parameters(center_frequency=np.full(3, 5e6), probe_bandwidth_percent=60.0)
assert np.ndim(uniform.bandwidth) == 0
assert uniform.bandwidth == pytest.approx(3e6)

# Varying per transmit: the derived bandwidth stays per transmit.
varying = Parameters(center_frequency=np.array([4e6, 5e6]), probe_bandwidth_percent=50.0)
np.testing.assert_allclose(varying.bandwidth, [2e6, 2.5e6])


# --- distance_to_apex ---


Expand Down
14 changes: 13 additions & 1 deletion zea/internal/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,14 +296,26 @@ def _find_leaf_params(self, name, seen=None):
"""Recursively find all leaf parameters that a property depends on.

If it is an optional dependency parameter, it will be included as a leaf. Not the ones it
depends on.
depends on, unless it is unset and derived from them instead.
"""
if seen is None:
seen = set()
if name in seen:
return set()
seen.add(name)

# An optional dependency parameter that is unset falls back to its dependencies, so
# those are leaves too (e.g. bandwidth derived from center_frequency).
if (
name in self.VALID_PARAMS
and self._params.get(name) is None
and self._is_property_with_dependencies(name)
):
leaves = {name}
for dep in self._get_dependencies(name):
leaves |= self._find_leaf_params(dep, seen) # union
return leaves

# If the name is already a leaf parameter, return it
if name in self._params or name in self.VALID_PARAMS:
return {name}
Expand Down
8 changes: 6 additions & 2 deletions zea/ops/ultrasound.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,9 @@ class LowPassFilterIQ(FirFilter):
operations. The :class:`LowPassFilterIQ` operation itself is not jittable and is provided
for convenience only.

Uses :func:`get_low_pass_iq_filter` to compute the filter taps.
Uses :func:`get_low_pass_iq_filter` to compute the filter taps. The call-time
``bandwidth`` (in Hz) defaults to :attr:`~zea.Parameters.bandwidth` when the parameters are
prepared with :meth:`~zea.Pipeline.prepare_parameters`.
"""

def __init__(
Expand Down Expand Up @@ -688,7 +690,9 @@ class BandPassFilter(FirFilter):
By default, the call-time ``bandwidth`` defines the passband centered around
``demodulation_frequency``, with edges at
``demodulation_frequency - bandwidth/2`` and
``demodulation_frequency + bandwidth/2``.
``demodulation_frequency + bandwidth/2``. When the parameters are prepared with
:meth:`~zea.Pipeline.prepare_parameters`, ``bandwidth`` defaults to
:attr:`~zea.Parameters.bandwidth`.

Optionally, a fixed ``passband=(f1, f2)`` can be provided at initialization, or a
call-time ``passband`` can be provided to override both the fixed passband and the
Expand Down
34 changes: 32 additions & 2 deletions zea/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,12 @@ class Parameters(BaseParameters):
"""Nominal center frequency of the probe [Hz]."""

probe_bandwidth_percent: float
"""Probe bandwidth as a percentage of the center frequency. Defaults to 200.0."""
"""Probe bandwidth as a percentage of the center frequency. Defaults to 100.0."""

bandwidth: float
"""Width of the RF band kept by processing [Hz], centered on the
``demodulation_frequency``. Used by :class:`~zea.ops.BandPassFilter` and by
:meth:`check_for_aliasing`."""

n_el: int
"""Number of elements in the transducer array."""
Expand Down Expand Up @@ -312,6 +317,7 @@ class Parameters(BaseParameters):
"n_tx": {"dtype": np.int32},
"n_ax": {"dtype": int}, # native dtype on purpose
"n_ch": {"dtype": np.int32},
"bandwidth": {"dtype": np.float32},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"attenuation_coef": {"dtype": np.float32, "default": 0.0},
"f_number": {"dtype": float, "default": 1.0}, # native dtype on purpose
"t_peak": {"dtype": np.float32},
Expand All @@ -325,7 +331,7 @@ class Parameters(BaseParameters):

# Add some defaults that are not stored in a file
VALID_PARAMS["sound_speed"]["default"] = 1540.0
VALID_PARAMS["probe_bandwidth_percent"]["default"] = 200.0
VALID_PARAMS["probe_bandwidth_percent"]["default"] = 100.0
# Give these a default of None (rather than leaving them unset) so that they can be
# declared as dependencies of computed properties (e.g. t_peak, n_waveforms) without
# tripping MissingDependencyError
Expand Down Expand Up @@ -844,6 +850,30 @@ def demodulation_frequency(self):

return self.center_frequency

@cache_with_dependencies("center_frequency", "probe_bandwidth_percent")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
def bandwidth(self):
"""The signal bandwidth in Hz, used by filter operations such as
:class:`~zea.ops.LowPassFilterIQ` and :class:`~zea.ops.BandPassFilter`.

If not set explicitly, it is derived from the probe metadata as
``center_frequency * probe_bandwidth_percent / 100``. When the file does not store
``probe_bandwidth_percent``, its default applies.

The filter operations design one set of taps, so they need a scalar. A per-transmit
``center_frequency`` that is the same for every transmit gives a scalar bandwidth; when
it varies across transmits, the derived bandwidth is per transmit as well, and
``bandwidth`` should be set explicitly for these filters.
"""
if self._params.get("bandwidth") is not None:
return self._params["bandwidth"]

bandwidth = self.center_frequency * self.probe_bandwidth_percent / 100
if np.ndim(bandwidth) > 0:
per_transmit = np.asarray(bandwidth)
if per_transmit.size > 0 and np.all(per_transmit == per_transmit.flat[0]):
return per_transmit.flat[0]
return bandwidth
Comment thread
tristan-deep marked this conversation as resolved.
Resolved

@cache_with_dependencies("selected_transmits")
def polar_angles(self):
"""Polar angles for each transmit event in radians of shape (n_tx,).
Expand Down
Loading