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
16 changes: 16 additions & 0 deletions tests/data/test_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,22 @@ def test_scan_dimension_count_consistency():
ScanSpec(**scan)


@pytest.mark.parametrize(
"field, match",
[
("t0_delays", "Transmit delays must be finite"),
("tx_apodizations", "Transmit apodizations must be finite"),
],
)
def test_scan_rejects_non_finite_transmit_parameters(field, match):
"""NaN transmit delays or apodizations are rejected."""
scan = _scan_minimal()
scan[field][0, 0] = np.nan

with pytest.raises(ValueError, match=match):
ScanSpec(**scan)


def test_inconsistent_dimension_error_groups_fields_by_size():
"""The error message groups the offending fields by their observed size."""
scan = _scan_minimal(n_tx=2)
Expand Down
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
34 changes: 34 additions & 0 deletions tests/test_pfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,37 @@ def test_pfield_not_triggered():
assert "flat_pfield" not in inputs and "pfield" not in inputs, (
"pfield was computed in default pipeline but should not have been."
)


def test_pfield_single_transmit_auto_xlims_is_finite():
"""Regression: grid points coinciding with an element must not produce NaNs.

With a single 0° plane wave and auto-derived xlims, the grid spans the aperture
exactly and starts at z=0, so some grid points land on an element position.
"""
probe = Verasonics_l11_4v()
n_el = probe.n_el
angles = np.zeros(1)
t0_delays = compute_t0_delays_planewave(
probe_geometry=probe.probe_geometry,
polar_angles=angles,
)

parameters = Parameters(
probe_geometry=probe.probe_geometry,
n_tx=1,
n_el=n_el,
zlims=(0, 40e-3),
n_ax=1024,
sampling_frequency=probe.probe_center_frequency * 4,
center_frequency=probe.probe_center_frequency,
polar_angles=angles,
t0_delays=t0_delays,
focus_distances=np.array([np.inf]),
tx_apodizations=np.ones((1, n_el)),
)

pfield = np.asarray(parameters.pfield)
assert np.all(np.isfinite(pfield)), (
f"pfield contains {np.sum(~np.isfinite(pfield))} non-finite values"
)
37 changes: 36 additions & 1 deletion tests/test_probes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

import os
import tempfile
from unittest.mock import patch

import numpy as np
import pytest

from zea.data.file import File
from zea.internal.registry import probe_registry
from zea.probes import Probe
from zea.probes import Probe, _resolve_element_width


@pytest.mark.parametrize("probe_name", probe_registry.registered_names())
Expand Down Expand Up @@ -120,6 +121,40 @@ def test_pitch_derived_from_probe_geometry():
_ = probe.pitch


def test_pitch_positive_for_descending_geometry():
"""Elements ordered by descending x still give a positive pitch."""
pg = np.zeros((4, 3), dtype=np.float32)
pg[:, 0] = np.arange(4)[::-1] * 0.3e-3
assert Probe.get_pitch(pg) == pytest.approx(0.3e-3, rel=1e-4)


def test_pitch_rejects_coinciding_elements():
"""Coinciding element positions have no pitch."""
with pytest.raises(ValueError, match="element positions coincide"):
Probe.get_pitch(np.zeros((4, 3), dtype=np.float32))


def test_resolve_element_width():
"""An explicit element width is returned as is; otherwise 90% of the pitch."""
pg = np.zeros((4, 3), dtype=np.float32)
pg[:, 0] = np.arange(4) * 0.3e-3
assert _resolve_element_width(pg, 1e-3) == 1e-3
assert _resolve_element_width(pg, None) == pytest.approx(0.27e-3, rel=1e-4)


def test_resolve_element_width_invalid_geometry():
"""Inference from a geometry without a pitch raises a helpful error."""
with pytest.raises(ValueError, match="automatic estimation failed"):
_resolve_element_width(np.zeros((1, 3), dtype=np.float32), None)


def test_resolve_element_width_unconvertible_geometry():
"""Inference from geometry that cannot be converted to numpy raises a helpful error."""
with patch("zea.probes.ops.convert_to_numpy", side_effect=RuntimeError("traced")):
with pytest.raises(ValueError, match="traced/symbolic probe geometry"):
_resolve_element_width(np.zeros((4, 3), dtype=np.float32), None)


def test_verasonics_c5_2v_curved_probe():
"""The C5-2v built-in is a 128-element convex arc (curved, y=0, facing +z)."""
from zea.probes import create_curved_probe_geometry
Expand Down
55 changes: 53 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,50 @@ 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


@pytest.mark.parametrize("field", ["t0_delays", "tx_apodizations"])
def test_pfield_rejects_non_finite_transmit_parameters(field):
"""NaN transmit delays or apodizations are rejected rather than silently zeroed."""
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=np.array(parameters.tx_apodizations),
grid=parameters.grid,
t0_delays=np.array(parameters.t0_delays),
)
kwargs[field][0, 0] = np.nan
with pytest.raises(ValueError, match=f"`{field}` must be finite"):
compute_pfield(**kwargs)


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
Loading
Loading