From 24dfd42d4d0a37a7c402b381f326787b3ddbb84f Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 26 Nov 2026 12:12:42 +0000 Subject: [PATCH] fix: JAX weak fits visualize (#614); mixed factor graphs under the default setup Part of PyAutoLabs/PyAutoLens#895. Co-Authored-By: Claude Opus 5.5 --- autolens/weak/model/analysis.py | 20 +++ autolens/weak/model/result.py | 7 +- .../test_factor_graph_default_setup.py | 143 ++++++++++++++++++ .../weak/model/test_visualizer_weak.py | 88 +++++++++++ 4 files changed, 257 insertions(+), 1 deletion(-) create mode 100644 test_autolens/analysis/test_factor_graph_default_setup.py create mode 100644 test_autolens/weak/model/test_visualizer_weak.py diff --git a/autolens/weak/model/analysis.py b/autolens/weak/model/analysis.py index 30847a86a..617251c4c 100644 --- a/autolens/weak/model/analysis.py +++ b/autolens/weak/model/analysis.py @@ -15,6 +15,8 @@ """ from typing import Optional +import numpy as np + import autofit as af import autogalaxy as ag @@ -187,6 +189,24 @@ def fit_from(self, instance) -> FitWeak: xp=self._xp, ) + def fit_for_visualization(self, instance) -> FitWeak: + """ + Build the `FitWeak` used by the visualizer, always on the NumPy path. + + On the JAX path `FitWeak.model_shear` is a raw `(N, 2)` array (`ShearYX2DIrregular` is not a + registered pytree), which the shear-field plotters cannot draw. Visualization runs once per + update on the max-likelihood instance, so it is computed with NumPy whatever the likelihood's + backend: the model shear is then a `ShearYX2DIrregular` and the log likelihood is the same. + + Parameters + ---------- + instance + The maximum log likelihood model instance being visualized. + """ + tracer = self.tracer_via_instance_from(instance=instance) + + return FitWeak(dataset=self.dataset, tracer=tracer, xp=np) + @staticmethod def _register_fit_weak_pytrees() -> None: """Register every type reachable from a ``FitWeak`` return value so diff --git a/autolens/weak/model/result.py b/autolens/weak/model/result.py index 5ffef4508..822734937 100644 --- a/autolens/weak/model/result.py +++ b/autolens/weak/model/result.py @@ -10,4 +10,9 @@ def grid(self): @property def max_log_likelihood_fit(self): - return self.analysis.fit_from(instance=self.instance) + """ + The `FitWeak` of the maximum log likelihood model, built on the NumPy path (via + `AnalysisWeak.fit_for_visualization`) so its `model_shear` is a `ShearYX2DIrregular` that the + shear-field plotters can draw, whatever backend the likelihood ran on. + """ + return self.analysis.fit_for_visualization(instance=self.instance) diff --git a/test_autolens/analysis/test_factor_graph_default_setup.py b/test_autolens/analysis/test_factor_graph_default_setup.py new file mode 100644 index 000000000..bcd48839a --- /dev/null +++ b/test_autolens/analysis/test_factor_graph_default_setup.py @@ -0,0 +1,143 @@ +""" +`FactorGraphModel`s mixing PyAutoLens dataset types with default-constructed analyses (R6: every +analysis defaults to `setup="auto"`): each factor resolves its own setup, and factors left on the +default adopt one shared backend so the whole graph fits without `use_jax=` pins. +""" +import importlib.util + +import numpy as np +import pytest + +import autofit as af +import autofit.graphical as g +import autolens as al + +from autofit import exc +from autonerves.environment import Environment + +MANY_CORE = Environment( + gpu=False, + gpu_name=None, + gpu_memory_gb=None, + cores=64, + ram_gb=None, + numba=True, + nufftax=True, + site="local", +) + +HAS_JAX = importlib.util.find_spec("jax") is not None + + +@pytest.fixture(autouse=True) +def many_core(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: MANY_CORE)) + + +def _imaging_model(): + return af.Collection( + galaxies=af.Collection( + lens=af.Model( + al.Galaxy, redshift=0.5, mass=al.mp.Isothermal, light=al.lp.Sersic + ), + source=af.Model(al.Galaxy, redshift=1.0, light=al.lp.Sersic), + ) + ) + + +def _point_model(): + return af.Collection( + galaxies=af.Collection( + lens=al.Galaxy(redshift=0.5, point_0=al.ps.Point(centre=(0.0, 0.0))) + ) + ) + + +def _graph(*factors, **kwargs): + return g.FactorGraphModel( + *[ + g.AnalysisFactor(model, analysis=analysis, name=f"factor_{i}") + for i, (analysis, model) in enumerate(factors) + ], + **kwargs, + ) + + +def _modify(graph, name): + return graph.modify_before_fit( + paths=af.DirectoryPaths(name=name), model=graph.global_prior_model + ) + + +def test__default_imaging_and_interferometer__pass_modify_before_fit( + masked_imaging_7x7, interferometer_7 +): + graph = _graph( + (al.AnalysisImaging(dataset=masked_imaging_7x7), _imaging_model()), + (al.AnalysisInterferometer(dataset=interferometer_7), _imaging_model()), + ) + + _modify(graph, "lens_graph_imaging_interferometer") + + for factor in graph.model_factors: + assert factor.analysis.setup is None + assert factor.analysis.is_jax is HAS_JAX + + graph.check_setup_agreement() + graph.check_backend_agreement() + + instance = graph.global_prior_model.instance_from_prior_medians() + assert np.isfinite(float(graph.log_likelihood_function(instance))) + + +def test__default_imaging_and_point__pass_modify_before_fit( + masked_imaging_7x7, point_dataset +): + solver = al.m.MockPointSolver(model_positions=point_dataset.positions) + + graph = _graph( + (al.AnalysisImaging(dataset=masked_imaging_7x7), _imaging_model()), + ( + al.AnalysisPoint( + dataset=point_dataset, + solver=solver, + fit_positions_cls=al.FitPositionsImagePairAll, + ), + _point_model(), + ), + ) + + _modify(graph, "lens_graph_imaging_point") + + for factor in graph.model_factors: + assert factor.analysis.setup is None + assert factor.analysis.is_jax is HAS_JAX + + graph.check_setup_agreement() + graph.check_backend_agreement() + + instance = graph.global_prior_model.instance_from_prior_medians() + assert np.isfinite(float(graph.log_likelihood_function(instance))) + + +def test__explicit_disagreeing_setups__still_raise(masked_imaging_7x7, point_dataset): + solver = al.m.MockPointSolver(model_positions=point_dataset.positions) + + graph = _graph( + ( + al.AnalysisImaging(dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64"), + _imaging_model(), + ), + ( + al.AnalysisPoint(dataset=point_dataset, solver=solver, setup="auto"), + _point_model(), + ), + ) + + if not HAS_JAX: + pytest.skip("the point auto setup is JAX; without JAX it may still disagree on numpy") + + with pytest.raises(exc.SearchException, match="setups passed explicitly"): + _modify(graph, "lens_graph_explicit_bad") diff --git a/test_autolens/weak/model/test_visualizer_weak.py b/test_autolens/weak/model/test_visualizer_weak.py new file mode 100644 index 000000000..25500055e --- /dev/null +++ b/test_autolens/weak/model/test_visualizer_weak.py @@ -0,0 +1,88 @@ +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest + +import autoarray as aa +import autofit as af +import autolens as al + +from autogalaxy.util.shear_field import ShearYX2DIrregular + +from autolens.weak.model.visualizer import VisualizerWeak + +directory = Path(__file__).resolve().parent + + +def _lens_model(einstein_radius=1.6): + return af.Collection( + galaxies=af.Collection( + lens=al.Galaxy( + redshift=0.5, + mass=al.mp.Isothermal( + centre=(0.0, 0.0), + ell_comps=(0.0, 0.05), + einstein_radius=einstein_radius, + ), + ), + source=al.Galaxy(redshift=1.0), + ) + ) + + +def _make_dataset(): + grid = aa.Grid2DIrregular( + values=[(0.7, 0.5), (1.0, 1.0), (-0.3, 0.6), (-1.1, -0.8)] + ) + instance = _lens_model().instance_from_unit_vector([]) + tracer = al.Tracer(galaxies=[instance.galaxies.lens, instance.galaxies.source]) + return al.SimulatorShearYX(noise_sigma=0.1, seed=1).via_tracer_from( + tracer=tracer, grid=grid, name="test" + ) + + +def test__fit_for_visualization__jax_analysis__returns_numpy_structured_fit(): + """ + PyAutoLens#614: on the JAX path `FitWeak.model_shear` is a raw `(N, 2)` array, which the + shear-field plotters cannot draw (`shear_yx.grid`). The visualizer's fit must be the NumPy fit, + whose model shear is a `ShearYX2DIrregular`, with the same log likelihood as the JAX fit. + """ + pytest.importorskip("jax") + + dataset = _make_dataset() + analysis = al.AnalysisWeak(dataset=dataset, use_jax=True) + instance = _lens_model(einstein_radius=1.5).instance_from_unit_vector([]) + + fit = analysis.fit_for_visualization(instance=instance) + + assert isinstance(fit.model_shear, ShearYX2DIrregular) + np.testing.assert_allclose( + fit.log_likelihood, + float(analysis.fit_from(instance=instance).log_likelihood), + rtol=1e-8, + ) + + +def test__visualize__jax_analysis__writes_fit_subplot(plot_patch): + """ + End-to-end form of PyAutoLens#614: visualizing the max-likelihood fit of a JAX `AnalysisWeak` + raised `AttributeError: 'ArrayImpl' object has no attribute 'grid'` before the fix. + """ + pytest.importorskip("jax") + + dataset = _make_dataset() + analysis = al.AnalysisWeak(dataset=dataset, use_jax=True) + instance = _lens_model(einstein_radius=1.5).instance_from_unit_vector([]) + + paths = SimpleNamespace(image_path=directory / "files") + + VisualizerWeak.visualize( + analysis=analysis, + paths=paths, + instance=instance, + during_analysis=False, + quick_update=True, + ) + + assert str(directory / "files" / "subplot_fit_weak.png") in plot_patch.paths