Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
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
103 changes: 61 additions & 42 deletions zea/beamform/pfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ def compute_pfield(
sound_speed,
center_frequency,
probe_bandwidth_percent,
n_el,
probe_geometry,
tx_apodizations,
grid,
t0_delays,
element_width=None,
frequency_step=4,
db_thresh=-1.0,
downsample=10,
Expand All @@ -51,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 All @@ -71,10 +75,11 @@ def compute_pfield(
downmix (int, optional): Downmixing the frequency to facilitate a smaller grid.
Default is 4. Higher requires lower number of grid points but is less accurate.
alpha (float, optional): Exponent to 'sharpen or smooth' the weighting. Higher is sharper.
Only works when norm is True. Default is 1.
Default is 1.
percentile (int, optional): minimum percentile threshold to keep in the weighting.
Only works when norm is True. Higher is more aggressive. Default is 10.
norm (bool, optional): per pixel normalization (True) or unnormalized (False)
Higher is more aggressive. Default is 10.
norm (bool, optional): per pixel normalization over the transmit axis (True)
or unnormalized (False).
point_batch_size (int, optional): Batch size for the pressure field computation.
Higher is slightly faster, but requires more memory. Default is 2048.
interpolation (str, optional): Interpolation used to resize the pressure
Expand All @@ -94,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 @@ -107,13 +121,11 @@ def compute_pfield(
probe_geometry = ops.convert_to_tensor(probe_geometry, dtype="float32")
grid_x = ops.convert_to_tensor(grid[:, :, 0], dtype="float32")
grid_z = ops.convert_to_tensor(grid[:, :, 2], dtype="float32")
for name, value in (("t0_delays", t0_delays), ("tx_apodizations", tx_apodizations)):
if not np.all(np.isfinite(ops.convert_to_numpy(value))):
raise ValueError(f"`{name}` must be finite to compute the pressure field.")
t0_delays = ops.convert_to_tensor(t0_delays, dtype="float32")
tx_apodizations = ops.convert_to_tensor(tx_apodizations, dtype="float32")

# formatting
t0_delays = ops.where(ops.isnan(t0_delays), 0, t0_delays)
tx_apodizations = ops.where(ops.isnan(tx_apodizations), 0, tx_apodizations)
tx_apodizations = ops.cast(tx_apodizations, "complex64")
tx_apodizations = ops.convert_to_tensor(tx_apodizations, dtype="complex64")
Comment thread
wesselvannierop marked this conversation as resolved.
Resolved

# probe params
fc_original = center_frequency
Expand All @@ -122,12 +134,6 @@ def compute_pfield(
# pulse params
num_waveforms = 1 # number of waveforms in the pulse

# array params
pitch = ops.abs(probe_geometry[1, 0] - probe_geometry[0, 0]) # element pitch

kerf = 0.1 * pitch # for now this is hardcoded
element_width = pitch - kerf

# %------------------------------------%
# % POINT LOCATIONS, DISTANCES & GRIDS %
# %------------------------------------%
Expand All @@ -148,9 +154,9 @@ def compute_pfield(
grid_z = ops.reshape(grid_z, (-1,))

# Centers of the transducer elements (x- and z-coordinates)
element_x = (ops.arange(0.0, n_el) - (n_el - 1) / 2) * pitch
element_z = ops.zeros(n_el)
element_theta = ops.zeros(n_el)
element_x = probe_geometry[:, 0]
element_z = probe_geometry[:, 2]
element_theta = ops.zeros_like(element_x)

# Centroids of the sub-elements
seg_length = element_width / num_sub_elements
Expand Down Expand Up @@ -205,8 +211,9 @@ def probe_spectrum(f):
denom = (bandwidth / 2) / (ops.log(2) ** (1 / p_shape))
# Raise the normalized difference to the power of p_shape
exponent = (freq_diff / denom) ** p_shape
# Apply the negative sign and exponential
return ops.cast(ops.exp(-exponent), "complex64")
# The bandwidth is a pulse-echo (two-way) bandwidth; the one-way transmit
# response is the square root of the two-way response, hence the factor 1/2.
return ops.cast(ops.exp(-exponent / 2), "complex64")

# The frequency response is a pulse-echo (transmit + receive) response.
# The spectrum of the pulse (pulse_spectrum) will be then multiplied
Expand Down Expand Up @@ -307,6 +314,14 @@ def scan_fn(carry, k):
# Zero out pressure behind the transducer (z < 0)
pressure_squared = ops.where(grid_z[:, None] < 0, 0, pressure_squared)

# Mean over the retained frequency samples, not their sum: the scan accumulates
# |P(f_k)|^2 with no df factor, so a sum scales with the sample count, i.e. with
# 1/freq_step -- which is set above from max(t0_delays) and so depends on which
# transmits are in the stack. The mean keeps the field a true RMS over the
# retained band, and comparable across transmit subsets (~2e-3 apart, from the
# differing grids). No effect when norm=True: a global factor cancels below.
pressure_squared = pressure_squared / ops.cast(ops.shape(freq)[0], "float32")

# RMS acoustic pressure, reshaped to (n_tx, grid_size_z, grid_size_x)
pressure = ops.transpose(ops.sqrt(pressure_squared), (1, 0))
pressure = ops.reshape(pressure, (-1, *size_downsampled))
Expand All @@ -316,28 +331,23 @@ def scan_fn(carry, k):
ops.image.resize(pressure[..., None], size_orig, interpolation=interpolation), axis=-1
)

if norm:
normalized_pfield = normalize_pressure_field(p_arr, alpha=alpha, percentile=percentile)
else:
normalized_pfield = p_arr
p_arr = shape_pressure_field(p_arr, alpha=alpha, percentile=percentile)

return normalized_pfield
return normalize_pressure_field(p_arr) if norm else p_arr


def normalize_pressure_field(pfield, alpha: float = 1.0, percentile: float = 10.0):
"""
Normalize the input array of intensities by zeroing out values below a given percentile.
def shape_pressure_field(pfield, alpha: float = 1.0, percentile: float = 10.0):
"""Per-transmit shaping of a pressure field: floor the dim tail, sharpen the beam.

Args:
pfield (array): The unnormalized pressure field array
of shape (n_tx, grid_size_z, grid_size_x).
pfield (array): Pressure field of shape (n_tx, grid_size_z, grid_size_x).
alpha (float, optional): Exponent to 'sharpen or smooth' the weighting.
Higher values result in sharper weighting. Default is 1.0.
percentile (int, optional): minimum percentile threshold to keep in the weighting.
Higher is more aggressive. Default is 10.
Higher values result in sharper weighting. Default is 1.0 (no change).
percentile (int, optional): minimum percentile threshold to keep in the
weighting, per transmit. Higher is more aggressive. Default is 10.

Returns:
ops.array: Normalized intensity array.
ops.array: Shaped pressure field, same shape.
"""
# Convert percentile to quantile (0–1 range)
q = percentile / 100.0
Expand All @@ -349,12 +359,21 @@ def normalize_pressure_field(pfield, alpha: float = 1.0, percentile: float = 10.
pfield = ops.where(pfield < threshold, 0, pfield)

# Sharpen the beam
pfield = ops.power(pfield, alpha)
return ops.power(pfield, alpha)


def normalize_pressure_field(pfield):
"""Normalize a pressure field per pixel, over the transmit axis.

# Normalize over transmit events (axis=0)
normalized_pfield = pfield / (keras.config.epsilon() + ops.sum(pfield, axis=0, keepdims=True))
Turns the field into compounding weights that sum to 1 at every pixel.

return normalized_pfield
Args:
pfield (array): Pressure field of shape (n_tx, grid_size_z, grid_size_x).

Returns:
ops.array: Normalized intensity array.
"""
return pfield / (keras.config.epsilon() + ops.sum(pfield, axis=0, keepdims=True))


def _pfield_freq_step(
Expand Down
4 changes: 4 additions & 0 deletions zea/data/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -1965,8 +1965,12 @@ def __post_init__(self):
raise ValueError(
f"Demodulation frequency cannot be negative, got {self.demodulation_frequency}"
)
if not np.all(np.isfinite(self.t0_delays)):
raise ValueError(f"Transmit delays must be finite, got {self.t0_delays}")
if np.any(self.t0_delays < 0):
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
raise ValueError(f"Transmit delays cannot be negative, got {self.t0_delays}")
if not np.all(np.isfinite(self.tx_apodizations)):
raise ValueError(f"Transmit apodizations must be finite, got {self.tx_apodizations}")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if np.any(np.logical_and(self.focus_distances >= 1, self.focus_distances != np.inf)):
log.warning(
"Focus distances greater than or equal to 1 meter may be unusually large. "
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
4 changes: 2 additions & 2 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,12 +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._params.get("element_width"),
**self.pfield_kwargs,
)
return ops.convert_to_numpy(pfield)
Expand Down
Loading
Loading