From a080047bff70611b6e6211f4bba0b162f46a3b20 Mon Sep 17 00:00:00 2001 From: Charles Guan <3221512+charlesbmi@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:44:52 -0700 Subject: [PATCH 1/3] Add runtime array validation Co-authored-by: Cursor --- pyproject.toml | 2 +- src/mach/geometry.py | 5 ++++- src/mach/io/must.py | 12 ++++++++++-- src/mach/wavefront.py | 6 +++++- tests/io/test_must.py | 23 ++++++++++++++++------- tests/test_geometry.py | 17 +++++++++-------- tests/test_wavefront.py | 38 ++++++++++++++++++++++++++++---------- uv.lock | 6 ++---- 8 files changed, 75 insertions(+), 34 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f0e79f7..8ab0e68 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ classifiers = [ ] dependencies = [ "array-api-compat>=1.11.0", + "beartype>=0.21.0", "einops>=0.8.0", "jaxtyping>=0.3.4", ] @@ -70,7 +71,6 @@ dev = [ test = [ "array-api-extra>=0.10.0", "array-api-strict>=2.0.0", - "beartype>=0.21.0", "h5py>=3.12.1", "matplotlib>=3.9.4", "numpy>=2.0.2", diff --git a/src/mach/geometry.py b/src/mach/geometry.py index df6b9ca..23b1107 100644 --- a/src/mach/geometry.py +++ b/src/mach/geometry.py @@ -23,11 +23,13 @@ import numbers import types -from jaxtyping import Real +from beartype import beartype +from jaxtyping import Real, jaxtyped from mach._array_api import Array, _ArrayNamespace, array_namespace +@jaxtyped(typechecker=beartype) def ultrasound_angles_to_cartesian( azimuth_rad: Real[Array, " *angles"] | float | int, elevation_rad: Real[Array, " *angles"] | float | int, @@ -86,6 +88,7 @@ def ultrasound_angles_to_cartesian( return result +@jaxtyped(typechecker=beartype) def spherical_to_cartesian( theta_rad: Real[Array, " *angles"] | float | int, phi_rad: Real[Array, " *angles"] | float | int, diff --git a/src/mach/io/must.py b/src/mach/io/must.py index ef64a94..89bb863 100644 --- a/src/mach/io/must.py +++ b/src/mach/io/must.py @@ -4,11 +4,13 @@ import numpy as np import scipy.io -from jaxtyping import Float +from beartype import beartype +from jaxtyping import Float, jaxtyped from mach.io.utils import cached_download +@jaxtyped(typechecker=beartype) def download_pymust_doppler_data() -> dict: """Download and load the PyMUST PWI_disk.mat test data. @@ -29,6 +31,7 @@ def download_pymust_doppler_data() -> dict: return mat_data +@jaxtyped(typechecker=beartype) def extract_pymust_params(mat_data: dict) -> dict: """Extract PyMUST parameters from loaded MATLAB data. @@ -68,7 +71,11 @@ def extract_pymust_params(mat_data: dict) -> dict: return param -def linear_probe_positions(n_elements: int, pitch: float) -> Float[np.ndarray, "{n_elements} xyz=3"]: +@jaxtyped(typechecker=beartype) +def linear_probe_positions( + n_elements: int | np.integer, + pitch: float | np.floating, +) -> Float[np.ndarray, "{n_elements} xyz=3"]: """Generate element positions for a linear array. Args: @@ -88,6 +95,7 @@ def linear_probe_positions(n_elements: int, pitch: float) -> Float[np.ndarray, " return positions +@jaxtyped(typechecker=beartype) def scan_grid(*axes: np.ndarray) -> Float[np.ndarray, "points {len(axes)}"]: """Return a flattened meshgrid of the given axes. diff --git a/src/mach/wavefront.py b/src/mach/wavefront.py index da9ac92..1609f5b 100644 --- a/src/mach/wavefront.py +++ b/src/mach/wavefront.py @@ -2,7 +2,8 @@ from typing import NamedTuple -from jaxtyping import Float, Real +from beartype import beartype +from jaxtyping import Float, Real, jaxtyped from mach._array_api import Array, array_namespace, vector_norm @@ -21,6 +22,7 @@ class _ApertureGeometry(NamedTuple): elevation_half_width_m: Array +@jaxtyped(typechecker=beartype) def plane( origin_m: Real[Array, "xyz=3"], points_m: Real[Array, "*points xyz=3"], @@ -298,6 +300,7 @@ def _unified_spherical_bounded( ) +@jaxtyped(typechecker=beartype) def spherical( origin_m: Real[Array, "xyz=3"], points_m: Real[Array, "*points xyz=3"], @@ -372,6 +375,7 @@ def spherical( ) +@jaxtyped(typechecker=beartype) def earliest_arrival( element_positions_m: Real[Array, "elements xyz=3"], element_delays_s: Real[Array, " elements"], diff --git a/tests/io/test_must.py b/tests/io/test_must.py index 43bbb84..82993be 100644 --- a/tests/io/test_must.py +++ b/tests/io/test_must.py @@ -5,8 +5,7 @@ import numpy as np import pytest -from beartype import beartype -from jaxtyping import jaxtyped +from jaxtyping import TypeCheckError from mach.io.must import ( download_pymust_doppler_data, @@ -33,7 +32,7 @@ def test_download_pymust_doppler_data(pymust_doppler_data): @pytest.mark.no_cuda def test_extract_pymust_params(pymust_doppler_data): """Test extracting PyMUST parameters.""" - params = jaxtyped(extract_pymust_params, typechecker=beartype)(pymust_doppler_data) + params = extract_pymust_params(pymust_doppler_data) assert params is not None assert len(params) > 0 assert "Nelements" in params @@ -44,7 +43,7 @@ def test_extract_pymust_params(pymust_doppler_data): def test_linear_probe_positions(): """Test generating linear probe positions.""" num_elements = 10 - positions = jaxtyped(linear_probe_positions, typechecker=beartype)(10, 0.1) + positions = linear_probe_positions(10, 0.1) assert isinstance(positions, np.ndarray) assert positions.shape == (num_elements, 3) np.testing.assert_allclose(positions.mean(axis=0), np.zeros(3), atol=1e-8) @@ -56,8 +55,18 @@ def test_scan_grid(): num_x = 3 num_y = 4 num_z = 5 - grid = jaxtyped(scan_grid, typechecker=beartype)( - np.linspace(0, 1, num_x), np.linspace(0, 1, num_y), np.linspace(0, 1, num_z) - ) + grid = scan_grid(np.linspace(0, 1, num_x), np.linspace(0, 1, num_y), np.linspace(0, 1, num_z)) assert isinstance(grid, np.ndarray) assert grid.shape == (num_x * num_y * num_z, 3) + + +@pytest.mark.no_cuda +def test_linear_probe_positions_rejects_noninteger_count(): + with pytest.raises(TypeCheckError): + linear_probe_positions(10.0, 0.1) + + +@pytest.mark.no_cuda +def test_scan_grid_rejects_nonarray_axis(): + with pytest.raises(TypeCheckError): + scan_grid(np.linspace(0, 1, 3), [0.0, 1.0]) diff --git a/tests/test_geometry.py b/tests/test_geometry.py index 76ba217..55be01d 100644 --- a/tests/test_geometry.py +++ b/tests/test_geometry.py @@ -4,15 +4,9 @@ import array_api_strict as xp import pytest -from beartype import beartype -from jaxtyping import jaxtyped +from jaxtyping import TypeCheckError -from mach.geometry import spherical_to_cartesian as spherical_unchecked -from mach.geometry import ultrasound_angles_to_cartesian as az_el_unchecked - -# type-check functions during unit tests -ultrasound_angles_to_cartesian = jaxtyped(typechecker=beartype)(az_el_unchecked) -spherical_to_cartesian = jaxtyped(typechecker=beartype)(spherical_unchecked) +from mach.geometry import spherical_to_cartesian, ultrasound_angles_to_cartesian @pytest.mark.no_cuda @@ -166,6 +160,13 @@ def test_mixed_scalar_array_inputs(self): assert float(result[0, 2]) == pytest.approx(1.0) # First point z-coordinate assert float(result[1, 0]) == pytest.approx(1.0) # Second point x-coordinate + def test_rejects_mismatched_angle_shapes(self): + with pytest.raises(TypeCheckError): + ultrasound_angles_to_cartesian( + xp.asarray([0.0, 0.1]), + xp.asarray([0.0, 0.1, 0.2]), + ) + @pytest.mark.no_cuda class TestSphericalToCartesian: diff --git a/tests/test_wavefront.py b/tests/test_wavefront.py index 1a8c231..8913b86 100644 --- a/tests/test_wavefront.py +++ b/tests/test_wavefront.py @@ -5,17 +5,9 @@ import array_api_strict as xp import pytest from array_api_extra.testing import assert_close -from beartype import beartype -from jaxtyping import jaxtyped +from jaxtyping import TypeCheckError -from mach.wavefront import earliest_arrival as earliest_arrival_unchecked -from mach.wavefront import plane as plane_unchecked -from mach.wavefront import spherical as spherical_unchecked - -# type-check functions during unit tests -earliest_arrival = jaxtyped(typechecker=beartype)(earliest_arrival_unchecked) -plane = jaxtyped(typechecker=beartype)(plane_unchecked) -spherical = jaxtyped(typechecker=beartype)(spherical_unchecked) +from mach.wavefront import earliest_arrival, plane, spherical @pytest.mark.no_cuda @@ -97,6 +89,14 @@ def test_non_unit_direction_raises_error(self): with pytest.raises(ValueError, match="direction must be a unit vector"): plane(origin, points, direction) + def test_rejects_non_xyz_origin(self): + with pytest.raises(TypeCheckError): + plane( + xp.asarray([0.0, 0.0]), + xp.asarray([[0.0, 0.0, 1.0]]), + xp.asarray([0.0, 0.0, 1.0]), + ) + def test_different_origins(self): """Test with non-zero origin.""" origin = xp.asarray([2.0, 3.0, 1.0]) @@ -482,3 +482,21 @@ def test_rejects_nonpositive_sound_speed(self): xp.asarray([[0.0, 0.0, 1.0]]), sound_speed_m_s=0.0, ) + + def test_rejects_non_xyz_element_positions(self): + with pytest.raises(TypeCheckError): + earliest_arrival( + xp.asarray([[0.0, 0.0]]), + xp.asarray([0.0]), + xp.asarray([[0.0, 0.0, 1.0]]), + sound_speed_m_s=1540.0, + ) + + def test_rejects_mismatched_element_counts(self): + with pytest.raises(TypeCheckError): + earliest_arrival( + xp.asarray([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]), + xp.asarray([0.0]), + xp.asarray([[0.0, 0.0, 1.0]]), + sound_speed_m_s=1540.0, + ) diff --git a/uv.lock b/uv.lock index 11d62e0..6e5d32c 100644 --- a/uv.lock +++ b/uv.lock @@ -1623,6 +1623,7 @@ source = { editable = "." } default-groups = "all" dependencies = [ { name = "array-api-compat" }, + { name = "beartype" }, { name = "einops" }, { name = "jaxtyping" }, ] @@ -1703,7 +1704,6 @@ docs = [ profile = [ { name = "array-api-extra" }, { name = "array-api-strict" }, - { name = "beartype" }, { name = "h5py" }, { name = "matplotlib" }, { name = "numpy" }, @@ -1720,7 +1720,6 @@ profile = [ test = [ { name = "array-api-extra" }, { name = "array-api-strict" }, - { name = "beartype" }, { name = "h5py" }, { name = "matplotlib" }, { name = "numpy" }, @@ -1737,6 +1736,7 @@ test = [ [package.metadata] requires-dist = [ { name = "array-api-compat", specifier = ">=1.11.0" }, + { name = "beartype", specifier = ">=0.21.0" }, { name = "colorcet", marker = "extra == 'vis'", specifier = ">=3.1.0" }, { name = "cupy-cuda12x", marker = "extra == 'all'", specifier = ">=14.0.0" }, { name = "einops", specifier = ">=0.8.0" }, @@ -1798,7 +1798,6 @@ docs = [ profile = [ { name = "array-api-extra", specifier = ">=0.10.0" }, { name = "array-api-strict", specifier = ">=2.0.0" }, - { name = "beartype", specifier = ">=0.21.0" }, { name = "h5py", specifier = ">=3.12.1" }, { name = "matplotlib", specifier = ">=3.9.4" }, { name = "numpy", specifier = ">=2.0.2" }, @@ -1815,7 +1814,6 @@ profile = [ test = [ { name = "array-api-extra", specifier = ">=0.10.0" }, { name = "array-api-strict", specifier = ">=2.0.0" }, - { name = "beartype", specifier = ">=0.21.0" }, { name = "h5py", specifier = ">=3.12.1" }, { name = "matplotlib", specifier = ">=3.9.4" }, { name = "numpy", specifier = ">=2.0.2" }, From 0fbde627787df20e6b7613e034a8fe7439b0fa5a Mon Sep 17 00:00:00 2001 From: Charles Guan Date: Thu, 15 Oct 2026 21:30:17 -0700 Subject: [PATCH 2/3] Don't need io/must.py jaxtyping --- src/mach/io/must.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/mach/io/must.py b/src/mach/io/must.py index 89bb863..0706827 100644 --- a/src/mach/io/must.py +++ b/src/mach/io/must.py @@ -4,13 +4,10 @@ import numpy as np import scipy.io -from beartype import beartype -from jaxtyping import Float, jaxtyped from mach.io.utils import cached_download -@jaxtyped(typechecker=beartype) def download_pymust_doppler_data() -> dict: """Download and load the PyMUST PWI_disk.mat test data. @@ -31,7 +28,6 @@ def download_pymust_doppler_data() -> dict: return mat_data -@jaxtyped(typechecker=beartype) def extract_pymust_params(mat_data: dict) -> dict: """Extract PyMUST parameters from loaded MATLAB data. @@ -71,10 +67,9 @@ def extract_pymust_params(mat_data: dict) -> dict: return param -@jaxtyped(typechecker=beartype) def linear_probe_positions( - n_elements: int | np.integer, - pitch: float | np.floating, + n_elements: int, + pitch: float | int, ) -> Float[np.ndarray, "{n_elements} xyz=3"]: """Generate element positions for a linear array. @@ -95,7 +90,6 @@ def linear_probe_positions( return positions -@jaxtyped(typechecker=beartype) def scan_grid(*axes: np.ndarray) -> Float[np.ndarray, "points {len(axes)}"]: """Return a flattened meshgrid of the given axes. From add4bb7eda8da16ca5b5a6c944d38edb42d50846 Mon Sep 17 00:00:00 2001 From: Charles Guan Date: Thu, 15 Oct 2026 21:35:16 -0700 Subject: [PATCH 3/3] Some cleanup --- src/mach/io/must.py | 1 + src/mach/wavefront.py | 6 +++--- tests/io/test_must.py | 23 +++++++---------------- 3 files changed, 11 insertions(+), 19 deletions(-) diff --git a/src/mach/io/must.py b/src/mach/io/must.py index 0706827..3ccdfb3 100644 --- a/src/mach/io/must.py +++ b/src/mach/io/must.py @@ -4,6 +4,7 @@ import numpy as np import scipy.io +from jaxtyping import Float from mach.io.utils import cached_download diff --git a/src/mach/wavefront.py b/src/mach/wavefront.py index 1609f5b..ca7755c 100644 --- a/src/mach/wavefront.py +++ b/src/mach/wavefront.py @@ -3,7 +3,7 @@ from typing import NamedTuple from beartype import beartype -from jaxtyping import Float, Real, jaxtyped +from jaxtyping import Real, jaxtyped from mach._array_api import Array, array_namespace, vector_norm @@ -379,9 +379,9 @@ def spherical( def earliest_arrival( element_positions_m: Real[Array, "elements xyz=3"], element_delays_s: Real[Array, " elements"], - points_m: Float[Array, "*points xyz=3"], + points_m: Real[Array, "*points xyz=3"], *, - sound_speed_m_s: float, + sound_speed_m_s: float | int, element_chunk_size: int = _DEFAULT_ELEMENT_CHUNK, point_chunk_size: int = _DEFAULT_POINT_CHUNK, ) -> Real[Array, "*points"]: diff --git a/tests/io/test_must.py b/tests/io/test_must.py index 82993be..43bbb84 100644 --- a/tests/io/test_must.py +++ b/tests/io/test_must.py @@ -5,7 +5,8 @@ import numpy as np import pytest -from jaxtyping import TypeCheckError +from beartype import beartype +from jaxtyping import jaxtyped from mach.io.must import ( download_pymust_doppler_data, @@ -32,7 +33,7 @@ def test_download_pymust_doppler_data(pymust_doppler_data): @pytest.mark.no_cuda def test_extract_pymust_params(pymust_doppler_data): """Test extracting PyMUST parameters.""" - params = extract_pymust_params(pymust_doppler_data) + params = jaxtyped(extract_pymust_params, typechecker=beartype)(pymust_doppler_data) assert params is not None assert len(params) > 0 assert "Nelements" in params @@ -43,7 +44,7 @@ def test_extract_pymust_params(pymust_doppler_data): def test_linear_probe_positions(): """Test generating linear probe positions.""" num_elements = 10 - positions = linear_probe_positions(10, 0.1) + positions = jaxtyped(linear_probe_positions, typechecker=beartype)(10, 0.1) assert isinstance(positions, np.ndarray) assert positions.shape == (num_elements, 3) np.testing.assert_allclose(positions.mean(axis=0), np.zeros(3), atol=1e-8) @@ -55,18 +56,8 @@ def test_scan_grid(): num_x = 3 num_y = 4 num_z = 5 - grid = scan_grid(np.linspace(0, 1, num_x), np.linspace(0, 1, num_y), np.linspace(0, 1, num_z)) + grid = jaxtyped(scan_grid, typechecker=beartype)( + np.linspace(0, 1, num_x), np.linspace(0, 1, num_y), np.linspace(0, 1, num_z) + ) assert isinstance(grid, np.ndarray) assert grid.shape == (num_x * num_y * num_z, 3) - - -@pytest.mark.no_cuda -def test_linear_probe_positions_rejects_noninteger_count(): - with pytest.raises(TypeCheckError): - linear_probe_positions(10.0, 0.1) - - -@pytest.mark.no_cuda -def test_scan_grid_rejects_nonarray_axis(): - with pytest.raises(TypeCheckError): - scan_grid(np.linspace(0, 1, 3), [0.0, 1.0])