Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Restrict pfield to linear arrays and track element_width in its cache
- Reject non-linear probe geometries in compute_pfield: element orientation
  and sub-element layout assume all elements lie on the x-axis.
- Infer element_width with the shared _resolve_element_width helper (moved
  to zea.probes), which converts the geometry to numpy before get_pitch.
- Add optional dependencies to cache_with_dependencies, and make pfield
  optionally depend on element_width so changing it invalidates the cache.
- Drop the unused n_el argument from compute_pfield and document
  element_width.
  • Loading branch information
wesselvannierop committed Oct 16, 2026
commit d621f3bf0cf11922ec4c2d7686a86bdd35c47707
13 changes: 13 additions & 0 deletions tests/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ class DummyParameters(BaseParameters):
computed1: A computed property depending on param1 and param2
computed2: A computed property depending on computed1
computed3: A computed property depending on param3 and param4
computed4: A computed property depending on param3, and optionally on param5
optional_param: A property that is either set directly or computed from dependencies
"""

Expand Down Expand Up @@ -118,6 +119,11 @@ def computed3(self):
self._computed3_count += 1
return self.param3 / self.param4

@cache_with_dependencies("param3", optional=("param5",))
def computed4(self):
param5 = self._params.get("param5")
return self.param3 if param5 is None else self.param3 + param5

@cache_with_dependencies("param3", "param1", "param4")
def optional_param(self):
# Use the underlying param if set
Expand Down Expand Up @@ -258,6 +264,13 @@ def test_missing_dependency_error_message():
assert "param1" in msg and "param2" in msg


def test_optional_dependency(dummy_params):
"""An optional dependency is not required, but setting it invalidates the cache."""
assert dummy_params.computed4 == 1500.0
dummy_params.param5 = 10.0
assert dummy_params.computed4 == 1510.0


def test_to_tensor_includes_all(dummy_params: DummyParameters):
"""Test that to_tensor includes all parameters and computed properties."""
tensors = dummy_params.to_tensor()
Expand Down
37 changes: 35 additions & 2 deletions tests/test_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@

import numpy as np
import pytest
from keras import ops

from zea import Parameters
from zea.beamform.pfield import compute_pfield
from zea.data.spec import ProbeSpec, ScanSpec
from zea.internal.dummy_scan import get_parameters
from zea.probes import create_curved_probe_geometry
from zea.probes import Probe, create_curved_probe_geometry

scan_args = {
"n_tx": 10,
Expand Down Expand Up @@ -715,7 +717,12 @@ def edit3(parameters):
parameters.zlims[1] += 0.01
return parameters

for edit_fn in (edit1, edit2, edit3):
def edit4(parameters):
"""edit a direct dependency that is a scalar parameter"""
parameters.element_width = parameters.element_width * 0.5
return parameters

for edit_fn in (edit1, edit2, edit3, edit4):
parameters = get_parameters(pfield_kwargs={"norm": True})
original_pfield = parameters.pfield.copy()
assert "pfield" in parameters._cache, "pfield should be cached after first access"
Expand All @@ -742,6 +749,32 @@ def test_inplace_modification_tensor_cache():
)


def test_pfield_rejects_curved_probe():
"""Pfield computation only supports linear arrays."""
parameters = get_parameters()
parameters.probe_geometry = create_curved_probe_geometry(parameters.n_el, 3e-4, 40e-3)
with pytest.raises(NotImplementedError, match="linear"):
_ = parameters.pfield


def test_pfield_infers_element_width():
"""Without an element width, the pfield uses 90% of the pitch."""
parameters = get_parameters()
kwargs = dict(
sound_speed=parameters.sound_speed,
center_frequency=parameters.center_frequency,
probe_bandwidth_percent=parameters.probe_bandwidth_percent,
probe_geometry=parameters.probe_geometry,
tx_apodizations=parameters.tx_apodizations,
grid=parameters.grid,
t0_delays=parameters.t0_delays,
)
pitch = Probe.get_pitch(parameters.probe_geometry)
inferred = ops.convert_to_numpy(compute_pfield(**kwargs))
explicit = ops.convert_to_numpy(compute_pfield(**kwargs, element_width=0.9 * pitch))
np.testing.assert_allclose(inferred, explicit)


def test_update_behaviour_and_cache_invalidation():
"""Test Parameters.update: skipping unchanged values and force invalidation."""
parameters = Parameters(**scan_args)
Expand Down
30 changes: 17 additions & 13 deletions zea/beamform/pfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ def compute_pfield(
sound_speed,
center_frequency,
probe_bandwidth_percent,
n_el,
probe_geometry,
tx_apodizations,
grid,
Expand All @@ -52,17 +51,21 @@ def compute_pfield(
):
"""Compute the pressure field for ultrasound imaging.

