diff --git a/autolens/point/plot/point_solver_plots.py b/autolens/point/plot/point_solver_plots.py index 36f3e9113..64143c856 100644 --- a/autolens/point/plot/point_solver_plots.py +++ b/autolens/point/plot/point_solver_plots.py @@ -353,8 +353,8 @@ def display_pixel_scale_from(extent, points) -> float: def display_solver_from(solver, extent, pixel_scale: float): """ Returns a solver of the same class as ``solver`` tiling ``extent`` (plus a pixel of margin) with triangles of - ``pixel_scale``, with the solver's own ``pixel_scale_precision``, ``magnification_threshold`` and - ``neighbor_degree``. It is used for the figure only. + ``pixel_scale``, with the solver's own ``pixel_scale_precision``, ``magnification_threshold``, + ``neighbor_degree`` and ``residual_threshold``. It is used for the figure only. """ x_min, x_max, y_min, y_max = extent return type(solver).for_limits_and_scale( @@ -366,6 +366,7 @@ def display_solver_from(solver, extent, pixel_scale: float): pixel_scale_precision=solver.pixel_scale_precision, magnification_threshold=solver.magnification_threshold, neighbor_degree=getattr(solver, "neighbor_degree", 1), + residual_threshold=getattr(solver, "residual_threshold", 10.0), ) diff --git a/autolens/point/solver/point_solver.py b/autolens/point/solver/point_solver.py index 282f91e9a..a7bc8f3cb 100644 --- a/autolens/point/solver/point_solver.py +++ b/autolens/point/solver/point_solver.py @@ -199,9 +199,9 @@ def solve( # `_solve_array`, because there are two distinct routes to an empty answer: # # 1. no triangle contained the coordinate -> `filtered_means` is already length 0 - # 2. every candidate failed the magnification threshold -> `_filter_low_magnification` - # preserves the length and writes NaN rows, which become `inf` and are then stripped - # by `remove_infinities`, landing here at length 0 + # 2. every candidate failed the magnification threshold (or the residual + # threshold) -> the filters preserve the length and write NaN rows, which become + # `inf` and are then stripped by `remove_infinities`, landing here at length 0 # # Only reachable on the NumPy path: the JAX path keeps its padded static shape, so # `len(solution)` is non-zero there and this reads no traced value. @@ -212,7 +212,13 @@ def solve( f"{tuple(source_plane_coordinate)}, so an empty grid is returned. This means " f"either that the coordinate lies outside the region traced by the image-plane " f"grid, or that every candidate image was rejected by " - f"`magnification_threshold` (currently {self.magnification_threshold})." + f"`magnification_threshold` (currently {self.magnification_threshold})" + + ( + "" + if self.residual_threshold is None + else f" or `residual_threshold` (currently {self.residual_threshold})" + ) + + "." ) return aa.Grid2DIrregular(solution) @@ -226,7 +232,8 @@ def _solve_array( remove_infinities: bool = False, ): """ - The raw solve: triangle refinement, magnification filtering and sentinel padding, + The raw solve: triangle refinement, magnification (and, unless ``residual_threshold`` + is ``None``, source-residual) filtering and sentinel padding, returning the bare ``xp`` positions array (no ``Grid2DIrregular`` wrap, no logging). On the JAX path this is the primal of the ``custom_jvp`` wrapper built by @@ -248,6 +255,20 @@ def _solve_array( plane_redshift=plane_redshift, ) + # On by default (``None`` disables): drop candidates that do not satisfy the lens + # equation, e.g. on a zero-core mass profile's singular centre (PyAutoLens#799). A + # mask, like the magnification filter, so the shape stays static; the length-0 NumPy + # case has nothing to trace. + if self.residual_threshold is not None and len(filtered_means) > 0: + + filtered_means = self._filter_large_residual( + tracer=tracer, + points=filtered_means, + source_plane_coordinate=source_plane_coordinate, + xp=xp, + plane_redshift=plane_redshift, + ) + # When no triangle traces to the source-plane coordinate -- e.g. the coordinate lies # outside the region the image-plane grid tiles -- `filtered_means` comes back with shape # (0, 2). The `[pair for pair in ...]` comprehension below then yields `[]`, and the diff --git a/autolens/point/solver/shape_solver.py b/autolens/point/solver/shape_solver.py index e5ac6b650..e7dcb3d86 100644 --- a/autolens/point/solver/shape_solver.py +++ b/autolens/point/solver/shape_solver.py @@ -44,6 +44,7 @@ def __init__( magnification_threshold=0.1, neighbor_degree: int = 1, use_jax: bool = False, + residual_threshold: Optional[float] = 10.0, ): """ Determine the image plane coordinates that are traced to be a source plane coordinate. @@ -75,6 +76,32 @@ def __init__( galaxy / profile classes it carries as JAX pytrees on the first call. The user wraps the call in their own ``@jax.jit`` — see the ``lens_calc.py`` workspace guide for the canonical pattern. + residual_threshold + ``PointSolver`` rejects every candidate image whose source-plane residual + ``|beta(theta) - beta|`` exceeds ``residual_threshold * pixel_scale_precision``. + The default is 10.0; ``None`` disables the filter. + + This removes candidates on the centre of a zero-core mass profile (e.g. a + ``dPIEMassSph`` cluster member with ``r_core=0``, PyAutoLens#799). The deflection + is discontinuous there, so a triangle around the centre traces to a triangle + inscribed in a circle of the member's Einstein radius. That triangle can contain + the source at every refinement step with no root inside it. The candidate then + lies within one final triangle of the centre, with a residual of order the + Einstein radius (~0.04" on cluster members). The magnification filter can pass + it, because in a near-critical host ``|mu|`` there is ~0.1-0.3. + + A true image traces to within its final triangle, so its residual is of order + the final triangle edge times the largest singular value of the lens-equation + Jacobian, which near a cusp is small. On the cluster and near-cusp fixtures of + PyAutoLens#799, true images reach 3.6 times ``pixel_scale_precision`` (1.1 times + near a cusp) and the core candidates at least 38 times, so 10 is the default: it + keeps every true image with margin and removes every core candidate. The + linearised correction ``|A^-1 r|`` is deliberately not used: ``A`` is huge near a + singular centre, so it would accept the core candidate. + + The cut scales with ``pixel_scale_precision``. At a coarse precision (e.g. 0.01, + a cut of 0.1") it is looser than the ~0.04" core residuals, so core candidates + can survive; lower ``residual_threshold`` or refine the precision if they matter. """ self.y_min = y_min self.y_max = y_max @@ -85,6 +112,7 @@ def __init__( self.magnification_threshold = magnification_threshold self.neighbor_degree = neighbor_degree self.use_jax = use_jax + self.residual_threshold = residual_threshold # The grid ``for_grid`` was built from, when there was one. It is the image-plane # pixelization ``image_regions_from`` reports its regions on; a solver built via @@ -159,6 +187,7 @@ def for_grid( magnification_threshold=0.1, neighbor_degree: int = 1, use_jax: bool = False, + residual_threshold: Optional[float] = 10.0, ): """ Create a solver for a given grid. @@ -177,6 +206,8 @@ def for_grid( The number of times recursively add neighbors for the triangles that contain use_jax Forwarded to the constructor; see ``__init__``. + residual_threshold + Forwarded to the constructor; see ``__init__``. Returns ------- @@ -197,6 +228,7 @@ def for_grid( magnification_threshold=magnification_threshold, neighbor_degree=neighbor_degree, use_jax=use_jax, + residual_threshold=residual_threshold, ) # Remembered so ``ShapeSolver.image_regions_from`` can report image-plane regions @@ -218,6 +250,7 @@ def for_limits_and_scale( magnification_threshold=0.1, neighbor_degree: int = 1, use_jax: bool = False, + residual_threshold: Optional[float] = 10.0, ): """ Create a solver for an explicit image-plane extent. @@ -236,6 +269,8 @@ def for_limits_and_scale( The number of times recursively add neighbors for the triangles that contain use_jax Forwarded to the constructor; see ``__init__``. + residual_threshold + Forwarded to the constructor; see ``__init__``. Returns ------- @@ -251,6 +286,7 @@ def for_limits_and_scale( magnification_threshold=magnification_threshold, neighbor_degree=neighbor_degree, use_jax=use_jax, + residual_threshold=residual_threshold, ) @property @@ -447,6 +483,54 @@ def _filter_low_magnification( mask = xp.abs(magnifications) > self.magnification_threshold return xp.where(mask[:, None], points, xp.nan) + def _filter_large_residual( + self, + tracer: Tracer, + points, + source_plane_coordinate: Tuple[float, float], + xp, + plane_redshift: Optional[float] = None, + ): + """ + Reject the points whose source-plane residual ``|beta(theta) - beta|`` exceeds + ``residual_threshold * pixel_scale_precision`` (see ``__init__``). + + The points are traced with ``_plane_grid``, the callable the triangle search uses, + so the residual is measured at the plane being solved for. Rejected points become + ``nan`` rows, as in ``_filter_low_magnification``, so the array keeps its static + shape; rows that are already ``nan`` stay ``nan``. + + Parameters + ---------- + points + The ``(n, 2)`` candidate image-plane positions. + source_plane_coordinate + The plane coordinate being solved for. + xp + The array module used for the trace. + plane_redshift + The redshift of the plane being solved for. ``None`` is the last plane. + + Returns + ------- + The points with a source-plane residual no larger than the threshold. + """ + traced = self._plane_grid( + tracer=tracer, + grid=aa.Grid2DIrregular(points), + xp=xp, + plane_redshift=plane_redshift, + ).array + beta = xp.stack( + [ + xp.asarray(source_plane_coordinate[0]), + xp.asarray(source_plane_coordinate[1]), + ] + ) + residuals = xp.sqrt(xp.sum((traced - beta[None, :]) ** 2, axis=1)) + reject = residuals > self.residual_threshold * self.pixel_scale_precision + return xp.where(reject[:, None], xp.nan, points) + def _plane_triangles( self, tracer: Tracer, @@ -547,6 +631,7 @@ def tree_flatten(self): self.magnification_threshold, self.neighbor_degree, self.use_jax, + self.residual_threshold, ) @classmethod @@ -561,6 +646,7 @@ def tree_unflatten(cls, aux_data, children): magnification_threshold, neighbor_degree, use_jax, + residual_threshold, ) = aux_data return cls( y_min=y_min, @@ -572,6 +658,7 @@ def tree_unflatten(cls, aux_data, children): magnification_threshold=magnification_threshold, neighbor_degree=neighbor_degree, use_jax=use_jax, + residual_threshold=residual_threshold, ) diff --git a/test_autolens/point/triangles/test_solver_spurious_core.py b/test_autolens/point/triangles/test_solver_spurious_core.py new file mode 100644 index 000000000..c62d9d908 --- /dev/null +++ b/test_autolens/point/triangles/test_solver_spurious_core.py @@ -0,0 +1,355 @@ +""" +Regression tests for PyAutoLens#799: spurious candidates on a zero-core mass profile's centre. + +A ``dPIEMassSph`` with ``r_core=0`` has a deflection which is discontinuous at its centre: a +triangle around the centre traces to a triangle inscribed in a circle of the profile's Einstein +radius, which can contain the source at every refinement step without containing a root. On the +cluster draws of autolens_profiling#439 this returned a candidate ~0.001" from a scaling member's +centre with a source-plane residual of 0.04". The magnification filter passes it, because in a +near-critical host region ``|mu|`` there is ~0.1-0.3. + +The fixture reproduces that with one member inside a cored host whose lens-equation Jacobian at +the member is ~ -0.05 I (overcritical): two true images (``mu`` ~ 210 and ~ -155) and one spurious +candidate at ~6e-4" from the member centre, residual 0.066", ``mu`` 0.29. + +``residual_threshold`` (default 10.0; ``None`` disables it and restores the pre-#799 solve) removes +it. The JAX tests skip +on the NumPy-only (no ``[optional]`` extras) CI leg. +""" + +import importlib + +import numpy as np +import pytest + +import autolens as al + +MEMBER_CENTRE = (0.3, 0.2) +SOURCE = (-0.0165, -0.011) +PRECISION = 0.001 + + +def _core_tracer(host_sigma=480.0): + host = al.Galaxy( + redshift=0.5, + mass=al.mp.dPIEMassSph( + centre=(0.0, 0.0), + sigma=host_sigma, + r_core=2.0, + r_cut=50.0, + redshift_object=0.5, + redshift_source=1.0, + ), + ) + member = al.Galaxy( + redshift=0.5, + mass=al.mp.dPIEMassSph( + centre=MEMBER_CENTRE, + sigma=60.0, + r_core=0.0, + r_cut=2.0, + redshift_object=0.5, + redshift_source=1.0, + ), + ) + return al.Tracer(galaxies=[host, member, al.Galaxy(redshift=1.0)]) + + +def _isothermal_tracer(einstein_radius=1.0): + return al.Tracer( + galaxies=[ + al.Galaxy( + redshift=0.5, + mass=al.mp.Isothermal( + centre=(0.0, 0.0), + ell_comps=(0.1, 0.0), + einstein_radius=einstein_radius, + ), + ), + al.Galaxy(redshift=1.0), + ] + ) + + +def _solver(use_jax=False, **kwargs): + """A solver over the fixture grid; ``residual_threshold`` is only passed when given.""" + return al.PointSolver.for_grid( + grid=al.Grid2D.uniform(shape_native=(40, 40), pixel_scales=0.1), + pixel_scale_precision=PRECISION, + use_jax=use_jax, + **kwargs, + ) + + +def _residuals(tracer, positions, source): + traced = np.asarray( + tracer.traced_grid_2d_list_from(grid=al.Grid2DIrregular(positions))[-1] + ) + return np.linalg.norm(traced - np.asarray(source), axis=1) + + +def _near_member(positions): + return np.linalg.norm(positions - np.asarray(MEMBER_CENTRE), axis=1) < 0.002 + + +def _finite_sorted(positions): + positions = np.asarray(positions) + positions = positions[np.all(np.isfinite(positions), axis=1)] + return positions[np.lexsort((positions[:, 1], positions[:, 0]))] + + +def test__disabled_filter_returns_a_candidate_on_the_zero_core_centre(): + """The baseline the filter exists for: with it disabled the solver keeps the spurious point.""" + tracer = _core_tracer() + + positions = np.asarray( + _solver(residual_threshold=None) + .solve(tracer, source_plane_coordinate=SOURCE) + .array + ) + + assert positions.shape == (3, 2) + near = _near_member(positions) + assert near.sum() == 1 + residuals = _residuals(tracer, positions, SOURCE) + assert residuals[near][0] > 0.05 + assert (residuals[~near] < PRECISION).all() + + +def test__default_solver_removes_the_spurious_candidate_only(): + tracer = _core_tracer() + + unfiltered = np.asarray( + _solver(residual_threshold=None) + .solve(tracer, source_plane_coordinate=SOURCE) + .array + ) + default = np.asarray(_solver().solve(tracer, source_plane_coordinate=SOURCE).array) + explicit = np.asarray( + _solver(residual_threshold=10.0) + .solve(tracer, source_plane_coordinate=SOURCE) + .array + ) + + assert default.shape == (2, 2) + assert not _near_member(default).any() + np.testing.assert_array_equal(default, unfiltered[~_near_member(unfiltered)]) + np.testing.assert_array_equal(explicit, default) + + +@pytest.mark.parametrize("source", [(0.05, 0.02), (0.0, 0.0), (0.3, -0.2)]) +def test__residual_threshold_leaves_a_normal_lens_unchanged(source): + tracer = _isothermal_tracer() + + unfiltered = np.asarray( + _solver(residual_threshold=None) + .solve(tracer, source_plane_coordinate=source) + .array + ) + default = np.asarray(_solver().solve(tracer, source_plane_coordinate=source).array) + + assert len(unfiltered) > 0 + np.testing.assert_array_equal(default, unfiltered) + + +def test__residual_threshold_defaults_to_10_and_threads_through_constructors(): + grid = al.Grid2D.uniform(shape_native=(10, 10), pixel_scales=1.0) + + assert ( + al.PointSolver.for_grid( + grid=grid, pixel_scale_precision=0.01 + ).residual_threshold + == 10.0 + ) + assert ( + al.PointSolver.for_limits_and_scale( + pixel_scale_precision=0.01 + ).residual_threshold + == 10.0 + ) + assert ( + al.PointSolver( + y_min=-1.0, + y_max=1.0, + x_min=-1.0, + x_max=1.0, + scale=0.1, + pixel_scale_precision=0.01, + ).residual_threshold + == 10.0 + ) + assert ( + al.PointSolver.for_grid( + grid=grid, pixel_scale_precision=0.01, residual_threshold=None + ).residual_threshold + is None + ) + assert ( + al.PointSolver.for_limits_and_scale( + pixel_scale_precision=0.01, residual_threshold=5.0 + ).residual_threshold + == 5.0 + ) + + +def test__tree_flatten_roundtrips_residual_threshold(): + for residual_threshold, kwargs in ( + (10.0, {}), + (None, {"residual_threshold": None}), + ): + solver = _solver(**kwargs) + + children, aux = solver.tree_flatten() + rebuilt = al.PointSolver.tree_unflatten(aux, children) + + assert rebuilt.residual_threshold == residual_threshold + assert rebuilt.magnification_threshold == solver.magnification_threshold + + +if importlib.util.find_spec("jax") is not None: + import jax + import jax.numpy as jnp + + jax.config.update("jax_enable_x64", True) + + from autolens.jax.registration import register_tracer_classes + + def _jit_solve(solver, tracer_from, source, *args): + return np.asarray( + jax.jit( + lambda s, *a: solver.solve( + tracer_from(*a), source_plane_coordinate=(s[0], s[1]) + ).array + )(jnp.array(source), *args) + ) + + def _point_tracer(einstein_radius): + lens = al.Galaxy( + redshift=0.5, + mass=al.mp.Isothermal( + centre=(0.0, 0.0), + einstein_radius=einstein_radius, + ell_comps=(0.05, 0.03), + ), + ) + return al.Tracer( + galaxies=[ + lens, + al.Galaxy(redshift=1.0, point_0=al.ps.Point(centre=(0.07, 0.07))), + ] + ) + + def _log_likelihood_and_grad(solver): + positions = al.Grid2DIrregular([(1.53, 0.35), (-1.24, -0.28)]) + noise_map = al.ArrayIrregular([0.05, 0.05]) + + def log_likelihood(einstein_radius): + fit = al.FitPositionsImagePairAll( + name="point_0", + data=positions, + noise_map=noise_map, + tracer=_point_tracer(einstein_radius), + solver=solver, + xp=jnp, + ) + return fit.log_likelihood + + value, grad = jax.jit(jax.value_and_grad(log_likelihood))(1.6) + return float(value), float(grad) + + +requires_jax = pytest.mark.skipif( + importlib.util.find_spec("jax") is None, + reason="requires jax (the [optional] extras)", +) + + +@requires_jax +def test__jit_default_residual_threshold_removes_the_spurious_candidate(): + register_tracer_classes(_core_tracer()) + + unfiltered = _jit_solve( + _solver(residual_threshold=None, use_jax=True), _core_tracer, SOURCE + ) + filtered = _jit_solve(_solver(use_jax=True), _core_tracer, SOURCE) + + assert unfiltered.shape == filtered.shape + assert _near_member(_finite_sorted(unfiltered)).sum() == 1 + + numpy = np.asarray( + _solver().solve(_core_tracer(), source_plane_coordinate=SOURCE).array + ) + np.testing.assert_allclose( + _finite_sorted(filtered), _finite_sorted(numpy), rtol=0.0, atol=1e-10 + ) + + +@requires_jax +def test__vmap_matches_scalar_solves_with_residual_threshold(): + solver = _solver(residual_threshold=10.0, use_jax=True) + register_tracer_classes(_core_tracer()) + + sources = jnp.array([SOURCE, (0.0034, -0.011), (-0.0165, -0.031)]) + + batched = np.asarray( + jax.jit( + jax.vmap( + lambda s: solver.solve( + _core_tracer(), source_plane_coordinate=(s[0], s[1]) + ).array + ) + )(sources) + ) + + for i, source in enumerate(np.asarray(sources)): + scalar = _finite_sorted(_jit_solve(solver, _core_tracer, tuple(source))) + assert not _near_member(scalar).any() + np.testing.assert_allclose( + _finite_sorted(batched[i]), scalar, rtol=0.0, atol=1e-10 + ) + + +@requires_jax +def test__grad_through_the_solver_is_unchanged_by_residual_threshold(): + """ + The filter runs in the ``custom_jvp`` primal only, so at true images the implicit + fixed-point gradient is untouched. + """ + register_tracer_classes(_point_tracer(1.6)) + + grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.2) + + def solver(residual_threshold): + return al.PointSolver.for_grid( + grid=grid, + pixel_scale_precision=PRECISION, + residual_threshold=residual_threshold, + use_jax=True, + ) + + value, grad = _log_likelihood_and_grad(solver(None)) + value_filtered, grad_filtered = _log_likelihood_and_grad(solver(10.0)) + + assert np.isfinite(value) and np.isfinite(grad) + assert grad != 0.0, "jax.grad through the solver is silently zero" + assert value_filtered == value + assert grad_filtered == grad + + +@requires_jax +def test__grad_at_the_true_images_of_the_core_fixture_is_finite(): + solver = _solver(residual_threshold=10.0, use_jax=True) + register_tracer_classes(_core_tracer()) + + def summed_positions(host_sigma): + positions = solver.solve( + _core_tracer(host_sigma), source_plane_coordinate=SOURCE + ).array + finite = jnp.all(jnp.isfinite(positions), axis=1) + return jnp.sum(jnp.where(finite[:, None], positions, 0.0)) + + value, grad = jax.jit(jax.value_and_grad(summed_positions))(480.0) + + assert np.isfinite(float(value)) + assert np.isfinite(float(grad)) + assert float(grad) != 0.0 diff --git a/test_autolens/point/triangles/test_static_lattice_jax.py b/test_autolens/point/triangles/test_static_lattice_jax.py index 5d766d208..8ce00f533 100644 --- a/test_autolens/point/triangles/test_static_lattice_jax.py +++ b/test_autolens/point/triangles/test_static_lattice_jax.py @@ -61,6 +61,9 @@ def _solver(shape_native=(100, 100), pixel_scales=0.2): ), pixel_scale_precision=0.001, magnification_threshold=0.1, + # The residual filter adds one trace of the padded candidates; this test + # counts the triangle-step traces only. + residual_threshold=None, use_jax=True, )