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
2 changes: 2 additions & 0 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@ 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 or ``center_frequency`` varies across transmits (:gh:`644` by :user:`tristan-deep`)

Changed
^^^^^^^
- Streaming ``hf://`` datasets no longer runs into the Hugging Face rate limit, so you can train on many batches with many workers without downloading the data. The API is unchanged; two new environment variables, ``ZEA_MAX_CONCURRENT_REQUESTS`` and ``ZEA_FIND_H5_SHAPES_WORKERS``, tune it (see :doc:`environment`) (:gh:`671` by :user:`tristan-deep`)
- 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
^^^^^
Expand Down
81 changes: 81 additions & 0 deletions tests/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,87 @@ 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(
"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)])
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",
[
Expand Down
54 changes: 54 additions & 0 deletions tests/test_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,60 @@ 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: no bandwidth is derived, but an explicit one is still used.
varying = Parameters(center_frequency=np.array([4e6, 5e6]), probe_bandwidth_percent=50.0)
assert varying.bandwidth is None
varying.bandwidth = 2e6
assert varying.bandwidth == pytest.approx(2e6)


# --- 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
51 changes: 48 additions & 3 deletions zea/ops/ultrasound.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import math
from collections.abc import Iterable

import keras
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -634,7 +654,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 @@ -671,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(),
Expand All @@ -688,7 +716,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 Expand Up @@ -734,6 +764,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,
Expand Down Expand Up @@ -767,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)
Expand Down
35 changes: 33 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,31 @@ 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, 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"]

bandwidth = self.center_frequency * self.probe_bandwidth_percent / 100
if np.ndim(bandwidth) > 0:
per_transmit = np.asarray(bandwidth)
if per_transmit.size == 0 or np.any(per_transmit != per_transmit.flat[0]):
return None
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