diff --git a/autogalaxy/__init__.py b/autogalaxy/__init__.py index e0675ff7..5044e21f 100644 --- a/autogalaxy/__init__.py +++ b/autogalaxy/__init__.py @@ -59,6 +59,8 @@ from .analysis import model_util from .analysis.adapt_images.adapt_images import AdaptImages from .analysis.adapt_images.adapt_images import galaxy_name_image_dict_via_result_from +from .analysis.adapt_images.adapt_images import galaxy_snr_maps_from +from .analysis.adapt_images.adapt_images import soft_snr_maps_from from . import aggregator as agg from . import exc from . import util diff --git a/autogalaxy/analysis/adapt_images/adapt_images.py b/autogalaxy/analysis/adapt_images/adapt_images.py index c40d2a1e..5b81540e 100644 --- a/autogalaxy/analysis/adapt_images/adapt_images.py +++ b/autogalaxy/analysis/adapt_images/adapt_images.py @@ -164,7 +164,7 @@ def _galaxy_image_dict_to_cache(cache_path, galaxy_name_image_dict: Dict, paths) def galaxy_name_image_dict_via_result_from( - result, use_model_images: bool = False + result, use_model_images: bool = False, minimum_percent: Optional[float] = None ) -> "AdaptImages": """ Returns per-galaxy subtracted signal-to-noise maps by default, or model images. @@ -187,6 +187,12 @@ def galaxy_name_image_dict_via_result_from( galaxy-image, which is a fraction of its maximum value defined via a config file. This flooring applies to both signal-to-noise maps and model images. + The `HilbertSNR` image mesh and the soft maps of `soft_snr_maps_from` need the + signal-to-noise maps *before* that floor: they work in absolute S/N, and above a peak S/N of 200 the default + 1% floor lifts empty sky over their noise threshold of S/N 2 (sky reads 2.5 at a peak of 250), which is then + weighted as source. Pass ``minimum_percent=0.0`` for those: negative values are set to 0 and nothing else + changes. + The raw per-galaxy images are cached to the result's own ``files/`` folder on first computation (``galaxy_images_model.fits`` / ``galaxy_images_snr.fits``) and loaded from there on every later call — computing them rebuilds the result's maximum log likelihood fit, which on a resumed pipeline pays a fresh @@ -214,13 +220,20 @@ def galaxy_name_image_dict_via_result_from( use_model_images If True, use the model images of the galaxies. If False (the default), use their subtracted signal-to-noise maps, which have already been divided by the noise map. + minimum_percent + The fraction of each image's maximum it is floored at. None (the default) uses the config value + ``general.adapt.adapt_minimum_percent`` (0.01). ``0.0`` gives the images before the floor, with negative + values set to 0: the input for `HilbertSNR` and `soft_snr_maps_from` (see also `galaxy_snr_maps_from`). Returns ------- A dictionary mapping galaxy paths to subtracted signal-to-noise maps by default, or model images when - use_model_images is True, with the configured minimum-value flooring applied in either mode. + use_model_images is True, floored at ``minimum_percent`` of each image's maximum in either mode. """ - adapt_minimum_percent = conf.instance["general"]["adapt"]["adapt_minimum_percent"] + if minimum_percent is None: + adapt_minimum_percent = conf.instance["general"]["adapt"]["adapt_minimum_percent"] + else: + adapt_minimum_percent = minimum_percent cache_path = _galaxy_images_cache_path(result, use_model_images=use_model_images) raw_image_dict = _galaxy_image_dict_from_cache( @@ -244,6 +257,10 @@ def galaxy_name_image_dict_via_result_from( galaxy_name_image_dict = {} for path, galaxy_image in raw_image_dict.items(): + # Floor a copy: computed without a cache, these arrays are the result's own, and flooring them in place + # would change what every later call on the same result returns (e.g. a later ``minimum_percent=0.0``). + galaxy_image = galaxy_image.copy() + minimum_galaxy_value = adapt_minimum_percent * np.max(galaxy_image.array) galaxy_image[galaxy_image < minimum_galaxy_value] = minimum_galaxy_value @@ -252,6 +269,141 @@ def galaxy_name_image_dict_via_result_from( return galaxy_name_image_dict +def galaxy_snr_maps_from(result) -> Dict[str, aa.Array2D]: + """ + Returns each galaxy's signal-to-noise (S/N) map from a previous fit: the data minus the model images of every + other galaxy, divided by the noise map, with negative values set to 0 and no other floor. + + This is the input the `HilbertSNR` image mesh and `soft_snr_maps_from` expect. It is + ``galaxy_name_image_dict_via_result_from(result=result, minimum_percent=0.0)``: the same maps the default adapt + images are built from (and cached as ``files/galaxy_images_snr.fits``), before the 1% minimum-percent floor, + which above a peak S/N of 200 lifts empty sky over S/N 2. + + Parameters + ---------- + result + The result of a previous model-fit. + + Returns + ------- + A dictionary mapping each galaxy's path name (e.g. ``"('galaxies', 'source')"``) to its S/N map. + """ + return galaxy_name_image_dict_via_result_from(result=result, minimum_percent=0.0) + + +def soft_snr_maps_from( + snr_maps: Dict[str, aa.Array2D], + galaxy_names: Optional[List[str]] = None, +) -> Dict[str, aa.Array2D]: + """ + Returns the maps to give adaptive regularizations (e.g. `AdaptSplit`) so they adapt to the same signal as the + `HilbertSNR` image mesh: each S/N map passed through `aa.image_mesh.soft_snr_map_from` + (``(x / (x + 3)) ** 2`` with ``x = max(S/N - 2, 0)``, floored at 1% of its maximum). + + The regularization schemes are unchanged; only the map they are given changes. `AdaptImages.from_result` does + this (and builds the meshes) in one call: + + image_mesh = ag.image_mesh.HilbertSNR(pixels=1000, edge_pixels=30) + adapt_images = ag.AdaptImages.from_result(result=result, image_mesh={"source": image_mesh}) + + Parameters + ---------- + snr_maps + Galaxy path name -> S/N map, e.g. from `galaxy_snr_maps_from`. + galaxy_names + The galaxies to transform, as full path names or short names (e.g. ``"source"``); the others are returned + unchanged. None (the default) transforms every galaxy. + + Returns + ------- + A new dictionary with the same keys. + """ + selected = None + if galaxy_names is not None: + selected = {galaxy_name_key_from(name, list(snr_maps)) for name in galaxy_names} + + soft_maps = {} + + for name, snr_map in snr_maps.items(): + if selected is not None and name not in selected: + soft_maps[name] = snr_map + continue + + soft_maps[name] = aa.Array2D( + values=aa.image_mesh.soft_snr_map_from(np.asarray(snr_map.array)), + mask=snr_map.mask, + ) + + return soft_maps + + +def _galaxy_path_forms(key: str) -> List[str]: + """ + The names a galaxy path key can be written as: the full key (``"('galaxies', 'source')"``), the dotted path + (``"galaxies.source"``) and the galaxy's own name (``"source"``). + """ + import ast + + forms = [key] + try: + path = ast.literal_eval(key) + except (ValueError, SyntaxError): + return forms + if isinstance(path, tuple) and path and all(isinstance(part, str) for part in path): + forms += [".".join(path), path[-1]] + return forms + + +def galaxy_name_key_from(name: str, keys: List[str]) -> str: + """ + Returns the full galaxy path key in ``keys`` that ``name`` refers to. + + ``name`` may be the full key (``"('galaxies', 'source')"``), the dotted path (``"galaxies.source"``) or the + galaxy's own name (``"source"``). A short name that matches more than one galaxy (e.g. two galaxies called + ``"source"`` in different collections) raises an error; use the full or dotted form then. + + Parameters + ---------- + name + The name as written by the user. + keys + The full path keys to resolve against (e.g. ``str(path)`` of every galaxy in the model). + """ + keys = [str(key) for key in keys] + if name in keys: + return name + + matches = [key for key in keys if name in _galaxy_path_forms(key)] + if len(matches) == 1: + return matches[0] + if not matches: + raise KeyError(f"No galaxy called {name!r}; the galaxies are {keys}.") + raise KeyError( + f"{name!r} matches more than one galaxy ({matches}); use the full or dotted path name." + ) + + +def _resolved_name_dict(name_dict: Optional[Dict], keys: List[str]) -> Optional[Dict]: + """ + ``name_dict`` with every short key (``"source"``, ``"galaxies.source"``) replaced by the full galaxy path key it + refers to. A key that names no galaxy in ``keys`` is kept as it is (and, as before short keys existed, simply + matches nothing); a short key naming more than one galaxy raises. + """ + if name_dict is None: + return None + + resolved = {} + for name, value in name_dict.items(): + name = str(name) + try: + name = galaxy_name_key_from(name, keys) + except KeyError as exc: + if "more than one galaxy" in str(exc): + raise + resolved[name] = value + return resolved + + class AdaptImages: def __init__( self, @@ -283,7 +435,7 @@ def __init__( an `AdaptImages` instance cannot be passed directly to an `Analysis` class, as the galaxy instances need to be updated for every iteration of the non-linear search. - A dictionary mapping the path name of each galaxy (e.g. "galaxies.lens") to its model-image is therefore used + A dictionary mapping the path name of each galaxy (e.g. "('galaxies', 'lens')", or in short "lens") to its model-image is therefore used which is called inside the `log_likelihood_function` o map the model-image of each galaxy to the galaxy instance of that iteration's specific model. @@ -293,7 +445,8 @@ def __init__( A dictionary associating each galaxy instance to an image of only that galaxy (e.g. for a strong lens one entry will map an instance of the source galaxy entry to an image of the lensed source. galaxy_name_image_dict - A dictionary associating each galaxy path name (e.g. "galaxies.source") to an image of only that + A dictionary associating each galaxy path name (e.g. "('galaxies', 'source')", or in short "source" + or "galaxies.source") to an image of only that galaxy (e.g. for a strong lens the `source` entry is an image of the lensed source, without the lens light). """ @@ -313,6 +466,57 @@ def __init__( # ``galaxy_image_dict`` keys. self.galaxy_path_list = galaxy_path_list + @classmethod + def from_result( + cls, + result, + image_mesh: Optional[Dict[str, "aa.AbstractImageMesh"]] = None, + mask: Optional[aa.Mask2D] = None, + ) -> "AdaptImages": + """ + Returns the adapt images for the next model-fit of a pipeline, in one call, from the result of the previous + one: each galaxy's S/N map (`galaxy_snr_maps_from`), the image-plane mesh grid of every galaxy listed in + ``image_mesh`` drawn from its S/N map, and the soft S/N maps (`soft_snr_maps_from`) the adaptive + regularizations (e.g. `AdaptSplit`) adapt to. + + image_mesh = ag.image_mesh.HilbertSNR(pixels=1000, edge_pixels=30) + adapt_images = ag.AdaptImages.from_result(result=result, image_mesh={"source": image_mesh}) + + mesh = ag.mesh.Delaunay(pixels=image_mesh.pixels, zeroed_pixels=image_mesh.edge_pixels) + + This is the recommended set-up with `HilbertSNR`. For the older peak-normalised set-up (`Hilbert` with + ``weight_power`` / ``weight_floor`` on the floored S/N map), build `AdaptImages` directly from + `galaxy_name_image_dict_via_result_from`. + + Parameters + ---------- + result + The result of the previous model-fit. + image_mesh + Galaxy name -> the image mesh to draw that galaxy's mesh grid with. Names may be short (``"source"``), + dotted (``"galaxies.source"``) or full (``"('galaxies', 'source')"``). Edge points are appended when the + image mesh has ``edge_pixels``. None draws no mesh grids. + mask + The mask the mesh grids are drawn on; defaults to the result's mask. + """ + snr_maps = galaxy_snr_maps_from(result=result) + + mesh_grid_dict = None + if image_mesh is not None: + mask = mask if mask is not None else result.mask + keys = list(snr_maps) + mesh_grid_dict = {} + for name, mesh in image_mesh.items(): + key = galaxy_name_key_from(name, keys) + mesh_grid_dict[key] = mesh.image_plane_mesh_grid_from( + mask=mask, adapt_data=snr_maps[key] + ) + + return cls( + galaxy_name_image_dict=soft_snr_maps_from(snr_maps), + galaxy_name_image_plane_mesh_grid_dict=mesh_grid_dict, + ) + @property def mask(self) -> aa.Mask2D: """ @@ -359,7 +563,7 @@ def updated_via_instance_from( an `AdaptImages` instance cannot be passed directly to an `Analysis` class, as the galaxy instances need to be updated for every iteration of the non-linear search. - A dictionary mapping the path name of each galaxy (e.g. "galaxies.lens") to its model-image is therefore used + A dictionary mapping the path name of each galaxy (e.g. "('galaxies', 'lens')", or in short "lens") to its model-image is therefore used which is called inside the `log_likelihood_function` o map the model-image of each galaxy to the galaxy instance of that iteration's specific model. @@ -404,17 +608,28 @@ def updated_via_instance_from( for galaxy_name, galaxy in instance.path_instance_tuples_for_class(Galaxy) } + # Keys may be written short ("source", "galaxies.source"); resolve them to the full path keys once. + galaxy_keys = list(path_by_id.values()) + resolved = AdaptImages( + galaxy_name_image_dict=_resolved_name_dict( + self.galaxy_name_image_dict, galaxy_keys + ), + galaxy_name_image_plane_mesh_grid_dict=_resolved_name_dict( + self.galaxy_name_image_plane_mesh_grid_dict, galaxy_keys + ), + ) + galaxy_image_dict = None - if self.galaxy_name_image_dict is not None: + if resolved.galaxy_name_image_dict is not None: galaxy_image_dict = {} for galaxy_name, galaxy in instance.path_instance_tuples_for_class(Galaxy): galaxy_name = str(galaxy_name) - if galaxy_name in self.galaxy_name_image_dict: - galaxy_image_dict[galaxy] = self.galaxy_name_image_dict[galaxy_name] + if galaxy_name in resolved.galaxy_name_image_dict: + galaxy_image_dict[galaxy] = resolved.galaxy_name_image_dict[galaxy_name] if mask is not None: for key, image in galaxy_image_dict.items(): @@ -422,15 +637,15 @@ def updated_via_instance_from( galaxy_image_plane_mesh_grid_dict = None - if self.galaxy_name_image_plane_mesh_grid_dict is not None: + if resolved.galaxy_name_image_plane_mesh_grid_dict is not None: galaxy_image_plane_mesh_grid_dict = {} for galaxy_name, galaxy in instance.path_instance_tuples_for_class(Galaxy): galaxy_name = str(galaxy_name) - if galaxy_name in self.galaxy_name_image_plane_mesh_grid_dict: - cached_mesh = self.galaxy_name_image_plane_mesh_grid_dict[galaxy_name] + if galaxy_name in resolved.galaxy_name_image_plane_mesh_grid_dict: + cached_mesh = resolved.galaxy_name_image_plane_mesh_grid_dict[galaxy_name] if dataset_model is not None: cached_mesh = cached_mesh.subtracted_and_rotated_from( offset=dataset_model.grid_offset, @@ -450,8 +665,8 @@ def updated_via_instance_from( return AdaptImages( galaxy_image_dict=galaxy_image_dict, galaxy_image_plane_mesh_grid_dict=galaxy_image_plane_mesh_grid_dict, - galaxy_name_image_dict=self.galaxy_name_image_dict, - galaxy_name_image_plane_mesh_grid_dict=self.galaxy_name_image_plane_mesh_grid_dict, + galaxy_name_image_dict=resolved.galaxy_name_image_dict, + galaxy_name_image_plane_mesh_grid_dict=resolved.galaxy_name_image_plane_mesh_grid_dict, galaxy_path_list=galaxy_path_list, ) diff --git a/test_autogalaxy/analysis/test_adapt_images.py b/test_autogalaxy/analysis/test_adapt_images.py index fa22b5b1..47dbc500 100644 --- a/test_autogalaxy/analysis/test_adapt_images.py +++ b/test_autogalaxy/analysis/test_adapt_images.py @@ -2,6 +2,7 @@ import numpy as np import autofit as af +import autoarray as aa import autogalaxy as ag @@ -293,3 +294,153 @@ def test__galaxy_name_image_dict_via_result_from__stale_cache_is_recomputed(tmp_ unchanged.mask = mask assert galaxy_name_image_dict_via_result_from(result=unchanged) is not None + + +def _snr_test_image_dict(): + """A lens and a source S/N map with negatives, noise-level values and a bright peak (S/N 250).""" + mask = ag.Mask2D.circular(shape_native=(7, 7), pixel_scales=0.1, radius=0.3) + n = int((~np.asarray(mask)).sum()) + source = np.linspace(-3.0, 40.0, n) + source[-1] = 250.0 + lens = np.linspace(-1.0, 10.0, n) + return { + "('galaxies', 'lens')": ag.Array2D(values=lens, mask=mask), + "('galaxies', 'source')": ag.Array2D(values=source, mask=mask), + } + + +@pytest.mark.parametrize("cached", [False, True]) +def test__galaxy_name_image_dict_via_result_from__minimum_percent(tmp_path, cached): + from autogalaxy.analysis.adapt_images.adapt_images import ( + galaxy_name_image_dict_via_result_from, + ) + + image_dict = _snr_test_image_dict() + raw = {name: np.asarray(image.array).copy() for name, image in image_dict.items()} + + result = _StubCacheResult(tmp_path if cached else None, image_dict) + if not cached: + result.paths = None + + floored = galaxy_name_image_dict_via_result_from(result=result) + unfloored = galaxy_name_image_dict_via_result_from(result=result, minimum_percent=0.0) + floored_again = galaxy_name_image_dict_via_result_from(result=result) + + for name in raw: + floor = 0.01 * raw[name].max() + assert floored[name].array == pytest.approx(np.maximum(raw[name], floor), 1.0e-8) + assert unfloored[name].array == pytest.approx(np.clip(raw[name], 0.0, None), 1.0e-8) + assert floored_again[name].array == pytest.approx(floored[name].array, 1.0e-8) + # The result's own arrays are not floored in place. + assert np.asarray(image_dict[name].array) == pytest.approx(raw[name], 1.0e-8) + + +def test__soft_snr_maps_from(): + image_dict = _snr_test_image_dict() + + soft = ag.soft_snr_maps_from(image_dict) + + for name, image in image_dict.items(): + expected = aa.image_mesh.soft_snr_map_from(np.asarray(image.array)) + assert soft[name].array == pytest.approx(expected, 1.0e-10) + assert (soft[name].mask == image.mask).all() + + source_only = ag.soft_snr_maps_from(image_dict, galaxy_names=["source"]) + + assert source_only["('galaxies', 'lens')"] is image_dict["('galaxies', 'lens')"] + assert source_only["('galaxies', 'source')"].array == pytest.approx( + soft["('galaxies', 'source')"].array, 1.0e-10 + ) + + # Sky below S/N 2 sits on the floor; the bright peak saturates rather than dominating. + values = soft["('galaxies', 'source')"].array + assert values.min() == pytest.approx(0.01 * values.max(), 1.0e-10) + assert values.max() == pytest.approx((248.0 / 251.0) ** 2, 1.0e-10) + + +def test__galaxy_snr_maps_from__is_unfloored(tmp_path): + image_dict = _snr_test_image_dict() + raw = {name: np.asarray(image.array).copy() for name, image in image_dict.items()} + + snr_maps = ag.galaxy_snr_maps_from(result=_StubCacheResult(tmp_path, image_dict)) + + for name in raw: + assert snr_maps[name].array == pytest.approx(np.clip(raw[name], 0.0, None), 1.0e-8) + + +def test__galaxy_name_key_from(): + from autogalaxy.analysis.adapt_images.adapt_images import galaxy_name_key_from + + keys = ["('galaxies', 'lens')", "('galaxies', 'source')", "('extra_galaxies', 'source')"] + + assert galaxy_name_key_from("('galaxies', 'lens')", keys) == "('galaxies', 'lens')" + assert galaxy_name_key_from("lens", keys) == "('galaxies', 'lens')" + assert galaxy_name_key_from("galaxies.source", keys) == "('galaxies', 'source')" + + with pytest.raises(KeyError, match="more than one galaxy"): + galaxy_name_key_from("source", keys) + with pytest.raises(KeyError, match="No galaxy"): + galaxy_name_key_from("subhalo", keys) + + +def test__updated_via_instance_from__short_keys_and_unknown_keys(): + galaxies = af.ModelInstance() + galaxies.lens = ag.Galaxy(redshift=0.5) + galaxies.source = ag.Galaxy(redshift=1.0) + instance = af.ModelInstance() + instance.galaxies = galaxies + + image = ag.Array2D.ones(shape_native=(3, 3), pixel_scales=1.0) + grid = ag.Grid2DIrregular(values=[(0.0, 0.0), (1.0, 1.0)]) + + adapt_images = ag.AdaptImages( + galaxy_name_image_dict={"source": 2.0 * image, "('galaxies', 'lens')": image, "subhalo": 3.0 * image}, + galaxy_name_image_plane_mesh_grid_dict={"galaxies.source": grid}, + ) + + updated = adapt_images.updated_via_instance_from(instance=instance) + + assert updated.galaxy_image_dict[galaxies.source] == pytest.approx(2.0 * np.ones(9)) + assert updated.galaxy_image_dict[galaxies.lens] == pytest.approx(np.ones(9)) + assert len(updated.galaxy_image_dict) == 2 + assert updated.galaxy_image_plane_mesh_grid_dict[galaxies.source] == pytest.approx(np.asarray(grid)) + assert "('galaxies', 'source')" in updated.galaxy_name_image_dict + + +class _StubFromResult(_StubCacheResult): + """A stub result that also has the mask `AdaptImages.from_result` draws mesh grids on.""" + + @property + def mask(self): + return next(iter(self._image_dict.values())).mask + + +def test__adapt_images_from_result(tmp_path): + mask = ag.Mask2D.circular(shape_native=(30, 30), pixel_scales=0.1, radius=1.2) + y, x = np.indices(mask.shape_native) + radius = np.sqrt(((14.5 - y) * 0.1) ** 2 + ((x - 14.5) * 0.1) ** 2) + source = 20.0 * np.exp(-0.5 * ((radius - 0.8) / 0.1) ** 2) - 0.5 + lens = 5.0 * np.exp(-0.5 * (radius / 0.2) ** 2) + image_dict = { + "('galaxies', 'lens')": ag.Array2D(values=lens[~np.asarray(mask)], mask=mask), + "('galaxies', 'source')": ag.Array2D(values=source[~np.asarray(mask)], mask=mask), + } + raw_source = np.asarray(image_dict["('galaxies', 'source')"].array).copy() + + image_mesh = ag.image_mesh.HilbertSNR(pixels=40, edge_pixels=10) + + adapt_images = ag.AdaptImages.from_result( + result=_StubFromResult(tmp_path, image_dict), image_mesh={"source": image_mesh} + ) + + unfloored = ag.Array2D(values=np.clip(raw_source, 0.0, None), mask=mask) + expected_grid = image_mesh.image_plane_mesh_grid_from(mask=mask, adapt_data=unfloored) + + grid = adapt_images.galaxy_name_image_plane_mesh_grid_dict["('galaxies', 'source')"] + assert np.asarray(grid).shape == (50, 2) + assert np.asarray(grid) == pytest.approx(np.asarray(expected_grid), 1.0e-12) + + assert adapt_images.galaxy_name_image_dict["('galaxies', 'source')"].array == pytest.approx( + aa.image_mesh.soft_snr_map_from(np.clip(raw_source, 0.0, None)), 1.0e-12 + ) + assert set(adapt_images.galaxy_name_image_dict) == set(image_dict)