Only linear (and phased) arrays are supported: all elements must lie on the x-axis
and face +z.

Args:
sound_speed (float): Speed of sound in the medium.
center_frequency (float): Center frequency of the transmit pulse in Hz.
probe_bandwidth_percent (float): Bandwidth of the probe, pulse-echo 6dB
fractional bandwidth (%)
n_el (int): Number of elements in the probe.
probe_geometry (array): Geometry of the probe elements.
probe_geometry (array): Geometry of the probe elements of shape (n_el, 3).
tx_apodizations (array): Transmit apodizations of shape (n_tx, n_el).
grid (array): Grid points where the pressure field is computed
of shape (grid_size_z, grid_size_x, 3).
t0_delays (array): Transmit delays for each transmit event.
element_width (float, optional): Width of a single element in metres.
Default is None, which infers it as 90% of the pitch.
frequency_step (int, optional): Frequency step. Default is 4.
Higher is faster but less accurate.
db_thresh (float, optional): dB threshold. Default is -1.0
Expand Down Expand Up @@ -96,7 +99,16 @@ def compute_pfield(
attenuation_coef = attenuation_coef / 8.686 # convert to Np/cm/MHz
attenuation_coef = attenuation_coef / 1e6 / 1e2 # convert to Np/m/Hz

n_el = int(n_el)
# Element orientation (theta) is assumed zero and sub-elements are laid out along x.
geometry = ops.convert_to_numpy(probe_geometry)
if not (np.allclose(geometry[:, 1], 0) and np.allclose(geometry[:, 2], 0)):
raise NotImplementedError(
"Pfield computation currently only supports linear arrays, with all elements "
"at y=0 and z=0."
)
from zea.probes import _resolve_element_width

element_width = _resolve_element_width(geometry, element_width)

# cast to float32
sound_speed = ops.cast(sound_speed, "float32")
Expand All @@ -119,14 +131,6 @@ def compute_pfield(
# pulse params
num_waveforms = 1 # number of waveforms in the pulse

# array params
if element_width is None:
from zea.probes import Probe

pitch = Probe.get_pitch(probe_geometry)
kerf = 0.1 * pitch
element_width = pitch - kerf

# %------------------------------------%
# % POINT LOCATIONS, DISTANCES & GRIDS %
# %------------------------------------%
Expand All @@ -149,7 +153,7 @@ def compute_pfield(
# Centers of the transducer elements (x- and z-coordinates)
element_x = probe_geometry[:, 0]
element_z = probe_geometry[:, 2]
element_theta = ops.zeros(n_el)
element_theta = ops.zeros_like(element_x)

# Centroids of the sub-elements
seg_length = element_width / num_sub_elements
Expand Down
17 changes: 13 additions & 4 deletions zea/internal/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,18 @@
from zea.internal.core import _to_tensor, hash_elements, serialize_elements


def cache_with_dependencies(*deps):
"""Decorator to mark a method as a computed property with dependencies."""
def cache_with_dependencies(*deps, optional=()):
"""Decorator to mark a method as a computed property with dependencies.

Args:
*deps: Names of the parameters or properties the computed property needs.
optional: Names of parameters the computed property uses when set. Changing
them invalidates the cache, but the property can be computed without them.
"""

def decorator(func):
func._dependencies = deps
func._dependencies = deps + tuple(optional)
func._optional_dependencies = tuple(optional)

@functools.wraps(func)
def wrapper(self: "BaseParameters"):
Expand Down Expand Up @@ -535,8 +542,10 @@ def _find_missing_dependencies(self, name) -> set:
return missing_set

if self._is_property_with_dependencies(name):
optional = getattr(self.__class__, name).fget._optional_dependencies
for dep in self._get_dependencies(name):
missing_set |= self._find_missing_dependencies(dep) # union
if dep not in optional:
missing_set |= self._find_missing_dependencies(dep) # union
else:
missing_set.add(name)

Expand Down
5 changes: 2 additions & 3 deletions zea/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1070,12 +1070,12 @@ def tgc_gain_curve(self):
"sound_speed",
"center_frequency",
"probe_bandwidth_percent",
"n_el",
"probe_geometry",
"tx_apodizations",
"grid",
"t0_delays",
"pfield_kwargs",
optional=("element_width",),
)
def pfield(self) -> np.ndarray:
"""Compute or return the pressure field (pfield) for weighting
Expand All @@ -1086,13 +1086,12 @@ def pfield(self) -> np.ndarray:
pfield = compute_pfield(
sound_speed=self.sound_speed,
center_frequency=self.center_frequency,
n_el=self.n_el,
probe_geometry=self.probe_geometry,
tx_apodizations=self.tx_apodizations,
grid=self.grid,
t0_delays=self.t0_delays,
probe_bandwidth_percent=self.probe_bandwidth_percent,
element_width=self.element_width if hasattr(self, "element_width") else None,
element_width=self._params.get("element_width"),
**self.pfield_kwargs,
)
return ops.convert_to_numpy(pfield)
Expand Down
26 changes: 26 additions & 0 deletions zea/probes.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@
""" # noqa: E501

import numpy as np
from keras import ops

from zea.data.spec import ProbeSpec
from zea.internal.core import dict_to_tensor
Expand Down Expand Up @@ -380,6 +381,31 @@ def kerf(self) -> float | None:
return None


def _resolve_element_width(probe_geometry, element_width):
"""Return the element width, inferring it from the probe pitch when not given."""
if element_width is not None:
return element_width
Comment thread
wesselvannierop marked this conversation as resolved.
Resolved
try:
geometry = ops.convert_to_numpy(probe_geometry)
except (RuntimeError, ValueError, TypeError) as exc:
raise ValueError(
"Element width is not provided, and automatic inference is not available for "
"traced/symbolic probe geometry (for example under JAX JIT or TensorFlow graph "
"mode). Please provide `element_width` explicitly in the scan/probe parameters."
) from exc

try:
pitch = Probe.get_pitch(geometry)
except (ValueError, IndexError, AttributeError) as exc:
raise ValueError(
"Element width is not provided and automatic estimation failed from probe "
"geometry. Please provide `element_width` explicitly or ensure the probe "
"geometry is a 1-D uniformly spaced linear array. "
f"Details: {exc}"
) from exc
return pitch * 0.9 # 90% of the pitch


@probe_registry(name="verasonics_l11_4v")
class Verasonics_l11_4v(Probe):
"""Verasonics L11-4V linear array.
Expand Down
29 changes: 2 additions & 27 deletions zea/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ def simulate_rf(

n_tx = t0_delays.shape[0]

from zea.probes import _resolve_element_width

element_width = _resolve_element_width(probe_geometry, element_width)

if element_height is None:
Expand Down Expand Up @@ -297,33 +299,6 @@ def _validate_scatter_exponent(scatter_exponent):
)


def _resolve_element_width(probe_geometry, element_width):
"""Return the element width, inferring it from the probe pitch when not given."""
if element_width is not None:
return element_width
try:
geometry = ops.convert_to_numpy(probe_geometry)
except (RuntimeError, ValueError, TypeError) as exc:
raise ValueError(
"Element width is not provided, and automatic inference is not available for "
"traced/symbolic probe geometry (for example under JAX JIT or TensorFlow graph "
"mode). Please provide `element_width` explicitly in the scan/probe parameters."
) from exc

try:
from zea.probes import Probe

pitch = Probe.get_pitch(geometry)
except (ValueError, IndexError, AttributeError) as exc:
raise ValueError(
"Element width is not provided and automatic estimation failed from probe "
"geometry. Please provide `element_width` explicitly or ensure the probe "
"geometry is a 1-D uniformly spaced linear array. "
f"Details: {exc}"
) from exc
return pitch * 0.9 # 90% of the pitch


def delay2(f, tau, n_fft, sampling_frequency):
"""
Applies a delay in the frequency domain without phase wrapping.
Expand Down
3 changes: 2 additions & 1 deletion zea/simulator_time_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
from zea.func.ultrasound import directivity
from zea.simulator import (
_apply_elevation_slab,
_resolve_element_width,
_validate_scatter_exponent,
_warn_if_elevation_extent,
attenuate,
Expand Down Expand Up @@ -134,6 +133,8 @@ def simulate_rf_td(
Returns:
rf_data (array-like): The simulated RF data of shape (n_tx, n_ax, n_el, 1).
"""
from zea.probes import _resolve_element_width

element_width = _resolve_element_width(probe_geometry, element_width)
if element_height is None:
element_height = element_width
Expand Down
Loading