From f474138deb20fb4cc58822c7d8025239128f3ad4 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Tue, 29 Sep 2026 13:13:23 +0000 Subject: [PATCH 1/7] Derive a default bandwidth from the probe metadata Parameters.bandwidth defaults to center_frequency * probe_bandwidth_percent / 100, so LowPassFilterIQ and BandPassFilter get a bandwidth from prepare_parameters. An explicit bandwidth (on the parameters or as an override) still wins. --- tests/test_operations.py | 43 ++++++++++++++++++++++++++++++++++++++++ tests/test_scan.py | 32 ++++++++++++++++++++++++++++++ zea/ops/ultrasound.py | 8 ++++++-- zea/parameters.py | 17 ++++++++++++++++ 4 files changed, 98 insertions(+), 2 deletions(-) diff --git a/tests/test_operations.py b/tests/test_operations.py index d411df6f1..ab1ffe962 100644 --- a/tests/test_operations.py +++ b/tests/test_operations.py @@ -341,6 +341,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", [ diff --git a/tests/test_scan.py b/tests/test_scan.py index e703ef126..3f544e8eb 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -821,6 +821,38 @@ 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 200 % default applies. + assert Parameters(center_frequency=5e6).bandwidth == pytest.approx(10e6) + + assert "bandwidth" in Parameters(**scan_args).to_tensor(include=["bandwidth"]) + + +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) + + # --- distance_to_apex --- diff --git a/zea/ops/ultrasound.py b/zea/ops/ultrasound.py index ba87fe04a..54a1af64d 100644 --- a/zea/ops/ultrasound.py +++ b/zea/ops/ultrasound.py @@ -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__( @@ -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 diff --git a/zea/parameters.py b/zea/parameters.py index eeb747c64..35d7bd881 100644 --- a/zea/parameters.py +++ b/zea/parameters.py @@ -327,6 +327,7 @@ class Parameters(BaseParameters): "fill_value": {"dtype": float}, "resolution": {"dtype": (np.float32, type(None)), "default": None}, "distance_to_apex": {"dtype": (np.float32, type(None)), "default": None}, + "bandwidth": {"dtype": np.float32}, } # Add some defaults that are not stored in a file @@ -848,6 +849,22 @@ def demodulation_frequency(self): return self.center_frequency + @cache_with_dependencies("center_frequency", "probe_bandwidth_percent") + 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 200 % default makes this ``2 * center_frequency``, + which may be too wide for these filters. Set ``bandwidth`` (or + ``probe_bandwidth_percent``) explicitly in that case. + """ + if self._params.get("bandwidth") is not None: + return self._params["bandwidth"] + + return self.center_frequency * self.probe_bandwidth_percent / 100 + @cache_with_dependencies("selected_transmits") def polar_angles(self): """Polar angles for each transmit event in radians of shape (n_tx,). From 3af0f66a6f8c989a8046aa95fe28c8916347f644 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Tue, 29 Sep 2026 13:34:21 +0000 Subject: [PATCH 2/7] Collapse a uniform per-transmit bandwidth to a scalar --- tests/test_scan.py | 11 +++++++++++ zea/parameters.py | 12 +++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/test_scan.py b/tests/test_scan.py index 3f544e8eb..b9c651030 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -853,6 +853,17 @@ def test_bandwidth_explicit_value_wins(): 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 --- diff --git a/zea/parameters.py b/zea/parameters.py index 35d7bd881..8609c918e 100644 --- a/zea/parameters.py +++ b/zea/parameters.py @@ -859,11 +859,21 @@ def bandwidth(self): ``probe_bandwidth_percent``, its 200 % default makes this ``2 * center_frequency``, which may be too wide for these filters. Set ``bandwidth`` (or ``probe_bandwidth_percent``) explicitly in that case. + + 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"] - return self.center_frequency * self.probe_bandwidth_percent / 100 + 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 @cache_with_dependencies("selected_transmits") def polar_angles(self): From 6a14c2e489c10d7fefe6f20f4ad3978f968eb0aa Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 13:18:30 +0100 Subject: [PATCH 3/7] Default probe_bandwidth_percent to 100 %, aligning with #673 * note this also changes pfield computation --- tests/test_scan.py | 4 ++-- zea/parameters.py | 15 +++++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/tests/test_scan.py b/tests/test_scan.py index 828cc9c54..ebf2f3008 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -913,8 +913,8 @@ def test_bandwidth_derived_from_probe(): parameters.probe_bandwidth_percent = 80.0 assert parameters.bandwidth == pytest.approx(4e6) - # Without probe_bandwidth_percent in the file, its 200 % default applies. - assert Parameters(center_frequency=5e6).bandwidth == pytest.approx(10e6) + # 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"]) diff --git a/zea/parameters.py b/zea/parameters.py index 9fdb9382b..88420c9e0 100644 --- a/zea/parameters.py +++ b/zea/parameters.py @@ -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.""" @@ -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}, "attenuation_coef": {"dtype": np.float32, "default": 0.0}, "f_number": {"dtype": float, "default": 1.0}, # native dtype on purpose "t_peak": {"dtype": np.float32}, @@ -321,12 +327,11 @@ class Parameters(BaseParameters): "fill_value": {"dtype": float}, "resolution": {"dtype": (np.float32, type(None)), "default": None}, "distance_to_apex": {"dtype": (np.float32, type(None)), "default": None}, - "bandwidth": {"dtype": np.float32}, } # 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 @@ -852,9 +857,7 @@ def bandwidth(self): 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 200 % default makes this ``2 * center_frequency``, - which may be too wide for these filters. Set ``bandwidth`` (or - ``probe_bandwidth_percent``) explicitly in that case. + ``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 From 1f624f4e0c8c2736121745fdf323959ff72453ce Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 13:20:01 +0100 Subject: [PATCH 4/7] Track derivation inputs in the cache hash of unset parameters A parameter that is also a computed property (bandwidth, demodulation_frequency) was treated as its own only leaf, so its cache hash covered only its unset value. In-place changes to the inputs it is derived from, such as center_frequency[:] = 6e6, left the cached value stale. When such a parameter is unset, include its dependencies as leaves as well. --- tests/test_scan.py | 9 +++++++++ zea/internal/parameters.py | 14 +++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/test_scan.py b/tests/test_scan.py index ebf2f3008..fe2a7a580 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -919,6 +919,15 @@ def test_bandwidth_derived_from_probe(): 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) diff --git a/zea/internal/parameters.py b/zea/internal/parameters.py index 5392fc0a1..f7c8f40d3 100644 --- a/zea/internal/parameters.py +++ b/zea/internal/parameters.py @@ -296,7 +296,7 @@ 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() @@ -304,6 +304,18 @@ def _find_leaf_params(self, name, seen=None): 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} From d2c28c4ca933384b78e897a3eb118da950921a61 Mon Sep 17 00:00:00 2001 From: Ben Luijten Date: Thu, 5 Nov 2026 15:12:20 +0100 Subject: [PATCH 5/7] Allow manually specified bandpass filters --- tests/test_operations.py | 9 +++++++++ zea/ops/ultrasound.py | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/tests/test_operations.py b/tests/test_operations.py index 9a743e23f..70eea65d1 100644 --- a/tests/test_operations.py +++ b/tests/test_operations.py @@ -386,6 +386,15 @@ def parameters(**kwargs): np.testing.assert_allclose(overridden, call_level, rtol=1e-5, atol=1e-6) +def test_fixed_band_pass_filter_without_center_frequency(): + """A fixed passband does not require deriving a bandwidth.""" + pipeline = Pipeline([ops.BandPassFilter(passband=(3e6, 7e6), num_taps=31)]) + parameters = Parameters(sampling_frequency=20e6, demodulation_frequency=5e6) + inputs = pipeline.prepare_parameters(parameters) + data = np.ones((1, 64, 2, 1), dtype=np.float32) + assert pipeline(data=data, **inputs)["data"].shape == data.shape + + @pytest.mark.parametrize( "factor, batch_size", [ diff --git a/zea/ops/ultrasound.py b/zea/ops/ultrasound.py index 54a1af64d..fca8b9c07 100644 --- a/zea/ops/ultrasound.py +++ b/zea/ops/ultrasound.py @@ -738,6 +738,14 @@ def __init__( self.num_taps = num_taps self.passband = passband + @property + def needs_keys(self): + keys = super().needs_keys + if self.passband is not None: + # A manually set passband bypasses automatic frequency and bandwidth computation. + return keys - {"bandwidth", "demodulation_frequency"} + return keys + def call( self, sampling_frequency, From 3a91887b6811e665d26ce5a5219a446e2ac4b629 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Thu, 5 Nov 2026 15:10:00 +0000 Subject: [PATCH 6/7] Add changelog entries for derived bandwidth --- docs/source/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index db632087c..81f34d425 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -27,6 +27,7 @@ New Features - Transparent GIFs from RGBA frames with ``transparent=True`` in :func:`zea.io_lib.save_video` and :func:`zea.io_lib.save_to_gif` (:gh:`663` by :user:`tristan-deep`) - GIFs that play once, with ``loop=None`` in :func:`zea.io_lib.save_to_gif` (:gh:`680` by :user:`wesselvannierop`) - ``zea app`` can serve over HTTPS with ``--ssl-certfile`` and ``--ssl-keyfile`` (:gh:`648` by :user:`Louisvh`) +- :class:`zea.ops.BandPassFilter` and :class:`zea.ops.LowPassFilterIQ` take their ``bandwidth`` from the new :attr:`zea.Parameters.bandwidth`, derived as ``center_frequency * probe_bandwidth_percent / 100`` unless set (:gh:`644` by :user:`tristan-deep`) Changed ^^^^^^^ @@ -34,6 +35,7 @@ Changed - Conversion scripts for EchoNet-Dynamic, CAMUS and PICMUS accept the ``.zip`` file itself. EchoNet-Dynamic reproduces the published split by default, and its polar conversion is about 15 times faster (:gh:`676` by :user:`wesselvannierop`) - (Breaking) In ``compute_pfield``, ``alpha`` and ``percentile`` also shape the field when ``norm=False``, the unused ``n_el`` argument is removed, and probes other than linear and phased arrays raise ``NotImplementedError`` (:gh:`657` by :user:`wesselvannierop`) - ``Parameters.copy()`` and ``set_transmits`` are much faster (:gh:`656` by :user:`wesselvannierop`) +- The default ``probe_bandwidth_percent`` is 100 instead of 200, which also narrows the band used by ``compute_pfield`` (:gh:`644` by :user:`tristan-deep`) Fixed ^^^^^ From c14fe56848ca03c861cdd0ef9b8b78e02cfdf047 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Thu, 5 Nov 2026 15:23:28 +0000 Subject: [PATCH 7/7] Require scalar filter inputs; no derived bandwidth for varying per-transmit center frequency --- docs/source/changelog.rst | 2 +- tests/test_operations.py | 29 +++++++++++++++++++++++++++++ tests/test_scan.py | 6 ++++-- zea/ops/ultrasound.py | 35 ++++++++++++++++++++++++++++++++++- zea/parameters.py | 9 +++++---- 5 files changed, 73 insertions(+), 8 deletions(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 81f34d425..5f8dde422 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -27,7 +27,7 @@ New Features - Transparent GIFs from RGBA frames with ``transparent=True`` in :func:`zea.io_lib.save_video` and :func:`zea.io_lib.save_to_gif` (:gh:`663` by :user:`tristan-deep`) - GIFs that play once, with ``loop=None`` in :func:`zea.io_lib.save_to_gif` (:gh:`680` by :user:`wesselvannierop`) - ``zea app`` can serve over HTTPS with ``--ssl-certfile`` and ``--ssl-keyfile`` (:gh:`648` by :user:`Louisvh`) -- :class:`zea.ops.BandPassFilter` and :class:`zea.ops.LowPassFilterIQ` take their ``bandwidth`` from the new :attr:`zea.Parameters.bandwidth`, derived as ``center_frequency * probe_bandwidth_percent / 100`` unless set (:gh:`644` by :user:`tristan-deep`) +- :class:`zea.ops.BandPassFilter` and :class:`zea.ops.LowPassFilterIQ` take their ``bandwidth`` from the new :attr:`zea.Parameters.bandwidth`, derived as ``center_frequency * probe_bandwidth_percent / 100`` unless set or ``center_frequency`` varies across transmits (:gh:`644` by :user:`tristan-deep`) Changed ^^^^^^^ diff --git a/tests/test_operations.py b/tests/test_operations.py index 70eea65d1..00c48c033 100644 --- a/tests/test_operations.py +++ b/tests/test_operations.py @@ -386,6 +386,35 @@ def parameters(**kwargs): np.testing.assert_allclose(overridden, call_level, rtol=1e-5, atol=1e-6) +@pytest.mark.parametrize( + "operation, kwargs", + [ + ( + ops.LowPassFilterIQ(num_taps=31), + {"center_frequency": 0.0, "bandwidth": np.array([2e6, 2.5e6])}, + ), + ( + ops.LowPassFilterIQ(num_taps=31), + {"center_frequency": 0.0, "bandwidth": None}, + ), + ( + ops.BandPassFilter(num_taps=31), + {"demodulation_frequency": np.array([4e6, 5e6]), "bandwidth": 2e6}, + ), + ( + ops.BandPassFilter(num_taps=31), + {"demodulation_frequency": 5e6, "bandwidth": None}, + ), + ], +) +def test_filters_reject_per_transmit_inputs(operation, kwargs): + """The filters design one set of taps, so per-transmit or missing inputs raise clearly.""" + n_ch = 2 if isinstance(operation, ops.LowPassFilterIQ) else 1 + data = np.ones((1, 64, 2, n_ch), dtype=np.float32) + with pytest.raises(ValueError, match="bandwidth|scalar"): + operation(data=data, sampling_frequency=20e6, **kwargs) + + def test_fixed_band_pass_filter_without_center_frequency(): """A fixed passband does not require deriving a bandwidth.""" pipeline = Pipeline([ops.BandPassFilter(passband=(3e6, 7e6), num_taps=31)]) diff --git a/tests/test_scan.py b/tests/test_scan.py index fe2a7a580..bccedce5b 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -951,9 +951,11 @@ def test_bandwidth_per_transmit_center_frequency(): assert np.ndim(uniform.bandwidth) == 0 assert uniform.bandwidth == pytest.approx(3e6) - # Varying per transmit: the derived bandwidth stays per transmit. + # Varying per transmit: no bandwidth is derived, but an explicit one is still used. varying = Parameters(center_frequency=np.array([4e6, 5e6]), probe_bandwidth_percent=50.0) - np.testing.assert_allclose(varying.bandwidth, [2e6, 2.5e6]) + assert varying.bandwidth is None + varying.bandwidth = 2e6 + assert varying.bandwidth == pytest.approx(2e6) # --- distance_to_apex --- diff --git a/zea/ops/ultrasound.py b/zea/ops/ultrasound.py index fca8b9c07..720b49304 100644 --- a/zea/ops/ultrasound.py +++ b/zea/ops/ultrasound.py @@ -1,3 +1,4 @@ +import math from collections.abc import Iterable import keras @@ -557,6 +558,25 @@ def call(self, demodulation_frequency=None, sampling_frequency=None, **kwargs): } +def _check_scalar_filter_inputs(op_name, **values): + """Raise a clear error unless each filter design input is a single value. + + The filter operations design one set of taps, so per-transmit frequencies cannot be used. + Only the static shape is checked, so this also works inside ``jit``. + """ + for name, value in values.items(): + if value is None: + raise ValueError( + f"{op_name} needs a scalar `{name}`, but got None. When `center_frequency` " + "varies across transmits, `bandwidth` is not derived; set it explicitly." + ) + if math.prod(getattr(value, "shape", ())) != 1: + raise ValueError( + f"{op_name} designs one set of filter taps, so `{name}` must be a scalar, " + f"got shape {tuple(value.shape)}. Set a scalar `{name}` explicitly." + ) + + @ops_registry("fir_filter") class FirFilter(Operation): """Apply a FIR filter to the input signal using convolution. @@ -673,6 +693,12 @@ def __init__( self.num_taps = num_taps def call(self, bandwidth, sampling_frequency, center_frequency, **kwargs): + _check_scalar_filter_inputs( + "LowPassFilterIQ", + bandwidth=bandwidth, + sampling_frequency=sampling_frequency, + center_frequency=center_frequency, + ) lpf = get_low_pass_iq_filter( self.num_taps, ops.convert_to_numpy(sampling_frequency).item(), @@ -779,11 +805,18 @@ def call( if demodulation_frequency is None or bandwidth is None: raise ValueError( "BandPassFilter requires either passband=(f1, f2) or both " - "demodulation_frequency and bandwidth." + "demodulation_frequency and bandwidth. When `center_frequency` varies " + "across transmits, `bandwidth` is not derived; set it explicitly." ) + _check_scalar_filter_inputs( + "BandPassFilter", + demodulation_frequency=demodulation_frequency, + bandwidth=bandwidth, + ) f1 = demodulation_frequency - bandwidth / 2 f2 = demodulation_frequency + bandwidth / 2 + _check_scalar_filter_inputs("BandPassFilter", sampling_frequency=sampling_frequency) bpf = get_band_pass_filter(self.num_taps, sampling_frequency, f1, f2) kwargs[self.filter_key] = bpf return super().call(**kwargs) diff --git a/zea/parameters.py b/zea/parameters.py index 88420c9e0..e92dd71e1 100644 --- a/zea/parameters.py +++ b/zea/parameters.py @@ -861,8 +861,8 @@ def bandwidth(self): 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. + it varies across transmits, no bandwidth is derived (``None``), and ``bandwidth`` must be + set explicitly for these filters. """ if self._params.get("bandwidth") is not None: return self._params["bandwidth"] @@ -870,8 +870,9 @@ def bandwidth(self): 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] + if per_transmit.size == 0 or np.any(per_transmit != per_transmit.flat[0]): + return None + return per_transmit.flat[0] return bandwidth @cache_with_dependencies("selected_transmits")