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
27 changes: 26 additions & 1 deletion tests/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from zea.func.ultrasound import (
channels_to_complex,
complex_to_channels,
compute_time_to_peak,
compute_time_to_peak_stack,
construct_acquisition_from_synthetic_aperture,
decode_hadamard,
Expand Down Expand Up @@ -973,10 +974,34 @@ def test_compute_time_to_peak():
center_frequencies = np.array([center_frequency0, center_frequency1])
waveforms = np.array([waveform0, waveform1])

t_peak = compute_time_to_peak_stack(waveforms, center_frequencies, 250e6)
t_peak = compute_time_to_peak(waveforms, center_frequencies, 250e6)

assert np.allclose(t_peak, 1e-6, atol=1e-8), f"t_peak should be close to 1e-6, got {t_peak}"

# With a sine carrier the largest raw sample sits a quarter period away from the
# envelope peak, so this catches taking argmax(|waveform|) instead of the envelope.
waveform_sin = np.exp(-((t - 1e-6) ** 2) / (2 * (0.2e-6) ** 2)) * np.sin(
2 * np.pi * center_frequency0 * (t - 1e-6)
)
t_peak = compute_time_to_peak(waveform_sin, center_frequency0, 250e6)
assert np.allclose(t_peak, 1e-6, atol=1e-8), f"t_peak should be close to 1e-6, got {t_peak}"

# Deprecated alias still works
t_peak = compute_time_to_peak_stack(waveforms, center_frequencies, 250e6)
assert np.allclose(t_peak, 1e-6, atol=1e-8)

# A size-1 frequency acts as a scalar, both for one waveform and for a stack
t_peak = compute_time_to_peak(waveform0, np.array([center_frequency0]), 250e6)
assert np.shape(t_peak) == ()
t_peak = compute_time_to_peak(waveforms, np.array([center_frequency0]), 250e6)
assert np.shape(t_peak) == (2,)

# A frequency per waveform must match the number of waveforms
with pytest.raises(ValueError, match="center_frequency"):
compute_time_to_peak(waveform0, center_frequencies, 250e6)
with pytest.raises(ValueError, match="center_frequency"):
compute_time_to_peak(np.stack([waveform0] * 3), center_frequencies, 250e6)


# Only the beamformers zea.ops defines itself. A model-backed beamformer (such as
# "able", registered by zea.models.able) is not comparable across backends: its
Expand Down
54 changes: 54 additions & 0 deletions tests/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -828,3 +828,57 @@ def test_mapping_protocol(dummy_params):

del dummy_params["custom"]
assert "custom" not in dummy_params


class DummySubParameters(DummyParameters):
"""Subclass without its own computed properties, like the deprecated Scan."""


def test_subclass_invalidates_inherited_properties():
"""Dependents must be found through the MRO, not only in the subclass itself."""
assert DummySubParameters._find_all_dependents(
"param1"
) == DummyParameters._find_all_dependents("param1")

params = DummySubParameters(param1=5, param2=10, param3=1500.0, param4=5e6)
assert params.computed2[0] == 1
params.param1 = 3
assert params.computed1[0].shape == (3, 10)
params.computed2
assert params._computed2_count == 2


def test_setattr_looks_up_dependents_once(dummy_params, monkeypatch):
"""The transitive dependent set is popped in one pass, not re-walked per dependent."""
calls = []
original = DummyParameters._find_all_dependents

def counting(target):
calls.append(target)
return original(target)

monkeypatch.setattr(DummyParameters, "_find_all_dependents", staticmethod(counting))
dummy_params.computed2 # populate computed1 and computed2
dummy_params.param1 = 3
assert calls == ["param1"]
assert "computed1" not in dummy_params._cache
assert "computed2" not in dummy_params._cache


def test_dependents_cache_is_per_class():
"""The memoised dependency graph lives on each class, so it is freed with the class."""
import gc
import weakref

class Temporary(DummyParameters):
pass

params = Temporary(param1=5, param2=10, param3=1500.0, param4=5e6)
params.param1 = 3 # populate the cache
assert "param1" in Temporary.__dict__["_dependents_cache"]
assert Temporary._dependents_cache is not DummyParameters._dependents_cache

ref = weakref.ref(Temporary)
del Temporary, params
gc.collect()
assert ref() is None
66 changes: 41 additions & 25 deletions zea/func/ultrasound.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,42 +521,39 @@ def demodulate(data, demodulation_frequency, sampling_frequency, axis=-3, pad_fa
return iq_data_two_channel


def compute_time_to_peak_stack(waveforms, center_frequencies, waveform_sampling_frequency=250e6):
"""Compute the time of the peak of each waveform in a stack of waveforms.

Args:
waveforms (ndarray): The waveforms of shape (n_waveforms, n_samples).
center_frequencies (ndarray): The center frequencies of the waveforms in Hz of shape
(n_waveforms,) or a scalar if all waveforms have the same center frequency.
waveform_sampling_frequency (float): The sampling frequency of the waveforms in Hz.

Returns:
ndarray: The time to peak for each waveform in seconds.
"""
t_peak = []
center_frequencies = center_frequencies * ops.ones((waveforms.shape[0],))
for waveform, center_frequency in zip(waveforms, center_frequencies):
t_peak.append(compute_time_to_peak(waveform, center_frequency, waveform_sampling_frequency))
return ops.stack(t_peak)


def compute_time_to_peak(waveform, center_frequency, waveform_sampling_frequency=250e6):
"""Compute the time of the peak of the waveform.
"""Compute the time of the peak of the envelope of a waveform or a stack of waveforms.

Args:
waveform (ndarray): The waveform of shape (n_samples).
center_frequency (float): The center frequency of the waveform in Hz.
waveform (ndarray): The waveform of shape (n_samples), or a stack of them of
shape (n_waveforms, n_samples).
center_frequency (float or ndarray): The center frequency in Hz, either a scalar
(or size-1 array) or, for a stack, one per waveform of shape (n_waveforms,).
waveform_sampling_frequency (float): The sampling frequency of the waveform in Hz.

Returns:
float: The time to peak for the waveform in seconds.
float or ndarray: The time to peak in seconds, a scalar for a single waveform
or of shape (n_waveforms,) for a stack.
"""
n_samples = waveform.shape[0]
waveform = ops.convert_to_tensor(waveform)
n_samples = waveform.shape[-1]
if n_samples == 0:
raise ValueError("Waveform has zero samples.")

center_frequency = ops.convert_to_tensor(center_frequency)
batch_shape = tuple(waveform.shape[:-1])
if ops.size(center_frequency) == 1:
center_frequency = ops.reshape(center_frequency, ())
elif tuple(center_frequency.shape) != batch_shape:
raise ValueError(
f"center_frequency must be a scalar or have shape {batch_shape} to match the "
f"waveforms of shape {tuple(waveform.shape)}, got {tuple(center_frequency.shape)}."
)
# Trailing axes for the sample and channel axes of `waveform[..., None]`
center_frequency = ops.reshape(center_frequency, tuple(center_frequency.shape) + (1, 1))

waveforms_iq_complex_channels = demodulate(
waveform[..., None], center_frequency, waveform_sampling_frequency, axis=-1
waveform[..., None], center_frequency, waveform_sampling_frequency, axis=-2
)
waveforms_iq_complex = ops.view_as_complex(waveforms_iq_complex_channels)
envelope = ops.abs(waveforms_iq_complex)
Expand All @@ -565,6 +562,25 @@ def compute_time_to_peak(waveform, center_frequency, waveform_sampling_frequency
return t_peak


@deprecated(replacement="zea.func.ultrasound.compute_time_to_peak")
def compute_time_to_peak_stack(waveforms, center_frequencies, waveform_sampling_frequency=250e6):
"""Compute the time of the peak of each waveform in a stack of waveforms.

.. deprecated::
Use :func:`compute_time_to_peak`, which also accepts a stack of waveforms.

Args:
waveforms (ndarray): The waveforms of shape (n_waveforms, n_samples).
center_frequencies (ndarray): The center frequencies of the waveforms in Hz of shape
(n_waveforms,) or a scalar if all waveforms have the same center frequency.
waveform_sampling_frequency (float): The sampling frequency of the waveforms in Hz.

Returns:
ndarray: The time to peak for each waveform in seconds.
"""
return compute_time_to_peak(waveforms, center_frequencies, waveform_sampling_frequency)


def channels_to_analytic(data, axis):
"""Return the analytic signal (complex) from RF (``n_ch == 1``) or from
two-channel I/Q (``n_ch == 2``) data.
Expand Down
51 changes: 39 additions & 12 deletions zea/internal/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,16 @@ class BaseParameters:
# Subclasses must populate this; an empty mapping means "not defined".
VALID_PARAMS: ClassVar[dict[str, dict[str, Any]]] = {}

# Memoised `_find_all_dependents` results: the dependency graph is fixed per class.
# Properties patched onto a class later are still recomputed correctly, because the
# cached-property wrapper also checks a hash of its leaf parameters on every access.
_dependents_cache: ClassVar[dict[str, frozenset[str]]] = {}

def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
# Own dict per class, so it is freed together with the class
cls._dependents_cache = {}

def __init__(self, **kwargs):
super().__init__()

Expand Down Expand Up @@ -476,39 +486,56 @@ def _check_validity_of_dependencies(cls):
f"{cls.__name__} class definition."
)

def _find_all_dependents(self, target, seen=None):
@classmethod
def _find_all_dependents(cls, target):
"""
Find all computed properties that depend (directly or indirectly) on the target parameter
with a global search. Returns a set of property names that depend on the target.
with a global search. Returns a frozenset of property names that depend on the target.

Memoised per class in `_dependents_cache`: every `__setattr__` invalidates through
here, and the uncached search rescans the class for each node -- which made `copy()`
of a full `Parameters` cost about a second.
"""
cache = cls._dependents_cache
if target not in cache:
cache[target] = frozenset(cls._collect_dependents(target, set()))
return cache[target]

@classmethod
def _collect_dependents(cls, target, seen):
dependents = set()
if seen is None:
seen = set()
if target in seen:
return dependents
seen.add(target)
for name in self.__class__.__dict__:
if self._is_property_with_dependencies(name):
if target in self._get_dependencies(name):
# Walk the MRO so subclasses (e.g. the deprecated Scan) see inherited properties
names = dict.fromkeys(name for klass in cls.__mro__ for name in vars(klass))
for name in names:
if cls._is_property_with_dependencies(name):
if target in cls._get_dependencies(name):
dependents.add(name)
# Recursively add dependents of this property
dependents |= self._find_all_dependents(name, seen)
dependents |= cls._collect_dependents(name, seen)
return dependents

def _invalidate(self, key):
"""Invalidate a specific cached computed property and its dependencies."""
self._cache.pop(key, None)
self._dependency_versions.pop(key, None)
self._tensor_cache.pop(key, None)
self._drop_cached(key)
self._invalidate_dependents(key)

def _invalidate_dependents(self, changed_key):
"""
Invalidate all cached computed properties that (directly or indirectly)
depend on the changed_key.
"""
# The dependents are already transitive, so no need to recurse per dependent
for key in self._find_all_dependents(changed_key):
self._invalidate(key)
self._drop_cached(key)

def _drop_cached(self, key):
"""Drop the cached value of a single key, without touching its dependents."""
self._cache.pop(key, None)
self._dependency_versions.pop(key, None)
self._tensor_cache.pop(key, None)

def _current_dependency_hash(self, key) -> str:
"""Compute a hash representing the current state of the dependencies of key.
Expand Down
6 changes: 3 additions & 3 deletions zea/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
)
from zea.data.spec import ProbeSpec, ScanSpec
from zea.display import compute_scan_convert_2d_coordinates
from zea.func.ultrasound import compute_time_to_peak_stack
from zea.func.ultrasound import compute_time_to_peak
from zea.internal.parameters import BaseParameters, MissingDependencyError, cache_with_dependencies
from zea.internal.utils import deprecated
from zea.probes import Probe, fit_curved_probe_radius
Expand Down Expand Up @@ -1032,15 +1032,15 @@ def t_peak(self):

If not set explicitly and ``waveforms_two_way`` (the two-way,
pulse-echo transmit waveform) is available, this is estimated from it
via :func:`~zea.func.ultrasound.compute_time_to_peak_stack`. Otherwise
via :func:`~zea.func.ultrasound.compute_time_to_peak`. Otherwise
it defaults to ``1 / center_frequency``.
"""
t_peak = self._params.get("t_peak")
if t_peak is None:
waveforms = self._params.get("waveforms_two_way")
if waveforms is not None:
t_peak = ops.convert_to_numpy(
compute_time_to_peak_stack(waveforms, self.center_frequency)
compute_time_to_peak(waveforms, self.center_frequency)
)
else:
t_peak = np.full(self.n_tx_total, 1 / self.center_frequency)
Expand Down
Loading